@portal-hq/provider 0.2.7 → 0.2.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@portal-hq/provider",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "license": "MIT",
5
5
  "main": "lib/commonjs/index",
6
6
  "module": "lib/esm/index",
@@ -17,7 +17,7 @@
17
17
  "prepare:esm": "tsc --outDir lib/esm --module es2015 --target es2015"
18
18
  },
19
19
  "dependencies": {
20
- "@portal-hq/utils": "^0.2.7"
20
+ "@portal-hq/utils": "^0.2.9"
21
21
  },
22
22
  "devDependencies": {
23
23
  "typescript": "^4.8.4"
@@ -43,7 +43,7 @@ class Provider {
43
43
  public chainId: number
44
44
  public isMPC?: boolean
45
45
 
46
- private _address: string
46
+ private _address: string = ''
47
47
  private apiUrl: string
48
48
  private autoApprove?: boolean
49
49
  private events: Record<string, RegisteredEventHandler[]>
@@ -108,6 +108,7 @@ class Provider {
108
108
  } else {
109
109
  // If MPC is disabled, initialize an HttpSigner, talking to whatever httpHost was provided
110
110
  this.signer = new HttpSigner({
111
+ keychain: this.keychain,
111
112
  portal: this.portal,
112
113
  })
113
114
  }
@@ -387,14 +388,6 @@ class Provider {
387
388
  })
388
389
  }
389
390
 
