@chipi-stack/backend 14.4.0 → 14.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,11 +1,654 @@
1
- import { isValidApiKey, ChipiAuthError, STARKNET_NETWORKS, API_VERSIONING, validateErrorResponse, ChipiApiError, handleApiError, WALLET_RPC_ENDPOINTS, WALLET_CLASS_HASHES, API_ENDPOINTS, ChipiTransactionError, getWalletTypeFromClassHash, formatAmount, SKU_CONTRACTS, CARRIER_IDS, SERVICE_TYPES, ChipiSessionError, SESSION_ERRORS, SESSION_DEFAULTS, SESSION_ENTRYPOINTS, CONTRACT_ADDRESSES, TOKEN_DECIMALS } from '@chipi-stack/shared';
1
+ import { shortString, hash, CallData, ec, RpcProvider, Account, num, CairoCustomEnum, CairoOption, CairoOptionVariant, cairo, typedData, uint256 } from 'starknet';
2
+ import { SHHH_KIND_GAS_OVERHEAD, isValidApiKey, ChipiAuthError, STARKNET_NETWORKS, API_VERSIONING, validateErrorResponse, ChipiApiError, handleApiError, getWalletTypeFromClassHash, WALLET_CLASS_HASHES, WALLET_RPC_ENDPOINTS, SHHH_VERIFIER_CLASS_HASHES, API_ENDPOINTS, ChipiTransactionError, formatAmount, SKU_CONTRACTS, CARRIER_IDS, SERVICE_TYPES, ChipiSessionError, SESSION_ERRORS, SESSION_DEFAULTS, SESSION_ENTRYPOINTS, CONTRACT_ADDRESSES, TOKEN_DECIMALS } from '@chipi-stack/shared';
2
3
  import CryptoES from 'crypto-es';
3
- import { RpcProvider, ec, hash, Account, num, CairoCustomEnum, CairoOption, CairoOptionVariant, CallData, cairo, typedData, uint256 } from 'starknet';
4
+ import { randomBytes } from 'crypto';
4
5
  import { STARKNET_CONTRACTS, Chain } from '@chipi-stack/types';
5
6
  export { Chain, ChainToken, Currency } from '@chipi-stack/types';
6
7
  import { buildX402TypedData } from '@chipi-stack/core';
7
8
 
