@stridge/pay-sdk 0.0.0-stage → 0.1.0-alpha.1
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/LICENSE +21 -0
- package/README.md +32 -2
- package/dist/cjs/_internal/coordinator.cjs +3898 -0
- package/dist/cjs/_internal/coordinator.cjs.map +1 -0
- package/dist/cjs/_internal/coordinator.d.cts +6263 -0
- package/dist/cjs/guards-CQWGp5eP.d.cts +3311 -0
- package/dist/cjs/guards-r1nnLHLD.cjs +3617 -0
- package/dist/cjs/guards-r1nnLHLD.cjs.map +1 -0
- package/dist/cjs/index.cjs +40 -0
- package/dist/cjs/index.d.cts +2 -0
- package/dist/esm/_internal/coordinator.d.ts +6263 -0
- package/dist/esm/_internal/coordinator.js +3677 -0
- package/dist/esm/_internal/coordinator.js.map +1 -0
- package/dist/esm/guards-CQWGp5eP.d.ts +3311 -0
- package/dist/esm/guards-CukG42GQ.js +2940 -0
- package/dist/esm/guards-CukG42GQ.js.map +1 -0
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +2 -0
- package/package.json +54 -3
|
@@ -0,0 +1,3677 @@
|
|
|
1
|
+
import { $ as HUB_NEEDS_POPUP_MESSAGE, $t as SUA_PROTOCOL_VERSION, At as PAY_ELEMENT_MESSAGE_TYPES, B as payJobOf, Bt as PAY_PROTOCOL, C as isElementMessage, Ct as PAY_AMOUNT_PATTERN, D as isHubFrameAppMessage, Dt as PAY_ELEMENT_FAILURE_CODES, E as isHubElementMessage, Et as PAY_DESTINATION_RULE_PATTERN, F as isElementCheckoutResultPayload, Ft as PAY_FUND_REQUEST_TYPE, Gt as SUA_ELEMENT_GEOMETRY_EASINGS, H as samePayDestinationAsk, Ht as SESSION_HEADER_OMIT, I as isElementDepositRequestPayload, It as PAY_FUND_START_SCREENS, J as GUEST_COOKIE_ACCESS_HEADER, Jt as SUA_GUEST_HANDOFF_MESSAGE_TYPE, K as APP_ID_PATTERN, Kt as SUA_ELEMENT_RELOAD_REASONS, L as isElementPaidPayload, Lt as PAY_HUB_FRAME_MESSAGE_TYPES, M as isWindowElementMessage, Mt as PAY_ELEMENT_PATH, N as answersPayAmount, Nt as PAY_FIRST_STEPS, O as isHubFrameName, Ot as PAY_ELEMENT_LIFETIME_MESSAGE_TYPES, P as comparePayAmounts, Pt as PAY_FUND_MESSAGE_TYPES, Q as HUB_GUEST_COOKIE_NAME, Qt as SUA_PAY_REQUEST_TYPE, R as isElementPayRequestAckPayload, Rt as PAY_JOBS, S as isElementHubMessage, St as MAX_SIGN_MESSAGE_BYTES, T as isHubBuildId, Tt as PAY_DESTINATION_ASSET_PATTERN, U as samePayTerms, Ut as SUA_ACCOUNT_EMAIL_MESSAGE_TYPES, V as sameLegacyPayDestinationAsk, Vt as SESSION_HEADER, W as createHubSuaEnvelope, Wt as SUA_APP_WINDOW_MESSAGE_TYPES, X as HUB_CSRF_COOKIE_NAME, Xt as SUA_LINK_C_MESSAGE_TYPES, Y as HUB_BUILD_ID_PATTERN, Yt as SUA_LINK_C_ID_SEPARATOR, Z as HUB_FRAME_NAME_PATTERN, Zt as SUA_LINK_C_STREAM_PREFIXES, _ as isAppElementMessage, _t as MAX_PAY_AMOUNT, a as decodeAppWindowAccountEmailRefreshMessage, an as utf8ToBytes, at as MAX_ACCOUNT_EMAIL_LENGTH, b as isAppWindowHubMessage, bt as MAX_PAY_SOURCE_FUNDS_WALLETS, c as decodeElementHubMessage, ct as MAX_ELEMENT_BLOCK_SIZE, d as decodeHubElementMessage, dt as MAX_ERROR_MESSAGE_LENGTH, en as SUA_RELAY_CONTROL_MESSAGE_TYPES, et as HUB_PARTITIONED_GUEST_COOKIE_NAME, f as decodeHubFrameAppMessage, ft as MAX_HUB_BALANCE_AMOUNT_LENGTH, g as decodeWindowElementMessage, gt as MAX_PAGE_URL_LENGTH, h as decodeWindowAccountEmailMessage, ht as MAX_MESSAGE_ID_LENGTH, i as decodeAppWindowAccountEmailMessage, in as bytesToUtf8, it as MAX_ACCOUNT_EMAIL_LEASE_MS, j as isSuaEnvelope, jt as PAY_ELEMENT_NOTIFICATION_MESSAGE_TYPES, k as isHubMessage, kt as PAY_ELEMENT_LOAD_FAILURE_REASONS, l as decodeElementMessage, lt as MAX_ELEMENT_LABEL_LENGTH, m as decodeRelayAccountEmailMessage, mt as MAX_MENU_RECT_VALUE, n as decodeAppHubFrameMessage, nn as SUA_WINDOW_CANCEL_CAUSES, nt as HUB_SURFACE_POPUP, o as decodeAppWindowAccountEmailRefreshReplyMessage, ot as MAX_ACCOUNT_IDENTITY_LENGTH, p as decodeHubMessage, pt as MAX_HUB_BUILD_ID_LENGTH, q as EVM_ADDRESS_PATTERN, qt as SUA_FUND_WINDOW_MESSAGE_TYPE, r as decodeAppMessage, rn as SUA_WINDOW_END_CAUSES, rt as HUB_URL_PARAMS, s as decodeAppWindowHubMessage, st as MAX_APP_ORIGIN_LENGTH, t as decodeAppElementMessage, tn as SUA_RELAY_MESSAGE_TYPES, tt as HUB_SURFACE_ELEMENT, u as decodeElementWindowMessage, ut as MAX_ELEMENT_RESIZE_DURATION_MS, v as isAppHubFrameMessage, vt as MAX_PAY_ITEM_LENGTH, w as isElementWindowMessage, wt as PAY_CURRENCIES, x as isAppearance, xt as MAX_RELAY_STATE_EXPIRY_LENGTH, y as isAppMessage, yt as MAX_PAY_PAYOUT_ADDRESS_LENGTH, z as isElementPayRequestPayload, zt as PAY_MESSAGE_TYPES } from "../guards-CukG42GQ.js";
|
|
2
|
+
//#region src/client/constants.ts
|
|
3
|
+
/**
|
|
4
|
+
* The path prefix of the sign-in routes and every route that needs a session.
|
|
5
|
+
*/
|
|
6
|
+
const WALLET_API_PREFIX = "/wallet/v1";
|
|
7
|
+
/**
|
|
8
|
+
* The path prefix of the guest routes: the guest, its saved accounts and its checkout.
|
|
9
|
+
*/
|
|
10
|
+
const PAY_API_PREFIX = "/pay/v1";
|
|
11
|
+
/**
|
|
12
|
+
* Every path prefix the client calls under `baseUrl`, and so every prefix a hub proxy forwards.
|
|
13
|
+
*/
|
|
14
|
+
const HUB_API_PREFIXES = [WALLET_API_PREFIX, PAY_API_PREFIX];
|
|
15
|
+
/**
|
|
16
|
+
* The CSRF double-submit header. Sent with the stored `csrf_token` on every `POST`, `PUT` and `DELETE`.
|
|
17
|
+
*/
|
|
18
|
+
const CSRF_HEADER = "X-CSRF-Token";
|
|
19
|
+
/**
|
|
20
|
+
* The app attribution header. Sent with the client's `appId` on `POST /wallet/v1/credentials/session`, `GET
|
|
21
|
+
* /wallet/v1/account` and `POST /wallet/v1/relay` (the routes that require it, `internal/hub/router.go`), on the linked
|
|
22
|
+
* wallet routes (`POST /wallet/v1/external-accounts`, `PATCH /wallet/v1/external-accounts/{id}`), on every
|
|
23
|
+
* `/wallet/v1/routes` route, on the guest routes, on the wallet offer answer and on every pay-in route. Attribution is
|
|
24
|
+
* never authority: the Coordinator does not check it against `Origin`.
|
|
25
|
+
*/
|
|
26
|
+
const APP_HEADER = "X-Stridge-App";
|
|
27
|
+
/**
|
|
28
|
+
* The idempotency header, required on route open and pay-in confirm. Repeating an open key returns its first route.
|
|
29
|
+
* Repeating a confirm key with the same body returns its pay-in; a different body is IDEMPOTENCY_KEY_REUSED.
|
|
30
|
+
* The Coordinator scopes the key to the identity.
|
|
31
|
+
*/
|
|
32
|
+
const IDEMPOTENCY_HEADER = "Idempotency-Key";
|
|
33
|
+
/**
|
|
34
|
+
* The longest `Idempotency-Key` the Coordinator takes, in characters.
|
|
35
|
+
*/
|
|
36
|
+
const MAX_IDEMPOTENCY_KEY_LENGTH = 128;
|
|
37
|
+
/**
|
|
38
|
+
* The most routes one `GET /wallet/v1/routes` answer holds, and the largest `limit` the client sends.
|
|
39
|
+
*/
|
|
40
|
+
const MAX_ROUTE_LIST_LIMIT = 100;
|
|
41
|
+
/**
|
|
42
|
+
* The CAIP-2 chain every route leaves from, Tempo (the Coordinator's `routing/domain.SourceChain`): the only
|
|
43
|
+
* `chain_id` a route step may name. A route answer with a step on any other chain is unusable.
|
|
44
|
+
*/
|
|
45
|
+
const ROUTE_SOURCE_CHAIN_ID = "eip155:4217";
|
|
46
|
+
/**
|
|
47
|
+
* The response header the hub proxy repeats the Coordinator's `Date` in, so the client can read the Coordinator's
|
|
48
|
+
* clock even where the hosting platform rewrites `Date` with its own. The client reads it before `Date`.
|
|
49
|
+
*/
|
|
50
|
+
const UPSTREAM_DATE_HEADER = "X-Stridge-Upstream-Date";
|
|
51
|
+
/**
|
|
52
|
+
* The longest `name` a pay-in quote's `wallet` descriptor takes, in characters (pay-in guide §4.2); a longer one is
|
|
53
|
+
* `400 WALLET_MALFORMED`. The client sends the name as given, so cut it to this length first.
|
|
54
|
+
*/
|
|
55
|
+
const MAX_EXTERNAL_WALLET_NAME_LENGTH = 64;
|
|
56
|
+
/**
|
|
57
|
+
* The most chains a pay-in quote's `wallet.capabilities` names (pay-in guide §4.2); more is `400 WALLET_MALFORMED`.
|
|
58
|
+
* The client sends the chains as given.
|
|
59
|
+
*/
|
|
60
|
+
const MAX_WALLET_CAPABILITY_CHAINS = 64;
|
|
61
|
+
/**
|
|
62
|
+
* The canonical Permit2 contract, at the same address on every EVM chain: the only spender a pay-in's approvals name,
|
|
63
|
+
* whether the wallet sends one (K7) or signs one (K3 to K5), and the verifying contract of a Permit2 transfer (K2).
|
|
64
|
+
* Never a Stridge contract.
|
|
65
|
+
*/
|
|
66
|
+
const PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
|
|
67
|
+
/**
|
|
68
|
+
* Relay's depository, at the same address on every EVM chain it serves: the only `to` of a coin send (mechanism `W`),
|
|
69
|
+
* which deposits the wallet's native coin there through `depositNative`. Never a Stridge contract.
|
|
70
|
+
*/
|
|
71
|
+
const RELAY_DEPOSITORY_ADDRESS = "0x4cD00E387622C35bDDB9b4c962C136462338BC31";
|
|
72
|
+
/**
|
|
73
|
+
* The selector of Relay's `depositNative(address depositor, bytes32 id)`, lowercase with its `0x`: the call of every
|
|
74
|
+
* coin send.
|
|
75
|
+
*/
|
|
76
|
+
const DEPOSIT_NATIVE_SELECTOR = "0x49290c1c";
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region src/errors/CsrfStoreError.ts
|
|
79
|
+
/**
|
|
80
|
+
* The verify succeeded but `csrf.set` threw or rejected (for example `sessionStorage` refusing a write with
|
|
81
|
+
* `QuotaExceededError` or `SecurityError`). Thrown by `CoordinatorClient.verifyRound` in that case.
|
|
82
|
+
*
|
|
83
|
+
* The session is already open: the Coordinator set its cookie in the same answer, and no route re-issues the token.
|
|
84
|
+
* So the answer is never discarded. `answer` holds it in full, `csrf_token` and `credential` included: keep the token
|
|
85
|
+
* (retry the store, or hold it in memory) and carry on with the credential, or the session stays locked until its
|
|
86
|
+
* absolute expiry.
|
|
87
|
+
*/
|
|
88
|
+
var CsrfStoreError = class CsrfStoreError extends Error {
|
|
89
|
+
/**
|
|
90
|
+
* The verify answer, unchanged.
|
|
91
|
+
*/
|
|
92
|
+
answer;
|
|
93
|
+
/**
|
|
94
|
+
* The value `csrf.set` threw or rejected with.
|
|
95
|
+
*/
|
|
96
|
+
cause;
|
|
97
|
+
/**
|
|
98
|
+
* Wraps the store failure. The message is always `The csrf_token could not be stored`.
|
|
99
|
+
*/
|
|
100
|
+
constructor(answer, cause) {
|
|
101
|
+
super("The csrf_token could not be stored");
|
|
102
|
+
this.name = "CsrfStoreError";
|
|
103
|
+
this.answer = answer;
|
|
104
|
+
this.cause = cause;
|
|
105
|
+
Object.setPrototypeOf(this, CsrfStoreError.prototype);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
//#endregion
|
|
109
|
+
//#region src/shared/isJsonObject.ts
|
|
110
|
+
/**
|
|
111
|
+
* Reports whether `value` is a non-null, non-array object: the shape a parsed JSON object has. Unlike the protocol
|
|
112
|
+
* guards' stricter check, class instances pass. Internal: not exported from the package index.
|
|
113
|
+
*/
|
|
114
|
+
function isJsonObject(value) {
|
|
115
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
//#region src/errors/SuaError.ts
|
|
119
|
+
/**
|
|
120
|
+
* A request got an HTTP answer that is not a usable success. Thrown by every `CoordinatorClient` method for any
|
|
121
|
+
* response whose body is the error envelope, for any non-2xx response, and for a `2xx` whose body is unusable (empty,
|
|
122
|
+
* not JSON, not an object, or an unexpected `204`), which has code `internal` and its `2xx` status.
|
|
123
|
+
*
|
|
124
|
+
* With the envelope it is the Coordinator's own answer: a refusal, or an outcome it could not assert (`code:
|
|
125
|
+
* "ambiguous"`). Without one (`body` is not an `ErrorEnvelopeDto`) it most likely came from a hop in front of the
|
|
126
|
+
* Coordinator, a proxy's `502` for example, and says nothing about whether the request reached it. `settleRelay`
|
|
127
|
+
* reads a relay's `2xx` and `5xx` as unknown for that reason.
|
|
128
|
+
*
|
|
129
|
+
* Client transitions key on `status` plus `reason` (guide §11); `code` is the coarser kind. The fields map from the
|
|
130
|
+
* envelope (`toSuaError`) as follows; the SDK keeps its own names, so `code` here is not the envelope's `code`:
|
|
131
|
+
*
|
|
132
|
+
* | `SuaError` | Envelope | Example |
|
|
133
|
+
* |---|---|---|
|
|
134
|
+
* | `code` | `error.type` | `"rejected"` |
|
|
135
|
+
* | `reason` | `error.code`, when it is a published code; `""` for a bare kind | `"SESSION_EXPIRED"` |
|
|
136
|
+
* | `requestId` | `error.request_id` | `"req_01J8Z…"` |
|
|
137
|
+
* | `param` | `error.param` | `"limit"` |
|
|
138
|
+
*/
|
|
139
|
+
var SuaError = class SuaError extends Error {
|
|
140
|
+
/**
|
|
141
|
+
* The HTTP status.
|
|
142
|
+
*/
|
|
143
|
+
status;
|
|
144
|
+
/**
|
|
145
|
+
* The envelope's kind.
|
|
146
|
+
*/
|
|
147
|
+
code;
|
|
148
|
+
/**
|
|
149
|
+
* The envelope's stable code (`error.code`), or `""`.
|
|
150
|
+
*/
|
|
151
|
+
reason;
|
|
152
|
+
/**
|
|
153
|
+
* Whole seconds from `Retry-After`, when the response carried one (every rate-limit `429` does).
|
|
154
|
+
*/
|
|
155
|
+
retryAfterSeconds;
|
|
156
|
+
/**
|
|
157
|
+
* The Coordinator's id for the request (`req_…`), when the envelope carried one. Quote it in bug reports.
|
|
158
|
+
*/
|
|
159
|
+
requestId;
|
|
160
|
+
/**
|
|
161
|
+
* The request field the refusal is about, when the envelope named one.
|
|
162
|
+
*/
|
|
163
|
+
param;
|
|
164
|
+
/**
|
|
165
|
+
* The response body, for diagnostics.
|
|
166
|
+
*/
|
|
167
|
+
body;
|
|
168
|
+
/**
|
|
169
|
+
* Builds the error. The message reads `Coordinator answered <status> <code>`, followed by ` (<reason>)` when the
|
|
170
|
+
* reason is not empty.
|
|
171
|
+
*/
|
|
172
|
+
constructor(init) {
|
|
173
|
+
super(`Coordinator answered ${init.status} ${init.code}${init.reason ? ` (${init.reason})` : ""}`);
|
|
174
|
+
this.name = "SuaError";
|
|
175
|
+
this.status = init.status;
|
|
176
|
+
this.code = init.code;
|
|
177
|
+
this.reason = init.reason;
|
|
178
|
+
this.retryAfterSeconds = init.retryAfterSeconds;
|
|
179
|
+
this.requestId = init.requestId;
|
|
180
|
+
this.param = init.param;
|
|
181
|
+
this.body = init.body;
|
|
182
|
+
Object.setPrototypeOf(this, SuaError.prototype);
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
//#endregion
|
|
186
|
+
//#region src/errors/SuaNetworkError.ts
|
|
187
|
+
/**
|
|
188
|
+
* The request got no HTTP answer: `fetch` rejected for a reason other than the caller's abort (DNS, TLS, a dropped
|
|
189
|
+
* connection, a CORS refusal). Thrown by every `CoordinatorClient` method in that case.
|
|
190
|
+
*
|
|
191
|
+
* On a state-changing call the request may still have reached the Coordinator, so the outcome is unknown: never
|
|
192
|
+
* re-send a registration or a relay automatically. `settleRelay` reads it as an unknown outcome.
|
|
193
|
+
*/
|
|
194
|
+
var SuaNetworkError = class SuaNetworkError extends Error {
|
|
195
|
+
/**
|
|
196
|
+
* The value `fetch` rejected with.
|
|
197
|
+
*/
|
|
198
|
+
cause;
|
|
199
|
+
/**
|
|
200
|
+
* Wraps the rejection. The message is always `Network request failed`.
|
|
201
|
+
*/
|
|
202
|
+
constructor(cause) {
|
|
203
|
+
super("Network request failed");
|
|
204
|
+
this.name = "SuaNetworkError";
|
|
205
|
+
this.cause = cause;
|
|
206
|
+
Object.setPrototypeOf(this, SuaNetworkError.prototype);
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
//#endregion
|
|
210
|
+
//#region src/errors/guards.ts
|
|
211
|
+
/**
|
|
212
|
+
* Reports whether `value` is shaped like the Coordinator's error envelope: a non-null, non-array object whose `error`
|
|
213
|
+
* is a non-null, non-array object with a string `code`. Neither the value of `code` nor `type` (of any type, or
|
|
214
|
+
* absent) is checked here: `toSuaError` normalises both, so a malformed kind still reads as a refusal rather than as
|
|
215
|
+
* a success body. Extra keys are allowed.
|
|
216
|
+
*
|
|
217
|
+
* This is how the client tells an error body from a success body on a `2xx` (the relay's `202` is an envelope; the
|
|
218
|
+
* round's `202` and the registration's `202` are not).
|
|
219
|
+
*/
|
|
220
|
+
function isErrorEnvelopeDto(value) {
|
|
221
|
+
if (!isJsonObject(value)) return false;
|
|
222
|
+
const error = value.error;
|
|
223
|
+
return isJsonObject(error) && typeof error.code === "string";
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Reports whether `value` is a {@link SuaError}, optionally with a given reason.
|
|
227
|
+
*
|
|
228
|
+
* True when `value instanceof SuaError`, or, for a copy of the class from a second bundle, when it is an `Error`
|
|
229
|
+
* whose `name` is `"SuaError"` and which has a numeric `status` and string `code` and `reason`. With `reason`
|
|
230
|
+
* given, the error's `reason` must also equal it (`isSuaError(error, "CREDENTIAL_EXPIRED")`).
|
|
231
|
+
*/
|
|
232
|
+
function isSuaError(value, reason) {
|
|
233
|
+
if (!(value instanceof SuaError) && !isSuaErrorCopy(value)) return false;
|
|
234
|
+
return reason === void 0 || value.reason === reason;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Reports whether `value` is a {@link SuaNetworkError}: `instanceof`, or an `Error` whose `name` is
|
|
238
|
+
* `"SuaNetworkError"`.
|
|
239
|
+
*/
|
|
240
|
+
function isSuaNetworkError(value) {
|
|
241
|
+
return value instanceof SuaNetworkError || value instanceof Error && value.name === "SuaNetworkError";
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Reports whether `value` is a {@link CsrfStoreError}: `instanceof`, or an `Error` whose `name` is `"CsrfStoreError"`
|
|
245
|
+
* and which carries an `answer` object.
|
|
246
|
+
*/
|
|
247
|
+
function isCsrfStoreError(value) {
|
|
248
|
+
if (value instanceof CsrfStoreError) return true;
|
|
249
|
+
return value instanceof Error && value.name === "CsrfStoreError" && isJsonObject(value.answer);
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* The duck-typed half of {@link isSuaError}: a `SuaError` built by another copy of the class.
|
|
253
|
+
*/
|
|
254
|
+
function isSuaErrorCopy(value) {
|
|
255
|
+
if (!(value instanceof Error) || value.name !== "SuaError") return false;
|
|
256
|
+
const fields = value;
|
|
257
|
+
return typeof fields.status === "number" && typeof fields.code === "string" && typeof fields.reason === "string";
|
|
258
|
+
}
|
|
259
|
+
//#endregion
|
|
260
|
+
//#region src/errors/json.ts
|
|
261
|
+
/**
|
|
262
|
+
* Parses a response body read as text. Never throws.
|
|
263
|
+
*/
|
|
264
|
+
function parseBody(text) {
|
|
265
|
+
if (text === "") return { kind: "empty" };
|
|
266
|
+
try {
|
|
267
|
+
return {
|
|
268
|
+
kind: "json",
|
|
269
|
+
value: JSON.parse(text)
|
|
270
|
+
};
|
|
271
|
+
} catch {
|
|
272
|
+
return {
|
|
273
|
+
kind: "text",
|
|
274
|
+
text
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
//#endregion
|
|
279
|
+
//#region src/errors/SuaReason.ts
|
|
280
|
+
/**
|
|
281
|
+
* Every reason code a hub API route the client calls can name, as the Coordinator's `pkg/errs` code list publishes them
|
|
282
|
+
* (guide §11 lists most of them). `""` is the refusal that names no reason.
|
|
283
|
+
*/
|
|
284
|
+
const SUA_REASONS = [
|
|
285
|
+
"SESSION_MISSING",
|
|
286
|
+
"CHECKOUT_RULE_NOT_FOUND",
|
|
287
|
+
"SESSION_EXPIRED",
|
|
288
|
+
"SESSION_REVOKED",
|
|
289
|
+
"CREDENTIAL_EXPIRED",
|
|
290
|
+
"APP_SUSPENDED",
|
|
291
|
+
"ROUND_NOT_YOURS",
|
|
292
|
+
"INVALID_CHALLENGE_CODE",
|
|
293
|
+
"CHALLENGE_EXHAUSTED",
|
|
294
|
+
"WALLET_NOT_ACTIVE",
|
|
295
|
+
"PROVIDER_DRAINING",
|
|
296
|
+
"ACCOUNT_EJECTED",
|
|
297
|
+
"LOGIN_NOT_PERMITTED",
|
|
298
|
+
"IDEMPOTENCY_KEY_MISSING",
|
|
299
|
+
"IDEMPOTENCY_KEY_REUSED",
|
|
300
|
+
"ASSET_NOT_LISTED",
|
|
301
|
+
"AMOUNT_MALFORMED",
|
|
302
|
+
"DESTINATION_MALFORMED",
|
|
303
|
+
"DESTINATION_REQUIRED",
|
|
304
|
+
"ROUTING_UNAVAILABLE",
|
|
305
|
+
"ROUTE_NOT_OFFERED",
|
|
306
|
+
"ROUTE_UNAVAILABLE",
|
|
307
|
+
"ROUTE_NOT_FOUND",
|
|
308
|
+
"ROUTE_SOURCE_ALREADY_REPORTED",
|
|
309
|
+
"ROUTE_TX_CLAIMED",
|
|
310
|
+
"ROUTE_NOT_REPORTABLE",
|
|
311
|
+
"ROUTE_TX_MISMATCH",
|
|
312
|
+
"PAYMENT_IN_FLIGHT",
|
|
313
|
+
"INVALID_ADDRESS",
|
|
314
|
+
"WALLET_MALFORMED",
|
|
315
|
+
"WALLET_WOUND_DOWN",
|
|
316
|
+
"AMOUNT_BELOW_MINIMUM",
|
|
317
|
+
"INSUFFICIENT_ROUTABLE_BALANCE",
|
|
318
|
+
"QUOTE_EXPIRED",
|
|
319
|
+
"BALANCES_STALE",
|
|
320
|
+
"ROUTE_STATE_CONFLICT",
|
|
321
|
+
"ROUTE_BUSY",
|
|
322
|
+
"SIGNATURE_BATCH_INVALID",
|
|
323
|
+
"INTERNAL",
|
|
324
|
+
"WALLET_BRAND_UNKNOWN",
|
|
325
|
+
"WALLET_BRAND_MISMATCH",
|
|
326
|
+
"EXTERNAL_ACCOUNT_LIMIT",
|
|
327
|
+
"EXTERNAL_ACCOUNT_REMOVED",
|
|
328
|
+
"RATE_LIMITED",
|
|
329
|
+
"APP_NOT_FOUND",
|
|
330
|
+
"GUEST_UNKNOWN",
|
|
331
|
+
"GUEST_HANDOFF_INVALID",
|
|
332
|
+
"GUEST_ALREADY_MERGED",
|
|
333
|
+
"GUEST_OFFER_CHANGED",
|
|
334
|
+
""
|
|
335
|
+
];
|
|
336
|
+
//#endregion
|
|
337
|
+
//#region src/errors/parseSuaError.ts
|
|
338
|
+
/**
|
|
339
|
+
* The six envelope kinds the Coordinator names (`pkg/errs/errs.go`).
|
|
340
|
+
*/
|
|
341
|
+
const ERROR_KINDS = [
|
|
342
|
+
"invalid",
|
|
343
|
+
"not_found",
|
|
344
|
+
"conflict",
|
|
345
|
+
"rejected",
|
|
346
|
+
"ambiguous",
|
|
347
|
+
"internal"
|
|
348
|
+
];
|
|
349
|
+
/**
|
|
350
|
+
* The obsolete asctime HTTP-date form (`Sun Nov 6 08:49:37 1994`), RFC 9110 §5.6.7.
|
|
351
|
+
*/
|
|
352
|
+
const ASCTIME_DATE = /^[A-Za-z]{3} [A-Za-z]{3} [ \d]\d \d{2}:\d{2}:\d{2} \d{4}$/;
|
|
353
|
+
/**
|
|
354
|
+
* Builds a {@link SuaError} from a failure response that was already read.
|
|
355
|
+
*
|
|
356
|
+
* 1. `body` is parsed as JSON when it is not empty; a parse failure keeps the raw text.
|
|
357
|
+
* 2. When the parsed value is an error envelope (`isErrorEnvelopeDto`):
|
|
358
|
+
* - `code` is `error.type` when it is one of the six `ErrorKindDto` values, and `"internal"` otherwise;
|
|
359
|
+
* - `reason` is `error.code` when it is one of `SUA_REASONS`, and `""` otherwise (the bare kind a refusal with no
|
|
360
|
+
* stable code carries, such as a rate-limit `429`'s `"rejected"`, or a code the SDK does not list);
|
|
361
|
+
* - `requestId` is `error.request_id` and `param` is `error.param`, each when it is a non-empty string.
|
|
362
|
+
* 3. Otherwise (no envelope: empty body, HTML, another JSON shape) `code` is `"internal"` and `reason` is `""`,
|
|
363
|
+
* whatever the status.
|
|
364
|
+
* 4. `retryAfterSeconds` is `parseRetryAfter(retryAfter)`.
|
|
365
|
+
* 5. `SuaError.body` is the parsed JSON, else the raw text, else `undefined` for an empty body.
|
|
366
|
+
*
|
|
367
|
+
* Never throws.
|
|
368
|
+
*/
|
|
369
|
+
function toSuaError(response) {
|
|
370
|
+
const parsed = parseBody(response.body);
|
|
371
|
+
let code = "internal";
|
|
372
|
+
let reason = "";
|
|
373
|
+
let requestId;
|
|
374
|
+
let param;
|
|
375
|
+
let body;
|
|
376
|
+
if (parsed.kind === "json") {
|
|
377
|
+
body = parsed.value;
|
|
378
|
+
if (isErrorEnvelopeDto(parsed.value)) {
|
|
379
|
+
const error = parsed.value.error;
|
|
380
|
+
code = toErrorKind(error.type);
|
|
381
|
+
reason = toReason(error.code);
|
|
382
|
+
requestId = toNonEmptyString(error.request_id);
|
|
383
|
+
param = toNonEmptyString(error.param);
|
|
384
|
+
}
|
|
385
|
+
} else if (parsed.kind === "text") body = parsed.text;
|
|
386
|
+
return new SuaError({
|
|
387
|
+
status: response.status,
|
|
388
|
+
code,
|
|
389
|
+
reason,
|
|
390
|
+
retryAfterSeconds: parseRetryAfter(response.retryAfter),
|
|
391
|
+
requestId,
|
|
392
|
+
param,
|
|
393
|
+
body
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Reads a failure `Response` into a {@link SuaError}: reads `response.text()` once (a read failure counts as an empty
|
|
398
|
+
* body), takes `Retry-After` from `response.headers`, and delegates to {@link toSuaError}.
|
|
399
|
+
*
|
|
400
|
+
* Consumes the body. Never rejects.
|
|
401
|
+
*/
|
|
402
|
+
async function parseSuaError(response) {
|
|
403
|
+
let body = "";
|
|
404
|
+
try {
|
|
405
|
+
body = await response.text();
|
|
406
|
+
} catch {
|
|
407
|
+
body = "";
|
|
408
|
+
}
|
|
409
|
+
let retryAfter = null;
|
|
410
|
+
try {
|
|
411
|
+
retryAfter = response.headers.get("Retry-After");
|
|
412
|
+
} catch {
|
|
413
|
+
retryAfter = null;
|
|
414
|
+
}
|
|
415
|
+
return toSuaError({
|
|
416
|
+
status: response.status,
|
|
417
|
+
retryAfter,
|
|
418
|
+
body
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Reads a `Retry-After` header value (RFC 9110 §10.2.3) into whole seconds to wait.
|
|
423
|
+
*
|
|
424
|
+
* - A non-negative integer of decimal digits (`"30"`, surrounding whitespace allowed) is returned as that number.
|
|
425
|
+
* This is the only form the Coordinator sends (`ceil` of the bucket window, at least 1).
|
|
426
|
+
* - An HTTP-date (`"Wed, 21 Oct 2015 07:28:00 GMT"`) is returned as `max(0, ceil((date - nowMs) / 1000))`.
|
|
427
|
+
* - `null`, `""`, a negative or fractional number, or anything unparseable returns `undefined`.
|
|
428
|
+
*
|
|
429
|
+
* @param value The raw header value.
|
|
430
|
+
* @param nowMs The current time in ms since the epoch, for the HTTP-date form. Defaults to `Date.now()`.
|
|
431
|
+
*/
|
|
432
|
+
function parseRetryAfter(value, nowMs) {
|
|
433
|
+
if (value === null) return;
|
|
434
|
+
const trimmed = value.trim();
|
|
435
|
+
if (/^\d+$/.test(trimmed)) {
|
|
436
|
+
const seconds = Number(trimmed);
|
|
437
|
+
return Number.isSafeInteger(seconds) ? seconds : void 0;
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Every HTTP-date form (IMF-fixdate, RFC 850, asctime) starts with a day name. Requiring it keeps `Date.parse`'s
|
|
441
|
+
* lenient reading of strings such as `"-1"` or `"1.5"` out.
|
|
442
|
+
*/
|
|
443
|
+
if (!/^[A-Za-z]{3,9},?\s/.test(trimmed)) return;
|
|
444
|
+
/**
|
|
445
|
+
* The asctime form carries no zone but is UTC by definition; `Date.parse` would read it as local time.
|
|
446
|
+
*/
|
|
447
|
+
const dateMs = Date.parse(ASCTIME_DATE.test(trimmed) ? `${trimmed} GMT` : trimmed);
|
|
448
|
+
if (Number.isNaN(dateMs)) return;
|
|
449
|
+
return Math.max(0, Math.ceil((dateMs - (nowMs ?? Date.now())) / 1e3));
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Narrows an envelope's `type` onto {@link ErrorKindDto}, reading an absent or unknown kind as `internal`.
|
|
453
|
+
*/
|
|
454
|
+
function toErrorKind(type) {
|
|
455
|
+
return ERROR_KINDS.find((kind) => kind === type) ?? "internal";
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Narrows an envelope's `code` onto {@link SuaReason}, reading a bare kind, an absent or an unlisted code as `""`.
|
|
459
|
+
*/
|
|
460
|
+
function toReason(code) {
|
|
461
|
+
return SUA_REASONS.find((known) => known === code) ?? "";
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Returns `value` when it is a non-empty string, else `undefined`.
|
|
465
|
+
*/
|
|
466
|
+
function toNonEmptyString(value) {
|
|
467
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
468
|
+
}
|
|
469
|
+
//#endregion
|
|
470
|
+
//#region src/models/Route/entities/RouteStateDto.ts
|
|
471
|
+
/**
|
|
472
|
+
* Every state a route can be in, in the order a route moves through them, as the Coordinator lists core's route
|
|
473
|
+
* states (`internal/routing/domain/routes.go` `States`). `GET /wallet/v1/routes?status=…` refuses any other name.
|
|
474
|
+
*/
|
|
475
|
+
const ROUTE_STATES = [
|
|
476
|
+
"planned",
|
|
477
|
+
"expired",
|
|
478
|
+
"submitted",
|
|
479
|
+
"awaiting_destination",
|
|
480
|
+
"stalled",
|
|
481
|
+
"completed",
|
|
482
|
+
"refunded",
|
|
483
|
+
"failed",
|
|
484
|
+
"unresolved"
|
|
485
|
+
];
|
|
486
|
+
//#endregion
|
|
487
|
+
//#region src/client/endpoints.ts
|
|
488
|
+
/**
|
|
489
|
+
* Every hub endpoint the client calls, keyed by the client method that calls it. The single place a path is spelled;
|
|
490
|
+
* the `satisfies` check holds each verb and path to the generated document.
|
|
491
|
+
*/
|
|
492
|
+
const HUB_ENDPOINTS = {
|
|
493
|
+
resolveGuestCheckout: ["post", "/pay/v1/checkouts/resolve"],
|
|
494
|
+
resolveCheckout: ["post", "/wallet/v1/checkouts/resolve"],
|
|
495
|
+
listGuestAssets: ["get", "/pay/v1/assets"],
|
|
496
|
+
listAssets: ["get", "/wallet/v1/assets"],
|
|
497
|
+
startRound: ["post", "/wallet/v1/auth-rounds"],
|
|
498
|
+
getRound: ["get", "/wallet/v1/auth-rounds/{id}"],
|
|
499
|
+
verifyRound: ["post", "/wallet/v1/auth-rounds/{id}/verify"],
|
|
500
|
+
registerKeypair: ["post", "/wallet/v1/credentials/session"],
|
|
501
|
+
getSession: ["get", "/wallet/v1/session"],
|
|
502
|
+
signOut: ["delete", "/wallet/v1/session"],
|
|
503
|
+
getWallet: ["get", "/wallet/v1/account"],
|
|
504
|
+
relay: ["post", "/wallet/v1/relay"],
|
|
505
|
+
saveExternalAccount: ["post", "/wallet/v1/external-accounts"],
|
|
506
|
+
markExternalAccountUsed: ["patch", "/wallet/v1/external-accounts/{id}"],
|
|
507
|
+
removeExternalAccount: ["delete", "/wallet/v1/external-accounts/{id}"],
|
|
508
|
+
answerWalletOffer: ["patch", "/wallet/v1/session"],
|
|
509
|
+
quoteRoute: ["post", "/wallet/v1/routes/quotes"],
|
|
510
|
+
openRoute: ["post", "/wallet/v1/routes"],
|
|
511
|
+
getRoute: ["get", "/wallet/v1/routes/{id}"],
|
|
512
|
+
listRoutes: ["get", "/wallet/v1/routes"],
|
|
513
|
+
reportRouteSource: ["post", "/wallet/v1/routes/{id}/source"],
|
|
514
|
+
getExternalBalances: ["get", "/wallet/v1/balances"],
|
|
515
|
+
warmExternalBalances: ["post", "/wallet/v1/balances"],
|
|
516
|
+
quoteTopUp: ["post", "/wallet/v1/smart-routes"],
|
|
517
|
+
quoteCheckout: ["post", "/wallet/v1/smart-routes"],
|
|
518
|
+
getPayIn: ["get", "/wallet/v1/smart-routes/{id}"],
|
|
519
|
+
confirmPayIn: ["post", "/wallet/v1/smart-routes/{id}/confirm"],
|
|
520
|
+
adjustPayIn: ["post", "/wallet/v1/smart-routes/{id}/adjust"],
|
|
521
|
+
cancelPayIn: ["post", "/wallet/v1/smart-routes/{id}/cancel"],
|
|
522
|
+
createGuestHandoff: ["post", "/pay/v1/handoffs"],
|
|
523
|
+
mergeGuestSession: ["post", "/pay/v1/session/merge"],
|
|
524
|
+
openGuest: ["post", "/pay/v1/session"],
|
|
525
|
+
saveGuestWallet: ["post", "/pay/v1/external-accounts"],
|
|
526
|
+
removeGuestWallet: ["delete", "/pay/v1/external-accounts/{id}"],
|
|
527
|
+
markGuestWalletUsed: ["patch", "/pay/v1/external-accounts/{id}"],
|
|
528
|
+
getGuestExternalBalances: ["get", "/pay/v1/balances"],
|
|
529
|
+
warmGuestExternalBalances: ["post", "/pay/v1/balances"],
|
|
530
|
+
quoteGuestPayIn: ["post", "/pay/v1/smart-routes"],
|
|
531
|
+
getGuestPayIn: ["get", "/pay/v1/smart-routes/{id}"],
|
|
532
|
+
confirmGuestPayIn: ["post", "/pay/v1/smart-routes/{id}/confirm"],
|
|
533
|
+
adjustGuestPayIn: ["post", "/pay/v1/smart-routes/{id}/adjust"],
|
|
534
|
+
cancelGuestPayIn: ["post", "/pay/v1/smart-routes/{id}/cancel"]
|
|
535
|
+
};
|
|
536
|
+
/**
|
|
537
|
+
* Builds one call's verb and path from its endpoint. `id` replaces the template's `{id}` and must already be encoded;
|
|
538
|
+
* `query` is appended as given (`""` or `?a=b`).
|
|
539
|
+
*/
|
|
540
|
+
function hubTarget(name, id, query = "") {
|
|
541
|
+
const [verb, template] = HUB_ENDPOINTS[name];
|
|
542
|
+
const path = id === void 0 ? template : template.replace("{id}", id);
|
|
543
|
+
return {
|
|
544
|
+
method: verb.toUpperCase(),
|
|
545
|
+
path: `${path}${query}`
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
//#endregion
|
|
549
|
+
//#region src/models/PayIn/entities/PayInDripDto.ts
|
|
550
|
+
/**
|
|
551
|
+
* Every state of the gas Stridge sends a wallet for an `R` leg (pay-in guide §5.3.2, §6.2), in order.
|
|
552
|
+
*/
|
|
553
|
+
const PAY_IN_DRIP_STATES = [
|
|
554
|
+
"held",
|
|
555
|
+
"sending",
|
|
556
|
+
"landed"
|
|
557
|
+
];
|
|
558
|
+
//#endregion
|
|
559
|
+
//#region src/models/PayIn/entities/PayInLegStateDto.ts
|
|
560
|
+
/**
|
|
561
|
+
* Every state a pay-in leg can be in (pay-in guide §7.2), as core names them, grouped as the guide shows them.
|
|
562
|
+
*/
|
|
563
|
+
const PAY_IN_LEG_STATES = [
|
|
564
|
+
"planned",
|
|
565
|
+
"needs_signature",
|
|
566
|
+
"needs_approval",
|
|
567
|
+
"approving",
|
|
568
|
+
"submitting",
|
|
569
|
+
"submitted",
|
|
570
|
+
"in_flight",
|
|
571
|
+
"refunding",
|
|
572
|
+
"voiding",
|
|
573
|
+
"filled",
|
|
574
|
+
"refunded",
|
|
575
|
+
"voided",
|
|
576
|
+
"dropped",
|
|
577
|
+
"needs_support",
|
|
578
|
+
"written_off"
|
|
579
|
+
];
|
|
580
|
+
//#endregion
|
|
581
|
+
//#region src/models/PayIn/entities/PayInMechanismDto.ts
|
|
582
|
+
/**
|
|
583
|
+
* Every mechanism a pay-in leg can pull funds with (pay-in guide §6), as core names them.
|
|
584
|
+
*/
|
|
585
|
+
const PAY_IN_MECHANISMS = [
|
|
586
|
+
"P",
|
|
587
|
+
"C",
|
|
588
|
+
"B",
|
|
589
|
+
"G",
|
|
590
|
+
"N",
|
|
591
|
+
"R",
|
|
592
|
+
"S",
|
|
593
|
+
"D",
|
|
594
|
+
"W",
|
|
595
|
+
"T",
|
|
596
|
+
"X",
|
|
597
|
+
"Y",
|
|
598
|
+
"U",
|
|
599
|
+
"V"
|
|
600
|
+
];
|
|
601
|
+
//#endregion
|
|
602
|
+
//#region src/models/PayIn/entities/PayInPhaseDto.ts
|
|
603
|
+
/**
|
|
604
|
+
* Every phase a pay-in reports (pay-in guide §5.3), as core names them.
|
|
605
|
+
*/
|
|
606
|
+
const PAY_IN_PHASES = ["executing", "winding_down"];
|
|
607
|
+
//#endregion
|
|
608
|
+
//#region src/models/PayIn/entities/PayInShapeDto.ts
|
|
609
|
+
/**
|
|
610
|
+
* Every shape a pay-in plan takes (pay-in guide §5.3), as core names them.
|
|
611
|
+
*/
|
|
612
|
+
const PAY_IN_SHAPES = ["single_leg", "multi_leg"];
|
|
613
|
+
//#endregion
|
|
614
|
+
//#region src/models/PayIn/entities/PayInStateDto.ts
|
|
615
|
+
/**
|
|
616
|
+
* Every state a pay-in can be in (pay-in guide §7.1), as core names them.
|
|
617
|
+
*/
|
|
618
|
+
const PAY_IN_STATES = [
|
|
619
|
+
"requires_confirmation",
|
|
620
|
+
"requires_action",
|
|
621
|
+
"processing",
|
|
622
|
+
"on_hold",
|
|
623
|
+
"completed",
|
|
624
|
+
"failed",
|
|
625
|
+
"canceled",
|
|
626
|
+
"expired"
|
|
627
|
+
];
|
|
628
|
+
/**
|
|
629
|
+
* The states a pay-in never leaves: polling stops at them.
|
|
630
|
+
*/
|
|
631
|
+
const PAY_IN_TERMINAL_STATES = [
|
|
632
|
+
"completed",
|
|
633
|
+
"failed",
|
|
634
|
+
"canceled",
|
|
635
|
+
"expired"
|
|
636
|
+
];
|
|
637
|
+
//#endregion
|
|
638
|
+
//#region src/models/PayIn/entities/PayInStepSchemeDto.ts
|
|
639
|
+
/**
|
|
640
|
+
* Every scheme core issues to external wallets (pay-in guide §8). The step model also defines
|
|
641
|
+
* `eip7702_authorization` and `tempo_transaction`, which core never issues to an external wallet.
|
|
642
|
+
*/
|
|
643
|
+
const PAY_IN_STEP_SCHEMES = [
|
|
644
|
+
"eip712",
|
|
645
|
+
"evm_transaction",
|
|
646
|
+
"solana_transaction"
|
|
647
|
+
];
|
|
648
|
+
//#endregion
|
|
649
|
+
//#region src/models/PayIn/entities/PayInStepStatusDto.ts
|
|
650
|
+
/**
|
|
651
|
+
* Every status a pay-in step can have (pay-in guide §7.3), as core names them.
|
|
652
|
+
*/
|
|
653
|
+
const PAY_IN_STEP_STATUSES = [
|
|
654
|
+
"unsigned",
|
|
655
|
+
"signed",
|
|
656
|
+
"submitted",
|
|
657
|
+
"invalid",
|
|
658
|
+
"expired",
|
|
659
|
+
"refused",
|
|
660
|
+
"superseded",
|
|
661
|
+
"dead"
|
|
662
|
+
];
|
|
663
|
+
//#endregion
|
|
664
|
+
//#region src/models/PayIn/entities/PayInUnspendableDto.ts
|
|
665
|
+
/**
|
|
666
|
+
* Every reason a holding goes unused (pay-in guide §5.3.1), as core names them.
|
|
667
|
+
*/
|
|
668
|
+
const PAY_IN_UNSPENDABLE_REASONS = [
|
|
669
|
+
"route_unverifiable",
|
|
670
|
+
"native_coin",
|
|
671
|
+
"smart_account",
|
|
672
|
+
"no_free_route",
|
|
673
|
+
"drip_refused",
|
|
674
|
+
"approval_required",
|
|
675
|
+
"over_sponsor_cap"
|
|
676
|
+
];
|
|
677
|
+
//#endregion
|
|
678
|
+
//#region src/models/Route/entities/RouteStepRoleDto.ts
|
|
679
|
+
/**
|
|
680
|
+
* Every role a route step can have, as core names them. The client refuses a route answer with any other role, so a
|
|
681
|
+
* step it cannot name never reaches a signature.
|
|
682
|
+
*/
|
|
683
|
+
const ROUTE_STEP_ROLES = [
|
|
684
|
+
"approve",
|
|
685
|
+
"provider",
|
|
686
|
+
"transfer"
|
|
687
|
+
];
|
|
688
|
+
//#endregion
|
|
689
|
+
//#region src/payIn/constants.ts
|
|
690
|
+
/**
|
|
691
|
+
* The CAIP-2 namespace of EVM chains (`eip155:1`, `eip155:56`, Tempo's `eip155:4217`): its reference is the decimal
|
|
692
|
+
* chain id.
|
|
693
|
+
*/
|
|
694
|
+
const EVM_CAIP_NAMESPACE = "eip155";
|
|
695
|
+
/**
|
|
696
|
+
* The most decimals a token amount may have: an ERC-20 token's `decimals` is a `uint8`. An external holding naming
|
|
697
|
+
* more is unusable, and the base-unit helpers refuse more.
|
|
698
|
+
*/
|
|
699
|
+
const MAX_TOKEN_DECIMALS = 255;
|
|
700
|
+
/**
|
|
701
|
+
* Every kind of pay-in step (pay-in guide §6.1), told apart by the step's `scheme` and, for `eip712`, the payload's
|
|
702
|
+
* `primaryType`. The kit never builds one; it recognises them to choose the wallet call and the copy, and never signs a
|
|
703
|
+
* step whose kind it cannot name.
|
|
704
|
+
*
|
|
705
|
+
* - `K1` — an EIP-3009 transfer authorization (`ReceiveWithAuthorization`), mechanism
|
|
706
|
+
* `P`.
|
|
707
|
+
* - `K2` — a Permit2 transfer (`PermitBatchWitnessTransferFrom`, or `PermitWitnessTransferFrom`): mechanism `C`, and
|
|
708
|
+
* the second step of `B`, `G`, `N` and `R`; or a plain `PermitTransferFrom` with no witness: mechanism `V`.
|
|
709
|
+
* - `K3` — an EIP-2612 `Permit` (`owner, spender, value, nonce, deadline`) approving Permit2, the first step of `B`.
|
|
710
|
+
* - `K4` — a DAI-style `Permit` (`holder, spender, nonce, expiry, allowed`) approving Permit2, the first step of `B`.
|
|
711
|
+
* - `K5` — a Polygon `MetaTransaction` whose call approves Permit2, the first step of `B`.
|
|
712
|
+
* - `K6` — a Calibur `SignedBatchedCall`, mechanism `D`.
|
|
713
|
+
* - `K7` — a transaction the wallet sends itself (`evm_transaction`): `approve(Permit2, max)` for mechanisms `G`, `N`
|
|
714
|
+
* and `R`, or a coin send (`depositNative` to Relay's depository) for mechanism `W`.
|
|
715
|
+
* - `K8` — a sponsored Solana transaction, signed by the user and broadcast by Core.
|
|
716
|
+
*/
|
|
717
|
+
const PAY_IN_STEP_KINDS = [
|
|
718
|
+
"K1",
|
|
719
|
+
"K2",
|
|
720
|
+
"K3",
|
|
721
|
+
"K4",
|
|
722
|
+
"K5",
|
|
723
|
+
"K6",
|
|
724
|
+
"K7",
|
|
725
|
+
"K8"
|
|
726
|
+
];
|
|
727
|
+
//#endregion
|
|
728
|
+
//#region src/payIn/caip.ts
|
|
729
|
+
/**
|
|
730
|
+
* A CAIP-2 chain id: a namespace of 3 to 8 lowercase letters, digits or hyphens, `:`, then a reference of 1 to 32
|
|
731
|
+
* letters, digits, hyphens or underscores.
|
|
732
|
+
*/
|
|
733
|
+
const CAIP2_PATTERN = /^([-a-z0-9]{3,8}):([-_a-zA-Z0-9]{1,32})$/;
|
|
734
|
+
/**
|
|
735
|
+
* A CAIP-19 asset id: a CAIP-2 chain id, `/`, an asset namespace of 3 to 8 lowercase letters, digits or hyphens, `:`,
|
|
736
|
+
* then an asset reference of 1 to 128 letters, digits, hyphens, dots or `%`. No token id: pay-ins move fungible
|
|
737
|
+
* assets only.
|
|
738
|
+
*/
|
|
739
|
+
const CAIP19_PATTERN = /^(([-a-z0-9]{3,8}):([-_a-zA-Z0-9]{1,32}))\/([-a-z0-9]{3,8}):([-.%a-zA-Z0-9]{1,128})$/;
|
|
740
|
+
/**
|
|
741
|
+
* An `eip155` reference: a decimal chain id without a leading zero.
|
|
742
|
+
*/
|
|
743
|
+
const EVM_CHAIN_REFERENCE_PATTERN = /^[1-9][0-9]*$/;
|
|
744
|
+
/**
|
|
745
|
+
* Splits a CAIP-2 chain id into its namespace and reference, or `null` when `chain` is not one. Pure.
|
|
746
|
+
*
|
|
747
|
+
* @example parseCaip2("eip155:56") → { namespace: "eip155", reference: "56" }
|
|
748
|
+
* @example parseCaip2("solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp") → { namespace: "solana", reference: "5eykt4Us…KqZKvdp" }
|
|
749
|
+
*/
|
|
750
|
+
function parseCaip2(chain) {
|
|
751
|
+
if (typeof chain !== "string") return null;
|
|
752
|
+
const match = CAIP2_PATTERN.exec(chain);
|
|
753
|
+
if (match === null) return null;
|
|
754
|
+
return {
|
|
755
|
+
namespace: match[1],
|
|
756
|
+
reference: match[2]
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
/**
|
|
760
|
+
* Splits a CAIP-19 asset id into its chain and asset parts, or `null` when `asset` is not one. An asset id with a
|
|
761
|
+
* token id (`…/erc721:0x…/1`) is not a pay-in asset and reads as `null`. Pure.
|
|
762
|
+
*
|
|
763
|
+
* @example parseCaip19("eip155:1/slip44:60") → { chain: "eip155:1", namespace: "eip155", reference: "1",
|
|
764
|
+
* assetNamespace: "slip44", assetReference: "60" }
|
|
765
|
+
*/
|
|
766
|
+
function parseCaip19(asset) {
|
|
767
|
+
if (typeof asset !== "string") return null;
|
|
768
|
+
const match = CAIP19_PATTERN.exec(asset);
|
|
769
|
+
if (match === null) return null;
|
|
770
|
+
return {
|
|
771
|
+
chain: match[1],
|
|
772
|
+
namespace: match[2],
|
|
773
|
+
reference: match[3],
|
|
774
|
+
assetNamespace: match[4],
|
|
775
|
+
assetReference: match[5]
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* The hex chain id of an EVM CAIP-2 chain, lowercase and without leading zeros: what `wallet_switchEthereumChain` takes
|
|
780
|
+
* and what keys `wallet_getCapabilities`. `null` when `chain` is not an `eip155` chain with a decimal chain id. Pure.
|
|
781
|
+
*
|
|
782
|
+
* @example evmChainHex("eip155:56") === "0x38"
|
|
783
|
+
* @example evmChainHex("solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp") === null
|
|
784
|
+
*/
|
|
785
|
+
function evmChainHex(chain) {
|
|
786
|
+
const reference = evmChainReference(chain);
|
|
787
|
+
return reference === null ? null : `0x${BigInt(reference).toString(16)}`;
|
|
788
|
+
}
|
|
789
|
+
/**
|
|
790
|
+
* The numeric chain id of an EVM CAIP-2 chain, as viem and wagmi take it. `null` when `chain` is not an `eip155` chain
|
|
791
|
+
* with a decimal chain id, or when the id is too large to be a safe integer. Pure.
|
|
792
|
+
*
|
|
793
|
+
* @example evmChainNumber("eip155:4217") === 4217
|
|
794
|
+
*/
|
|
795
|
+
function evmChainNumber(chain) {
|
|
796
|
+
const reference = evmChainReference(chain);
|
|
797
|
+
if (reference === null) return null;
|
|
798
|
+
const chainId = Number(reference);
|
|
799
|
+
return Number.isSafeInteger(chainId) ? chainId : null;
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* The decimal chain id of an EVM CAIP-2 chain, or `null` when `chain` is not one.
|
|
803
|
+
*/
|
|
804
|
+
function evmChainReference(chain) {
|
|
805
|
+
const parts = parseCaip2(chain);
|
|
806
|
+
if (parts === null || parts.namespace !== "eip155" || !EVM_CHAIN_REFERENCE_PATTERN.test(parts.reference)) return null;
|
|
807
|
+
return parts.reference;
|
|
808
|
+
}
|
|
809
|
+
//#endregion
|
|
810
|
+
//#region src/shared/patterns.ts
|
|
811
|
+
/**
|
|
812
|
+
* EVM calldata: `0x` and whole bytes of hex, either case (`0x` alone for none), as core writes it with
|
|
813
|
+
* `hexutil.Encode`. A route step's `data` and a pay-in approval's `data` both match it. Internal: not exported from
|
|
814
|
+
* the package index.
|
|
815
|
+
*/
|
|
816
|
+
const CALLDATA_PATTERN = /^0x(?:[0-9a-fA-F]{2})*$/;
|
|
817
|
+
/**
|
|
818
|
+
* A decimal integer without leading zeros, as core writes a route step's native value in wei and every pay-in amount
|
|
819
|
+
* in base units (kept as a string: it may exceed 2^53). Internal: not exported from the package index.
|
|
820
|
+
*/
|
|
821
|
+
const DECIMAL_INTEGER_PATTERN = /^(?:0|[1-9][0-9]*)$/;
|
|
822
|
+
//#endregion
|
|
823
|
+
//#region src/client/guards.ts
|
|
824
|
+
/**
|
|
825
|
+
* Reports whether `value` is shaped like a {@link RouteQuoteDto}: a JSON object whose `estimated_output`,
|
|
826
|
+
* `minimum_output`, `expires_at` and `provider` are strings, whose `eta_seconds` is a safe integer, and whose `fees`
|
|
827
|
+
* is an object with a string `platform` and `provider`. Its `trade_type` and `source_amount` are each a string,
|
|
828
|
+
* `null` or absent.
|
|
829
|
+
*
|
|
830
|
+
* It checks shapes, not values: an amount is not checked to be digits, nor an instant to parse. Extra keys are
|
|
831
|
+
* allowed, at every level, as on every Coordinator answer (`isErrorEnvelopeDto` allows them too), so a field the
|
|
832
|
+
* Coordinator adds later never breaks the client.
|
|
833
|
+
*/
|
|
834
|
+
function isRouteQuoteDto(value) {
|
|
835
|
+
return isJsonObject(value) && typeof value.estimated_output === "string" && typeof value.minimum_output === "string" && isOptionalString(value.trade_type) && isOptionalString(value.source_amount) && isRouteFeesDto(value.fees) && Number.isSafeInteger(value.eta_seconds) && typeof value.expires_at === "string" && typeof value.provider === "string";
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* Reports whether `value` is shaped like a {@link RouteDto}: {@link isRouteQuoteDto}, plus a non-empty string
|
|
839
|
+
* `id`, a non-empty string `status`, a `steps` array whose every entry is a step the client can sign, an
|
|
840
|
+
* `actual_output`, `destination_tx`, `source_tx`, `error`, `submitted_at` and `source_confirmed_at` that are each a
|
|
841
|
+
* string, `null`, or absent, an `amount`, `created_at` and `updated_at` that are each a string or absent, and a
|
|
842
|
+
* `source` and `destination` that are each a {@link RouteEndDto} (a string `asset` and `address`) or absent.
|
|
843
|
+
*
|
|
844
|
+
* The echoed fields are optional, so an answer from a Coordinator that predates them still reads; a present one of
|
|
845
|
+
* the wrong shape fails the check. Whether an echo matches the request is the caller's to check.
|
|
846
|
+
*
|
|
847
|
+
* A step the client can sign has a `role` from `ROUTE_STEP_ROLES` and an `evm` call whose `chain_id` is
|
|
848
|
+
* {@link ROUTE_SOURCE_CHAIN_ID}, whose `to` matches `EVM_ADDRESS_PATTERN`, whose `data` is `0x` and whole bytes of
|
|
849
|
+
* hex, and whose `value` is a decimal integer. The steps are what the account signs, so their values are checked,
|
|
850
|
+
* not only their shapes: an unknown role, another chain or a malformed call fails the check, and a step the client
|
|
851
|
+
* cannot name never reaches a signature.
|
|
852
|
+
*
|
|
853
|
+
* A state outside `ROUTE_STATES` passes: core may add states, and a route whose funds are moving must still read.
|
|
854
|
+
* Tell a known state with {@link isRouteStateDto}, and treat any other as in flight, never as failed or done. Extra
|
|
855
|
+
* keys are allowed, as in {@link isRouteQuoteDto}, inside `evm` too; build a transaction from the four checked fields
|
|
856
|
+
* only.
|
|
857
|
+
*/
|
|
858
|
+
function isRouteDto(value) {
|
|
859
|
+
return isRouteWith(value, isRouteStepDto);
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Reports whether `value` is shaped like a {@link RouteListDto}: a JSON object whose `data` is an array of routes and
|
|
863
|
+
* whose `has_more` is a boolean. Each route is checked as in {@link isRouteDto}, except that a step's `chain_id` may
|
|
864
|
+
* name any chain: the list also holds the routes that carried a pay-in's legs, whose steps run on the connected
|
|
865
|
+
* wallet's chain, and a list is history, never something to sign. One malformed route fails the whole list; a route
|
|
866
|
+
* in a state this client does not know does not. Extra keys are allowed, as in {@link isRouteQuoteDto}.
|
|
867
|
+
*
|
|
868
|
+
* Sign only the steps of a route read again through `getRoute`, whose answer {@link isRouteDto} holds to Tempo.
|
|
869
|
+
*/
|
|
870
|
+
function isRouteListDto(value) {
|
|
871
|
+
return isJsonObject(value) && Array.isArray(value.data) && value.data.every((route) => isRouteWith(route, isListedRouteStepDto)) && typeof value.has_more === "boolean";
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* Reports whether `value` is a route whose every step passes `isStep`, with the fields {@link isRouteDto} names.
|
|
875
|
+
*/
|
|
876
|
+
function isRouteWith(value, isStep) {
|
|
877
|
+
return isJsonObject(value) && isRouteQuoteDto(value) && isNonEmptyString(value.id) && isNonEmptyString(value.status) && Array.isArray(value.steps) && value.steps.every(isStep) && isOptionalString(value.actual_output) && isOptionalString(value.destination_tx) && isOptionalString(value.source_tx) && isOptionalString(value.error) && isOptionalString(value.refund_amount) && isOptionalString(value.refund_tx) && isOptionalString(value.submitted_at) && isOptionalString(value.source_confirmed_at) && isAbsentOrString(value.amount) && isAbsentOrString(value.created_at) && isAbsentOrString(value.updated_at) && (value.source === void 0 || isRouteEndDto(value.source)) && (value.destination === void 0 || isRouteEndDto(value.destination));
|
|
878
|
+
}
|
|
879
|
+
/**
|
|
880
|
+
* Reports whether `value` is one of the route states this client knows, `ROUTE_STATES`. A route's `status` that is
|
|
881
|
+
* not one of them is a state core added later: the funds are in flight.
|
|
882
|
+
*/
|
|
883
|
+
function isRouteStateDto(value) {
|
|
884
|
+
return isMember(ROUTE_STATES, value);
|
|
885
|
+
}
|
|
886
|
+
/**
|
|
887
|
+
* Reports whether `value` is shaped like an {@link ExternalBalancesDto}: a JSON object whose `holdings` is an array of
|
|
888
|
+
* holdings, whose `id` is a string, `null` or absent, whose `as_of` is `null`, absent or an object of
|
|
889
|
+
* `{ block, at }` reads (a safe-integer `block` and a string `at`), and whose `missing` is `null`, absent or an array
|
|
890
|
+
* of strings.
|
|
891
|
+
*
|
|
892
|
+
* A holding has a string `chain`, `asset` and `symbol`, a `decimals` that is an integer from 0 to 255, an `amount` that
|
|
893
|
+
* is a decimal integer without leading zeros (kept as a string: it may exceed 2^53), a `usd` that is a string, `null`
|
|
894
|
+
* or absent, and a `mechanisms` array of strings. A mechanism this client does not know passes; the quote is
|
|
895
|
+
* authoritative. An optional field that is `null` reads as absent: refusing it would cost a read and protect nothing.
|
|
896
|
+
* Extra keys are allowed, at every level, as on every Coordinator answer.
|
|
897
|
+
*/
|
|
898
|
+
function isExternalBalancesDto(value) {
|
|
899
|
+
return isJsonObject(value) && isOptionalString(value.id) && isOptionalString(value.spendable_usd) && (isAbsent(value.unpriced) || isStringArray(value.unpriced)) && (isAbsent(value.unread) || isStringArray(value.unread)) && (isAbsent(value.as_of) || isJsonObject(value.as_of) && Object.values(value.as_of).every(isExternalBalanceReadDto)) && (isAbsent(value.missing) || isStringArray(value.missing)) && Array.isArray(value.holdings) && value.holdings.every(isExternalHoldingDto);
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* Reports whether `value` is shaped like a {@link PayInDto}, the answer of every pay-in call: a JSON object with a
|
|
903
|
+
* non-empty string `id` and `status`; a `phase`, `failure_reason`, `cancellation_reason`, `deadline` and `snapshot_id`
|
|
904
|
+
* that are each a string, `null` or absent; a `destination` with a string `asset` and `address`; a string `amount`,
|
|
905
|
+
* `delivered`, `shape` and `expires_at`; a `poll_after_ms` that is a non-negative safe integer, `null` or absent; and
|
|
906
|
+
* arrays of `legs`, `steps`, `required_steps` and `unspendable`, each entry well-formed, where every id in
|
|
907
|
+
* `required_steps` names an entry of `steps`.
|
|
908
|
+
*
|
|
909
|
+
* A leg has a safe-integer `n`, a non-empty string `status` and `mechanism`, a string `source_asset`, `input_amount`
|
|
910
|
+
* and `min_output`, and a `source_tx`, `actual_output`, `refund_tx`, `refund_amount`, `fail_reason` and `drip` that
|
|
911
|
+
* are each a string, `null` or absent. An unspendable holding has a string `asset`, `amount` and `reason`.
|
|
912
|
+
*
|
|
913
|
+
* It checks shapes, never values, and a step's base fields only: a non-empty string `id`, `scheme` and `status`,
|
|
914
|
+
* a safe-integer `leg`, a string `chain` and `expires_at`, and a `digest`, `reason` and `tx_hash` that are each a
|
|
915
|
+
* string, `null` or absent. A step's `payload` is not checked at all. `steps` is the pay-in's whole history and core
|
|
916
|
+
* may add schemes, so a step this client could never sign must not make a pay-in that is moving money unreadable.
|
|
917
|
+
* Check a step by value before a wallet sees it.
|
|
918
|
+
*
|
|
919
|
+
* Only the fields the guide marks required are required: an optional field that is `null` reads as absent, so a
|
|
920
|
+
* pay-in that is moving money never turns unreadable over one (the guide's own loop polls at `poll_after_ms ?? 2000`).
|
|
921
|
+
* A state, leg state, step status, scheme, mechanism, phase, shape or drip outside this client's lists passes: core
|
|
922
|
+
* may add them. Tell a known pay-in state with {@link isPayInStateDto}, and treat any other as in flight, never as
|
|
923
|
+
* failed or done. Extra keys are allowed, at every level, as on every Coordinator answer.
|
|
924
|
+
*/
|
|
925
|
+
function isPayInDto(value) {
|
|
926
|
+
return isJsonObject(value) && isNonEmptyString(value.id) && isNonEmptyString(value.status) && isOptionalString(value.phase) && isOptionalString(value.failure_reason) && isOptionalString(value.cancellation_reason) && isPayInDestinationDto(value.destination) && (isAbsent(value.payee) || isJsonObject(value.payee) && typeof value.payee.name === "string") && typeof value.amount === "string" && typeof value.delivered === "string" && typeof value.shape === "string" && typeof value.expires_at === "string" && isOptionalString(value.deadline) && isOptionalString(value.fee_usd) && Array.isArray(value.legs) && value.legs.every(isPayInLegDto) && Array.isArray(value.steps) && value.steps.every(isPayInStepDto) && isStringArray(value.required_steps) && namesListedSteps(value.required_steps, value.steps) && Array.isArray(value.unspendable) && value.unspendable.every(isPayInUnspendableDto) && isOptionalString(value.snapshot_id) && (isAbsent(value.poll_after_ms) || isSafeIntegerFrom(value.poll_after_ms, 0, Number.MAX_SAFE_INTEGER));
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Reports whether `value` is one of the pay-in states this client knows, `PAY_IN_STATES`. A pay-in's `status` that is
|
|
930
|
+
* not one of them is a state core added later: the funds may be moving.
|
|
931
|
+
*/
|
|
932
|
+
function isPayInStateDto(value) {
|
|
933
|
+
return isMember(PAY_IN_STATES, value);
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* Reports whether `value` is an {@link ExternalBalanceReadDto}: an object with a safe-integer `block` and a string
|
|
937
|
+
* `at`.
|
|
938
|
+
*/
|
|
939
|
+
function isExternalBalanceReadDto(value) {
|
|
940
|
+
return isJsonObject(value) && Number.isSafeInteger(value.block) && typeof value.at === "string";
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* Reports whether `value` is an {@link ExternalHoldingDto}, per {@link isExternalBalancesDto}.
|
|
944
|
+
*/
|
|
945
|
+
function isExternalHoldingDto(value) {
|
|
946
|
+
return isJsonObject(value) && typeof value.chain === "string" && typeof value.asset === "string" && typeof value.symbol === "string" && isSafeIntegerFrom(value.decimals, 0, 255) && typeof value.amount === "string" && DECIMAL_INTEGER_PATTERN.test(value.amount) && isOptionalString(value.usd) && (isAbsent(value.spendable) || typeof value.spendable === "boolean") && (isAbsent(value.payable_mechanisms) || isStringArray(value.payable_mechanisms)) && isOptionalString(value.reason) && isStringArray(value.mechanisms);
|
|
947
|
+
}
|
|
948
|
+
/**
|
|
949
|
+
* Reports whether `value` is a {@link PayInDestinationDto}: an object with a string `asset` and `address`.
|
|
950
|
+
*/
|
|
951
|
+
function isPayInDestinationDto(value) {
|
|
952
|
+
return isJsonObject(value) && typeof value.asset === "string" && typeof value.address === "string";
|
|
953
|
+
}
|
|
954
|
+
/**
|
|
955
|
+
* Reports whether `value` is a {@link PayInLegDto}, per {@link isPayInDto}.
|
|
956
|
+
*/
|
|
957
|
+
function isPayInLegDto(value) {
|
|
958
|
+
return isJsonObject(value) && Number.isSafeInteger(value.n) && isNonEmptyString(value.status) && isNonEmptyString(value.mechanism) && typeof value.source_asset === "string" && typeof value.input_amount === "string" && typeof value.min_output === "string" && isOptionalString(value.fee_usd) && isOptionalString(value.source_tx) && isOptionalString(value.destination_tx) && isOptionalString(value.actual_output) && isOptionalString(value.refund_tx) && isOptionalString(value.refund_amount) && isOptionalString(value.fail_reason) && isOptionalString(value.drip);
|
|
959
|
+
}
|
|
960
|
+
/**
|
|
961
|
+
* Reports whether `value` has a pay-in step's base fields, per {@link isPayInDto}. Its `payload` is not checked.
|
|
962
|
+
*/
|
|
963
|
+
function isPayInStepDto(value) {
|
|
964
|
+
return isJsonObject(value) && isNonEmptyString(value.id) && Number.isSafeInteger(value.leg) && isNonEmptyString(value.scheme) && typeof value.chain === "string" && isOptionalString(value.digest) && typeof value.expires_at === "string" && isNonEmptyString(value.status) && isOptionalString(value.reason) && isOptionalString(value.tx_hash);
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* Reports whether `value` is a {@link PayInUnspendableDto}: an object with a string `asset`, `amount` and `reason`.
|
|
968
|
+
*/
|
|
969
|
+
function isPayInUnspendableDto(value) {
|
|
970
|
+
return isJsonObject(value) && typeof value.asset === "string" && typeof value.amount === "string" && typeof value.reason === "string";
|
|
971
|
+
}
|
|
972
|
+
/**
|
|
973
|
+
* Reports whether every id in `requiredSteps` is the `id` of an entry of `steps`, so the step to do next can
|
|
974
|
+
* always be found.
|
|
975
|
+
*/
|
|
976
|
+
function namesListedSteps(requiredSteps, steps) {
|
|
977
|
+
const listed = new Set(steps.map((step) => step.id));
|
|
978
|
+
return requiredSteps.every((stepId) => listed.has(stepId));
|
|
979
|
+
}
|
|
980
|
+
/**
|
|
981
|
+
* Reports whether `value` is a {@link RouteFeesDto}: an object with a string `platform` and `provider`.
|
|
982
|
+
*/
|
|
983
|
+
function isRouteFeesDto(value) {
|
|
984
|
+
return isJsonObject(value) && typeof value.platform === "string" && typeof value.provider === "string";
|
|
985
|
+
}
|
|
986
|
+
/**
|
|
987
|
+
* Reports whether `value` is a {@link RouteEndDto}: an object with a string `asset` and `address`. Extra keys are
|
|
988
|
+
* allowed, as in {@link isRouteQuoteDto}.
|
|
989
|
+
*/
|
|
990
|
+
function isRouteEndDto(value) {
|
|
991
|
+
return isJsonObject(value) && typeof value.asset === "string" && typeof value.address === "string";
|
|
992
|
+
}
|
|
993
|
+
/**
|
|
994
|
+
* Reports whether `value` is a {@link RouteStepDto} the client can sign: a known `role` and a
|
|
995
|
+
* {@link RouteStepCallDto} `evm`.
|
|
996
|
+
*/
|
|
997
|
+
function isRouteStepDto(value) {
|
|
998
|
+
return isListedRouteStepDto(value) && value.evm.chain_id === "eip155:4217";
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* Reports whether `value` is a step of a listed route: a known `role` and an `evm` call shaped as in
|
|
1002
|
+
* {@link isRouteStepCallDto}, on any chain.
|
|
1003
|
+
*/
|
|
1004
|
+
function isListedRouteStepDto(value) {
|
|
1005
|
+
return isJsonObject(value) && isMember(ROUTE_STEP_ROLES, value.role) && isRouteStepCallDto(value.evm);
|
|
1006
|
+
}
|
|
1007
|
+
/**
|
|
1008
|
+
* Reports whether `value` is shaped like a {@link RouteStepCallDto}: an object whose `chain_id` is a CAIP-2 EVM chain
|
|
1009
|
+
* (`eip155:` and digits), whose `to` is an EVM address, whose `data` is `0x` and whole bytes of hex, and whose `value`
|
|
1010
|
+
* is a decimal integer. Whether the chain is Tempo is {@link isRouteStepDto}'s check.
|
|
1011
|
+
*/
|
|
1012
|
+
function isRouteStepCallDto(value) {
|
|
1013
|
+
return isJsonObject(value) && typeof value.chain_id === "string" && evmChainHex(value.chain_id) !== null && typeof value.to === "string" && EVM_ADDRESS_PATTERN.test(value.to) && typeof value.data === "string" && CALLDATA_PATTERN.test(value.data) && typeof value.value === "string" && DECIMAL_INTEGER_PATTERN.test(value.value);
|
|
1014
|
+
}
|
|
1015
|
+
/**
|
|
1016
|
+
* Reports whether `value` is a string other than `""`.
|
|
1017
|
+
*/
|
|
1018
|
+
function isNonEmptyString(value) {
|
|
1019
|
+
return typeof value === "string" && value !== "";
|
|
1020
|
+
}
|
|
1021
|
+
/**
|
|
1022
|
+
* Reports whether `value` is `null` or `undefined` (an absent key).
|
|
1023
|
+
*/
|
|
1024
|
+
function isAbsent(value) {
|
|
1025
|
+
return value === void 0 || value === null;
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Reports whether `value` is a string, `null`, or `undefined` (an absent key).
|
|
1029
|
+
*/
|
|
1030
|
+
function isOptionalString(value) {
|
|
1031
|
+
return isAbsent(value) || typeof value === "string";
|
|
1032
|
+
}
|
|
1033
|
+
/**
|
|
1034
|
+
* Reports whether `value` is a string or `undefined` (an absent key), never `null`.
|
|
1035
|
+
*/
|
|
1036
|
+
function isAbsentOrString(value) {
|
|
1037
|
+
return value === void 0 || typeof value === "string";
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* Reports whether `value` is a safe integer from `min` to `max`, both included.
|
|
1041
|
+
*/
|
|
1042
|
+
function isSafeIntegerFrom(value, min, max) {
|
|
1043
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= min && value <= max;
|
|
1044
|
+
}
|
|
1045
|
+
/**
|
|
1046
|
+
* Reports whether `value` is an array of strings.
|
|
1047
|
+
*/
|
|
1048
|
+
function isStringArray(value) {
|
|
1049
|
+
return Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
1050
|
+
}
|
|
1051
|
+
/**
|
|
1052
|
+
* Reports whether `value` is one of `members`.
|
|
1053
|
+
*/
|
|
1054
|
+
function isMember(members, value) {
|
|
1055
|
+
return members.some((member) => member === value);
|
|
1056
|
+
}
|
|
1057
|
+
/**
|
|
1058
|
+
* Checks the registry envelope and every entry, allowing absent or null logos.
|
|
1059
|
+
*/
|
|
1060
|
+
function isAssetListDto(value) {
|
|
1061
|
+
return isAssetListEnvelope(value) && value.data.every(isAssetDto);
|
|
1062
|
+
}
|
|
1063
|
+
/**
|
|
1064
|
+
* Reports whether `value` is a registry list envelope: `object` `list`, a boolean `has_more`, and an array `data`
|
|
1065
|
+
* whose entries are not checked yet.
|
|
1066
|
+
*/
|
|
1067
|
+
function isAssetListEnvelope(value) {
|
|
1068
|
+
return isJsonObject(value) && value.object === "list" && typeof value.has_more === "boolean" && Array.isArray(value.data);
|
|
1069
|
+
}
|
|
1070
|
+
/**
|
|
1071
|
+
* Keeps only the envelope's entries that {@link isAssetDto} accepts. Spec C12: one bad row is dropped, and the rest
|
|
1072
|
+
* stays. A row's network name or logo that is malformed is dropped alone ({@link withValidNetworkFacts}): display facts
|
|
1073
|
+
* never decide whether a coin is listed.
|
|
1074
|
+
*/
|
|
1075
|
+
function keepValidAssets(envelope) {
|
|
1076
|
+
return {
|
|
1077
|
+
object: "list",
|
|
1078
|
+
data: envelope.data.filter(isAssetDto).map(withValidNetworkFacts),
|
|
1079
|
+
has_more: envelope.has_more
|
|
1080
|
+
};
|
|
1081
|
+
}
|
|
1082
|
+
/**
|
|
1083
|
+
* `asset` without a `network_name` that is not a nonblank string or a `network_logo_url` that is not a string or null.
|
|
1084
|
+
* Returns `asset` itself when both are absent or valid.
|
|
1085
|
+
*/
|
|
1086
|
+
function withValidNetworkFacts(asset) {
|
|
1087
|
+
const nameValid = asset.network_name === void 0 || typeof asset.network_name === "string" && asset.network_name.trim() !== "";
|
|
1088
|
+
const logoValid = asset.network_logo_url === void 0 || isOptionalString(asset.network_logo_url);
|
|
1089
|
+
if (nameValid && logoValid) return asset;
|
|
1090
|
+
const { network_name, network_logo_url, ...rest } = asset;
|
|
1091
|
+
return {
|
|
1092
|
+
...rest,
|
|
1093
|
+
...nameValid && network_name !== void 0 ? { network_name } : {},
|
|
1094
|
+
...logoValid && network_logo_url !== void 0 ? { network_logo_url } : {}
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
/**
|
|
1098
|
+
* Reports whether `value` is one {@link AssetDto} registry entry, allowing an absent or null logo.
|
|
1099
|
+
*/
|
|
1100
|
+
function isAssetDto(value) {
|
|
1101
|
+
return isJsonObject(value) && value.object === "asset" && typeof value.asset === "string" && typeof value.network === "string" && typeof value.symbol === "string" && isSafeIntegerFrom(value.decimals, 0, 255) && isOptionalString(value.logo_url);
|
|
1102
|
+
}
|
|
1103
|
+
/** Accept only coherent EVM checkout resolutions, with a nonzero destination. */
|
|
1104
|
+
function isCheckoutResolutionDto(value) {
|
|
1105
|
+
if (!isJsonObject(value) || value.object !== "checkout_resolution" || typeof value.asset !== "string" || !/^eip155:[1-9][0-9]*\/(?:erc20:0x[0-9a-fA-F]{40}|slip44:[0-9]+)$/.test(value.asset) || typeof value.address !== "string" || !EVM_ADDRESS_PATTERN.test(value.address) || /^0x0{40}$/i.test(value.address) || !isNonEmptyString(value.symbol) || typeof value.default !== "boolean" || typeof value.registered !== "boolean" || !(value.decimals === void 0 || Number.isSafeInteger(value.decimals)) || !isOptionalString(value.usd_price)) return false;
|
|
1106
|
+
if (!value.registered) return value.rule_id === null && value.payee === null && !value.default;
|
|
1107
|
+
return typeof value.rule_id === "string" && /^ckr_.+/.test(value.rule_id) && isJsonObject(value.payee) && isNonEmptyString(value.payee.name);
|
|
1108
|
+
}
|
|
1109
|
+
//#endregion
|
|
1110
|
+
//#region src/client/serverTime.ts
|
|
1111
|
+
/**
|
|
1112
|
+
* The time a date header names, in ms since the epoch, or `null` when the header is absent or does not parse.
|
|
1113
|
+
*/
|
|
1114
|
+
function parseDateHeader(value) {
|
|
1115
|
+
if (value === null || value.trim() === "") return null;
|
|
1116
|
+
const ms = Date.parse(value);
|
|
1117
|
+
return Number.isFinite(ms) ? ms : null;
|
|
1118
|
+
}
|
|
1119
|
+
/**
|
|
1120
|
+
* The server's time a response carries: `X-Stridge-Upstream-Date` (the hub proxy's copy of the Coordinator's `Date`)
|
|
1121
|
+
* when it parses, else `Date`, else `null`.
|
|
1122
|
+
*/
|
|
1123
|
+
function readServerTimeMs(headers) {
|
|
1124
|
+
return parseDateHeader(headers.get("X-Stridge-Upstream-Date")) ?? parseDateHeader(headers.get("Date"));
|
|
1125
|
+
}
|
|
1126
|
+
/**
|
|
1127
|
+
* Hands `sink` the server time `headers` carry, with the device's send and receipt times. Does nothing without a sink
|
|
1128
|
+
* or without a parseable date, and swallows what the sink throws, so a sink never fails a call.
|
|
1129
|
+
*/
|
|
1130
|
+
function reportServerTime(sink, headers, sentAtMs, receivedAtMs) {
|
|
1131
|
+
if (sink === void 0) return;
|
|
1132
|
+
const serverTimeMs = readServerTimeMs(headers);
|
|
1133
|
+
if (serverTimeMs === null) return;
|
|
1134
|
+
try {
|
|
1135
|
+
sink({
|
|
1136
|
+
serverTimeMs,
|
|
1137
|
+
sentAtMs,
|
|
1138
|
+
receivedAtMs
|
|
1139
|
+
});
|
|
1140
|
+
} catch {
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
//#endregion
|
|
1145
|
+
//#region src/client/createCoordinatorClient.ts
|
|
1146
|
+
/**
|
|
1147
|
+
* The credentials of every session route.
|
|
1148
|
+
*/
|
|
1149
|
+
const SESSION = { kind: "session" };
|
|
1150
|
+
/**
|
|
1151
|
+
* The header names only the transport writes, from a route's {@link RouteCredentials}. A route header naming one is a
|
|
1152
|
+
* programming error.
|
|
1153
|
+
*/
|
|
1154
|
+
const CREDENTIAL_HEADERS = /* @__PURE__ */ new Set([
|
|
1155
|
+
CSRF_HEADER.toLowerCase(),
|
|
1156
|
+
GUEST_COOKIE_ACCESS_HEADER.toLowerCase(),
|
|
1157
|
+
SESSION_HEADER.toLowerCase()
|
|
1158
|
+
]);
|
|
1159
|
+
/**
|
|
1160
|
+
* A transaction hash as `POST /wallet/v1/routes/{id}/source` takes it: `0x` and 32 bytes of hex, either case.
|
|
1161
|
+
*/
|
|
1162
|
+
const TX_HASH_PATTERN = /^0x[0-9a-fA-F]{64}$/;
|
|
1163
|
+
/**
|
|
1164
|
+
* An idempotency key the client sends: visible ASCII only (`!` through `~`), so its length in characters is its
|
|
1165
|
+
* length in bytes, which is what the Coordinator bounds, and no header rule trims or refuses it.
|
|
1166
|
+
*/
|
|
1167
|
+
const IDEMPOTENCY_KEY_PATTERN = /^[\x21-\x7E]+$/;
|
|
1168
|
+
/**
|
|
1169
|
+
* Creates the Coordinator client: one method per hub API route the hub uses, with the shared request and answer rules
|
|
1170
|
+
* documented on {@link CoordinatorClient}.
|
|
1171
|
+
*
|
|
1172
|
+
* Validates the options once, up front:
|
|
1173
|
+
*
|
|
1174
|
+
* - `baseUrl` must parse with `new URL(baseUrl)` as an absolute `http:` or `https:` URL with no query and no fragment.
|
|
1175
|
+
* Trailing slashes are removed; any path prefix is kept.
|
|
1176
|
+
* - `appId` must be a non-empty string. Its format is not checked (the Coordinator answers `403 APP_SUSPENDED` for a
|
|
1177
|
+
* bad one).
|
|
1178
|
+
* - `csrf` must have `get` and `set` functions.
|
|
1179
|
+
* - `fetch` defaults to `globalThis.fetch`, read now. It is always called as a plain function, never as a method
|
|
1180
|
+
* of the options object.
|
|
1181
|
+
* - `onServerTime`, when given, must be a function. It too is called as a plain function.
|
|
1182
|
+
*
|
|
1183
|
+
* Creating the client sends nothing.
|
|
1184
|
+
*
|
|
1185
|
+
* @throws {TypeError} when an option breaks one of those rules, or no `fetch` is available.
|
|
1186
|
+
*/
|
|
1187
|
+
function createCoordinatorClient(options) {
|
|
1188
|
+
if (!isJsonObject(options)) throw new TypeError("createCoordinatorClient: options must be an object");
|
|
1189
|
+
const baseUrl = normaliseBaseUrl(options.baseUrl);
|
|
1190
|
+
const appId = options.appId;
|
|
1191
|
+
if (typeof appId !== "string" || appId === "") throw new TypeError("createCoordinatorClient: appId must be a non-empty string");
|
|
1192
|
+
const csrf = options.csrf;
|
|
1193
|
+
if (!isJsonObject(csrf) || typeof csrf.get !== "function" || typeof csrf.set !== "function") throw new TypeError("createCoordinatorClient: csrf must have get and set functions");
|
|
1194
|
+
const fetchFn = options.fetch ?? globalThis.fetch;
|
|
1195
|
+
if (typeof fetchFn !== "function") throw new TypeError("createCoordinatorClient: no fetch is available; pass options.fetch");
|
|
1196
|
+
const onServerTime = options.onServerTime;
|
|
1197
|
+
if (onServerTime !== void 0 && typeof onServerTime !== "function") throw new TypeError("createCoordinatorClient: onServerTime must be a function");
|
|
1198
|
+
const transport = createTransport(baseUrl, appId, csrf, fetchFn, onServerTime);
|
|
1199
|
+
return {
|
|
1200
|
+
baseUrl,
|
|
1201
|
+
appId,
|
|
1202
|
+
async startRound(input, callOptions) {
|
|
1203
|
+
const body = {};
|
|
1204
|
+
if (input.email !== void 0) {
|
|
1205
|
+
body.method = "email";
|
|
1206
|
+
body.email = input.email;
|
|
1207
|
+
}
|
|
1208
|
+
return await transport.send({
|
|
1209
|
+
...hubTarget("startRound"),
|
|
1210
|
+
body,
|
|
1211
|
+
sendsApp: true,
|
|
1212
|
+
credentials: SESSION,
|
|
1213
|
+
callOptions
|
|
1214
|
+
});
|
|
1215
|
+
},
|
|
1216
|
+
async getRound(roundId, callOptions) {
|
|
1217
|
+
return await transport.send({
|
|
1218
|
+
...hubTarget("getRound", encodeURIComponent(roundId)),
|
|
1219
|
+
credentials: SESSION,
|
|
1220
|
+
callOptions
|
|
1221
|
+
});
|
|
1222
|
+
},
|
|
1223
|
+
async verifyRound(roundId, request, callOptions) {
|
|
1224
|
+
const body = { encrypted_otp_bundle: request.encrypted_otp_bundle };
|
|
1225
|
+
const answer = await transport.send({
|
|
1226
|
+
...hubTarget("verifyRound", encodeURIComponent(roundId)),
|
|
1227
|
+
body,
|
|
1228
|
+
credentials: SESSION,
|
|
1229
|
+
callOptions
|
|
1230
|
+
});
|
|
1231
|
+
const token = answer.csrf_token;
|
|
1232
|
+
if (typeof token === "string" && token !== "") try {
|
|
1233
|
+
await csrf.set(token);
|
|
1234
|
+
} catch (cause) {
|
|
1235
|
+
throw new CsrfStoreError(answer, cause);
|
|
1236
|
+
}
|
|
1237
|
+
return answer;
|
|
1238
|
+
},
|
|
1239
|
+
async registerKeypair(request, callOptions) {
|
|
1240
|
+
const body = {
|
|
1241
|
+
round_id: request.round_id,
|
|
1242
|
+
stamped_body: request.stamped_body,
|
|
1243
|
+
attested_stamp: request.attested_stamp
|
|
1244
|
+
};
|
|
1245
|
+
return await transport.send({
|
|
1246
|
+
...hubTarget("registerKeypair"),
|
|
1247
|
+
body,
|
|
1248
|
+
sendsApp: true,
|
|
1249
|
+
credentials: SESSION,
|
|
1250
|
+
callOptions
|
|
1251
|
+
});
|
|
1252
|
+
},
|
|
1253
|
+
async getSession(callOptions) {
|
|
1254
|
+
return await transport.send({
|
|
1255
|
+
...hubTarget("getSession"),
|
|
1256
|
+
credentials: SESSION,
|
|
1257
|
+
callOptions
|
|
1258
|
+
});
|
|
1259
|
+
},
|
|
1260
|
+
async getWallet(callOptions) {
|
|
1261
|
+
return await transport.send({
|
|
1262
|
+
...hubTarget("getWallet"),
|
|
1263
|
+
sendsApp: true,
|
|
1264
|
+
credentials: SESSION,
|
|
1265
|
+
callOptions
|
|
1266
|
+
});
|
|
1267
|
+
},
|
|
1268
|
+
async relay(request, callOptions) {
|
|
1269
|
+
const pinned = callOptions !== void 0 && "sessionCsrfToken" in callOptions;
|
|
1270
|
+
const token = pinned ? callOptions.sessionCsrfToken : void 0;
|
|
1271
|
+
if (pinned && (typeof token !== "string" || token === "")) throw new TypeError("relay: sessionCsrfToken must be a non-empty string");
|
|
1272
|
+
const body = {
|
|
1273
|
+
body: request.body,
|
|
1274
|
+
stamp_header: {
|
|
1275
|
+
name: request.stamp_header.name,
|
|
1276
|
+
value: request.stamp_header.value
|
|
1277
|
+
},
|
|
1278
|
+
purpose: request.purpose
|
|
1279
|
+
};
|
|
1280
|
+
return await transport.send({
|
|
1281
|
+
...hubTarget("relay"),
|
|
1282
|
+
body,
|
|
1283
|
+
sendsApp: true,
|
|
1284
|
+
credentials: typeof token === "string" ? {
|
|
1285
|
+
kind: "pinned-session",
|
|
1286
|
+
token
|
|
1287
|
+
} : SESSION,
|
|
1288
|
+
callOptions: pinned ? toSignalOnly(callOptions) : callOptions
|
|
1289
|
+
});
|
|
1290
|
+
},
|
|
1291
|
+
async signOut(callOptions) {
|
|
1292
|
+
await transport.send({
|
|
1293
|
+
...hubTarget("signOut"),
|
|
1294
|
+
noContent: true,
|
|
1295
|
+
credentials: SESSION,
|
|
1296
|
+
callOptions
|
|
1297
|
+
});
|
|
1298
|
+
},
|
|
1299
|
+
async saveExternalAccount(request, callOptions) {
|
|
1300
|
+
const pinned = callOptions !== void 0 && "sessionCsrfToken" in callOptions;
|
|
1301
|
+
const token = pinned ? callOptions.sessionCsrfToken : void 0;
|
|
1302
|
+
if (pinned && (typeof token !== "string" || token === "")) throw new TypeError("saveExternalAccount: sessionCsrfToken must be a non-empty string");
|
|
1303
|
+
return await transport.send({
|
|
1304
|
+
...hubTarget("saveExternalAccount"),
|
|
1305
|
+
body: buildSaveExternalAccountBody(request),
|
|
1306
|
+
sendsApp: true,
|
|
1307
|
+
credentials: typeof token === "string" ? {
|
|
1308
|
+
kind: "pinned-session",
|
|
1309
|
+
token
|
|
1310
|
+
} : SESSION,
|
|
1311
|
+
callOptions: pinned ? toSignalOnly(callOptions) : callOptions
|
|
1312
|
+
});
|
|
1313
|
+
},
|
|
1314
|
+
async markExternalAccountUsed(walletId, request, callOptions) {
|
|
1315
|
+
const lastChainId = request?.last_chain_id;
|
|
1316
|
+
await transport.send({
|
|
1317
|
+
...hubTarget("markExternalAccountUsed", encodeURIComponent(walletId)),
|
|
1318
|
+
...lastChainId === void 0 ? {} : { body: { last_chain_id: lastChainId } },
|
|
1319
|
+
sendsApp: true,
|
|
1320
|
+
noContent: true,
|
|
1321
|
+
credentials: SESSION,
|
|
1322
|
+
callOptions
|
|
1323
|
+
});
|
|
1324
|
+
},
|
|
1325
|
+
async removeExternalAccount(walletId, callOptions) {
|
|
1326
|
+
await transport.send({
|
|
1327
|
+
...hubTarget("removeExternalAccount", encodeURIComponent(walletId)),
|
|
1328
|
+
sendsApp: true,
|
|
1329
|
+
noContent: true,
|
|
1330
|
+
credentials: SESSION,
|
|
1331
|
+
callOptions
|
|
1332
|
+
});
|
|
1333
|
+
},
|
|
1334
|
+
async quoteRoute(request, callOptions) {
|
|
1335
|
+
return await transport.send({
|
|
1336
|
+
...hubTarget("quoteRoute"),
|
|
1337
|
+
body: buildRouteRequestBody(request),
|
|
1338
|
+
sendsApp: true,
|
|
1339
|
+
isAnswer: isRouteQuoteDto,
|
|
1340
|
+
credentials: SESSION,
|
|
1341
|
+
callOptions
|
|
1342
|
+
});
|
|
1343
|
+
},
|
|
1344
|
+
async openRoute(request, callOptions) {
|
|
1345
|
+
const idempotencyKey = checkIdempotencyKey("openRoute", callOptions?.idempotencyKey);
|
|
1346
|
+
return await transport.send({
|
|
1347
|
+
...hubTarget("openRoute"),
|
|
1348
|
+
body: buildRouteOpenBody(request),
|
|
1349
|
+
sendsApp: true,
|
|
1350
|
+
headers: { [IDEMPOTENCY_HEADER]: idempotencyKey },
|
|
1351
|
+
isAnswer: isRouteDto,
|
|
1352
|
+
credentials: SESSION,
|
|
1353
|
+
callOptions
|
|
1354
|
+
});
|
|
1355
|
+
},
|
|
1356
|
+
async getRoute(routeId, callOptions) {
|
|
1357
|
+
return await transport.send({
|
|
1358
|
+
...hubTarget("getRoute", encodePathId("getRoute", "routeId", routeId)),
|
|
1359
|
+
sendsApp: true,
|
|
1360
|
+
isAnswer: isRouteDto,
|
|
1361
|
+
credentials: SESSION,
|
|
1362
|
+
callOptions
|
|
1363
|
+
});
|
|
1364
|
+
},
|
|
1365
|
+
async listAssets(callOptions) {
|
|
1366
|
+
return keepValidAssets(await transport.send({
|
|
1367
|
+
...hubTarget("listAssets"),
|
|
1368
|
+
sendsApp: true,
|
|
1369
|
+
isAnswer: isAssetListEnvelope,
|
|
1370
|
+
credentials: SESSION,
|
|
1371
|
+
callOptions
|
|
1372
|
+
}));
|
|
1373
|
+
},
|
|
1374
|
+
async listGuestAssets(callOptions) {
|
|
1375
|
+
return keepValidAssets(await transport.send({
|
|
1376
|
+
...hubTarget("listGuestAssets"),
|
|
1377
|
+
sendsApp: true,
|
|
1378
|
+
isAnswer: isAssetListEnvelope,
|
|
1379
|
+
credentials: checkGuestReadCredentials("listGuestAssets", callOptions),
|
|
1380
|
+
callOptions
|
|
1381
|
+
}));
|
|
1382
|
+
},
|
|
1383
|
+
async listRoutes(query, callOptions) {
|
|
1384
|
+
return await transport.send({
|
|
1385
|
+
...hubTarget("listRoutes", void 0, buildRouteListQuery(query)),
|
|
1386
|
+
sendsApp: true,
|
|
1387
|
+
isAnswer: isRouteListDto,
|
|
1388
|
+
credentials: SESSION,
|
|
1389
|
+
callOptions
|
|
1390
|
+
});
|
|
1391
|
+
},
|
|
1392
|
+
async reportRouteSource(routeId, request, callOptions) {
|
|
1393
|
+
const tx = request.tx;
|
|
1394
|
+
if (typeof tx !== "string" || !TX_HASH_PATTERN.test(tx)) throw new TypeError("reportRouteSource: tx must be 0x followed by 64 hex digits");
|
|
1395
|
+
const body = { tx };
|
|
1396
|
+
return await transport.send({
|
|
1397
|
+
...hubTarget("reportRouteSource", encodePathId("reportRouteSource", "routeId", routeId)),
|
|
1398
|
+
body,
|
|
1399
|
+
sendsApp: true,
|
|
1400
|
+
isAnswer: isRouteDto,
|
|
1401
|
+
credentials: SESSION,
|
|
1402
|
+
callOptions
|
|
1403
|
+
});
|
|
1404
|
+
},
|
|
1405
|
+
async openGuest(request, callOptions) {
|
|
1406
|
+
const body = { cookie_access: request.cookie_access };
|
|
1407
|
+
return await transport.send({
|
|
1408
|
+
...hubTarget("openGuest"),
|
|
1409
|
+
body,
|
|
1410
|
+
sendsApp: true,
|
|
1411
|
+
credentials: { kind: "guest-open" },
|
|
1412
|
+
callOptions: toSignalOnly(callOptions)
|
|
1413
|
+
});
|
|
1414
|
+
},
|
|
1415
|
+
async createGuestHandoff(options) {
|
|
1416
|
+
return await transport.send({
|
|
1417
|
+
...hubTarget("createGuestHandoff"),
|
|
1418
|
+
credentials: checkGuestCredentials("createGuestHandoff", options),
|
|
1419
|
+
sendsApp: true,
|
|
1420
|
+
callOptions: toSignalOnly(options)
|
|
1421
|
+
});
|
|
1422
|
+
},
|
|
1423
|
+
async mergeGuestSession(request, options) {
|
|
1424
|
+
await transport.send({
|
|
1425
|
+
...hubTarget("mergeGuestSession"),
|
|
1426
|
+
body: { handoff: request.handoff },
|
|
1427
|
+
credentials: checkGuestCredentials("mergeGuestSession", options),
|
|
1428
|
+
noContent: true,
|
|
1429
|
+
sendsApp: true,
|
|
1430
|
+
callOptions: toSignalOnly(options)
|
|
1431
|
+
});
|
|
1432
|
+
},
|
|
1433
|
+
async saveGuestWallet(request, callOptions) {
|
|
1434
|
+
const credentials = checkGuestCredentials("saveGuestWallet", callOptions);
|
|
1435
|
+
return await transport.send({
|
|
1436
|
+
...hubTarget("saveGuestWallet"),
|
|
1437
|
+
body: buildSaveExternalAccountBody(request),
|
|
1438
|
+
sendsApp: true,
|
|
1439
|
+
credentials,
|
|
1440
|
+
callOptions: toSignalOnly(callOptions)
|
|
1441
|
+
});
|
|
1442
|
+
},
|
|
1443
|
+
async removeGuestWallet(walletId, callOptions) {
|
|
1444
|
+
const credentials = checkGuestCredentials("removeGuestWallet", callOptions);
|
|
1445
|
+
await transport.send({
|
|
1446
|
+
...hubTarget("removeGuestWallet", encodeURIComponent(walletId)),
|
|
1447
|
+
sendsApp: true,
|
|
1448
|
+
noContent: true,
|
|
1449
|
+
credentials,
|
|
1450
|
+
callOptions: toSignalOnly(callOptions)
|
|
1451
|
+
});
|
|
1452
|
+
},
|
|
1453
|
+
async markGuestWalletUsed(walletId, request, callOptions) {
|
|
1454
|
+
const credentials = checkGuestCredentials("markGuestWalletUsed", callOptions);
|
|
1455
|
+
const lastChainId = request?.last_chain_id;
|
|
1456
|
+
return await transport.send({
|
|
1457
|
+
...hubTarget("markGuestWalletUsed", encodeURIComponent(walletId)),
|
|
1458
|
+
...lastChainId === void 0 ? {} : { body: { last_chain_id: lastChainId } },
|
|
1459
|
+
sendsApp: true,
|
|
1460
|
+
credentials,
|
|
1461
|
+
callOptions: toSignalOnly(callOptions)
|
|
1462
|
+
});
|
|
1463
|
+
},
|
|
1464
|
+
async answerWalletOffer(request, callOptions) {
|
|
1465
|
+
const token = callOptions?.sessionCsrfToken;
|
|
1466
|
+
if (typeof token !== "string" || token === "") throw new TypeError("answerWalletOffer: sessionCsrfToken must be a non-empty string");
|
|
1467
|
+
const accept = readWalletIds("accept_guest_accounts", request?.accept_guest_accounts ?? null) ?? [];
|
|
1468
|
+
const discard = readWalletIds("discard_guest_accounts", request?.discard_guest_accounts);
|
|
1469
|
+
const shown = readWalletIds("shown", request?.shown);
|
|
1470
|
+
const body = { accept_guest_accounts: accept };
|
|
1471
|
+
if (discard !== void 0) body.discard_guest_accounts = discard;
|
|
1472
|
+
if (shown !== void 0) body.shown = shown;
|
|
1473
|
+
return await transport.send({
|
|
1474
|
+
...hubTarget("answerWalletOffer"),
|
|
1475
|
+
body,
|
|
1476
|
+
sendsApp: true,
|
|
1477
|
+
credentials: {
|
|
1478
|
+
kind: "pinned-session",
|
|
1479
|
+
token
|
|
1480
|
+
},
|
|
1481
|
+
callOptions: toSignalOnly(callOptions)
|
|
1482
|
+
});
|
|
1483
|
+
},
|
|
1484
|
+
async resolveGuestCheckout(request, callOptions) {
|
|
1485
|
+
const body = {};
|
|
1486
|
+
if (request.asset !== void 0) body.asset = request.asset;
|
|
1487
|
+
if (request.destination !== void 0) body.destination = request.destination;
|
|
1488
|
+
return await transport.send({
|
|
1489
|
+
...hubTarget("resolveGuestCheckout"),
|
|
1490
|
+
body,
|
|
1491
|
+
sendsApp: true,
|
|
1492
|
+
credentials: checkGuestCredentials("resolveGuestCheckout", callOptions),
|
|
1493
|
+
isAnswer: isCheckoutResolutionDto,
|
|
1494
|
+
callOptions: toSignalOnly(callOptions)
|
|
1495
|
+
});
|
|
1496
|
+
},
|
|
1497
|
+
async resolveCheckout(request, callOptions) {
|
|
1498
|
+
const body = {};
|
|
1499
|
+
if (request.asset !== void 0) body.asset = request.asset;
|
|
1500
|
+
if (request.destination !== void 0) body.destination = request.destination;
|
|
1501
|
+
return await transport.send({
|
|
1502
|
+
...hubTarget("resolveCheckout"),
|
|
1503
|
+
body,
|
|
1504
|
+
sendsApp: true,
|
|
1505
|
+
credentials: SESSION,
|
|
1506
|
+
isAnswer: isCheckoutResolutionDto,
|
|
1507
|
+
callOptions
|
|
1508
|
+
});
|
|
1509
|
+
},
|
|
1510
|
+
async warmGuestExternalBalances(request, callOptions) {
|
|
1511
|
+
await transport.send({
|
|
1512
|
+
credentials: checkGuestCredentials("warmGuestExternalBalances", callOptions),
|
|
1513
|
+
...hubTarget("warmGuestExternalBalances"),
|
|
1514
|
+
body: buildExternalBalancesBody(request),
|
|
1515
|
+
sendsApp: true,
|
|
1516
|
+
noContent: true,
|
|
1517
|
+
callOptions: toSignalOnly(callOptions)
|
|
1518
|
+
});
|
|
1519
|
+
},
|
|
1520
|
+
async warmExternalBalances(request, callOptions) {
|
|
1521
|
+
await transport.send({
|
|
1522
|
+
credentials: SESSION,
|
|
1523
|
+
...hubTarget("warmExternalBalances"),
|
|
1524
|
+
body: buildExternalBalancesBody(request),
|
|
1525
|
+
sendsApp: true,
|
|
1526
|
+
noContent: true,
|
|
1527
|
+
callOptions
|
|
1528
|
+
});
|
|
1529
|
+
},
|
|
1530
|
+
async getGuestExternalBalances(request, callOptions) {
|
|
1531
|
+
return await transport.send({
|
|
1532
|
+
credentials: checkGuestReadCredentials("getGuestExternalBalances", callOptions),
|
|
1533
|
+
...hubTarget("getGuestExternalBalances", void 0, buildExternalBalancesQuery(request)),
|
|
1534
|
+
sendsApp: true,
|
|
1535
|
+
isAnswer: isExternalBalancesDto,
|
|
1536
|
+
callOptions: toSignalOnly(callOptions)
|
|
1537
|
+
});
|
|
1538
|
+
},
|
|
1539
|
+
async getExternalBalances(request, callOptions) {
|
|
1540
|
+
return await transport.send({
|
|
1541
|
+
credentials: SESSION,
|
|
1542
|
+
...hubTarget("getExternalBalances", void 0, buildExternalBalancesQuery(request)),
|
|
1543
|
+
sendsApp: true,
|
|
1544
|
+
isAnswer: isExternalBalancesDto,
|
|
1545
|
+
callOptions
|
|
1546
|
+
});
|
|
1547
|
+
},
|
|
1548
|
+
async quoteGuestPayIn(request, callOptions) {
|
|
1549
|
+
return await transport.send({
|
|
1550
|
+
credentials: checkGuestCredentials("quoteGuestPayIn", callOptions),
|
|
1551
|
+
...hubTarget("quoteGuestPayIn"),
|
|
1552
|
+
body: buildCheckoutQuoteBody(request),
|
|
1553
|
+
sendsApp: true,
|
|
1554
|
+
isAnswer: isPayInDto,
|
|
1555
|
+
callOptions: toSignalOnly(callOptions)
|
|
1556
|
+
});
|
|
1557
|
+
},
|
|
1558
|
+
async quoteCheckout(request, callOptions) {
|
|
1559
|
+
return await transport.send({
|
|
1560
|
+
credentials: SESSION,
|
|
1561
|
+
...hubTarget("quoteCheckout"),
|
|
1562
|
+
body: buildCheckoutQuoteBody(request),
|
|
1563
|
+
sendsApp: true,
|
|
1564
|
+
isAnswer: isPayInDto,
|
|
1565
|
+
callOptions
|
|
1566
|
+
});
|
|
1567
|
+
},
|
|
1568
|
+
async quoteTopUp(request, callOptions) {
|
|
1569
|
+
return await transport.send({
|
|
1570
|
+
credentials: SESSION,
|
|
1571
|
+
...hubTarget("quoteTopUp"),
|
|
1572
|
+
body: buildTopUpQuoteBody(request),
|
|
1573
|
+
sendsApp: true,
|
|
1574
|
+
isAnswer: isPayInDto,
|
|
1575
|
+
callOptions
|
|
1576
|
+
});
|
|
1577
|
+
},
|
|
1578
|
+
async confirmGuestPayIn(payInId, request, callOptions) {
|
|
1579
|
+
const idempotencyKey = checkIdempotencyKey("confirmGuestPayIn", callOptions?.idempotencyKey);
|
|
1580
|
+
const body = { signatures: buildSignatureBatch("confirmGuestPayIn", request, {
|
|
1581
|
+
allowTxHash: false,
|
|
1582
|
+
allowEmpty: true
|
|
1583
|
+
}) };
|
|
1584
|
+
return await transport.send({
|
|
1585
|
+
credentials: checkGuestCredentials("confirmGuestPayIn", callOptions),
|
|
1586
|
+
...hubTarget("confirmGuestPayIn", encodePathId("confirmGuestPayIn", "payInId", payInId)),
|
|
1587
|
+
body,
|
|
1588
|
+
sendsApp: true,
|
|
1589
|
+
headers: { [IDEMPOTENCY_HEADER]: idempotencyKey },
|
|
1590
|
+
isAnswer: isPayInDto,
|
|
1591
|
+
callOptions: toSignalOnly(callOptions)
|
|
1592
|
+
});
|
|
1593
|
+
},
|
|
1594
|
+
async confirmPayIn(payInId, request, callOptions) {
|
|
1595
|
+
const idempotencyKey = checkIdempotencyKey("confirmPayIn", callOptions?.idempotencyKey);
|
|
1596
|
+
const body = { signatures: buildSignatureBatch("confirmPayIn", request, {
|
|
1597
|
+
allowTxHash: false,
|
|
1598
|
+
allowEmpty: true
|
|
1599
|
+
}) };
|
|
1600
|
+
return await transport.send({
|
|
1601
|
+
credentials: SESSION,
|
|
1602
|
+
...hubTarget("confirmPayIn", encodePathId("confirmPayIn", "payInId", payInId)),
|
|
1603
|
+
body,
|
|
1604
|
+
sendsApp: true,
|
|
1605
|
+
headers: { [IDEMPOTENCY_HEADER]: idempotencyKey },
|
|
1606
|
+
isAnswer: isPayInDto,
|
|
1607
|
+
callOptions
|
|
1608
|
+
});
|
|
1609
|
+
},
|
|
1610
|
+
async adjustGuestPayIn(payInId, request, callOptions) {
|
|
1611
|
+
const body = { signatures: buildSignatureBatch("adjustGuestPayIn", request, {
|
|
1612
|
+
allowTxHash: true,
|
|
1613
|
+
allowEmpty: false
|
|
1614
|
+
}) };
|
|
1615
|
+
return await transport.send({
|
|
1616
|
+
credentials: checkGuestCredentials("adjustGuestPayIn", callOptions),
|
|
1617
|
+
...hubTarget("adjustGuestPayIn", encodePathId("adjustGuestPayIn", "payInId", payInId)),
|
|
1618
|
+
body,
|
|
1619
|
+
sendsApp: true,
|
|
1620
|
+
isAnswer: isPayInDto,
|
|
1621
|
+
callOptions: toSignalOnly(callOptions)
|
|
1622
|
+
});
|
|
1623
|
+
},
|
|
1624
|
+
async adjustPayIn(payInId, request, callOptions) {
|
|
1625
|
+
const body = { signatures: buildSignatureBatch("adjustPayIn", request, {
|
|
1626
|
+
allowTxHash: true,
|
|
1627
|
+
allowEmpty: false
|
|
1628
|
+
}) };
|
|
1629
|
+
return await transport.send({
|
|
1630
|
+
credentials: SESSION,
|
|
1631
|
+
...hubTarget("adjustPayIn", encodePathId("adjustPayIn", "payInId", payInId)),
|
|
1632
|
+
body,
|
|
1633
|
+
sendsApp: true,
|
|
1634
|
+
isAnswer: isPayInDto,
|
|
1635
|
+
callOptions
|
|
1636
|
+
});
|
|
1637
|
+
},
|
|
1638
|
+
async cancelGuestPayIn(payInId, callOptions) {
|
|
1639
|
+
return await transport.send({
|
|
1640
|
+
credentials: checkGuestCredentials("cancelGuestPayIn", callOptions),
|
|
1641
|
+
...hubTarget("cancelGuestPayIn", encodePathId("cancelGuestPayIn", "payInId", payInId)),
|
|
1642
|
+
sendsApp: true,
|
|
1643
|
+
isAnswer: isPayInDto,
|
|
1644
|
+
callOptions: toSignalOnly(callOptions)
|
|
1645
|
+
});
|
|
1646
|
+
},
|
|
1647
|
+
async cancelPayIn(payInId, callOptions) {
|
|
1648
|
+
return await transport.send({
|
|
1649
|
+
credentials: SESSION,
|
|
1650
|
+
...hubTarget("cancelPayIn", encodePathId("cancelPayIn", "payInId", payInId)),
|
|
1651
|
+
sendsApp: true,
|
|
1652
|
+
isAnswer: isPayInDto,
|
|
1653
|
+
callOptions
|
|
1654
|
+
});
|
|
1655
|
+
},
|
|
1656
|
+
async getGuestPayIn(payInId, callOptions) {
|
|
1657
|
+
return await transport.send({
|
|
1658
|
+
credentials: checkGuestReadCredentials("getGuestPayIn", callOptions),
|
|
1659
|
+
...hubTarget("getGuestPayIn", encodePathId("getGuestPayIn", "payInId", payInId)),
|
|
1660
|
+
sendsApp: true,
|
|
1661
|
+
isAnswer: isPayInDto,
|
|
1662
|
+
callOptions: toSignalOnly(callOptions)
|
|
1663
|
+
});
|
|
1664
|
+
},
|
|
1665
|
+
async getPayIn(payInId, callOptions) {
|
|
1666
|
+
return await transport.send({
|
|
1667
|
+
credentials: SESSION,
|
|
1668
|
+
...hubTarget("getPayIn", encodePathId("getPayIn", "payInId", payInId)),
|
|
1669
|
+
sendsApp: true,
|
|
1670
|
+
isAnswer: isPayInDto,
|
|
1671
|
+
callOptions
|
|
1672
|
+
});
|
|
1673
|
+
}
|
|
1674
|
+
};
|
|
1675
|
+
}
|
|
1676
|
+
/**
|
|
1677
|
+
* Keeps only the caller's abort signal from per-call options: the guest and pinned routes take no other option.
|
|
1678
|
+
*/
|
|
1679
|
+
function toSignalOnly(options) {
|
|
1680
|
+
return options?.signal === void 0 ? void 0 : { signal: options.signal };
|
|
1681
|
+
}
|
|
1682
|
+
/**
|
|
1683
|
+
* Checks a guest write's credentials and returns them.
|
|
1684
|
+
*
|
|
1685
|
+
* @throws {TypeError} when `guestCsrfToken` is not a non-empty string or `cookieAccess` is not a guest cookie scope.
|
|
1686
|
+
*/
|
|
1687
|
+
function checkGuestCredentials(method, options) {
|
|
1688
|
+
const token = options?.guestCsrfToken;
|
|
1689
|
+
if (typeof token !== "string" || token === "") throw new TypeError(`${method}: guestCsrfToken must be a non-empty string`);
|
|
1690
|
+
const cookieAccess = options?.cookieAccess;
|
|
1691
|
+
if (cookieAccess !== "unpartitioned" && cookieAccess !== "partitioned") throw new TypeError(`${method}: cookieAccess must be "unpartitioned" or "partitioned"`);
|
|
1692
|
+
return {
|
|
1693
|
+
kind: "guest",
|
|
1694
|
+
token,
|
|
1695
|
+
cookieAccess
|
|
1696
|
+
};
|
|
1697
|
+
}
|
|
1698
|
+
/** Validates the cookie scope of a guest read without requiring or reading any token. */
|
|
1699
|
+
function checkGuestReadCredentials(method, options) {
|
|
1700
|
+
const cookieAccess = options?.cookieAccess;
|
|
1701
|
+
if (cookieAccess !== "unpartitioned" && cookieAccess !== "partitioned") throw new TypeError(`${method}: cookieAccess must be "unpartitioned" or "partitioned"`);
|
|
1702
|
+
return {
|
|
1703
|
+
kind: "guest-read",
|
|
1704
|
+
cookieAccess
|
|
1705
|
+
};
|
|
1706
|
+
}
|
|
1707
|
+
/**
|
|
1708
|
+
* Builds the body of `saveExternalAccount` and `saveGuestWallet` key by key: `chain_kind`, `address`, `wallet_brand`,
|
|
1709
|
+
* `connector`, `saved_via`, and the optional fields `display_name`, `last_chain_id` and `reconnect` when defined.
|
|
1710
|
+
*/
|
|
1711
|
+
function buildSaveExternalAccountBody(request) {
|
|
1712
|
+
return {
|
|
1713
|
+
chain_kind: request.chain_kind,
|
|
1714
|
+
address: request.address,
|
|
1715
|
+
wallet_brand: request.wallet_brand,
|
|
1716
|
+
connector: request.connector,
|
|
1717
|
+
...request.display_name === void 0 ? {} : { display_name: request.display_name },
|
|
1718
|
+
...request.last_chain_id === void 0 ? {} : { last_chain_id: request.last_chain_id },
|
|
1719
|
+
saved_via: request.saved_via,
|
|
1720
|
+
...request.reconnect === void 0 ? {} : { reconnect: request.reconnect }
|
|
1721
|
+
};
|
|
1722
|
+
}
|
|
1723
|
+
/**
|
|
1724
|
+
* A copy of one wallet-id list of the offer answer, or `undefined` when the caller left it out. Anything else that is
|
|
1725
|
+
* not an array of strings (`null` included) throws before sending.
|
|
1726
|
+
*/
|
|
1727
|
+
function readWalletIds(field, value) {
|
|
1728
|
+
if (value === void 0) return void 0;
|
|
1729
|
+
if (!Array.isArray(value) || !value.every((id) => typeof id === "string")) throw new TypeError(`answerWalletOffer: ${field} must be an array of wallet ids`);
|
|
1730
|
+
return [...value];
|
|
1731
|
+
}
|
|
1732
|
+
/**
|
|
1733
|
+
* Builds the body of `quoteRoute` key by key: `source.asset`, `source.amount`, `destination.asset`, then
|
|
1734
|
+
* `destination.address` only when it is defined. A quote never carries `purpose` or `payment_ref`.
|
|
1735
|
+
*/
|
|
1736
|
+
function buildRouteRequestBody(request) {
|
|
1737
|
+
const destination = request.destination;
|
|
1738
|
+
return {
|
|
1739
|
+
source: {
|
|
1740
|
+
asset: request.source.asset,
|
|
1741
|
+
amount: request.source.amount
|
|
1742
|
+
},
|
|
1743
|
+
destination: destination.address === void 0 ? { asset: destination.asset } : {
|
|
1744
|
+
asset: destination.asset,
|
|
1745
|
+
address: destination.address
|
|
1746
|
+
}
|
|
1747
|
+
};
|
|
1748
|
+
}
|
|
1749
|
+
/**
|
|
1750
|
+
* Builds the body of `openRoute`: the quote body ({@link buildRouteRequestBody}), then `purpose` and `payment_ref`, each
|
|
1751
|
+
* only when it is defined. The key order is fixed: the Coordinator compares the body's bytes under one idempotency key.
|
|
1752
|
+
*/
|
|
1753
|
+
function buildRouteOpenBody(request) {
|
|
1754
|
+
return {
|
|
1755
|
+
...buildRouteRequestBody(request),
|
|
1756
|
+
...request.purpose === void 0 ? {} : { purpose: request.purpose },
|
|
1757
|
+
...request.payment_ref === void 0 ? {} : { payment_ref: request.payment_ref }
|
|
1758
|
+
};
|
|
1759
|
+
}
|
|
1760
|
+
/**
|
|
1761
|
+
* Builds the body of `warmExternalBalances` and `warmGuestExternalBalances`: exactly `wallets`.
|
|
1762
|
+
*/
|
|
1763
|
+
function buildExternalBalancesBody(request) {
|
|
1764
|
+
return { wallets: buildPayInWallets(request.wallets) };
|
|
1765
|
+
}
|
|
1766
|
+
/**
|
|
1767
|
+
* Builds the query of `getExternalBalances` and `getGuestExternalBalances` from the request's `wallets`: `evm` and
|
|
1768
|
+
* `svm`, then JSON `wallet` and its optional checkout target. Each value is URI-encoded.
|
|
1769
|
+
*/
|
|
1770
|
+
function buildExternalBalancesQuery(request) {
|
|
1771
|
+
const wallets = buildPayInWallets(request.wallets);
|
|
1772
|
+
const parts = [];
|
|
1773
|
+
if (wallets.evm !== void 0) parts.push(`evm=${encodeURIComponent(wallets.evm)}`);
|
|
1774
|
+
if (wallets.svm !== void 0) parts.push(`svm=${encodeURIComponent(wallets.svm)}`);
|
|
1775
|
+
if (request.wallet !== void 0) {
|
|
1776
|
+
parts.push(`wallet=${encodeURIComponent(JSON.stringify(buildWalletDescriptor(request.wallet)))}`);
|
|
1777
|
+
if (request.asset !== void 0 && request.destination !== void 0) parts.push(`asset=${encodeURIComponent(request.asset)}`, `destination=${encodeURIComponent(request.destination)}`);
|
|
1778
|
+
}
|
|
1779
|
+
return parts.length === 0 ? "" : `?${parts.join("&")}`;
|
|
1780
|
+
}
|
|
1781
|
+
/**
|
|
1782
|
+
* Builds a pay-in call's `wallets` key by key: `evm` and `svm`, only when defined.
|
|
1783
|
+
*/
|
|
1784
|
+
function buildPayInWallets(wallets) {
|
|
1785
|
+
const body = {};
|
|
1786
|
+
if (wallets.evm !== void 0) body.evm = wallets.evm;
|
|
1787
|
+
if (wallets.svm !== void 0) body.svm = wallets.svm;
|
|
1788
|
+
return body;
|
|
1789
|
+
}
|
|
1790
|
+
/**
|
|
1791
|
+
* Builds `quoteTopUp`'s body key by key: `wallets`, then `wallet` only when it is defined, then `asset` and `amount`,
|
|
1792
|
+
* then `sources` and `source_chains` when defined. Never a `destination`.
|
|
1793
|
+
*/
|
|
1794
|
+
function buildTopUpQuoteBody(request) {
|
|
1795
|
+
return {
|
|
1796
|
+
wallets: buildPayInWallets(request.wallets),
|
|
1797
|
+
...request.wallet === void 0 ? {} : { wallet: buildWalletDescriptor(request.wallet) },
|
|
1798
|
+
asset: request.asset,
|
|
1799
|
+
amount: request.amount,
|
|
1800
|
+
...request.sources === void 0 ? {} : { sources: [...request.sources] },
|
|
1801
|
+
...request.source_chains === void 0 ? {} : { source_chains: [...request.source_chains] }
|
|
1802
|
+
};
|
|
1803
|
+
}
|
|
1804
|
+
/** Builds a checkout with an explicit destination and the wallet's complete capabilities answer. */
|
|
1805
|
+
function buildCheckoutQuoteBody(request) {
|
|
1806
|
+
const wallet = request.wallet;
|
|
1807
|
+
return {
|
|
1808
|
+
wallets: buildPayInWallets(request.wallets),
|
|
1809
|
+
...wallet === void 0 ? {} : { wallet: {
|
|
1810
|
+
kind: wallet.kind,
|
|
1811
|
+
...wallet.name === void 0 ? {} : { name: wallet.name },
|
|
1812
|
+
...wallet.capabilities === void 0 ? {} : { capabilities: wallet.capabilities }
|
|
1813
|
+
} },
|
|
1814
|
+
asset: request.asset,
|
|
1815
|
+
amount: request.amount,
|
|
1816
|
+
...request.sources === void 0 ? {} : { sources: [...request.sources] },
|
|
1817
|
+
...request.source_chains === void 0 ? {} : { source_chains: [...request.source_chains] },
|
|
1818
|
+
destination: request.destination
|
|
1819
|
+
};
|
|
1820
|
+
}
|
|
1821
|
+
/**
|
|
1822
|
+
* Builds a quote's `wallet` key by key: `kind`, then `name` and `capabilities` only when they are defined.
|
|
1823
|
+
*/
|
|
1824
|
+
function buildWalletDescriptor(wallet) {
|
|
1825
|
+
return {
|
|
1826
|
+
kind: wallet.kind,
|
|
1827
|
+
...wallet.name === void 0 ? {} : { name: wallet.name },
|
|
1828
|
+
...wallet.capabilities === void 0 ? {} : { capabilities: buildCapabilities(wallet.capabilities) }
|
|
1829
|
+
};
|
|
1830
|
+
}
|
|
1831
|
+
/**
|
|
1832
|
+
* Copies a `wallet_getCapabilities` answer chain by chain, in its own order, with {@link buildChainCapabilities}. The
|
|
1833
|
+
* answer comes from the wallet unchecked, so a `capabilities` that is not an object is sent as it is, for the
|
|
1834
|
+
* Coordinator to refuse as `400 WALLET_MALFORMED`; the quote then goes out again without `wallet`.
|
|
1835
|
+
*/
|
|
1836
|
+
function buildCapabilities(capabilities) {
|
|
1837
|
+
if (!isJsonObject(capabilities)) return capabilities;
|
|
1838
|
+
return Object.fromEntries(Object.entries(capabilities).map(([chainId, chain]) => [chainId, buildChainCapabilities(chain)]));
|
|
1839
|
+
}
|
|
1840
|
+
/**
|
|
1841
|
+
* Copies one chain's capabilities, keeping only the three the Coordinator reads, each only when it is defined:
|
|
1842
|
+
* `alternateGasFees` and `paymasterService` as `{ supported }`, and `atomic` as `{ status }`. A wallet reports many
|
|
1843
|
+
* more, which never reach the wire. A `null` chain stays `null`; a chain or a capability that is not an object is sent
|
|
1844
|
+
* as it is, for the Coordinator to refuse as `400 WALLET_MALFORMED`.
|
|
1845
|
+
*/
|
|
1846
|
+
function buildChainCapabilities(chain) {
|
|
1847
|
+
if (chain === null || !isJsonObject(chain)) return chain;
|
|
1848
|
+
const copy = {};
|
|
1849
|
+
if (chain.alternateGasFees !== void 0) copy.alternateGasFees = buildSupportCapability(chain.alternateGasFees);
|
|
1850
|
+
if (chain.paymasterService !== void 0) copy.paymasterService = buildSupportCapability(chain.paymasterService);
|
|
1851
|
+
if (chain.atomic !== void 0) {
|
|
1852
|
+
const atomic = chain.atomic;
|
|
1853
|
+
copy.atomic = isJsonObject(atomic) ? { status: chain.atomic.status } : chain.atomic;
|
|
1854
|
+
}
|
|
1855
|
+
return copy;
|
|
1856
|
+
}
|
|
1857
|
+
/**
|
|
1858
|
+
* Copies a `{ supported }` capability: exactly `supported`, or the value as it is when it is not an object.
|
|
1859
|
+
*/
|
|
1860
|
+
function buildSupportCapability(capability) {
|
|
1861
|
+
return isJsonObject(capability) ? { supported: capability.supported } : capability;
|
|
1862
|
+
}
|
|
1863
|
+
function buildSignatureBatch(method, request, rules) {
|
|
1864
|
+
const items = isJsonObject(request) ? request.signatures : void 0;
|
|
1865
|
+
if (!Array.isArray(items)) throw new TypeError(`${method}: signatures must be an array`);
|
|
1866
|
+
if (items.length === 0 && !rules.allowEmpty) throw new TypeError(`${method}: signatures must hold at least one item`);
|
|
1867
|
+
return Array.from(items, (item, index) => buildSignatureItem(`${method}: signatures[${index}]`, item, rules.allowTxHash));
|
|
1868
|
+
}
|
|
1869
|
+
/**
|
|
1870
|
+
* Builds one batch item key by key, per {@link buildSignatureBatch}. `label` names the item in a refusal.
|
|
1871
|
+
*
|
|
1872
|
+
* @throws {TypeError} when the item breaks a rule {@link buildSignatureBatch} lists.
|
|
1873
|
+
*/
|
|
1874
|
+
function buildSignatureItem(label, item, allowTxHash) {
|
|
1875
|
+
if (!isJsonObject(item)) throw new TypeError(`${label} must be an object`);
|
|
1876
|
+
const stepId = item.step_id;
|
|
1877
|
+
if (typeof stepId !== "string" || stepId === "") throw new TypeError(`${label}.step_id must be a non-empty string`);
|
|
1878
|
+
const signature = item.signature;
|
|
1879
|
+
const txHash = item.tx_hash;
|
|
1880
|
+
if (signature === void 0 === (txHash === void 0)) throw new TypeError(`${label} must carry exactly one of signature and tx_hash`);
|
|
1881
|
+
if (txHash === void 0) {
|
|
1882
|
+
if (typeof signature !== "string" || signature === "") throw new TypeError(`${label}.signature must be a non-empty string`);
|
|
1883
|
+
return {
|
|
1884
|
+
step_id: stepId,
|
|
1885
|
+
signature
|
|
1886
|
+
};
|
|
1887
|
+
}
|
|
1888
|
+
if (!allowTxHash) throw new TypeError(`${label} carries a tx_hash, which is never sent on confirm`);
|
|
1889
|
+
if (typeof txHash !== "string" || !TX_HASH_PATTERN.test(txHash)) throw new TypeError(`${label}.tx_hash must be 0x followed by 64 hex digits`);
|
|
1890
|
+
return {
|
|
1891
|
+
step_id: stepId,
|
|
1892
|
+
tx_hash: txHash
|
|
1893
|
+
};
|
|
1894
|
+
}
|
|
1895
|
+
/**
|
|
1896
|
+
* Checks a route open or pay-in confirm's idempotency key: 1 to {@link MAX_IDEMPOTENCY_KEY_LENGTH} visible ASCII characters.
|
|
1897
|
+
*
|
|
1898
|
+
* @throws {TypeError} when it is anything else.
|
|
1899
|
+
*/
|
|
1900
|
+
function checkIdempotencyKey(method, key) {
|
|
1901
|
+
if (typeof key !== "string" || key.length > 128 || !IDEMPOTENCY_KEY_PATTERN.test(key)) throw new TypeError(`${method}: idempotencyKey must be 1 to 128 visible ASCII characters`);
|
|
1902
|
+
return key;
|
|
1903
|
+
}
|
|
1904
|
+
/**
|
|
1905
|
+
* Checks a route id and encodes it for the path. `.` and `..` are refused: `encodeURIComponent` leaves them as they
|
|
1906
|
+
* are, and the URL parser would resolve them as dot segments, sending the call to another hub API path.
|
|
1907
|
+
*
|
|
1908
|
+
* @throws {TypeError} when it is not a non-empty string, or is `.` or `..`.
|
|
1909
|
+
*/
|
|
1910
|
+
function encodePathId(method, field, routeId) {
|
|
1911
|
+
if (typeof routeId !== "string" || routeId === "" || routeId === "." || routeId === "..") throw new TypeError(`${method}: ${field} must be a non-empty string other than "." and ".."`);
|
|
1912
|
+
return encodeURIComponent(routeId);
|
|
1913
|
+
}
|
|
1914
|
+
/**
|
|
1915
|
+
* Builds `listRoutes`' query string: `?status=a,b&limit=N`, each part only when it is sent, or `""` when neither is.
|
|
1916
|
+
* The states need no encoding: every `ROUTE_STATES` member is lowercase letters and `_`.
|
|
1917
|
+
*
|
|
1918
|
+
* @throws {TypeError} when `query` is not an object, `states` is not an array of `ROUTE_STATES` members, or `limit`
|
|
1919
|
+
* is not an integer from 1 to {@link MAX_ROUTE_LIST_LIMIT}.
|
|
1920
|
+
*/
|
|
1921
|
+
function buildRouteListQuery(query) {
|
|
1922
|
+
if (query === void 0) return "";
|
|
1923
|
+
if (!isJsonObject(query)) throw new TypeError("listRoutes: query must be an object");
|
|
1924
|
+
const parts = [];
|
|
1925
|
+
const states = query.states;
|
|
1926
|
+
if (states !== void 0) {
|
|
1927
|
+
if (!Array.isArray(states) || !states.every(isRouteStateDto)) throw new TypeError(`listRoutes: states must hold only ${ROUTE_STATES.join(", ")}`);
|
|
1928
|
+
if (states.length > 0) parts.push(`status=${states.join(",")}`);
|
|
1929
|
+
}
|
|
1930
|
+
const limit = query.limit;
|
|
1931
|
+
if (limit !== void 0) {
|
|
1932
|
+
if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 100) throw new TypeError(`listRoutes: limit must be an integer from 1 to 100`);
|
|
1933
|
+
parts.push(`limit=${limit}`);
|
|
1934
|
+
}
|
|
1935
|
+
return parts.length === 0 ? "" : `?${parts.join("&")}`;
|
|
1936
|
+
}
|
|
1937
|
+
/**
|
|
1938
|
+
* Validates `baseUrl` and removes its trailing slashes.
|
|
1939
|
+
*
|
|
1940
|
+
* @throws {TypeError} when it is not an absolute `http:` or `https:` URL without a query or fragment.
|
|
1941
|
+
*/
|
|
1942
|
+
function normaliseBaseUrl(baseUrl) {
|
|
1943
|
+
if (typeof baseUrl !== "string" || baseUrl === "") throw new TypeError("createCoordinatorClient: baseUrl is required");
|
|
1944
|
+
let url;
|
|
1945
|
+
try {
|
|
1946
|
+
url = new URL(baseUrl);
|
|
1947
|
+
} catch {
|
|
1948
|
+
throw new TypeError(`createCoordinatorClient: baseUrl must be an absolute URL, got "${baseUrl}"`);
|
|
1949
|
+
}
|
|
1950
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new TypeError(`createCoordinatorClient: baseUrl must use http: or https:, got "${url.protocol}"`);
|
|
1951
|
+
if (url.search !== "" || url.hash !== "" || baseUrl.includes("?") || baseUrl.includes("#")) throw new TypeError("createCoordinatorClient: baseUrl must not carry a query or a fragment");
|
|
1952
|
+
return url.href.replace(/\/+$/, "");
|
|
1953
|
+
}
|
|
1954
|
+
/**
|
|
1955
|
+
* Builds the request sender every method shares. Every response reports its server time to `onServerTime` before
|
|
1956
|
+
* its answer is read.
|
|
1957
|
+
*
|
|
1958
|
+
* The route's {@link RouteCredentials} are written after every other header. A session call with `omitCredentials`
|
|
1959
|
+
* goes out with `credentials: "include"`, `X-Stridge-Session: omit` and no `X-CSRF-Token`, and the token is not read:
|
|
1960
|
+
* the hub proxy drops the session cookie on such a request, and the token only proves the session that cookie names.
|
|
1961
|
+
* The browser still stores the cookies the answer sets, such as an email round's binder cookie. Only a session call
|
|
1962
|
+
* ever reads the stored token.
|
|
1963
|
+
*
|
|
1964
|
+
* @throws {TypeError} when a route header names `X-CSRF-Token`, `X-Stridge-Cookie-Access` or `X-Stridge-Session`,
|
|
1965
|
+
* which only the credentials write.
|
|
1966
|
+
*/
|
|
1967
|
+
function createTransport(baseUrl, appId, csrf, fetchFn, onServerTime) {
|
|
1968
|
+
return { async send(call) {
|
|
1969
|
+
const signal = call.callOptions?.signal;
|
|
1970
|
+
const credentials = call.credentials;
|
|
1971
|
+
const omitCredentials = credentials.kind === "session" && call.callOptions?.omitCredentials === true;
|
|
1972
|
+
const headers = {};
|
|
1973
|
+
if (call.body !== void 0) headers["Content-Type"] = "application/json";
|
|
1974
|
+
if (call.sendsApp === true) headers[APP_HEADER] = appId;
|
|
1975
|
+
if (call.headers !== void 0) {
|
|
1976
|
+
for (const name of Object.keys(call.headers)) if (CREDENTIAL_HEADERS.has(name.toLowerCase())) throw new TypeError(`a route header may not name ${name}`);
|
|
1977
|
+
Object.assign(headers, call.headers);
|
|
1978
|
+
}
|
|
1979
|
+
if (omitCredentials) headers[SESSION_HEADER] = SESSION_HEADER_OMIT;
|
|
1980
|
+
if (credentials.kind === "session" && call.method !== "GET" && !omitCredentials) {
|
|
1981
|
+
const token = await csrf.get();
|
|
1982
|
+
if (typeof token === "string" && token !== "") headers[CSRF_HEADER] = token;
|
|
1983
|
+
}
|
|
1984
|
+
if (credentials.kind === "pinned-session") headers[CSRF_HEADER] = credentials.token;
|
|
1985
|
+
if (credentials.kind === "guest") headers[CSRF_HEADER] = credentials.token;
|
|
1986
|
+
if (credentials.kind === "guest" || credentials.kind === "guest-read") headers[GUEST_COOKIE_ACCESS_HEADER] = credentials.cookieAccess;
|
|
1987
|
+
const init = {
|
|
1988
|
+
method: call.method,
|
|
1989
|
+
headers,
|
|
1990
|
+
credentials: "include"
|
|
1991
|
+
};
|
|
1992
|
+
if (call.body !== void 0) init.body = JSON.stringify(call.body);
|
|
1993
|
+
if (signal !== void 0) init.signal = signal;
|
|
1994
|
+
let response;
|
|
1995
|
+
const sentAtMs = Date.now();
|
|
1996
|
+
try {
|
|
1997
|
+
response = await fetchFn(`${baseUrl}${call.path}`, init);
|
|
1998
|
+
} catch (cause) {
|
|
1999
|
+
if (signal?.aborted === true) throw cause;
|
|
2000
|
+
throw new SuaNetworkError(cause);
|
|
2001
|
+
}
|
|
2002
|
+
reportServerTime(onServerTime, response.headers, sentAtMs, Date.now());
|
|
2003
|
+
return readAnswer(response, signal, call.noContent === true, call.isAnswer);
|
|
2004
|
+
} };
|
|
2005
|
+
}
|
|
2006
|
+
/**
|
|
2007
|
+
* Reads an answer: an error envelope on any status and any non-`2xx` throw a `SuaError`. On a `noContent` route any
|
|
2008
|
+
* other `2xx` resolves `undefined`. On every other route a `2xx` whose body is not a JSON object (a `204` included),
|
|
2009
|
+
* or fails the route's `isAnswer` check, throws a `SuaError` with code `internal`, and any other `2xx` resolves its
|
|
2010
|
+
* parsed body.
|
|
2011
|
+
*
|
|
2012
|
+
* A body that fails to read rethrows the abort when the caller aborted. Otherwise it throws `SuaNetworkError` on a
|
|
2013
|
+
* `2xx` (no usable answer arrived) and counts as an empty body on a failure status.
|
|
2014
|
+
*/
|
|
2015
|
+
async function readAnswer(response, signal, noContent, isAnswer) {
|
|
2016
|
+
if (response.status === 204) {
|
|
2017
|
+
if (noContent) return;
|
|
2018
|
+
throw toSuaError({
|
|
2019
|
+
status: 204,
|
|
2020
|
+
retryAfter: response.headers.get("Retry-After"),
|
|
2021
|
+
body: ""
|
|
2022
|
+
});
|
|
2023
|
+
}
|
|
2024
|
+
let text;
|
|
2025
|
+
try {
|
|
2026
|
+
text = await response.text();
|
|
2027
|
+
} catch (cause) {
|
|
2028
|
+
if (signal?.aborted === true) throw cause;
|
|
2029
|
+
if (response.ok) throw new SuaNetworkError(cause);
|
|
2030
|
+
text = "";
|
|
2031
|
+
}
|
|
2032
|
+
const parsed = parseBody(text);
|
|
2033
|
+
const isEnvelope = parsed.kind === "json" && isErrorEnvelopeDto(parsed.value);
|
|
2034
|
+
const isSuccessBody = parsed.kind === "json" && isJsonObject(parsed.value) && (isAnswer === void 0 || isAnswer(parsed.value));
|
|
2035
|
+
if (noContent && response.ok && !isEnvelope) return;
|
|
2036
|
+
if (isEnvelope || !response.ok || !isSuccessBody) throw toSuaError({
|
|
2037
|
+
status: response.status,
|
|
2038
|
+
retryAfter: response.headers.get("Retry-After"),
|
|
2039
|
+
body: text
|
|
2040
|
+
});
|
|
2041
|
+
return parsed.value;
|
|
2042
|
+
}
|
|
2043
|
+
//#endregion
|
|
2044
|
+
//#region src/encoding/base64.ts
|
|
2045
|
+
const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
2046
|
+
const BASE64_URL_PATTERN = /^[A-Za-z0-9_-]*$/;
|
|
2047
|
+
const CHUNK_SIZE = 32768;
|
|
2048
|
+
/**
|
|
2049
|
+
* Builds a binary string (one character per byte, every code unit 0–255) from bytes, in chunks so a large input
|
|
2050
|
+
* never overflows the argument limit of `String.fromCharCode`. A binary string is the only input `btoa` handles
|
|
2051
|
+
* correctly.
|
|
2052
|
+
*/
|
|
2053
|
+
function toBinaryString(bytes) {
|
|
2054
|
+
let out = "";
|
|
2055
|
+
for (let offset = 0; offset < bytes.length; offset += CHUNK_SIZE) out += String.fromCharCode(...bytes.subarray(offset, offset + CHUNK_SIZE));
|
|
2056
|
+
return out;
|
|
2057
|
+
}
|
|
2058
|
+
/**
|
|
2059
|
+
* Turns the binary string `atob` returns back into bytes.
|
|
2060
|
+
*/
|
|
2061
|
+
function fromBinaryString(binary) {
|
|
2062
|
+
const out = new Uint8Array(binary.length);
|
|
2063
|
+
for (let index = 0; index < binary.length; index += 1) out[index] = binary.charCodeAt(index);
|
|
2064
|
+
return out;
|
|
2065
|
+
}
|
|
2066
|
+
/**
|
|
2067
|
+
* Encodes bytes as standard base64 (RFC 4648 §4: `+`, `/`, padded with `=`). This is the encoding of the
|
|
2068
|
+
* Coordinator's `[]byte` JSON fields (`body`, `stamp_header.value`, `provider_response`) and of
|
|
2069
|
+
* `session_public_key`.
|
|
2070
|
+
*
|
|
2071
|
+
* Works on bytes, never on text: to base64 a string, encode it with {@link utf8ToBytes} first. Calling `btoa` on
|
|
2072
|
+
* a string with any character above U+00FF throws, and on a Latin-1 string it silently encodes the wrong bytes.
|
|
2073
|
+
*/
|
|
2074
|
+
function toBase64(bytes) {
|
|
2075
|
+
return btoa(toBinaryString(bytes));
|
|
2076
|
+
}
|
|
2077
|
+
/**
|
|
2078
|
+
* Decodes standard base64 (RFC 4648 §4). Padding may be present or omitted; whitespace and the URL-safe
|
|
2079
|
+
* alphabet (`-`, `_`) are refused.
|
|
2080
|
+
*
|
|
2081
|
+
* @throws {TypeError} when `value` is not standard base64.
|
|
2082
|
+
*/
|
|
2083
|
+
function fromBase64(value) {
|
|
2084
|
+
if (typeof value !== "string" || !BASE64_PATTERN.test(value) || value.length % 4 === 1) throw new TypeError("fromBase64: expected standard base64");
|
|
2085
|
+
try {
|
|
2086
|
+
return fromBinaryString(atob(value));
|
|
2087
|
+
} catch {
|
|
2088
|
+
throw new TypeError("fromBase64: expected standard base64");
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
/**
|
|
2092
|
+
* Encodes bytes as base64url without padding (RFC 4648 §5: `-`, `_`, no `=`). This is the encoding of the
|
|
2093
|
+
* Turnkey stamp string before it is wrapped in standard base64 for `stamp_header.value` (guide §7.2).
|
|
2094
|
+
*/
|
|
2095
|
+
function toBase64Url(bytes) {
|
|
2096
|
+
return toBase64(bytes).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
|
|
2097
|
+
}
|
|
2098
|
+
/**
|
|
2099
|
+
* Decodes base64url (RFC 4648 §5) without padding. Padding, whitespace and the standard alphabet (`+`, `/`) are
|
|
2100
|
+
* refused.
|
|
2101
|
+
*
|
|
2102
|
+
* @throws {TypeError} when `value` is not unpadded base64url.
|
|
2103
|
+
*/
|
|
2104
|
+
function fromBase64Url(value) {
|
|
2105
|
+
if (typeof value !== "string" || !BASE64_URL_PATTERN.test(value) || value.length % 4 === 1) throw new TypeError("fromBase64Url: expected unpadded base64url");
|
|
2106
|
+
return fromBase64(value.replaceAll("-", "+").replaceAll("_", "/"));
|
|
2107
|
+
}
|
|
2108
|
+
//#endregion
|
|
2109
|
+
//#region src/encoding/hex.ts
|
|
2110
|
+
const HEX_PATTERN = /^(?:[0-9a-fA-F]{2})*$/;
|
|
2111
|
+
/**
|
|
2112
|
+
* Encodes bytes as lowercase hex, two characters per byte, with no `0x` prefix.
|
|
2113
|
+
*
|
|
2114
|
+
* @example toHex(new Uint8Array([0x02, 0x4e])) === "024e"
|
|
2115
|
+
*/
|
|
2116
|
+
function toHex(bytes) {
|
|
2117
|
+
let out = "";
|
|
2118
|
+
for (const byte of bytes) out += byte.toString(16).padStart(2, "0");
|
|
2119
|
+
return out;
|
|
2120
|
+
}
|
|
2121
|
+
/**
|
|
2122
|
+
* Decodes hex into bytes. Accepts either case; refuses a `0x` prefix, an odd length and any non-hex character.
|
|
2123
|
+
*
|
|
2124
|
+
* @throws {TypeError} when `hex` is not an even-length string of hex digits.
|
|
2125
|
+
*/
|
|
2126
|
+
function fromHex(hex) {
|
|
2127
|
+
if (typeof hex !== "string" || !HEX_PATTERN.test(hex)) throw new TypeError("fromHex: expected an even-length hex string without a 0x prefix");
|
|
2128
|
+
const out = new Uint8Array(hex.length / 2);
|
|
2129
|
+
for (let index = 0; index < out.length; index += 1) out[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);
|
|
2130
|
+
return out;
|
|
2131
|
+
}
|
|
2132
|
+
//#endregion
|
|
2133
|
+
//#region src/crypto/der.ts
|
|
2134
|
+
const SEQUENCE_TAG = 48;
|
|
2135
|
+
const INTEGER_TAG = 2;
|
|
2136
|
+
const COORDINATE_LENGTH = 32;
|
|
2137
|
+
const RAW_LENGTH = COORDINATE_LENGTH * 2;
|
|
2138
|
+
const MAX_INTEGER_LENGTH = 33;
|
|
2139
|
+
const LONG_FORM_BIT = 128;
|
|
2140
|
+
/**
|
|
2141
|
+
* Encodes one 32-byte big-endian coordinate as a minimal, positive DER INTEGER: leading zeros stripped (at least one
|
|
2142
|
+
* byte kept), then one `0x00` prepended when the high bit of the first remaining byte is set.
|
|
2143
|
+
*/
|
|
2144
|
+
function encodeInteger(value) {
|
|
2145
|
+
let start = 0;
|
|
2146
|
+
while (start < value.length - 1 && value[start] === 0) start += 1;
|
|
2147
|
+
const digits = value.subarray(start);
|
|
2148
|
+
const pad = digits[0] >= 128 ? 1 : 0;
|
|
2149
|
+
const out = new Uint8Array(2 + pad + digits.length);
|
|
2150
|
+
out[0] = INTEGER_TAG;
|
|
2151
|
+
out[1] = pad + digits.length;
|
|
2152
|
+
out.set(digits, 2 + pad);
|
|
2153
|
+
return out;
|
|
2154
|
+
}
|
|
2155
|
+
/**
|
|
2156
|
+
* Converts a raw P-256 ECDSA signature (r‖s, 32 bytes each) to DER (X.690):
|
|
2157
|
+
* `0x30 <len> 0x02 <rlen> <r> 0x02 <slen> <s>`, where each integer is minimal and positive: leading `0x00` bytes are
|
|
2158
|
+
* stripped (keeping at least one byte), then one `0x00` is prepended when the first remaining byte is `≥ 0x80`.
|
|
2159
|
+
* Lengths are always short-form (the whole signature is at most 72 bytes).
|
|
2160
|
+
*
|
|
2161
|
+
* Example (§12.7): r `a364…d7f6` has its high bit set and becomes `022100a364…d7f6`; s `4199…556e` does not and
|
|
2162
|
+
* becomes `02204199…556e`, giving `3045022100a364f4…42556e`.
|
|
2163
|
+
*
|
|
2164
|
+
* @throws {TypeError} when `raw` is not exactly 64 bytes.
|
|
2165
|
+
*/
|
|
2166
|
+
function rawSignatureToDer(raw) {
|
|
2167
|
+
if (!(raw instanceof Uint8Array) || raw.length !== RAW_LENGTH) throw new TypeError("rawSignatureToDer: expected a 64-byte r‖s signature");
|
|
2168
|
+
const r = encodeInteger(raw.subarray(0, COORDINATE_LENGTH));
|
|
2169
|
+
const s = encodeInteger(raw.subarray(COORDINATE_LENGTH));
|
|
2170
|
+
const out = new Uint8Array(2 + r.length + s.length);
|
|
2171
|
+
out[0] = SEQUENCE_TAG;
|
|
2172
|
+
out[1] = r.length + s.length;
|
|
2173
|
+
out.set(r, 2);
|
|
2174
|
+
out.set(s, 2 + r.length);
|
|
2175
|
+
return out;
|
|
2176
|
+
}
|
|
2177
|
+
/**
|
|
2178
|
+
* Reads one strict DER INTEGER at `offset`: tag `0x02`, a short-form length of 1–33 that ends at or before `end`, a
|
|
2179
|
+
* positive and minimal encoding, and a value of at most 32 bytes once the sign-padding byte is dropped.
|
|
2180
|
+
*
|
|
2181
|
+
* @throws {TypeError} when the INTEGER breaks any of those rules.
|
|
2182
|
+
*/
|
|
2183
|
+
function readInteger(der, offset, end) {
|
|
2184
|
+
if (offset + 2 > end || der[offset] !== INTEGER_TAG) throw new TypeError("derSignatureToRaw: expected an INTEGER");
|
|
2185
|
+
const length = der[offset + 1];
|
|
2186
|
+
if ((length & LONG_FORM_BIT) !== 0) throw new TypeError("derSignatureToRaw: long-form lengths are not allowed");
|
|
2187
|
+
if (length < 1 || length > MAX_INTEGER_LENGTH) throw new TypeError("derSignatureToRaw: INTEGER length out of range");
|
|
2188
|
+
const start = offset + 2;
|
|
2189
|
+
const next = start + length;
|
|
2190
|
+
if (next > end) throw new TypeError("derSignatureToRaw: INTEGER runs past the end of the SEQUENCE");
|
|
2191
|
+
const first = der[start];
|
|
2192
|
+
if (first >= 128) throw new TypeError("derSignatureToRaw: negative INTEGER");
|
|
2193
|
+
const padded = first === 0 && length > 1;
|
|
2194
|
+
if (padded && der[start + 1] < 128) throw new TypeError("derSignatureToRaw: non-minimal INTEGER");
|
|
2195
|
+
const value = der.subarray(padded ? start + 1 : start, next);
|
|
2196
|
+
if (value.length > COORDINATE_LENGTH) throw new TypeError("derSignatureToRaw: INTEGER is longer than 32 bytes");
|
|
2197
|
+
return {
|
|
2198
|
+
value,
|
|
2199
|
+
next
|
|
2200
|
+
};
|
|
2201
|
+
}
|
|
2202
|
+
/**
|
|
2203
|
+
* Converts a DER ECDSA signature to raw r‖s (64 bytes): each INTEGER is stripped of leading `0x00` bytes and
|
|
2204
|
+
* left-padded with zeros to 32 bytes. The exact inverse of {@link rawSignatureToDer} on its output.
|
|
2205
|
+
*
|
|
2206
|
+
* Strict: a `0x30` SEQUENCE with a short-form length equal to the rest of the input, holding exactly two `0x02`
|
|
2207
|
+
* INTEGERs with short-form lengths of 1–33 bytes, each positive (first byte `< 0x80`) and minimal (a leading `0x00`
|
|
2208
|
+
* only when the next byte is `≥ 0x80`), with a value of at most 32 bytes once stripped, and no trailing bytes.
|
|
2209
|
+
*
|
|
2210
|
+
* @throws {TypeError} when `der` breaks any of those rules.
|
|
2211
|
+
*/
|
|
2212
|
+
function derSignatureToRaw(der) {
|
|
2213
|
+
if (!(der instanceof Uint8Array) || der.length < 2 || der[0] !== SEQUENCE_TAG) throw new TypeError("derSignatureToRaw: expected a DER SEQUENCE");
|
|
2214
|
+
const length = der[1];
|
|
2215
|
+
if ((length & LONG_FORM_BIT) !== 0) throw new TypeError("derSignatureToRaw: long-form lengths are not allowed");
|
|
2216
|
+
if (length !== der.length - 2) throw new TypeError("derSignatureToRaw: SEQUENCE length does not match the input");
|
|
2217
|
+
const r = readInteger(der, 2, der.length);
|
|
2218
|
+
const s = readInteger(der, r.next, der.length);
|
|
2219
|
+
if (s.next !== der.length) throw new TypeError("derSignatureToRaw: trailing bytes after the two INTEGERs");
|
|
2220
|
+
const out = new Uint8Array(RAW_LENGTH);
|
|
2221
|
+
out.set(r.value, COORDINATE_LENGTH - r.value.length);
|
|
2222
|
+
out.set(s.value, RAW_LENGTH - s.value.length);
|
|
2223
|
+
return out;
|
|
2224
|
+
}
|
|
2225
|
+
//#endregion
|
|
2226
|
+
//#region src/crypto/subtle.ts
|
|
2227
|
+
/**
|
|
2228
|
+
* Returns WebCrypto's `SubtleCrypto`, read from `globalThis` at call time so importing a module never touches it (a
|
|
2229
|
+
* server bundle may import the SDK on a runtime without WebCrypto).
|
|
2230
|
+
*
|
|
2231
|
+
* @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.
|
|
2232
|
+
*/
|
|
2233
|
+
function getSubtle() {
|
|
2234
|
+
const subtle = globalThis.crypto?.subtle;
|
|
2235
|
+
if (!subtle) throw new Error("WebCrypto is unavailable");
|
|
2236
|
+
return subtle;
|
|
2237
|
+
}
|
|
2238
|
+
//#endregion
|
|
2239
|
+
//#region src/crypto/types.ts
|
|
2240
|
+
/**
|
|
2241
|
+
* The WebCrypto parameters of the keypair: ECDSA on P-256.
|
|
2242
|
+
*/
|
|
2243
|
+
const KEYPAIR_ALGORITHM = {
|
|
2244
|
+
name: "ECDSA",
|
|
2245
|
+
namedCurve: "P-256"
|
|
2246
|
+
};
|
|
2247
|
+
/**
|
|
2248
|
+
* The WebCrypto parameters of every signature: ECDSA with SHA-256. WebCrypto hashes the message itself and returns
|
|
2249
|
+
* raw r‖s (IEEE P1363, 64 bytes).
|
|
2250
|
+
*/
|
|
2251
|
+
const SIGNATURE_ALGORITHM = {
|
|
2252
|
+
name: "ECDSA",
|
|
2253
|
+
hash: "SHA-256"
|
|
2254
|
+
};
|
|
2255
|
+
/**
|
|
2256
|
+
* The registration's activity type: the keypair's own login.
|
|
2257
|
+
*/
|
|
2258
|
+
const STAMP_LOGIN_ACTIVITY_TYPE = "ACTIVITY_TYPE_STAMP_LOGIN";
|
|
2259
|
+
/**
|
|
2260
|
+
* The login window the registration asks for, as the decimal string the activity carries: one hour, the Coordinator's
|
|
2261
|
+
* `OWNER_SESSION_LIFETIME`. There is no server-side logout, so this is how long a registered keypair can sign.
|
|
2262
|
+
*/
|
|
2263
|
+
const STAMP_LOGIN_EXPIRATION_SECONDS = "3600";
|
|
2264
|
+
/**
|
|
2265
|
+
* The stamp's `scheme`.
|
|
2266
|
+
*/
|
|
2267
|
+
const STAMP_SCHEME = "SIGNATURE_SCHEME_TK_API_P256";
|
|
2268
|
+
/**
|
|
2269
|
+
* The stamp header's name.
|
|
2270
|
+
*/
|
|
2271
|
+
const STAMP_HEADER_NAME = "X-Stamp";
|
|
2272
|
+
//#endregion
|
|
2273
|
+
//#region src/crypto/sign.ts
|
|
2274
|
+
/**
|
|
2275
|
+
* Signs the UTF-8 bytes of `message` with ECDSA P-256 / SHA-256 and returns WebCrypto's raw r‖s bytes.
|
|
2276
|
+
*
|
|
2277
|
+
* @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.
|
|
2278
|
+
*/
|
|
2279
|
+
async function signBytes(privateKey, message) {
|
|
2280
|
+
const subtle = getSubtle();
|
|
2281
|
+
return new Uint8Array(await subtle.sign(SIGNATURE_ALGORITHM, privateKey, utf8ToBytes(message)));
|
|
2282
|
+
}
|
|
2283
|
+
/**
|
|
2284
|
+
* Signs `message` with ECDSA P-256 and SHA-256 (`SIGNATURE_ALGORITHM`) over the UTF-8 bytes of `message`
|
|
2285
|
+
* (`utf8ToBytes`), returned as **raw r‖s**: the 64 bytes WebCrypto produces, as 128 lowercase hex characters. No DER,
|
|
2286
|
+
* no low-S normalisation. No Coordinator request takes this form; stamps use {@link signDer}.
|
|
2287
|
+
*
|
|
2288
|
+
* ECDSA is randomised, so two calls give different signatures; test by verifying, not by comparing.
|
|
2289
|
+
*
|
|
2290
|
+
* @param privateKey The keypair's private key.
|
|
2291
|
+
* @param message The message, verbatim.
|
|
2292
|
+
* @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.
|
|
2293
|
+
*/
|
|
2294
|
+
async function signRaw(privateKey, message) {
|
|
2295
|
+
return toHex(await signBytes(privateKey, message));
|
|
2296
|
+
}
|
|
2297
|
+
/**
|
|
2298
|
+
* Signs `message` for the **stamp** (guide §7.2): the same ECDSA P-256 / SHA-256 signature over the UTF-8 bytes of
|
|
2299
|
+
* `message` as {@link signRaw}, converted with `rawSignatureToDer` and returned as lowercase DER hex (140–144
|
|
2300
|
+
* characters; 138 or fewer is possible but rare).
|
|
2301
|
+
*
|
|
2302
|
+
* @param privateKey The keypair's private key.
|
|
2303
|
+
* @param message The exact activity body string that the relay will forward.
|
|
2304
|
+
* @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.
|
|
2305
|
+
*/
|
|
2306
|
+
async function signDer(privateKey, message) {
|
|
2307
|
+
return toHex(rawSignatureToDer(await signBytes(privateKey, message)));
|
|
2308
|
+
}
|
|
2309
|
+
//#endregion
|
|
2310
|
+
//#region src/crypto/credential.ts
|
|
2311
|
+
const COMPRESSED_PUBLIC_KEY_HEX$1 = /^0[23][0-9a-f]{64}$/;
|
|
2312
|
+
/**
|
|
2313
|
+
* Builds the keypair's login activity, once, as the exact string the stamp signs and the hub relays:
|
|
2314
|
+
*
|
|
2315
|
+
* `{"type":"ACTIVITY_TYPE_STAMP_LOGIN","timestampMs":"<nowMs>","organizationId":"<organizationId>","parameters":{"publicKey":"<publicKeyHex>","expirationSeconds":"3600","invalidateExisting":false}}`
|
|
2316
|
+
*
|
|
2317
|
+
* The hub refuses any other key, casing or order of fields, a window above its own, and `invalidateExisting: true`
|
|
2318
|
+
* (which would sign the person out on every other device). Never re-serialise the result.
|
|
2319
|
+
*
|
|
2320
|
+
* @param organizationId The wallet's `provider_account_ref`.
|
|
2321
|
+
* @param publicKeyHex The keypair's compressed public key: 66 lowercase hex characters starting `02` or `03`.
|
|
2322
|
+
* @param nowMs The activity's timestamp, in milliseconds since the epoch.
|
|
2323
|
+
* @throws {TypeError} when `organizationId` is empty or `publicKeyHex` is not a lowercase compressed key.
|
|
2324
|
+
*/
|
|
2325
|
+
function buildStampLogin(organizationId, publicKeyHex, nowMs = Date.now()) {
|
|
2326
|
+
if (typeof organizationId !== "string" || organizationId === "") throw new TypeError("buildStampLogin: expected a non-empty organization id");
|
|
2327
|
+
if (typeof publicKeyHex !== "string" || !COMPRESSED_PUBLIC_KEY_HEX$1.test(publicKeyHex)) throw new TypeError("buildStampLogin: expected a 66-character lowercase compressed public key hex");
|
|
2328
|
+
return JSON.stringify({
|
|
2329
|
+
type: STAMP_LOGIN_ACTIVITY_TYPE,
|
|
2330
|
+
timestampMs: String(Math.trunc(nowMs)),
|
|
2331
|
+
organizationId,
|
|
2332
|
+
parameters: {
|
|
2333
|
+
publicKey: publicKeyHex,
|
|
2334
|
+
expirationSeconds: STAMP_LOGIN_EXPIRATION_SECONDS,
|
|
2335
|
+
invalidateExisting: false
|
|
2336
|
+
}
|
|
2337
|
+
});
|
|
2338
|
+
}
|
|
2339
|
+
/**
|
|
2340
|
+
* Builds the `X-Stamp-Attested` value over `body`: the keypair's DER signature over the UTF-8 bytes of `body`
|
|
2341
|
+
* (`signDer`), in the JSON `{"publicKeyAttestation","scheme","publicKey","signature"}` with the attestation verbatim,
|
|
2342
|
+
* then its UTF-8 bytes as **unpadded base64url**. Never log the result: it carries the attestation token.
|
|
2343
|
+
*
|
|
2344
|
+
* @param body The exact string to sign, from {@link buildStampLogin}.
|
|
2345
|
+
* @param keypair The keypair that sealed the code the attestation was issued for.
|
|
2346
|
+
* @param attestation The credential's `attestation`.
|
|
2347
|
+
*/
|
|
2348
|
+
async function stampAttested(body, keypair, attestation) {
|
|
2349
|
+
const signature = await signDer(keypair.keys.privateKey, body);
|
|
2350
|
+
return toBase64Url(utf8ToBytes(JSON.stringify({
|
|
2351
|
+
publicKeyAttestation: attestation.token,
|
|
2352
|
+
scheme: attestation.scheme,
|
|
2353
|
+
publicKey: keypair.publicKeyHex,
|
|
2354
|
+
signature
|
|
2355
|
+
})));
|
|
2356
|
+
}
|
|
2357
|
+
/**
|
|
2358
|
+
* Builds the registration body for a credential: the keypair's login for `organizationId` ({@link buildStampLogin})
|
|
2359
|
+
* and its attested stamp ({@link stampAttested}), as exactly `{ round_id: credential.round_id, stamped_body,
|
|
2360
|
+
* attested_stamp }`.
|
|
2361
|
+
*
|
|
2362
|
+
* @param organizationId The wallet's `provider_account_ref`.
|
|
2363
|
+
* @throws {TypeError} on the inputs {@link buildStampLogin} refuses.
|
|
2364
|
+
*/
|
|
2365
|
+
async function createRegisterKeypairRequest(credential, keypair, organizationId, nowMs = Date.now()) {
|
|
2366
|
+
const stampedBody = buildStampLogin(organizationId, keypair.publicKeyHex, nowMs);
|
|
2367
|
+
return {
|
|
2368
|
+
round_id: credential.round_id,
|
|
2369
|
+
stamped_body: stampedBody,
|
|
2370
|
+
attested_stamp: await stampAttested(stampedBody, keypair, credential.attestation)
|
|
2371
|
+
};
|
|
2372
|
+
}
|
|
2373
|
+
//#endregion
|
|
2374
|
+
//#region src/crypto/keypair.ts
|
|
2375
|
+
const UNCOMPRESSED_LENGTH = 65;
|
|
2376
|
+
const COMPRESSED_LENGTH = 33;
|
|
2377
|
+
const UNCOMPRESSED_PREFIX = 4;
|
|
2378
|
+
/**
|
|
2379
|
+
* Reports whether a key's algorithm is ECDSA on P-256.
|
|
2380
|
+
*/
|
|
2381
|
+
function isEcdsaP256(key) {
|
|
2382
|
+
const algorithm = key.algorithm;
|
|
2383
|
+
return algorithm?.name === KEYPAIR_ALGORITHM.name && algorithm.namedCurve === KEYPAIR_ALGORITHM.namedCurve;
|
|
2384
|
+
}
|
|
2385
|
+
/**
|
|
2386
|
+
* Checks that `keys` is an ECDSA P-256 pair whose private half can sign.
|
|
2387
|
+
*
|
|
2388
|
+
* @throws {TypeError} when it is not.
|
|
2389
|
+
*/
|
|
2390
|
+
function assertSigningPair(keys) {
|
|
2391
|
+
const { publicKey, privateKey } = keys ?? {};
|
|
2392
|
+
if (!publicKey || publicKey.type !== "public" || !isEcdsaP256(publicKey)) throw new TypeError("keypairFromKeys: the public key must be an ECDSA P-256 public key");
|
|
2393
|
+
if (!privateKey || privateKey.type !== "private" || !isEcdsaP256(privateKey) || !Array.from(privateKey.usages ?? []).includes("sign")) throw new TypeError("keypairFromKeys: the private key must be an ECDSA P-256 private key that can sign");
|
|
2394
|
+
}
|
|
2395
|
+
/**
|
|
2396
|
+
* Generates a new keypair (guide §3.3): `crypto.subtle.generateKey(KEYPAIR_ALGORITHM, false, ["sign"])`, so the
|
|
2397
|
+
* private key is ECDSA P-256, non-extractable and can only sign. Then derives the compressed public key forms through
|
|
2398
|
+
* {@link keypairFromKeys}.
|
|
2399
|
+
*
|
|
2400
|
+
* Reads `globalThis.crypto.subtle` at call time, never at module load.
|
|
2401
|
+
*
|
|
2402
|
+
* @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.
|
|
2403
|
+
*/
|
|
2404
|
+
async function generateKeypair() {
|
|
2405
|
+
return keypairFromKeys(await getSubtle().generateKey(KEYPAIR_ALGORITHM, false, ["sign"]));
|
|
2406
|
+
}
|
|
2407
|
+
/**
|
|
2408
|
+
* Builds a {@link Keypair} around an existing WebCrypto pair, for example one read back from storage: exports
|
|
2409
|
+
* `keys.publicKey` as `"raw"` (the 65-byte uncompressed point), compresses it with {@link compressPublicKey}, and fills
|
|
2410
|
+
* `publicKeyHex` (`toHex`, lowercase) and `publicKeyBase64` (`toBase64`, standard, padded). `keys` is kept by
|
|
2411
|
+
* reference.
|
|
2412
|
+
*
|
|
2413
|
+
* @throws {TypeError} when `keys.publicKey.algorithm` is not ECDSA on P-256, or `keys.privateKey` is not an ECDSA
|
|
2414
|
+
* private key whose usages include `"sign"`.
|
|
2415
|
+
* @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.
|
|
2416
|
+
*/
|
|
2417
|
+
async function keypairFromKeys(keys) {
|
|
2418
|
+
const subtle = getSubtle();
|
|
2419
|
+
assertSigningPair(keys);
|
|
2420
|
+
const publicKey = compressPublicKey(new Uint8Array(await subtle.exportKey("raw", keys.publicKey)));
|
|
2421
|
+
return {
|
|
2422
|
+
keys,
|
|
2423
|
+
publicKey,
|
|
2424
|
+
publicKeyHex: toHex(publicKey),
|
|
2425
|
+
publicKeyBase64: toBase64(publicKey)
|
|
2426
|
+
};
|
|
2427
|
+
}
|
|
2428
|
+
/**
|
|
2429
|
+
* Compresses an uncompressed SEC1 P-256 point (`0x04 ‖ X ‖ Y`, 65 bytes) into 33 bytes: prefix `0x02 + (Y[31] & 1)`,
|
|
2430
|
+
* then X (guide §3.3: `publicKey[0] = 2 + (raw[64] & 1)`). Returns a new array; the input is not modified.
|
|
2431
|
+
*
|
|
2432
|
+
* Only the encoding is checked, not that the point is on the curve (WebCrypto produced it).
|
|
2433
|
+
*
|
|
2434
|
+
* @throws {TypeError} when `uncompressed` is not 65 bytes starting with `0x04`.
|
|
2435
|
+
*/
|
|
2436
|
+
function compressPublicKey(uncompressed) {
|
|
2437
|
+
if (!(uncompressed instanceof Uint8Array) || uncompressed.length !== UNCOMPRESSED_LENGTH || uncompressed[0] !== UNCOMPRESSED_PREFIX) throw new TypeError("compressPublicKey: expected a 65-byte uncompressed point starting with 0x04");
|
|
2438
|
+
const out = new Uint8Array(COMPRESSED_LENGTH);
|
|
2439
|
+
out[0] = 2 + (uncompressed[UNCOMPRESSED_LENGTH - 1] & 1);
|
|
2440
|
+
out.set(uncompressed.subarray(1, COMPRESSED_LENGTH), 1);
|
|
2441
|
+
return out;
|
|
2442
|
+
}
|
|
2443
|
+
//#endregion
|
|
2444
|
+
//#region src/crypto/stamp.ts
|
|
2445
|
+
const COMPRESSED_PUBLIC_KEY_HEX = /^0[23][0-9a-fA-F]{64}$/;
|
|
2446
|
+
const NON_EMPTY_HEX = /^(?:[0-9a-fA-F]{2})+$/;
|
|
2447
|
+
/**
|
|
2448
|
+
* Builds the Turnkey API-key stamp string (guide §7.2; `router/internal/turnkey/stamp.go`): the compact JSON
|
|
2449
|
+
* `{"publicKey":"<publicKeyHex>","scheme":"SIGNATURE_SCHEME_TK_API_P256","signature":"<signatureDerHex>"}`, keys in
|
|
2450
|
+
* exactly that order and no whitespace (build it with `JSON.stringify` of an object literal in that order), then its
|
|
2451
|
+
* UTF-8 bytes as **unpadded base64url** (`toBase64Url`).
|
|
2452
|
+
*
|
|
2453
|
+
* Both hex inputs are lowercased before they are embedded.
|
|
2454
|
+
*
|
|
2455
|
+
* Vector (§12.7): public key `024e7fb37bf4a0c496da3d6ce2bd68f82b1a1c877a8f258a4bceb121bec94ba272` and the §12.7 DER
|
|
2456
|
+
* signature give the string whose standard base64 is the §12.7 `stamp_header.value`.
|
|
2457
|
+
*
|
|
2458
|
+
* @param publicKeyHex The keypair's compressed public key: 66 hex characters starting `02` or `03`.
|
|
2459
|
+
* @param signatureDerHex The DER signature over the body, as hex (from `signDer`).
|
|
2460
|
+
* @throws {TypeError} when `publicKeyHex` is not 66 hex characters starting `02` or `03`, or `signatureDerHex` is not
|
|
2461
|
+
* a non-empty even-length hex string.
|
|
2462
|
+
*/
|
|
2463
|
+
function buildStamp(publicKeyHex, signatureDerHex) {
|
|
2464
|
+
if (typeof publicKeyHex !== "string" || !COMPRESSED_PUBLIC_KEY_HEX.test(publicKeyHex)) throw new TypeError("buildStamp: expected a 66-character compressed public key hex starting 02 or 03");
|
|
2465
|
+
if (typeof signatureDerHex !== "string" || !NON_EMPTY_HEX.test(signatureDerHex)) throw new TypeError("buildStamp: expected a non-empty even-length DER signature hex");
|
|
2466
|
+
return toBase64Url(utf8ToBytes(JSON.stringify({
|
|
2467
|
+
publicKey: publicKeyHex.toLowerCase(),
|
|
2468
|
+
scheme: STAMP_SCHEME,
|
|
2469
|
+
signature: signatureDerHex.toLowerCase()
|
|
2470
|
+
})));
|
|
2471
|
+
}
|
|
2472
|
+
/**
|
|
2473
|
+
* Builds the relay's `stamp_header`: `{ name: "X-Stamp", value }` where `value` is the **standard base64 (padded)**
|
|
2474
|
+
* of the UTF-8 bytes of {@link buildStamp}'s string, so base64 of base64url. The Coordinator decodes it once and
|
|
2475
|
+
* forwards the result as the `X-Stamp` header verbatim.
|
|
2476
|
+
*
|
|
2477
|
+
* Vector (§12.7): the §12.7 public key and DER signature give exactly the §12.7 `stamp_header.value`
|
|
2478
|
+
* (`ZXlKd2RXSnNhV05MWlhr…Wk5UVTJaU0o5`).
|
|
2479
|
+
*
|
|
2480
|
+
* @throws {TypeError} on the same inputs as {@link buildStamp}.
|
|
2481
|
+
*/
|
|
2482
|
+
function buildStampHeader(publicKeyHex, signatureDerHex) {
|
|
2483
|
+
return {
|
|
2484
|
+
name: STAMP_HEADER_NAME,
|
|
2485
|
+
value: toBase64(utf8ToBytes(buildStamp(publicKeyHex, signatureDerHex)))
|
|
2486
|
+
};
|
|
2487
|
+
}
|
|
2488
|
+
/**
|
|
2489
|
+
* Encodes the activity body for the relay's `body` field (guide §7.3): the **standard base64 (padded)** of the exact
|
|
2490
|
+
* UTF-8 bytes of `body`, which are the bytes the stamp signed. `toBase64(utf8ToBytes(body))`; never `btoa(body)`,
|
|
2491
|
+
* which throws on any character above U+00FF and silently encodes Latin-1 wrongly.
|
|
2492
|
+
*
|
|
2493
|
+
* Vector (§12.7): the §12.7 body string encodes to the §12.7 request's `body`
|
|
2494
|
+
* (`eyJ0eXBlIjoiQUNUSVZJVFlfVFlQRV9TSUdOX1JBV19QQVlMT0FEX1YyIiwi…In19`).
|
|
2495
|
+
*/
|
|
2496
|
+
function encodeRelayBody(body) {
|
|
2497
|
+
return toBase64(utf8ToBytes(body));
|
|
2498
|
+
}
|
|
2499
|
+
//#endregion
|
|
2500
|
+
//#region src/crypto/relayRequest.ts
|
|
2501
|
+
/**
|
|
2502
|
+
* Stamps an activity body and builds the relay request for it (guide §7.2–§7.3):
|
|
2503
|
+
*
|
|
2504
|
+
* 1. `signDer(keypair.keys.privateKey, body)` over the exact UTF-8 bytes of `body`.
|
|
2505
|
+
* 2. Returns exactly `{ body: encodeRelayBody(body), stamp_header: buildStampHeader(keypair.publicKeyHex,
|
|
2506
|
+
* signatureDer), purpose }`, with those keys in that order.
|
|
2507
|
+
*
|
|
2508
|
+
* `body` is the string `buildSignRawPayloadBody` returned; it is never parsed or re-serialised here.
|
|
2509
|
+
*
|
|
2510
|
+
* @param body The activity body string to sign and forward.
|
|
2511
|
+
* @param keypair The registered keypair.
|
|
2512
|
+
* @param purpose The relay's purpose. Defaults to `"signing"`.
|
|
2513
|
+
*/
|
|
2514
|
+
async function createRelayRequest(body, keypair, purpose = "signing") {
|
|
2515
|
+
const signatureDer = await signDer(keypair.keys.privateKey, body);
|
|
2516
|
+
return {
|
|
2517
|
+
body: encodeRelayBody(body),
|
|
2518
|
+
stamp_header: buildStampHeader(keypair.publicKeyHex, signatureDer),
|
|
2519
|
+
purpose
|
|
2520
|
+
};
|
|
2521
|
+
}
|
|
2522
|
+
//#endregion
|
|
2523
|
+
//#region src/payIn/units.ts
|
|
2524
|
+
/**
|
|
2525
|
+
* A decimal amount as text: digits with an optional fraction after a `.` (`12`, `12.`, `12.5`), or a fraction alone
|
|
2526
|
+
* (`.5`). No sign, exponent, grouping or spaces.
|
|
2527
|
+
*/
|
|
2528
|
+
const DECIMAL_TEXT_PATTERN = /^(?:([0-9]+)(?:\.([0-9]*))?|\.([0-9]+))$/;
|
|
2529
|
+
/**
|
|
2530
|
+
* A run of fraction digits that are all zeros, or none.
|
|
2531
|
+
*/
|
|
2532
|
+
const ZEROS_PATTERN = /^0*$/;
|
|
2533
|
+
/**
|
|
2534
|
+
* Reads an amount in base units as the API writes it (a holding's `amount`, a leg's `input_amount`, a pay-in's
|
|
2535
|
+
* `delivered`): a decimal integer without leading zeros, which may exceed 2^53. `null` when `text` is not one. Pure.
|
|
2536
|
+
*
|
|
2537
|
+
* @example parseBaseUnits("419397733767447402007014") === 419397733767447402007014n
|
|
2538
|
+
* @example parseBaseUnits("012") === null
|
|
2539
|
+
*/
|
|
2540
|
+
function parseBaseUnits(text) {
|
|
2541
|
+
return typeof text === "string" && DECIMAL_INTEGER_PATTERN.test(text) ? BigInt(text) : null;
|
|
2542
|
+
}
|
|
2543
|
+
/**
|
|
2544
|
+
* Reads a decimal amount of a token with `decimals` decimals into its base units, exactly: `toBaseUnits("20", 6)` is
|
|
2545
|
+
* `20000000n`, the `amount` a 20 USDC.e quote sends. `null` when `text` is not a decimal amount (see the pattern above)
|
|
2546
|
+
* or names a fraction finer than one base unit: an amount is never rounded. Zeros past `decimals` are exact, so
|
|
2547
|
+
* `"1.5000000"` reads at 6 decimals. Pure.
|
|
2548
|
+
*
|
|
2549
|
+
* @example toBaseUnits("1096.08", 6) === 1096080000n
|
|
2550
|
+
* @example toBaseUnits("0.0000001", 6) === null
|
|
2551
|
+
*
|
|
2552
|
+
* @throws {TypeError} when `decimals` is not a whole number from 0 to {@link MAX_TOKEN_DECIMALS}.
|
|
2553
|
+
*/
|
|
2554
|
+
function toBaseUnits(text, decimals) {
|
|
2555
|
+
checkDecimals("toBaseUnits", decimals);
|
|
2556
|
+
if (typeof text !== "string") return null;
|
|
2557
|
+
const match = DECIMAL_TEXT_PATTERN.exec(text);
|
|
2558
|
+
if (match === null) return null;
|
|
2559
|
+
const fraction = match[2] ?? match[3] ?? "";
|
|
2560
|
+
if (!ZEROS_PATTERN.test(fraction.slice(decimals))) return null;
|
|
2561
|
+
const whole = BigInt(match[1] ?? "0");
|
|
2562
|
+
const kept = fraction.slice(0, decimals).padEnd(decimals, "0");
|
|
2563
|
+
return whole * 10n ** BigInt(decimals) + (kept === "" ? 0n : BigInt(kept));
|
|
2564
|
+
}
|
|
2565
|
+
/**
|
|
2566
|
+
* Writes base units of a token with `decimals` decimals as a decimal figure, rounded toward zero to
|
|
2567
|
+
* `maxFractionDigits` (every decimal by default) and without trailing zeros: `formatBaseUnits(20049318n, 6, 2)` is
|
|
2568
|
+
* `"20.04"`. No grouping and no symbol; the screens format it for display. A negative amount keeps its sign, unless it
|
|
2569
|
+
* rounds to zero. Pure.
|
|
2570
|
+
*
|
|
2571
|
+
* @example formatBaseUnits(1096076785n, 6) === "1096.076785"
|
|
2572
|
+
* @example formatBaseUnits(20000000n, 6) === "20"
|
|
2573
|
+
*
|
|
2574
|
+
* @throws {TypeError} when `units` is not a bigint, `decimals` is not a whole number from 0 to
|
|
2575
|
+
* {@link MAX_TOKEN_DECIMALS}, or `maxFractionDigits` is not a whole number from 0.
|
|
2576
|
+
*/
|
|
2577
|
+
function formatBaseUnits(units, decimals, maxFractionDigits = decimals) {
|
|
2578
|
+
if (typeof units !== "bigint") throw new TypeError("formatBaseUnits: units must be a bigint");
|
|
2579
|
+
checkDecimals("formatBaseUnits", decimals);
|
|
2580
|
+
if (!Number.isSafeInteger(maxFractionDigits) || maxFractionDigits < 0) throw new TypeError("formatBaseUnits: maxFractionDigits must be a whole number from 0");
|
|
2581
|
+
const magnitude = units < 0n ? -units : units;
|
|
2582
|
+
const scale = 10n ** BigInt(decimals);
|
|
2583
|
+
const fraction = (magnitude % scale).toString().padStart(decimals, "0").slice(0, Math.min(decimals, maxFractionDigits)).replace(/0+$/, "");
|
|
2584
|
+
const figure = fraction === "" ? (magnitude / scale).toString() : `${magnitude / scale}.${fraction}`;
|
|
2585
|
+
return units < 0n && figure !== "0" ? `-${figure}` : figure;
|
|
2586
|
+
}
|
|
2587
|
+
/**
|
|
2588
|
+
* Throws unless `decimals` is a whole number from 0 to {@link MAX_TOKEN_DECIMALS}.
|
|
2589
|
+
*
|
|
2590
|
+
* @throws {TypeError} naming `method` when it is not.
|
|
2591
|
+
*/
|
|
2592
|
+
function checkDecimals(method, decimals) {
|
|
2593
|
+
if (!Number.isSafeInteger(decimals) || decimals < 0 || decimals > 255) throw new TypeError(`${method}: decimals must be a whole number from 0 to 255`);
|
|
2594
|
+
}
|
|
2595
|
+
//#endregion
|
|
2596
|
+
//#region src/payIn/steps.ts
|
|
2597
|
+
/**
|
|
2598
|
+
* A hex quantity as an `evm_transaction` payload writes its value, gas and fees: `0x` and at least one hex digit.
|
|
2599
|
+
*/
|
|
2600
|
+
const HEX_QUANTITY_PATTERN = /^0x[0-9a-fA-F]+$/;
|
|
2601
|
+
/**
|
|
2602
|
+
* The selector of ERC-20 `approve(address,uint256)`, lowercase with its `0x`.
|
|
2603
|
+
*/
|
|
2604
|
+
const APPROVE_SELECTOR = "0x095ea7b3";
|
|
2605
|
+
const TRANSFER_SELECTOR = "0xa9059cbb";
|
|
2606
|
+
const TEMPO_FEE_MANAGER = "0xfeec000000000000000000000000000000000000";
|
|
2607
|
+
const SET_USER_TOKEN_SELECTOR = "0xe7897444";
|
|
2608
|
+
const TEMPO_CHAIN_HEX = "0x1079";
|
|
2609
|
+
/**
|
|
2610
|
+
* The length of ERC-20 approval or transfer calldata: `0x`, the 4-byte selector and two 32-byte words.
|
|
2611
|
+
*/
|
|
2612
|
+
const ERC20_CALLDATA_LENGTH = 138;
|
|
2613
|
+
/**
|
|
2614
|
+
* The length of `depositNative(address,bytes32)` calldata as text: `0x`, the 4-byte selector and two 32-byte words.
|
|
2615
|
+
*/
|
|
2616
|
+
const DEPOSIT_NATIVE_CALLDATA_LENGTH = 138;
|
|
2617
|
+
/**
|
|
2618
|
+
* An ABI-encoded address word as text without `0x`: 12 zero bytes (24 zero digits), then 20 bytes of address.
|
|
2619
|
+
*/
|
|
2620
|
+
const ADDRESS_WORD_PATTERN = /^0{24}[0-9a-fA-F]{40}$/;
|
|
2621
|
+
/**
|
|
2622
|
+
* {@link PERMIT2_ADDRESS} as an ABI-encoded address word: 12 zero bytes, then the address, lowercase, without `0x`.
|
|
2623
|
+
*/
|
|
2624
|
+
const PERMIT2_SPENDER_WORD = `${"0".repeat(24)}${PERMIT2_ADDRESS.slice(2).toLowerCase()}`;
|
|
2625
|
+
/**
|
|
2626
|
+
* The `primaryType` of mechanism `V`'s one step: a plain Permit2 transfer with no witness, which Stridge's relayer
|
|
2627
|
+
* sends. Checked field by field ({@link isRelayedTransfer}), since no witness binds what the signature allows.
|
|
2628
|
+
*/
|
|
2629
|
+
const RELAYED_TRANSFER_TYPE = "PermitTransferFrom";
|
|
2630
|
+
/**
|
|
2631
|
+
* The exact `types` of a {@link RELAYED_TRANSFER_TYPE} step, each list as `[name, type]` in order, as core writes them.
|
|
2632
|
+
*/
|
|
2633
|
+
const RELAYED_TRANSFER_TYPES = {
|
|
2634
|
+
EIP712Domain: [
|
|
2635
|
+
["name", "string"],
|
|
2636
|
+
["chainId", "uint256"],
|
|
2637
|
+
["verifyingContract", "address"]
|
|
2638
|
+
],
|
|
2639
|
+
[RELAYED_TRANSFER_TYPE]: [
|
|
2640
|
+
["permitted", "TokenPermissions"],
|
|
2641
|
+
["spender", "address"],
|
|
2642
|
+
["nonce", "uint256"],
|
|
2643
|
+
["deadline", "uint256"]
|
|
2644
|
+
],
|
|
2645
|
+
TokenPermissions: [["token", "address"], ["amount", "uint256"]]
|
|
2646
|
+
};
|
|
2647
|
+
/**
|
|
2648
|
+
* A `uint256` as core writes it in typed data: a decimal string with no leading zero.
|
|
2649
|
+
*/
|
|
2650
|
+
const DECIMAL_UINT_PATTERN = /^(0|[1-9][0-9]*)$/;
|
|
2651
|
+
/**
|
|
2652
|
+
* The zero EVM address, lowercase.
|
|
2653
|
+
*/
|
|
2654
|
+
const ZERO_ADDRESS = `0x${"0".repeat(40)}`;
|
|
2655
|
+
/**
|
|
2656
|
+
* The `primaryType`s of the typed-data kinds whose type alone names them (pay-in guide §6.1). `Permit` is K3 or K4
|
|
2657
|
+
* depending on its fields, so it is told apart by {@link permitKind}.
|
|
2658
|
+
*/
|
|
2659
|
+
const EIP712_KINDS = {
|
|
2660
|
+
ReceiveWithAuthorization: "K1",
|
|
2661
|
+
PermitBatchWitnessTransferFrom: "K2",
|
|
2662
|
+
PermitWitnessTransferFrom: "K2",
|
|
2663
|
+
[RELAYED_TRANSFER_TYPE]: "K2",
|
|
2664
|
+
MetaTransaction: "K5",
|
|
2665
|
+
SignedBatchedCall: "K6"
|
|
2666
|
+
};
|
|
2667
|
+
/**
|
|
2668
|
+
* The fields of an EIP-2612 `Permit` (K3), in order.
|
|
2669
|
+
*/
|
|
2670
|
+
const EIP2612_PERMIT_FIELDS = [
|
|
2671
|
+
"owner",
|
|
2672
|
+
"spender",
|
|
2673
|
+
"value",
|
|
2674
|
+
"nonce",
|
|
2675
|
+
"deadline"
|
|
2676
|
+
];
|
|
2677
|
+
/**
|
|
2678
|
+
* The fields of a DAI-style `Permit` (K4), in order.
|
|
2679
|
+
*/
|
|
2680
|
+
const DAI_PERMIT_FIELDS = [
|
|
2681
|
+
"holder",
|
|
2682
|
+
"spender",
|
|
2683
|
+
"nonce",
|
|
2684
|
+
"expiry",
|
|
2685
|
+
"allowed"
|
|
2686
|
+
];
|
|
2687
|
+
/**
|
|
2688
|
+
* Reports whether the status closes ordinary pay-in actions. Use {@link isPayInSettled} to decide when to stop polling.
|
|
2689
|
+
*/
|
|
2690
|
+
function isPayInTerminalState(state) {
|
|
2691
|
+
return PAY_IN_TERMINAL_STATES.some((terminal) => terminal === state);
|
|
2692
|
+
}
|
|
2693
|
+
/** A canceled or failed pay-in can still complete while Core supplies a late-transfer poll hint. */
|
|
2694
|
+
function isPayInSettled(read) {
|
|
2695
|
+
return read.status === "completed" || read.status === "expired" || (read.status === "canceled" || read.status === "failed") && read.poll_after_ms == null;
|
|
2696
|
+
}
|
|
2697
|
+
/**
|
|
2698
|
+
* The step to do now (pay-in guide §5.6): the entry of `steps` that `required_steps[0]` names. `null` when the pay-in
|
|
2699
|
+
* is terminal, when nothing is required (a `processing` pay-in waiting on a chain, a bridge or the drip), or when no
|
|
2700
|
+
* step has that id. Never a step from history: only `required_steps` is acted on after confirm, one step at a time and
|
|
2701
|
+
* in order, since the next step often exists only once the previous one lands. Pure.
|
|
2702
|
+
*/
|
|
2703
|
+
function nextRequiredStep(payIn) {
|
|
2704
|
+
if (isPayInTerminalState(payIn.status)) return null;
|
|
2705
|
+
const stepId = payIn.required_steps[0];
|
|
2706
|
+
if (stepId === void 0) return null;
|
|
2707
|
+
return payIn.steps.find((step) => step.id === stepId) ?? null;
|
|
2708
|
+
}
|
|
2709
|
+
/**
|
|
2710
|
+
* Names a pay-in step's kind (pay-in guide §6.1): `K8` for `solana_transaction`, `K7` for `evm_transaction`, and
|
|
2711
|
+
* for an `eip712` the kind its payload's `primaryType` names, a `Permit` told apart by its fields. `"unknown"` for any
|
|
2712
|
+
* other scheme, a typed-data type outside the list, or a `Permit` with neither field list: such a step is never
|
|
2713
|
+
* signed. The kind is for choosing the copy and the wallet call; it says nothing about whether the payload is sound,
|
|
2714
|
+
* which {@link isSignablePayInStep} checks. Pure.
|
|
2715
|
+
*/
|
|
2716
|
+
function payInStepKind(step) {
|
|
2717
|
+
if (step.scheme === "solana_transaction") return "K8";
|
|
2718
|
+
if (step.scheme === "evm_transaction") return "K7";
|
|
2719
|
+
if (step.scheme !== "eip712" || !isJsonObject(step.payload) || typeof step.payload.primaryType !== "string") return "unknown";
|
|
2720
|
+
const { primaryType } = step.payload;
|
|
2721
|
+
if (primaryType === "Permit") return permitKind(step.payload.types);
|
|
2722
|
+
return Object.hasOwn(EIP712_KINDS, primaryType) ? EIP712_KINDS[primaryType] : "unknown";
|
|
2723
|
+
}
|
|
2724
|
+
/**
|
|
2725
|
+
* The instant, in epoch milliseconds, by which every one of `steps` must be signed or sent and submitted: the earliest
|
|
2726
|
+
* of their `expires_at` and, while the pay-in is `requires_confirmation`, its own `expires_at` (the confirm
|
|
2727
|
+
* deadline); after confirm, its `deadline` when it has one instead. At quote time pass every quote step (a Solana step
|
|
2728
|
+
* lives about 40 s, the quote 60 s); after confirm, the required step.
|
|
2729
|
+
*
|
|
2730
|
+
* `null` when there is no instant at all, or one does not parse: no deadline can be proven, so treat it as passed and
|
|
2731
|
+
* sign nothing. Compare it with a server-corrected clock, less a margin for the wallet prompt. Pure.
|
|
2732
|
+
*/
|
|
2733
|
+
function earliestPayInExpiry(payIn, steps) {
|
|
2734
|
+
const instants = steps.map((step) => step.expires_at);
|
|
2735
|
+
if (payIn.status === "requires_confirmation") instants.push(payIn.expires_at);
|
|
2736
|
+
else if (typeof payIn.deadline === "string") instants.push(payIn.deadline);
|
|
2737
|
+
if (instants.length === 0) return null;
|
|
2738
|
+
const times = instants.map((instant) => typeof instant === "string" ? Date.parse(instant) : NaN);
|
|
2739
|
+
if (times.some((time) => Number.isNaN(time))) return null;
|
|
2740
|
+
return Math.min(...times);
|
|
2741
|
+
}
|
|
2742
|
+
/**
|
|
2743
|
+
* Reports whether a wallet may be asked to sign or send `step` (pay-in guide §8): its scheme is known and its payload
|
|
2744
|
+
* holds what that wallet call needs, checked by value, since a pay-in answer is read without checking any payload.
|
|
2745
|
+
* The kit runs it before every wallet prompt; a step that fails it is never signed: cancel the pay-in and report it
|
|
2746
|
+
* (§8.4). Pure.
|
|
2747
|
+
*
|
|
2748
|
+
* - `eip712` — the step is on an `eip155` chain; the payload has an object `types` whose every entry is a list of
|
|
2749
|
+
* `{ name, type }` strings and which holds `EIP712Domain` and the `primaryType`; a `primaryType` whose kind is K1 to
|
|
2750
|
+
* K6 ({@link payInStepKind}); an object `domain` and `message`; and no number anywhere that is not a safe integer.
|
|
2751
|
+
* `JSON.parse` rounds a larger number, so the payload passed to the wallet would no longer be the one core sent, and
|
|
2752
|
+
* the step is refused rather than signed altered. A K2 `PermitTransferFrom` (mechanism `V`) has exactly core's
|
|
2753
|
+
* types, domain name and field shapes ({@link isRelayedTransfer}). Permit2 is bound where the kind says it must be, any case of
|
|
2754
|
+
* {@link PERMIT2_ADDRESS} accepted: a K2 transfer's `domain.verifyingContract` is Permit2, a K3 or K4 permit's
|
|
2755
|
+
* `message.spender` is Permit2, and a K5 meta-transaction's `message.functionSignature` is
|
|
2756
|
+
* `approve(PERMIT2_ADDRESS, amount)` calldata. Core puts a signed approval on chain without the user paying gas, so
|
|
2757
|
+
* one naming any other spender is never signed.
|
|
2758
|
+
* - `evm_transaction` — `from` and `to` are EVM addresses, `data` is `0x` and whole bytes of hex, `value`, `gas`,
|
|
2759
|
+
* `max_fee_per_gas` and `max_priority_fee_per_gas` are hex quantities, `chain_id` is exactly the step's chain as
|
|
2760
|
+
* {@link evmChainHex} writes it, and the call has the shape of a Permit2 approval, Tempo fee-coin step, coin send, or wallet transfer.
|
|
2761
|
+
* A wallet transfer must also pass {@link isWalletTransfer} against its leg and destination before a prompt.
|
|
2762
|
+
*
|
|
2763
|
+
* - `solana_transaction` — a Solana CAIP-2 chain and nonempty message/fee-payer strings. The hub's lazy signer
|
|
2764
|
+
* validates the v0 message bytes, sponsor, user and instructions before the Wallet Standard prompt.
|
|
2765
|
+
*
|
|
2766
|
+
* Whether the step is the one to do now, whether its signer is the connected wallet (and a coin send's depositor and
|
|
2767
|
+
* value its leg's), and whether it has expired are the caller's to check ({@link nextRequiredStep}, {@link earliestPayInExpiry}).
|
|
2768
|
+
*/
|
|
2769
|
+
function isSignablePayInStep(step) {
|
|
2770
|
+
if (!isJsonObject(step) || !isJsonObject(step.payload) || typeof step.chain !== "string") return false;
|
|
2771
|
+
switch (step.scheme) {
|
|
2772
|
+
case "solana_transaction": return parseCaip2(step.chain)?.namespace === "solana" && typeof step.payload.message === "string" && step.payload.message.length > 0 && typeof step.payload.fee_payer === "string" && step.payload.fee_payer.length > 0;
|
|
2773
|
+
case "eip712": return isSignableEip712(step.chain, step.payload, payInStepKind(step));
|
|
2774
|
+
case "evm_transaction": return isSendableEvmTransaction(step.chain, step.payload);
|
|
2775
|
+
default: return false;
|
|
2776
|
+
}
|
|
2777
|
+
}
|
|
2778
|
+
/**
|
|
2779
|
+
* Reports whether an `evm_transaction` payload is ERC-20 `approve(PERMIT2_ADDRESS, amount)` that sends no native
|
|
2780
|
+
* value (pay-in guide §8.3, K7): `data` is the `0x095ea7b3` selector and two 32-byte words, the first of them
|
|
2781
|
+
* {@link PERMIT2_ADDRESS}, and `value` is a hex zero. Any amount passes, core asking for the max; that `to` is the leg's
|
|
2782
|
+
* source token is the caller's to check. Pure.
|
|
2783
|
+
*/
|
|
2784
|
+
function isPermit2Approval(payload) {
|
|
2785
|
+
if (!isJsonObject(payload)) return false;
|
|
2786
|
+
const { data, value } = payload;
|
|
2787
|
+
return isPermit2ApproveCalldata(data) && isHexQuantity(value) && BigInt(value) === 0n;
|
|
2788
|
+
}
|
|
2789
|
+
/**
|
|
2790
|
+
* Reads the token from a zero-value Tempo FeeManager setUserToken call, or null for any other payload.
|
|
2791
|
+
* The caller binds the token and sender to the leg and connected wallet before sending.
|
|
2792
|
+
*/
|
|
2793
|
+
function tempoFeeTokenOf(payload) {
|
|
2794
|
+
if (!isJsonObject(payload)) return null;
|
|
2795
|
+
const { chain_id, to, data, value } = payload;
|
|
2796
|
+
if (chain_id !== TEMPO_CHAIN_HEX || typeof to !== "string" || to.toLowerCase() !== TEMPO_FEE_MANAGER || typeof data !== "string" || data.slice(0, 10).toLowerCase() !== SET_USER_TOKEN_SELECTOR || !ADDRESS_WORD_PATTERN.test(data.slice(10)) || !isHexQuantity(value) || BigInt(value) !== 0n) return null;
|
|
2797
|
+
return `0x${data.slice(34).toLowerCase()}`;
|
|
2798
|
+
}
|
|
2799
|
+
/**
|
|
2800
|
+
* Reports whether an `evm_transaction` payload is a coin send (mechanism `W`): `to` is {@link RELAY_DEPOSITORY_ADDRESS}
|
|
2801
|
+
* in any case, `data` is exactly the {@link DEPOSIT_NATIVE_SELECTOR} and two 32-byte words, the first a zero-padded
|
|
2802
|
+
* address (the depositor), and `value` is a hex quantity above zero. That the depositor is the wallet and the value is
|
|
2803
|
+
* at most the leg's `input_amount` are the caller's to check. Pure.
|
|
2804
|
+
*/
|
|
2805
|
+
function isCoinSend(payload) {
|
|
2806
|
+
if (!isJsonObject(payload)) return false;
|
|
2807
|
+
const { to, data, value } = payload;
|
|
2808
|
+
return typeof to === "string" && to.toLowerCase() === "0x4cD00E387622C35bDDB9b4c962C136462338BC31".toLowerCase() && coinSendDepositor(data) !== null && isHexQuantity(value) && BigInt(value) > 0n;
|
|
2809
|
+
}
|
|
2810
|
+
/**
|
|
2811
|
+
* Whether the calldata and value have the shape of a native or ERC-20 wallet transfer.
|
|
2812
|
+
*/
|
|
2813
|
+
function isWalletTransferShape(data, value) {
|
|
2814
|
+
if (!isHexQuantity(value)) return false;
|
|
2815
|
+
if (data === "0x") return BigInt(value) > 0n;
|
|
2816
|
+
return data.length === ERC20_CALLDATA_LENGTH && data.slice(0, 10).toLowerCase() === TRANSFER_SELECTOR && CALLDATA_PATTERN.test(data) && ADDRESS_WORD_PATTERN.test(data.slice(10, 74)) && BigInt(value) === 0n;
|
|
2817
|
+
}
|
|
2818
|
+
/**
|
|
2819
|
+
* Binds an X, Y or U transfer to its leg's chain, asset and exact input, and to the pay-in's recipient. Y and U
|
|
2820
|
+
* move only ERC-20 tokens.
|
|
2821
|
+
* The caller checks the enclosing step, connected sender and reviewed destination separately.
|
|
2822
|
+
*/
|
|
2823
|
+
function isWalletTransfer(payload, leg, destination) {
|
|
2824
|
+
if (leg.mechanism !== "X" && leg.mechanism !== "Y" && leg.mechanism !== "U" || !isJsonObject(payload)) return false;
|
|
2825
|
+
const source = parseCaip19(leg.source_asset);
|
|
2826
|
+
const chain = source === null ? null : evmChainHex(source.chain);
|
|
2827
|
+
const amount = parseBaseUnits(leg.input_amount);
|
|
2828
|
+
const { to, data, value, chain_id } = payload;
|
|
2829
|
+
if (source === null || chain === null || chain_id !== chain || amount === null || amount <= 0n || !isEvmAddress(destination.address) || !isEvmAddress(to) || typeof data !== "string" || !isWalletTransferShape(data, value)) return false;
|
|
2830
|
+
if (source.assetNamespace === "slip44") return leg.mechanism === "X" && /^[0-9]+$/.test(source.assetReference) && leg.source_asset === destination.asset && data === "0x" && to.toLowerCase() === destination.address.toLowerCase() && BigInt(value) === amount;
|
|
2831
|
+
const token = source.assetReference;
|
|
2832
|
+
const target = parseCaip19(destination.asset);
|
|
2833
|
+
return source.assetNamespace === "erc20" && isEvmAddress(token) && target?.chain === source.chain && target.assetNamespace === "erc20" && isEvmAddress(target.assetReference) && token.toLowerCase() === target.assetReference.toLowerCase() && to.toLowerCase() === token.toLowerCase() && data !== "0x" && data.slice(34, 74).toLowerCase() === destination.address.slice(2).toLowerCase() && BigInt(`0x${data.slice(74)}`) === amount;
|
|
2834
|
+
}
|
|
2835
|
+
/**
|
|
2836
|
+
* The depositor a coin send's `data` names (its first word), as `0x` and 40 lowercase hex digits, or `null` when
|
|
2837
|
+
* `data` is not coin-send calldata ({@link isCoinSend}). Pure.
|
|
2838
|
+
*/
|
|
2839
|
+
function coinSendDepositor(data) {
|
|
2840
|
+
if (typeof data !== "string" || data.length !== DEPOSIT_NATIVE_CALLDATA_LENGTH || data.slice(0, 10).toLowerCase() !== "0x49290c1c" || !CALLDATA_PATTERN.test(data) || !ADDRESS_WORD_PATTERN.test(data.slice(10, 74))) return null;
|
|
2841
|
+
return `0x${data.slice(34, 74).toLowerCase()}`;
|
|
2842
|
+
}
|
|
2843
|
+
/**
|
|
2844
|
+
* Reports whether `data` is ERC-20 `approve(PERMIT2_ADDRESS, amount)` calldata, any amount: the `0x095ea7b3` selector
|
|
2845
|
+
* and two 32-byte words, the first of them {@link PERMIT2_ADDRESS}, either case. A K7 transaction's `data` and a K5
|
|
2846
|
+
* meta-transaction's `functionSignature` are both read with it.
|
|
2847
|
+
*/
|
|
2848
|
+
function isPermit2ApproveCalldata(data) {
|
|
2849
|
+
return typeof data === "string" && data.length === ERC20_CALLDATA_LENGTH && CALLDATA_PATTERN.test(data) && data.slice(0, 10).toLowerCase() === APPROVE_SELECTOR && data.slice(10, 74).toLowerCase() === PERMIT2_SPENDER_WORD;
|
|
2850
|
+
}
|
|
2851
|
+
/**
|
|
2852
|
+
* Reports whether `value` is {@link PERMIT2_ADDRESS}, in any case.
|
|
2853
|
+
*/
|
|
2854
|
+
function isPermit2Address(value) {
|
|
2855
|
+
return typeof value === "string" && value.toLowerCase() === "0x000000000022D473030F116dDEE9F6B43aC78BA3".toLowerCase();
|
|
2856
|
+
}
|
|
2857
|
+
/**
|
|
2858
|
+
* The kind of a typed-data `Permit`: K3 when `types.Permit` lists the EIP-2612 fields in order, K4 when it lists the
|
|
2859
|
+
* DAI-style ones, `"unknown"` otherwise.
|
|
2860
|
+
*/
|
|
2861
|
+
function permitKind(types) {
|
|
2862
|
+
if (!isJsonObject(types) || !Array.isArray(types.Permit)) return "unknown";
|
|
2863
|
+
const names = types.Permit.map((field) => isJsonObject(field) ? field.name : void 0);
|
|
2864
|
+
if (hasFieldNames(names, EIP2612_PERMIT_FIELDS)) return "K3";
|
|
2865
|
+
if (hasFieldNames(names, DAI_PERMIT_FIELDS)) return "K4";
|
|
2866
|
+
return "unknown";
|
|
2867
|
+
}
|
|
2868
|
+
/**
|
|
2869
|
+
* Reports whether `names` is exactly `expected`, in order.
|
|
2870
|
+
*/
|
|
2871
|
+
function hasFieldNames(names, expected) {
|
|
2872
|
+
return names.length === expected.length && expected.every((name, index) => names[index] === name);
|
|
2873
|
+
}
|
|
2874
|
+
/**
|
|
2875
|
+
* The `eip712` rule of {@link isSignablePayInStep}.
|
|
2876
|
+
*/
|
|
2877
|
+
function isSignableEip712(chain, payload, kind) {
|
|
2878
|
+
const { types, primaryType, domain, message } = payload;
|
|
2879
|
+
return evmChainHex(chain) !== null && isEip712Types(types) && Object.hasOwn(types, "EIP712Domain") && typeof primaryType === "string" && Object.hasOwn(types, primaryType) && isJsonObject(domain) && isJsonObject(message) && isTypedDataKind(kind) && bindsPermit2(kind, domain, message) && (primaryType !== RELAYED_TRANSFER_TYPE || isRelayedTransfer(types, domain, message)) && hasOnlySafeIntegers(payload);
|
|
2880
|
+
}
|
|
2881
|
+
/**
|
|
2882
|
+
* Reports whether typed data of `kind` binds Permit2 where that kind must (pay-in guide §6.1): a K2 transfer's
|
|
2883
|
+
* `domain.verifyingContract` is Permit2, a K3 or K4 permit's `message.spender` is Permit2, and a K5
|
|
2884
|
+
* meta-transaction's `message.functionSignature` approves Permit2 ({@link isPermit2ApproveCalldata}). K1 and K6 name
|
|
2885
|
+
* no Permit2 and pass; any other kind fails.
|
|
2886
|
+
*/
|
|
2887
|
+
function bindsPermit2(kind, domain, message) {
|
|
2888
|
+
switch (kind) {
|
|
2889
|
+
case "K1":
|
|
2890
|
+
case "K6": return true;
|
|
2891
|
+
case "K2": return isPermit2Address(domain.verifyingContract);
|
|
2892
|
+
case "K3":
|
|
2893
|
+
case "K4": return isPermit2Address(message.spender);
|
|
2894
|
+
case "K5": return isPermit2ApproveCalldata(message.functionSignature);
|
|
2895
|
+
default: return false;
|
|
2896
|
+
}
|
|
2897
|
+
}
|
|
2898
|
+
/**
|
|
2899
|
+
* Reports whether a `PermitTransferFrom` is exactly core's relayed transfer: `types` holds only
|
|
2900
|
+
* {@link RELAYED_TRANSFER_TYPES}, field for field and in order; the domain, the message and `permitted` hold exactly
|
|
2901
|
+
* the declared keys, so a wallet that reads the keys signs the digest core issued; the domain is named `Permit2` with
|
|
2902
|
+
* a positive number `chainId`; `permitted` is one `{ token, amount }`; `spender` is a nonzero address; and the amount,
|
|
2903
|
+
* nonce and deadline are decimal `uint256` strings.
|
|
2904
|
+
* The spender is core's relayer, which differs by environment, so it is not pinned: which token, how much and until
|
|
2905
|
+
* when are the caller's to check against the leg.
|
|
2906
|
+
*/
|
|
2907
|
+
function isRelayedTransfer(types, domain, message) {
|
|
2908
|
+
const { permitted } = message;
|
|
2909
|
+
return Object.keys(types).length === Object.keys(RELAYED_TRANSFER_TYPES).length && Object.entries(RELAYED_TRANSFER_TYPES).every(([name, fields]) => Object.hasOwn(types, name) && types[name].length === fields.length && fields.every(([field, type], index) => {
|
|
2910
|
+
const entry = types[name][index];
|
|
2911
|
+
return isJsonObject(entry) && entry.name === field && entry.type === type;
|
|
2912
|
+
})) && hasExactKeys(domain, [
|
|
2913
|
+
"name",
|
|
2914
|
+
"chainId",
|
|
2915
|
+
"verifyingContract"
|
|
2916
|
+
]) && domain.name === "Permit2" && Number.isSafeInteger(domain.chainId) && domain.chainId > 0 && hasExactKeys(message, [
|
|
2917
|
+
"permitted",
|
|
2918
|
+
"spender",
|
|
2919
|
+
"nonce",
|
|
2920
|
+
"deadline"
|
|
2921
|
+
]) && isJsonObject(permitted) && hasExactKeys(permitted, ["token", "amount"]) && isEvmAddress(permitted.token) && isDecimalUint(permitted.amount) && isEvmAddress(message.spender) && message.spender.toLowerCase() !== ZERO_ADDRESS && isDecimalUint(message.nonce) && isDecimalUint(message.deadline);
|
|
2922
|
+
}
|
|
2923
|
+
/**
|
|
2924
|
+
* Reports whether `value` has exactly the keys `keys`, in any order.
|
|
2925
|
+
*/
|
|
2926
|
+
function hasExactKeys(value, keys) {
|
|
2927
|
+
return Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
|
|
2928
|
+
}
|
|
2929
|
+
/**
|
|
2930
|
+
* Reports whether `value` is a `uint256` as a decimal string ({@link DECIMAL_UINT_PATTERN}) below 2^256.
|
|
2931
|
+
*/
|
|
2932
|
+
function isDecimalUint(value) {
|
|
2933
|
+
return typeof value === "string" && DECIMAL_UINT_PATTERN.test(value) && BigInt(value) < 2n ** 256n;
|
|
2934
|
+
}
|
|
2935
|
+
/**
|
|
2936
|
+
* Reports whether `value` is a typed-data `types` object: every entry a list of `{ name, type }` with string values.
|
|
2937
|
+
*/
|
|
2938
|
+
function isEip712Types(value) {
|
|
2939
|
+
return isJsonObject(value) && Object.values(value).every((fields) => Array.isArray(fields) && fields.every((field) => isJsonObject(field) && typeof field.name === "string" && typeof field.type === "string"));
|
|
2940
|
+
}
|
|
2941
|
+
/**
|
|
2942
|
+
* Reports whether `kind` is one the EVM wallet signs as typed data, K1 to K6.
|
|
2943
|
+
*/
|
|
2944
|
+
function isTypedDataKind(kind) {
|
|
2945
|
+
return [
|
|
2946
|
+
"K1",
|
|
2947
|
+
"K2",
|
|
2948
|
+
"K3",
|
|
2949
|
+
"K4",
|
|
2950
|
+
"K5",
|
|
2951
|
+
"K6"
|
|
2952
|
+
].includes(kind);
|
|
2953
|
+
}
|
|
2954
|
+
/**
|
|
2955
|
+
* Reports whether every number anywhere inside `root` is a safe integer. Walks with its own stack, so a deeply nested
|
|
2956
|
+
* payload cannot overflow the call stack, and visits each object once.
|
|
2957
|
+
*/
|
|
2958
|
+
function hasOnlySafeIntegers(root) {
|
|
2959
|
+
const pending = [root];
|
|
2960
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2961
|
+
while (pending.length > 0) {
|
|
2962
|
+
const value = pending.pop();
|
|
2963
|
+
if (typeof value === "number" && !Number.isSafeInteger(value)) return false;
|
|
2964
|
+
if (typeof value === "object" && value !== null && !seen.has(value)) {
|
|
2965
|
+
seen.add(value);
|
|
2966
|
+
for (const child of Object.values(value)) pending.push(child);
|
|
2967
|
+
}
|
|
2968
|
+
}
|
|
2969
|
+
return true;
|
|
2970
|
+
}
|
|
2971
|
+
/**
|
|
2972
|
+
* The `evm_transaction` rule of {@link isSignablePayInStep}.
|
|
2973
|
+
*/
|
|
2974
|
+
function isSendableEvmTransaction(chain, payload) {
|
|
2975
|
+
const chainHex = evmChainHex(chain);
|
|
2976
|
+
return chainHex !== null && payload.chain_id === chainHex && isEvmAddress(payload.from) && isEvmAddress(payload.to) && typeof payload.data === "string" && CALLDATA_PATTERN.test(payload.data) && isHexQuantity(payload.value) && isHexQuantity(payload.gas) && isHexQuantity(payload.max_fee_per_gas) && isHexQuantity(payload.max_priority_fee_per_gas) && (isPermit2Approval({
|
|
2977
|
+
data: payload.data,
|
|
2978
|
+
value: payload.value
|
|
2979
|
+
}) || isCoinSend({
|
|
2980
|
+
to: payload.to,
|
|
2981
|
+
data: payload.data,
|
|
2982
|
+
value: payload.value
|
|
2983
|
+
}) || tempoFeeTokenOf(payload) !== null || isWalletTransferShape(payload.data, payload.value));
|
|
2984
|
+
}
|
|
2985
|
+
/**
|
|
2986
|
+
* Reports whether `value` is an EVM address: `0x` and 40 hex digits, any case.
|
|
2987
|
+
*/
|
|
2988
|
+
function isEvmAddress(value) {
|
|
2989
|
+
return typeof value === "string" && EVM_ADDRESS_PATTERN.test(value);
|
|
2990
|
+
}
|
|
2991
|
+
/**
|
|
2992
|
+
* Reports whether `value` is a hex quantity: `0x` and at least one hex digit.
|
|
2993
|
+
*/
|
|
2994
|
+
function isHexQuantity(value) {
|
|
2995
|
+
return typeof value === "string" && HEX_QUANTITY_PATTERN.test(value);
|
|
2996
|
+
}
|
|
2997
|
+
//#endregion
|
|
2998
|
+
//#region src/polling/sleep.ts
|
|
2999
|
+
/**
|
|
3000
|
+
* The default `Sleep`: a `setTimeout` of `ms` (negative values count as `0`). When `signal` is already aborted it
|
|
3001
|
+
* rejects with `signal.reason` without scheduling anything; when `signal` aborts during the wait it clears the timer
|
|
3002
|
+
* and rejects with `signal.reason`. The abort listener is removed once the wait settles either way.
|
|
3003
|
+
*/
|
|
3004
|
+
function sleep(ms, signal) {
|
|
3005
|
+
return new Promise((resolve, reject) => {
|
|
3006
|
+
if (signal?.aborted) {
|
|
3007
|
+
reject(signal.reason);
|
|
3008
|
+
return;
|
|
3009
|
+
}
|
|
3010
|
+
const onAbort = () => {
|
|
3011
|
+
clearTimeout(timer);
|
|
3012
|
+
signal?.removeEventListener("abort", onAbort);
|
|
3013
|
+
reject(signal?.reason);
|
|
3014
|
+
};
|
|
3015
|
+
const timer = setTimeout(() => {
|
|
3016
|
+
signal?.removeEventListener("abort", onAbort);
|
|
3017
|
+
resolve();
|
|
3018
|
+
}, ms > 0 ? ms : 0);
|
|
3019
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3020
|
+
});
|
|
3021
|
+
}
|
|
3022
|
+
//#endregion
|
|
3023
|
+
//#region src/polling/waitForActiveWallet.ts
|
|
3024
|
+
/**
|
|
3025
|
+
* Polls `GET /wallet/v1/account` until the wallet is active, closed, or the attempts run out (guide §5, §10).
|
|
3026
|
+
* Every read counts against the session's 120-a-minute limit, which the default 1.5 s
|
|
3027
|
+
* interval keeps well under.
|
|
3028
|
+
*
|
|
3029
|
+
* Since Coordinator rc.19 nothing is polled on the normal path: verify returns the wallet, and a keypair registration
|
|
3030
|
+
* waits on the server for it to become active. Use this only for a short, bounded read (a small `maxAttempts`), such
|
|
3031
|
+
* as fetching `provider_account_ref` once after the first registration.
|
|
3032
|
+
*
|
|
3033
|
+
* The loop, for `attempt` from 1 to `maxAttempts`:
|
|
3034
|
+
*
|
|
3035
|
+
* 1. `signal?.throwIfAborted()`.
|
|
3036
|
+
* 2. `wallet = await getWallet({ signal })`. The first read happens at once.
|
|
3037
|
+
* 3. `wallet.status === "active"`, and (when `requireWalletRef`) `wallet.provider_account_ref !== ""`
|
|
3038
|
+
* → resolve `{ kind: "active", wallet }`.
|
|
3039
|
+
* 4. `wallet.status === "wound_down"` → resolve `{ kind: "wound-down", wallet }`.
|
|
3040
|
+
* 5. `attempt === maxAttempts` → resolve `{ kind: "timeout", wallet }`.
|
|
3041
|
+
* 6. `await sleep(intervalMs, signal)` and continue.
|
|
3042
|
+
*
|
|
3043
|
+
* So `getWallet` is called at most `maxAttempts` times and `sleep` at most `maxAttempts - 1` times. An active wallet
|
|
3044
|
+
* with an empty `provider_account_ref` keeps polling. Errors from `getWallet` propagate at once, without a retry. An
|
|
3045
|
+
* abort rejects with `signal.reason`.
|
|
3046
|
+
*
|
|
3047
|
+
* @throws {TypeError} (as a rejection) when `maxAttempts` is not a positive integer or `intervalMs` is negative.
|
|
3048
|
+
*/
|
|
3049
|
+
async function waitForActiveWallet(options) {
|
|
3050
|
+
const { getWallet, signal, intervalMs = 1500, maxAttempts = 80, requireWalletRef = true, sleep: sleep$2 = sleep } = options;
|
|
3051
|
+
if (!Number.isInteger(maxAttempts) || maxAttempts < 1) throw new TypeError("waitForActiveWallet: maxAttempts must be a positive integer");
|
|
3052
|
+
if (!Number.isFinite(intervalMs) || intervalMs < 0) throw new TypeError("waitForActiveWallet: intervalMs must be a non-negative finite number");
|
|
3053
|
+
for (let attempt = 1;; attempt += 1) {
|
|
3054
|
+
signal?.throwIfAborted();
|
|
3055
|
+
const wallet = await getWallet({ signal });
|
|
3056
|
+
if (wallet.status === "active" && (!requireWalletRef || wallet.provider_account_ref !== "")) return {
|
|
3057
|
+
kind: "active",
|
|
3058
|
+
wallet
|
|
3059
|
+
};
|
|
3060
|
+
if (wallet.status === "wound_down") return {
|
|
3061
|
+
kind: "wound-down",
|
|
3062
|
+
wallet
|
|
3063
|
+
};
|
|
3064
|
+
if (attempt === maxAttempts) return {
|
|
3065
|
+
kind: "timeout",
|
|
3066
|
+
wallet
|
|
3067
|
+
};
|
|
3068
|
+
await sleep$2(intervalMs, signal);
|
|
3069
|
+
}
|
|
3070
|
+
}
|
|
3071
|
+
//#endregion
|
|
3072
|
+
//#region src/polling/waitForRound.ts
|
|
3073
|
+
/**
|
|
3074
|
+
* Whether `value` is a finite number above zero.
|
|
3075
|
+
*/
|
|
3076
|
+
function isPositiveFinite(value) {
|
|
3077
|
+
return Number.isFinite(value) && value > 0;
|
|
3078
|
+
}
|
|
3079
|
+
/**
|
|
3080
|
+
* Polls `GET /wallet/v1/auth-rounds/{id}` until the round is ready, failed, or ends (guide §3.2). Only an open that answered
|
|
3081
|
+
* `202` needs it: a `200` open already carries the ready round. A `202` (`status: "opening"`) means still opening;
|
|
3082
|
+
* that includes an unknown round and a decoy, so besides `ready` and `failed` the only stop is `expires_at`.
|
|
3083
|
+
*
|
|
3084
|
+
* The loop, with `attempt` starting at 0:
|
|
3085
|
+
*
|
|
3086
|
+
* 1. `signal?.throwIfAborted()`.
|
|
3087
|
+
* 2. `round = await getRound(roundId, { signal })`. The first read happens at once, with no initial wait.
|
|
3088
|
+
* 3. `round.status === "ready"` → resolve `{ kind: "ready", round }`; `round.status === "failed"` → resolve
|
|
3089
|
+
* `{ kind: "failed" }` at once, whatever time is left.
|
|
3090
|
+
* 4. `remaining = expiresAtMs - now()`. `remaining <= 0` → resolve `{ kind: "expired" }`.
|
|
3091
|
+
* 5. `await sleep(min(initialIntervalMs * backoffFactor ** attempt, maxIntervalMs, remaining), signal)`, then
|
|
3092
|
+
* `attempt += 1` and go to 1. So with the defaults the waits are 250, 500, 1000, 1000, … ms, and the last read
|
|
3093
|
+
* lands at `expires_at`.
|
|
3094
|
+
*
|
|
3095
|
+
* Errors from `getRound` (a `SuaNetworkError`, say) propagate at once, without a retry; the caller may call again
|
|
3096
|
+
* for the same round. An abort rejects with `signal.reason`.
|
|
3097
|
+
*
|
|
3098
|
+
* Pure apart from the injected `getRound`, `sleep` and `now`.
|
|
3099
|
+
*
|
|
3100
|
+
* @throws {TypeError} (as a rejection, before the first read) when `expiresAt` does not parse with `Date.parse`,
|
|
3101
|
+
* `initialIntervalMs` or `maxIntervalMs` is not a positive finite number, or `backoffFactor` is below `1`.
|
|
3102
|
+
*/
|
|
3103
|
+
async function waitForRound(options) {
|
|
3104
|
+
const { getRound, roundId, expiresAt, signal, initialIntervalMs = 250, maxIntervalMs = 1e3, backoffFactor = 2, sleep: sleep$1 = sleep, now = Date.now } = options;
|
|
3105
|
+
const expiresAtMs = Date.parse(expiresAt);
|
|
3106
|
+
if (Number.isNaN(expiresAtMs)) throw new TypeError("waitForRound: expiresAt must be an RFC 3339 instant");
|
|
3107
|
+
if (!isPositiveFinite(initialIntervalMs)) throw new TypeError("waitForRound: initialIntervalMs must be a positive finite number");
|
|
3108
|
+
if (!isPositiveFinite(maxIntervalMs)) throw new TypeError("waitForRound: maxIntervalMs must be a positive finite number");
|
|
3109
|
+
if (!(backoffFactor >= 1)) throw new TypeError("waitForRound: backoffFactor must be at least 1");
|
|
3110
|
+
for (let attempt = 0;; attempt += 1) {
|
|
3111
|
+
signal?.throwIfAborted();
|
|
3112
|
+
const round = await getRound(roundId, { signal });
|
|
3113
|
+
if (round.status === "ready") return {
|
|
3114
|
+
kind: "ready",
|
|
3115
|
+
round
|
|
3116
|
+
};
|
|
3117
|
+
if (round.status === "failed") return { kind: "failed" };
|
|
3118
|
+
const remaining = expiresAtMs - now();
|
|
3119
|
+
if (remaining <= 0) return { kind: "expired" };
|
|
3120
|
+
await sleep$1(Math.min(initialIntervalMs * backoffFactor ** attempt, maxIntervalMs, remaining), signal);
|
|
3121
|
+
}
|
|
3122
|
+
}
|
|
3123
|
+
//#endregion
|
|
3124
|
+
//#region src/relay/buildSignRawPayloadBody.ts
|
|
3125
|
+
/**
|
|
3126
|
+
* Builds the `ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2` body for an EVM message signature (guide §7.1, §12.7): the exact
|
|
3127
|
+
* string to sign and relay, never re-serialised afterwards. Keep it: `settleRelay` compares the answer with it.
|
|
3128
|
+
*
|
|
3129
|
+
* Returns `JSON.stringify` of an object literal written in exactly this key order (a `SignRawPayloadActivityDto`):
|
|
3130
|
+
* `type: "ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2"`, `timestampMs: String(input.signedAtMs)`, `organizationId:
|
|
3131
|
+
* input.walletRef`, `parameters: { signWith: input.evmAddress, payload: toHex(input.payload), encoding:
|
|
3132
|
+
* "PAYLOAD_ENCODING_HEXADECIMAL", hashFunction: "HASH_FUNCTION_KECCAK256" }`. The payload hex is lowercase with no
|
|
3133
|
+
* `0x`; the address is kept verbatim.
|
|
3134
|
+
*
|
|
3135
|
+
* Vector (§12.7): `{ walletRef: "497b3e43-6b9d-4555-b839-5b791701aa43", evmAddress:
|
|
3136
|
+
* "0xcD27bBba88329D4Ae8CCd0A16E4cD08f11226716", payload: utf8ToBytes("stridge relay smoke test"), signedAtMs:
|
|
3137
|
+
* 1790000000000 }` returns the §12.7 body byte for byte.
|
|
3138
|
+
*
|
|
3139
|
+
* @throws {TypeError} when `walletRef` is empty, `evmAddress` is not `0x` plus 40 hex digits, `payload` is empty, or
|
|
3140
|
+
* `signedAtMs` is not a non-negative safe integer.
|
|
3141
|
+
*/
|
|
3142
|
+
function buildSignRawPayloadBody(input) {
|
|
3143
|
+
const { walletRef, evmAddress, payload, signedAtMs } = input;
|
|
3144
|
+
if (typeof walletRef !== "string" || walletRef === "") throw new TypeError("buildSignRawPayloadBody: walletRef must be a non-empty string");
|
|
3145
|
+
if (typeof evmAddress !== "string" || !EVM_ADDRESS_PATTERN.test(evmAddress)) throw new TypeError("buildSignRawPayloadBody: evmAddress must be 0x followed by 40 hex digits");
|
|
3146
|
+
if (!(payload instanceof Uint8Array) || payload.length === 0) throw new TypeError("buildSignRawPayloadBody: payload must be a non-empty Uint8Array");
|
|
3147
|
+
if (!Number.isSafeInteger(signedAtMs) || signedAtMs < 0) throw new TypeError("buildSignRawPayloadBody: signedAtMs must be a non-negative safe integer");
|
|
3148
|
+
const activity = {
|
|
3149
|
+
type: "ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2",
|
|
3150
|
+
timestampMs: String(signedAtMs),
|
|
3151
|
+
organizationId: walletRef,
|
|
3152
|
+
parameters: {
|
|
3153
|
+
signWith: evmAddress,
|
|
3154
|
+
payload: toHex(payload),
|
|
3155
|
+
encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
|
|
3156
|
+
hashFunction: "HASH_FUNCTION_KECCAK256"
|
|
3157
|
+
}
|
|
3158
|
+
};
|
|
3159
|
+
return JSON.stringify(activity);
|
|
3160
|
+
}
|
|
3161
|
+
//#endregion
|
|
3162
|
+
//#region src/relay/constants.ts
|
|
3163
|
+
/**
|
|
3164
|
+
* The EIP-191 version `0x45` ("E") prefix of a personal message, before the decimal byte length: the byte `0x19`, then
|
|
3165
|
+
* `Ethereum Signed Message:` and a line feed.
|
|
3166
|
+
*/
|
|
3167
|
+
const PERSONAL_MESSAGE_PREFIX = "Ethereum Signed Message:\n";
|
|
3168
|
+
/**
|
|
3169
|
+
* The order n of the secp256k1 group. A signature's `s` above `n / 2` is "high"; the low-s form is `n - s`.
|
|
3170
|
+
*/
|
|
3171
|
+
const SECP256K1_ORDER = 115792089237316195423570985008687907852837564279074904382605163141518161494337n;
|
|
3172
|
+
/**
|
|
3173
|
+
* r and s of a secp256k1 signature: 32 bytes as 64 hex digits, either case.
|
|
3174
|
+
*/
|
|
3175
|
+
const SCALAR_HEX_PATTERN = /^[0-9a-fA-F]{64}$/;
|
|
3176
|
+
//#endregion
|
|
3177
|
+
//#region src/relay/buildPersonalSignBody.ts
|
|
3178
|
+
/**
|
|
3179
|
+
* Builds the EIP-191 personal-message payload for a text message: the UTF-8 bytes of
|
|
3180
|
+
* `PERSONAL_MESSAGE_PREFIX + String(byteLength)` followed by the UTF-8 bytes of `message`, where `byteLength` is the
|
|
3181
|
+
* UTF-8 byte count of `message` written in decimal (`utf8ToBytes(message).length`, never `message.length`). The
|
|
3182
|
+
* message is always text: a `0x…` string is encoded as its characters.
|
|
3183
|
+
*
|
|
3184
|
+
* `keccak256` of the result equals viem's `hashMessage(message)`.
|
|
3185
|
+
*
|
|
3186
|
+
* Vectors:
|
|
3187
|
+
* - `"hello world"` → hex `19457468657265756d205369676e6564204d6573736167653a0a313168656c6c6f20776f726c64` (the
|
|
3188
|
+
* length is `11`); its keccak-256 is `d9eba16ed0ecae432b71fe008c98cc872bb4cc214d3220a36f365326cf807d68`.
|
|
3189
|
+
* - `"héllo"` has 6 UTF-8 bytes, so the length part is `"6"`.
|
|
3190
|
+
* - `"0x1234"` is 6 characters of text, so the length part is `"6"` and the bytes are `30 78 31 32 33 34`.
|
|
3191
|
+
*
|
|
3192
|
+
* @throws {TypeError} when `message` is not a non-empty string.
|
|
3193
|
+
*/
|
|
3194
|
+
function buildPersonalSignPayload(message) {
|
|
3195
|
+
if (typeof message !== "string" || message === "") throw new TypeError("buildPersonalSignPayload: message must be a non-empty string");
|
|
3196
|
+
const messageBytes = utf8ToBytes(message);
|
|
3197
|
+
const prefixBytes = utf8ToBytes(`${PERSONAL_MESSAGE_PREFIX}${String(messageBytes.length)}`);
|
|
3198
|
+
const payload = new Uint8Array(prefixBytes.length + messageBytes.length);
|
|
3199
|
+
payload.set(prefixBytes, 0);
|
|
3200
|
+
payload.set(messageBytes, prefixBytes.length);
|
|
3201
|
+
return payload;
|
|
3202
|
+
}
|
|
3203
|
+
/**
|
|
3204
|
+
* Builds the relay body for an app's `sign(message)`: the only path an app's message takes to a signature.
|
|
3205
|
+
*
|
|
3206
|
+
* 1. `payload = buildPersonalSignPayload(input.message)`.
|
|
3207
|
+
* 2. `body = buildSignRawPayloadBody({ walletRef: input.walletRef, evmAddress: input.evmAddress, payload, signedAtMs:
|
|
3208
|
+
* input.signedAtMs })`, so the body carries `PAYLOAD_ENCODING_HEXADECIMAL`, `HASH_FUNCTION_KECCAK256` and the
|
|
3209
|
+
* payload as lowercase hex without `0x`.
|
|
3210
|
+
* 3. Returns exactly `{ body, payload }`.
|
|
3211
|
+
*
|
|
3212
|
+
* Turnkey then signs `keccak256(payload)`, which is viem's `hashMessage(message)`, so the signature (after
|
|
3213
|
+
* `toEvmSignature`) is byte-identical to viem's `signMessage`.
|
|
3214
|
+
*
|
|
3215
|
+
* Vector: `{ walletRef: "497b3e43-6b9d-4555-b839-5b791701aa43", evmAddress: "0xcD27bBba88329D4Ae8CCd0A16E4cD08f11226716",
|
|
3216
|
+
* message: "hello world", signedAtMs: 1790000000000 }` gives a body whose `parameters.payload` is the
|
|
3217
|
+
* `buildPersonalSignPayload("hello world")` hex above and whose other fields match the guide's relay example body.
|
|
3218
|
+
*
|
|
3219
|
+
* @throws {TypeError} when `message` is empty or not a string, and on every input `buildSignRawPayloadBody` refuses.
|
|
3220
|
+
*/
|
|
3221
|
+
function buildPersonalSignBody(input) {
|
|
3222
|
+
const payload = buildPersonalSignPayload(input.message);
|
|
3223
|
+
return {
|
|
3224
|
+
body: buildSignRawPayloadBody({
|
|
3225
|
+
walletRef: input.walletRef,
|
|
3226
|
+
evmAddress: input.evmAddress,
|
|
3227
|
+
payload,
|
|
3228
|
+
signedAtMs: input.signedAtMs
|
|
3229
|
+
}),
|
|
3230
|
+
payload
|
|
3231
|
+
};
|
|
3232
|
+
}
|
|
3233
|
+
//#endregion
|
|
3234
|
+
//#region src/relay/decodeRelayResponse.ts
|
|
3235
|
+
/**
|
|
3236
|
+
* The only recovery ids the hub can build an EVM signature from.
|
|
3237
|
+
*/
|
|
3238
|
+
const RECOVERY_IDS = /* @__PURE__ */ new Set(["00", "01"]);
|
|
3239
|
+
/**
|
|
3240
|
+
* The only activity type this decoder reads a result for.
|
|
3241
|
+
*/
|
|
3242
|
+
const SIGN_RAW_PAYLOAD_TYPE = "ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2";
|
|
3243
|
+
/**
|
|
3244
|
+
* gRPC codes that prove Turnkey refused the request before acting on it: `INVALID_ARGUMENT` (3), `NOT_FOUND` (5),
|
|
3245
|
+
* `ALREADY_EXISTS` (6), `PERMISSION_DENIED` (7), `RESOURCE_EXHAUSTED` (8), `FAILED_PRECONDITION` (9), `OUT_OF_RANGE`
|
|
3246
|
+
* (11), `UNIMPLEMENTED` (12) and `UNAUTHENTICATED` (16). Every other code (`CANCELLED`, `UNKNOWN`,
|
|
3247
|
+
* `DEADLINE_EXCEEDED`, `ABORTED`, `INTERNAL`, `UNAVAILABLE`, `DATA_LOSS`) is what a server-side failure looks like, and
|
|
3248
|
+
* SigningRouter reads a Turnkey `5xx` as ambiguous.
|
|
3249
|
+
*/
|
|
3250
|
+
const REFUSAL_CODES = /* @__PURE__ */ new Set([
|
|
3251
|
+
3,
|
|
3252
|
+
5,
|
|
3253
|
+
6,
|
|
3254
|
+
7,
|
|
3255
|
+
8,
|
|
3256
|
+
9,
|
|
3257
|
+
11,
|
|
3258
|
+
12,
|
|
3259
|
+
16
|
|
3260
|
+
]);
|
|
3261
|
+
/**
|
|
3262
|
+
* Reads `provider_response` as a JSON object: standard base64, then strict UTF-8, then JSON. Returns `null` when any
|
|
3263
|
+
* step fails or the value is not a JSON object. Never throws.
|
|
3264
|
+
*/
|
|
3265
|
+
function readProviderObject(providerResponse) {
|
|
3266
|
+
if (typeof providerResponse !== "string" || providerResponse === "") return null;
|
|
3267
|
+
try {
|
|
3268
|
+
const parsed = JSON.parse(bytesToUtf8(fromBase64(providerResponse)));
|
|
3269
|
+
return isJsonObject(parsed) ? parsed : null;
|
|
3270
|
+
} catch {
|
|
3271
|
+
return null;
|
|
3272
|
+
}
|
|
3273
|
+
}
|
|
3274
|
+
/**
|
|
3275
|
+
* Parses the signed body string back into the fields the answer must echo, or `null` when it is not a
|
|
3276
|
+
* `SignRawPayloadActivityDto` JSON with string fields. Never throws.
|
|
3277
|
+
*/
|
|
3278
|
+
function readSignedBody(signedBody) {
|
|
3279
|
+
if (typeof signedBody !== "string") return null;
|
|
3280
|
+
let parsed;
|
|
3281
|
+
try {
|
|
3282
|
+
parsed = JSON.parse(signedBody);
|
|
3283
|
+
} catch {
|
|
3284
|
+
return null;
|
|
3285
|
+
}
|
|
3286
|
+
if (!isJsonObject(parsed) || !isJsonObject(parsed.parameters)) return null;
|
|
3287
|
+
const fields = {
|
|
3288
|
+
type: parsed.type,
|
|
3289
|
+
organizationId: parsed.organizationId,
|
|
3290
|
+
signWith: parsed.parameters.signWith,
|
|
3291
|
+
payload: parsed.parameters.payload,
|
|
3292
|
+
encoding: parsed.parameters.encoding,
|
|
3293
|
+
hashFunction: parsed.parameters.hashFunction
|
|
3294
|
+
};
|
|
3295
|
+
const strings = {};
|
|
3296
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
3297
|
+
if (typeof value !== "string") return null;
|
|
3298
|
+
strings[key] = value;
|
|
3299
|
+
}
|
|
3300
|
+
return strings;
|
|
3301
|
+
}
|
|
3302
|
+
/**
|
|
3303
|
+
* Whether two values are the same string, ignoring ASCII case (an address's checksum case, a hex payload's case).
|
|
3304
|
+
*/
|
|
3305
|
+
function sameIgnoringCase(actual, expected) {
|
|
3306
|
+
return typeof actual === "string" && actual.toLowerCase() === expected.toLowerCase();
|
|
3307
|
+
}
|
|
3308
|
+
/**
|
|
3309
|
+
* Whether a completed activity is the one that was signed: the same type (a raw-payload signature), organization,
|
|
3310
|
+
* address, payload, encoding and hash function. The address and the payload hex compare without case; everything
|
|
3311
|
+
* else compares exactly.
|
|
3312
|
+
*/
|
|
3313
|
+
function activityMatchesSignedBody(activity, signedBody) {
|
|
3314
|
+
const expected = readSignedBody(signedBody);
|
|
3315
|
+
if (expected === null || expected.type !== SIGN_RAW_PAYLOAD_TYPE) return false;
|
|
3316
|
+
const intent = isJsonObject(activity.intent) ? activity.intent.signRawPayloadIntentV2 : void 0;
|
|
3317
|
+
if (!isJsonObject(intent)) return false;
|
|
3318
|
+
return activity.type === expected.type && activity.organizationId === expected.organizationId && sameIgnoringCase(intent.signWith, expected.signWith) && sameIgnoringCase(intent.payload, expected.payload) && intent.encoding === expected.encoding && intent.hashFunction === expected.hashFunction;
|
|
3319
|
+
}
|
|
3320
|
+
/**
|
|
3321
|
+
* The relay's verdicts this decoder reads.
|
|
3322
|
+
*/
|
|
3323
|
+
const VERDICTS = /* @__PURE__ */ new Set([
|
|
3324
|
+
"signed",
|
|
3325
|
+
"rejected",
|
|
3326
|
+
"partially_approved",
|
|
3327
|
+
"ambiguous"
|
|
3328
|
+
]);
|
|
3329
|
+
/**
|
|
3330
|
+
* Decodes a relay's `200` or `202` answer into its outcome (guide §7.4). A `200` is not proof of a signature.
|
|
3331
|
+
*
|
|
3332
|
+
* A response that carries the key `verdict` (rc.55's `RelayResult`) is read by the relay's verdict first, before any
|
|
3333
|
+
* guess from the provider's bytes:
|
|
3334
|
+
*
|
|
3335
|
+
* - `ambiguous` → `unknown` with cause `ambiguous`, whatever the bytes hold: the request may have reached the
|
|
3336
|
+
* provider, so it is never a refusal.
|
|
3337
|
+
* - `partially_approved` → `cosignature`, with `activity_ref`.
|
|
3338
|
+
* - `rejected` → `refused`, with the error body's numeric `code` and string `message` when the bytes hold them, else
|
|
3339
|
+
* `providerCode: null` and `providerMessage: ""`.
|
|
3340
|
+
* - `signed` → steps 3 to 8 below, except that an error body (step 4) is `unknown` with cause `provider-error`,
|
|
3341
|
+
* never `refused`.
|
|
3342
|
+
* - any other value → `unknown` with cause `unreadable`.
|
|
3343
|
+
*
|
|
3344
|
+
* A response with no `verdict` (an older Coordinator) runs every step, and the first that matches wins:
|
|
3345
|
+
*
|
|
3346
|
+
* 1. `response` is not an object → `unknown` with cause `unreadable`.
|
|
3347
|
+
* 2. `root_activity` is a non-null object → `cosignature`.
|
|
3348
|
+
* 3. `provider_response` is `null`, `""`, not standard base64 (`fromBase64`), not UTF-8 (`bytesToUtf8`), not JSON, or
|
|
3349
|
+
* not a JSON object → `unknown` with cause `unreadable`.
|
|
3350
|
+
* 4. The object has no `activity` key, or `activity` is not a JSON object: Turnkey's error body. Its `code` is one of
|
|
3351
|
+
* the client-error gRPC codes (3, 5, 6, 7, 8, 9, 11, 12, 16) → `refused`, with `providerCode` and
|
|
3352
|
+
* `providerMessage` (its `message` when a string, else `""`). Any other code, or none → `unknown` with cause
|
|
3353
|
+
* `provider-error`, since SigningRouter reads a Turnkey `5xx` as ambiguous and an older Coordinator drops that
|
|
3354
|
+
* verdict.
|
|
3355
|
+
* 5. `activity.status !== "ACTIVITY_STATUS_COMPLETED"` → `unknown` with cause `status` and `activityStatus` (the
|
|
3356
|
+
* status when a string, else `null`).
|
|
3357
|
+
* 6. The activity is not the one in `signedBody`: its `type` is not `ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2`, its
|
|
3358
|
+
* `organizationId` differs, or `intent.signRawPayloadIntentV2` is missing or differs in `signWith`, `payload` (both
|
|
3359
|
+
* without case), `encoding` or `hashFunction` → `unknown` with cause `mismatch`.
|
|
3360
|
+
* 7. `activity.result.signRawPayloadResult` has `r` and `s` of 64 hex digits and `v` exactly `"00"` or `"01"` →
|
|
3361
|
+
* `signed`, with `r` and `s` lowercased. Any other `v` (`"1b"`, `"02"`, `"0"`, a number) is refused here: the hub
|
|
3362
|
+
* can only build an EVM signature from those two recovery ids.
|
|
3363
|
+
* 8. Otherwise → `unknown` with cause `unreadable`.
|
|
3364
|
+
*
|
|
3365
|
+
* `activityRef` is `response.activity_ref` when it is a string, else `""`; `activityStatus` is `null` except in step
|
|
3366
|
+
* 5. Does not recover the signer from the signature: the caller still checks it against the wallet's address. Pure;
|
|
3367
|
+
* never throws.
|
|
3368
|
+
*
|
|
3369
|
+
* Vectors (§12.7): with the §12.7 body as `signedBody`, the "Response `200`" body is `signed` with r
|
|
3370
|
+
* `3f1c8a9e…0b2d4f6a`, s `5e2a7c9e…9b1d3f5a`, v `00` and activityRef `01a0e31a-743d-7894-9edc-e00e87805a51`; the
|
|
3371
|
+
* "waiting for a second approval" body is `cosignature` even though its decoded activity says `COMPLETED`.
|
|
3372
|
+
*
|
|
3373
|
+
* @param response The relay's `200` or `202` body.
|
|
3374
|
+
* @param signedBody The exact activity body string that was signed and relayed (`buildSignRawPayloadBody`'s result).
|
|
3375
|
+
*/
|
|
3376
|
+
function decodeRelayResponse(response, signedBody) {
|
|
3377
|
+
if (!isJsonObject(response)) return {
|
|
3378
|
+
kind: "unknown",
|
|
3379
|
+
cause: "unreadable",
|
|
3380
|
+
activityRef: "",
|
|
3381
|
+
activityStatus: null
|
|
3382
|
+
};
|
|
3383
|
+
const activityRef = typeof response.activity_ref === "string" ? response.activity_ref : "";
|
|
3384
|
+
const hasVerdict = Object.hasOwn(response, "verdict");
|
|
3385
|
+
const verdict = response.verdict;
|
|
3386
|
+
if (hasVerdict) {
|
|
3387
|
+
if (!VERDICTS.has(verdict)) return {
|
|
3388
|
+
kind: "unknown",
|
|
3389
|
+
cause: "unreadable",
|
|
3390
|
+
activityRef,
|
|
3391
|
+
activityStatus: null
|
|
3392
|
+
};
|
|
3393
|
+
if (verdict === "ambiguous") return {
|
|
3394
|
+
kind: "unknown",
|
|
3395
|
+
cause: "ambiguous",
|
|
3396
|
+
activityRef,
|
|
3397
|
+
activityStatus: null
|
|
3398
|
+
};
|
|
3399
|
+
if (verdict === "partially_approved") return {
|
|
3400
|
+
kind: "cosignature",
|
|
3401
|
+
activityRef
|
|
3402
|
+
};
|
|
3403
|
+
if (verdict === "rejected") {
|
|
3404
|
+
const body = readProviderObject(response.provider_response);
|
|
3405
|
+
const code = body?.code;
|
|
3406
|
+
const message = body?.message;
|
|
3407
|
+
return {
|
|
3408
|
+
kind: "refused",
|
|
3409
|
+
activityRef,
|
|
3410
|
+
providerCode: typeof code === "number" ? code : null,
|
|
3411
|
+
providerMessage: typeof message === "string" ? message : ""
|
|
3412
|
+
};
|
|
3413
|
+
}
|
|
3414
|
+
} else {
|
|
3415
|
+
const rootActivity = response.root_activity;
|
|
3416
|
+
if (typeof rootActivity === "object" && rootActivity !== null) return {
|
|
3417
|
+
kind: "cosignature",
|
|
3418
|
+
activityRef
|
|
3419
|
+
};
|
|
3420
|
+
}
|
|
3421
|
+
const provider = readProviderObject(response.provider_response);
|
|
3422
|
+
if (provider === null) return {
|
|
3423
|
+
kind: "unknown",
|
|
3424
|
+
cause: "unreadable",
|
|
3425
|
+
activityRef,
|
|
3426
|
+
activityStatus: null
|
|
3427
|
+
};
|
|
3428
|
+
const activity = provider.activity;
|
|
3429
|
+
if (!isJsonObject(activity)) {
|
|
3430
|
+
const { code, message } = provider;
|
|
3431
|
+
if (hasVerdict || typeof code !== "number" || !REFUSAL_CODES.has(code)) return {
|
|
3432
|
+
kind: "unknown",
|
|
3433
|
+
cause: "provider-error",
|
|
3434
|
+
activityRef,
|
|
3435
|
+
activityStatus: null
|
|
3436
|
+
};
|
|
3437
|
+
return {
|
|
3438
|
+
kind: "refused",
|
|
3439
|
+
activityRef,
|
|
3440
|
+
providerCode: code,
|
|
3441
|
+
providerMessage: typeof message === "string" ? message : ""
|
|
3442
|
+
};
|
|
3443
|
+
}
|
|
3444
|
+
const status = activity.status;
|
|
3445
|
+
if (status !== "ACTIVITY_STATUS_COMPLETED") return {
|
|
3446
|
+
kind: "unknown",
|
|
3447
|
+
cause: "status",
|
|
3448
|
+
activityRef,
|
|
3449
|
+
activityStatus: typeof status === "string" ? status : null
|
|
3450
|
+
};
|
|
3451
|
+
if (!activityMatchesSignedBody(activity, signedBody)) return {
|
|
3452
|
+
kind: "unknown",
|
|
3453
|
+
cause: "mismatch",
|
|
3454
|
+
activityRef,
|
|
3455
|
+
activityStatus: null
|
|
3456
|
+
};
|
|
3457
|
+
const result = activity.result;
|
|
3458
|
+
const signature = isJsonObject(result) ? result.signRawPayloadResult : void 0;
|
|
3459
|
+
if (!isJsonObject(signature)) return {
|
|
3460
|
+
kind: "unknown",
|
|
3461
|
+
cause: "unreadable",
|
|
3462
|
+
activityRef,
|
|
3463
|
+
activityStatus: null
|
|
3464
|
+
};
|
|
3465
|
+
const { r, s, v } = signature;
|
|
3466
|
+
if (typeof r !== "string" || typeof s !== "string" || typeof v !== "string" || !SCALAR_HEX_PATTERN.test(r) || !SCALAR_HEX_PATTERN.test(s) || !RECOVERY_IDS.has(v)) return {
|
|
3467
|
+
kind: "unknown",
|
|
3468
|
+
cause: "unreadable",
|
|
3469
|
+
activityRef,
|
|
3470
|
+
activityStatus: null
|
|
3471
|
+
};
|
|
3472
|
+
return {
|
|
3473
|
+
kind: "signed",
|
|
3474
|
+
r: r.toLowerCase(),
|
|
3475
|
+
s: s.toLowerCase(),
|
|
3476
|
+
v,
|
|
3477
|
+
activityRef
|
|
3478
|
+
};
|
|
3479
|
+
}
|
|
3480
|
+
//#endregion
|
|
3481
|
+
//#region src/relay/settleRelay.ts
|
|
3482
|
+
/**
|
|
3483
|
+
* Sends a relay once and settles it into a {@link RelayResult}, folding in the outcomes that arrive as thrown errors.
|
|
3484
|
+
* Typical use: `settleRelay(() => client.relay(request), body)`, where `body` is the string that was signed.
|
|
3485
|
+
*
|
|
3486
|
+
* - `send` resolves → `decodeRelayResponse(response, signedBody)`.
|
|
3487
|
+
* - `send` rejects with a `SuaNetworkError` (`isSuaNetworkError`, so a copy from a second bundle counts) → `{ kind:
|
|
3488
|
+
* "unknown", cause: "network", activityRef: "", activityStatus: null }`.
|
|
3489
|
+
* - `send` rejects with a `SuaError` (`isSuaError`) whose `code` is `"ambiguous"` → `unknown` with cause
|
|
3490
|
+
* `ambiguous`.
|
|
3491
|
+
* - A `SuaError` with a `2xx` status (an unusable body: empty, not JSON, not an object, or a `204`) → `unknown` with
|
|
3492
|
+
* cause `unreadable`: the Coordinator answered success, so the request may have been signed.
|
|
3493
|
+
* - A `SuaError` with any status outside `4xx`, notably a `5xx` with or without the Coordinator's envelope → `unknown`
|
|
3494
|
+
* with cause `server`. A proxy in front of the Coordinator (nginx, Cloudflare, the hub proxy) can answer
|
|
3495
|
+
* `502`, `504` or `524` after the stamp was forwarded, and the Coordinator's own `500` can follow a provider call.
|
|
3496
|
+
* - Any other rejection is rethrown unchanged: a `4xx` `SuaError` (`401 CREDENTIAL_EXPIRED`, `409
|
|
3497
|
+
* WALLET_NOT_ACTIVE`, `429`, a proxy's `413`, …) is a refusal before anything reached the provider, and an abort is
|
|
3498
|
+
* the caller's.
|
|
3499
|
+
*
|
|
3500
|
+
* Calls `send` exactly once and never retries.
|
|
3501
|
+
*
|
|
3502
|
+
* @param send Sends the relay, typically `client.relay`.
|
|
3503
|
+
* @param signedBody The exact activity body string that was signed (`buildSignRawPayloadBody`'s result). A completed
|
|
3504
|
+
* activity that does not echo it settles as `unknown` with cause `mismatch`.
|
|
3505
|
+
*/
|
|
3506
|
+
async function settleRelay(send, signedBody) {
|
|
3507
|
+
let response;
|
|
3508
|
+
try {
|
|
3509
|
+
response = await send();
|
|
3510
|
+
} catch (error) {
|
|
3511
|
+
if (isSuaNetworkError(error)) return {
|
|
3512
|
+
kind: "unknown",
|
|
3513
|
+
cause: "network",
|
|
3514
|
+
activityRef: "",
|
|
3515
|
+
activityStatus: null
|
|
3516
|
+
};
|
|
3517
|
+
if (!isSuaError(error)) throw error;
|
|
3518
|
+
if (error.code === "ambiguous") return {
|
|
3519
|
+
kind: "unknown",
|
|
3520
|
+
cause: "ambiguous",
|
|
3521
|
+
activityRef: "",
|
|
3522
|
+
activityStatus: null
|
|
3523
|
+
};
|
|
3524
|
+
if (error.status >= 200 && error.status < 300) return {
|
|
3525
|
+
kind: "unknown",
|
|
3526
|
+
cause: "unreadable",
|
|
3527
|
+
activityRef: "",
|
|
3528
|
+
activityStatus: null
|
|
3529
|
+
};
|
|
3530
|
+
if (error.status < 400 || error.status >= 500) return {
|
|
3531
|
+
kind: "unknown",
|
|
3532
|
+
cause: "server",
|
|
3533
|
+
activityRef: "",
|
|
3534
|
+
activityStatus: null
|
|
3535
|
+
};
|
|
3536
|
+
throw error;
|
|
3537
|
+
}
|
|
3538
|
+
return decodeRelayResponse(response, signedBody);
|
|
3539
|
+
}
|
|
3540
|
+
//#endregion
|
|
3541
|
+
//#region src/relay/toEvmSignature.ts
|
|
3542
|
+
/**
|
|
3543
|
+
* The length of r or s as hex digits.
|
|
3544
|
+
*/
|
|
3545
|
+
const SCALAR_HEX_LENGTH = 64;
|
|
3546
|
+
/**
|
|
3547
|
+
* Half the secp256k1 order: an `s` above it is high.
|
|
3548
|
+
*/
|
|
3549
|
+
const HALF_ORDER = SECP256K1_ORDER / 2n;
|
|
3550
|
+
/**
|
|
3551
|
+
* What EVM adds to a recovery id to form `v` (27 or 28).
|
|
3552
|
+
*/
|
|
3553
|
+
const EVM_RECOVERY_OFFSET = 27;
|
|
3554
|
+
/**
|
|
3555
|
+
* Turns Turnkey's raw-payload result into the 65-byte EVM signature an app receives:
|
|
3556
|
+
* `0x` ‖ r ‖ s ‖ (27 + v), as 132 lowercase characters.
|
|
3557
|
+
*
|
|
3558
|
+
* 1. Refuses anything but `r` and `s` of exactly 64 hex digits (either case) and `v` exactly `"00"` or `"01"`.
|
|
3559
|
+
* 2. Low-s: when `BigInt("0x" + s) > SECP256K1_ORDER / 2n`, replaces `s` with `SECP256K1_ORDER - s` (left-padded to 64
|
|
3560
|
+
* hex digits) and flips the recovery id (`0` ↔ `1`). A signature with `s` exactly `n / 2` or below is kept.
|
|
3561
|
+
* 3. Returns `"0x" + r.toLowerCase() + s.toLowerCase() + (27 + v).toString(16)`, so v is `1b` or `1c`.
|
|
3562
|
+
*
|
|
3563
|
+
* The caller recovers the signer from the **raw** `r`, `s`, `v` first and only then calls this; the output recovers to
|
|
3564
|
+
* the same address because flipping v compensates for negating s.
|
|
3565
|
+
*
|
|
3566
|
+
* Vectors:
|
|
3567
|
+
* - The guide's relay result (r `3f1c8a9e…0b2d4f6a`, s `5e2a7c9e…9b1d3f5a`, v `"00"`) has a low s, so the output is
|
|
3568
|
+
* `0x3f1c8a9e…0b2d4f6a5e2a7c9e…9b1d3f5a1b`.
|
|
3569
|
+
* - s = `SECP256K1_ORDER - 1` with v `"00"` becomes s = `…0001` (63 zeros, then `1`) with v `1c`.
|
|
3570
|
+
* - s = `SECP256K1_ORDER / 2n` exactly is not high: kept, v unchanged.
|
|
3571
|
+
*
|
|
3572
|
+
* @throws {TypeError} when `r`, `s` or `v` breaks rule 1.
|
|
3573
|
+
*/
|
|
3574
|
+
function toEvmSignature(r, s, v) {
|
|
3575
|
+
if (typeof r !== "string" || !SCALAR_HEX_PATTERN.test(r)) throw new TypeError("toEvmSignature: r must be 64 hex digits");
|
|
3576
|
+
if (typeof s !== "string" || !SCALAR_HEX_PATTERN.test(s)) throw new TypeError("toEvmSignature: s must be 64 hex digits");
|
|
3577
|
+
if (v !== "00" && v !== "01") throw new TypeError("toEvmSignature: v must be \"00\" or \"01\"");
|
|
3578
|
+
let sHex = s.toLowerCase();
|
|
3579
|
+
let recoveryId = v === "01" ? 1 : 0;
|
|
3580
|
+
const sValue = BigInt(`0x${sHex}`);
|
|
3581
|
+
if (sValue > HALF_ORDER) {
|
|
3582
|
+
sHex = (SECP256K1_ORDER - sValue).toString(16).padStart(SCALAR_HEX_LENGTH, "0");
|
|
3583
|
+
recoveryId = 1 - recoveryId;
|
|
3584
|
+
}
|
|
3585
|
+
return `0x${r.toLowerCase()}${sHex}${(EVM_RECOVERY_OFFSET + recoveryId).toString(16)}`;
|
|
3586
|
+
}
|
|
3587
|
+
//#endregion
|
|
3588
|
+
//#region src/time/constants.ts
|
|
3589
|
+
/**
|
|
3590
|
+
* How many recent samples the server clock keeps. Its offset is their median.
|
|
3591
|
+
*/
|
|
3592
|
+
const SERVER_CLOCK_WINDOW = 5;
|
|
3593
|
+
/**
|
|
3594
|
+
* How close, in ms, the first two samples must agree before their offset is applied. One sample alone never moves
|
|
3595
|
+
* the offset.
|
|
3596
|
+
*/
|
|
3597
|
+
const SERVER_CLOCK_AGREEMENT_MS = 2e3;
|
|
3598
|
+
/**
|
|
3599
|
+
* The longest round trip, in ms, a sample may have. A slower answer says too little about when the server wrote its
|
|
3600
|
+
* time, so it is discarded.
|
|
3601
|
+
*/
|
|
3602
|
+
const SERVER_CLOCK_MAX_ROUND_TRIP_MS = 5e3;
|
|
3603
|
+
/**
|
|
3604
|
+
* The smallest offset, in ms, the server clock applies. `Date` has whole-second resolution, so a smaller offset is
|
|
3605
|
+
* noise and counts as 0.
|
|
3606
|
+
*/
|
|
3607
|
+
const SERVER_CLOCK_MIN_OFFSET_MS = 1e3;
|
|
3608
|
+
//#endregion
|
|
3609
|
+
//#region src/time/createServerClock.ts
|
|
3610
|
+
/**
|
|
3611
|
+
* Whether a sample can be used: three finite times and a round trip from 0 to
|
|
3612
|
+
* {@link SERVER_CLOCK_MAX_ROUND_TRIP_MS} inclusive. A negative round trip means the device's clock moved during the
|
|
3613
|
+
* request.
|
|
3614
|
+
*/
|
|
3615
|
+
function isUsableSample(sample) {
|
|
3616
|
+
const { serverTimeMs, sentAtMs, receivedAtMs } = sample;
|
|
3617
|
+
if (!Number.isFinite(serverTimeMs) || !Number.isFinite(sentAtMs) || !Number.isFinite(receivedAtMs)) return false;
|
|
3618
|
+
const roundTripMs = receivedAtMs - sentAtMs;
|
|
3619
|
+
return roundTripMs >= 0 && roundTripMs <= 5e3;
|
|
3620
|
+
}
|
|
3621
|
+
/**
|
|
3622
|
+
* The middle value of a non-empty list; the mean of the two middle values when its length is even.
|
|
3623
|
+
*/
|
|
3624
|
+
function median(values) {
|
|
3625
|
+
const sorted = [...values].sort((left, right) => left - right);
|
|
3626
|
+
const middle = Math.floor(sorted.length / 2);
|
|
3627
|
+
if (sorted.length % 2 === 1) return sorted[middle] ?? 0;
|
|
3628
|
+
return ((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2;
|
|
3629
|
+
}
|
|
3630
|
+
/**
|
|
3631
|
+
* The offset the window yields: `0` with fewer than two samples, and with exactly two that differ by more than
|
|
3632
|
+
* {@link SERVER_CLOCK_AGREEMENT_MS}; otherwise their median, rounded to a whole ms, and `0` when that is smaller in
|
|
3633
|
+
* size than {@link SERVER_CLOCK_MIN_OFFSET_MS}.
|
|
3634
|
+
*/
|
|
3635
|
+
function resolveOffset(offsets) {
|
|
3636
|
+
if (offsets.length < 2) return 0;
|
|
3637
|
+
const [first = 0, second = 0] = offsets;
|
|
3638
|
+
if (offsets.length === 2 && Math.abs(first - second) > 2e3) return 0;
|
|
3639
|
+
const offset = Math.round(median(offsets));
|
|
3640
|
+
return Math.abs(offset) < 1e3 ? 0 : offset;
|
|
3641
|
+
}
|
|
3642
|
+
/**
|
|
3643
|
+
* Creates a {@link ServerClock}: the device's clock corrected by its offset from the server's, learnt from the
|
|
3644
|
+
* samples passed to `record` (the Coordinator client's `onServerTime`).
|
|
3645
|
+
*
|
|
3646
|
+
* - **A sample's offset** is `serverTimeMs` minus the midpoint of `sentAtMs` and `receivedAtMs`.
|
|
3647
|
+
* - **Discarded samples.** One with a non-finite time, a negative round trip, or a round trip longer than
|
|
3648
|
+
* {@link SERVER_CLOCK_MAX_ROUND_TRIP_MS} (too uncertain) is ignored.
|
|
3649
|
+
* - **The offset** is the median of the last {@link SERVER_CLOCK_WINDOW} kept samples. One sample alone never moves
|
|
3650
|
+
* it; two move it only when they agree within {@link SERVER_CLOCK_AGREEMENT_MS}; from three on, the median ignores a
|
|
3651
|
+
* lone outlier.
|
|
3652
|
+
* - **The floor.** An offset smaller in size than {@link SERVER_CLOCK_MIN_OFFSET_MS} counts as 0, since `Date` has
|
|
3653
|
+
* whole-second resolution.
|
|
3654
|
+
* - **Memory only.** Nothing is stored: a new clock (a reload) starts again at 0.
|
|
3655
|
+
*
|
|
3656
|
+
* Durations (sleeps, timeouts, polling intervals, the sign confirm's dwell) stay on the device's clock; this clock is
|
|
3657
|
+
* only for comparing the device's time with a time the server wrote.
|
|
3658
|
+
*/
|
|
3659
|
+
function createServerClock(options = {}) {
|
|
3660
|
+
const deviceClock = options.deviceClock ?? Date.now;
|
|
3661
|
+
const offsets = [];
|
|
3662
|
+
let offsetMs = 0;
|
|
3663
|
+
return {
|
|
3664
|
+
now: () => deviceClock() + offsetMs,
|
|
3665
|
+
offsetMs: () => offsetMs,
|
|
3666
|
+
record(sample) {
|
|
3667
|
+
if (!isUsableSample(sample)) return;
|
|
3668
|
+
offsets.push(sample.serverTimeMs - (sample.sentAtMs + sample.receivedAtMs) / 2);
|
|
3669
|
+
if (offsets.length > 5) offsets.shift();
|
|
3670
|
+
offsetMs = resolveOffset(offsets);
|
|
3671
|
+
}
|
|
3672
|
+
};
|
|
3673
|
+
}
|
|
3674
|
+
//#endregion
|
|
3675
|
+
export { APP_HEADER, APP_ID_PATTERN, CSRF_HEADER, CsrfStoreError, DEPOSIT_NATIVE_SELECTOR, EVM_ADDRESS_PATTERN, EVM_CAIP_NAMESPACE, GUEST_COOKIE_ACCESS_HEADER, HUB_API_PREFIXES, HUB_BUILD_ID_PATTERN, HUB_CSRF_COOKIE_NAME, HUB_FRAME_NAME_PATTERN, HUB_GUEST_COOKIE_NAME, HUB_NEEDS_POPUP_MESSAGE, HUB_PARTITIONED_GUEST_COOKIE_NAME, HUB_SURFACE_ELEMENT, HUB_SURFACE_POPUP, HUB_URL_PARAMS, IDEMPOTENCY_HEADER, KEYPAIR_ALGORITHM, MAX_ACCOUNT_EMAIL_LEASE_MS, MAX_ACCOUNT_EMAIL_LENGTH, MAX_ACCOUNT_IDENTITY_LENGTH, MAX_APP_ORIGIN_LENGTH, MAX_ELEMENT_BLOCK_SIZE, MAX_ELEMENT_LABEL_LENGTH, MAX_ELEMENT_RESIZE_DURATION_MS, MAX_ERROR_MESSAGE_LENGTH, MAX_EXTERNAL_WALLET_NAME_LENGTH, MAX_HUB_BALANCE_AMOUNT_LENGTH, MAX_HUB_BUILD_ID_LENGTH, MAX_IDEMPOTENCY_KEY_LENGTH, MAX_MENU_RECT_VALUE, MAX_MESSAGE_ID_LENGTH, MAX_PAGE_URL_LENGTH, MAX_PAY_AMOUNT, MAX_PAY_ITEM_LENGTH, MAX_PAY_PAYOUT_ADDRESS_LENGTH, MAX_PAY_SOURCE_FUNDS_WALLETS, MAX_RELAY_STATE_EXPIRY_LENGTH, MAX_ROUTE_LIST_LIMIT, MAX_SIGN_MESSAGE_BYTES, MAX_TOKEN_DECIMALS, MAX_WALLET_CAPABILITY_CHAINS, PAY_AMOUNT_PATTERN, PAY_API_PREFIX, PAY_CURRENCIES, PAY_DESTINATION_ASSET_PATTERN, PAY_DESTINATION_RULE_PATTERN, PAY_ELEMENT_FAILURE_CODES, PAY_ELEMENT_LIFETIME_MESSAGE_TYPES, PAY_ELEMENT_LOAD_FAILURE_REASONS, PAY_ELEMENT_MESSAGE_TYPES, PAY_ELEMENT_NOTIFICATION_MESSAGE_TYPES, PAY_ELEMENT_PATH, PAY_FIRST_STEPS, PAY_FUND_MESSAGE_TYPES, PAY_FUND_REQUEST_TYPE, PAY_FUND_START_SCREENS, PAY_HUB_FRAME_MESSAGE_TYPES, PAY_IN_DRIP_STATES, PAY_IN_LEG_STATES, PAY_IN_MECHANISMS, PAY_IN_PHASES, PAY_IN_SHAPES, PAY_IN_STATES, PAY_IN_STEP_KINDS, PAY_IN_STEP_SCHEMES, PAY_IN_STEP_STATUSES, PAY_IN_TERMINAL_STATES, PAY_IN_UNSPENDABLE_REASONS, PAY_JOBS, PAY_MESSAGE_TYPES, PAY_PROTOCOL, PERMIT2_ADDRESS, PERSONAL_MESSAGE_PREFIX, RELAY_DEPOSITORY_ADDRESS, ROUTE_SOURCE_CHAIN_ID, ROUTE_STATES, ROUTE_STEP_ROLES, SECP256K1_ORDER, SERVER_CLOCK_AGREEMENT_MS, SERVER_CLOCK_MAX_ROUND_TRIP_MS, SERVER_CLOCK_MIN_OFFSET_MS, SERVER_CLOCK_WINDOW, SESSION_HEADER, SESSION_HEADER_OMIT, SIGNATURE_ALGORITHM, STAMP_HEADER_NAME, STAMP_LOGIN_ACTIVITY_TYPE, STAMP_LOGIN_EXPIRATION_SECONDS, STAMP_SCHEME, SUA_ACCOUNT_EMAIL_MESSAGE_TYPES, SUA_APP_WINDOW_MESSAGE_TYPES, SUA_ELEMENT_GEOMETRY_EASINGS, SUA_ELEMENT_RELOAD_REASONS, SUA_FUND_WINDOW_MESSAGE_TYPE, SUA_GUEST_HANDOFF_MESSAGE_TYPE, SUA_LINK_C_ID_SEPARATOR, SUA_LINK_C_MESSAGE_TYPES, SUA_LINK_C_STREAM_PREFIXES, SUA_PAY_REQUEST_TYPE, SUA_PROTOCOL_VERSION, SUA_REASONS, SUA_RELAY_CONTROL_MESSAGE_TYPES, SUA_RELAY_MESSAGE_TYPES, SUA_WINDOW_CANCEL_CAUSES, SUA_WINDOW_END_CAUSES, SuaError, SuaNetworkError, UPSTREAM_DATE_HEADER, WALLET_API_PREFIX, answersPayAmount, buildPersonalSignBody, buildPersonalSignPayload, buildSignRawPayloadBody, buildStamp, buildStampHeader, buildStampLogin, bytesToUtf8, coinSendDepositor, comparePayAmounts, compressPublicKey, createCoordinatorClient, createHubSuaEnvelope as createPayEnvelope, createRegisterKeypairRequest, createRelayRequest, createServerClock, decodeAppElementMessage, decodeAppHubFrameMessage, decodeAppMessage, decodeAppWindowAccountEmailMessage, decodeAppWindowAccountEmailRefreshMessage, decodeAppWindowAccountEmailRefreshReplyMessage, decodeAppWindowHubMessage, decodeElementHubMessage, decodeElementMessage, decodeElementWindowMessage, decodeHubElementMessage, decodeHubFrameAppMessage, decodeHubMessage, decodeRelayAccountEmailMessage, decodeRelayResponse, decodeWindowAccountEmailMessage, decodeWindowElementMessage, derSignatureToRaw, earliestPayInExpiry, encodeRelayBody, evmChainHex, evmChainNumber, formatBaseUnits, fromBase64, fromBase64Url, fromHex, generateKeypair, isAppElementMessage, isAppHubFrameMessage, isAppMessage, isAppWindowHubMessage, isAppearance, isAssetListDto, isCheckoutResolutionDto, isCoinSend, isCsrfStoreError, isElementCheckoutResultPayload, isElementDepositRequestPayload, isElementHubMessage, isElementMessage, isElementPaidPayload, isElementPayRequestAckPayload, isElementPayRequestPayload, isElementWindowMessage, isErrorEnvelopeDto, isExternalBalancesDto, isHubBuildId, isHubElementMessage, isHubFrameAppMessage, isHubFrameName, isHubMessage, isPayInDto, isPayInSettled, isPayInStateDto, isPayInTerminalState, isPermit2Approval, isRouteDto, isRouteListDto, isRouteQuoteDto, isRouteStateDto, isSignablePayInStep, isSuaEnvelope, isSuaError, isSuaNetworkError, isWalletTransfer, isWindowElementMessage, keypairFromKeys, nextRequiredStep, parseBaseUnits, parseCaip19, parseCaip2, parseSuaError, payInStepKind, payJobOf, rawSignatureToDer, sameLegacyPayDestinationAsk, samePayDestinationAsk, samePayTerms, settleRelay, signDer, signRaw, sleep, stampAttested, tempoFeeTokenOf, toBase64, toBase64Url, toBaseUnits, toEvmSignature, toHex, toSuaError, utf8ToBytes, waitForActiveWallet, waitForRound };
|
|
3676
|
+
|
|
3677
|
+
//# sourceMappingURL=coordinator.js.map
|