390
- private async dispatchDisconnect(): Promise<void> {
391
- this.emit('disconnect', {
392
- error: new ProviderRpcError({
393
- code: RpcErrorCodes.Disconnected,
394
- }),
395
- })
396
- }
397
-
398
391
  /**
399
392
  * Determines the RPC URL to be used for the current chain
400
393
  *
@@ -1,9 +1,9 @@
1
- import { HttpRequest } from '@portal-hq/utils'
2
1
  import {
2
+ HttpRequest,
3
3
  type HttpRequestOptions,
4
4
  type HttpOptions,
5
5
  type HttpRequesterOptions,
6
- } from '@portal-hq/utils/types'
6
+ } from '@portal-hq/utils'
7
7
 
8
8
  class HttpRequester {
9
9
  private baseUrl: string
@@ -1,10 +1,8 @@
1
- import { type SigningRequestArguments, type SignResult } from '../../types'
1
+ import { SigningRequestArguments } from '@portal-hq/utils'
2
+ import { type SignResult } from '../../types'
2
3
 
3
4
  abstract class Signer {
4
- public async sign(
5
- message: SigningRequestArguments,
6
- provider?: any,
7
- ): Promise<SignResult> {
5
+ public async sign(_: SigningRequestArguments, __?: any): Promise<SignResult> {
8
6
  throw new Error(
9
7
  '[Portal] sign() method must be implemented in a child of BaseSigner',
10
8
  )
@@ -1,11 +1,10 @@
1
- import { Keychain } from '@portal-hq/keychain'
2
- import { MissingOptionError } from '@portal-hq/utils'
3
-
4
1
  import {
5
- type HttpSignerOptions,
6
- type SigningRequestArguments,
7
- type SignResult,
8
- } from '../../types'
2
+ KeychainAdapter,
3
+ MissingOptionError,
4
+ SigningRequestArguments,
5
+ } from '@portal-hq/utils'
6
+
7
+ import { type HttpSignerOptions, type SignResult } from '../../types'
9
8
 
10
9
  import Signer from './abstract'
11
10
  import { Provider } from '../index'
@@ -13,7 +12,7 @@ import HttpRequester from '../requesters/http'
13
12
 
14
13
  class HttpSigner implements Signer {
15
14
  private portal: HttpRequester
16
- private keychain: Keychain
15
+ private keychain: KeychainAdapter
17
16
 
18
17
  constructor(opts: HttpSignerOptions) {
19
18
  if (!opts.portal) {
@@ -23,7 +22,7 @@ class HttpSigner implements Signer {
23
22
  })
24
23
  }
25
24
 
26
- this.keychain = new Keychain()
25
+ this.keychain = opts.keychain
27
26
  this.portal = opts.portal
28
27
  }
29
28
 
@@ -32,7 +31,6 @@ class HttpSigner implements Signer {
32
31
  provider: Provider,
33
32
  ): Promise<any> {
34
33
  const address = await this.keychain.getAddress()
35
- const arrayMethods = ['personal_sign']
36
34
  const { chainId, method, params } = message
37
35
 
38
36
  switch (method) {
@@ -1,5 +1,9 @@
1
1
  import { NativeModules } from 'react-native'
2
- import { KeychainAdapter, MpcSigningError } from '@portal-hq/utils'
2
+ import {
3
+ KeychainAdapter,
4
+ MpcSigningError,
5
+ type SigningRequestArguments,
6
+ } from '@portal-hq/utils'
3
7
 
4
8
  import { Provider } from '../index'
5
9
  import Signer from './abstract'
@@ -7,12 +11,11 @@ import Signer from './abstract'
7
11
  import {
8
12
  type MpcSignerOptions,
9
13
  type PortalMobileMpc,
10
- type SigningRequestArguments,
11
14
  type SigningResponse,
12
15
  } from '../../types'
13
16
 
14
17
  class MpcSigner implements Signer {
15
- public _address: string
18
+ public _address: string = ''
16
19
  private keychain: KeychainAdapter
17
20
  private mpc: PortalMobileMpc
18
21
  private mpcUrl: string
package/types.d.ts CHANGED
@@ -19,6 +19,7 @@ export interface HttpRequesterOptions {
19
19
  }
20
20
 
21
21
  export interface HttpSignerOptions extends SignerOptions {
22
+ keychain: KeychainAdapter
22
23
  portal: HttpRequester
23
24
  }
24
25
 
@@ -77,13 +78,6 @@ export interface SignResult {
77
78
 
78
79
  export interface SignerOptions {}
79
80
 
80
- export interface SigningRequestArguments {
81
- readonly chainId?: number
82
- readonly method: string
83
- readonly params?: unknown[] | SigningRequestParams
84
- readonly requestId?: string
85
- }
86
-
87
81
  export interface SigningRequestParams {
88
82
  gas?: string
89
83
  }
@@ -1,8 +0,0 @@
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
- exports.Provider = void 0;
7
- var providers_1 = require("./providers");
8
- Object.defineProperty(exports, "Provider", { enumerable: true, get: function () { return __importDefault(providers_1).default; } });
@@ -1,383 +0,0 @@
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 utils_1 = require("@portal-hq/utils");
13
- const requesters_1 = require("../requesters");
14
- const signers_1 = require("../signers");
15
- const passiveSignerMethods = [
16
- 'eth_accounts',
17
- 'eth_chainId',
18
- 'eth_requestAccounts',
19
- ];
20
- const signerMethods = [
21
- 'eth_accounts',
22
- 'eth_chainId',
23
- 'eth_requestAccounts',
24
- 'eth_sendTransaction',
25
- 'eth_sign',
26
- 'eth_signTransaction',
27
- 'eth_signTypedData',
28
- 'personal_sign',
29
- ];
30
- class Provider {
31
- constructor({
32
- // Required options
33
- apiKey, chainId, keychain,
34
- // Optional options
35
- apiUrl = 'api.portalhq.io', autoApprove = false, enableMpc = true, mpcUrl = 'mpc.portalhq.io', gatewayConfig = {}, }) {
36
- // Handle required fields
37
- if (!apiKey || apiKey.length === 0) {
38
- throw new utils_1.InvalidApiKeyError();
39
- }
40
- if (!chainId) {
41
- throw new utils_1.InvalidChainIdError();
42
- }
43
- if (!gatewayConfig) {
44
- throw new utils_1.InvalidGatewayConfigError();
45
- }
46
- // Handle the stuff we can auto-set
47
- this.apiKey = apiKey;
48
- this.apiUrl = apiUrl;
49
- this.autoApprove = autoApprove;
50
- this.chainId = chainId;
51
- this.events = {};
52
- this.isMPC = enableMpc;
53
- this.keychain = keychain;
54
- this.log = console;
55
- this.mpcUrl = mpcUrl;
56
- this.portal = new requesters_1.HttpRequester({
57
- baseUrl: this.apiUrl,
58
- });
59
- // Handle RPC Initialization
60
- this.gatewayConfig = gatewayConfig;
61
- this.rpc = new requesters_1.HttpRequester({
62
- baseUrl: this.getRpcUrl(),
63
- });
64
- if (this.isMPC) {
65
- // If MPC is enabled, initialize an MpcSigner
66
- this.signer = new signers_1.MpcSigner({
67
- mpcUrl: this.mpcUrl,
68
- keychain: this.keychain,
69
- });
70
- }
71
- else {
72
- // If MPC is disabled, initialize an HttpSigner, talking to whatever httpHost was provided
73
- this.signer = new signers_1.HttpSigner({
74
- portal: this.portal,
75
- });
76
- }
77
- this.dispatchConnect();
78
- }
79
- get address() {
80
- return this._address;
81
- }
82
- set address(value) {
83
- this._address = value;
84
- if (this.signer && this.isMPC) {
85
- ;
86
- this.signer._address = value;
87
- }
88
- }
89
- get rpcUrl() {
90
- return this.getRpcUrl();
91
- }
92
- /**
93
- * Invokes all registered event handlers with the data provided
94
- * - If any `once` handlers exist, they are removed after all handlers are invoked
95
- *
96
- * @param event The name of the event to be handled
97
- * @param data The data to be passed to registered event handlers
98
- * @returns BaseProvider
99
- */
100
- emit(event, data) {
101
- // Grab the registered event handlers if any are available
102
- const handlers = this.events[event] || [];
103
- // Execute every event handler
104
- for (const registeredEventHandler of handlers) {
105
- registeredEventHandler.handler(data);
106
- }
107
- // Remove any registered event handlers with the `once` flag
108
- this.events[event] = handlers.filter((handler) => !handler.once);
109
- return this;
110
- }
111
- /**
112
- * Registers an event handler for the provided event
113
- *
114
- * @param event The event name to add a handler to
115
- * @param callback The callback to be invoked when the event is emitted
116
- * @returns BaseProvider
117
- */
118
- on(event, callback) {
119
- // If no handlers are registered for this event, create an entry for the event
120
- if (!this.events[event]) {
121
- this.events[event] = [];
122
- }
123
- // Register event handler with the rudimentary event bus
124
- if (typeof callback !== 'undefined') {
125
- this.events[event].push({
126
- handler: callback,
127
- once: false,
128
- });
129
- }
130
- return this;
131
- }
132
- /**
133
- * Registers a single-execution event handler for the provided event
134
- *
135
- * @param event The event name to add a handler to
136
- * @param callback The callback to be invoked the next time the event is emitted
137
- * @returns BaseProvider
138
- */
139
- once(event, callback) {
140
- // If no handlers are registered for this event, create an entry for the event
141
- if (!this.events[event]) {
142
- this.events[event] = [];
143
- }
144
- // Register event handler with the rudimentary event bus
145
- if (typeof callback !== 'undefined') {
146
- this.events[event].push({
147
- handler: callback,
148
- once: true,
149
- });
150
- }
151
- return this;
152
- }
153
- removeEventListener(event, listenerToRemove) {
154
- if (!this.events[event]) {
155
- this.log.info(`[PortalProvider] Attempted to remove a listener from unregistered event '${event}'. Ignoring.`);
156
- return;
157
- }
158
- if (!listenerToRemove) {
159
- this.events[event] = [];
160
- }
161
- else {
162
- const filterEventHandlers = (registeredEventHandler) => {
163
- return registeredEventHandler.handler !== listenerToRemove;
164
- };
165
- this.events[event] = this.events[event].filter(filterEventHandlers);
166
- }
167
- }
168
- /**
169
- * Handles request routing in compliance with the EIP-1193 Ethereum Javascript Provider API
170
- * - See here for more info: https://eips.ethereum.org/EIPS/eip-1193
171
- *
172
- * @param args The arguments of the request being made
173
- * @returns Promise<any>
174
- */
175
- request({ method, params }) {
176
- return __awaiter(this, void 0, void 0, function* () {
177
- if (method === 'eth_chainId') {
178
- return this.chainId;
179
- }
180
- const isSignerMethod = signerMethods.includes(method);
181
- let result;
182
- if (!isSignerMethod && !method.startsWith('wallet_')) {
183
- // Send to Gateway for RPC calls
184
- const response = yield this.handleGatewayRequests({ method, params });
185
- this.emit('portal_signatureReceived', {
186
- method,
187
- params,
188
- signature: response,
189
- });
190
- if (response.error) {
191
- throw new utils_1.ProviderRpcError(response.error);
192
- }
193
- result = response.result;
194
- }
195
- else if (isSignerMethod) {
196
- // Handle signing
197
- const transactionHash = yield this.handleSigningRequests({
198
- method,
199
- params,
200
- });
201
- if (transactionHash) {
202
- console.log(`Received transaction hash: `, transactionHash);
203
- this.emit('portal_signatureReceived', {
204
- method,
205
- params,
206
- signature: transactionHash,
207
- });
208
- result = transactionHash;
209
- }
210
- }
211
- else {
212
- // Unsupported method
213
- throw new utils_1.ProviderRpcError({
214
- code: utils_1.RpcErrorCodes.UnsupportedMethod,
215
- data: {
216
- method,
217
- params,
218
- },
219
- });
220
- }
221
- return result;
222
- });
223
- }
224
- /**
225
- * Updates the chainId of this instance and builds a new RPC HttpRequester for
226
- * the gateway used for the new chain
227
- *
228
- * @param chainId A hex string of the chainId to use for this connection
229
- * @returns BaseProvider
230
- */
231
- updateChainId(chainId) {
232
- return __awaiter(this, void 0, void 0, function* () {
233
- this.chainId = Number(`${chainId}`);
234
- this.rpc = new requesters_1.HttpRequester({
235
- baseUrl: this.getRpcUrl(),
236
- });
237
- this.emit('chainChanged', { chainId });
238
- return this;
239
- });
240
- }
241
- /**
242
- * Kicks off the approval flow for a given request
243
- *
244
- * @param args The arguments of the request being made
245
- */
246
- getApproval({ method, params, }) {
247
- return __awaiter(this, void 0, void 0, function* () {
248
- // If autoApprove is enabled, just resolve to true
249
- if (this.autoApprove) {
250
- return true;
251
- }
252
- if (!this.events['portal_signingRequested']) {
253
- throw new Error(`[PortalProvider] Auto-approve is disabled. Cannot perform signing requests without an event handler for the 'portal_signingRequested' event.`);
254
- }
255
- return new Promise((resolve) => {
256
- // Remove already used listeners
257
- this.removeEventListener('portal_signingApproved');
258
- this.removeEventListener('portal_signingRejected');
259
- // If the signing has been approved, resolve to true
260
- this.once('portal_signingApproved', ({ method: approvedMethod, params: approvedParams }) => {
261
- console.log(`[PortalProvider] Signing Approved`, method, params);
262
- // Remove already used listeners
263
- this.removeEventListener('portal_signingApproved');
264
- this.removeEventListener('portal_signingRejected');
265
- // First verify that this is the same signing request
266
- if (method === approvedMethod &&
267
- JSON.stringify(params) === JSON.stringify(approvedParams)) {
268
- resolve(true);
269
- }
270
- });
271
- // If the signing request has been rejected, resolve to false
272
- this.once('portal_signingRejected', ({ method: rejectedMethod, params: rejectedParams }) => {
273
- console.log(`[PortalProvider] Signing Approved`, method, params);
274
- // Remove already used listeners
275
- this.removeEventListener('portal_signingApproved');
276
- this.removeEventListener('portal_signingRejected');
277
- // First verify that this is the same signing request
278
- if (method === rejectedMethod &&
279
- JSON.stringify(params) === JSON.stringify(rejectedParams)) {
280
- resolve(false);
281
- }
282
- });
283
- // Tell any listening clients that signing has been requested
284
- this.emit('portal_signingRequested', {
285
- method,
286
- params,
287
- });
288
- });
289
- });
290
- }
291
- dispatchConnect() {
292
- return __awaiter(this, void 0, void 0, function* () {
293
- console.log(`[PortalProvider] Connected on chainId: 0x${this.chainId.toString(16)}`);
294
- this.emit('connect', {
295
- chainId: `0x${this.chainId.toString(16)}`,
296
- });
297
- });
298
- }
299
- dispatchDisconnect() {
300
- return __awaiter(this, void 0, void 0, function* () {
301
- this.emit('disconnect', {
302
- error: new utils_1.ProviderRpcError({
303
- code: utils_1.RpcErrorCodes.Disconnected,
304
- }),
305
- });
306
- });
307
- }
308
- /**
309
- * Determines the RPC URL to be used for the current chain
310
- *
311
- * @returns string
312
- */
313
- getRpcUrl() {
314
- if (typeof this.gatewayConfig === 'string') {
315
- // If the gatewayConfig is just a static URL, return that
316
- return this.gatewayConfig;
317
- }
318
- else if (typeof this.gatewayConfig === 'object' &&
319
- !this.gatewayConfig.hasOwnProperty(this.chainId)) {
320
- // If there's no explicit mapping for the current chainId, error out
321
- throw new Error(`[PortalProvider] No RPC endpoint configured for chainId: ${this.chainId}`);
322
- }
323
- // Get the entry for the current chainId from the gatewayConfig
324
- const config = this.gatewayConfig[this.chainId];
325
- if (typeof config === 'string') {
326
- return config;
327
- }
328
- // If we got this far, there's no way to support the chain with the current config
329
- throw new Error(`[PortalProvider] Could not find a valid gatewayConfig entry for chainId: ${this.chainId}`);
330
- }
331
- /**
332
- * Sends the provided request payload along to the RPC HttpRequester
333
- *
334
- * @param args The arguments of the request being made
335
- * @returns Promise<any>
336
- */
337
- handleGatewayRequests({ method, params, }) {
338
- return __awaiter(this, void 0, void 0, function* () {
339
- // Pass request off to the gateway
340
- return yield this.rpc.post('', {
341
- body: {
342
- jsonrpc: '2.0',
343
- id: this.chainId,
344
- method,
345
- params,
346
- },
347
- });
348
- });
349
- }
350
- /**
351
- * Sends the provided request payload along to the Signer
352
- *
353
- * @param args The arguments of the request being made
354
- * @returns Promise<any>
355
- */
356
- handleSigningRequests({ method, params, }) {
357
- var _a;
358
- return __awaiter(this, void 0, void 0, function* () {
359
- const isApproved = passiveSignerMethods.includes(method)
360
- ? true
361
- : yield this.getApproval({ method, params });
362
- if (!isApproved) {
363
- this.log.info(`[PortalProvider] Request for signing method '${method}' could not be completed because it was not approved by the user.`);
364
- return;
365
- }
366
- switch (method) {
367
- case 'eth_chainId':
368
- return `0x${this.chainId.toString(16)}`;
369
- case 'eth_accounts':
370
- case 'eth_requestAccounts':
371
- case 'eth_sendTransaction':
372
- case 'eth_sign':
373
- case 'eth_signTransaction':
374
- case 'eth_signTypedData':
375
- case 'personal_sign':
376
- return yield ((_a = this.signer) === null || _a === void 0 ? void 0 : _a.sign({ chainId: this.chainId, method, params }, this));
377
- default:
378
- throw new Error('[PortalProvider] Method "' + method + '" not supported');
379
- }
380
- });
381
- }
382
- }
383
- exports.default = Provider;
@@ -1,52 +0,0 @@
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 utils_1 = require("@portal-hq/utils");
13
- class HttpRequester {
14
- constructor({ baseUrl }) {
15
- this.baseUrl = baseUrl.startsWith('https://')
16
- ? baseUrl
17
- : `https://${baseUrl}`;
18
- }
19
- get(path, options) {
20
- return __awaiter(this, void 0, void 0, function* () {
21
- const requestOptions = {
22
- method: 'GET',
23
- url: `${this.baseUrl}${path}`,
24
- };
25
- if (options && options.headers) {
26
- requestOptions.headers = this.buildHeaders(options.headers);
27
- }
28
- const request = new utils_1.HttpRequest(requestOptions);
29
- const response = (yield request.send());
30
- return response;
31
- });
32
- }
33
- post(path, options) {
34
- return __awaiter(this, void 0, void 0, function* () {
35
- const requestOptions = {
36
- method: 'POST',
37
- url: `${this.baseUrl}${path}`,
38
- };
39
- requestOptions.headers = this.buildHeaders(options && options.headers ? options.headers : {});
40
- if (options && options.body) {
41
- requestOptions.body = options.body;
42
- }
43
- const request = new utils_1.HttpRequest(requestOptions);
44
- const response = (yield request.send());
45
- return response;
46
- });
47
- }
48
- buildHeaders(headers) {
49
- return Object.assign({ 'Content-Type': 'application/json' }, headers);
50
- }
51
- }
52
- exports.default = HttpRequester;
@@ -1,8 +0,0 @@
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
- exports.HttpRequester = void 0;
7
- var http_1 = require("./http");
8
- Object.defineProperty(exports, "HttpRequester", { enumerable: true, get: function () { return __importDefault(http_1).default; } });
@@ -1,19 +0,0 @@
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
- sign(message, provider) {
14
- return __awaiter(this, void 0, void 0, function* () {
15
- throw new Error('[Portal] sign() method must be implemented in a child of BaseSigner');
16
- });
17
- }
18
- }
19
- exports.default = Signer;