8
- // src/chipi-sdk.ts
9
+ var __defProp = Object.defineProperty;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __esm = (fn, res) => function __init() {
12
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
13
+ };
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ function poseidon(values) {
19
+ const felts = values.map((v) => typeof v === "bigint" ? "0x" + v.toString(16) : v);
20
+ return BigInt(hash.computePoseidonHashOnElements(felts));
21
+ }
22
+ function ownerCommitment(kindTag, pubkey) {
23
+ return poseidon([kindTag, ...pubkey]);
24
+ }
25
+ function computeAddressSalt(primaryKind, pubkey) {
26
+ if (pubkey.length === 0) {
27
+ throw new Error(
28
+ "computeAddressSalt: pubkey must contain at least one felt \u2014 empty signer material is rejected to prevent silent address mismatch."
29
+ );
30
+ }
31
+ const kindTag = BigInt(shortString.encodeShortString(primaryKind));
32
+ const pubkeyHash = ownerCommitment(kindTag, pubkey);
33
+ return poseidon([kindTag, pubkeyHash]);
34
+ }
35
+ function computeShhhAddress(input) {
36
+ const {
37
+ classHash,
38
+ primaryKind,
39
+ pubkey,
40
+ verifierClassHash,
41
+ label = "primary",
42
+ deployerAddress = 0n
43
+ } = input;
44
+ const salt = computeAddressSalt(primaryKind, pubkey);
45
+ const kindTag = BigInt(shortString.encodeShortString(primaryKind));
46
+ const labelFelt = BigInt(shortString.encodeShortString(label));
47
+ const ctor = [
48
+ kindTag,
49
+ verifierClassHash,
50
+ BigInt(pubkey.length),
51
+ ...pubkey,
52
+ labelFelt
53
+ ];
54
+ const addressHex = hash.calculateContractAddressFromHash(
55
+ "0x" + salt.toString(16),
56
+ "0x" + classHash.toString(16),
57
+ ctor.map((x) => typeof x === "bigint" ? "0x" + x.toString(16) : x),
58
+ "0x" + deployerAddress.toString(16)
59
+ );
60
+ return BigInt(addressHex);
61
+ }
62
+ var init_compute_wallet_address = __esm({
63
+ "src/shhh/compute-wallet-address.ts"() {
64
+ }
65
+ });
66
+ function computeISignerId() {
67
+ return BigInt(hash.starknetKeccak(ISIGNER_CANONICAL_LABEL));
68
+ }
69
+ function toBigInt(x) {
70
+ if (typeof x === "bigint") return x;
71
+ if (typeof x === "number") return BigInt(x);
72
+ return BigInt(x);
73
+ }
74
+ function poseidonSpan(values) {
75
+ const felts = values.map((v) => typeof v === "bigint" ? "0x" + v.toString(16) : v);
76
+ return BigInt(hash.computePoseidonHashOnElements(felts));
77
+ }
78
+ function hashCall(call) {
79
+ const calldataFelts = CallData.toHex(
80
+ Array.isArray(call.calldata) ? call.calldata : [call.calldata]
81
+ );
82
+ const calldataItems = calldataFelts.map((x) => BigInt(x));
83
+ const calldataHash = poseidonSpan(calldataItems);
84
+ return poseidonSpan([
85
+ CALL_TYPE_HASH_REV1,
86
+ toBigInt(call.contractAddress),
87
+ toBigInt(hash.getSelectorFromName(call.entrypoint)),
88
+ calldataHash
89
+ ]);
90
+ }
91
+ function hashCalls(calls) {
92
+ const callHashes = calls.map(hashCall);
93
+ return poseidonSpan(callHashes);
94
+ }
95
+ function hashStarknetDomain(chainIdFelt) {
96
+ return poseidonSpan([
97
+ STARKNET_DOMAIN_TYPE_HASH_REV1,
98
+ BigInt(OE_DOMAIN_NAME),
99
+ OE_DOMAIN_VERSION,
100
+ toBigInt(chainIdFelt),
101
+ OE_DOMAIN_REVISION
102
+ ]);
103
+ }
104
+ function hashOutsideExecutionStruct(oe) {
105
+ const callsArrayHash = hashCalls(oe.calls);
106
+ return poseidonSpan([
107
+ OUTSIDE_EXECUTION_TYPE_HASH_REV1,
108
+ toBigInt(oe.caller),
109
+ toBigInt(oe.nonce),
110
+ oe.execute_after,
111
+ oe.execute_before,
112
+ callsArrayHash
113
+ ]);
114
+ }
115
+ function computeSnip12Hash(oe, contractAddress, chainIdFelt) {
116
+ const domainHash = hashStarknetDomain(chainIdFelt);
117
+ const structHash = hashOutsideExecutionStruct(oe);
118
+ return poseidonSpan([
119
+ BigInt(STARKNET_MESSAGE_PREFIX),
120
+ domainHash,
121
+ toBigInt(contractAddress),
122
+ structHash
123
+ ]);
124
+ }
125
+ function snip12HashToHexAsciiBytes(h) {
126
+ const hex = h.toString(16).padStart(64, "0");
127
+ return new TextEncoder().encode(hex);
128
+ }
129
+ var OUTSIDE_EXECUTION_TYPE_HASH_REV1, CALL_TYPE_HASH_REV1, STARKNET_DOMAIN_TYPE_HASH_REV1, STARKNET_MESSAGE_PREFIX, OE_DOMAIN_NAME, OE_DOMAIN_VERSION, OE_DOMAIN_REVISION, SIG_VERSION_V1_HEX_ASCII, SIG_VERSION_V2_SNIP12, SIG_VERSION_V2_THRESHOLD, ISRC9_V2_ID, ISIGNER_ID, ISIGNER_CANONICAL_LABEL;
130
+ var init_snip12_hash = __esm({
131
+ "src/shhh/snip12-hash.ts"() {
132
+ OUTSIDE_EXECUTION_TYPE_HASH_REV1 = 0x5a4b49e17039355cd95d1f0981d75901191d1319b1f4b05a9a791d218d7e0cn;
133
+ CALL_TYPE_HASH_REV1 = 0x3635c7f2a7ba93844c0d064e18e487f35ab90f7c39d00f186a781fc3f0c2ca9n;
134
+ STARKNET_DOMAIN_TYPE_HASH_REV1 = 0x1ff2f602e42168014d405a94f75e8a93d640751d71d16311266e140d8b0a210n;
135
+ STARKNET_MESSAGE_PREFIX = shortString.encodeShortString("StarkNet Message");
136
+ OE_DOMAIN_NAME = shortString.encodeShortString("Account.execute_from_outside");
137
+ OE_DOMAIN_VERSION = 2n;
138
+ OE_DOMAIN_REVISION = 1n;
139
+ SIG_VERSION_V1_HEX_ASCII = shortString.encodeShortString("V1_HEX_ASCII");
140
+ SIG_VERSION_V2_SNIP12 = shortString.encodeShortString("V2_SNIP12");
141
+ SIG_VERSION_V2_THRESHOLD = shortString.encodeShortString("V2_THRESHOLD");
142
+ ISRC9_V2_ID = BigInt(
143
+ "0x1d1144bb2138366ff28d8e9ab57456b1d332ac42196230c3a602003c89872"
144
+ );
145
+ ISIGNER_ID = BigInt(
146
+ "0x94c5a761f34b25a4e603c651ac0e1fc4fad9cdb5517f7fa1bb54044c7e5ef8"
147
+ );
148
+ ISIGNER_CANONICAL_LABEL = "ISigner_V1";
149
+ }
150
+ });
151
+ function assertValidV2Snip12Envelope(envelope) {
152
+ if (envelope.length < 2) {
153
+ throw new Error(
154
+ `THRESH: inner envelope must have at least 2 felts (tag + owner_id); got ${envelope.length}`
155
+ );
156
+ }
157
+ const tag = envelope[0];
158
+ if (tag !== V2_SNIP12_TAG) {
159
+ if (tag === V2_THRESHOLD_TAG) {
160
+ throw new Error(
161
+ "THRESH: nested threshold envelopes are not allowed; inner envelopes must be V2_SNIP12"
162
+ );
163
+ }
164
+ const decoded = _tryDecodeShortString(tag);
165
+ throw new Error(
166
+ `THRESH: inner envelope tag must be V2_SNIP12; got ${decoded ?? "0x" + tag.toString(16)}`
167
+ );
168
+ }
169
+ return envelope[1];
170
+ }
171
+ function _tryDecodeShortString(felt) {
172
+ try {
173
+ return shortString.decodeShortString("0x" + felt.toString(16));
174
+ } catch {
175
+ return null;
176
+ }
177
+ }
178
+ function buildThresholdEnvelope(args) {
179
+ const { innerEnvelopes } = args;
180
+ if (innerEnvelopes.length < MIN_THRESHOLD_OWNERS) {
181
+ throw new Error(
182
+ `THRESH: need at least ${MIN_THRESHOLD_OWNERS} inner envelopes; got ${innerEnvelopes.length}. Use wrap_v2_snip12_envelope for single-owner OEs.`
183
+ );
184
+ }
185
+ const seenOwners = /* @__PURE__ */ new Set();
186
+ const out = [V2_THRESHOLD_TAG, BigInt(innerEnvelopes.length)];
187
+ for (let i = 0; i < innerEnvelopes.length; i++) {
188
+ const env = innerEnvelopes[i];
189
+ const ownerId = assertValidV2Snip12Envelope(env);
190
+ const key = ownerId.toString();
191
+ if (seenOwners.has(key)) {
192
+ throw new Error(
193
+ `THRESH: duplicate owner_id ${"0x" + ownerId.toString(16)} at inner envelope ${i}`
194
+ );
195
+ }
196
+ seenOwners.add(key);
197
+ out.push(BigInt(env.length));
198
+ for (const felt of env) {
199
+ if (felt < 0n) {
200
+ throw new RangeError(
201
+ `THRESH: envelope ${i} contains negative felt (cannot serialize as felt252)`
202
+ );
203
+ }
204
+ out.push(felt);
205
+ }
206
+ }
207
+ return out;
208
+ }
209
+ function parseThresholdEnvelope(envelope) {
210
+ if (envelope.length < 2) {
211
+ throw new Error(`THRESH: envelope too short (need at least [tag, n]); got ${envelope.length}`);
212
+ }
213
+ if (envelope[0] !== V2_THRESHOLD_TAG) {
214
+ throw new Error(`THRESH: envelope tag must be V2_THRESHOLD; got 0x${envelope[0].toString(16)}`);
215
+ }
216
+ const n = Number(envelope[1]);
217
+ if (!Number.isInteger(n) || n < MIN_THRESHOLD_OWNERS) {
218
+ throw new Error(`THRESH: n must be an integer >= ${MIN_THRESHOLD_OWNERS}; got ${envelope[1]}`);
219
+ }
220
+ const seenOwners = /* @__PURE__ */ new Set();
221
+ const innerEnvelopes = [];
222
+ let cursor = 2;
223
+ for (let i = 0; i < n; i++) {
224
+ if (cursor >= envelope.length) {
225
+ throw new Error(`THRESH: envelope truncated at inner ${i} (no length felt)`);
226
+ }
227
+ const envLen = Number(envelope[cursor]);
228
+ cursor += 1;
229
+ if (!Number.isInteger(envLen) || envLen < 2) {
230
+ throw new Error(`THRESH: inner ${i} env_len must be >= 2; got ${envLen}`);
231
+ }
232
+ if (cursor + envLen > envelope.length) {
233
+ throw new Error(
234
+ `THRESH: inner ${i} would overflow envelope (env_len ${envLen}, cursor ${cursor}, total ${envelope.length})`
235
+ );
236
+ }
237
+ const inner = envelope.slice(cursor, cursor + envLen);
238
+ for (const felt of inner) {
239
+ if (felt < 0n) {
240
+ throw new RangeError(
241
+ `THRESH: inner ${i} contains negative felt (cannot serialize as felt252)`
242
+ );
243
+ }
244
+ }
245
+ const ownerId = assertValidV2Snip12Envelope(inner);
246
+ const key = ownerId.toString();
247
+ if (seenOwners.has(key)) {
248
+ throw new Error(
249
+ `THRESH: duplicate owner_id ${"0x" + ownerId.toString(16)} at inner envelope ${i}`
250
+ );
251
+ }
252
+ seenOwners.add(key);
253
+ innerEnvelopes.push(inner);
254
+ cursor += envLen;
255
+ }
256
+ if (cursor !== envelope.length) {
257
+ throw new Error(
258
+ `THRESH: trailing bytes after inner ${n - 1} (cursor ${cursor}, length ${envelope.length})`
259
+ );
260
+ }
261
+ return { innerEnvelopes };
262
+ }
263
+ function estimateThresholdGasOverhead(owners) {
264
+ if (owners.length < MIN_THRESHOLD_OWNERS) {
265
+ throw new Error(
266
+ `THRESH: need at least ${MIN_THRESHOLD_OWNERS} owners to estimate threshold gas; got ${owners.length}`
267
+ );
268
+ }
269
+ let total = 0;
270
+ for (const { signerKind } of owners) {
271
+ const overhead = SHHH_KIND_GAS_OVERHEAD[signerKind];
272
+ if (overhead === void 0) {
273
+ throw new Error(
274
+ `THRESH: unknown signer kind ${signerKind} \u2014 missing from SHHH_KIND_GAS_OVERHEAD`
275
+ );
276
+ }
277
+ total += overhead;
278
+ }
279
+ return total;
280
+ }
281
+ var V2_SNIP12_TAG, V2_THRESHOLD_TAG, MIN_THRESHOLD_OWNERS;
282
+ var init_threshold = __esm({
283
+ "src/shhh/threshold.ts"() {
284
+ init_snip12_hash();
285
+ V2_SNIP12_TAG = BigInt(SIG_VERSION_V2_SNIP12);
286
+ V2_THRESHOLD_TAG = BigInt(SIG_VERSION_V2_THRESHOLD);
287
+ MIN_THRESHOLD_OWNERS = 2;
288
+ }
289
+ });
290
+
291
+ // src/shhh/oe.ts
292
+ var oe_exports = {};
293
+ __export(oe_exports, {
294
+ ANY_CALLER_FELT: () => ANY_CALLER_FELT,
295
+ MAX_OE_VALIDITY_WINDOW_SECONDS: () => MAX_OE_VALIDITY_WINDOW_SECONDS,
296
+ OE_EXECUTE_AFTER_CLOCK_SKEW_BUFFER: () => OE_EXECUTE_AFTER_CLOCK_SKEW_BUFFER,
297
+ buildOutsideExecution: () => buildOutsideExecution,
298
+ computeOeHash: () => computeOeHash,
299
+ wrapV2Snip12Envelope: () => wrapV2Snip12Envelope,
300
+ wrapV2ThresholdEnvelope: () => wrapV2ThresholdEnvelope
301
+ });
302
+ function buildOutsideExecution(params) {
303
+ const nowSec = BigInt(Math.floor(Date.now() / 1e3));
304
+ const after = params.executeAfter ?? nowSec - BigInt(OE_EXECUTE_AFTER_CLOCK_SKEW_BUFFER);
305
+ const before = params.executeBefore ?? nowSec + BigInt(MAX_OE_VALIDITY_WINDOW_SECONDS) - BigInt(OE_EXECUTE_AFTER_CLOCK_SKEW_BUFFER);
306
+ if (before <= after) {
307
+ throw new Error(
308
+ `executeBefore (${before}) must be strictly greater than executeAfter (${after}).`
309
+ );
310
+ }
311
+ if (before - after > BigInt(MAX_OE_VALIDITY_WINDOW_SECONDS)) {
312
+ throw new Error(
313
+ `OE validity window ${before - after}s exceeds max ${MAX_OE_VALIDITY_WINDOW_SECONDS}s (audit M-2). Adjust executeBefore.`
314
+ );
315
+ }
316
+ return {
317
+ caller: params.caller ?? ANY_CALLER_FELT,
318
+ nonce: params.nonce,
319
+ execute_after: after,
320
+ execute_before: before,
321
+ calls: params.calls
322
+ };
323
+ }
324
+ function computeOeHash(oe, accountAddress, chainId) {
325
+ return computeSnip12Hash(oe, accountAddress, chainId);
326
+ }
327
+ function wrapV2Snip12Envelope(params) {
328
+ const tag = typeof params.kindTag === "bigint" ? params.kindTag : BigInt(shortString.encodeShortString(params.kindTag));
329
+ return [
330
+ BigInt(SIG_VERSION_V2_SNIP12),
331
+ params.ownerId,
332
+ tag,
333
+ ...params.payload.map((v) => typeof v === "bigint" ? v : BigInt(v))
334
+ ];
335
+ }
336
+ function wrapV2ThresholdEnvelope(innerEnvelopes) {
337
+ return buildThresholdEnvelope({ innerEnvelopes });
338
+ }
339
+ var ANY_CALLER_FELT, MAX_OE_VALIDITY_WINDOW_SECONDS, OE_EXECUTE_AFTER_CLOCK_SKEW_BUFFER;
340
+ var init_oe = __esm({
341
+ "src/shhh/oe.ts"() {
342
+ init_snip12_hash();
343
+ init_threshold();
344
+ ANY_CALLER_FELT = BigInt(shortString.encodeShortString("ANY_CALLER"));
345
+ MAX_OE_VALIDITY_WINDOW_SECONDS = 2 * 60 * 60;
346
+ OE_EXECUTE_AFTER_CLOCK_SKEW_BUFFER = 60;
347
+ }
348
+ });
349
+ async function ensureGaragaInit() {
350
+ if (garagaInitPromise) return garagaInitPromise;
351
+ const attempt = (async () => {
352
+ const garaga = await import('garaga');
353
+ await garaga.init();
354
+ return garaga;
355
+ })();
356
+ garagaInitPromise = attempt;
357
+ try {
358
+ return await attempt;
359
+ } catch (err) {
360
+ if (garagaInitPromise === attempt) garagaInitPromise = null;
361
+ throw err;
362
+ }
363
+ }
364
+ function bytesToLeU256(bytes) {
365
+ if (bytes.length !== 32) {
366
+ throw new Error(`Ed25519 value must be exactly 32 bytes; got ${bytes.length}.`);
367
+ }
368
+ let low = 0n;
369
+ let high = 0n;
370
+ for (let i = 0; i < 16; i++) low += BigInt(bytes[i]) << BigInt(8 * i);
371
+ for (let i = 0; i < 16; i++) high += BigInt(bytes[16 + i]) << BigInt(8 * i);
372
+ return { low, high };
373
+ }
374
+ function bytesToLeBigInt(bytes) {
375
+ let x = 0n;
376
+ for (let i = bytes.length - 1; i >= 0; i--) x = x << 8n | BigInt(bytes[i]);
377
+ return x;
378
+ }
379
+ function ed25519SignedBytes(messageHash) {
380
+ return snip12HashToHexAsciiBytes(messageHash);
381
+ }
382
+ function ed25519OwnerId(publicKey) {
383
+ const { low, high } = bytesToLeU256(publicKey);
384
+ return ownerCommitment(ED25519_KIND_TAG_FELT, [low, high]);
385
+ }
386
+ function ed25519PubkeyFelts(publicKey) {
387
+ const { low, high } = bytesToLeU256(publicKey);
388
+ return [low, high];
389
+ }
390
+ async function buildEd25519Envelope(params) {
391
+ const ownerIndex = params.ownerIndex ?? 0n;
392
+ if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
393
+ throw new Error(
394
+ `buildEd25519Envelope: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32). owner_id is the u32 INDEX into the wallet's owner_set (0 for primary, 1 for second, etc.); do NOT pass an owner_commitment or pubkey here.`
395
+ );
396
+ }
397
+ if (params.privateKey.length !== 32) {
398
+ throw new Error(
399
+ `Ed25519 private key must be exactly 32 bytes; got ${params.privateKey.length}.`
400
+ );
401
+ }
402
+ const ed = await import('@noble/ed25519');
403
+ const publicKey = await ed.getPublicKeyAsync(params.privateKey);
404
+ const signedBytes = ed25519SignedBytes(params.messageHash);
405
+ const signature = await ed.signAsync(signedBytes, params.privateKey);
406
+ return assembleEd25519Envelope({
407
+ R: signature.slice(0, 32),
408
+ s: signature.slice(32, 64),
409
+ publicKey,
410
+ signedBytes,
411
+ ownerIndex
412
+ });
413
+ }
414
+ async function buildEd25519EnvelopeFromSignature(params) {
415
+ const ownerIndex = params.ownerIndex ?? 0n;
416
+ if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
417
+ throw new Error(
418
+ `buildEd25519EnvelopeFromSignature: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32). owner_id is the u32 INDEX into the wallet's owner_set (0 for primary); do NOT pass an owner_commitment or pubkey here.`
419
+ );
420
+ }
421
+ if (params.signature.length !== 64) {
422
+ throw new Error(
423
+ `Ed25519 signature must be exactly 64 bytes (R\u2016s); got ${params.signature.length}.`
424
+ );
425
+ }
426
+ if (params.publicKey.length !== 32) {
427
+ throw new Error(`Ed25519 public key must be exactly 32 bytes; got ${params.publicKey.length}.`);
428
+ }
429
+ const signedBytes = ed25519SignedBytes(params.messageHash);
430
+ return assembleEd25519Envelope({
431
+ R: params.signature.slice(0, 32),
432
+ s: params.signature.slice(32, 64),
433
+ publicKey: params.publicKey,
434
+ signedBytes,
435
+ ownerIndex
436
+ });
437
+ }
438
+ async function assembleEd25519Envelope(parts) {
439
+ const garaga = await ensureGaragaInit();
440
+ const payload = garaga.eddsaCalldataBuilder(
441
+ bytesToLeBigInt(parts.R),
442
+ bytesToLeBigInt(parts.s),
443
+ bytesToLeBigInt(parts.publicKey),
444
+ parts.signedBytes,
445
+ false
446
+ );
447
+ return wrapV2Snip12Envelope({
448
+ ownerId: parts.ownerIndex,
449
+ kindTag: ED25519_KIND_TAG,
450
+ payload
451
+ });
452
+ }
453
+ var ED25519_KIND_TAG, ED25519_KIND_TAG_FELT, garagaInitPromise;
454
+ var init_ed25519 = __esm({
455
+ "src/shhh/signers/ed25519.ts"() {
456
+ init_compute_wallet_address();
457
+ init_oe();
458
+ init_snip12_hash();
459
+ ED25519_KIND_TAG = "ED25519";
460
+ ED25519_KIND_TAG_FELT = BigInt(shortString.encodeShortString(ED25519_KIND_TAG));
461
+ garagaInitPromise = null;
462
+ }
463
+ });
464
+ var encryptPrivateKey, decryptPrivateKey;
465
+ var init_encryption = __esm({
466
+ "src/lib/encryption.ts"() {
467
+ encryptPrivateKey = (privateKey, password) => {
468
+ if (!privateKey || !password) {
469
+ throw new Error("Private key and password are required");
470
+ }
471
+ return CryptoES.AES.encrypt(privateKey, password).toString();
472
+ };
473
+ decryptPrivateKey = (encryptedPrivateKey, password) => {
474
+ if (!encryptedPrivateKey || !password) {
475
+ throw new Error("Encrypted private key and password are required");
476
+ }
477
+ try {
478
+ const bytes = CryptoES.AES.decrypt(encryptedPrivateKey, password);
479
+ const decrypted = bytes.toString(CryptoES.enc.Utf8);
480
+ if (!decrypted) {
481
+ throw new Error("Decryption resulted in empty string");
482
+ }
483
+ return decrypted;
484
+ } catch (error) {
485
+ if (error instanceof Error) {
486
+ throw error;
487
+ }
488
+ throw new Error(`Decryption failed: ${error}`);
489
+ }
490
+ };
491
+ }
492
+ });
493
+
494
+ // src/encryption.ts
495
+ var init_encryption2 = __esm({
496
+ "src/encryption.ts"() {
497
+ init_encryption();
498
+ }
499
+ });
500
+ function buildStarkEnvelope(params) {
501
+ const pkHex = "0x" + (typeof params.privateKey === "bigint" ? params.privateKey : BigInt(params.privateKey)).toString(16).padStart(64, "0");
502
+ const sig = ec.starkCurve.sign("0x" + params.messageHash.toString(16), pkHex);
503
+ const r = BigInt("0x" + sig.r.toString(16));
504
+ const s = BigInt("0x" + sig.s.toString(16));
505
+ const ownerIndex = params.ownerIndex ?? 0n;
506
+ if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
507
+ throw new Error(
508
+ `buildStarkEnvelope: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32). owner_id is the u32 INDEX into the wallet's owner_set (0 for primary, 1 for second, etc.); do NOT pass an owner_commitment or pubkey here.`
509
+ );
510
+ }
511
+ return wrapV2Snip12Envelope({
512
+ ownerId: ownerIndex,
513
+ kindTag: STARK_KIND_TAG,
514
+ payload: [r, s]
515
+ });
516
+ }
517
+ function starkOwnerId(starkPubKey) {
518
+ return ownerCommitment(STARK_KIND_TAG_FELT, [starkPubKey]);
519
+ }
520
+ function starkPubkeyFelts(starkPubKey) {
521
+ return [typeof starkPubKey === "bigint" ? starkPubKey : BigInt(starkPubKey)];
522
+ }
523
+ var STARK_KIND_TAG, STARK_KIND_TAG_FELT;
524
+ var init_stark = __esm({
525
+ "src/shhh/signers/stark.ts"() {
526
+ init_compute_wallet_address();
527
+ init_oe();
528
+ STARK_KIND_TAG = "STARK";
529
+ STARK_KIND_TAG_FELT = BigInt(shortString.encodeShortString(STARK_KIND_TAG));
530
+ }
531
+ });
532
+
533
+ // src/shhh/execute-paymaster-raw.ts
534
+ var execute_paymaster_raw_exports = {};
535
+ __export(execute_paymaster_raw_exports, {
536
+ executeShhhSponsoredRaw: () => executeShhhSponsoredRaw,
537
+ resolveShhhChainId: () => resolveShhhChainId,
538
+ serializeExecuteFromOutsideV2Calldata: () => serializeExecuteFromOutsideV2Calldata
539
+ });
540
+ function resolveShhhChainId(params) {
541
+ if (params.override !== void 0) {
542
+ return typeof params.override === "bigint" ? "0x" + params.override.toString(16) : params.override;
543
+ }
544
+ const url = (params.baseUrl ?? "").toLowerCase();
545
+ if (url.includes("sepolia")) return SN_SEPOLIA_CHAIN_ID;
546
+ return SN_MAIN_CHAIN_ID;
547
+ }
548
+ function serializeExecuteFromOutsideV2Calldata(params) {
549
+ const out = [];
550
+ const oe = params.outsideExecution;
551
+ const toBig = (v) => typeof v === "bigint" ? v : BigInt(v);
552
+ out.push(toBig(oe.caller));
553
+ out.push(toBig(oe.nonce));
554
+ out.push(oe.execute_after);
555
+ out.push(oe.execute_before);
556
+ out.push(BigInt(oe.calls.length));
557
+ for (const call of oe.calls) {
558
+ out.push(BigInt(call.contractAddress));
559
+ out.push(BigInt(hash.getSelectorFromName(call.entrypoint)));
560
+ const callData = Array.isArray(call.calldata) ? call.calldata : [];
561
+ out.push(BigInt(callData.length));
562
+ for (const datum of callData) {
563
+ out.push(typeof datum === "bigint" ? datum : BigInt(datum));
564
+ }
565
+ }
566
+ out.push(BigInt(params.signature.length));
567
+ for (const sigFelt of params.signature) {
568
+ out.push(sigFelt);
569
+ }
570
+ return out.map((v) => "0x" + v.toString(16));
571
+ }
572
+ function newOeNonce() {
573
+ const tsMs = BigInt(Date.now());
574
+ const rand = BigInt(Math.floor(Math.random() * 16777215));
575
+ return tsMs << 24n | rand;
576
+ }
577
+ async function executeShhhSponsoredRaw(params) {
578
+ const signerKind = params.signerKind ?? "STARK";
579
+ const SDK_SHIPPED_OE_KINDS = ["STARK", "ED25519"];
580
+ if (!SDK_SHIPPED_OE_KINDS.includes(signerKind)) {
581
+ throw new Error(
582
+ `SHHH signerKind="${signerKind}" is not yet shipped from the SDK (Wave B ships STARK + ED25519). Wait for the follow-up PR that adds external-rooted (MetaMask, Phantom, passkey, Apple) signing.`
583
+ );
584
+ }
585
+ const privateKeyHex = decryptPrivateKey(params.wallet.encryptedPrivateKey, params.encryptKey);
586
+ if (!privateKeyHex) {
587
+ throw new Error(
588
+ "Failed to decrypt private key for SHHH OE. Verify the encryptKey matches the one used at wallet creation."
589
+ );
590
+ }
591
+ const oe = buildOutsideExecution({
592
+ nonce: params.nonce ?? newOeNonce(),
593
+ calls: params.calls,
594
+ caller: ANY_CALLER_FELT
595
+ });
596
+ const chainId = resolveShhhChainId({
597
+ override: params.chainId,
598
+ baseUrl: params.client.baseUrl
599
+ });
600
+ const messageHash = computeOeHash(oe, params.wallet.publicKey, chainId);
601
+ let signature;
602
+ if (signerKind === "STARK") {
603
+ signature = buildStarkEnvelope({
604
+ privateKey: privateKeyHex,
605
+ messageHash
606
+ });
607
+ } else {
608
+ const edKeyHex = privateKeyHex.startsWith("0x") ? privateKeyHex.slice(2) : privateKeyHex;
609
+ if (edKeyHex.length !== 64) {
610
+ throw new Error(
611
+ `SHHH ED25519 private key is ${edKeyHex.length} hex chars; expected 64 (32 raw bytes). The stored ciphertext does not look like a Chipi-held Ed25519 key \u2014 check wallet provenance.`
612
+ );
613
+ }
614
+ const edPrivKey = Uint8Array.from(Buffer.from(edKeyHex, "hex"));
615
+ signature = await buildEd25519Envelope({
616
+ privateKey: edPrivKey,
617
+ messageHash
618
+ });
619
+ }
620
+ const calldata = serializeExecuteFromOutsideV2Calldata({
621
+ outsideExecution: oe,
622
+ signature
623
+ });
624
+ const response = await params.client.post({
625
+ endpoint: "/transactions/execute-sponsored-raw",
626
+ bearerToken: params.bearerToken,
627
+ body: {
628
+ accountAddress: params.wallet.publicKey,
629
+ calldata,
630
+ signerKind,
631
+ ...params.externalUserId ? { externalUserId: params.externalUserId } : {}
632
+ }
633
+ });
634
+ if (!response || !response.transactionHash) {
635
+ throw new Error(
636
+ "execute-sponsored-raw response missing transactionHash. Check the chipi-back logs for upstream paymaster errors."
637
+ );
638
+ }
639
+ return response.transactionHash;
640
+ }
641
+ var SN_MAIN_CHAIN_ID, SN_SEPOLIA_CHAIN_ID;
642
+ var init_execute_paymaster_raw = __esm({
643
+ "src/shhh/execute-paymaster-raw.ts"() {
644
+ init_encryption2();
645
+ init_oe();
646
+ init_stark();
647
+ init_ed25519();
648
+ SN_MAIN_CHAIN_ID = "0x534e5f4d41494e";
649
+ SN_SEPOLIA_CHAIN_ID = "0x534e5f5345504f4c4941";
650
+ }
651
+ });
9
652
  var ChipiClient = class {
10
653
  constructor(config) {
11
654
  if (!isValidApiKey(config.apiPublicKey)) {
@@ -188,294 +831,60 @@ var ChipiClient = class {
188
831
  }
189
832
  }
190
833
  };
191
- var encryptPrivateKey = (privateKey, password) => {
192
- if (!privateKey || !password) {
193
- throw new Error("Private key and password are required");
834
+
835
+ // src/wallets.ts
836
+ init_compute_wallet_address();
837
+ init_ed25519();
838
+ init_encryption2();
839
+
840
+ // src/migrate-to-shhh.ts
841
+ init_encryption2();
842
+
843
+ // src/execute-paymaster-transaction.ts
844
+ init_encryption2();
845
+ function unwrapPrepareResponse(response) {
846
+ if (!response || typeof response !== "object") {
847
+ throw new Error(
848
+ "Invalid response from /transactions/prepare-typed-data: response is not an object"
849
+ );
194
850
  }
195
- return CryptoES.AES.encrypt(privateKey, password).toString();
196
- };
197
- var decryptPrivateKey = (encryptedPrivateKey, password) => {
198
- if (!encryptedPrivateKey || !password) {
199
- throw new Error("Encrypted private key and password are required");
851
+ if ("typedData" in response) {
852
+ const resp = response;
853
+ if (!resp.typedData || typeof resp.typedData !== "object" || !("types" in resp.typedData) || !("message" in resp.typedData)) {
854
+ throw new Error(
855
+ "Invalid response from /transactions/prepare-typed-data: typedData structure is invalid"
856
+ );
857
+ }
858
+ return { typedData: resp.typedData, walletType: resp.walletType };
200
859
  }
201
- try {
202
- const bytes = CryptoES.AES.decrypt(encryptedPrivateKey, password);
203
- const decrypted = bytes.toString(CryptoES.enc.Utf8);
204
- if (!decrypted) {
205
- throw new Error("Decryption resulted in empty string");
860
+ if ("types" in response && "message" in response) {
861
+ return { typedData: response };
862
+ }
863
+ const apiMessage = typeof response.message === "string" ? response.message : void 0;
864
+ throw new Error(
865
+ apiMessage ?? "Invalid response from /transactions/prepare-typed-data: typedData is missing"
866
+ );
867
+ }
868
+ function normalizeSignature(signature) {
869
+ if (Array.isArray(signature)) {
870
+ if (signature.length < 2) {
871
+ throw new Error(`Array signature must have at least 2 elements, got ${signature.length}`);
206
872
  }
207
- return decrypted;
208
- } catch (error) {
209
- if (error instanceof Error) {
210
- throw error;
873
+ const r = signature[0];
874
+ const s = signature[1];
875
+ if (r == null || s == null) {
876
+ throw new Error(`Signature elements must not be null/undefined. Got r=${r}, s=${s}`);
211
877
  }
212
- throw new Error(`Decryption failed: ${error}`);
878
+ return { r: String(r), s: String(s) };
213
879
  }
214
- };
215
-
216
- // src/wallets.ts
217
- var ChipiWallets = class {
218
- constructor(client) {
219
- this.client = client;
220
- this.getPrivateKeyAX = () => {
221
- const privateKeyBytes = CryptoES.lib.WordArray.random(32);
222
- const privateKey = privateKeyBytes.toString(CryptoES.enc.Hex);
223
- const fullPrivateKey = `0x${privateKey}`;
224
- const maxStarknetValue = BigInt(
225
- "0x800000000000000000000000000000000000000000000000000000000000000"
226
- );
227
- const privateKeyBigInt = BigInt(fullPrivateKey) % maxStarknetValue;
228
- return `0x${privateKeyBigInt.toString(16)}`;
229
- };
230
- }
231
- async createWallet(params) {
232
- try {
233
- const {
234
- encryptKey,
235
- externalUserId,
236
- bearerToken,
237
- userId,
238
- walletType = "CHIPI",
239
- // Default to CHIPI wallet
240
- classHash: customClassHash,
241
- usePasskey,
242
- chain
243
- } = params;
244
- if (!encryptKey) {
245
- if (usePasskey) {
246
- throw new Error(
247
- "encryptKey is required when using passkey. The passkey authentication should have provided the encryptKey."
248
- );
249
- }
250
- throw new Error("encryptKey is required for wallet creation");
251
- }
252
- const rpcUrl = walletType === "READY" ? WALLET_RPC_ENDPOINTS.READY : WALLET_RPC_ENDPOINTS.CHIPI;
253
- const provider = new RpcProvider({ nodeUrl: rpcUrl });
254
- const privateKeyAX = this.getPrivateKeyAX();
255
- const starkKeyPubAX = ec.starkCurve.getStarkKey(privateKeyAX);
256
- const constructorCallData = this.buildConstructorCallData(walletType, starkKeyPubAX);
257
- const accountClassHash = customClassHash ?? (walletType === "READY" ? WALLET_CLASS_HASHES.READY : WALLET_CLASS_HASHES.CHIPI);
258
- const publicKey = hash.calculateContractAddressFromHash(
259
- starkKeyPubAX,
260
- accountClassHash,
261
- constructorCallData,
262
- 0
263
- );
264
- const account = new Account({ provider, address: publicKey, signer: privateKeyAX });
265
- const typedDataResponse = await this.client.post({
266
- endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/prepare-creation`,
267
- bearerToken,
268
- body: {
269
- chain,
270
- publicKey,
271
- walletType,
272
- starkKeyPubAX,
273
- ...customClassHash && { classHash: customClassHash }
274
- }
275
- });
276
- const { typedData: typedData2, accountClassHash: accountClassHashResponse } = typedDataResponse;
277
- const userSignature = await account.signMessage(typedData2);
278
- const deploymentData = {
279
- class_hash: accountClassHashResponse,
280
- salt: starkKeyPubAX,
281
- unique: `${num.toHex(0)}`,
282
- calldata: constructorCallData.map((value) => num.toHex(value))
283
- };
284
- const encryptedPrivateKey = encryptPrivateKey(privateKeyAX, encryptKey);
285
- const encryptedPrivateKeyBackup = params.encryptKeyBackup ? encryptPrivateKey(privateKeyAX, params.encryptKeyBackup) : void 0;
286
- const executeTransactionResponse = await this.client.post({
287
- endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}`,
288
- bearerToken,
289
- body: {
290
- externalUserId,
291
- userId,
292
- publicKey,
293
- walletType,
294
- chain,
295
- userSignature: {
296
- r: userSignature.r.toString(),
297
- s: userSignature.s.toString(),
298
- recovery: userSignature.recovery
299
- },
300
- typedData: typedData2,
301
- encryptedPrivateKey,
302
- ...encryptedPrivateKeyBackup && { encryptedPrivateKeyBackup },
303
- ...params.authMethod && { authMethod: params.authMethod },
304
- ...params.credentialId && { credentialId: params.credentialId },
305
- ...params.prfSupported != null && { prfSupported: params.prfSupported },
306
- ...params.deviceType && { deviceType: params.deviceType },
307
- deploymentData: {
308
- ...deploymentData,
309
- salt: `${deploymentData.salt}`,
310
- calldata: deploymentData.calldata.map((data) => `${data}`)
311
- }
312
- }
313
- });
314
- return executeTransactionResponse;
315
- } catch (error) {
316
- console.error("Detailed error:", error);
317
- if (error instanceof Error && error.message.includes("SSL")) {
318
- throw new Error(
319
- "SSL connection error. Try using NODE_TLS_REJECT_UNAUTHORIZED=0 or verify the RPC URL"
320
- );
321
- }
322
- throw new ChipiTransactionError(
323
- `Failed to create wallet: ${error instanceof Error ? error.message : "Unknown error"}`,
324
- "WALLET_CREATION_FAILED"
325
- );
326
- }
327
- }
328
- /**
329
- * Build constructor calldata based on wallet type
330
- * - CHIPI: Simple OpenZeppelin account with just public_key
331
- * - ARGENT: Argent X Account with owner/guardian structure
332
- */
333
- buildConstructorCallData(walletType, starkKeyPubAX) {
334
- if (walletType === "READY") {
335
- const axSigner = new CairoCustomEnum({
336
- Starknet: { pubkey: starkKeyPubAX }
337
- });
338
- const axGuardian = new CairoOption(CairoOptionVariant.None);
339
- return CallData.compile({
340
- owner: axSigner,
341
- guardian: axGuardian
342
- });
343
- }
344
- return CallData.compile({
345
- public_key: starkKeyPubAX
346
- });
347
- }
348
- /**
349
- * Create a custodial merchant wallet
350
- */
351
- async createCustodialWallet({
352
- params,
353
- bearerToken
354
- }) {
355
- const response = await this.client.post({
356
- endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/custodial`,
357
- bearerToken,
358
- body: params
359
- });
360
- return response;
361
- }
362
- async getWallet(params, bearerToken) {
363
- try {
364
- const { externalUserId } = params;
365
- const getWalletResponse = await this.client.get({
366
- endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/by-user`,
367
- params: { externalUserId },
368
- bearerToken
369
- });
370
- return getWalletResponse;
371
- } catch (err) {
372
- if (err instanceof ChipiApiError && err.status === 404) {
373
- return null;
374
- }
375
- throw err;
376
- }
377
- }
378
- /**
379
- * Recover passkey credential metadata for a wallet.
380
- * Used when localStorage is cleared — SDK recovers credentialId from backend.
381
- */
382
- async getCredentialRecovery(params, bearerToken) {
383
- return this.client.get({
384
- endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/credential-recovery`,
385
- params: { externalUserId: params.externalUserId },
386
- bearerToken
387
- });
388
- }
389
- async updateWalletEncryption(params, bearerToken) {
390
- const body = {
391
- externalUserId: params.externalUserId,
392
- newEncryptedPrivateKey: params.newEncryptedPrivateKey
393
- };
394
- if (params.publicKey != null) {
395
- body.publicKey = params.publicKey;
396
- }
397
- return this.client.patch({
398
- endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/update-encryption-details`,
399
- bearerToken,
400
- body
401
- });
402
- }
403
- async getTokenBalance({
404
- params,
405
- bearerToken
406
- }) {
407
- const getBalanceResponse = await this.client.get({
408
- endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/token-balance`,
409
- params,
410
- bearerToken
411
- });
412
- return getBalanceResponse;
413
- }
414
- /**
415
- * Prepare a wallet upgrade (e.g., READY → CHIPI or CHIPI v29 → v33).
416
- * Returns typed data that must be signed by the wallet owner.
417
- */
418
- async prepareWalletUpgrade(params, bearerToken) {
419
- return this.client.post({
420
- endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/prepare-upgrade`,
421
- bearerToken,
422
- body: params
423
- });
424
- }
425
- /**
426
- * Execute a wallet upgrade after the owner has signed the typed data.
427
- */
428
- async executeWalletUpgrade(params, bearerToken) {
429
- return this.client.post({
430
- endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/upgrade`,
431
- bearerToken,
432
- body: params
433
- });
434
- }
435
- };
436
- function unwrapPrepareResponse(response) {
437
- if (!response || typeof response !== "object") {
438
- throw new Error(
439
- "Invalid response from /transactions/prepare-typed-data: response is not an object"
440
- );
441
- }
442
- if ("typedData" in response) {
443
- const resp = response;
444
- if (!resp.typedData || typeof resp.typedData !== "object" || !("types" in resp.typedData) || !("message" in resp.typedData)) {
445
- throw new Error(
446
- "Invalid response from /transactions/prepare-typed-data: typedData structure is invalid"
447
- );
448
- }
449
- return { typedData: resp.typedData, walletType: resp.walletType };
450
- }
451
- if ("types" in response && "message" in response) {
452
- return { typedData: response };
453
- }
454
- const apiMessage = typeof response.message === "string" ? response.message : void 0;
455
- throw new Error(
456
- apiMessage ?? "Invalid response from /transactions/prepare-typed-data: typedData is missing"
457
- );
458
- }
459
- function normalizeSignature(signature) {
460
- if (Array.isArray(signature)) {
461
- if (signature.length < 2) {
462
- throw new Error(`Array signature must have at least 2 elements, got ${signature.length}`);
463
- }
464
- const r = signature[0];
465
- const s = signature[1];
466
- if (r == null || s == null) {
467
- throw new Error(`Signature elements must not be null/undefined. Got r=${r}, s=${s}`);
468
- }
469
- return { r: String(r), s: String(s) };
470
- }
471
- if (signature && typeof signature === "object" && "r" in signature && "s" in signature) {
472
- const sig = signature;
473
- if (sig.r == null || sig.s == null) {
474
- throw new Error(`Object signature has null/undefined fields. Got r=${sig.r}, s=${sig.s}`);
475
- }
476
- return {
477
- r: String(sig.r),
478
- s: String(sig.s)
880
+ if (signature && typeof signature === "object" && "r" in signature && "s" in signature) {
881
+ const sig = signature;
882
+ if (sig.r == null || sig.s == null) {
883
+ throw new Error(`Object signature has null/undefined fields. Got r=${sig.r}, s=${sig.s}`);
884
+ }
885
+ return {
886
+ r: String(sig.r),
887
+ s: String(sig.s)
479
888
  };
480
889
  }
481
890
  throw new Error("Unrecognized signature format from account.signMessage()");
@@ -539,6 +948,22 @@ var executePaymasterTransaction = async ({
539
948
  );
540
949
  }
541
950
  const walletType = wallet.walletType ?? "READY";
951
+ if (walletType === "SHHH") {
952
+ const { executeShhhSponsoredRaw: executeShhhSponsoredRaw2 } = await Promise.resolve().then(() => (init_execute_paymaster_raw(), execute_paymaster_raw_exports));
953
+ const shhhSignerKind = (wallet.signerKind ?? "STARK") || "STARK";
954
+ return await executeShhhSponsoredRaw2({
955
+ client,
956
+ bearerToken,
957
+ wallet: {
958
+ publicKey: wallet.publicKey,
959
+ encryptedPrivateKey: wallet.encryptedPrivateKey,
960
+ walletType: wallet.walletType
961
+ },
962
+ encryptKey,
963
+ calls,
964
+ signerKind: shhhSignerKind
965
+ });
966
+ }
542
967
  const isKnownType = Object.prototype.hasOwnProperty.call(WALLET_RPC_ENDPOINTS, walletType) && Object.prototype.hasOwnProperty.call(WALLET_CLASS_HASHES, walletType);
543
968
  const rpcUrl = isKnownType ? WALLET_RPC_ENDPOINTS[walletType] : WALLET_RPC_ENDPOINTS["CHIPI"];
544
969
  const accountClassHash = isKnownType ? WALLET_CLASS_HASHES[walletType] : WALLET_CLASS_HASHES["CHIPI"];
@@ -623,16 +1048,15 @@ var executePaymasterTransactionWithSession = async ({
623
1048
  client
624
1049
  }) => {
625
1050
  const { encryptKey, wallet, session, calls, saveToDatabase } = params;
626
- if (wallet.walletType !== "CHIPI") {
1051
+ if (wallet.walletType !== "CHIPI" && wallet.walletType !== "SHHH") {
627
1052
  console.error("[ChipiSDK:Session:Execute] Invalid wallet type for session execution", {
628
1053
  provided: wallet.walletType,
629
- required: "CHIPI",
630
- expectedClassHash: WALLET_CLASS_HASHES.CHIPI,
1054
+ required: "CHIPI or SHHH",
631
1055
  walletAddress: wallet.publicKey?.slice(0, 15) + "...",
632
- hint: "Session keys only work with CHIPI wallets (SNIP-9 compatible)"
1056
+ hint: "Session keys require a SNIP-163 sessions component (CHIPI v29 or SHHH V8.4)."
633
1057
  });
634
1058
  throw new ChipiSessionError(
635
- `Session execution requires CHIPI wallet type. Got: "${wallet.walletType || "undefined"}"`,
1059
+ `Session execution requires CHIPI or SHHH wallet type. Got: "${wallet.walletType || "undefined"}"`,
636
1060
  SESSION_ERRORS.INVALID_WALLET_TYPE_FOR_SESSION
637
1061
  );
638
1062
  }
@@ -674,6 +1098,52 @@ var executePaymasterTransactionWithSession = async ({
674
1098
  SESSION_ERRORS.SESSION_DECRYPTION_FAILED
675
1099
  );
676
1100
  }
1101
+ if (wallet.walletType === "SHHH") {
1102
+ const { buildOutsideExecution: buildOutsideExecution2, computeOeHash: computeOeHash2, ANY_CALLER_FELT: ANY_CALLER_FELT2 } = await Promise.resolve().then(() => (init_oe(), oe_exports));
1103
+ const { resolveShhhChainId: resolveShhhChainId2, serializeExecuteFromOutsideV2Calldata: serializeExecuteFromOutsideV2Calldata2 } = await Promise.resolve().then(() => (init_execute_paymaster_raw(), execute_paymaster_raw_exports));
1104
+ const oe = buildOutsideExecution2({
1105
+ nonce: BigInt(Date.now()) << 24n | BigInt(Math.floor(Math.random() * 16777215)),
1106
+ calls,
1107
+ caller: ANY_CALLER_FELT2
1108
+ });
1109
+ const chainId = resolveShhhChainId2({ baseUrl: client.baseUrl });
1110
+ const messageHash = computeOeHash2(oe, wallet.publicKey, chainId);
1111
+ const messageHashHex = "0x" + messageHash.toString(16);
1112
+ const { r: r2, s: s2 } = ec.starkCurve.sign(messageHashHex, sessionPrivateKey);
1113
+ const sessionSignature2 = [
1114
+ BigInt(session.publicKey),
1115
+ BigInt(r2),
1116
+ BigInt(s2),
1117
+ BigInt(session.validUntil)
1118
+ ];
1119
+ const calldata = serializeExecuteFromOutsideV2Calldata2({
1120
+ outsideExecution: oe,
1121
+ signature: sessionSignature2
1122
+ });
1123
+ const response = await client.post({
1124
+ endpoint: "/transactions/execute-sponsored-raw",
1125
+ bearerToken,
1126
+ body: {
1127
+ accountAddress: wallet.publicKey,
1128
+ calldata,
1129
+ // Gas budget for the session-sig path is the same as STARK
1130
+ // primary (~2M l2_gas). The paymaster's kind-detection
1131
+ // branch reads signature[0] == 'V2_SNIP12' to look up the
1132
+ // per-kind gas overhead; signature[0] here is the
1133
+ // session_pubkey (not the V2_SNIP12 prefix), so the
1134
+ // detection falls through to the STARK default — which is
1135
+ // correct, since the session verifier is STARK ECDSA.
1136
+ signerKind: "STARK"
1137
+ }
1138
+ });
1139
+ if (!response?.transactionHash) {
1140
+ throw new ChipiSessionError(
1141
+ "execute-sponsored-raw response missing transactionHash. Check chipi-back logs for upstream paymaster errors.",
1142
+ SESSION_ERRORS.SESSION_INVALID_RESPONSE
1143
+ );
1144
+ }
1145
+ return response.transactionHash;
1146
+ }
677
1147
  const accountClassHash = WALLET_CLASS_HASHES.CHIPI;
678
1148
  const prepareResponse = await client.post({
679
1149
  endpoint: "/transactions/prepare-typed-data",
@@ -758,11 +1228,572 @@ var executePaymasterTransactionWithSession = async ({
758
1228
  walletAddress: wallet.publicKey?.slice(0, 15) + "...",
759
1229
  sessionPubKey: session.publicKey?.slice(0, 15) + "..."
760
1230
  });
761
- throw error;
1231
+ throw error;
1232
+ }
1233
+ };
1234
+ var BOOTSTRAP_DOMAIN_SEPARATOR = BigInt(
1235
+ shortString.encodeShortString("SHHH_BOOTSTRAP_V8_4")
1236
+ );
1237
+ var UPGRADE_ENTRYPOINT = "upgrade";
1238
+ var BOOTSTRAP_ENTRYPOINT = "bootstrap_from_sessions";
1239
+ var BOOTSTRAP_SIGNED_ENTRYPOINT = "bootstrap_from_sessions_signed";
1240
+ function _asHex(x) {
1241
+ return typeof x === "bigint" ? "0x" + x.toString(16) : x;
1242
+ }
1243
+ function _felt(x) {
1244
+ if (typeof x === "bigint") return x;
1245
+ return BigInt(x);
1246
+ }
1247
+ function labelToFelt(label) {
1248
+ if (label.length === 0) return 0n;
1249
+ for (let i = 0; i < label.length; i++) {
1250
+ if (label.charCodeAt(i) > 127) {
1251
+ throw new RangeError(
1252
+ `migrate label must be ASCII-only (starknet.js short-string encoder rejects non-ASCII)`
1253
+ );
1254
+ }
1255
+ }
1256
+ if (label.length > 31) {
1257
+ throw new RangeError(
1258
+ `migrate label must fit in felt252 short-string (\u226431 ASCII characters); got ${label.length}`
1259
+ );
1260
+ }
1261
+ return BigInt(shortString.encodeShortString(label));
1262
+ }
1263
+ function buildMigrationCalls(params) {
1264
+ const upgradeCall = {
1265
+ contractAddress: _asHex(params.legacyAccountAddress),
1266
+ entrypoint: UPGRADE_ENTRYPOINT,
1267
+ calldata: [_asHex(params.shhhAccountClassHash)]
1268
+ };
1269
+ const labelFelt = labelToFelt(params.label ?? "migrated");
1270
+ const bootstrapCall = {
1271
+ contractAddress: _asHex(params.legacyAccountAddress),
1272
+ entrypoint: BOOTSTRAP_ENTRYPOINT,
1273
+ calldata: [
1274
+ _asHex(params.legacyPublicKey),
1275
+ _asHex(params.starkVerifierClassHash),
1276
+ "0x" + labelFelt.toString(16)
1277
+ ]
1278
+ };
1279
+ return [upgradeCall, bootstrapCall];
1280
+ }
1281
+ function computeBootstrapMessage(params) {
1282
+ const accountFelt = _felt(params.accountAddress);
1283
+ const pubkeyFelt = _felt(params.publicKey);
1284
+ const verifierFelt = _felt(params.starkVerifierClassHash);
1285
+ const labelFelt = labelToFelt(params.label ?? "migrated");
1286
+ return BigInt(
1287
+ hash.computePoseidonHashOnElements([
1288
+ "0x" + BOOTSTRAP_DOMAIN_SEPARATOR.toString(16),
1289
+ "0x" + accountFelt.toString(16),
1290
+ "0x" + pubkeyFelt.toString(16),
1291
+ "0x" + verifierFelt.toString(16),
1292
+ "0x" + labelFelt.toString(16)
1293
+ ])
1294
+ );
1295
+ }
1296
+ function signBootstrapMessage(params) {
1297
+ const messageHash = computeBootstrapMessage(params.message);
1298
+ const pkHex = _asHex(_felt(params.privateKey));
1299
+ const sig = ec.starkCurve.sign("0x" + messageHash.toString(16), pkHex);
1300
+ return {
1301
+ r: BigInt("0x" + sig.r.toString(16)),
1302
+ s: BigInt("0x" + sig.s.toString(16))
1303
+ };
1304
+ }
1305
+ function buildBootstrapSignedCall(params) {
1306
+ const labelFelt = labelToFelt(params.label ?? "migrated");
1307
+ return {
1308
+ contractAddress: _asHex(params.accountAddress),
1309
+ entrypoint: BOOTSTRAP_SIGNED_ENTRYPOINT,
1310
+ calldata: [
1311
+ _asHex(params.publicKey),
1312
+ _asHex(params.starkVerifierClassHash),
1313
+ "0x" + labelFelt.toString(16),
1314
+ _asHex(params.signatureR),
1315
+ _asHex(params.signatureS)
1316
+ ]
1317
+ };
1318
+ }
1319
+
1320
+ // src/migrate-to-shhh.ts
1321
+ async function migrateChipiWalletToShhh(params) {
1322
+ const prepare = await params.client.post({
1323
+ endpoint: "/chipi-wallets/prepare-migrate-to-shhh",
1324
+ bearerToken: params.bearerToken,
1325
+ body: {
1326
+ walletId: params.walletId,
1327
+ externalUserId: params.externalUserId
1328
+ }
1329
+ });
1330
+ if (prepare.migrationPath === "ALREADY_MIGRATED") {
1331
+ return {
1332
+ kind: "ALREADY_MIGRATED",
1333
+ walletAddress: prepare.walletAddress,
1334
+ onChainClassHash: prepare.onChainClassHash,
1335
+ primaryKind: prepare.primaryKind
1336
+ };
1337
+ }
1338
+ if (prepare.migrationPath === "STRANDED") {
1339
+ throw new Error(
1340
+ "SHHH stranded-state recovery is not yet shipped in the SDK client. The wallet is at V8.4 class hash but primary_kind == 0, which means a prior migration completed `upgrade(SHHH)` but the `bootstrap_from_sessions` call silently reverted. Recovery requires `bootstrap_from_sessions_signed`; see `buildBootstrapSignedCall` in @chipi-stack/backend/src/shhh/migrate.ts."
1341
+ );
1342
+ }
1343
+ if (prepare.migrationPath !== "HAPPY") {
1344
+ throw new Error(
1345
+ "SHHH migration: unexpected migrationPath " + JSON.stringify(prepare.migrationPath) + " returned by chipi-back. This SDK build only handles HAPPY / STRANDED / ALREADY_MIGRATED; upgrade @chipi-stack/backend to a version that knows this path."
1346
+ );
1347
+ }
1348
+ const privateKeyHex = decryptPrivateKey(params.wallet.encryptedPrivateKey, params.encryptKey);
1349
+ if (!privateKeyHex) {
1350
+ throw new Error(
1351
+ "Failed to decrypt STARK private key for migration. Verify the encryptKey matches the one used at wallet creation."
1352
+ );
1353
+ }
1354
+ const starkKeyPub = BigInt(ec.starkCurve.getStarkKey(privateKeyHex));
1355
+ const calls = buildMigrationCalls({
1356
+ legacyAccountAddress: params.wallet.publicKey,
1357
+ legacyPublicKey: starkKeyPub,
1358
+ shhhAccountClassHash: BigInt(prepare.shhhClassHash),
1359
+ starkVerifierClassHash: BigInt(prepare.shhhVerifierClassHash),
1360
+ label: prepare.label
1361
+ });
1362
+ const transactionHash = await executePaymasterTransaction({
1363
+ params: {
1364
+ encryptKey: params.encryptKey,
1365
+ wallet: {
1366
+ publicKey: params.wallet.publicKey,
1367
+ encryptedPrivateKey: params.wallet.encryptedPrivateKey,
1368
+ // Explicit walletType: the wallet IS still CHIPI v29 at sign
1369
+ // time. The upgrade(SHHH) inside the multicall changes the
1370
+ // class hash mid-tx; that's after signature verification.
1371
+ walletType: "CHIPI"
1372
+ },
1373
+ calls,
1374
+ // Persist the migration tx so it shows up in the user's tx
1375
+ // history. The on-chain receipt is the load-bearing artifact;
1376
+ // the DB row is convenience surfacing.
1377
+ saveToDatabase: true
1378
+ },
1379
+ bearerToken: params.bearerToken,
1380
+ client: params.client
1381
+ });
1382
+ const execute = await params.client.post({
1383
+ endpoint: "/chipi-wallets/execute-migrate-to-shhh",
1384
+ bearerToken: params.bearerToken,
1385
+ body: {
1386
+ walletId: params.walletId,
1387
+ externalUserId: params.externalUserId,
1388
+ transactionHash
1389
+ }
1390
+ });
1391
+ return { kind: "MIGRATED", ...execute };
1392
+ }
1393
+
1394
+ // src/wallets.ts
1395
+ var ChipiWallets = class {
1396
+ constructor(client) {
1397
+ this.client = client;
1398
+ this.getPrivateKeyAX = () => {
1399
+ const privateKeyBytes = CryptoES.lib.WordArray.random(32);
1400
+ const privateKey = privateKeyBytes.toString(CryptoES.enc.Hex);
1401
+ const fullPrivateKey = `0x${privateKey}`;
1402
+ const maxStarknetValue = BigInt(
1403
+ "0x800000000000000000000000000000000000000000000000000000000000000"
1404
+ );
1405
+ const privateKeyBigInt = BigInt(fullPrivateKey) % maxStarknetValue;
1406
+ return `0x${privateKeyBigInt.toString(16)}`;
1407
+ };
1408
+ }
1409
+ /**
1410
+ * Create a new wallet on Starknet (gasless, paymaster-sponsored).
1411
+ *
1412
+ * **PIN is weak — not recommended for production.** `encryptKey` here
1413
+ * doubles as the only thing decrypting the wallet's private key. A
1414
+ * user-typed PIN is short, low-entropy, and trivially compromised
1415
+ * by shoulder-surfing or phishing. Production embedded-wallet apps
1416
+ * should derive `encryptKey` from a platform passkey
1417
+ * (`@chipi-stack/chipi-passkey` `getWalletEncryptKey` for the legacy
1418
+ * PRF flow, or — preferred — `createShhhPasskey` for new SHHH
1419
+ * V8.4 wallets where the P-256 key never leaves the platform
1420
+ * authenticator at all). PIN remains only as a last-resort
1421
+ * recovery surface for users without WebAuthn / biometrics.
1422
+ */
1423
+ async createWallet(params) {
1424
+ try {
1425
+ const {
1426
+ encryptKey,
1427
+ externalUserId,
1428
+ bearerToken,
1429
+ userId,
1430
+ // P2.2 default flip (re-applied 2026-05-29 after #270 revert and
1431
+ // the post-revert SHHH bug-fix run #271–#296). New wallets
1432
+ // default to SHHH V8.4 instead of legacy CHIPI v29 — pluggable-
1433
+ // signer Starknet account, guardian recovery, threshold support
1434
+ // out of the box. Existing wallets unaffected; this only
1435
+ // changes the default for callers that omit `walletType`.
1436
+ // Callers who explicitly pass `walletType: "CHIPI"` or
1437
+ // `"READY"` continue producing those.
1438
+ //
1439
+ // Server-side override: chipi-back's CHIPI_SHHH_DEFAULT env
1440
+ // var (chipi-back#267) lets ops force the legacy default back
1441
+ // for callers that bypass the SDK and POST to /chipi-wallets
1442
+ // directly without walletType.
1443
+ //
1444
+ // signerKind under the SHHH branch defaults to "STARK" further
1445
+ // down — same kind the original #267 P2.2 used and the same
1446
+ // kind every mainnet smoke since 2026-05-26 has been signing
1447
+ // under.
1448
+ walletType = "SHHH",
1449
+ classHash: customClassHash,
1450
+ usePasskey,
1451
+ chain
1452
+ } = params;
1453
+ if (!encryptKey) {
1454
+ if (usePasskey) {
1455
+ throw new Error(
1456
+ "encryptKey is required when using passkey. The passkey authentication should have provided the encryptKey."
1457
+ );
1458
+ }
1459
+ throw new Error("encryptKey is required for wallet creation");
1460
+ }
1461
+ const isShhh = walletType === "SHHH";
1462
+ const effectiveSignerKind = isShhh ? params.signerKind ?? "STARK" : void 0;
1463
+ const SDK_SHIPPED_SHHH_KINDS = [
1464
+ "STARK",
1465
+ "ED25519",
1466
+ "WEBAUTHN_P256",
1467
+ "EIP191_SECP256K1"
1468
+ ];
1469
+ if (isShhh && !SDK_SHIPPED_SHHH_KINDS.includes(
1470
+ effectiveSignerKind
1471
+ )) {
1472
+ throw new Error(
1473
+ `SHHH signerKind=${effectiveSignerKind} is not yet shipped from the SDK (supports STARK, ED25519, WEBAUTHN_P256, EIP191_SECP256K1). JWT_ES256_APPLE_SUB and others remain deferred to their follow-up PRs (OAuth / Apple-Developer context).`
1474
+ );
1475
+ }
1476
+ const rpcUrl = walletType === "READY" ? WALLET_RPC_ENDPOINTS.READY : WALLET_RPC_ENDPOINTS.CHIPI;
1477
+ const provider = new RpcProvider({ nodeUrl: rpcUrl });
1478
+ const privateKeyAX = this.getPrivateKeyAX();
1479
+ const starkKeyPubAX = ec.starkCurve.getStarkKey(privateKeyAX);
1480
+ let constructorCallData;
1481
+ let accountClassHash;
1482
+ let publicKey;
1483
+ let deploymentSalt;
1484
+ let shhhOwnerPubkeyFelts;
1485
+ let shhhKeyForEncryption = privateKeyAX;
1486
+ if (isShhh) {
1487
+ let pubkeyFelts;
1488
+ let shhhPrivateKeyHex;
1489
+ if (effectiveSignerKind === "STARK") {
1490
+ pubkeyFelts = [BigInt(starkKeyPubAX)];
1491
+ shhhPrivateKeyHex = privateKeyAX;
1492
+ } else if (effectiveSignerKind === "ED25519") {
1493
+ if (params.ownerPubkeyFelts && params.ownerPubkeyFelts.length > 0) {
1494
+ if (params.ownerPubkeyFelts.length !== 2) {
1495
+ throw new Error(
1496
+ `SHHH ED25519 ownerPubkeyFelts must be [low_u128, high_u128] (2 felts); got ${params.ownerPubkeyFelts.length}.`
1497
+ );
1498
+ }
1499
+ pubkeyFelts = params.ownerPubkeyFelts.map((s) => BigInt(s));
1500
+ shhhPrivateKeyHex = "";
1501
+ } else {
1502
+ const edPrivKey = randomBytes(32);
1503
+ const ed = await import('@noble/ed25519');
1504
+ const edPubKey = await ed.getPublicKeyAsync(edPrivKey);
1505
+ pubkeyFelts = ed25519PubkeyFelts(edPubKey);
1506
+ shhhPrivateKeyHex = Buffer.from(edPrivKey).toString("hex");
1507
+ }
1508
+ } else if (effectiveSignerKind === "WEBAUTHN_P256" || effectiveSignerKind === "EIP191_SECP256K1") {
1509
+ if (!params.ownerPubkeyFelts || params.ownerPubkeyFelts.length !== 4) {
1510
+ throw new Error(
1511
+ `SHHH ${effectiveSignerKind} ownerPubkeyFelts must be [x_low, x_high, y_low, y_high] (4 felts); got ${params.ownerPubkeyFelts?.length ?? 0}.`
1512
+ );
1513
+ }
1514
+ pubkeyFelts = params.ownerPubkeyFelts.map((s) => BigInt(s));
1515
+ shhhPrivateKeyHex = "";
1516
+ } else {
1517
+ throw new Error(
1518
+ `SHHH signerKind=${effectiveSignerKind} reached the address-derivation block without an implementation.`
1519
+ );
1520
+ }
1521
+ shhhOwnerPubkeyFelts = pubkeyFelts.map((f) => "0x" + f.toString(16));
1522
+ shhhKeyForEncryption = shhhPrivateKeyHex;
1523
+ const verifierClassHash = BigInt(
1524
+ SHHH_VERIFIER_CLASS_HASHES[effectiveSignerKind]
1525
+ );
1526
+ const shhhClassHash = customClassHash ?? WALLET_CLASS_HASHES.SHHH;
1527
+ const computedAddress = computeShhhAddress({
1528
+ classHash: BigInt(shhhClassHash),
1529
+ primaryKind: effectiveSignerKind,
1530
+ pubkey: pubkeyFelts,
1531
+ verifierClassHash
1532
+ });
1533
+ publicKey = "0x" + computedAddress.toString(16);
1534
+ accountClassHash = shhhClassHash;
1535
+ const labelFelt = BigInt(shortString.encodeShortString("primary"));
1536
+ const kindTagFelt = BigInt(shortString.encodeShortString(effectiveSignerKind));
1537
+ constructorCallData = [
1538
+ kindTagFelt.toString(),
1539
+ verifierClassHash.toString(),
1540
+ pubkeyFelts.length.toString(),
1541
+ ...pubkeyFelts.map((f) => f.toString()),
1542
+ labelFelt.toString()
1543
+ ];
1544
+ const salt = (() => {
1545
+ const ownerCommit = BigInt(
1546
+ hash.computePoseidonHashOnElements([
1547
+ "0x" + kindTagFelt.toString(16),
1548
+ ...pubkeyFelts.map((f) => "0x" + f.toString(16))
1549
+ ])
1550
+ );
1551
+ return BigInt(
1552
+ hash.computePoseidonHashOnElements([
1553
+ "0x" + kindTagFelt.toString(16),
1554
+ "0x" + ownerCommit.toString(16)
1555
+ ])
1556
+ );
1557
+ })();
1558
+ deploymentSalt = "0x" + salt.toString(16);
1559
+ } else {
1560
+ constructorCallData = this.buildConstructorCallData(walletType, starkKeyPubAX);
1561
+ accountClassHash = customClassHash ?? (walletType === "READY" ? WALLET_CLASS_HASHES.READY : WALLET_CLASS_HASHES.CHIPI);
1562
+ publicKey = hash.calculateContractAddressFromHash(
1563
+ starkKeyPubAX,
1564
+ accountClassHash,
1565
+ constructorCallData,
1566
+ 0
1567
+ );
1568
+ deploymentSalt = starkKeyPubAX;
1569
+ }
1570
+ const account = new Account({ provider, address: publicKey, signer: privateKeyAX });
1571
+ const typedDataResponse = await this.client.post({
1572
+ endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/prepare-creation`,
1573
+ bearerToken,
1574
+ body: {
1575
+ chain,
1576
+ publicKey,
1577
+ walletType,
1578
+ starkKeyPubAX,
1579
+ ...customClassHash && { classHash: customClassHash },
1580
+ // SHHH: tell chipi-back which signer kind + pubkey felts
1581
+ // produced this deployment so it can validate against the
1582
+ // expected SHHH constructor shape and populate the new
1583
+ // wallet row columns.
1584
+ ...isShhh && {
1585
+ signerKind: effectiveSignerKind,
1586
+ ownerPubkeyFelts: shhhOwnerPubkeyFelts
1587
+ }
1588
+ }
1589
+ });
1590
+ const { typedData: typedData2, accountClassHash: accountClassHashResponse } = typedDataResponse;
1591
+ let userSignaturePayload;
1592
+ if (isShhh) {
1593
+ userSignaturePayload = {
1594
+ r: "0x0",
1595
+ s: "0x0",
1596
+ recovery: 0
1597
+ };
1598
+ } else {
1599
+ const userSignature = await account.signMessage(typedData2);
1600
+ userSignaturePayload = {
1601
+ r: userSignature.r.toString(),
1602
+ s: userSignature.s.toString(),
1603
+ recovery: userSignature.recovery
1604
+ };
1605
+ }
1606
+ const deploymentData = {
1607
+ class_hash: accountClassHashResponse,
1608
+ salt: deploymentSalt,
1609
+ unique: `${num.toHex(0)}`,
1610
+ calldata: constructorCallData.map((value) => num.toHex(value))
1611
+ };
1612
+ const encryptedPrivateKey = shhhKeyForEncryption === "" ? void 0 : encryptPrivateKey(shhhKeyForEncryption, encryptKey);
1613
+ const encryptedPrivateKeyBackup = params.encryptKeyBackup && shhhKeyForEncryption !== "" ? encryptPrivateKey(shhhKeyForEncryption, params.encryptKeyBackup) : void 0;
1614
+ const executeTransactionResponse = await this.client.post({
1615
+ endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}`,
1616
+ bearerToken,
1617
+ body: {
1618
+ externalUserId,
1619
+ userId,
1620
+ publicKey,
1621
+ walletType,
1622
+ chain,
1623
+ userSignature: userSignaturePayload,
1624
+ typedData: typedData2,
1625
+ ...encryptedPrivateKey !== void 0 && { encryptedPrivateKey },
1626
+ // SHHH: write the signer kind to the new wallet row.
1627
+ ...isShhh && { signerKind: effectiveSignerKind },
1628
+ // External-rooted SHHH (passkey / MetaMask / Phantom): no
1629
+ // Chipi-held key, so chipi-back needs the pubkey felts (address
1630
+ // derivation) + `ownerPublicKey` as the credential source it
1631
+ // stores (encryptedPrivateKey stays null). Canonical
1632
+ // ownerPublicKey = comma-joined felts. STARK / Chipi-held kinds
1633
+ // are untouched — encryptedPrivateKey is their credential source.
1634
+ ...isShhh && encryptedPrivateKey === void 0 && shhhOwnerPubkeyFelts && {
1635
+ ownerPubkeyFelts: shhhOwnerPubkeyFelts,
1636
+ ownerPublicKey: shhhOwnerPubkeyFelts.join(",")
1637
+ },
1638
+ ...encryptedPrivateKeyBackup && { encryptedPrivateKeyBackup },
1639
+ ...params.authMethod && { authMethod: params.authMethod },
1640
+ ...params.credentialId && { credentialId: params.credentialId },
1641
+ ...params.prfSupported != null && { prfSupported: params.prfSupported },
1642
+ ...params.deviceType && { deviceType: params.deviceType },
1643
+ deploymentData: {
1644
+ ...deploymentData,
1645
+ salt: `${deploymentData.salt}`,
1646
+ calldata: deploymentData.calldata.map((data) => `${data}`)
1647
+ }
1648
+ }
1649
+ });
1650
+ return executeTransactionResponse;
1651
+ } catch (error) {
1652
+ console.error("Detailed error:", error);
1653
+ if (error instanceof Error && error.message.includes("SSL")) {
1654
+ throw new Error(
1655
+ "SSL connection error. Try using NODE_TLS_REJECT_UNAUTHORIZED=0 or verify the RPC URL"
1656
+ );
1657
+ }
1658
+ throw new ChipiTransactionError(
1659
+ `Failed to create wallet: ${error instanceof Error ? error.message : "Unknown error"}`,
1660
+ "WALLET_CREATION_FAILED"
1661
+ );
1662
+ }
1663
+ }
1664
+ /**
1665
+ * Build constructor calldata based on wallet type
1666
+ * - CHIPI: Simple OpenZeppelin account with just public_key
1667
+ * - ARGENT: Argent X Account with owner/guardian structure
1668
+ */
1669
+ buildConstructorCallData(walletType, starkKeyPubAX) {
1670
+ if (walletType === "READY") {
1671
+ const axSigner = new CairoCustomEnum({
1672
+ Starknet: { pubkey: starkKeyPubAX }
1673
+ });
1674
+ const axGuardian = new CairoOption(CairoOptionVariant.None);
1675
+ return CallData.compile({
1676
+ owner: axSigner,
1677
+ guardian: axGuardian
1678
+ });
1679
+ }
1680
+ return CallData.compile({
1681
+ public_key: starkKeyPubAX
1682
+ });
1683
+ }
1684
+ /**
1685
+ * Create a custodial merchant wallet
1686
+ */
1687
+ async createCustodialWallet({
1688
+ params,
1689
+ bearerToken
1690
+ }) {
1691
+ const response = await this.client.post({
1692
+ endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/custodial`,
1693
+ bearerToken,
1694
+ body: params
1695
+ });
1696
+ return response;
1697
+ }
1698
+ async getWallet(params, bearerToken) {
1699
+ try {
1700
+ const { externalUserId } = params;
1701
+ const getWalletResponse = await this.client.get({
1702
+ endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/by-user`,
1703
+ params: { externalUserId },
1704
+ bearerToken
1705
+ });
1706
+ return getWalletResponse;
1707
+ } catch (err) {
1708
+ if (err instanceof ChipiApiError && err.status === 404) {
1709
+ return null;
1710
+ }
1711
+ throw err;
1712
+ }
1713
+ }
1714
+ /**
1715
+ * Recover passkey credential metadata for a wallet.
1716
+ * Used when localStorage is cleared — SDK recovers credentialId from backend.
1717
+ */
1718
+ async getCredentialRecovery(params, bearerToken) {
1719
+ return this.client.get({
1720
+ endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/credential-recovery`,
1721
+ params: { externalUserId: params.externalUserId },
1722
+ bearerToken
1723
+ });
1724
+ }
1725
+ async updateWalletEncryption(params, bearerToken) {
1726
+ const body = {
1727
+ externalUserId: params.externalUserId,
1728
+ newEncryptedPrivateKey: params.newEncryptedPrivateKey
1729
+ };
1730
+ if (params.publicKey != null) {
1731
+ body.publicKey = params.publicKey;
1732
+ }
1733
+ return this.client.patch({
1734
+ endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/update-encryption-details`,
1735
+ bearerToken,
1736
+ body
1737
+ });
1738
+ }
1739
+ async getTokenBalance({
1740
+ params,
1741
+ bearerToken
1742
+ }) {
1743
+ const getBalanceResponse = await this.client.get({
1744
+ endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/token-balance`,
1745
+ params,
1746
+ bearerToken
1747
+ });
1748
+ return getBalanceResponse;
1749
+ }
1750
+ /**
1751
+ * Prepare a wallet upgrade (e.g., READY → CHIPI or CHIPI v29 → v33).
1752
+ * Returns typed data that must be signed by the wallet owner.
1753
+ */
1754
+ async prepareWalletUpgrade(params, bearerToken) {
1755
+ return this.client.post({
1756
+ endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/prepare-upgrade`,
1757
+ bearerToken,
1758
+ body: params
1759
+ });
1760
+ }
1761
+ /**
1762
+ * Execute a wallet upgrade after the owner has signed the typed data.
1763
+ */
1764
+ async executeWalletUpgrade(params, bearerToken) {
1765
+ return this.client.post({
1766
+ endpoint: `${API_ENDPOINTS.CHIPI_WALLETS}/upgrade`,
1767
+ bearerToken,
1768
+ body: params
1769
+ });
1770
+ }
1771
+ /**
1772
+ * Migrate a CHIPI v29 wallet to SHHH V8.4 in-place at the same
1773
+ * on-chain address. Composes the two-phase chipi-back endpoint:
1774
+ * prepare returns the path decision + parameters, then this method
1775
+ * builds the [upgrade, bootstrap_from_sessions] multicall locally,
1776
+ * signs the V8.4 OE with the wallet's STARK key (decrypted via
1777
+ * the user's encryptKey), and sends the signed calldata to the
1778
+ * execute endpoint. Server forwards verbatim to the paymaster.
1779
+ *
1780
+ * Returns `{kind: "ALREADY_MIGRATED"}` if the wallet is already
1781
+ * SHHH on chain (DB row gets patched server-side; no on-chain tx
1782
+ * fires); otherwise `{kind: "MIGRATED", transactionHash, ...}`.
1783
+ *
1784
+ * Throws on STRANDED-state recovery, UNDEPLOYED wallets, and
1785
+ * other deferred-feature paths with actionable error messages.
1786
+ *
1787
+ * Endpoints contract shipped in chipi-back task #28 (PR #272).
1788
+ */
1789
+ async migrateToShhh(params, bearerToken) {
1790
+ return migrateChipiWalletToShhh({
1791
+ client: this.client,
1792
+ bearerToken,
1793
+ ...params
1794
+ });
762
1795
  }
763
1796
  };
764
-
765
- // src/transactions.ts
766
1797
  var ChipiTransactions = class {
767
1798
  constructor(client) {
768
1799
  this.client = client;
@@ -895,9 +1926,9 @@ var ChipiTransactions = class {
895
1926
  /**
896
1927
  * Get on-chain transaction status
897
1928
  */
898
- async getTransactionStatus(hash3, bearerToken) {
1929
+ async getTransactionStatus(hash9, bearerToken) {
899
1930
  return this.client.get({
900
- endpoint: `${API_ENDPOINTS.TRANSACTIONS}/${hash3}/status`,
1931
+ endpoint: `${API_ENDPOINTS.TRANSACTIONS}/${hash9}/status`,
901
1932
  bearerToken
902
1933
  });
903
1934
  }
@@ -1064,25 +2095,39 @@ var ChipiSkus = class {
1064
2095
  });
1065
2096
  }
1066
2097
  };
2098
+
2099
+ // src/sessions.ts
2100
+ init_encryption2();
1067
2101
  var ChipiSessions = class {
1068
2102
  constructor(client) {
1069
2103
  this.client = client;
1070
2104
  }
1071
2105
  /**
1072
- * Validate that the wallet is a CHIPI wallet (required for session operations).
1073
- * Throws ChipiSessionError if wallet type is not CHIPI.
2106
+ * Validate that the wallet supports SNIP-163 session keys.
2107
+ *
2108
+ * Both CHIPI v29 (sessions-smart-contract) and SHHH V8.4
2109
+ * (ShhhAccount) embed the same SNIP-163 SessionKeyComponent, so
2110
+ * `add_or_update_session_key` / `revoke_session_key` /
2111
+ * `get_session_data` selectors exist on both. The 4-felt session
2112
+ * signature shape (`[session_pubkey, r, s, valid_until]`) is the
2113
+ * same on both — V8.4's `execute_from_outside_v2` checks
2114
+ * `signature.len() == 4` at account.cairo:389 BEFORE the
2115
+ * V2_SNIP12 envelope dispatch, so sessions land through the
2116
+ * legacy fast path on V8.4 wallets too.
2117
+ *
2118
+ * READY (Argent X v0.4.0) does NOT implement SNIP-163; reject with
2119
+ * a clear error.
1074
2120
  */
1075
- validateChipiWallet(walletType, operation, walletPublicKey) {
1076
- if (walletType !== "CHIPI") {
2121
+ validateWalletSupportsSessions(walletType, operation, walletPublicKey) {
2122
+ if (walletType !== "CHIPI" && walletType !== "SHHH") {
1077
2123
  console.error(`[ChipiSDK:Session:${operation}] Invalid wallet type`, {
1078
2124
  provided: walletType,
1079
- required: "CHIPI",
1080
- expectedClassHash: WALLET_CLASS_HASHES["CHIPI"],
2125
+ required: "CHIPI or SHHH",
1081
2126
  walletAddress: walletPublicKey ? walletPublicKey.slice(0, 15) + "..." : "(not provided)",
1082
- hint: "Session keys only work with CHIPI wallets (SNIP-9 compatible)"
2127
+ hint: "Session keys require a SNIP-163 sessions component. CHIPI v29 + SHHH V8.4 both embed it; READY (Argent X) does not."
1083
2128
  });
1084
2129
  throw new ChipiSessionError(
1085
- `Session keys require CHIPI wallet type. Got: "${walletType || "undefined"}". Session keys are only supported for CHIPI wallets with class hash ${WALLET_CLASS_HASHES["CHIPI"]}`,
2130
+ `Session keys require CHIPI or SHHH wallet type. Got: "${walletType || "undefined"}".`,
1086
2131
  SESSION_ERRORS.INVALID_WALLET_TYPE_FOR_SESSION
1087
2132
  );
1088
2133
  }
@@ -1102,6 +2147,15 @@ var ChipiSessions = class {
1102
2147
  *
1103
2148
  * After generating, call `addSessionKeyToContract()` to register the session on-chain.
1104
2149
  *
2150
+ * **PIN is weak — not recommended for production.** `encryptKey` here
2151
+ * is the symmetric key the SDK uses to encrypt the session's private
2152
+ * key at rest. If you're passing a user-typed PIN, anyone who
2153
+ * observes that PIN can decrypt the session. Derive `encryptKey`
2154
+ * from a platform passkey (`@chipi-stack/chipi-passkey`) — for SHHH
2155
+ * V8.4 wallets prefer `createShhhPasskey` + `signShhhMessage`, where
2156
+ * the wallet's primary key never needs to be decrypted client-side
2157
+ * at all.
2158
+ *
1105
2159
  * @param params - Session creation parameters
1106
2160
  * @returns SessionKeyData for external storage
1107
2161
  *
@@ -1174,7 +2228,7 @@ var ChipiSessions = class {
1174
2228
  */
1175
2229
  async addSessionKeyToContract(params, bearerToken) {
1176
2230
  const { encryptKey, wallet, sessionConfig } = params;
1177
- this.validateChipiWallet(wallet.walletType, "AddToContract", wallet.publicKey);
2231
+ this.validateWalletSupportsSessions(wallet.walletType, "AddToContract", wallet.publicKey);
1178
2232
  try {
1179
2233
  console.log("[ChipiSDK:Session:AddToContract] Registering session on-chain", {
1180
2234
  walletAddress: wallet.publicKey.slice(0, 15) + "...",
@@ -1194,7 +2248,7 @@ var ChipiSessions = class {
1194
2248
  const txHash = await executePaymasterTransaction({
1195
2249
  params: {
1196
2250
  encryptKey,
1197
- wallet: { ...wallet, walletType: "CHIPI" },
2251
+ wallet,
1198
2252
  calls: [
1199
2253
  {
1200
2254
  contractAddress: wallet.publicKey,
@@ -1248,7 +2302,7 @@ var ChipiSessions = class {
1248
2302
  */
1249
2303
  async revokeSessionKey(params, bearerToken) {
1250
2304
  const { encryptKey, wallet, sessionPublicKey } = params;
1251
- this.validateChipiWallet(wallet.walletType, "Revoke", wallet.publicKey);
2305
+ this.validateWalletSupportsSessions(wallet.walletType, "Revoke", wallet.publicKey);
1252
2306
  try {
1253
2307
  console.log("[ChipiSDK:Session:Revoke] Revoking session from contract", {
1254
2308
  walletAddress: wallet.publicKey.slice(0, 15) + "...",
@@ -1257,7 +2311,7 @@ var ChipiSessions = class {
1257
2311
  const txHash = await executePaymasterTransaction({
1258
2312
  params: {
1259
2313
  encryptKey,
1260
- wallet: { ...wallet, walletType: "CHIPI" },
2314
+ wallet,
1261
2315
  calls: [
1262
2316
  {
1263
2317
  contractAddress: wallet.publicKey,
@@ -1430,16 +2484,16 @@ var ChipiSessions = class {
1430
2484
  */
1431
2485
  async executeTransactionWithSession(params, bearerToken) {
1432
2486
  const { encryptKey, wallet, session, calls } = params;
1433
- if (wallet.walletType && wallet.walletType !== "CHIPI") {
2487
+ if (wallet.walletType && wallet.walletType !== "CHIPI" && wallet.walletType !== "SHHH") {
1434
2488
  throw new ChipiSessionError(
1435
- `Session execution only supports CHIPI wallets. Got: ${wallet.walletType}`,
2489
+ `Session execution requires CHIPI or SHHH wallet type. Got: ${wallet.walletType}`,
1436
2490
  SESSION_ERRORS.INVALID_WALLET_TYPE_FOR_SESSION
1437
2491
  );
1438
2492
  }
1439
2493
  return executePaymasterTransactionWithSession({
1440
2494
  params: {
1441
2495
  encryptKey,
1442
- wallet: { ...wallet, walletType: "CHIPI" },
2496
+ wallet: { ...wallet, walletType: wallet.walletType ?? "CHIPI" },
1443
2497
  session,
1444
2498
  calls,
1445
2499
  saveToDatabase: true
@@ -1864,6 +2918,13 @@ var X402Facilitator = class _X402Facilitator {
1864
2918
  * Otherwise falls back to a presence-only check (backwards compatible).
1865
2919
  */
1866
2920
  async verifySignature(payment) {
2921
+ if (payment.payload?.shhh) {
2922
+ const oeCalldata = payment.payload.shhh.oeCalldata;
2923
+ if (!Array.isArray(oeCalldata) || oeCalldata.length === 0) {
2924
+ return { valid: false, reason: "Missing SHHH oeCalldata" };
2925
+ }
2926
+ return { valid: true };
2927
+ }
1867
2928
  if (!this.provider) {
1868
2929
  if (!payment.payload?.signature?.r || !payment.payload?.signature?.s) {
1869
2930
  return { valid: false, reason: "Missing signature" };
@@ -1917,6 +2978,28 @@ var X402Facilitator = class _X402Facilitator {
1917
2978
  return { success: false, errorReason: "Nonce already consumed (concurrent replay)" };
1918
2979
  }
1919
2980
  try {
2981
+ if (payload.shhh) {
2982
+ const shhhResult = await this.client.post({
2983
+ endpoint: "/transactions/execute-sponsored-raw",
2984
+ bearerToken: this.bearerToken,
2985
+ body: {
2986
+ accountAddress: payload.fromAddress,
2987
+ calldata: payload.shhh.oeCalldata,
2988
+ signerKind: payload.shhh.signerKind
2989
+ }
2990
+ });
2991
+ if (typeof shhhResult?.transactionHash !== "string" || !shhhResult.transactionHash.trim()) {
2992
+ return {
2993
+ success: false,
2994
+ errorReason: shhhResult?.message ?? "execute-sponsored-raw returned no transactionHash"
2995
+ };
2996
+ }
2997
+ return {
2998
+ success: true,
2999
+ transactionHash: shhhResult.transactionHash,
3000
+ networkId: "starknet-mainnet"
3001
+ };
3002
+ }
1920
3003
  const amountU256 = uint256.bnToUint256(BigInt(payload.amount));
1921
3004
  const transferCall = {
1922
3005
  contractAddress: payload.asset,
@@ -1962,6 +3045,9 @@ var X402Facilitator = class _X402Facilitator {
1962
3045
  }
1963
3046
  }
1964
3047
  };
3048
+
3049
+ // src/sign-typed-data.ts
3050
+ init_encryption2();
1965
3051
  var signTypedData = async ({
1966
3052
  params
1967
3053
  }) => {
@@ -2149,9 +3235,7 @@ var ChipiSDK = class {
2149
3235
  * });
2150
3236
  * ```
2151
3237
  */
2152
- async signTypedData({
2153
- params
2154
- }) {
3238
+ async signTypedData({ params }) {
2155
3239
  return signTypedData({ params });
2156
3240
  }
2157
3241
  /**
@@ -2270,8 +3354,8 @@ var ChipiSDK = class {
2270
3354
  /**
2271
3355
  * Get on-chain transaction status (supports polling for confirmation)
2272
3356
  */
2273
- async getTransactionStatus(hash3, bearerToken) {
2274
- return this.transactions.getTransactionStatus(hash3, this.resolveBearerToken(bearerToken));
3357
+ async getTransactionStatus(hash9, bearerToken) {
3358
+ return this.transactions.getTransactionStatus(hash9, this.resolveBearerToken(bearerToken));
2275
3359
  }
2276
3360
  /**
2277
3361
  * Prepare a wallet upgrade (e.g., READY → CHIPI or CHIPI v29 → v33).
@@ -2319,6 +3403,207 @@ var ChipiBrowserSDK = class extends ChipiSDK {
2319
3403
  // All methods are inherited from ChipiSDK
2320
3404
  // bearerToken parameter is required for each authenticated request
2321
3405
  };
3406
+
3407
+ // src/index.ts
3408
+ init_encryption2();
3409
+
3410
+ // src/x402/shhh-client.ts
3411
+ init_encryption2();
3412
+ init_oe();
3413
+ init_stark();
3414
+ init_execute_paymaster_raw();
3415
+ var PAYMENT_REQUIRED_HEADER = "payment-required";
3416
+ var DEFAULT_PAYMENT_HEADER = "X-PAYMENT";
3417
+ var X402ShhhClient = class {
3418
+ constructor(opts) {
3419
+ this.wallet = opts.wallet;
3420
+ this.encryptKey = opts.encryptKey;
3421
+ this.chipiClient = opts.chipiClient;
3422
+ this.bearerToken = opts.bearerToken;
3423
+ this.config = {
3424
+ headerName: DEFAULT_PAYMENT_HEADER,
3425
+ ...opts.config
3426
+ };
3427
+ this.fetchFn = globalThis.fetch;
3428
+ }
3429
+ /**
3430
+ * Drop-in `fetch` replacement. If the seller returns 402, signs a
3431
+ * payment + retries with the X-PAYMENT header. Same surface as
3432
+ * `X402Client.fetch`.
3433
+ */
3434
+ async fetch(url, init) {
3435
+ const response = await this.fetchFn(url, init);
3436
+ if (response.status !== 402) {
3437
+ return response;
3438
+ }
3439
+ const requirement = this.parsePaymentRequired(response);
3440
+ this.validateRequirement(requirement);
3441
+ const payment = await this.signPayment(requirement);
3442
+ return this.retryWithPayment(url, init, payment);
3443
+ }
3444
+ parsePaymentRequired(response) {
3445
+ const headerValue = response.headers.get(PAYMENT_REQUIRED_HEADER);
3446
+ if (!headerValue) {
3447
+ throw new Error(
3448
+ "Server returned 402 but no PAYMENT-REQUIRED header. The server may not support x402 or is misconfigured."
3449
+ );
3450
+ }
3451
+ let requirement;
3452
+ try {
3453
+ requirement = JSON.parse(headerValue);
3454
+ } catch {
3455
+ throw new Error(
3456
+ `Malformed PAYMENT-REQUIRED header: invalid JSON. Got: "${headerValue.slice(0, 100)}"`
3457
+ );
3458
+ }
3459
+ if (!requirement.scheme || !requirement.network || !requirement.maxAmountRequired) {
3460
+ throw new Error(
3461
+ "Invalid payment requirement: missing required fields (scheme, network, maxAmountRequired)"
3462
+ );
3463
+ }
3464
+ if (requirement.scheme !== "exact") {
3465
+ throw new Error(
3466
+ `Unsupported payment scheme: "${requirement.scheme}". This client only supports "exact".`
3467
+ );
3468
+ }
3469
+ if (requirement.network !== "starknet-mainnet") {
3470
+ throw new Error(
3471
+ `Unsupported payment network: "${requirement.network}". This client only supports "starknet-mainnet" per CLAUDE.md.`
3472
+ );
3473
+ }
3474
+ return requirement;
3475
+ }
3476
+ validateRequirement(req) {
3477
+ if (this.config.allowedRecipients && this.config.allowedRecipients.length > 0 && !this.config.allowedRecipients.includes(req.payTo)) {
3478
+ throw new Error(
3479
+ `Payment recipient ${req.payTo} not in allowed list. Update X402ShhhClientConfig.allowedRecipients to permit this seller.`
3480
+ );
3481
+ }
3482
+ if (this.config.maxPaymentAmount) {
3483
+ const maxBaseUnits = humanUsdcToBaseUnits(this.config.maxPaymentAmount, 6);
3484
+ if (BigInt(req.maxAmountRequired) > maxBaseUnits) {
3485
+ throw new Error(
3486
+ `Payment amount ${req.maxAmountRequired} exceeds client max ${this.config.maxPaymentAmount} USDC.`
3487
+ );
3488
+ }
3489
+ }
3490
+ }
3491
+ /**
3492
+ * Sign an x402 payment as a SHHH V8.4 buyer. Builds the V8.4 OE
3493
+ * containing the single USDC.transfer call, computes the SNIP-12
3494
+ * hash against the wallet address + chain id, signs locally with
3495
+ * the decrypted STARK private key, wraps the result in a V2_SNIP12
3496
+ * envelope, and serializes the full execute_from_outside_v2
3497
+ * calldata. Returns a PaymentPayload with the `shhh` extension
3498
+ * populated; the facilitator's settle branch forwards
3499
+ * `payload.shhh.oeCalldata` verbatim to
3500
+ * `/transactions/execute-sponsored-raw`.
3501
+ *
3502
+ * The `signature: {r, s}` field is also populated with the inner
3503
+ * `(r, s)` pair so the wire format stays valid for receivers that
3504
+ * only inspect the legacy field. The facilitator uses the SHHH
3505
+ * branch when `payload.shhh` is present, so the redundant `{r, s}`
3506
+ * is informational, not load-bearing.
3507
+ */
3508
+ async signPayment(requirement) {
3509
+ const signerKind = this.wallet.signerKind ?? "STARK";
3510
+ if (signerKind !== "STARK") {
3511
+ throw new Error(
3512
+ `X402ShhhClient currently supports signerKind="STARK" only; got "${signerKind}". ED25519 + external-rooted (MetaMask, Phantom, passkey, Apple) x402 buyers ship in a follow-on PR.`
3513
+ );
3514
+ }
3515
+ const nonce = generateNonce();
3516
+ const validUntil = Math.floor(Date.now() / 1e3) + requirement.maxTimeoutSeconds;
3517
+ const amountU256 = uint256.bnToUint256(BigInt(requirement.maxAmountRequired));
3518
+ const transferCall = {
3519
+ contractAddress: requirement.asset,
3520
+ entrypoint: "transfer",
3521
+ calldata: [requirement.payTo, amountU256.low.toString(), amountU256.high.toString()]
3522
+ };
3523
+ const oe = buildOutsideExecution({
3524
+ nonce: BigInt("0x" + nonceToHexFelt(nonce)),
3525
+ calls: [transferCall],
3526
+ caller: ANY_CALLER_FELT
3527
+ });
3528
+ const chainId = resolveShhhChainId({
3529
+ override: this.config.chainId,
3530
+ baseUrl: this.chipiClient.baseUrl
3531
+ });
3532
+ const messageHash = computeOeHash(oe, this.wallet.publicKey, chainId);
3533
+ const privateKeyHex = decryptPrivateKey(this.wallet.encryptedPrivateKey, this.encryptKey);
3534
+ if (!privateKeyHex) {
3535
+ throw new Error(
3536
+ "Failed to decrypt SHHH STARK private key for x402 payment. Verify the encryptKey matches the wallet creation key."
3537
+ );
3538
+ }
3539
+ const envelope = buildStarkEnvelope({
3540
+ privateKey: privateKeyHex,
3541
+ messageHash
3542
+ });
3543
+ const oeCalldata = serializeExecuteFromOutsideV2Calldata({
3544
+ outsideExecution: oe,
3545
+ signature: envelope
3546
+ });
3547
+ const r = envelope[envelope.length - 2] ?? 0n;
3548
+ const s = envelope[envelope.length - 1] ?? 0n;
3549
+ return {
3550
+ x402Version: 1,
3551
+ scheme: "exact",
3552
+ network: "starknet-mainnet",
3553
+ payload: {
3554
+ signature: {
3555
+ r: "0x" + r.toString(16),
3556
+ s: "0x" + s.toString(16)
3557
+ },
3558
+ fromAddress: this.wallet.publicKey,
3559
+ toAddress: requirement.payTo,
3560
+ amount: requirement.maxAmountRequired,
3561
+ asset: requirement.asset,
3562
+ validUntil,
3563
+ nonce,
3564
+ shhh: {
3565
+ walletType: "SHHH",
3566
+ signerKind,
3567
+ oeCalldata
3568
+ }
3569
+ }
3570
+ };
3571
+ }
3572
+ async retryWithPayment(url, init, payment) {
3573
+ const HeadersCtor = globalThis.Headers;
3574
+ const headerName = this.config.headerName;
3575
+ const paymentJson = JSON.stringify(payment);
3576
+ let headers;
3577
+ if (typeof HeadersCtor === "function") {
3578
+ const merged = new HeadersCtor(init?.headers);
3579
+ merged.set(headerName, paymentJson);
3580
+ headers = merged;
3581
+ } else {
3582
+ const existing = init?.headers ?? {};
3583
+ headers = { ...existing, [headerName]: paymentJson };
3584
+ }
3585
+ return this.fetchFn(url, { ...init, headers });
3586
+ }
3587
+ };
3588
+ function humanUsdcToBaseUnits(amount, decimals) {
3589
+ const [whole, frac = ""] = amount.trim().split(".");
3590
+ const fracPadded = (frac + "0".repeat(decimals)).slice(0, decimals);
3591
+ return BigInt((whole || "0") + fracPadded);
3592
+ }
3593
+ function generateNonce() {
3594
+ if (typeof globalThis.crypto?.randomUUID === "function") {
3595
+ return globalThis.crypto.randomUUID();
3596
+ }
3597
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
3598
+ }
3599
+ function nonceToHexFelt(nonce) {
3600
+ const bytes = new TextEncoder().encode(nonce);
3601
+ let hex = "";
3602
+ for (const b of bytes) {
3603
+ hex += b.toString(16).padStart(2, "0");
3604
+ }
3605
+ return hex.slice(0, 60).padStart(60, "0");
3606
+ }
2322
3607
  function amountToBaseUnits(amount, decimals) {
2323
3608
  const [whole, frac = ""] = amount.split(".");
2324
3609
  const fracPadded = (frac + "0".repeat(decimals)).slice(0, decimals);
@@ -2443,6 +3728,815 @@ function x402Middleware(config) {
2443
3728
  };
2444
3729
  }
2445
3730
 
2446
- export { ChipiBrowserSDK, ChipiClient, ChipiPaymasterAdapter, ChipiSDK, ChipiServerSDK, ChipiSessions, ChipiSkuPurchases, ChipiSkus, ChipiTransactions, ChipiWallets, X402Facilitator, decryptPrivateKey, encryptPrivateKey, signTypedData, x402Middleware };
3731
+ // src/shhh/index.ts
3732
+ init_snip12_hash();
3733
+ init_compute_wallet_address();
3734
+ init_oe();
3735
+ init_stark();
3736
+ init_ed25519();
3737
+
3738
+ // src/shhh/signers/eip191.ts
3739
+ init_compute_wallet_address();
3740
+ init_oe();
3741
+ var EIP191_KIND_TAG = "EIP191_SECP256K1";
3742
+ var EIP191_KIND_TAG_FELT = BigInt(shortString.encodeShortString(EIP191_KIND_TAG));
3743
+ var SECP256K1_ORDER = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;
3744
+ function assertBytes(name, b, len) {
3745
+ if (b.length !== len) {
3746
+ throw new Error(`${name} must be exactly ${len} bytes; got ${b.length}.`);
3747
+ }
3748
+ }
3749
+ function bytesBeToU256(b) {
3750
+ assertBytes("secp256k1 32B value", b, 32);
3751
+ let x = 0n;
3752
+ for (let i = 0; i < b.length; i++) x = x << 8n | BigInt(b[i]);
3753
+ return { low: x & (1n << 128n) - 1n, high: x >> 128n };
3754
+ }
3755
+ function eip191PubkeyFelts(pubkey) {
3756
+ const x = bytesBeToU256(pubkey.x);
3757
+ const y = bytesBeToU256(pubkey.y);
3758
+ return [x.low, x.high, y.low, y.high];
3759
+ }
3760
+ function eip191OwnerId(pubkey) {
3761
+ return ownerCommitment(EIP191_KIND_TAG_FELT, eip191PubkeyFelts(pubkey));
3762
+ }
3763
+ function parseEip191Signature(signatureHex) {
3764
+ const hex = signatureHex.startsWith("0x") ? signatureHex.slice(2) : signatureHex;
3765
+ if (hex.length !== 130) {
3766
+ throw new Error(`EIP-191 signature must be 65 bytes (130 hex chars); got ${hex.length}.`);
3767
+ }
3768
+ if (!/^[0-9a-fA-F]+$/.test(hex)) {
3769
+ throw new Error("EIP-191 signature contains non-hex characters.");
3770
+ }
3771
+ const bytes = new Uint8Array(65);
3772
+ for (let i = 0; i < 65; i++) {
3773
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
3774
+ }
3775
+ const r = bytesBeToU256(bytes.slice(0, 32));
3776
+ const s = bytesBeToU256(bytes.slice(32, 64));
3777
+ const v = bytes[64];
3778
+ let yParity;
3779
+ if (v === 27) yParity = 0n;
3780
+ else if (v === 28) yParity = 1n;
3781
+ else if (v === 0) yParity = 0n;
3782
+ else if (v === 1) yParity = 1n;
3783
+ else throw new Error(`Unexpected v byte ${v} in EIP-191 signature; expected 27, 28, 0, or 1.`);
3784
+ if (s.low === 0n && s.high === 0n) {
3785
+ throw new Error("EIP-191 signature s component is zero");
3786
+ }
3787
+ return [r.low, r.high, s.low, s.high, yParity];
3788
+ }
3789
+ function buildEip191EnvelopeFromSignature(params) {
3790
+ const ownerIndex = params.ownerIndex ?? 0n;
3791
+ if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
3792
+ throw new Error(
3793
+ `buildEip191EnvelopeFromSignature: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32).`
3794
+ );
3795
+ }
3796
+ const payload = parseEip191Signature(params.signatureHex);
3797
+ return wrapV2Snip12Envelope({
3798
+ ownerId: ownerIndex,
3799
+ kindTag: EIP191_KIND_TAG,
3800
+ payload
3801
+ });
3802
+ }
3803
+ async function buildEip191EnvelopeFromPrivateKey(params) {
3804
+ const ownerIndex = params.ownerIndex ?? 0n;
3805
+ if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
3806
+ throw new Error(
3807
+ `buildEip191EnvelopeFromPrivateKey: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32).`
3808
+ );
3809
+ }
3810
+ const privBytes = normalizePrivateKey(params.privateKey);
3811
+ const [secp, keccak] = await Promise.all([
3812
+ import('@noble/secp256k1'),
3813
+ // @noble/hashes@2.x ESM exports use the .js suffix per their package.json
3814
+ // exports map.
3815
+ import('@noble/hashes/sha3.js')
3816
+ ]);
3817
+ const msgBe32 = bigintToBe32(params.messageHash);
3818
+ const prefix = new TextEncoder().encode("Ethereum Signed Message:\n32");
3819
+ const prefixedMsg = new Uint8Array(prefix.length + 32);
3820
+ prefixedMsg.set(prefix, 0);
3821
+ prefixedMsg.set(msgBe32, prefix.length);
3822
+ const ethSignedHash = keccak.keccak_256(prefixedMsg);
3823
+ const sig = await secp.signAsync(ethSignedHash, privBytes, {
3824
+ lowS: true
3825
+ });
3826
+ let r = typeof sig.r === "bigint" ? sig.r : BigInt(sig.r);
3827
+ let s = typeof sig.s === "bigint" ? sig.s : BigInt(sig.s);
3828
+ let recovery = typeof sig.recovery === "number" ? sig.recovery : Number(sig.recovery ?? 0);
3829
+ const halfOrder = SECP256K1_ORDER >> 1n;
3830
+ if (s > halfOrder) {
3831
+ s = SECP256K1_ORDER - s;
3832
+ recovery ^= 1;
3833
+ }
3834
+ const rBytes = bigintToBe32(r);
3835
+ const sBytes = bigintToBe32(s);
3836
+ const rU256 = bytesBeToU256(rBytes);
3837
+ const sU256 = bytesBeToU256(sBytes);
3838
+ return wrapV2Snip12Envelope({
3839
+ ownerId: ownerIndex,
3840
+ kindTag: EIP191_KIND_TAG,
3841
+ payload: [rU256.low, rU256.high, sU256.low, sU256.high, BigInt(recovery)]
3842
+ });
3843
+ }
3844
+ function normalizePrivateKey(input) {
3845
+ if (input instanceof Uint8Array) {
3846
+ assertBytes("EIP-191 private key", input, 32);
3847
+ return input;
3848
+ }
3849
+ const hex = input.startsWith("0x") ? input.slice(2) : input;
3850
+ if (hex.length !== 64) {
3851
+ throw new Error(`EIP-191 private key hex must be 64 chars (32 bytes); got ${hex.length}.`);
3852
+ }
3853
+ if (!/^[0-9a-fA-F]+$/.test(hex)) {
3854
+ throw new Error("EIP-191 private key contains non-hex characters.");
3855
+ }
3856
+ const out = new Uint8Array(32);
3857
+ for (let i = 0; i < 32; i++) {
3858
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
3859
+ }
3860
+ return out;
3861
+ }
3862
+ function bigintToBe32(x) {
3863
+ if (x < 0n) throw new Error("bigintToBe32: negative input");
3864
+ const out = new Uint8Array(32);
3865
+ for (let i = 31; i >= 0; i--) {
3866
+ out[i] = Number(x & 0xffn);
3867
+ x >>= 8n;
3868
+ }
3869
+ if (x !== 0n) throw new Error("bigintToBe32: input exceeds 256 bits");
3870
+ return out;
3871
+ }
3872
+
3873
+ // src/shhh/signers/webauthn.ts
3874
+ init_compute_wallet_address();
3875
+ init_oe();
3876
+ var WEBAUTHN_KIND_TAG = "WEBAUTHN_P256";
3877
+ var WEBAUTHN_KIND_TAG_FELT = BigInt(shortString.encodeShortString(WEBAUTHN_KIND_TAG));
3878
+ var P256_ORDER = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
3879
+ function assertBytes2(name, b, len) {
3880
+ if (b.length !== len) {
3881
+ throw new Error(`${name} must be exactly ${len} bytes; got ${b.length}.`);
3882
+ }
3883
+ }
3884
+ function bytesBeToU2562(b) {
3885
+ assertBytes2("32B value", b, 32);
3886
+ let x = 0n;
3887
+ for (let i = 0; i < b.length; i++) x = x << 8n | BigInt(b[i]);
3888
+ return { low: x & (1n << 128n) - 1n, high: x >> 128n };
3889
+ }
3890
+ function bigintToBe322(x) {
3891
+ if (x < 0n) throw new Error("bigintToBe32: negative input");
3892
+ const out = new Uint8Array(32);
3893
+ for (let i = 31; i >= 0; i--) {
3894
+ out[i] = Number(x & 0xffn);
3895
+ x >>= 8n;
3896
+ }
3897
+ if (x !== 0n) throw new Error("bigintToBe32: input exceeds 256 bits");
3898
+ return out;
3899
+ }
3900
+ function base64UrlEncode(bytes) {
3901
+ let bin = "";
3902
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
3903
+ const b64 = typeof Buffer !== "undefined" ? Buffer.from(bytes).toString("base64") : btoa(bin);
3904
+ return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
3905
+ }
3906
+ function byteArrayToFelts(bytes) {
3907
+ const totalFull = Math.floor(bytes.length / 31);
3908
+ const out = [BigInt(totalFull)];
3909
+ for (let i = 0; i < totalFull; i++) {
3910
+ let v = 0n;
3911
+ for (let j = 0; j < 31; j++) v = v << 8n | BigInt(bytes[i * 31 + j]);
3912
+ out.push(v);
3913
+ }
3914
+ const remStart = totalFull * 31;
3915
+ const remLen = bytes.length - remStart;
3916
+ let pending = 0n;
3917
+ for (let j = 0; j < remLen; j++) {
3918
+ pending = pending << 8n | BigInt(bytes[remStart + j]);
3919
+ }
3920
+ out.push(pending);
3921
+ out.push(BigInt(remLen));
3922
+ return out;
3923
+ }
3924
+ function parseDerEcdsaSignature(der) {
3925
+ if (der.length < 8) {
3926
+ throw new Error(`DER: input too short (${der.length} bytes)`);
3927
+ }
3928
+ if (der[0] !== 48) throw new Error("DER: expected SEQUENCE (0x30)");
3929
+ const seqLen = der[1];
3930
+ if (seqLen & 128) {
3931
+ throw new Error("DER: long-form sequence length not supported");
3932
+ }
3933
+ if (2 + seqLen !== der.length) {
3934
+ throw new Error(
3935
+ `DER: declared sequence length ${seqLen} does not match buffer (${der.length - 2})`
3936
+ );
3937
+ }
3938
+ let off = 2;
3939
+ if (der[off] !== 2) throw new Error("DER: expected INTEGER (0x02) for r");
3940
+ const rLen = der[off + 1];
3941
+ if (rLen === 0) throw new Error("DER: r component has zero length");
3942
+ if (off + 2 + rLen > der.length) {
3943
+ throw new Error(`DER: r length ${rLen} overruns buffer at offset ${off + 2}`);
3944
+ }
3945
+ off += 2;
3946
+ let rBytes = new Uint8Array(rLen);
3947
+ rBytes.set(der.subarray(off, off + rLen));
3948
+ off += rLen;
3949
+ if (off + 2 > der.length) {
3950
+ throw new Error("DER: no room for s INTEGER header");
3951
+ }
3952
+ if (der[off] !== 2) throw new Error("DER: expected INTEGER (0x02) for s");
3953
+ const sLen = der[off + 1];
3954
+ if (sLen === 0) throw new Error("DER: s component has zero length");
3955
+ if (off + 2 + sLen > der.length) {
3956
+ throw new Error(`DER: s length ${sLen} overruns buffer at offset ${off + 2}`);
3957
+ }
3958
+ off += 2;
3959
+ let sBytes = new Uint8Array(sLen);
3960
+ sBytes.set(der.subarray(off, off + sLen));
3961
+ rBytes = leftPadTo32(stripLeadingZero(rBytes));
3962
+ sBytes = leftPadTo32(stripLeadingZero(sBytes));
3963
+ return { r: rBytes, s: sBytes };
3964
+ }
3965
+ function stripLeadingZero(b) {
3966
+ const start = b.length > 0 && b[0] === 0 ? 1 : 0;
3967
+ const out = new Uint8Array(b.length - start);
3968
+ out.set(b.subarray(start));
3969
+ return out;
3970
+ }
3971
+ function leftPadTo32(b) {
3972
+ if (b.length > 32) throw new Error(`P-256 component longer than 32 bytes: ${b.length}`);
3973
+ const out = new Uint8Array(32);
3974
+ out.set(b, 32 - b.length);
3975
+ return out;
3976
+ }
3977
+ function webauthnPubkeyFelts(pub) {
3978
+ const x = bytesBeToU2562(pub.x);
3979
+ const y = bytesBeToU2562(pub.y);
3980
+ return [x.low, x.high, y.low, y.high];
3981
+ }
3982
+ function webauthnOwnerId(pub) {
3983
+ return ownerCommitment(WEBAUTHN_KIND_TAG_FELT, webauthnPubkeyFelts(pub));
3984
+ }
3985
+ function buildWebAuthnEnvelopeFromAssertion(params) {
3986
+ const ownerIndex = params.ownerIndex ?? 0n;
3987
+ if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
3988
+ throw new Error(
3989
+ `buildWebAuthnEnvelopeFromAssertion: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32).`
3990
+ );
3991
+ }
3992
+ const { r, s } = parseDerEcdsaSignature(params.signatureDer);
3993
+ const expectedChallenge = base64UrlEncode(bigintToBe322(params.messageHash));
3994
+ const needle = `"challenge":"${expectedChallenge}"`;
3995
+ const clientDataStr = new TextDecoder().decode(params.clientDataJSON);
3996
+ const needleStart = clientDataStr.indexOf(needle);
3997
+ if (needleStart < 0) {
3998
+ throw new Error(
3999
+ 'WebAuthn clientDataJSON does not contain a `"challenge":"<expected>"` substring for the given messageHash.'
4000
+ );
4001
+ }
4002
+ const challengeOffset = needleStart + '"challenge":"'.length;
4003
+ const rU = bytesBeToU2562(r);
4004
+ const sU = bytesBeToU2562(s);
4005
+ const payload = [
4006
+ ...byteArrayToFelts(params.authenticatorData),
4007
+ ...byteArrayToFelts(params.clientDataJSON),
4008
+ BigInt(challengeOffset),
4009
+ rU.low,
4010
+ rU.high,
4011
+ sU.low,
4012
+ sU.high,
4013
+ params.yParity ?? 0n
4014
+ ];
4015
+ return wrapV2Snip12Envelope({
4016
+ ownerId: ownerIndex,
4017
+ kindTag: WEBAUTHN_KIND_TAG,
4018
+ payload
4019
+ });
4020
+ }
4021
+ async function buildWebAuthnEnvelopeFromPrivateKey(params) {
4022
+ const ownerIndex = params.ownerIndex ?? 0n;
4023
+ if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
4024
+ throw new Error(
4025
+ `buildWebAuthnEnvelopeFromPrivateKey: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32).`
4026
+ );
4027
+ }
4028
+ const privBytes = normalizePrivateKey2(params.privateKey);
4029
+ const rpId = params.rpId ?? "cifra.mx";
4030
+ const origin = params.origin ?? "https://cifra.mx";
4031
+ const flags = params.flags ?? 5;
4032
+ const signCount = params.signCount ?? 42;
4033
+ if (!Number.isInteger(flags) || flags < 0 || flags > 255) {
4034
+ throw new Error(`WebAuthn flags must be an integer in [0, 255]; got ${flags}.`);
4035
+ }
4036
+ if (!Number.isInteger(signCount) || signCount < 0 || signCount > 4294967295) {
4037
+ throw new Error(`WebAuthn signCount must be an integer in [0, 0xFFFFFFFF]; got ${signCount}.`);
4038
+ }
4039
+ const [{ p256 }, sha2] = await Promise.all([
4040
+ import('@noble/curves/nist.js'),
4041
+ import('@noble/hashes/sha2.js')
4042
+ ]);
4043
+ const hashBytes = bigintToBe322(params.messageHash);
4044
+ const challengeStr = base64UrlEncode(hashBytes);
4045
+ const clientDataStr = `{"type":"webauthn.get","challenge":"${challengeStr}","origin":"${origin}","crossOrigin":false}`;
4046
+ const clientData = new TextEncoder().encode(clientDataStr);
4047
+ const challengeOffset = clientDataStr.indexOf(`"challenge":"${challengeStr}"`) + '"challenge":"'.length;
4048
+ const rpIdHash = sha2.sha256(new TextEncoder().encode(rpId));
4049
+ const authData = new Uint8Array(32 + 1 + 4);
4050
+ authData.set(rpIdHash, 0);
4051
+ authData[32] = flags;
4052
+ authData[33] = signCount >>> 24 & 255;
4053
+ authData[34] = signCount >>> 16 & 255;
4054
+ authData[35] = signCount >>> 8 & 255;
4055
+ authData[36] = signCount & 255;
4056
+ const hClient = sha2.sha256(clientData);
4057
+ const signingBase = new Uint8Array(authData.length + hClient.length);
4058
+ signingBase.set(authData, 0);
4059
+ signingBase.set(hClient, authData.length);
4060
+ const outerHash = sha2.sha256(signingBase);
4061
+ const sigBytes = p256.sign(outerHash, privBytes, {
4062
+ prehash: false
4063
+ });
4064
+ if (sigBytes.length !== 64) {
4065
+ throw new Error(`p256.sign returned ${sigBytes.length} bytes; expected 64`);
4066
+ }
4067
+ let r = bytesBeToBigint(sigBytes.slice(0, 32));
4068
+ let s = bytesBeToBigint(sigBytes.slice(32, 64));
4069
+ const halfOrder = P256_ORDER >> 1n;
4070
+ if (s > halfOrder) s = P256_ORDER - s;
4071
+ const rBytes = bigintToBe322(r);
4072
+ const sBytes = bigintToBe322(s);
4073
+ const rU = bytesBeToU2562(rBytes);
4074
+ const sU = bytesBeToU2562(sBytes);
4075
+ const payload = [
4076
+ ...byteArrayToFelts(authData),
4077
+ ...byteArrayToFelts(clientData),
4078
+ BigInt(challengeOffset),
4079
+ rU.low,
4080
+ rU.high,
4081
+ sU.low,
4082
+ sU.high,
4083
+ 0n
4084
+ // y_parity — Cairo verifier handles parity recovery internally
4085
+ ];
4086
+ return wrapV2Snip12Envelope({
4087
+ ownerId: ownerIndex,
4088
+ kindTag: WEBAUTHN_KIND_TAG,
4089
+ payload
4090
+ });
4091
+ }
4092
+ function normalizePrivateKey2(input) {
4093
+ if (input instanceof Uint8Array) {
4094
+ assertBytes2("P-256 private key", input, 32);
4095
+ return input;
4096
+ }
4097
+ const hex = input.startsWith("0x") ? input.slice(2) : input;
4098
+ if (hex.length !== 64) {
4099
+ throw new Error(`P-256 private key hex must be 64 chars (32 bytes); got ${hex.length}.`);
4100
+ }
4101
+ if (!/^[0-9a-fA-F]+$/.test(hex)) {
4102
+ throw new Error("P-256 private key contains non-hex characters.");
4103
+ }
4104
+ const out = new Uint8Array(32);
4105
+ for (let i = 0; i < 32; i++) {
4106
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
4107
+ }
4108
+ return out;
4109
+ }
4110
+ function bytesBeToBigint(b) {
4111
+ let x = 0n;
4112
+ for (let i = 0; i < b.length; i++) x = x << 8n | BigInt(b[i]);
4113
+ return x;
4114
+ }
4115
+
4116
+ // src/shhh/signers/jwt_apple_sub.ts
4117
+ init_compute_wallet_address();
4118
+ init_oe();
4119
+ var JWT_APPLE_SUB_KIND_TAG = "JWT_ES256_APPLE_SUB";
4120
+ var JWT_APPLE_SUB_KIND_TAG_FELT = BigInt(shortString.encodeShortString(JWT_APPLE_SUB_KIND_TAG));
4121
+ var APPLE_ISSUER = "https://appleid.apple.com";
4122
+ var NONCE_B64URL_LEN = 43;
4123
+ var U128_MASK = (1n << 128n) - 1n;
4124
+ function assertBytes3(name, b, len) {
4125
+ if (b.length !== len) {
4126
+ throw new Error(`${name} must be exactly ${len} bytes; got ${b.length}.`);
4127
+ }
4128
+ }
4129
+ function bytesBeToU2563(b) {
4130
+ assertBytes3("secp256r1 32B value", b, 32);
4131
+ let x = 0n;
4132
+ for (let i = 0; i < b.length; i++) x = x << 8n | BigInt(b[i]);
4133
+ return { low: x & U128_MASK, high: x >> 128n };
4134
+ }
4135
+ function jwtAppleSubHash(sub) {
4136
+ const bytes = new TextEncoder().encode(sub);
4137
+ const felts = Array.from(bytes).map((b) => BigInt(b));
4138
+ return BigInt(hash.computePoseidonHashOnElements(felts.map((f) => "0x" + f.toString(16))));
4139
+ }
4140
+ function jwtAppleSubPubkeyFelts(pubkey) {
4141
+ const x = bytesBeToU2563(pubkey.x);
4142
+ const y = bytesBeToU2563(pubkey.y);
4143
+ const subHash = jwtAppleSubHash(pubkey.sub);
4144
+ return [x.low, x.high, y.low, y.high, subHash];
4145
+ }
4146
+ function jwtAppleSubOwnerId(pubkey) {
4147
+ return ownerCommitment(JWT_APPLE_SUB_KIND_TAG_FELT, jwtAppleSubPubkeyFelts(pubkey));
4148
+ }
4149
+ function base64urlEncode(bytes) {
4150
+ let bin = "";
4151
+ for (const b of bytes) bin += String.fromCharCode(b);
4152
+ const b64 = btoaPortable(bin);
4153
+ return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
4154
+ }
4155
+ function btoaPortable(bin) {
4156
+ if (typeof btoa === "function") return btoa(bin);
4157
+ const buf = globalThis.Buffer;
4158
+ if (buf) return buf.from(bin, "binary").toString("base64");
4159
+ throw new Error("no base64 encoder available (need btoa or Buffer in scope)");
4160
+ }
4161
+ function base64urlDecode(s) {
4162
+ const pad = s.length % 4 === 0 ? 0 : 4 - s.length % 4;
4163
+ const std = s.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat(pad);
4164
+ const bin = atobPortable(std);
4165
+ const out = new Uint8Array(bin.length);
4166
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
4167
+ return out;
4168
+ }
4169
+ function atobPortable(s) {
4170
+ if (typeof atob === "function") return atob(s);
4171
+ const buf = globalThis.Buffer;
4172
+ if (buf) return buf.from(s, "base64").toString("binary");
4173
+ throw new Error("no base64 decoder available (need atob or Buffer in scope)");
4174
+ }
4175
+ function messageHashToNonceB64url(messageHash) {
4176
+ const beBytes = new Uint8Array(32);
4177
+ let x = messageHash;
4178
+ for (let i = 31; i >= 0; i--) {
4179
+ beBytes[i] = Number(x & 0xffn);
4180
+ x >>= 8n;
4181
+ }
4182
+ if (x !== 0n) {
4183
+ throw new RangeError("messageHash exceeds 256 bits");
4184
+ }
4185
+ const out = base64urlEncode(beBytes);
4186
+ if (out.length !== NONCE_B64URL_LEN) {
4187
+ throw new Error(`expected ${NONCE_B64URL_LEN}-char nonce b64url, got ${out.length}`);
4188
+ }
4189
+ return out;
4190
+ }
4191
+ function findByteOffset(haystack, needle, label) {
4192
+ outer: for (let i = 0; i + needle.length <= haystack.length; i++) {
4193
+ for (let j = 0; j < needle.length; j++) {
4194
+ if (haystack[i + j] !== needle[j]) continue outer;
4195
+ }
4196
+ return i;
4197
+ }
4198
+ throw new Error(`JWT_APPLE_SUB: ${label} not found in payload (verifier would reject)`);
4199
+ }
4200
+ function locateExactClaimValueOffset(payload, claim, expectedValue) {
4201
+ const literal = `"${claim}":"${expectedValue}"`;
4202
+ const literalBytes = new TextEncoder().encode(literal);
4203
+ const idx = findByteOffsetOrMinusOne(payload, literalBytes);
4204
+ if (idx < 0) {
4205
+ throw new Error(
4206
+ `JWT_APPLE_SUB: ${claim} claim with expected value not found in payload (verifier would reject)`
4207
+ );
4208
+ }
4209
+ const prefix = `"${claim}":"`;
4210
+ return idx + new TextEncoder().encode(prefix).length;
4211
+ }
4212
+ function findByteOffsetOrMinusOne(haystack, needle) {
4213
+ outer: for (let i = 0; i + needle.length <= haystack.length; i++) {
4214
+ for (let j = 0; j < needle.length; j++) {
4215
+ if (haystack[i + j] !== needle[j]) continue outer;
4216
+ }
4217
+ return i;
4218
+ }
4219
+ return -1;
4220
+ }
4221
+ function parseAppleIdToken(idToken) {
4222
+ const parts = idToken.split(".");
4223
+ if (parts.length !== 3) {
4224
+ throw new Error(
4225
+ `JWT_APPLE_SUB: id_token must have 3 parts separated by '.'; got ${parts.length}`
4226
+ );
4227
+ }
4228
+ const [headerB64, payloadB64, sigB64] = parts;
4229
+ const payloadDecoded = base64urlDecode(payloadB64);
4230
+ const rawSignature = base64urlDecode(sigB64);
4231
+ if (rawSignature.length !== 64) {
4232
+ throw new Error(
4233
+ `JWT_APPLE_SUB: ECDSA signature must be 64 bytes (raw r||s); got ${rawSignature.length}. Apple returns raw 64-byte signatures; if you have a DER-encoded one, decode it first.`
4234
+ );
4235
+ }
4236
+ return { headerB64, payloadDecoded, rawSignature };
4237
+ }
4238
+ function locateSubClaim(payload) {
4239
+ const SUB_KEY = new TextEncoder().encode('"sub":"');
4240
+ const start = findByteOffset(payload, SUB_KEY, '"sub":"');
4241
+ const valueStart = start + SUB_KEY.length;
4242
+ let end = valueStart;
4243
+ while (end < payload.length && payload[end] !== 34) {
4244
+ if (payload[end] === 92) {
4245
+ throw new Error("JWT_APPLE_SUB: sub claim contains escape sequence; not supported");
4246
+ }
4247
+ end += 1;
4248
+ }
4249
+ if (end >= payload.length) {
4250
+ throw new Error("JWT_APPLE_SUB: sub claim is unterminated");
4251
+ }
4252
+ return { offset: valueStart, length: end - valueStart };
4253
+ }
4254
+ function serdeByteArray(bytes) {
4255
+ return byteArrayToFelts(bytes);
4256
+ }
4257
+ function buildEnvelopePayload(fields) {
4258
+ const headerBytes = new TextEncoder().encode(fields.headerB64);
4259
+ const headerSerde = serdeByteArray(headerBytes);
4260
+ const payloadSerde = serdeByteArray(fields.payloadDecoded);
4261
+ return [
4262
+ ...headerSerde,
4263
+ ...payloadSerde,
4264
+ BigInt(fields.nonceOffset),
4265
+ BigInt(fields.issOffset),
4266
+ BigInt(fields.subOffset),
4267
+ BigInt(fields.subLen),
4268
+ fields.r & U128_MASK,
4269
+ fields.r >> 128n,
4270
+ fields.s & U128_MASK,
4271
+ fields.s >> 128n,
4272
+ BigInt(fields.yParity)
4273
+ ];
4274
+ }
4275
+ function buildJwtAppleSubEnvelopeFromTokenResponse(params) {
4276
+ const ownerIndex = params.ownerIndex ?? 0n;
4277
+ if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
4278
+ throw new Error(
4279
+ `buildJwtAppleSubEnvelopeFromTokenResponse: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32).`
4280
+ );
4281
+ }
4282
+ const { headerB64, payloadDecoded, rawSignature } = parseAppleIdToken(params.idToken);
4283
+ const expectedNonce = messageHashToNonceB64url(params.messageHash);
4284
+ const nonceOffset = locateExactClaimValueOffset(payloadDecoded, "nonce", expectedNonce);
4285
+ const issOffset = locateExactClaimValueOffset(payloadDecoded, "iss", APPLE_ISSUER);
4286
+ const { offset: subOffset, length: subLen } = locateSubClaim(payloadDecoded);
4287
+ const actualSub = new TextDecoder().decode(
4288
+ payloadDecoded.subarray(subOffset, subOffset + subLen)
4289
+ );
4290
+ if (actualSub !== params.pubkey.sub) {
4291
+ throw new Error(
4292
+ `JWT_APPLE_SUB: id_token sub "${actualSub}" doesn't match pubkey.sub "${params.pubkey.sub}" \u2014 wrong user signed in`
4293
+ );
4294
+ }
4295
+ const { r, s } = parseRawEcdsaSignature(rawSignature);
4296
+ const yParity = 0;
4297
+ return wrapV2Snip12Envelope({
4298
+ ownerId: ownerIndex,
4299
+ kindTag: JWT_APPLE_SUB_KIND_TAG,
4300
+ payload: buildEnvelopePayload({
4301
+ headerB64,
4302
+ payloadDecoded,
4303
+ nonceOffset,
4304
+ issOffset,
4305
+ subOffset,
4306
+ subLen,
4307
+ r,
4308
+ s,
4309
+ yParity
4310
+ })
4311
+ });
4312
+ }
4313
+ function parseRawEcdsaSignature(raw) {
4314
+ if (raw.length !== 64) {
4315
+ throw new Error(`JWT_APPLE_SUB: ECDSA signature must be 64 bytes; got ${raw.length}`);
4316
+ }
4317
+ let r = 0n;
4318
+ for (let i = 0; i < 32; i++) r = r << 8n | BigInt(raw[i]);
4319
+ let s = 0n;
4320
+ for (let i = 32; i < 64; i++) s = s << 8n | BigInt(raw[i]);
4321
+ return { r, s };
4322
+ }
4323
+ async function buildJwtAppleSubEnvelopeFromTestKey(params) {
4324
+ const ownerIndex = params.ownerIndex ?? 0n;
4325
+ if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
4326
+ throw new Error(
4327
+ `buildJwtAppleSubEnvelopeFromTestKey: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32).`
4328
+ );
4329
+ }
4330
+ const { p256 } = await import('@noble/curves/nist.js');
4331
+ const { sha256 } = await import('@noble/hashes/sha2.js');
4332
+ if (params.privateKey.length !== 32) {
4333
+ throw new Error(
4334
+ `JWT_APPLE_SUB: P-256 private key must be 32 bytes; got ${params.privateKey.length}`
4335
+ );
4336
+ }
4337
+ const pubUncompressed = p256.getPublicKey(params.privateKey, false);
4338
+ if (pubUncompressed.length !== 65 || pubUncompressed[0] !== 4) {
4339
+ throw new Error("expected 65-byte uncompressed P-256 pubkey");
4340
+ }
4341
+ const pubkey = {
4342
+ x: pubUncompressed.slice(1, 33),
4343
+ y: pubUncompressed.slice(33, 65),
4344
+ sub: params.sub
4345
+ };
4346
+ const headerJson = JSON.stringify({ alg: "ES256", kid: "synthesized" });
4347
+ const headerB64 = base64urlEncode(new TextEncoder().encode(headerJson));
4348
+ const now = Math.floor(Date.now() / 1e3);
4349
+ const nonce = messageHashToNonceB64url(params.messageHash);
4350
+ const payloadObject = {
4351
+ iss: APPLE_ISSUER,
4352
+ aud: params.aud,
4353
+ sub: params.sub,
4354
+ iat: now,
4355
+ exp: now + 600,
4356
+ nonce
4357
+ };
4358
+ const payloadJson = JSON.stringify(payloadObject);
4359
+ const payloadDecoded = new TextEncoder().encode(payloadJson);
4360
+ const payloadB64 = base64urlEncode(payloadDecoded);
4361
+ const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
4362
+ const digest = sha256(signingInput);
4363
+ const rawSig = p256.sign(digest, params.privateKey, {
4364
+ lowS: true
4365
+ });
4366
+ if (rawSig.length !== 64) {
4367
+ throw new Error(`expected 64-byte raw ECDSA signature from p256.sign; got ${rawSig.length}`);
4368
+ }
4369
+ const { r, s } = parseRawEcdsaSignature(rawSig);
4370
+ const idToken = `${headerB64}.${payloadB64}.${base64urlEncode(rawSig)}`;
4371
+ const nonceOffset = locateExactClaimValueOffset(payloadDecoded, "nonce", nonce);
4372
+ const issOffset = locateExactClaimValueOffset(payloadDecoded, "iss", APPLE_ISSUER);
4373
+ const { offset: subOffset, length: subLen } = locateSubClaim(payloadDecoded);
4374
+ const envelope = wrapV2Snip12Envelope({
4375
+ ownerId: ownerIndex,
4376
+ kindTag: JWT_APPLE_SUB_KIND_TAG,
4377
+ payload: buildEnvelopePayload({
4378
+ headerB64,
4379
+ payloadDecoded,
4380
+ nonceOffset,
4381
+ issOffset,
4382
+ subOffset,
4383
+ subLen,
4384
+ r,
4385
+ s,
4386
+ yParity: 0
4387
+ })
4388
+ });
4389
+ return { envelope, pubkey, idToken };
4390
+ }
4391
+ var ROLE_OWNER = BigInt(shortString.encodeShortString("OWNER"));
4392
+ var ROLE_GUARDIAN = BigInt(shortString.encodeShortString("GUARDIAN"));
4393
+ var OP_ADD_OWNER = BigInt(shortString.encodeShortString("ADD_OWNER"));
4394
+ var OP_REMOVE_OWNER = BigInt(shortString.encodeShortString("REMOVE_OWNER"));
4395
+ var OP_ROTATE_OWNER = BigInt(shortString.encodeShortString("ROTATE_OWNER"));
4396
+ var OP_SET_THRESHOLD = BigInt(shortString.encodeShortString("SET_THRESHOLD"));
4397
+ var TIMELOCK_SECONDS = {
4398
+ ADD_OWNER: 172800,
4399
+ // 48h
4400
+ REMOVE_OWNER: 86400,
4401
+ // 24h
4402
+ ROTATE_OWNER: 86400,
4403
+ // 24h
4404
+ SET_THRESHOLD: 172800,
4405
+ // 48h
4406
+ ADD_VERIFIER: 172800,
4407
+ // 48h
4408
+ REMOVE_VERIFIER: 86400,
4409
+ // 24h
4410
+ ADD_GUARDIAN: 86400,
4411
+ // 24h
4412
+ REMOVE_GUARDIAN: 86400,
4413
+ // 24h
4414
+ RECOVERY: 604800
4415
+ // 7d — `TIMELOCK_RECOVERY`, the headline UX gate
4416
+ };
4417
+ var DEFAULT_OP_EXPIRY_SECONDS = 1209600;
4418
+ function _felt2(x, field = "felt") {
4419
+ const v = typeof x === "bigint" ? x : BigInt(x);
4420
+ if (v < 0n) {
4421
+ throw new RangeError(`${field} must be a non-negative felt; got ${v.toString()}`);
4422
+ }
4423
+ return v;
4424
+ }
4425
+ function _encodeOwnerInput(input) {
4426
+ if (input.weight < 0) {
4427
+ throw new RangeError(`NewOwnerInput.weight must be non-negative; got ${input.weight}`);
4428
+ }
4429
+ const kindFelt = _felt2(BigInt(shortString.encodeShortString(input.kind)), "kind");
4430
+ const roleFelt = input.role === "OWNER" ? ROLE_OWNER : ROLE_GUARDIAN;
4431
+ const pubkey = input.pubkeyBytes.map((p, i) => _felt2(p, `pubkeyBytes[${i}]`));
4432
+ return [
4433
+ kindFelt,
4434
+ BigInt(pubkey.length),
4435
+ ...pubkey,
4436
+ roleFelt,
4437
+ BigInt(input.weight),
4438
+ _felt2(BigInt(shortString.encodeShortString(input.label)), "label")
4439
+ ];
4440
+ }
4441
+ function _call(walletAddress, entrypoint, calldata) {
4442
+ for (let i = 0; i < calldata.length; i++) {
4443
+ if (calldata[i] < 0n) {
4444
+ throw new RangeError(
4445
+ `calldata[${i}] must be a non-negative felt; got ${calldata[i].toString()}`
4446
+ );
4447
+ }
4448
+ }
4449
+ return {
4450
+ contractAddress: typeof walletAddress === "bigint" ? "0x" + walletAddress.toString(16) : walletAddress,
4451
+ entrypoint,
4452
+ calldata: calldata.map((v) => "0x" + v.toString(16))
4453
+ };
4454
+ }
4455
+ function buildProposeAddOwnerCall(args) {
4456
+ const calldata = [BigInt(args.proposer), ..._encodeOwnerInput(args.newOwner)];
4457
+ return _call(args.walletAddress, "propose_add_owner", calldata);
4458
+ }
4459
+ function buildExecuteAddOwnerCall(args) {
4460
+ const calldata = [_felt2(args.opId), ..._encodeOwnerInput(args.newOwner)];
4461
+ return _call(args.walletAddress, "execute_add_owner", calldata);
4462
+ }
4463
+ function buildProposeRemoveOwnerCall(args) {
4464
+ return _call(args.walletAddress, "propose_remove_owner", [
4465
+ BigInt(args.proposer),
4466
+ BigInt(args.ownerId)
4467
+ ]);
4468
+ }
4469
+ function buildExecuteRemoveOwnerCall(args) {
4470
+ return _call(args.walletAddress, "execute_remove_owner", [
4471
+ _felt2(args.opId),
4472
+ BigInt(args.ownerId)
4473
+ ]);
4474
+ }
4475
+ function buildProposeRotateOwnerCall(args) {
4476
+ return _call(args.walletAddress, "propose_rotate_owner", [
4477
+ BigInt(args.proposer),
4478
+ BigInt(args.ownerId),
4479
+ BigInt(args.newPubkeyBytes.length),
4480
+ ...args.newPubkeyBytes
4481
+ ]);
4482
+ }
4483
+ function buildExecuteRotateOwnerCall(args) {
4484
+ return _call(args.walletAddress, "execute_rotate_owner", [
4485
+ _felt2(args.opId),
4486
+ BigInt(args.ownerId),
4487
+ BigInt(args.newPubkeyBytes.length),
4488
+ ...args.newPubkeyBytes
4489
+ ]);
4490
+ }
4491
+ function buildProposeSetThresholdCall(args) {
4492
+ return _call(args.walletAddress, "propose_set_threshold", [
4493
+ BigInt(args.proposer),
4494
+ BigInt(args.newThreshold)
4495
+ ]);
4496
+ }
4497
+ function buildExecuteSetThresholdCall(args) {
4498
+ return _call(args.walletAddress, "execute_set_threshold", [
4499
+ _felt2(args.opId),
4500
+ BigInt(args.newThreshold)
4501
+ ]);
4502
+ }
4503
+ function buildCancelPendingOpCall(args) {
4504
+ return _call(args.walletAddress, "cancel_pending_op", [_felt2(args.opId)]);
4505
+ }
4506
+ function buildInitiateRecoveryCall(args) {
4507
+ const calldata = [BigInt(args.proposer), ..._encodeOwnerInput(args.newOwner)];
4508
+ return _call(args.walletAddress, "initiate_recovery", calldata);
4509
+ }
4510
+ function buildCancelRecoveryCall(args) {
4511
+ return _call(args.walletAddress, "cancel_recovery", [BigInt(args.ownerId)]);
4512
+ }
4513
+ function buildFinalizeRecoveryCall(args) {
4514
+ return _call(args.walletAddress, "finalize_recovery", _encodeOwnerInput(args.newOwner));
4515
+ }
4516
+ var VIEW_SELECTORS = {
4517
+ get_pending_op: hash.getSelectorFromName("get_pending_op"),
4518
+ get_pending_recovery: hash.getSelectorFromName("get_pending_recovery"),
4519
+ get_owner: hash.getSelectorFromName("get_owner")
4520
+ };
4521
+ function _toSecondsBigInt(value, field) {
4522
+ if (typeof value === "bigint") return value;
4523
+ if (!Number.isFinite(value)) {
4524
+ throw new TypeError(`${field} must be a finite timestamp; got ${value}`);
4525
+ }
4526
+ return BigInt(Math.floor(value));
4527
+ }
4528
+ function isReadyToExecute(validAfterSecs, nowSecs) {
4529
+ return _toSecondsBigInt(nowSecs, "nowSecs") >= _toSecondsBigInt(validAfterSecs, "validAfterSecs");
4530
+ }
4531
+ function secondsUntilExecutable(validAfterSecs, nowSecs) {
4532
+ const remaining = _toSecondsBigInt(validAfterSecs, "validAfterSecs") - _toSecondsBigInt(nowSecs, "nowSecs");
4533
+ return remaining <= 0n ? 0 : Number(remaining);
4534
+ }
4535
+
4536
+ // src/shhh/index.ts
4537
+ init_threshold();
4538
+ init_execute_paymaster_raw();
4539
+
4540
+ export { ANY_CALLER_FELT, APPLE_ISSUER, BOOTSTRAP_DOMAIN_SEPARATOR, ChipiBrowserSDK, ChipiClient, ChipiPaymasterAdapter, ChipiSDK, ChipiServerSDK, ChipiSessions, ChipiSkuPurchases, ChipiSkus, ChipiTransactions, ChipiWallets, DEFAULT_OP_EXPIRY_SECONDS, ISIGNER_CANONICAL_LABEL, ISIGNER_ID, ISRC9_V2_ID, MAX_OE_VALIDITY_WINDOW_SECONDS, MIN_THRESHOLD_OWNERS, OE_DOMAIN_NAME, OE_DOMAIN_REVISION, OE_DOMAIN_VERSION, OP_ADD_OWNER, OP_REMOVE_OWNER, OP_ROTATE_OWNER, OP_SET_THRESHOLD, ROLE_GUARDIAN, ROLE_OWNER, SIG_VERSION_V1_HEX_ASCII, SIG_VERSION_V2_SNIP12, SIG_VERSION_V2_THRESHOLD, STARKNET_MESSAGE_PREFIX, TIMELOCK_SECONDS, VIEW_SELECTORS, X402Facilitator, X402ShhhClient, assertValidV2Snip12Envelope, buildBootstrapSignedCall, buildCancelPendingOpCall, buildCancelRecoveryCall, buildEd25519Envelope, buildEd25519EnvelopeFromSignature, buildEip191EnvelopeFromPrivateKey, buildEip191EnvelopeFromSignature, buildExecuteAddOwnerCall, buildExecuteRemoveOwnerCall, buildExecuteRotateOwnerCall, buildExecuteSetThresholdCall, buildFinalizeRecoveryCall, buildInitiateRecoveryCall, buildJwtAppleSubEnvelopeFromTestKey, buildJwtAppleSubEnvelopeFromTokenResponse, buildMigrationCalls, buildOutsideExecution, buildProposeAddOwnerCall, buildProposeRemoveOwnerCall, buildProposeRotateOwnerCall, buildProposeSetThresholdCall, buildStarkEnvelope, buildThresholdEnvelope, buildWebAuthnEnvelopeFromAssertion, buildWebAuthnEnvelopeFromPrivateKey, byteArrayToFelts, computeAddressSalt, computeBootstrapMessage, computeISignerId, computeOeHash, computeShhhAddress, computeSnip12Hash, decryptPrivateKey, ed25519OwnerId, ed25519PubkeyFelts, ed25519SignedBytes, eip191OwnerId, eip191PubkeyFelts, encryptPrivateKey, estimateThresholdGasOverhead, executeShhhSponsoredRaw, hashCall, hashCalls, hashOutsideExecutionStruct, hashStarknetDomain, isReadyToExecute, jwtAppleSubHash, jwtAppleSubOwnerId, jwtAppleSubPubkeyFelts, labelToFelt, locateSubClaim, messageHashToNonceB64url, migrateChipiWalletToShhh, ownerCommitment, parseAppleIdToken, parseDerEcdsaSignature, parseEip191Signature, parseThresholdEnvelope, resolveShhhChainId, secondsUntilExecutable, serializeExecuteFromOutsideV2Calldata, signBootstrapMessage, signTypedData, snip12HashToHexAsciiBytes, starkOwnerId, starkPubkeyFelts, webauthnOwnerId, webauthnPubkeyFelts, wrapV2Snip12Envelope, wrapV2ThresholdEnvelope, x402Middleware };
2447
4541
  //# sourceMappingURL=index.mjs.map
2448
4542
  //# sourceMappingURL=index.mjs.map