@portal-hq/provider 4.1.3 → 4.1.5

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.
@@ -44,7 +44,7 @@ class Provider {
44
44
  // Required
45
45
  apiKey, keychain, gatewayConfig,
46
46
  // Optional
47
- autoApprove = false, apiHost = 'api.portalhq.io', mpcHost = 'mpc.portalhq.io', version = 'v6', chainId = 'eip155:11155111', featureFlags = {}, }) {
47
+ autoApprove = false, apiHost = 'api.portalhq.io', mpcHost = 'mpc.portalhq.io', enclaveMPCHost = 'mpc-client.portalhq.io', version = 'v6', chainId = 'eip155:11155111', featureFlags = {}, }) {
48
48
  // Handle required fields
49
49
  if (!apiKey || apiKey.length === 0) {
50
50
  throw new utils_1.InvalidApiKeyError();
@@ -69,14 +69,26 @@ class Provider {
69
69
  });
70
70
  // Initialize Gateway HttpRequester
71
71
  this.gateway = new utils_1.PortalRequests();
72
- // Initialize an MpcSigner
73
- this.signer = new signers_1.MpcSigner({
74
- mpcHost,
75
- keychain,
76
- version,
77
- portalApi: this.portalApi,
78
- featureFlags,
79
- });
72
+ // Initialize the appropriate signer based on feature flags
73
+ if (featureFlags.useEnclaveMPCApi) {
74
+ this.signer = new signers_1.EnclaveSigner({
75
+ mpcHost,
76
+ enclaveMPCHost,
77
+ keychain,
78
+ version,
79
+ portalApi: this.portalApi,
80
+ featureFlags,
81
+ });
82
+ }
83
+ else {
84
+ this.signer = new signers_1.MpcSigner({
85
+ mpcHost,
86
+ keychain,
87
+ version,
88
+ portalApi: this.portalApi,
89
+ featureFlags,
90
+ });
91
+ }
80
92
  }
