@onekeyfe/onekey-polkadot-provider 1.1.28 → 1.1.30

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.
@@ -1,8 +1,9 @@
1
1
  import type { IInpageProviderConfig } from '@onekeyfe/cross-inpage-provider-core';
2
2
  import { ProviderPolkadotBase } from './ProviderPolkadotBase';
3
3
  import type { IJsonRpcRequest } from '@onekeyfe/cross-inpage-provider-types';
4
- import { Unsubcall, InjectedAccount } from '@polkadot/extension-inject/types';
5
- import { SignerPayloadJSON, SignerPayloadRaw, SignerResult } from './types';
4
+ import type { JsonRpcResponse } from '@polkadot/rpc-provider/types';
5
+ import { Unsubcall, InjectedAccount, ProviderList, ProviderMeta } from '@polkadot/extension-inject/types';
6
+ import { RequestRpcSend, RequestRpcSubscribe, RequestRpcUnsubscribe, SignerPayloadJSON, SignerPayloadRaw, SignerResult } from './types';
6
7
  declare const PROVIDER_EVENTS: {
7
8
  readonly connect: "connect";
8
9
  readonly disconnect: "disconnect";
@@ -21,6 +22,12 @@ export declare type PolkadotRequest = {
21
22
  'web3AccountsSubscribe': (cb: (accounts: InjectedAccount[]) => any) => Promise<Unsubcall>;
22
23
  'web3SignPayload': (payload: SignerPayloadJSON) => Promise<SignerResult>;
23
24
  'web3SignRaw': (payload: SignerPayloadRaw) => Promise<SignerResult>;
25
+ 'web3RpcSubscribe': (payload: RequestRpcSubscribe, cb: (cb: JsonRpcResponse<unknown>) => void) => Promise<string | number>;
26
+ 'web3RpcUnSubscribe': () => Promise<boolean>;
27
+ 'web3RpcSubscribeConnected': (cb: (connected: boolean) => void) => boolean;
28
+ 'web3RpcSend': (payload: RequestRpcSend) => Promise<JsonRpcResponse<unknown>>;
29
+ 'web3RpcListProviders': () => Promise<ProviderList>;
30
+ 'web3RpcStartProvider': (payload: string) => Promise<ProviderMeta>;
24
31
  };
25
32
  export declare type PROVIDER_EVENTS_STRINGS = keyof typeof PROVIDER_EVENTS;
26
33
  export interface IProviderPolkadot {
@@ -30,6 +37,12 @@ export interface IProviderPolkadot {
30
37
  web3AccountsSubscribe: (cb: (accounts: InjectedAccount[]) => any) => Unsubcall;
31
38
  web3SignPayload: (payload: SignerPayloadJSON) => Promise<SignerResult>;
32
39
  web3SignRaw: (payload: SignerPayloadRaw) => Promise<SignerResult>;
40
+ web3RpcSubscribe: (payload: RequestRpcSubscribe, cb: (accounts: JsonRpcResponse<unknown>) => void) => Promise<string | number>;
41
+ web3RpcUnSubscribe: (payload: RequestRpcUnsubscribe) => Promise<boolean>;
42
+ web3RpcSubscribeConnected: (cb: (connected: boolean) => void) => boolean;
43
+ web3RpcSend: (payload: RequestRpcSend) => Promise<JsonRpcResponse<unknown>>;
44
+ web3RpcListProviders: () => Promise<ProviderList>;
45
+ web3RpcStartProvider: (payload: string) => Promise<ProviderMeta>;
33
46
  }
34
47
  export declare type OneKeyPolkadotProviderProps = IInpageProviderConfig & {
35
48
  timeout?: number;
@@ -48,11 +61,22 @@ declare class ProviderPolkadot extends ProviderPolkadotBase implements IProvider
48
61
  isConnected(): boolean;
49
62
  on<E extends keyof CosmosProviderEventsMap>(event: E, listener: CosmosProviderEventsMap[E]): this;
50
63
  emit<E extends keyof CosmosProviderEventsMap>(event: E, ...args: Parameters<CosmosProviderEventsMap[E]>): boolean;
64
+ private createMessage;
65
+ private _postMessage;
66
+ postRequest(payload: any): void;
67
+ postResponse(payload: any): void;
68
+ postError(payload: string): void;
51
69
  web3Enable(dappName: string): Promise<boolean>;
52
70
  web3Accounts(anyType?: boolean): Promise<InjectedAccount[]>;
53
71
  web3AccountsSubscribe(cb: (accounts: InjectedAccount[]) => any): Unsubcall;
54
72
  web3SignPayload(payload: SignerPayloadJSON): Promise<SignerResult>;
55
73
  web3SignRaw(payload: SignerPayloadRaw): Promise<SignerResult>;
74
+ web3RpcSubscribe(payload: RequestRpcSubscribe, cb: (accounts: JsonRpcResponse<unknown>) => void): Promise<string | number>;
75
+ web3RpcUnSubscribe(): Promise<boolean>;
76
+ web3RpcSubscribeConnected(cb: (connected: boolean) => void): boolean;
77
+ web3RpcSend(payload: RequestRpcSend): Promise<JsonRpcResponse<unknown>>;
78
+ web3RpcListProviders(): Promise<ProviderList>;
79
+ web3RpcStartProvider(payload: string): Promise<ProviderMeta>;
56
80
  }
57
- declare const registerPolkadot: (provider: ProviderPolkadot) => void;
81
+ declare const registerPolkadot: (provider: ProviderPolkadot, name?: string, version?: string) => void;
58
82
  export { ProviderPolkadot, registerPolkadot };
@@ -1,6 +1,16 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
1
10
  import { getOrCreateExtInjectedJsBridge } from '@onekeyfe/extension-bridge-injected';
2
11
  import { ProviderPolkadotBase } from './ProviderPolkadotBase';
3
12
  import { injectExtension } from '@polkadot/extension-inject';
13
+ import OneKeyInjected from './inject/Injected';
4
14
  const PROVIDER_EVENTS = {
5
15
  'connect': 'connect',
6
16
  'disconnect': 'disconnect',
@@ -78,6 +88,33 @@ class ProviderPolkadot extends ProviderPolkadotBase {
78
88
  emit(event, ...args) {
79
89
  return super.emit(event, ...args);
80
90
  }
91
+ createMessage(payload) {
92
+ return Object.assign({ id: 2, origin: 'OneKey Polkadot Provider' }, payload);
93
+ }
94
+ _postMessage(payload) {
95
+ try {
96
+ const message = this.createMessage(payload);
97
+ window.postMessage(message);
98
+ }
99
+ catch (error) {
100
+ // ignore
101
+ }
102
+ }
103
+ postRequest(payload) {
104
+ this._postMessage({
105
+ request: payload,
106
+ });
107
+ }
108
+ postResponse(payload) {
109
+ this._postMessage({
110
+ response: payload,
111
+ });
112
+ }
113
+ postError(payload) {
114
+ this._postMessage({
115
+ error: payload,
116
+ });
117
+ }
81
118
  web3Enable(dappName) {
82
119
  return this._callBridge({
83
120
  method: 'web3Enable',
@@ -97,48 +134,92 @@ class ProviderPolkadot extends ProviderPolkadotBase {
97
134
  };
98
135
  }
99
136
  web3SignPayload(payload) {
137
+ return __awaiter(this, void 0, void 0, function* () {
138
+ try {
139
+ this.postRequest(payload);
140
+ const result = yield this._callBridge({
141
+ method: 'web3SignPayload',
142
+ params: payload,
143
+ });
144
+ this.postResponse({
145
+ id: 1,
146
+ origin: 'OneKey Polkadot Provider',
147
+ signature: result.signature,
148
+ });
149
+ return result;
150
+ }
151
+ catch (error) {
152
+ this.postError('Cancelled');
153
+ return Promise.reject('Cancelled');
154
+ }
155
+ });
156
+ }
157
+ web3SignRaw(payload) {
158
+ return __awaiter(this, void 0, void 0, function* () {
159
+ try {
160
+ this.postRequest(payload);
161
+ const result = yield this._callBridge({
162
+ method: 'web3SignRaw',
163
+ params: payload,
164
+ });
165
+ this.postResponse({
166
+ id: 1,
167
+ origin: 'OneKey Polkadot Provider',
168
+ signature: result.signature,
169
+ });
170
+ return result;
171
+ }
172
+ catch (error) {
173
+ this.postError('Cancelled');
174
+ return Promise.reject('Cancelled');
175
+ }
176
+ });
177
+ }
178
+ web3RpcSubscribe(payload, cb) {
100
179
  return this._callBridge({
101
- method: 'web3SignPayload',
180
+ method: 'web3RpcSubscribe',
102
181
  params: payload,
103
182
  });
104
183
  }
105
- web3SignRaw(payload) {
184
+ web3RpcUnSubscribe() {
185
+ super.removeAllListeners();
106
186
  return this._callBridge({
107
- method: 'web3SignRaw',
187
+ method: 'web3RpcUnSubscribe',
188
+ params: undefined,
189
+ });
190
+ }
191
+ web3RpcSubscribeConnected(cb) {
192
+ cb(this.isConnected());
193
+ super.on(PROVIDER_EVENTS.connect, cb);
194
+ super.on(PROVIDER_EVENTS.disconnect, cb);
195
+ return true;
196
+ }
197
+ web3RpcSend(payload) {
198
+ return this._callBridge({
199
+ method: 'web3RpcSend',
200
+ params: payload,
201
+ });
202
+ }
203
+ web3RpcListProviders() {
204
+ return this._callBridge({
205
+ method: 'web3RpcListProviders',
206
+ params: undefined,
207
+ });
208
+ }
209
+ web3RpcStartProvider(payload) {
210
+ return this._callBridge({
211
+ method: 'web3RpcStartProvider',
108
212
  params: payload,
109
213
  });
110
214
  }
111
215
  }
112
- const registerPolkadot = (provider) => {
216
+ const registerPolkadot = (provider, name = 'OneKey', version = '1.0.0') => {
113
217
  try {
114
- const enableFn = (originName) => {
115
- return provider.web3Enable(originName).then((res) => {
116
- if (!res) {
117
- throw new Error('not support');
118
- }
119
- return {
120
- accounts: {
121
- get: (anyType) => {
122
- return provider.web3Accounts(anyType);
123
- },
124
- subscribe: (cb) => {
125
- return provider.web3AccountsSubscribe(cb);
126
- },
127
- },
128
- metadata: undefined,
129
- provider: undefined,
130
- signer: {
131
- signPayload: (message) => {
132
- return provider.web3SignPayload(message);
133
- },
134
- signRaw: (message) => {
135
- return provider.web3SignRaw(message);
136
- },
137
- },
138
- };
139
- });
140
- };
141
- injectExtension(enableFn, { name: 'OneKey', version: '1.0.0' });
218
+ const enableFn = (originName) => __awaiter(void 0, void 0, void 0, function* () {
219
+ yield provider.web3Enable(originName);
220
+ return new OneKeyInjected(provider);
221
+ });
222
+ injectExtension(enableFn, { name: name !== null && name !== void 0 ? name : 'OneKey', version: version !== null && version !== void 0 ? version : '1.0.0' });
142
223
  }
143
224
  catch (error) {
144
225
  console.error(error);
@@ -1,9 +1,22 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
2
14
  Object.defineProperty(exports, "__esModule", { value: true });
3
15
  exports.registerPolkadot = exports.ProviderPolkadot = void 0;
4
16
  const extension_bridge_injected_1 = require("@onekeyfe/extension-bridge-injected");
5
17
  const ProviderPolkadotBase_1 = require("./ProviderPolkadotBase");
6
18
  const extension_inject_1 = require("@polkadot/extension-inject");
19
+ const Injected_1 = __importDefault(require("./inject/Injected"));
7
20
  const PROVIDER_EVENTS = {
8
21
  'connect': 'connect',
9
22
  'disconnect': 'disconnect',
@@ -81,6 +94,33 @@ class ProviderPolkadot extends ProviderPolkadotBase_1.ProviderPolkadotBase {
81
94
  emit(event, ...args) {
82
95
  return super.emit(event, ...args);
83
96
  }
97
+ createMessage(payload) {
98
+ return Object.assign({ id: 2, origin: 'OneKey Polkadot Provider' }, payload);
99
+ }
100
+ _postMessage(payload) {
101
+ try {
102
+ const message = this.createMessage(payload);
103
+ window.postMessage(message);
104
+ }
105
+ catch (error) {
106
+ // ignore
107
+ }
108
+ }
109
+ postRequest(payload) {
110
+ this._postMessage({
111
+ request: payload,
112
+ });
113
+ }
114
+ postResponse(payload) {
115
+ this._postMessage({
116
+ response: payload,
117
+ });
118
+ }
119
+ postError(payload) {
120
+ this._postMessage({
121
+ error: payload,
122
+ });
123
+ }
84
124
  web3Enable(dappName) {
85
125
  return this._callBridge({
86
126
  method: 'web3Enable',
@@ -100,49 +140,93 @@ class ProviderPolkadot extends ProviderPolkadotBase_1.ProviderPolkadotBase {
100
140
  };
101
141
  }
102
142
  web3SignPayload(payload) {
143
+ return __awaiter(this, void 0, void 0, function* () {
144
+ try {
145
+ this.postRequest(payload);
146
+ const result = yield this._callBridge({
147
+ method: 'web3SignPayload',
148
+ params: payload,
149
+ });
150
+ this.postResponse({
151
+ id: 1,
152
+ origin: 'OneKey Polkadot Provider',
153
+ signature: result.signature,
154
+ });
155
+ return result;
156
+ }
157
+ catch (error) {
158
+ this.postError('Cancelled');
159
+ return Promise.reject('Cancelled');
160
+ }
161
+ });
162
+ }
163
+ web3SignRaw(payload) {
164
+ return __awaiter(this, void 0, void 0, function* () {
165
+ try {
166
+ this.postRequest(payload);
167
+ const result = yield this._callBridge({
168
+ method: 'web3SignRaw',
169
+ params: payload,
170
+ });
171
+ this.postResponse({
172
+ id: 1,
173
+ origin: 'OneKey Polkadot Provider',
174
+ signature: result.signature,
175
+ });
176
+ return result;
177
+ }
178
+ catch (error) {
179
+ this.postError('Cancelled');
180
+ return Promise.reject('Cancelled');
181
+ }
182
+ });
183
+ }
184
+ web3RpcSubscribe(payload, cb) {
103
185
  return this._callBridge({
104
- method: 'web3SignPayload',
186
+ method: 'web3RpcSubscribe',
105
187
  params: payload,
106
188
  });
107
189
  }
108
- web3SignRaw(payload) {
190
+ web3RpcUnSubscribe() {
191
+ super.removeAllListeners();
192
+ return this._callBridge({
193
+ method: 'web3RpcUnSubscribe',
194
+ params: undefined,
195
+ });
196
+ }
197
+ web3RpcSubscribeConnected(cb) {
198
+ cb(this.isConnected());
199
+ super.on(PROVIDER_EVENTS.connect, cb);
200
+ super.on(PROVIDER_EVENTS.disconnect, cb);
201
+ return true;
202
+ }
203
+ web3RpcSend(payload) {
204
+ return this._callBridge({
205
+ method: 'web3RpcSend',
206
+ params: payload,
207
+ });
208
+ }
209
+ web3RpcListProviders() {
109
210
  return this._callBridge({
110
- method: 'web3SignRaw',
211
+ method: 'web3RpcListProviders',
212
+ params: undefined,
213
+ });
214
+ }
215
+ web3RpcStartProvider(payload) {
216
+ return this._callBridge({
217
+ method: 'web3RpcStartProvider',
111
218
  params: payload,
112
219
  });
113
220
  }
114
221
  }
115
222
  exports.ProviderPolkadot = ProviderPolkadot;
116
- const registerPolkadot = (provider) => {
223
+ const registerPolkadot = (provider, name = 'OneKey', version = '1.0.0') => {
117
224
  try {
118
- const enableFn = (originName) => {
119
- return provider.web3Enable(originName).then((res) => {
120
- if (!res) {
121
- throw new Error('not support');
122
- }
123
- return {
124
- accounts: {
125
- get: (anyType) => {
126
- return provider.web3Accounts(anyType);
127
- },
128
- subscribe: (cb) => {
129
- return provider.web3AccountsSubscribe(cb);
130
- },
131
- },
132
- metadata: undefined,
133
- provider: undefined,
134
- signer: {
135
- signPayload: (message) => {
136
- return provider.web3SignPayload(message);
137
- },
138
- signRaw: (message) => {
139
- return provider.web3SignRaw(message);
140
- },
141
- },
142
- };
143
- });
144
- };
145
- (0, extension_inject_1.injectExtension)(enableFn, { name: 'OneKey', version: '1.0.0' });
225
+ const enableFn = (originName) => __awaiter(void 0, void 0, void 0, function* () {
226
+ yield provider.web3Enable(originName);
227
+ return new Injected_1.default(provider);
228
+ });
229
+ (0, extension_inject_1.injectExtension)(enableFn, { name: name !== null && name !== void 0 ? name : 'OneKey', version: version !== null && version !== void 0 ? version : '1.0.0' });
146
230
  }
147
231
  catch (error) {
148
232
  console.error(error);
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class default_1 {
4
+ constructor(provider) {
5
+ this.provider = provider;
6
+ }
7
+ get(anyType) {
8
+ return this.provider.web3Accounts(anyType);
9
+ }
10
+ subscribe(cb) {
11
+ return this.provider.web3AccountsSubscribe(cb);
12
+ }
13
+ }
14
+ exports.default = default_1;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const Signer_1 = __importDefault(require("./Signer"));
7
+ const Accounts_1 = __importDefault(require("./Accounts"));
8
+ class default_1 {
9
+ constructor(provider) {
10
+ this.accounts = new Accounts_1.default(provider);
11
+ this.metadata = undefined;
12
+ this.provider = undefined;
13
+ this.signer = new Signer_1.default(provider);
14
+ }
15
+ }
16
+ exports.default = default_1;
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const eventemitter3_1 = require("eventemitter3");
13
+ function isUndefined(value) {
14
+ return value === undefined;
15
+ }
16
+ class MessageProvider {
17
+ constructor(provider) {
18
+ this.provider = provider;
19
+ // Whether or not the actual extension background provider is connected
20
+ this._isConnected = false;
21
+ // Subscription IDs are (historically) not guaranteed to be globally unique;
22
+ // only unique for a given subscription method; which is why we identify
23
+ // the subscriptions based on subscription id + type
24
+ this._subscriptions = {};
25
+ this._eventemitter = new eventemitter3_1.EventEmitter();
26
+ }
27
+ get isClonable() {
28
+ return true;
29
+ }
30
+ clone() {
31
+ return new MessageProvider(this.provider);
32
+ }
33
+ // eslint-disable-next-line @typescript-eslint/require-await
34
+ connect() {
35
+ return __awaiter(this, void 0, void 0, function* () {
36
+ // FIXME This should see if the extension's state's provider can disconnect
37
+ console.error('PostMessageProvider.disconnect() is not implemented.');
38
+ });
39
+ }
40
+ // eslint-disable-next-line @typescript-eslint/require-await
41
+ disconnect() {
42
+ return __awaiter(this, void 0, void 0, function* () {
43
+ // FIXME This should see if the extension's state's provider can disconnect
44
+ console.error('PostMessageProvider.disconnect() is not implemented.');
45
+ });
46
+ }
47
+ get hasSubscriptions() {
48
+ // FIXME This should see if the extension's state's provider has subscriptions
49
+ return true;
50
+ }
51
+ /**
52
+ * @summary Whether the node is connected or not.
53
+ * @return {boolean} true if connected
54
+ */
55
+ get isConnected() {
56
+ return this._isConnected;
57
+ }
58
+ listProviders() {
59
+ return this.provider.web3RpcListProviders();
60
+ }
61
+ /**
62
+ * @summary Listens on events after having subscribed using the [[subscribe]] function.
63
+ * @param {ProviderInterfaceEmitted} type Event
64
+ * @param {ProviderInterfaceEmitCb} sub Callback
65
+ * @return unsubscribe function
66
+ */
67
+ on(type, sub) {
68
+ this._eventemitter.on(type, sub);
69
+ return () => {
70
+ this._eventemitter.removeListener(type, sub);
71
+ };
72
+ }
73
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
74
+ send(method, params, _, subscription) {
75
+ return __awaiter(this, void 0, void 0, function* () {
76
+ if (subscription) {
77
+ const { callback, type } = subscription;
78
+ const id = yield this.provider.web3RpcSubscribe({ method, params, type }, (res) => {
79
+ subscription.callback(null, res);
80
+ });
81
+ // const id = await sendRequest('pub(rpc.subscribe)', { method, params, type }, (res): void => {
82
+ // subscription.callback(null, res);
83
+ // });
84
+ this._subscriptions[`${type}::${id}`] = callback;
85
+ return id;
86
+ }
87
+ return this.provider.web3RpcSend({ method, params });
88
+ });
89
+ }
90
+ /**
91
+ * @summary Spawn a provider on the extension background.
92
+ */
93
+ startProvider(key) {
94
+ return __awaiter(this, void 0, void 0, function* () {
95
+ // Disconnect from the previous provider
96
+ this._isConnected = false;
97
+ this._eventemitter.emit('disconnected');
98
+ // const meta = await sendRequest('pub(rpc.startProvider)', key);
99
+ const meta = yield this.provider.web3RpcStartProvider(key);
100
+ this.provider.web3RpcSubscribeConnected((connected) => {
101
+ this._isConnected = connected;
102
+ if (connected) {
103
+ this._eventemitter.emit('connected');
104
+ }
105
+ else {
106
+ this._eventemitter.emit('disconnected');
107
+ }
108
+ return true;
109
+ });
110
+ return meta;
111
+ });
112
+ }
113
+ subscribe(type, method, params, callback) {
114
+ return this.send(method, params, false, { callback, type });
115
+ }
116
+ /**
117
+ * @summary Allows unsubscribing to subscriptions made with [[subscribe]].
118
+ */
119
+ unsubscribe(type, method, id) {
120
+ return __awaiter(this, void 0, void 0, function* () {
121
+ const subscription = `${type}::${id}`;
122
+ // FIXME This now could happen with re-subscriptions. The issue is that with a re-sub
123
+ // the assigned id now does not match what the API user originally received. It has
124
+ // a slight complication in solving - since we cannot rely on the send id, but rather
125
+ // need to find the actual subscription id to map it
126
+ if (isUndefined(this._subscriptions[subscription])) {
127
+ console.debug(`Unable to find active subscription=${subscription}`);
128
+ return false;
129
+ }
130
+ delete this._subscriptions[subscription];
131
+ yield this.provider.web3RpcUnSubscribe();
132
+ return this.send(method, [id]);
133
+ });
134
+ }
135
+ }
136
+ exports.default = MessageProvider;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ class Signer {
13
+ constructor(provider) {
14
+ this.provider = provider;
15
+ }
16
+ signPayload(payload) {
17
+ return __awaiter(this, void 0, void 0, function* () {
18
+ return this.provider.web3SignPayload(payload);
19
+ });
20
+ }
21
+ signRaw(payload) {
22
+ return __awaiter(this, void 0, void 0, function* () {
23
+ return this.provider.web3SignRaw(payload);
24
+ });
25
+ }
26
+ }
27
+ exports.default = Signer;
@@ -0,0 +1,9 @@
1
+ import { Unsubcall, InjectedAccount } from '@polkadot/extension-inject/types';
2
+ import type { InjectedAccounts } from '@polkadot/extension-inject/types';
3
+ import { ProviderPolkadot } from '../OnekeyPolkadotProvider';
4
+ export default class implements InjectedAccounts {
5
+ private provider;
6
+ constructor(provider: ProviderPolkadot);
7
+ get(anyType?: boolean): Promise<InjectedAccount[]>;
8
+ subscribe(cb: (accounts: InjectedAccount[]) => unknown): Unsubcall;
9
+ }
@@ -0,0 +1,11 @@
1
+ export default class {
2
+ constructor(provider) {
3
+ this.provider = provider;
4
+ }
5
+ get(anyType) {
6
+ return this.provider.web3Accounts(anyType);
7
+ }
8
+ subscribe(cb) {
9
+ return this.provider.web3AccountsSubscribe(cb);
10
+ }
11
+ }
@@ -0,0 +1,11 @@
1
+ import { ProviderPolkadot } from '../OnekeyPolkadotProvider';
2
+ import Signer from './Signer';
3
+ import type { Injected, InjectedMetadata, InjectedProvider } from '@polkadot/extension-inject/types';
4
+ import Accounts from './Accounts';
5
+ export default class implements Injected {
6
+ readonly accounts: Accounts;
7
+ readonly metadata: InjectedMetadata | undefined;
8
+ readonly provider: InjectedProvider | undefined;
9
+ readonly signer: Signer;
10
+ constructor(provider: ProviderPolkadot);
11
+ }
@@ -0,0 +1,10 @@
1
+ import Signer from './Signer';
2
+ import Accounts from './Accounts';
3
+ export default class {
4
+ constructor(provider) {
5
+ this.accounts = new Accounts(provider);
6
+ this.metadata = undefined;
7
+ this.provider = undefined;
8
+ this.signer = new Signer(provider);
9
+ }
10
+ }
@@ -0,0 +1,46 @@
1
+ import type { InjectedProvider, ProviderList, ProviderMeta } from '@polkadot/extension-inject/types';
2
+ import type { ProviderInterfaceEmitCb, ProviderInterfaceEmitted } from '@polkadot/rpc-provider/types';
3
+ import { EventEmitter } from 'eventemitter3';
4
+ import { ProviderPolkadot } from '../OnekeyPolkadotProvider';
5
+ declare type CallbackHandler = (error?: null | Error, value?: unknown) => void;
6
+ declare type AnyFunction = (...args: any[]) => any;
7
+ interface SubscriptionHandler {
8
+ callback: CallbackHandler;
9
+ type: string;
10
+ }
11
+ export default class MessageProvider implements InjectedProvider {
12
+ private provider;
13
+ readonly _eventemitter: EventEmitter;
14
+ _isConnected: boolean;
15
+ readonly _subscriptions: Record<string, AnyFunction>;
16
+ constructor(provider: ProviderPolkadot);
17
+ get isClonable(): boolean;
18
+ clone(): MessageProvider;
19
+ connect(): Promise<void>;
20
+ disconnect(): Promise<void>;
21
+ get hasSubscriptions(): boolean;
22
+ /**
23
+ * @summary Whether the node is connected or not.
24
+ * @return {boolean} true if connected
25
+ */
26
+ get isConnected(): boolean;
27
+ listProviders(): Promise<ProviderList>;
28
+ /**
29
+ * @summary Listens on events after having subscribed using the [[subscribe]] function.
30
+ * @param {ProviderInterfaceEmitted} type Event
31
+ * @param {ProviderInterfaceEmitCb} sub Callback
32
+ * @return unsubscribe function
33
+ */
34
+ on(type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): () => void;
35
+ send(method: string, params: unknown[], _?: boolean, subscription?: SubscriptionHandler): Promise<any>;
36
+ /**
37
+ * @summary Spawn a provider on the extension background.
38
+ */
39
+ startProvider(key: string): Promise<ProviderMeta>;
40
+ subscribe(type: string, method: string, params: unknown[], callback: AnyFunction): Promise<number>;
41
+ /**
42
+ * @summary Allows unsubscribing to subscriptions made with [[subscribe]].
43
+ */
44
+ unsubscribe(type: string, method: string, id: number): Promise<boolean>;
45
+ }
46
+ export {};
@@ -0,0 +1,133 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { EventEmitter } from 'eventemitter3';
11
+ function isUndefined(value) {
12
+ return value === undefined;
13
+ }
14
+ export default class MessageProvider {
15
+ constructor(provider) {
16
+ this.provider = provider;
17
+ // Whether or not the actual extension background provider is connected
18
+ this._isConnected = false;
19
+ // Subscription IDs are (historically) not guaranteed to be globally unique;
20
+ // only unique for a given subscription method; which is why we identify
21
+ // the subscriptions based on subscription id + type
22
+ this._subscriptions = {};
23
+ this._eventemitter = new EventEmitter();
24
+ }
25
+ get isClonable() {
26
+ return true;
27
+ }
28
+ clone() {
29
+ return new MessageProvider(this.provider);
30
+ }
31
+ // eslint-disable-next-line @typescript-eslint/require-await
32
+ connect() {
33
+ return __awaiter(this, void 0, void 0, function* () {
34
+ // FIXME This should see if the extension's state's provider can disconnect
35
+ console.error('PostMessageProvider.disconnect() is not implemented.');
36
+ });
37
+ }
38
+ // eslint-disable-next-line @typescript-eslint/require-await
39
+ disconnect() {
40
+ return __awaiter(this, void 0, void 0, function* () {
41
+ // FIXME This should see if the extension's state's provider can disconnect
42
+ console.error('PostMessageProvider.disconnect() is not implemented.');
43
+ });
44
+ }
45
+ get hasSubscriptions() {
46
+ // FIXME This should see if the extension's state's provider has subscriptions
47
+ return true;
48
+ }
49
+ /**
50
+ * @summary Whether the node is connected or not.
51
+ * @return {boolean} true if connected
52
+ */
53
+ get isConnected() {
54
+ return this._isConnected;
55
+ }
56
+ listProviders() {
57
+ return this.provider.web3RpcListProviders();
58
+ }
59
+ /**
60
+ * @summary Listens on events after having subscribed using the [[subscribe]] function.
61
+ * @param {ProviderInterfaceEmitted} type Event
62
+ * @param {ProviderInterfaceEmitCb} sub Callback
63
+ * @return unsubscribe function
64
+ */
65
+ on(type, sub) {
66
+ this._eventemitter.on(type, sub);
67
+ return () => {
68
+ this._eventemitter.removeListener(type, sub);
69
+ };
70
+ }
71
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
72
+ send(method, params, _, subscription) {
73
+ return __awaiter(this, void 0, void 0, function* () {
74
+ if (subscription) {
75
+ const { callback, type } = subscription;
76
+ const id = yield this.provider.web3RpcSubscribe({ method, params, type }, (res) => {
77
+ subscription.callback(null, res);
78
+ });
79
+ // const id = await sendRequest('pub(rpc.subscribe)', { method, params, type }, (res): void => {
80
+ // subscription.callback(null, res);
81
+ // });
82
+ this._subscriptions[`${type}::${id}`] = callback;
83
+ return id;
84
+ }
85
+ return this.provider.web3RpcSend({ method, params });
86
+ });
87
+ }
88
+ /**
89
+ * @summary Spawn a provider on the extension background.
90
+ */
91
+ startProvider(key) {
92
+ return __awaiter(this, void 0, void 0, function* () {
93
+ // Disconnect from the previous provider
94
+ this._isConnected = false;
95
+ this._eventemitter.emit('disconnected');
96
+ // const meta = await sendRequest('pub(rpc.startProvider)', key);
97
+ const meta = yield this.provider.web3RpcStartProvider(key);
98
+ this.provider.web3RpcSubscribeConnected((connected) => {
99
+ this._isConnected = connected;
100
+ if (connected) {
101
+ this._eventemitter.emit('connected');
102
+ }
103
+ else {
104
+ this._eventemitter.emit('disconnected');
105
+ }
106
+ return true;
107
+ });
108
+ return meta;
109
+ });
110
+ }
111
+ subscribe(type, method, params, callback) {
112
+ return this.send(method, params, false, { callback, type });
113
+ }
114
+ /**
115
+ * @summary Allows unsubscribing to subscriptions made with [[subscribe]].
116
+ */
117
+ unsubscribe(type, method, id) {
118
+ return __awaiter(this, void 0, void 0, function* () {
119
+ const subscription = `${type}::${id}`;
120
+ // FIXME This now could happen with re-subscriptions. The issue is that with a re-sub
121
+ // the assigned id now does not match what the API user originally received. It has
122
+ // a slight complication in solving - since we cannot rely on the send id, but rather
123
+ // need to find the actual subscription id to map it
124
+ if (isUndefined(this._subscriptions[subscription])) {
125
+ console.debug(`Unable to find active subscription=${subscription}`);
126
+ return false;
127
+ }
128
+ delete this._subscriptions[subscription];
129
+ yield this.provider.web3RpcUnSubscribe();
130
+ return this.send(method, [id]);
131
+ });
132
+ }
133
+ }
@@ -0,0 +1,8 @@
1
+ import { ProviderPolkadot } from '../OnekeyPolkadotProvider';
2
+ import { SignerPayloadJSON, SignerPayloadRaw, SignerResult } from '../types';
3
+ export default class Signer {
4
+ private provider;
5
+ constructor(provider: ProviderPolkadot);
6
+ signPayload(payload: SignerPayloadJSON): Promise<SignerResult>;
7
+ signRaw(payload: SignerPayloadRaw): Promise<SignerResult>;
8
+ }
@@ -0,0 +1,24 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ export default class Signer {
11
+ constructor(provider) {
12
+ this.provider = provider;
13
+ }
14
+ signPayload(payload) {
15
+ return __awaiter(this, void 0, void 0, function* () {
16
+ return this.provider.web3SignPayload(payload);
17
+ });
18
+ }
19
+ signRaw(payload) {
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ return this.provider.web3SignRaw(payload);
22
+ });
23
+ }
24
+ }
package/dist/types.d.ts CHANGED
@@ -78,3 +78,15 @@ export interface SignerResult {
78
78
  */
79
79
  signature: `0x${string}`;
80
80
  }
81
+ export interface RequestRpcSend {
82
+ method: string;
83
+ params: unknown[];
84
+ }
85
+ export interface RequestRpcSubscribe extends RequestRpcSend {
86
+ type: string;
87
+ }
88
+ export interface RequestRpcUnsubscribe {
89
+ type: string;
90
+ method: string;
91
+ id: string;
92
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/onekey-polkadot-provider",
3
- "version": "1.1.28",
3
+ "version": "1.1.30",
4
4
  "keywords": [
5
5
  "cross-inpage-provider"
6
6
  ],
@@ -28,15 +28,15 @@
28
28
  "start": "tsc --watch"
29
29
  },
30
30
  "dependencies": {
31
- "@noble/hashes": "^1.1.4",
32
- "@onekeyfe/cross-inpage-provider-core": "1.1.28",
33
- "@onekeyfe/cross-inpage-provider-errors": "1.1.28",
34
- "@onekeyfe/cross-inpage-provider-types": "1.1.28",
35
- "@onekeyfe/extension-bridge-injected": "1.1.28",
36
- "@polkadot/extension-inject": "^0.46.2",
31
+ "@noble/hashes": "^1.3.0",
32
+ "@onekeyfe/cross-inpage-provider-core": "1.1.30",
33
+ "@onekeyfe/cross-inpage-provider-errors": "1.1.30",
34
+ "@onekeyfe/cross-inpage-provider-types": "1.1.30",
35
+ "@onekeyfe/extension-bridge-injected": "1.1.30",
36
+ "@polkadot/extension-inject": "^0.46.3",
37
37
  "eth-rpc-errors": "^4.0.3",
38
38
  "long": "^5.2.1",
39
39
  "mitt": "^3.0.0"
40
40
  },
41
- "gitHead": "5469ed1680c52acc985f6191bdbe2a102f848071"
41
+ "gitHead": "9efd9608ab6acf801f61145cc62c964941b2b340"
42
42
  }