@portal-hq/utils 5.0.0 → 5.2.0
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/lib/commonjs/config/index.js +1 -0
- package/lib/commonjs/credentials/index.js +4 -2
- package/lib/commonjs/errors/http-error.js +27 -0
- package/lib/commonjs/errors/index.js +12 -1
- package/lib/commonjs/errors/portal-idempotency-error.js +74 -0
- package/lib/commonjs/errors/portal-policy-error.js +83 -0
- package/lib/commonjs/events/index.js +29 -0
- package/lib/commonjs/idempotency/index.js +74 -0
- package/lib/commonjs/index.js +14 -1
- package/lib/commonjs/version/version.json +1 -1
- package/lib/esm/config/index.js +1 -0
- package/lib/esm/credentials/index.js +5 -3
- package/lib/esm/errors/http-error.js +27 -0
- package/lib/esm/errors/index.js +2 -0
- package/lib/esm/errors/portal-idempotency-error.js +69 -0
- package/lib/esm/errors/portal-policy-error.js +77 -0
- package/lib/esm/events/index.js +29 -0
- package/lib/esm/idempotency/index.js +66 -0
- package/lib/esm/index.js +2 -1
- package/lib/esm/version/version.json +1 -1
- package/package.json +2 -2
- package/src/config/index.ts +1 -0
- package/src/credentials/index.ts +5 -3
- package/src/definitions/index.ts +48 -0
- package/src/errors/http-error.ts +40 -1
- package/src/errors/index.ts +14 -0
- package/src/errors/portal-idempotency-error.ts +91 -0
- package/src/errors/portal-policy-error.ts +97 -0
- package/src/events/index.ts +30 -0
- package/src/idempotency/index.ts +97 -0
- package/src/index.ts +16 -0
- package/src/version/version.json +1 -1
- package/types.d.ts +27 -11
package/lib/esm/events/index.js
CHANGED
|
@@ -33,6 +33,18 @@ var Events;
|
|
|
33
33
|
Events["YieldXyzGetHistoricalActions"] = "YieldXyz Get Historical Actions";
|
|
34
34
|
Events["YieldXyzGetTransaction"] = "YieldXyz Get Transaction";
|
|
35
35
|
Events["YieldXyzTrack"] = "YieldXyz Track";
|
|
36
|
+
Events["YieldXyzBorrowGetIntegrations"] = "YieldXyz Borrow Get Integrations";
|
|
37
|
+
Events["YieldXyzBorrowGetIntegration"] = "YieldXyz Borrow Get Integration";
|
|
38
|
+
Events["YieldXyzBorrowGetMarkets"] = "YieldXyz Borrow Get Markets";
|
|
39
|
+
Events["YieldXyzBorrowGetMarket"] = "YieldXyz Borrow Get Market";
|
|
40
|
+
Events["YieldXyzBorrowGetPositions"] = "YieldXyz Borrow Get Positions";
|
|
41
|
+
Events["YieldXyzBorrowGetLiquidations"] = "YieldXyz Borrow Get Liquidations";
|
|
42
|
+
Events["YieldXyzBorrowCreateAction"] = "YieldXyz Borrow Create Action";
|
|
43
|
+
Events["YieldXyzBorrowGetActions"] = "YieldXyz Borrow Get Actions";
|
|
44
|
+
Events["YieldXyzBorrowGetAction"] = "YieldXyz Borrow Get Action";
|
|
45
|
+
Events["YieldXyzBorrowStepAction"] = "YieldXyz Borrow Step Action";
|
|
46
|
+
Events["YieldXyzBorrowSubmitTransaction"] = "YieldXyz Borrow Submit Transaction";
|
|
47
|
+
Events["YieldXyzBorrowGetHealth"] = "YieldXyz Borrow Get Health";
|
|
36
48
|
Events["LifiGetRoutes"] = "Lifi Get Routes";
|
|
37
49
|
Events["LifiGetQuote"] = "Lifi Get Quote";
|
|
38
50
|
Events["LifiGetStatus"] = "Lifi Get Status";
|
|
@@ -87,5 +99,22 @@ var Events;
|
|
|
87
99
|
Events["MeldGetBuyLimits"] = "Meld Get Buy Limits";
|
|
88
100
|
Events["MeldGetSellLimits"] = "Meld Get Sell Limits";
|
|
89
101
|
Events["MeldGetKycLimits"] = "Meld Get Kyc Limits";
|
|
102
|
+
Events["YieldXyzPerpsGetProviders"] = "YieldXyz Perps Get Providers";
|
|
103
|
+
Events["YieldXyzPerpsGetProvider"] = "YieldXyz Perps Get Provider";
|
|
104
|
+
Events["YieldXyzPerpsGetMarkets"] = "YieldXyz Perps Get Markets";
|
|
105
|
+
Events["YieldXyzPerpsGetMarket"] = "YieldXyz Perps Get Market";
|
|
106
|
+
Events["YieldXyzPerpsGetMarketCandles"] = "YieldXyz Perps Get Market Candles";
|
|
107
|
+
Events["YieldXyzPerpsGetPositions"] = "YieldXyz Perps Get Positions";
|
|
108
|
+
Events["YieldXyzPerpsGetOrders"] = "YieldXyz Perps Get Orders";
|
|
109
|
+
Events["YieldXyzPerpsGetBalances"] = "YieldXyz Perps Get Balances";
|
|
110
|
+
Events["YieldXyzPerpsCreateAction"] = "YieldXyz Perps Create Action";
|
|
111
|
+
Events["YieldXyzPerpsGetActions"] = "YieldXyz Perps Get Actions";
|
|
112
|
+
Events["YieldXyzPerpsGetAction"] = "YieldXyz Perps Get Action";
|
|
113
|
+
Events["YieldXyzPerpsSubmitTransaction"] = "YieldXyz Perps Submit Transaction";
|
|
114
|
+
Events["YieldXyzPerpsGetActivity"] = "YieldXyz Perps Get Activity";
|
|
115
|
+
Events["YieldXyzPerpsGetEvents"] = "YieldXyz Perps Get Events";
|
|
116
|
+
Events["YieldXyzPerpsGetEvent"] = "YieldXyz Perps Get Event";
|
|
117
|
+
Events["YieldXyzPerpsGetHealth"] = "YieldXyz Perps Get Health";
|
|
118
|
+
Events["YieldXyzPerpsGetProvidersHealth"] = "YieldXyz Perps Get Providers Health";
|
|
90
119
|
})(Events || (Events = {}));
|
|
91
120
|
export default Events;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import PortalIdempotencyError from '../errors/portal-idempotency-error';
|
|
2
|
+
import { generateTraceId } from '../tracing';
|
|
3
|
+
/**
|
|
4
|
+
* The HTTP header the Enclave MPC API reads a transaction broadcast's
|
|
5
|
+
* idempotency key from.
|
|
6
|
+
*/
|
|
7
|
+
export const PORTAL_IDEMPOTENCY_KEY_HEADER = 'Idempotency-Key';
|
|
8
|
+
const IDEMPOTENCY_KEY_MAX_LENGTH = 255;
|
|
9
|
+
/** RFC 3986 unreserved characters, the only ones Portal accepts in a key. */
|
|
10
|
+
const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9._~-]+$/;
|
|
11
|
+
const uuidV4FromRandomValues = (getRandomValues) => {
|
|
12
|
+
const bytes = getRandomValues(new Uint8Array(16));
|
|
13
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
14
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
15
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
16
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Generates an idempotency key: a lowercase UUID v4. Generate one per logical
|
|
20
|
+
* operation, store it with the pending operation, and reuse it only to retry
|
|
21
|
+
* that identical request.
|
|
22
|
+
*
|
|
23
|
+
* The key comes from `crypto.randomUUID` or `crypto.getRandomValues` when the
|
|
24
|
+
* runtime provides one. Hermes provides neither unless the app installs a
|
|
25
|
+
* polyfill such as `react-native-get-random-values`; without one the key is
|
|
26
|
+
* built from `Math.random`, which keeps keys unique in practice but is not a
|
|
27
|
+
* cryptographic source.
|
|
28
|
+
*/
|
|
29
|
+
export const generateIdempotencyKey = () => {
|
|
30
|
+
const runtimeCrypto = typeof crypto === 'undefined' ? undefined : crypto;
|
|
31
|
+
if (typeof (runtimeCrypto === null || runtimeCrypto === void 0 ? void 0 : runtimeCrypto.randomUUID) === 'function') {
|
|
32
|
+
return runtimeCrypto.randomUUID().toLowerCase();
|
|
33
|
+
}
|
|
34
|
+
if (typeof (runtimeCrypto === null || runtimeCrypto === void 0 ? void 0 : runtimeCrypto.getRandomValues) === 'function') {
|
|
35
|
+
return uuidV4FromRandomValues(runtimeCrypto.getRandomValues.bind(runtimeCrypto));
|
|
36
|
+
}
|
|
37
|
+
// With neither API available, generateTraceId builds the key from
|
|
38
|
+
// Math.random.
|
|
39
|
+
return generateTraceId().toLowerCase();
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Trims `key` the way Portal does (`String.prototype.trim`) and checks it
|
|
43
|
+
* against Portal's rules: 1–255 characters of `A-Z a-z 0-9 . _ ~ -`.
|
|
44
|
+
*
|
|
45
|
+
* @internal Exported only so the SDK packages can share it across the package
|
|
46
|
+
* boundary. Not part of the public API.
|
|
47
|
+
*
|
|
48
|
+
* @returns The trimmed key, which is the value the SDK sends.
|
|
49
|
+
* @throws {PortalIdempotencyError} `invalidKey`, naming the rule that failed.
|
|
50
|
+
*/
|
|
51
|
+
export const validateIdempotencyKey = (key) => {
|
|
52
|
+
if (typeof key !== 'string') {
|
|
53
|
+
throw new PortalIdempotencyError('invalidKey', 'idempotencyKey must be a string');
|
|
54
|
+
}
|
|
55
|
+
const trimmed = key.trim();
|
|
56
|
+
if (trimmed.length === 0) {
|
|
57
|
+
throw new PortalIdempotencyError('invalidKey', 'idempotencyKey must not be empty or whitespace-only');
|
|
58
|
+
}
|
|
59
|
+
if (trimmed.length > IDEMPOTENCY_KEY_MAX_LENGTH) {
|
|
60
|
+
throw new PortalIdempotencyError('invalidKey', `idempotencyKey must be at most ${IDEMPOTENCY_KEY_MAX_LENGTH} characters`);
|
|
61
|
+
}
|
|
62
|
+
if (!IDEMPOTENCY_KEY_PATTERN.test(trimmed)) {
|
|
63
|
+
throw new PortalIdempotencyError('invalidKey', "idempotencyKey may only contain the characters A-Z, a-z, 0-9, '.', '_', '~' and '-'");
|
|
64
|
+
}
|
|
65
|
+
return trimmed;
|
|
66
|
+
};
|
package/lib/esm/index.js
CHANGED
|
@@ -3,7 +3,8 @@ export { buildDefaultGatewayConfig, DEFAULT_HOSTS } from './config';
|
|
|
3
3
|
export { StaticCredentials, failFromMpcError, invalidateCredentials, onCredentialsInvalidated, reportUnauthorized, resolveCredentials, resolveCredentialToken, staticApiKeyOf, } from './credentials';
|
|
4
4
|
export { convertLocalToCrypto, convertCryptoToLocal, convert } from './currency';
|
|
5
5
|
export { KeychainAdapter, MpcStatuses, PasswordStorage, PortalRequestMethod, Storage, } from './definitions';
|
|
6
|
-
export { CloudStorageReadError, HttpError, InvalidApiKeyError, InvalidChainIdError, InvalidGatewayConfigError, MissingOptionError, MpcSigningError, NoAddressError, PortalAuthError, PortalAuthErrorReason, PortalCredentialError, PortalCredentialErrorReason, MPC_AUTH_FAILED_ERROR_ID, PortalErrorCodes, PortalErrorCodeTypes, PortalMpcError, isMpcAuthFailure, ProviderRpcError, RpcErrorCodes, } from './errors';
|
|
6
|
+
export { CloudStorageReadError, HttpError, InvalidApiKeyError, InvalidChainIdError, InvalidGatewayConfigError, MissingOptionError, MpcSigningError, NoAddressError, PortalAuthError, PortalAuthErrorReason, PortalCredentialError, PortalCredentialErrorReason, MPC_AUTH_FAILED_ERROR_ID, PortalErrorCodes, PortalErrorCodeTypes, PortalMpcError, PortalIdempotencyError, PortalIdempotencyErrorId, isIdempotencyKeyReused, isIdempotencyRejection, PortalPolicyError, POLICY_ERROR_ID_PREFIX, PolicyErrorId, isMpcAuthFailure, isPolicyViolation, mpcErrorFrom, ProviderRpcError, RpcErrorCodes, } from './errors';
|
|
7
|
+
export { generateIdempotencyKey, PORTAL_IDEMPOTENCY_KEY_HEADER, validateIdempotencyKey, } from './idempotency';
|
|
7
8
|
export { default as Events } from './events';
|
|
8
9
|
export { getClientPlatformVersion } from './version';
|
|
9
10
|
export { numberToHexString, parseRequest } from './eth-requests';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{ "version": "5.
|
|
1
|
+
{ "version": "5.2.0" }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@portal-hq/utils",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.2.0",
|
|
4
4
|
"main": "lib/commonjs/index",
|
|
5
5
|
"module": "lib/esm/index",
|
|
6
6
|
"source": "src/index",
|
|
@@ -26,5 +26,5 @@
|
|
|
26
26
|
"ts-jest": "^29.0.3",
|
|
27
27
|
"typescript": "^4.8.4"
|
|
28
28
|
},
|
|
29
|
-
"gitHead": "
|
|
29
|
+
"gitHead": "a14b1c60fd0d4cb72839dc6ed81f6c9f251dd980"
|
|
30
30
|
}
|
package/src/config/index.ts
CHANGED
|
@@ -21,6 +21,7 @@ export const SUPPORTED_CHAINS: ReadonlyArray<{
|
|
|
21
21
|
{ namespace: 'eip155', reference: '84532' },
|
|
22
22
|
{ namespace: 'eip155', reference: '143' },
|
|
23
23
|
{ namespace: 'eip155', reference: '10143' },
|
|
24
|
+
{ namespace: 'eip155', reference: '42161' },
|
|
24
25
|
{ namespace: 'solana', reference: '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' },
|
|
25
26
|
{ namespace: 'solana', reference: 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1' },
|
|
26
27
|
]
|
package/src/credentials/index.ts
CHANGED
|
@@ -4,8 +4,8 @@ import {
|
|
|
4
4
|
PortalCredentialError,
|
|
5
5
|
PortalCredentialErrorReason,
|
|
6
6
|
type PortalError,
|
|
7
|
-
PortalMpcError,
|
|
8
7
|
isMpcAuthFailure,
|
|
8
|
+
mpcErrorFrom,
|
|
9
9
|
} from '../errors'
|
|
10
10
|
import { sdkLogger } from '../logger'
|
|
11
11
|
|
|
@@ -268,7 +268,9 @@ export async function reportUnauthorized(
|
|
|
268
268
|
* envelope rather than a status code any requester here can see.
|
|
269
269
|
*
|
|
270
270
|
* The binary's error is rethrown unchanged either way — the invalidation is
|
|
271
|
-
* bookkeeping, and callers keep branching on `PortalMpcError` and its `id`.
|
|
271
|
+
* bookkeeping, and callers keep branching on `PortalMpcError` and its `id`. A
|
|
272
|
+
* Policy Engine rejection is promoted to `PortalPolicyError`, a subclass, so
|
|
273
|
+
* that stays true.
|
|
272
274
|
*/
|
|
273
275
|
export async function failFromMpcError(
|
|
274
276
|
credentials: PortalCredentials,
|
|
@@ -285,7 +287,7 @@ export async function failFromMpcError(
|
|
|
285
287
|
}
|
|
286
288
|
}
|
|
287
289
|
|
|
288
|
-
throw
|
|
290
|
+
throw mpcErrorFrom(error)
|
|
289
291
|
}
|
|
290
292
|
|
|
291
293
|
/**
|
package/src/definitions/index.ts
CHANGED
|
@@ -85,6 +85,30 @@ export interface RequestOptions {
|
|
|
85
85
|
sponsorGas?: boolean
|
|
86
86
|
signatureApprovalMemo?: string
|
|
87
87
|
traceId?: string
|
|
88
|
+
/**
|
|
89
|
+
* Makes a transaction broadcast safe to retry: while Portal remembers a key
|
|
90
|
+
* (at least 24 hours) it broadcasts it at most once. Honoured for
|
|
91
|
+
* `eth_sendTransaction`, `sol_signAndSendTransaction` and
|
|
92
|
+
* `sol_signAndConfirmTransaction`; ignored with a warning for any other
|
|
93
|
+
* method. Surrounding whitespace is trimmed, and the key must then be 1–255
|
|
94
|
+
* characters of `A-Z a-z 0-9 . _ ~ -`, otherwise the request throws a
|
|
95
|
+
* `PortalIdempotencyError` before the approval prompt. A key on
|
|
96
|
+
* `eth_sendRawTransaction` or `sol_sendTransaction` also throws, because
|
|
97
|
+
* Portal cannot deduplicate a transaction that is already signed.
|
|
98
|
+
*
|
|
99
|
+
* Portal recognises a retry only when its `chainId`, `method` and `params`
|
|
100
|
+
* match the first request's, with `params` compared as the JSON string the
|
|
101
|
+
* SDK sends. Retry with the same transaction object: the same fields in a
|
|
102
|
+
* different order serialize differently, and the retry can be rejected with
|
|
103
|
+
* `IDEMPOTENCY_KEY_REUSED`. No rejection returns the original transaction
|
|
104
|
+
* hash.
|
|
105
|
+
*
|
|
106
|
+
* With presignatures on, a presignature attempt that fails after reaching
|
|
107
|
+
* Portal leaves the fallback sign reusing the key, so Portal can reject it
|
|
108
|
+
* (for example with `IDEMPOTENT_REQUEST_IN_PROGRESS`) where a request without
|
|
109
|
+
* a key would have been signed.
|
|
110
|
+
*/
|
|
111
|
+
idempotencyKey?: string
|
|
88
112
|
}
|
|
89
113
|
|
|
90
114
|
export enum PortalRequestMethod {
|
|
@@ -209,6 +233,30 @@ export interface SendAssetParams {
|
|
|
209
233
|
* to underlying API requests to aid in observability.
|
|
210
234
|
*/
|
|
211
235
|
traceId?: string
|
|
236
|
+
/**
|
|
237
|
+
* Optional idempotency key for the broadcast, honoured on EVM and Solana
|
|
238
|
+
* chains (see `RequestOptions.idempotencyKey`). A key on a Bitcoin chain
|
|
239
|
+
* throws a `PortalIdempotencyError` before the transaction is built.
|
|
240
|
+
*
|
|
241
|
+
* `sendAsset` rebuilds the transaction on every call, and a retry is
|
|
242
|
+
* recognised only when the rebuilt transaction matches the first one. An EVM
|
|
243
|
+
* build carries no nonce or gas, so with unchanged inputs it normally
|
|
244
|
+
* matches and the retry is rejected with the first request's status (for
|
|
245
|
+
* example `IDEMPOTENT_REQUEST_ALREADY_COMPLETED`). A Solana build carries a
|
|
246
|
+
* new recent blockhash, so the retry is usually rejected with
|
|
247
|
+
* `IDEMPOTENCY_KEY_REUSED`, which does not say whether the first transfer
|
|
248
|
+
* is in progress, completed or failed. Either way the transfer is not
|
|
249
|
+
* broadcast twice under this key, and no rejection returns the original
|
|
250
|
+
* transaction hash.
|
|
251
|
+
*
|
|
252
|
+
* Before sending the transfer again under a new key, confirm on-chain that
|
|
253
|
+
* the first one did not land: on Solana, wait until it is confirmed or its
|
|
254
|
+
* recent blockhash has expired; on EVM, until it is confirmed or the
|
|
255
|
+
* account's nonce has moved past it. For predictable retries, build the
|
|
256
|
+
* transaction once and send it with `portal.request` and the same key on
|
|
257
|
+
* every attempt.
|
|
258
|
+
*/
|
|
259
|
+
idempotencyKey?: string
|
|
212
260
|
}
|
|
213
261
|
|
|
214
262
|
export interface RawSignOptions {
|
package/src/errors/http-error.ts
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
type HttpErrorOptions,
|
|
3
|
+
type JsonObject,
|
|
4
|
+
type JsonValue,
|
|
5
|
+
} from '../../types'
|
|
2
6
|
|
|
3
7
|
class HttpError extends Error {
|
|
4
8
|
/** The HTTP status code that produced this error, so callers can distinguish retryable (5xx) from terminal (4xx) failures. */
|
|
5
9
|
public status: number
|
|
10
|
+
/** The Portal API error message (`error` in the response body), when present. */
|
|
11
|
+
public errorMessage?: string
|
|
12
|
+
/** The stable Portal API error identifier (`id` in the response body), when present. */
|
|
13
|
+
public id?: string
|
|
14
|
+
/** Structured error details (`details` in the response body), when present. */
|
|
15
|
+
public details?: JsonObject
|
|
6
16
|
|
|
7
17
|
constructor({ message, status, statusText }: HttpErrorOptions) {
|
|
8
18
|
super(`${status} - ${statusText}: ${message}`)
|
|
@@ -11,7 +21,36 @@ class HttpError extends Error {
|
|
|
11
21
|
Object.setPrototypeOf(this, HttpError.prototype)
|
|
12
22
|
|
|
13
23
|
this.status = status
|
|
24
|
+
|
|
25
|
+
const body = parseJsonBody(message)
|
|
26
|
+
if (!isJsonObject(body)) {
|
|
27
|
+
return
|
|
28
|
+
}
|
|
29
|
+
if (typeof body.error === 'string') {
|
|
30
|
+
this.errorMessage = body.error
|
|
31
|
+
}
|
|
32
|
+
if (typeof body.id === 'string') {
|
|
33
|
+
this.id = body.id
|
|
34
|
+
}
|
|
35
|
+
if (isJsonObject(body.details)) {
|
|
36
|
+
this.details = body.details
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function parseJsonBody(responseText: string): JsonValue | undefined {
|
|
42
|
+
if (responseText.trim() === '') {
|
|
43
|
+
return undefined
|
|
14
44
|
}
|
|
45
|
+
try {
|
|
46
|
+
return JSON.parse(responseText) as JsonValue
|
|
47
|
+
} catch {
|
|
48
|
+
return undefined
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function isJsonObject(value: JsonValue | undefined): value is JsonObject {
|
|
53
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
15
54
|
}
|
|
16
55
|
|
|
17
56
|
export default HttpError
|
package/src/errors/index.ts
CHANGED
|
@@ -17,6 +17,20 @@ export {
|
|
|
17
17
|
type PortalCredentialErrorOptions,
|
|
18
18
|
} from './portal-credential-error'
|
|
19
19
|
export * from './portal-error'
|
|
20
|
+
export {
|
|
21
|
+
default as PortalIdempotencyError,
|
|
22
|
+
type PortalIdempotencyErrorReason,
|
|
23
|
+
PortalIdempotencyErrorId,
|
|
24
|
+
isIdempotencyKeyReused,
|
|
25
|
+
isIdempotencyRejection,
|
|
26
|
+
} from './portal-idempotency-error'
|
|
27
|
+
export {
|
|
28
|
+
default as PortalPolicyError,
|
|
29
|
+
POLICY_ERROR_ID_PREFIX,
|
|
30
|
+
PolicyErrorId,
|
|
31
|
+
isPolicyViolation,
|
|
32
|
+
mpcErrorFrom,
|
|
33
|
+
} from './portal-policy-error'
|
|
20
34
|
export {
|
|
21
35
|
default as ProviderRpcError,
|
|
22
36
|
RpcErrorCodes,
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The IDs Portal returns when it refuses a request because of its idempotency
|
|
3
|
+
* key. None of them carries the original transaction hash, and several mean
|
|
4
|
+
* Portal cannot confirm whether the transaction reached the chain: look it up
|
|
5
|
+
* before sending the operation again under a new key.
|
|
6
|
+
*/
|
|
7
|
+
export const PortalIdempotencyErrorId = {
|
|
8
|
+
RequestInProgress: 'IDEMPOTENT_REQUEST_IN_PROGRESS',
|
|
9
|
+
RequestAlreadyCompleted: 'IDEMPOTENT_REQUEST_ALREADY_COMPLETED',
|
|
10
|
+
RequestPreviouslyFailed: 'IDEMPOTENT_REQUEST_PREVIOUSLY_FAILED',
|
|
11
|
+
RequestUnexpectedState: 'IDEMPOTENT_REQUEST_UNEXPECTED_STATE',
|
|
12
|
+
KeyReused: 'IDEMPOTENCY_KEY_REUSED',
|
|
13
|
+
TxMissing: 'IDEMPOTENT_TX_MISSING',
|
|
14
|
+
} as const
|
|
15
|
+
|
|
16
|
+
const IDEMPOTENCY_ERROR_IDS: ReadonlySet<string> = new Set(
|
|
17
|
+
Object.values(PortalIdempotencyErrorId),
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
const errorIdOf = (error: unknown): unknown =>
|
|
21
|
+
typeof error === 'object' && error !== null
|
|
22
|
+
? (error as { id?: unknown }).id
|
|
23
|
+
: undefined
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Whether Portal refused the request because of its idempotency key: the
|
|
27
|
+
* error's `id` is one of {@link PortalIdempotencyErrorId}. Accepts a raw error
|
|
28
|
+
* envelope or a thrown error, and matches the ID exactly, never the message or
|
|
29
|
+
* `code`.
|
|
30
|
+
*/
|
|
31
|
+
export const isIdempotencyRejection = (error: unknown): boolean => {
|
|
32
|
+
const id = errorIdOf(error)
|
|
33
|
+
|
|
34
|
+
return typeof id === 'string' && IDEMPOTENCY_ERROR_IDS.has(id)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Whether the idempotency key was already used for a request with a different
|
|
39
|
+
* payload ({@link PortalIdempotencyErrorId.KeyReused}).
|
|
40
|
+
*/
|
|
41
|
+
export const isIdempotencyKeyReused = (error: unknown): boolean =>
|
|
42
|
+
errorIdOf(error) === PortalIdempotencyErrorId.KeyReused
|
|
43
|
+
|
|
44
|
+
export type PortalIdempotencyErrorReason = 'invalidKey' | 'unsupportedTarget'
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Cross-copy brand. `instanceof` compares prototypes, so it returns `false`
|
|
48
|
+
* when a consumer's tree resolves two `@portal-hq/utils`.
|
|
49
|
+
*
|
|
50
|
+
* This key and the members {@link PortalIdempotencyError.is} implies are a
|
|
51
|
+
* compatibility contract: changing either breaks recognition between copies.
|
|
52
|
+
*/
|
|
53
|
+
const BRAND: unique symbol = Symbol.for(
|
|
54
|
+
'@portal-hq/utils/PortalIdempotencyError',
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Thrown by the SDK, before anything is signed or sent, when an idempotency key
|
|
59
|
+
* cannot be used: `invalidKey` for a key that breaks Portal's rules, and
|
|
60
|
+
* `unsupportedTarget` for a key on a broadcast Portal cannot deduplicate. The
|
|
61
|
+
* message names the problem and never contains the key.
|
|
62
|
+
*/
|
|
63
|
+
class PortalIdempotencyError extends Error {
|
|
64
|
+
public readonly reason: PortalIdempotencyErrorReason
|
|
65
|
+
|
|
66
|
+
/** @internal Cross-copy brand. Read it through {@link PortalIdempotencyError.is}. */
|
|
67
|
+
public readonly [BRAND] = true
|
|
68
|
+
|
|
69
|
+
constructor(reason: PortalIdempotencyErrorReason, message: string) {
|
|
70
|
+
super(message)
|
|
71
|
+
|
|
72
|
+
Object.setPrototypeOf(this, PortalIdempotencyError.prototype)
|
|
73
|
+
|
|
74
|
+
this.name = 'PortalIdempotencyError'
|
|
75
|
+
this.reason = reason
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Brand check — see BRAND. Narrowing a branded error from another copy to
|
|
80
|
+
* this class is intentional.
|
|
81
|
+
*/
|
|
82
|
+
public static is(error: unknown): error is PortalIdempotencyError {
|
|
83
|
+
return (
|
|
84
|
+
typeof error === 'object' &&
|
|
85
|
+
error !== null &&
|
|
86
|
+
(error as { [BRAND]?: unknown })[BRAND] === true
|
|
87
|
+
)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export default PortalIdempotencyError
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { type PortalError, PortalMpcError } from './portal-error'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Every Policy Engine rejection the gateway emits carries an ID under this
|
|
5
|
+
* prefix. Classification is by prefix, not by a known-ID list, so a policy kind
|
|
6
|
+
* added to the gateway later is still recognised without an SDK release.
|
|
7
|
+
*/
|
|
8
|
+
export const POLICY_ERROR_ID_PREFIX = 'POLICY_'
|
|
9
|
+
|
|
10
|
+
/** The policy IDs the gateway emits today. The set is open — see the prefix. */
|
|
11
|
+
export const PolicyErrorId = {
|
|
12
|
+
AmountLimitExceeded: 'POLICY_AMOUNT_LIMIT_EXCEEDED',
|
|
13
|
+
} as const
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Whether an error reports a Policy Engine rejection.
|
|
17
|
+
*
|
|
18
|
+
* Accepts a raw error envelope or a thrown {@link PortalMpcError}. Matched on
|
|
19
|
+
* the ID, never the companion `code` — the binary maps policy IDs onto a
|
|
20
|
+
* generic legacy code — and never on the message text.
|
|
21
|
+
*/
|
|
22
|
+
export const isPolicyViolation = (error: unknown): boolean => {
|
|
23
|
+
if (typeof error !== 'object' || error === null) {
|
|
24
|
+
return false
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const { id } = error as { id?: unknown }
|
|
28
|
+
|
|
29
|
+
return typeof id === 'string' && id.startsWith(POLICY_ERROR_ID_PREFIX)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Cross-copy brand. `instanceof` compares prototypes, so it returns `false`
|
|
34
|
+
* when a consumer's tree resolves two `@portal-hq/utils` — a real policy
|
|
35
|
+
* rejection would then silently degrade to an ordinary MPC failure.
|
|
36
|
+
*
|
|
37
|
+
* This key and the members {@link PortalPolicyError.is} implies are a
|
|
38
|
+
* compatibility contract: changing either breaks recognition between copies.
|
|
39
|
+
*/
|
|
40
|
+
const BRAND: unique symbol = Symbol.for('@portal-hq/utils/PortalPolicyError')
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A transaction the Policy Engine refused to sign. Extends
|
|
44
|
+
* {@link PortalMpcError} so callers already branching on that type, or reading
|
|
45
|
+
* its `id`, keep working unchanged. `id` always carries the `POLICY_*`
|
|
46
|
+
* identifier here, even though the inherited type leaves it optional.
|
|
47
|
+
*
|
|
48
|
+
* The rejection is terminal: the same request will be refused again, so it is
|
|
49
|
+
* not retried and it never invalidates the credential — the session is fine,
|
|
50
|
+
* the transaction is not.
|
|
51
|
+
*/
|
|
52
|
+
export class PortalPolicyError extends PortalMpcError {
|
|
53
|
+
/** The underlying failure, when the rejection arrived wrapped in one. */
|
|
54
|
+
public readonly cause?: unknown
|
|
55
|
+
|
|
56
|
+
/** @internal Cross-copy brand. Read it through {@link PortalPolicyError.is}. */
|
|
57
|
+
public readonly [BRAND] = true
|
|
58
|
+
|
|
59
|
+
public constructor(error: PortalError, cause?: unknown) {
|
|
60
|
+
super(error)
|
|
61
|
+
|
|
62
|
+
Object.setPrototypeOf(this, PortalPolicyError.prototype)
|
|
63
|
+
|
|
64
|
+
this.cause = cause
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Brand check — see BRAND. Narrowing a branded error from another copy to
|
|
69
|
+
* this class is intentional.
|
|
70
|
+
*/
|
|
71
|
+
public static is(error: unknown): error is PortalPolicyError {
|
|
72
|
+
return (
|
|
73
|
+
typeof error === 'object' &&
|
|
74
|
+
error !== null &&
|
|
75
|
+
(error as { [BRAND]?: unknown })[BRAND] === true
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Builds the error for an MPC envelope, promoting a Policy Engine rejection to
|
|
82
|
+
* {@link PortalPolicyError}. Every other envelope stays a {@link PortalMpcError},
|
|
83
|
+
* so only the policy path changes shape.
|
|
84
|
+
*
|
|
85
|
+
* @internal Exported only so the provider packages can share it across the
|
|
86
|
+
* package boundary. Not part of the public API — catch {@link PortalPolicyError}
|
|
87
|
+
* or call {@link isPolicyViolation} instead.
|
|
88
|
+
*/
|
|
89
|
+
export const mpcErrorFrom = (
|
|
90
|
+
error: PortalError,
|
|
91
|
+
cause?: unknown,
|
|
92
|
+
): PortalMpcError =>
|
|
93
|
+
isPolicyViolation(error)
|
|
94
|
+
? new PortalPolicyError(error, cause)
|
|
95
|
+
: new PortalMpcError(error)
|
|
96
|
+
|
|
97
|
+
export default PortalPolicyError
|
package/src/events/index.ts
CHANGED
|
@@ -33,6 +33,18 @@ enum Events {
|
|
|
33
33
|
YieldXyzGetHistoricalActions = 'YieldXyz Get Historical Actions',
|
|
34
34
|
YieldXyzGetTransaction = 'YieldXyz Get Transaction',
|
|
35
35
|
YieldXyzTrack = 'YieldXyz Track',
|
|
36
|
+
YieldXyzBorrowGetIntegrations = 'YieldXyz Borrow Get Integrations',
|
|
37
|
+
YieldXyzBorrowGetIntegration = 'YieldXyz Borrow Get Integration',
|
|
38
|
+
YieldXyzBorrowGetMarkets = 'YieldXyz Borrow Get Markets',
|
|
39
|
+
YieldXyzBorrowGetMarket = 'YieldXyz Borrow Get Market',
|
|
40
|
+
YieldXyzBorrowGetPositions = 'YieldXyz Borrow Get Positions',
|
|
41
|
+
YieldXyzBorrowGetLiquidations = 'YieldXyz Borrow Get Liquidations',
|
|
42
|
+
YieldXyzBorrowCreateAction = 'YieldXyz Borrow Create Action',
|
|
43
|
+
YieldXyzBorrowGetActions = 'YieldXyz Borrow Get Actions',
|
|
44
|
+
YieldXyzBorrowGetAction = 'YieldXyz Borrow Get Action',
|
|
45
|
+
YieldXyzBorrowStepAction = 'YieldXyz Borrow Step Action',
|
|
46
|
+
YieldXyzBorrowSubmitTransaction = 'YieldXyz Borrow Submit Transaction',
|
|
47
|
+
YieldXyzBorrowGetHealth = 'YieldXyz Borrow Get Health',
|
|
36
48
|
LifiGetRoutes = 'Lifi Get Routes',
|
|
37
49
|
LifiGetQuote = 'Lifi Get Quote',
|
|
38
50
|
LifiGetStatus = 'Lifi Get Status',
|
|
@@ -95,6 +107,24 @@ enum Events {
|
|
|
95
107
|
MeldGetBuyLimits = 'Meld Get Buy Limits',
|
|
96
108
|
MeldGetSellLimits = 'Meld Get Sell Limits',
|
|
97
109
|
MeldGetKycLimits = 'Meld Get Kyc Limits',
|
|
110
|
+
|
|
111
|
+
YieldXyzPerpsGetProviders = 'YieldXyz Perps Get Providers',
|
|
112
|
+
YieldXyzPerpsGetProvider = 'YieldXyz Perps Get Provider',
|
|
113
|
+
YieldXyzPerpsGetMarkets = 'YieldXyz Perps Get Markets',
|
|
114
|
+
YieldXyzPerpsGetMarket = 'YieldXyz Perps Get Market',
|
|
115
|
+
YieldXyzPerpsGetMarketCandles = 'YieldXyz Perps Get Market Candles',
|
|
116
|
+
YieldXyzPerpsGetPositions = 'YieldXyz Perps Get Positions',
|
|
117
|
+
YieldXyzPerpsGetOrders = 'YieldXyz Perps Get Orders',
|
|
118
|
+
YieldXyzPerpsGetBalances = 'YieldXyz Perps Get Balances',
|
|
119
|
+
YieldXyzPerpsCreateAction = 'YieldXyz Perps Create Action',
|
|
120
|
+
YieldXyzPerpsGetActions = 'YieldXyz Perps Get Actions',
|
|
121
|
+
YieldXyzPerpsGetAction = 'YieldXyz Perps Get Action',
|
|
122
|
+
YieldXyzPerpsSubmitTransaction = 'YieldXyz Perps Submit Transaction',
|
|
123
|
+
YieldXyzPerpsGetActivity = 'YieldXyz Perps Get Activity',
|
|
124
|
+
YieldXyzPerpsGetEvents = 'YieldXyz Perps Get Events',
|
|
125
|
+
YieldXyzPerpsGetEvent = 'YieldXyz Perps Get Event',
|
|
126
|
+
YieldXyzPerpsGetHealth = 'YieldXyz Perps Get Health',
|
|
127
|
+
YieldXyzPerpsGetProvidersHealth = 'YieldXyz Perps Get Providers Health',
|
|
98
128
|
}
|
|
99
129
|
|
|
100
130
|
export default Events
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import PortalIdempotencyError from '../errors/portal-idempotency-error'
|
|
2
|
+
import { generateTraceId } from '../tracing'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The HTTP header the Enclave MPC API reads a transaction broadcast's
|
|
6
|
+
* idempotency key from.
|
|
7
|
+
*/
|
|
8
|
+
export const PORTAL_IDEMPOTENCY_KEY_HEADER = 'Idempotency-Key'
|
|
9
|
+
|
|
10
|
+
const IDEMPOTENCY_KEY_MAX_LENGTH = 255
|
|
11
|
+
|
|
12
|
+
/** RFC 3986 unreserved characters, the only ones Portal accepts in a key. */
|
|
13
|
+
const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9._~-]+$/
|
|
14
|
+
|
|
15
|
+
const uuidV4FromRandomValues = (getRandomValues: Crypto['getRandomValues']) => {
|
|
16
|
+
const bytes = getRandomValues(new Uint8Array(16))
|
|
17
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40
|
|
18
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80
|
|
19
|
+
const hex = Array.from(bytes, (byte) =>
|
|
20
|
+
byte.toString(16).padStart(2, '0'),
|
|
21
|
+
).join('')
|
|
22
|
+
|
|
23
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Generates an idempotency key: a lowercase UUID v4. Generate one per logical
|
|
28
|
+
* operation, store it with the pending operation, and reuse it only to retry
|
|
29
|
+
* that identical request.
|
|
30
|
+
*
|
|
31
|
+
* The key comes from `crypto.randomUUID` or `crypto.getRandomValues` when the
|
|
32
|
+
* runtime provides one. Hermes provides neither unless the app installs a
|
|
33
|
+
* polyfill such as `react-native-get-random-values`; without one the key is
|
|
34
|
+
* built from `Math.random`, which keeps keys unique in practice but is not a
|
|
35
|
+
* cryptographic source.
|
|
36
|
+
*/
|
|
37
|
+
export const generateIdempotencyKey = (): string => {
|
|
38
|
+
const runtimeCrypto = typeof crypto === 'undefined' ? undefined : crypto
|
|
39
|
+
|
|
40
|
+
if (typeof runtimeCrypto?.randomUUID === 'function') {
|
|
41
|
+
return runtimeCrypto.randomUUID().toLowerCase()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (typeof runtimeCrypto?.getRandomValues === 'function') {
|
|
45
|
+
return uuidV4FromRandomValues(
|
|
46
|
+
runtimeCrypto.getRandomValues.bind(runtimeCrypto),
|
|
47
|
+
)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// With neither API available, generateTraceId builds the key from
|
|
51
|
+
// Math.random.
|
|
52
|
+
return generateTraceId().toLowerCase()
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Trims `key` the way Portal does (`String.prototype.trim`) and checks it
|
|
57
|
+
* against Portal's rules: 1–255 characters of `A-Z a-z 0-9 . _ ~ -`.
|
|
58
|
+
*
|
|
59
|
+
* @internal Exported only so the SDK packages can share it across the package
|
|
60
|
+
* boundary. Not part of the public API.
|
|
61
|
+
*
|
|
62
|
+
* @returns The trimmed key, which is the value the SDK sends.
|
|
63
|
+
* @throws {PortalIdempotencyError} `invalidKey`, naming the rule that failed.
|
|
64
|
+
*/
|
|
65
|
+
export const validateIdempotencyKey = (key: unknown): string => {
|
|
66
|
+
if (typeof key !== 'string') {
|
|
67
|
+
throw new PortalIdempotencyError(
|
|
68
|
+
'invalidKey',
|
|
69
|
+
'idempotencyKey must be a string',
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const trimmed = key.trim()
|
|
74
|
+
|
|
75
|
+
if (trimmed.length === 0) {
|
|
76
|
+
throw new PortalIdempotencyError(
|
|
77
|
+
'invalidKey',
|
|
78
|
+
'idempotencyKey must not be empty or whitespace-only',
|
|
79
|
+
)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (trimmed.length > IDEMPOTENCY_KEY_MAX_LENGTH) {
|
|
83
|
+
throw new PortalIdempotencyError(
|
|
84
|
+
'invalidKey',
|
|
85
|
+
`idempotencyKey must be at most ${IDEMPOTENCY_KEY_MAX_LENGTH} characters`,
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (!IDEMPOTENCY_KEY_PATTERN.test(trimmed)) {
|
|
90
|
+
throw new PortalIdempotencyError(
|
|
91
|
+
'invalidKey',
|
|
92
|
+
"idempotencyKey may only contain the characters A-Z, a-z, 0-9, '.', '_', '~' and '-'",
|
|
93
|
+
)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return trimmed
|
|
97
|
+
}
|