81
93
  /**
82
94
  * Invokes all registered event handlers with the data provided
@@ -282,8 +294,7 @@ class Provider {
282
294
  });
283
295
  }
284
296
  /**
285
- * Updates the chainId of this instance and builds a new RPC HttpRequester for
286
- * the gateway used for the new chain
297
+ * Updates the chainId of this instance
287
298
  *
288
299
  * @param chainId The numerical ID of the chain to switch to
289
300
  * @returns BaseProvider
@@ -0,0 +1,323 @@
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
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const core_1 = require("@portal-hq/core");
16
+ const utils_1 = require("@portal-hq/utils");
17
+ const react_native_uuid_1 = __importDefault(require("react-native-uuid"));
18
+ var Operation;
19
+ (function (Operation) {
20
+ Operation["SIGN"] = "sign";
21
+ Operation["RAW_SIGN"] = "raw_sign";
22
+ })(Operation || (Operation = {}));
23
+ class EnclaveSigner {
24
+ constructor({ keychain, enclaveMPCHost = 'mpc-client.portalhq.io', version = 'v6', portalApi, featureFlags = {}, }) {
25
+ this.version = 'v6';
26
+ this.buildParams = (method, txParams) => {
27
+ let params = txParams;
28
+ switch (method) {
29
+ case 'eth_sign':
30
+ case 'personal_sign':
31
+ case 'eth_signTypedData_v3':
32
+ case 'eth_signTypedData_v4':
33
+ case 'sol_signMessage':
34
+ case 'sol_signTransaction':
35
+ case 'sol_signAndSendTransaction':
36
+ case 'sol_signAndConfirmTransaction':
37
+ if (!Array.isArray(txParams)) {
38
+ params = [txParams];
39
+ }
40
+ break;
41
+ default:
42
+ if (Array.isArray(txParams)) {
43
+ if (txParams.length === 1) {
44
+ params = txParams[0];
45
+ }
46
+ }
47
+ }
48
+ return params;
49
+ };
50
+ this.featureFlags = featureFlags;
51
+ this.keychain = keychain;
52
+ this.enclaveMPCHost = enclaveMPCHost;
53
+ this.version = version;
54
+ this.portalApi = portalApi;
55
+ this.requests = new utils_1.HttpRequester({
56
+ baseUrl: `https://${this.enclaveMPCHost}`,
57
+ });
58
+ }
59
+ sign(message, provider) {
60
+ return __awaiter(this, void 0, void 0, function* () {
61
+ // Always track metrics, but only send if feature flag is enabled
62
+ const shouldSendMetrics = this.featureFlags.enableSdkPerformanceMetrics === true;
63
+ const signStartTime = performance.now();
64
+ const preOperationStartTime = performance.now();
65
+ // Generate a traceId for this operation
66
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
67
+ const traceId = react_native_uuid_1.default.v4();
68
+ const metrics = {
69
+ hasError: false,
70
+ operation: Operation.SIGN,
71
+ signingMethod: message.method,
72
+ traceId,
73
+ };
74
+ try {
75
+ const eip155Address = yield this.keychain.getEip155Address();
76
+ const apiKey = provider.apiKey;
77
+ const { method, chainId, curve, isRaw } = message;
78
+ // Add chainId to metrics
79
+ if (chainId) {
80
+ metrics.chainId = chainId;
81
+ }
82
+ switch (method) {
83
+ case 'eth_requestAccounts':
84
+ return [eip155Address];
85
+ case 'eth_accounts':
86
+ return [eip155Address];
87
+ default:
88
+ break;
89
+ }
90
+ const shares = yield this.keychain.getShares();
91
+ let signingShare = shares.secp256k1.share;
92
+ if (curve === core_1.PortalCurve.ED25519) {
93
+ if (!shares.ed25519) {
94
+ throw new Error('[Portal.Provider.EnclaveSigner] The ED25519 share is missing from the keychain.');
95
+ }
96
+ signingShare = shares.ed25519.share;
97
+ }
98
+ const metadata = {
99
+ clientPlatform: 'REACT_NATIVE',
100
+ clientPlatformVersion: (0, utils_1.getClientPlatformVersion)(),
101
+ isMultiBackupEnabled: this.featureFlags.isMultiBackupEnabled,
102
+ mpcServerVersion: this.version,
103
+ optimized: true,
104
+ curve,
105
+ chainId,
106
+ isRaw,
107
+ reqId: traceId,
108
+ connectionTracingEnabled: shouldSendMetrics,
109
+ };
110
+ // Build params
111
+ // Avoid double JSON encoding: if params is already a string (e.g. a hex message), pass it directly; otherwise stringify objects/arrays.
112
+ const params = this.buildParams(method, message.params);
113
+ let formattedParams;
114
+ if (isRaw) {
115
+ if (typeof params !== 'string') {
116
+ throw new Error('[Portal.Provider.EnclaveSigner] For raw signing, params must be a string (e.g., a hex-encoded message).');
117
+ }
118
+ formattedParams = params;
119
+ }
120
+ else {
121
+ formattedParams =
122
+ typeof params === 'string' ? params : JSON.stringify(params);
123
+ }
124
+ // Get RPC URL
125
+ const rpcUrl = isRaw ? '' : provider.getGatewayUrl(chainId);
126
+ // Set metrics operation
127
+ metrics.operation = isRaw ? Operation.RAW_SIGN : Operation.SIGN;
128
+ if (typeof formattedParams !== 'string') {
129
+ throw new Error(`[Portal.Provider.EnclaveSigner] The formatted params for the signing request could not be converted to a string. The params were: ${formattedParams}`);
130
+ }
131
+ // Record pre-operation time
132
+ metrics.sdkPreOperationMs = performance.now() - preOperationStartTime;
133
+ // Measure enclave signing operation time
134
+ const enclaveSignStartTime = performance.now();
135
+ const result = isRaw
136
+ ? yield this.enclaveRawSign(apiKey, JSON.stringify(signingShare), formattedParams, curve || 'SECP256K1')
137
+ : yield this.enclaveSign(apiKey, JSON.stringify(signingShare), message.method, formattedParams, rpcUrl, chainId || '', JSON.stringify(metadata));
138
+ // Post-operation processing time starts
139
+ const postOperationStartTime = performance.now();
140
+ // Record HTTP call time
141
+ metrics.enclaveHttpCallMs = performance.now() - enclaveSignStartTime;
142
+ // Record post-operation time
143
+ metrics.sdkPostOperationMs = performance.now() - postOperationStartTime;
144
+ // Calculate total SDK signing time
145
+ metrics.sdkOperationMs = performance.now() - signStartTime;
146
+ // Log performance timing to console
147
+ const timingMetrics = {};
148
+ if (typeof metrics.sdkPreOperationMs === 'number') {
149
+ timingMetrics['Pre-operation'] = metrics.sdkPreOperationMs;
150
+ }
151
+ if (typeof metrics.enclaveHttpCallMs === 'number') {
152
+ timingMetrics['Enclave HTTP Call'] = metrics.enclaveHttpCallMs;
153
+ }
154
+ if (typeof metrics.sdkPostOperationMs === 'number') {
155
+ timingMetrics['Post-operation'] = metrics.sdkPostOperationMs;
156
+ }
157
+ // Only send metrics if the feature flag is enabled
158
+ if (shouldSendMetrics && this.portalApi) {
159
+ try {
160
+ yield this.sendMetrics(metrics, apiKey);
161
+ }
162
+ catch (err) {
163
+ // No-op
164
+ }
165
+ }
166
+ return result;
167
+ }
168
+ catch (error) {
169
+ // Calculate total time even in error case
170
+ metrics.sdkOperationMs = performance.now() - signStartTime;
171
+ // Log performance timing to console even in error case
172
+ const errorTimingMetrics = {};
173
+ if (typeof metrics.sdkPreOperationMs === 'number') {
174
+ errorTimingMetrics['Pre-operation'] = metrics.sdkPreOperationMs;
175
+ }
176
+ // Only send metrics if the feature flag is enabled
177
+ if (shouldSendMetrics) {
178
+ const apiKey = provider.apiKey;
179
+ metrics.hasError = true;
180
+ try {
181
+ yield this.sendMetrics(metrics, apiKey);
182
+ }
183
+ catch (_a) {
184
+ // No-op
185
+ }
186
+ }
187
+ throw error;
188
+ }
189
+ });
190
+ }
191
+ enclaveRawSign(apiKey, signingShare, params, curve) {
192
+ var _a;
193
+ return __awaiter(this, void 0, void 0, function* () {
194
+ if (!apiKey || !signingShare || !params || !curve) {
195
+ return this.encodeErrorResult('INVALID_PARAMETERS', 'Invalid parameters provided for raw signing');
196
+ }
197
+ const requestBody = {
198
+ params: params,
199
+ share: signingShare,
200
+ };
201
+ const endpoint = `/v1/raw/sign/${curve}`;
202
+ try {
203
+ const response = yield this.requests.post(endpoint, {
204
+ headers: {
205
+ Authorization: `Bearer ${apiKey}`,
206
+ 'Content-Type': 'application/json',
207
+ },
208
+ body: requestBody,
209
+ });
210
+ return this.encodeSuccessResult(response.data);
211
+ }
212
+ catch (error) {
213
+ if ((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) {
214
+ const portalError = this.decodePortalError(JSON.stringify(error.response.data));
215
+ return this.encodeErrorResult(portalError === null || portalError === void 0 ? void 0 : portalError.id, portalError === null || portalError === void 0 ? void 0 : portalError.message);
216
+ }
217
+ return this.encodeErrorResult('SIGNING_NETWORK_ERROR',
218
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument
219
+ error.message || 'Network error occurred');
220
+ }
221
+ });
222
+ }
223
+ enclaveSign(apiKey, signingShare, method, params, rpcURL, chainId, metadata) {
224
+ var _a;
225
+ return __awaiter(this, void 0, void 0, function* () {
226
+ if (!apiKey ||
227
+ !signingShare ||
228
+ !method ||
229
+ !params ||
230
+ !chainId ||
231
+ !metadata) {
232
+ return this.encodeErrorResult('INVALID_PARAMETERS', 'Invalid parameters provided');
233
+ }
234
+ const requestBody = {
235
+ method: method,
236
+ params: params,
237
+ share: signingShare,
238
+ chainId: chainId,
239
+ rpcUrl: rpcURL,
240
+ metadataStr: metadata,
241
+ clientPlatform: 'REACT_NATIVE',
242
+ clientPlatformVersion: (0, utils_1.getClientPlatformVersion)(),
243
+ };
244
+ try {
245
+ const response = yield this.requests.post('/v1/sign', {
246
+ headers: {
247
+ Authorization: `Bearer ${apiKey}`,
248
+ 'Content-Type': 'application/json',
249
+ },
250
+ body: requestBody,
251
+ });
252
+ return this.encodeSuccessResult(response.data);
253
+ }
254
+ catch (error) {
255
+ if ((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) {
256
+ const portalError = this.decodePortalError(JSON.stringify(error.response.data));
257
+ return this.encodeErrorResult(portalError === null || portalError === void 0 ? void 0 : portalError.id, portalError === null || portalError === void 0 ? void 0 : portalError.message);
258
+ }
259
+ return this.encodeErrorResult('SIGNING_NETWORK_ERROR',
260
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument
261
+ error.message || 'Network error occurred');
262
+ }
263
+ });
264
+ }
265
+ // Helper function to encode success results
266
+ encodeSuccessResult(data) {
267
+ const successResult = { data: data, error: undefined };
268
+ return this.encodeJSON(successResult);
269
+ }
270
+ // Helper function to decode Portal errors
271
+ decodePortalError(errorStr) {
272
+ if (!errorStr)
273
+ return null;
274
+ try {
275
+ return JSON.parse(errorStr);
276
+ }
277
+ catch (_a) {
278
+ return null;
279
+ }
280
+ }
281
+ // Helper function to encode error results
282
+ encodeErrorResult(id, message) {
283
+ const errorResult = {
284
+ data: undefined,
285
+ error: { id, message },
286
+ };
287
+ return this.encodeJSON(errorResult);
288
+ }
289
+ // Helper function to encode any object to JSON string
290
+ encodeJSON(value) {
291
+ try {
292
+ const jsonString = JSON.stringify(value);
293
+ return jsonString;
294
+ }
295
+ catch (error) {
296
+ return JSON.stringify({
297
+ error: {
298
+ id: 'ENCODING_ERROR',
299
+ message: `Failed to encode JSON: ${error.message}`,
300
+ },
301
+ });
302
+ }
303
+ }
304
+ sendMetrics(metrics, apiKey) {
305
+ return __awaiter(this, void 0, void 0, function* () {
306
+ try {
307
+ if (this.portalApi) {
308
+ yield this.portalApi.post('/api/v3/clients/me/sdk/metrics', {
309
+ headers: {
310
+ Authorization: `Bearer ${apiKey}`,
311
+ 'Content-Type': 'application/json',
312
+ },
313
+ body: metrics,
314
+ });
315
+ }
316
+ }
317
+ catch (_a) {
318
+ // No-op
319
+ }
320
+ });
321
+ }
322
+ }
323
+ exports.default = EnclaveSigner;
@@ -3,8 +3,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.MpcSigner = exports.Signer = void 0;
6
+ exports.EnclaveSigner = exports.MpcSigner = exports.Signer = void 0;
7
7
  var abstract_1 = require("./abstract");
8
8
  Object.defineProperty(exports, "Signer", { enumerable: true, get: function () { return __importDefault(abstract_1).default; } });
9
9
  var mpc_1 = require("./mpc");
10
10
  Object.defineProperty(exports, "MpcSigner", { enumerable: true, get: function () { return __importDefault(mpc_1).default; } });
11
+ var enclave_1 = require("./enclave");
12
+ Object.defineProperty(exports, "EnclaveSigner", { enumerable: true, get: function () { return __importDefault(enclave_1).default; } });
@@ -158,7 +158,7 @@ class MpcSigner {
158
158
  metrics.sdkBinaryConnectMs = binaryMetrics.connectMs;
159
159
  }
160
160
  }
161
- if ((error === null || error === void 0 ? void 0 : error.code) > 0) {
161
+ if (error === null || error === void 0 ? void 0 : error.id) {
162
162
  throw new utils_1.PortalMpcError(error);
163
163
  }
164
164
  // Record post-operation time
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import { PortalCurve } from '@portal-hq/core';
11
11
  import { Events, HttpRequester, InvalidApiKeyError, InvalidGatewayConfigError, PortalRequests, ProviderRpcError, RpcErrorCodes, } from '@portal-hq/utils';
12
- import { MpcSigner } from '../signers';
12
+ import { MpcSigner, EnclaveSigner } from '../signers';
13
13
  const passiveSignerMethods = [
14
14
  'eth_accounts',
15
15
  'eth_chainId',
@@ -42,7 +42,7 @@ class Provider {
42
42
  // Required
43
43
  apiKey, keychain, gatewayConfig,
44
44
  // Optional
45
- autoApprove = false, apiHost = 'api.portalhq.io', mpcHost = 'mpc.portalhq.io', version = 'v6', chainId = 'eip155:11155111', featureFlags = {}, }) {
45
+ autoApprove = false, apiHost = 'api.portalhq.io', mpcHost = 'mpc.portalhq.io', enclaveMPCHost = 'mpc-client.portalhq.io', version = 'v6', chainId = 'eip155:11155111', featureFlags = {}, }) {
46
46
  // Handle required fields
47
47
  if (!apiKey || apiKey.length === 0) {
48
48
  throw new InvalidApiKeyError();
@@ -67,14 +67,26 @@ class Provider {
67
67
  });
68
68
  // Initialize Gateway HttpRequester
69
69
  this.gateway = new PortalRequests();
70
- // Initialize an MpcSigner
71
- this.signer = new MpcSigner({
72
- mpcHost,
73
- keychain,
74
- version,
75
- portalApi: this.portalApi,
76
- featureFlags,
77
- });
70
+ // Initialize the appropriate signer based on feature flags
71
+ if (featureFlags.useEnclaveMPCApi) {
72
+ this.signer = new EnclaveSigner({
73
+ mpcHost,
74
+ enclaveMPCHost,
75
+ keychain,
76
+ version,
77
+ portalApi: this.portalApi,
78
+ featureFlags,
79
+ });
80
+ }
81
+ else {
82
+ this.signer = new MpcSigner({
83
+ mpcHost,
84
+ keychain,
85
+ version,
86
+ portalApi: this.portalApi,
87
+ featureFlags,
88
+ });
89
+ }
78
90
  }
79
91
  /**
80
92
  * Invokes all registered event handlers with the data provided
@@ -280,8 +292,7 @@ class Provider {
280
292
  });
281
293
  }
282
294
  /**
283
- * Updates the chainId of this instance and builds a new RPC HttpRequester for
284
- * the gateway used for the new chain
295
+ * Updates the chainId of this instance
285
296
  *
286
297
  * @param chainId The numerical ID of the chain to switch to
287
298
  * @returns BaseProvider