@dynamic-labs-wallet/aleo 0.0.0 → 0.0.331

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/index.esm.js ADDED
@@ -0,0 +1,3316 @@
1
+ import { AuthMode, DynamicWalletClient, ERROR_PASSWORD_MISMATCH, getMPCChainConfig, getMPCSigner } from '@dynamic-labs-wallet/browser';
2
+ import * as AleoSdkMainnet from '@provablehq/sdk/mainnet.js';
3
+ import * as AleoSdkTestnet from '@provablehq/sdk/testnet.js';
4
+
5
+ var ERROR_KEYGEN_FAILED = 'Error with Aleo keygen';
6
+ var ERROR_CREATE_WALLET_ACCOUNT = 'Error creating Aleo wallet account';
7
+ var ERROR_ACCOUNT_ADDRESS_REQUIRED = 'Account address is required';
8
+ var ERROR_EXPORT_PRIVATE_KEY = 'Error exporting Aleo private key';
9
+ var ERROR_IMPORT_PRIVATE_KEY_NOT_SUPPORTED = 'Aleo importPrivateKey is not supported yet';
10
+ var ERROR_SIGN_MESSAGE_NOT_SUPPORTED = 'Aleo signMessage is not supported yet — pending arbitrary-bytes EdBls12377 signing';
11
+ var ERROR_SIGN_TRANSACTION_NOT_SUPPORTED = 'Aleo signTransaction is not supported yet — coming in Phase 2';
12
+ var ALEO_NETWORKS = {
13
+ MAINNET: 'mainnet',
14
+ TESTNET: 'testnet'
15
+ };
16
+ /**
17
+ * Default Provable Delegated Proving Service endpoint.
18
+ * Used by `submitProvingRequest` — Provable computes the ZK proof on their
19
+ * accelerator hardware and (optionally) broadcasts. No API key required for
20
+ * testnet during Phase 2.
21
+ */ var DEFAULT_PROVABLE_PROVER_URI = 'https://accelerate.provable.com';
22
+
23
+ /**
24
+ * IndexedDB-backed persistence for Aleo per-wallet record-scanner state.
25
+ *
26
+ * We cache the scanner's UUID, the owned-records list, and the spent-record
27
+ * nonces per accountAddress so subsequent queries resume from the last known
28
+ * state instead of re-registering with Provable's scanner on every page load.
29
+ *
30
+ * Storage shape (object store "state", keyed by `${accountAddress}:${network}`):
31
+ * { accountAddress, network, scannerUuid, records, spentNonces, lastScannedBlock,
32
+ * sealanceProofs, updatedAt }
33
+ *
34
+ * The keyPath value is the composite `${accountAddress}:${network}` so testnet
35
+ * and mainnet entries for the same wallet don't collide. Pre-network-aware
36
+ * entries (raw `accountAddress` keys) are functionally orphaned by the new
37
+ * composite lookups and will simply be re-registered on first call. Acceptable
38
+ * one-time cost; avoids a DB schema migration / version bump.
39
+ *
40
+ * `records` is a JSON-stringified array of `OwnedRecord` — keeping it as a
41
+ * string lets us cache decrypted plaintexts without imposing a Provable SDK
42
+ * type dependency on this persistence module.
43
+ *
44
+ * Security: blobs are stored plaintext, matching Dynamic's existing policy
45
+ * for locally-cached key material. Protection comes from the iframe's origin
46
+ * isolation, not at-rest encryption. Cloned from Midnight's
47
+ * walletStateStorage.ts; a future refactor may extract a generic kv store.
48
+ */ function asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, key, arg) {
49
+ try {
50
+ var info = gen[key](arg);
51
+ var value = info.value;
52
+ } catch (error) {
53
+ reject(error);
54
+ return;
55
+ }
56
+ if (info.done) {
57
+ resolve(value);
58
+ } else {
59
+ Promise.resolve(value).then(_next, _throw);
60
+ }
61
+ }
62
+ function _async_to_generator$3(fn) {
63
+ return function() {
64
+ var self = this, args = arguments;
65
+ return new Promise(function(resolve, reject) {
66
+ var gen = fn.apply(self, args);
67
+ function _next(value) {
68
+ asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "next", value);
69
+ }
70
+ function _throw(err) {
71
+ asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "throw", err);
72
+ }
73
+ _next(undefined);
74
+ });
75
+ };
76
+ }
77
+ function _instanceof$2(left, right) {
78
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
79
+ return !!right[Symbol.hasInstance](left);
80
+ } else {
81
+ return left instanceof right;
82
+ }
83
+ }
84
+ function _type_of$1(obj) {
85
+ "@swc/helpers - typeof";
86
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
87
+ }
88
+ function _ts_generator$3(thisArg, body) {
89
+ var f, y, t, g, _ = {
90
+ label: 0,
91
+ sent: function() {
92
+ if (t[0] & 1) throw t[1];
93
+ return t[1];
94
+ },
95
+ trys: [],
96
+ ops: []
97
+ };
98
+ return g = {
99
+ next: verb(0),
100
+ "throw": verb(1),
101
+ "return": verb(2)
102
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
103
+ return this;
104
+ }), g;
105
+ function verb(n) {
106
+ return function(v) {
107
+ return step([
108
+ n,
109
+ v
110
+ ]);
111
+ };
112
+ }
113
+ function step(op) {
114
+ if (f) throw new TypeError("Generator is already executing.");
115
+ while(_)try {
116
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
117
+ if (y = 0, t) op = [
118
+ op[0] & 2,
119
+ t.value
120
+ ];
121
+ switch(op[0]){
122
+ case 0:
123
+ case 1:
124
+ t = op;
125
+ break;
126
+ case 4:
127
+ _.label++;
128
+ return {
129
+ value: op[1],
130
+ done: false
131
+ };
132
+ case 5:
133
+ _.label++;
134
+ y = op[1];
135
+ op = [
136
+ 0
137
+ ];
138
+ continue;
139
+ case 7:
140
+ op = _.ops.pop();
141
+ _.trys.pop();
142
+ continue;
143
+ default:
144
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
145
+ _ = 0;
146
+ continue;
147
+ }
148
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
149
+ _.label = op[1];
150
+ break;
151
+ }
152
+ if (op[0] === 6 && _.label < t[1]) {
153
+ _.label = t[1];
154
+ t = op;
155
+ break;
156
+ }
157
+ if (t && _.label < t[2]) {
158
+ _.label = t[2];
159
+ _.ops.push(op);
160
+ break;
161
+ }
162
+ if (t[2]) _.ops.pop();
163
+ _.trys.pop();
164
+ continue;
165
+ }
166
+ op = body.call(thisArg, _);
167
+ } catch (e) {
168
+ op = [
169
+ 6,
170
+ e
171
+ ];
172
+ y = 0;
173
+ } finally{
174
+ f = t = 0;
175
+ }
176
+ if (op[0] & 5) throw op[1];
177
+ return {
178
+ value: op[0] ? op[1] : void 0,
179
+ done: true
180
+ };
181
+ }
182
+ }
183
+ var DB_NAME = 'dynamic-aleo-wallet-state';
184
+ var DB_VERSION = 1;
185
+ var STORE_NAME = 'state';
186
+ /** Composes the IndexedDB key from a wallet address + network. Exported so
187
+ * callers can build the same string when they need to look up a record
188
+ * outside the standard `getWalletState` path. */ var buildStorageKey = function(accountAddress, network) {
189
+ return "".concat(accountAddress, ":").concat(network);
190
+ };
191
+ // Normalizes a DOMException | unknown into an Error so promise rejections
192
+ // always carry an Error instance. Object-shaped errors (DOMException, plain
193
+ // objects) are looked up for a `.message` string first so we don't stringify
194
+ // them via Object.prototype.toString (which yields the useless '[object Object]').
195
+ // Exported for direct unit testing of the fallback chain.
196
+ function toError(err, fallbackMessage) {
197
+ if (_instanceof$2(err, Error)) return err;
198
+ if (err == null) return new Error(fallbackMessage);
199
+ if (typeof err === 'string') return new Error(err);
200
+ if (typeof err === 'number' || typeof err === 'boolean' || (typeof err === "undefined" ? "undefined" : _type_of$1(err)) === 'bigint') {
201
+ return new Error(String(err));
202
+ }
203
+ var message = err.message;
204
+ if (typeof message === 'string' && message.length > 0) return new Error(message);
205
+ try {
206
+ return new Error(JSON.stringify(err));
207
+ } catch (e) {
208
+ return new Error(fallbackMessage);
209
+ }
210
+ }
211
+ var dbPromise = null;
212
+ function openDb() {
213
+ if (dbPromise) return dbPromise;
214
+ // On rejection, null the module-level cache so the next caller retries
215
+ // the open instead of receiving the same rejected promise for the rest of
216
+ // the session (private-browsing bootup, transient quota errors, etc).
217
+ dbPromise = new Promise(function(resolve, reject) {
218
+ var req = indexedDB.open(DB_NAME, DB_VERSION);
219
+ req.onupgradeneeded = function() {
220
+ var db = req.result;
221
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
222
+ db.createObjectStore(STORE_NAME, {
223
+ keyPath: 'accountAddress'
224
+ });
225
+ }
226
+ };
227
+ req.onsuccess = function() {
228
+ return resolve(req.result);
229
+ };
230
+ req.onerror = function() {
231
+ return reject(toError(req.error, 'IndexedDB open failed'));
232
+ };
233
+ }).catch(function(err) {
234
+ dbPromise = null;
235
+ throw err;
236
+ });
237
+ return dbPromise;
238
+ }
239
+ function runTransaction(mode, fn) {
240
+ return _runTransaction.apply(this, arguments);
241
+ }
242
+ function _runTransaction() {
243
+ _runTransaction = _async_to_generator$3(function(mode, fn) {
244
+ var db;
245
+ return _ts_generator$3(this, function(_state) {
246
+ switch(_state.label){
247
+ case 0:
248
+ return [
249
+ 4,
250
+ openDb()
251
+ ];
252
+ case 1:
253
+ db = _state.sent();
254
+ return [
255
+ 2,
256
+ new Promise(function(resolve, reject) {
257
+ var tx = db.transaction(STORE_NAME, mode);
258
+ var store = tx.objectStore(STORE_NAME);
259
+ var req = fn(store);
260
+ req.onsuccess = function() {
261
+ return resolve(req.result);
262
+ };
263
+ req.onerror = function() {
264
+ return reject(toError(req.error, 'IndexedDB request failed'));
265
+ };
266
+ })
267
+ ];
268
+ }
269
+ });
270
+ });
271
+ return _runTransaction.apply(this, arguments);
272
+ }
273
+ function getWalletState(accountAddress, network) {
274
+ return _getWalletState.apply(this, arguments);
275
+ }
276
+ function _getWalletState() {
277
+ _getWalletState = _async_to_generator$3(function(accountAddress, network) {
278
+ var key, result;
279
+ return _ts_generator$3(this, function(_state) {
280
+ switch(_state.label){
281
+ case 0:
282
+ _state.trys.push([
283
+ 0,
284
+ 2,
285
+ ,
286
+ 3
287
+ ]);
288
+ key = buildStorageKey(accountAddress, network);
289
+ return [
290
+ 4,
291
+ runTransaction('readonly', function(store) {
292
+ return store.get(key);
293
+ })
294
+ ];
295
+ case 1:
296
+ result = _state.sent();
297
+ return [
298
+ 2,
299
+ result !== null && result !== void 0 ? result : null
300
+ ];
301
+ case 2:
302
+ _state.sent();
303
+ // IndexedDB unavailable (private mode, corrupt DB, etc.) — behave as if empty.
304
+ return [
305
+ 2,
306
+ null
307
+ ];
308
+ case 3:
309
+ return [
310
+ 2
311
+ ];
312
+ }
313
+ });
314
+ });
315
+ return _getWalletState.apply(this, arguments);
316
+ }
317
+ function putWalletState(accountAddress, network, state) {
318
+ return _putWalletState.apply(this, arguments);
319
+ }
320
+ function _putWalletState() {
321
+ _putWalletState = _async_to_generator$3(function(accountAddress, network, state) {
322
+ var record;
323
+ return _ts_generator$3(this, function(_state) {
324
+ switch(_state.label){
325
+ case 0:
326
+ record = {
327
+ accountAddress: buildStorageKey(accountAddress, network),
328
+ walletAddress: accountAddress,
329
+ network: network,
330
+ scannerUuid: state.scannerUuid,
331
+ records: state.records,
332
+ spentNonces: state.spentNonces,
333
+ lastScannedBlock: state.lastScannedBlock,
334
+ sealanceProofs: state.sealanceProofs,
335
+ updatedAt: Date.now()
336
+ };
337
+ _state.label = 1;
338
+ case 1:
339
+ _state.trys.push([
340
+ 1,
341
+ 3,
342
+ ,
343
+ 4
344
+ ]);
345
+ return [
346
+ 4,
347
+ runTransaction('readwrite', function(store) {
348
+ return store.put(record);
349
+ })
350
+ ];
351
+ case 2:
352
+ _state.sent();
353
+ return [
354
+ 3,
355
+ 4
356
+ ];
357
+ case 3:
358
+ _state.sent();
359
+ return [
360
+ 3,
361
+ 4
362
+ ];
363
+ case 4:
364
+ return [
365
+ 2
366
+ ];
367
+ }
368
+ });
369
+ });
370
+ return _putWalletState.apply(this, arguments);
371
+ }
372
+
373
+ /**
374
+ * Iframe-side Feemaster surface used by `proveTransaction`.
375
+ *
376
+ * Earlier versions made `fetch()` calls to ANF directly with a hardcoded
377
+ * Bearer key shipped in the iframe bundle. As of Phase A1 the iframe goes
378
+ * through redcoast (which holds the ANF key server-side) — and by reusing
379
+ * the existing `DynamicApiClient` in `@dynamic-labs-wallet/core`, all the
380
+ * baseApiUrl / Authorization-header / retry plumbing is shared with the
381
+ * other waas redcoast endpoints (`exportAleoViewKey`, `signAleoRequest`,
382
+ * etc.).
383
+ *
384
+ * This file is now a thin wrapper that:
385
+ * - holds the network the iframe is bound to
386
+ * - keeps a 5-min in-memory policy cache (matches the previous behaviour)
387
+ * - delegates HTTP work to `DynamicApiClient`
388
+ *
389
+ * Surface kept identical (`fetchPolicy`, `isCovered`, `requestFeeAuthorization`)
390
+ * so call sites in `proveTransaction` don't change.
391
+ */ function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
392
+ try {
393
+ var info = gen[key](arg);
394
+ var value = info.value;
395
+ } catch (error) {
396
+ reject(error);
397
+ return;
398
+ }
399
+ if (info.done) {
400
+ resolve(value);
401
+ } else {
402
+ Promise.resolve(value).then(_next, _throw);
403
+ }
404
+ }
405
+ function _async_to_generator$2(fn) {
406
+ return function() {
407
+ var self = this, args = arguments;
408
+ return new Promise(function(resolve, reject) {
409
+ var gen = fn.apply(self, args);
410
+ function _next(value) {
411
+ asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
412
+ }
413
+ function _throw(err) {
414
+ asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
415
+ }
416
+ _next(undefined);
417
+ });
418
+ };
419
+ }
420
+ function _class_call_check$2(instance, Constructor) {
421
+ if (!(instance instanceof Constructor)) {
422
+ throw new TypeError("Cannot call a class as a function");
423
+ }
424
+ }
425
+ function _defineProperties$2(target, props) {
426
+ for(var i = 0; i < props.length; i++){
427
+ var descriptor = props[i];
428
+ descriptor.enumerable = descriptor.enumerable || false;
429
+ descriptor.configurable = true;
430
+ if ("value" in descriptor) descriptor.writable = true;
431
+ Object.defineProperty(target, descriptor.key, descriptor);
432
+ }
433
+ }
434
+ function _create_class$2(Constructor, protoProps, staticProps) {
435
+ if (protoProps) _defineProperties$2(Constructor.prototype, protoProps);
436
+ return Constructor;
437
+ }
438
+ function _define_property$2(obj, key, value) {
439
+ if (key in obj) {
440
+ Object.defineProperty(obj, key, {
441
+ value: value,
442
+ enumerable: true,
443
+ configurable: true,
444
+ writable: true
445
+ });
446
+ } else {
447
+ obj[key] = value;
448
+ }
449
+ return obj;
450
+ }
451
+ function _ts_generator$2(thisArg, body) {
452
+ var f, y, t, g, _ = {
453
+ label: 0,
454
+ sent: function() {
455
+ if (t[0] & 1) throw t[1];
456
+ return t[1];
457
+ },
458
+ trys: [],
459
+ ops: []
460
+ };
461
+ return g = {
462
+ next: verb(0),
463
+ "throw": verb(1),
464
+ "return": verb(2)
465
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
466
+ return this;
467
+ }), g;
468
+ function verb(n) {
469
+ return function(v) {
470
+ return step([
471
+ n,
472
+ v
473
+ ]);
474
+ };
475
+ }
476
+ function step(op) {
477
+ if (f) throw new TypeError("Generator is already executing.");
478
+ while(_)try {
479
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
480
+ if (y = 0, t) op = [
481
+ op[0] & 2,
482
+ t.value
483
+ ];
484
+ switch(op[0]){
485
+ case 0:
486
+ case 1:
487
+ t = op;
488
+ break;
489
+ case 4:
490
+ _.label++;
491
+ return {
492
+ value: op[1],
493
+ done: false
494
+ };
495
+ case 5:
496
+ _.label++;
497
+ y = op[1];
498
+ op = [
499
+ 0
500
+ ];
501
+ continue;
502
+ case 7:
503
+ op = _.ops.pop();
504
+ _.trys.pop();
505
+ continue;
506
+ default:
507
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
508
+ _ = 0;
509
+ continue;
510
+ }
511
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
512
+ _.label = op[1];
513
+ break;
514
+ }
515
+ if (op[0] === 6 && _.label < t[1]) {
516
+ _.label = t[1];
517
+ t = op;
518
+ break;
519
+ }
520
+ if (t && _.label < t[2]) {
521
+ _.label = t[2];
522
+ _.ops.push(op);
523
+ break;
524
+ }
525
+ if (t[2]) _.ops.pop();
526
+ _.trys.pop();
527
+ continue;
528
+ }
529
+ op = body.call(thisArg, _);
530
+ } catch (e) {
531
+ op = [
532
+ 6,
533
+ e
534
+ ];
535
+ y = 0;
536
+ } finally{
537
+ f = t = 0;
538
+ }
539
+ if (op[0] & 5) throw op[1];
540
+ return {
541
+ value: op[0] ? op[1] : void 0,
542
+ done: true
543
+ };
544
+ }
545
+ }
546
+ var POLICY_TTL_MS = 5 * 60 * 1000;
547
+ var FeemasterClient = /*#__PURE__*/ function() {
548
+ function FeemasterClient(args) {
549
+ _class_call_check$2(this, FeemasterClient);
550
+ _define_property$2(this, "apiClient", void 0);
551
+ _define_property$2(this, "network", void 0);
552
+ _define_property$2(this, "policyCache", null);
553
+ this.apiClient = args.apiClient;
554
+ this.network = args.network;
555
+ }
556
+ _create_class$2(FeemasterClient, [
557
+ {
558
+ key: "fetchPolicy",
559
+ value: /** Fetches the Feemaster policy for the configured network. Cached for
560
+ * 5 minutes; pass `force: true` after a quota-exhausted response. */ function fetchPolicy() {
561
+ var force = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
562
+ var _this = this;
563
+ return _async_to_generator$2(function() {
564
+ var policy;
565
+ return _ts_generator$2(this, function(_state) {
566
+ switch(_state.label){
567
+ case 0:
568
+ if (!force && _this.policyCache && Date.now() - _this.policyCache.cachedAt < POLICY_TTL_MS) {
569
+ return [
570
+ 2,
571
+ _this.policyCache.policy
572
+ ];
573
+ }
574
+ return [
575
+ 4,
576
+ _this.apiClient.getAleoFeemasterPolicy({
577
+ network: _this.network
578
+ })
579
+ ];
580
+ case 1:
581
+ policy = _state.sent();
582
+ _this.policyCache = {
583
+ policy: policy,
584
+ cachedAt: Date.now()
585
+ };
586
+ return [
587
+ 2,
588
+ policy
589
+ ];
590
+ }
591
+ });
592
+ })();
593
+ }
594
+ },
595
+ {
596
+ key: "isCovered",
597
+ value: /** Returns true when the configured network's policy permits sponsoring
598
+ * `(programId, functionName)`. Never throws — returns false on any
599
+ * policy fetch failure so callers can fall back to user-paid. */ function isCovered(programId, functionName) {
600
+ var _this = this;
601
+ return _async_to_generator$2(function() {
602
+ var policy, entry;
603
+ return _ts_generator$2(this, function(_state) {
604
+ switch(_state.label){
605
+ case 0:
606
+ _state.trys.push([
607
+ 0,
608
+ 2,
609
+ ,
610
+ 3
611
+ ]);
612
+ return [
613
+ 4,
614
+ _this.apiClient.isAleoFeemasterCovered({
615
+ network: _this.network,
616
+ programId: programId,
617
+ functionName: functionName
618
+ })
619
+ ];
620
+ case 1:
621
+ return [
622
+ 2,
623
+ _state.sent()
624
+ ];
625
+ case 2:
626
+ _state.sent();
627
+ return [
628
+ 3,
629
+ 3
630
+ ];
631
+ case 3:
632
+ _state.trys.push([
633
+ 3,
634
+ 5,
635
+ ,
636
+ 6
637
+ ]);
638
+ return [
639
+ 4,
640
+ _this.fetchPolicy()
641
+ ];
642
+ case 4:
643
+ policy = _state.sent();
644
+ if (!policy.allowed_programs) return [
645
+ 2,
646
+ true
647
+ ];
648
+ entry = policy.allowed_programs.find(function(p) {
649
+ return p.program_id === programId;
650
+ });
651
+ if (!entry) return [
652
+ 2,
653
+ false
654
+ ];
655
+ if (!entry.allowed_functions) return [
656
+ 2,
657
+ true
658
+ ];
659
+ return [
660
+ 2,
661
+ entry.allowed_functions.includes(functionName)
662
+ ];
663
+ case 5:
664
+ _state.sent();
665
+ return [
666
+ 2,
667
+ false
668
+ ];
669
+ case 6:
670
+ return [
671
+ 2
672
+ ];
673
+ }
674
+ });
675
+ })();
676
+ }
677
+ },
678
+ {
679
+ key: "requestFeeAuthorization",
680
+ value: /** Forwards a user-signed Aleo Authorization to ANF (via redcoast) and
681
+ * returns the corresponding `feeAuthorization` for bundling into a
682
+ * ProvingRequest. Throws on quota / service errors so the caller falls
683
+ * back to user-paid fees. */ function requestFeeAuthorization(params) {
684
+ var _this = this;
685
+ return _async_to_generator$2(function() {
686
+ var feeAuthorization;
687
+ return _ts_generator$2(this, function(_state) {
688
+ switch(_state.label){
689
+ case 0:
690
+ return [
691
+ 4,
692
+ _this.apiClient.requestAleoFeeAuthorization({
693
+ network: _this.network,
694
+ authorization: params.authorizationString,
695
+ priorityFee: params.priorityFee
696
+ })
697
+ ];
698
+ case 1:
699
+ feeAuthorization = _state.sent().feeAuthorization;
700
+ return [
701
+ 2,
702
+ {
703
+ feeAuthorizationString: feeAuthorization
704
+ }
705
+ ];
706
+ }
707
+ });
708
+ })();
709
+ }
710
+ }
711
+ ]);
712
+ return FeemasterClient;
713
+ }();
714
+
715
+ /**
716
+ * Iframe-side RecordScanner that mirrors the Provable SDK's surface but
717
+ * routes every HTTP call through redcoast. This is the Phase A2 swap —
718
+ * before this, the iframe held a hardcoded scanner apiKey + consumerId;
719
+ * now those credentials live in redcoast env vars and the iframe
720
+ * authenticates via the user's Dynamic JWT (handled by `DynamicApiClient`).
721
+ *
722
+ * What stays in the iframe:
723
+ * - The `crypto_box_seal` wrap of the view key (`encryptRegistrationRequest`
724
+ * from the Provable SDK). The view key plaintext never leaves the
725
+ * iframe; only its encrypted form crosses the wire.
726
+ *
727
+ * What now lives in redcoast:
728
+ * - The Provable Bearer apiKey + consumerId.
729
+ * - JWT lifecycle (the SDK used to manage this in the browser; redcoast
730
+ * manages it server-side now and the iframe is unaware).
731
+ *
732
+ * The class signature intentionally matches the parts of `sdk.RecordScanner`
733
+ * the iframe consumes (`registerEncrypted`, `findRecords`) so the rest of
734
+ * `DynamicAleoWalletClient.findOwnedRecordsInner` doesn't change.
735
+ */ function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
736
+ try {
737
+ var info = gen[key](arg);
738
+ var value = info.value;
739
+ } catch (error) {
740
+ reject(error);
741
+ return;
742
+ }
743
+ if (info.done) {
744
+ resolve(value);
745
+ } else {
746
+ Promise.resolve(value).then(_next, _throw);
747
+ }
748
+ }
749
+ function _async_to_generator$1(fn) {
750
+ return function() {
751
+ var self = this, args = arguments;
752
+ return new Promise(function(resolve, reject) {
753
+ var gen = fn.apply(self, args);
754
+ function _next(value) {
755
+ asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
756
+ }
757
+ function _throw(err) {
758
+ asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
759
+ }
760
+ _next(undefined);
761
+ });
762
+ };
763
+ }
764
+ function _class_call_check$1(instance, Constructor) {
765
+ if (!(instance instanceof Constructor)) {
766
+ throw new TypeError("Cannot call a class as a function");
767
+ }
768
+ }
769
+ function _defineProperties$1(target, props) {
770
+ for(var i = 0; i < props.length; i++){
771
+ var descriptor = props[i];
772
+ descriptor.enumerable = descriptor.enumerable || false;
773
+ descriptor.configurable = true;
774
+ if ("value" in descriptor) descriptor.writable = true;
775
+ Object.defineProperty(target, descriptor.key, descriptor);
776
+ }
777
+ }
778
+ function _create_class$1(Constructor, protoProps, staticProps) {
779
+ if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
780
+ return Constructor;
781
+ }
782
+ function _define_property$1(obj, key, value) {
783
+ if (key in obj) {
784
+ Object.defineProperty(obj, key, {
785
+ value: value,
786
+ enumerable: true,
787
+ configurable: true,
788
+ writable: true
789
+ });
790
+ } else {
791
+ obj[key] = value;
792
+ }
793
+ return obj;
794
+ }
795
+ function _instanceof$1(left, right) {
796
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
797
+ return !!right[Symbol.hasInstance](left);
798
+ } else {
799
+ return left instanceof right;
800
+ }
801
+ }
802
+ function _ts_generator$1(thisArg, body) {
803
+ var f, y, t, g, _ = {
804
+ label: 0,
805
+ sent: function() {
806
+ if (t[0] & 1) throw t[1];
807
+ return t[1];
808
+ },
809
+ trys: [],
810
+ ops: []
811
+ };
812
+ return g = {
813
+ next: verb(0),
814
+ "throw": verb(1),
815
+ "return": verb(2)
816
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
817
+ return this;
818
+ }), g;
819
+ function verb(n) {
820
+ return function(v) {
821
+ return step([
822
+ n,
823
+ v
824
+ ]);
825
+ };
826
+ }
827
+ function step(op) {
828
+ if (f) throw new TypeError("Generator is already executing.");
829
+ while(_)try {
830
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
831
+ if (y = 0, t) op = [
832
+ op[0] & 2,
833
+ t.value
834
+ ];
835
+ switch(op[0]){
836
+ case 0:
837
+ case 1:
838
+ t = op;
839
+ break;
840
+ case 4:
841
+ _.label++;
842
+ return {
843
+ value: op[1],
844
+ done: false
845
+ };
846
+ case 5:
847
+ _.label++;
848
+ y = op[1];
849
+ op = [
850
+ 0
851
+ ];
852
+ continue;
853
+ case 7:
854
+ op = _.ops.pop();
855
+ _.trys.pop();
856
+ continue;
857
+ default:
858
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
859
+ _ = 0;
860
+ continue;
861
+ }
862
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
863
+ _.label = op[1];
864
+ break;
865
+ }
866
+ if (op[0] === 6 && _.label < t[1]) {
867
+ _.label = t[1];
868
+ t = op;
869
+ break;
870
+ }
871
+ if (t && _.label < t[2]) {
872
+ _.label = t[2];
873
+ _.ops.push(op);
874
+ break;
875
+ }
876
+ if (t[2]) _.ops.pop();
877
+ _.trys.pop();
878
+ continue;
879
+ }
880
+ op = body.call(thisArg, _);
881
+ } catch (e) {
882
+ op = [
883
+ 6,
884
+ e
885
+ ];
886
+ y = 0;
887
+ } finally{
888
+ f = t = 0;
889
+ }
890
+ if (op[0] & 5) throw op[1];
891
+ return {
892
+ value: op[0] ? op[1] : void 0,
893
+ done: true
894
+ };
895
+ }
896
+ }
897
+ var RedcoastRecordScanner = /*#__PURE__*/ function() {
898
+ function RedcoastRecordScanner(args) {
899
+ _class_call_check$1(this, RedcoastRecordScanner);
900
+ _define_property$1(this, "apiClient", void 0);
901
+ _define_property$1(this, "network", void 0);
902
+ _define_property$1(this, "sdk", void 0);
903
+ this.apiClient = args.apiClient;
904
+ this.network = args.network;
905
+ this.sdk = args.sdk;
906
+ }
907
+ _create_class$1(RedcoastRecordScanner, [
908
+ {
909
+ key: "registerEncrypted",
910
+ value: /**
911
+ * Registers an encrypted view key with the scanner. Mirrors
912
+ * `sdk.RecordScanner.registerEncrypted(viewKey, startBlock)`:
913
+ *
914
+ * 1. GET `/scanner/pubkey` → ephemeral public key
915
+ * 2. Wrap `(viewKey, startBlock)` via libsodium `crypto_box_seal`
916
+ * 3. POST `/scanner/register` with `{ key_id, ciphertext }`
917
+ *
918
+ * Returns the SDK-shaped Result so callers don't have to change.
919
+ */ function registerEncrypted(viewKey, startBlock) {
920
+ var _this = this;
921
+ return _async_to_generator$1(function() {
922
+ var pubkey, ciphertext, data, err, _err_response, status, message;
923
+ return _ts_generator$1(this, function(_state) {
924
+ switch(_state.label){
925
+ case 0:
926
+ _state.trys.push([
927
+ 0,
928
+ 3,
929
+ ,
930
+ 4
931
+ ]);
932
+ return [
933
+ 4,
934
+ _this.apiClient.getAleoScannerPubkey({
935
+ network: _this.network
936
+ })
937
+ ];
938
+ case 1:
939
+ pubkey = _state.sent();
940
+ ciphertext = _this.sdk.encryptRegistrationRequest(pubkey.public_key, viewKey, startBlock);
941
+ return [
942
+ 4,
943
+ _this.apiClient.registerAleoScanner({
944
+ network: _this.network,
945
+ keyId: pubkey.key_id,
946
+ ciphertext: ciphertext
947
+ })
948
+ ];
949
+ case 2:
950
+ data = _state.sent();
951
+ return [
952
+ 2,
953
+ {
954
+ ok: true,
955
+ data: data
956
+ }
957
+ ];
958
+ case 3:
959
+ err = _state.sent();
960
+ status = (_err_response = err.response) === null || _err_response === void 0 ? void 0 : _err_response.status;
961
+ message = _instanceof$1(err, Error) ? err.message : String(err);
962
+ return [
963
+ 2,
964
+ {
965
+ ok: false,
966
+ status: status,
967
+ error: {
968
+ message: message
969
+ }
970
+ }
971
+ ];
972
+ case 4:
973
+ return [
974
+ 2
975
+ ];
976
+ }
977
+ });
978
+ })();
979
+ }
980
+ },
981
+ {
982
+ key: "findRecords",
983
+ value: /**
984
+ * Find owned records by uuid. Mirrors the subset of
985
+ * `sdk.RecordScanner.findRecords(filter)` the iframe consumes.
986
+ *
987
+ * The SDK's filter shape is `{ uuid, decrypt, unspent, filter, ... }`.
988
+ * We forward it verbatim. Records returned are still encrypted on
989
+ * the wire; the caller (`DynamicAleoWalletClient.findOwnedRecordsInner`)
990
+ * decrypts them locally with the view key — same as before A2, just
991
+ * with a different transport underneath.
992
+ */ function findRecords(filter) {
993
+ var _this = this;
994
+ return _async_to_generator$1(function() {
995
+ var records;
996
+ return _ts_generator$1(this, function(_state) {
997
+ switch(_state.label){
998
+ case 0:
999
+ return [
1000
+ 4,
1001
+ _this.apiClient.findAleoScannerRecords({
1002
+ network: _this.network,
1003
+ filter: filter
1004
+ })
1005
+ ];
1006
+ case 1:
1007
+ records = _state.sent().records;
1008
+ return [
1009
+ 2,
1010
+ Array.isArray(records) ? records : []
1011
+ ];
1012
+ }
1013
+ });
1014
+ })();
1015
+ }
1016
+ },
1017
+ {
1018
+ key: "revoke",
1019
+ value: /** Optional but useful for parity with the SDK; not currently called. */ function revoke(uuid) {
1020
+ var _this = this;
1021
+ return _async_to_generator$1(function() {
1022
+ return _ts_generator$1(this, function(_state) {
1023
+ return [
1024
+ 2,
1025
+ _this.apiClient.revokeAleoScanner({
1026
+ network: _this.network,
1027
+ uuid: uuid
1028
+ })
1029
+ ];
1030
+ });
1031
+ })();
1032
+ }
1033
+ }
1034
+ ]);
1035
+ return RedcoastRecordScanner;
1036
+ }();
1037
+
1038
+ function _array_like_to_array(arr, len) {
1039
+ if (len == null || len > arr.length) len = arr.length;
1040
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1041
+ return arr2;
1042
+ }
1043
+ function _array_with_holes(arr) {
1044
+ if (Array.isArray(arr)) return arr;
1045
+ }
1046
+ function _array_without_holes(arr) {
1047
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
1048
+ }
1049
+ function _assert_this_initialized(self) {
1050
+ if (self === void 0) {
1051
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
1052
+ }
1053
+ return self;
1054
+ }
1055
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
1056
+ try {
1057
+ var info = gen[key](arg);
1058
+ var value = info.value;
1059
+ } catch (error) {
1060
+ reject(error);
1061
+ return;
1062
+ }
1063
+ if (info.done) {
1064
+ resolve(value);
1065
+ } else {
1066
+ Promise.resolve(value).then(_next, _throw);
1067
+ }
1068
+ }
1069
+ function _async_to_generator(fn) {
1070
+ return function() {
1071
+ var self = this, args = arguments;
1072
+ return new Promise(function(resolve, reject) {
1073
+ var gen = fn.apply(self, args);
1074
+ function _next(value) {
1075
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
1076
+ }
1077
+ function _throw(err) {
1078
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
1079
+ }
1080
+ _next(undefined);
1081
+ });
1082
+ };
1083
+ }
1084
+ function _call_super(_this, derived, args) {
1085
+ derived = _get_prototype_of(derived);
1086
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
1087
+ }
1088
+ function _class_call_check(instance, Constructor) {
1089
+ if (!(instance instanceof Constructor)) {
1090
+ throw new TypeError("Cannot call a class as a function");
1091
+ }
1092
+ }
1093
+ function _defineProperties(target, props) {
1094
+ for(var i = 0; i < props.length; i++){
1095
+ var descriptor = props[i];
1096
+ descriptor.enumerable = descriptor.enumerable || false;
1097
+ descriptor.configurable = true;
1098
+ if ("value" in descriptor) descriptor.writable = true;
1099
+ Object.defineProperty(target, descriptor.key, descriptor);
1100
+ }
1101
+ }
1102
+ function _create_class(Constructor, protoProps, staticProps) {
1103
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
1104
+ return Constructor;
1105
+ }
1106
+ function _define_property(obj, key, value) {
1107
+ if (key in obj) {
1108
+ Object.defineProperty(obj, key, {
1109
+ value: value,
1110
+ enumerable: true,
1111
+ configurable: true,
1112
+ writable: true
1113
+ });
1114
+ } else {
1115
+ obj[key] = value;
1116
+ }
1117
+ return obj;
1118
+ }
1119
+ function _get_prototype_of(o) {
1120
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
1121
+ return o.__proto__ || Object.getPrototypeOf(o);
1122
+ };
1123
+ return _get_prototype_of(o);
1124
+ }
1125
+ function _inherits(subClass, superClass) {
1126
+ if (typeof superClass !== "function" && superClass !== null) {
1127
+ throw new TypeError("Super expression must either be null or a function");
1128
+ }
1129
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
1130
+ constructor: {
1131
+ value: subClass,
1132
+ writable: true,
1133
+ configurable: true
1134
+ }
1135
+ });
1136
+ if (superClass) _set_prototype_of(subClass, superClass);
1137
+ }
1138
+ function _instanceof(left, right) {
1139
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
1140
+ return !!right[Symbol.hasInstance](left);
1141
+ } else {
1142
+ return left instanceof right;
1143
+ }
1144
+ }
1145
+ function _iterable_to_array(iter) {
1146
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1147
+ }
1148
+ function _iterable_to_array_limit(arr, i) {
1149
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
1150
+ if (_i == null) return;
1151
+ var _arr = [];
1152
+ var _n = true;
1153
+ var _d = false;
1154
+ var _s, _e;
1155
+ try {
1156
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
1157
+ _arr.push(_s.value);
1158
+ if (i && _arr.length === i) break;
1159
+ }
1160
+ } catch (err) {
1161
+ _d = true;
1162
+ _e = err;
1163
+ } finally{
1164
+ try {
1165
+ if (!_n && _i["return"] != null) _i["return"]();
1166
+ } finally{
1167
+ if (_d) throw _e;
1168
+ }
1169
+ }
1170
+ return _arr;
1171
+ }
1172
+ function _non_iterable_rest() {
1173
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1174
+ }
1175
+ function _non_iterable_spread() {
1176
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1177
+ }
1178
+ function _object_spread(target) {
1179
+ for(var i = 1; i < arguments.length; i++){
1180
+ var source = arguments[i] != null ? arguments[i] : {};
1181
+ var ownKeys = Object.keys(source);
1182
+ if (typeof Object.getOwnPropertySymbols === "function") {
1183
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
1184
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1185
+ }));
1186
+ }
1187
+ ownKeys.forEach(function(key) {
1188
+ _define_property(target, key, source[key]);
1189
+ });
1190
+ }
1191
+ return target;
1192
+ }
1193
+ function ownKeys(object, enumerableOnly) {
1194
+ var keys = Object.keys(object);
1195
+ if (Object.getOwnPropertySymbols) {
1196
+ var symbols = Object.getOwnPropertySymbols(object);
1197
+ keys.push.apply(keys, symbols);
1198
+ }
1199
+ return keys;
1200
+ }
1201
+ function _object_spread_props(target, source) {
1202
+ source = source != null ? source : {};
1203
+ if (Object.getOwnPropertyDescriptors) {
1204
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
1205
+ } else {
1206
+ ownKeys(Object(source)).forEach(function(key) {
1207
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
1208
+ });
1209
+ }
1210
+ return target;
1211
+ }
1212
+ function _possible_constructor_return(self, call) {
1213
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
1214
+ return call;
1215
+ }
1216
+ return _assert_this_initialized(self);
1217
+ }
1218
+ function _set_prototype_of(o, p) {
1219
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
1220
+ o.__proto__ = p;
1221
+ return o;
1222
+ };
1223
+ return _set_prototype_of(o, p);
1224
+ }
1225
+ function _sliced_to_array(arr, i) {
1226
+ return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
1227
+ }
1228
+ function _to_consumable_array(arr) {
1229
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
1230
+ }
1231
+ function _type_of(obj) {
1232
+ "@swc/helpers - typeof";
1233
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
1234
+ }
1235
+ function _unsupported_iterable_to_array(o, minLen) {
1236
+ if (!o) return;
1237
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
1238
+ var n = Object.prototype.toString.call(o).slice(8, -1);
1239
+ if (n === "Object" && o.constructor) n = o.constructor.name;
1240
+ if (n === "Map" || n === "Set") return Array.from(n);
1241
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
1242
+ }
1243
+ function _is_native_reflect_construct() {
1244
+ try {
1245
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1246
+ } catch (_) {}
1247
+ return (_is_native_reflect_construct = function() {
1248
+ return !!result;
1249
+ })();
1250
+ }
1251
+ function _ts_generator(thisArg, body) {
1252
+ var f, y, t, g, _ = {
1253
+ label: 0,
1254
+ sent: function() {
1255
+ if (t[0] & 1) throw t[1];
1256
+ return t[1];
1257
+ },
1258
+ trys: [],
1259
+ ops: []
1260
+ };
1261
+ return g = {
1262
+ next: verb(0),
1263
+ "throw": verb(1),
1264
+ "return": verb(2)
1265
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
1266
+ return this;
1267
+ }), g;
1268
+ function verb(n) {
1269
+ return function(v) {
1270
+ return step([
1271
+ n,
1272
+ v
1273
+ ]);
1274
+ };
1275
+ }
1276
+ function step(op) {
1277
+ if (f) throw new TypeError("Generator is already executing.");
1278
+ while(_)try {
1279
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1280
+ if (y = 0, t) op = [
1281
+ op[0] & 2,
1282
+ t.value
1283
+ ];
1284
+ switch(op[0]){
1285
+ case 0:
1286
+ case 1:
1287
+ t = op;
1288
+ break;
1289
+ case 4:
1290
+ _.label++;
1291
+ return {
1292
+ value: op[1],
1293
+ done: false
1294
+ };
1295
+ case 5:
1296
+ _.label++;
1297
+ y = op[1];
1298
+ op = [
1299
+ 0
1300
+ ];
1301
+ continue;
1302
+ case 7:
1303
+ op = _.ops.pop();
1304
+ _.trys.pop();
1305
+ continue;
1306
+ default:
1307
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1308
+ _ = 0;
1309
+ continue;
1310
+ }
1311
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1312
+ _.label = op[1];
1313
+ break;
1314
+ }
1315
+ if (op[0] === 6 && _.label < t[1]) {
1316
+ _.label = t[1];
1317
+ t = op;
1318
+ break;
1319
+ }
1320
+ if (t && _.label < t[2]) {
1321
+ _.label = t[2];
1322
+ _.ops.push(op);
1323
+ break;
1324
+ }
1325
+ if (t[2]) _.ops.pop();
1326
+ _.trys.pop();
1327
+ continue;
1328
+ }
1329
+ op = body.call(thisArg, _);
1330
+ } catch (e) {
1331
+ op = [
1332
+ 6,
1333
+ e
1334
+ ];
1335
+ y = 0;
1336
+ } finally{
1337
+ f = t = 0;
1338
+ }
1339
+ if (op[0] & 5) throw op[1];
1340
+ return {
1341
+ value: op[0] ? op[1] : void 0,
1342
+ done: true
1343
+ };
1344
+ }
1345
+ }
1346
+ /**
1347
+ * Feemaster sponsorship for the Aleo `proveTransaction` flow runs through
1348
+ * redcoast as of A1.b. Redcoast holds the ANF Bearer key server-side; the
1349
+ * iframe authenticates with the user's Dynamic JWT. See `feemasterClient.ts`
1350
+ * for the request shape. No API key lives in this bundle anymore.
1351
+ */ /**
1352
+ * Tier-3 stablecoin programs whose `transfer_private` and
1353
+ * `transfer_private_to_public` functions require a Sealance Merkle exclusion
1354
+ * proof for the sender. Programs not in this map skip the proof flow.
1355
+ *
1356
+ * Each entry maps `<stablecoinProgramId> → <freezelistProgramId, network>`.
1357
+ * The freezelist program publishes the BigInt-string Merkle tree at
1358
+ * `/v2/{network}/programs/{freezelist}/compliance/freeze-list` and the
1359
+ * current root at `/program/{freezelist}/mapping/freeze_list_root/1u8`.
1360
+ */ var SEALANCE_PROGRAM_REGISTRY = {
1361
+ test_usad_stablecoin: {
1362
+ freezelistProgram: 'test_usad_freezelist.aleo',
1363
+ network: 'testnet'
1364
+ },
1365
+ test_usdcx_stablecoin: {
1366
+ freezelistProgram: 'test_usdcx_freezelist.aleo',
1367
+ network: 'testnet'
1368
+ },
1369
+ usad_stablecoin: {
1370
+ freezelistProgram: 'usad_freezelist.aleo',
1371
+ network: 'mainnet'
1372
+ },
1373
+ usdcx_stablecoin: {
1374
+ freezelistProgram: 'usdcx_freezelist.aleo',
1375
+ network: 'mainnet'
1376
+ }
1377
+ };
1378
+ var SEALANCE_FUNCTIONS_REQUIRING_PROOF = new Set([
1379
+ 'transfer_private',
1380
+ 'transfer_private_to_public'
1381
+ ]);
1382
+ /** Aleo VM input type for the proof argument on Sealance stablecoin programs.
1383
+ * Verified against `test_usad_stablecoin.aleo` source: `[MerkleProof; 2u32].private`. */ var SEALANCE_PROOF_INPUT_TYPE = '[MerkleProof; 2u32].private';
1384
+ /** Tree depth used by the freezelist Merkle tree. Matches the on-chain
1385
+ * `MerkleProof` struct: `siblings as [field; 16u32]`. */ var SEALANCE_TREE_DEPTH = 16;
1386
+ /** Heuristic for deriving the Aleo network from a program ID alone:
1387
+ * on Aleo, by convention all testnet programs are deployed under a `test_`
1388
+ * prefix; mainnet programs use the bare name. Both `credits.aleo` and
1389
+ * `<token>_freezelist.aleo` follow this. */ var networkFromProgramId = function(programId) {
1390
+ return programId.startsWith('test_') ? 'testnet' : 'mainnet';
1391
+ };
1392
+ /** Aleo numeric network ids (matches the connector's `getSelectedNetwork().chainId`):
1393
+ * `0` = mainnet, `1` = testnet. The connector + widget pass these in as
1394
+ * strings or numbers; this helper accepts both shapes. Defaults to testnet
1395
+ * when undefined / unrecognised so a missing network arg never silently
1396
+ * switches a session to mainnet. */ var resolveAleoNetwork = function(chainId) {
1397
+ if (chainId === undefined || chainId === null) return 'testnet';
1398
+ var asNumber = typeof chainId === 'number' ? chainId : Number(String(chainId));
1399
+ if (asNumber === 0) return 'mainnet';
1400
+ if (asNumber === 1) return 'testnet';
1401
+ return 'testnet';
1402
+ };
1403
+ var loadAleoSdk = /*#__PURE__*/ function() {
1404
+ var _ref = _async_to_generator(function(network) {
1405
+ return _ts_generator(this, function(_state) {
1406
+ return [
1407
+ 2,
1408
+ network === 'mainnet' ? AleoSdkMainnet : AleoSdkTestnet
1409
+ ];
1410
+ });
1411
+ });
1412
+ return function loadAleoSdk(network) {
1413
+ return _ref.apply(this, arguments);
1414
+ };
1415
+ }();
1416
+ var lookupSealanceConfig = function(programId) {
1417
+ var stem = programId.endsWith('.aleo') ? programId.slice(0, -'.aleo'.length) : programId;
1418
+ return SEALANCE_PROGRAM_REGISTRY[stem];
1419
+ };
1420
+ var DynamicAleoWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1421
+ _inherits(DynamicAleoWalletClient, DynamicWalletClient);
1422
+ function DynamicAleoWalletClient(param, internalOptions) {
1423
+ var environmentId = param.environmentId, authToken = param.authToken, baseApiUrl = param.baseApiUrl, baseMPCRelayApiUrl = param.baseMPCRelayApiUrl, storageKey = param.storageKey, debug = param.debug, featureFlags = param.featureFlags, _param_authMode = param.authMode, authMode = _param_authMode === void 0 ? AuthMode.HEADER : _param_authMode, sdkVersion = param.sdkVersion, forwardMPCClient = param.forwardMPCClient, logger = param.logger;
1424
+ _class_call_check(this, DynamicAleoWalletClient);
1425
+ var _this;
1426
+ _this = _call_super(this, DynamicAleoWalletClient, [
1427
+ {
1428
+ environmentId: environmentId,
1429
+ authToken: authToken,
1430
+ baseApiUrl: baseApiUrl,
1431
+ baseMPCRelayApiUrl: baseMPCRelayApiUrl,
1432
+ storageKey: storageKey,
1433
+ debug: debug,
1434
+ featureFlags: featureFlags,
1435
+ authMode: authMode,
1436
+ sdkVersion: sdkVersion,
1437
+ forwardMPCClient: forwardMPCClient,
1438
+ logger: logger
1439
+ },
1440
+ internalOptions
1441
+ ]), _define_property(_this, "chainName", 'ALEO'), /**
1442
+ * Cached ProgramManager per Aleo network. The SDK ships separate
1443
+ * mainnet/testnet builds (`@provablehq/sdk/{mainnet,testnet}.js`) that
1444
+ * export network-specific class identities — `ExecutionRequest`,
1445
+ * `ProvingRequest`, etc. each network's prebundle has its own constructor.
1446
+ * `provingRequest` validates `executionRequest instanceof ExecutionRequest`
1447
+ * against the manager's own SDK build, so a manager constructed from the
1448
+ * testnet build will reject a mainnet-built executionRequest (silently
1449
+ * falling into the no-executionRequest branch and throwing a misleading
1450
+ * "No private key provided" error). Caching per network keeps both
1451
+ * builds available and ensures the manager and the executionRequest
1452
+ * always come from the same SDK build.
1453
+ */ _define_property(_this, "programManagersByNetwork", new Map()), /**
1454
+ * Cached RecordScanner instances per Aleo network. Each entry talks to a
1455
+ * single network's scanner endpoint with a single network-specific SDK
1456
+ * build (`@provablehq/sdk/{testnet,mainnet}.js`). Per-wallet identity is
1457
+ * via the scanner UUID cached in walletStateStorage (also keyed by
1458
+ * network). Scanner credentials (apiKey, consumerId) are shared across
1459
+ * networks. The SDK handles JWT refresh automatically.
1460
+ */ _define_property(_this, "scannersByNetwork", new Map()), /**
1461
+ * Cached `FeemasterClient` per Aleo network. Each instance holds an in-
1462
+ * memory policy cache (5 min TTL) and delegates HTTP work to the
1463
+ * inherited `this.apiClient` — the same `DynamicApiClient` every other
1464
+ * iframe→redcoast call uses. So baseApiUrl, auth headers, traceContext
1465
+ * propagation, etc. all come from the existing plumbing for free.
1466
+ */ _define_property(_this, "feemasterClients", new Map()), /**
1467
+ * In-memory cache of program checksums keyed by `${network}:${programId}`.
1468
+ * The Aleo VM's external-signing path requires a non-null `program_checksum`
1469
+ * for any program with a constructor (i.e. anything other than credits.aleo
1470
+ * in our universe). The checksum is immutable for a given deployed program
1471
+ * edition, so we fetch once per session and reuse. Persistence not needed —
1472
+ * a single network round-trip on first use is cheap.
1473
+ */ _define_property(_this, "programChecksumCache", new Map()), /**
1474
+ * Single-flight guard for `findOwnedRecords`, keyed by accountAddress.
1475
+ * The widget's Shielded tab + the demo's "List my records" button can fire
1476
+ * concurrent record scans on the same wallet; without dedup, multiple
1477
+ * findRecords calls race against a stale cached UUID and serially trip
1478
+ * UUIDErrors. With dedup, all concurrent callers await the same in-flight
1479
+ * promise and the recovery path runs at most once.
1480
+ */ _define_property(_this, "pendingFindOwnedRecords", new Map());
1481
+ return _this;
1482
+ }
1483
+ _create_class(DynamicAleoWalletClient, [
1484
+ {
1485
+ key: "createWalletAccount",
1486
+ value: function createWalletAccount(param) {
1487
+ var thresholdSignatureScheme = param.thresholdSignatureScheme, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, onError = param.onError, signedSessionId = param.signedSessionId;
1488
+ var _this = this;
1489
+ return _async_to_generator(function() {
1490
+ var ceremonyCompleteResolver, ceremonyCompletePromise, serverAccountAddress, _ref, rawPublicKey, clientKeyShares, firstShare, accountAddress, publicKeyHex, pubKeyBytes, error, detail;
1491
+ return _ts_generator(this, function(_state) {
1492
+ switch(_state.label){
1493
+ case 0:
1494
+ _state.trys.push([
1495
+ 0,
1496
+ 5,
1497
+ ,
1498
+ 6
1499
+ ]);
1500
+ ceremonyCompletePromise = new Promise(function(resolve) {
1501
+ ceremonyCompleteResolver = resolve;
1502
+ });
1503
+ return [
1504
+ 4,
1505
+ _this.keyGen({
1506
+ chainName: _this.chainName,
1507
+ thresholdSignatureScheme: thresholdSignatureScheme,
1508
+ onError: onError,
1509
+ onCeremonyComplete: function(accountAddress, walletId) {
1510
+ var chainConfig = getMPCChainConfig(_this.chainName);
1511
+ serverAccountAddress = accountAddress;
1512
+ _this.initializeWalletMapEntry({
1513
+ accountAddress: accountAddress,
1514
+ walletId: walletId,
1515
+ chainName: _this.chainName,
1516
+ thresholdSignatureScheme: thresholdSignatureScheme,
1517
+ derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map(function(value, index) {
1518
+ return [
1519
+ index,
1520
+ value
1521
+ ];
1522
+ })))
1523
+ });
1524
+ ceremonyCompleteResolver(undefined);
1525
+ },
1526
+ password: password,
1527
+ signedSessionId: signedSessionId
1528
+ })
1529
+ ];
1530
+ case 1:
1531
+ _ref = _state.sent(), rawPublicKey = _ref.rawPublicKey, clientKeyShares = _ref.clientKeyShares;
1532
+ return [
1533
+ 4,
1534
+ ceremonyCompletePromise
1535
+ ];
1536
+ case 2:
1537
+ _state.sent();
1538
+ if (!clientKeyShares || clientKeyShares.length === 0) {
1539
+ throw new Error(ERROR_KEYGEN_FAILED);
1540
+ }
1541
+ // Aleo addresses come from the Sodot EdBls12377 keygen result directly
1542
+ // (keygenResult.address is the bech32 `aleo1...` address).
1543
+ // Prefer the server-provided address if present; otherwise read from the local keygen result.
1544
+ firstShare = clientKeyShares[0];
1545
+ accountAddress = serverAccountAddress !== null && serverAccountAddress !== void 0 ? serverAccountAddress : firstShare.address;
1546
+ if (!accountAddress) {
1547
+ throw new Error(ERROR_KEYGEN_FAILED);
1548
+ }
1549
+ return [
1550
+ 4,
1551
+ _this.setClientKeySharesToStorage({
1552
+ accountAddress: accountAddress,
1553
+ clientKeyShares: clientKeyShares,
1554
+ overwriteOrMerge: 'overwrite'
1555
+ })
1556
+ ];
1557
+ case 3:
1558
+ _state.sent();
1559
+ return [
1560
+ 4,
1561
+ _this.storeEncryptedBackupByWallet({
1562
+ accountAddress: accountAddress,
1563
+ clientKeyShares: clientKeyShares,
1564
+ password: password,
1565
+ signedSessionId: signedSessionId
1566
+ })
1567
+ ];
1568
+ case 4:
1569
+ _state.sent();
1570
+ // For Aleo, `rawPublicKey` from the base keygen is the EdBls12377 computeKey hex.
1571
+ // There's no separate public-key-to-address derivation — the address is baked into
1572
+ // the keygen result. Keep the hex for backup/reconstruction purposes.
1573
+ publicKeyHex = typeof rawPublicKey === 'string' ? rawPublicKey : '';
1574
+ pubKeyBytes = publicKeyHex ? Buffer.from(publicKeyHex, 'hex') : new Uint8Array();
1575
+ return [
1576
+ 2,
1577
+ {
1578
+ accountAddress: accountAddress,
1579
+ publicKeyHex: publicKeyHex,
1580
+ rawPublicKey: new Uint8Array(pubKeyBytes)
1581
+ }
1582
+ ];
1583
+ case 5:
1584
+ error = _state.sent();
1585
+ if (_instanceof(error, Error) && error.message === ERROR_PASSWORD_MISMATCH) {
1586
+ throw error;
1587
+ }
1588
+ _this.logger.error(ERROR_CREATE_WALLET_ACCOUNT, error);
1589
+ detail = _instanceof(error, Error) ? error.message : String(error);
1590
+ throw new Error("".concat(ERROR_CREATE_WALLET_ACCOUNT, ": ").concat(detail));
1591
+ case 6:
1592
+ return [
1593
+ 2
1594
+ ];
1595
+ }
1596
+ });
1597
+ })();
1598
+ }
1599
+ },
1600
+ {
1601
+ key: "signMessage",
1602
+ value: // Phase 1 does not implement arbitrary-message signing for Aleo.
1603
+ // Sodot's EdBls12377 signer only exposes `signRequest(payload)` for Aleo transaction
1604
+ // authorization today — no plain `sign(bytes)` for native Aleo Schnorr signatures.
1605
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1606
+ function signMessage(_args) {
1607
+ return _async_to_generator(function() {
1608
+ return _ts_generator(this, function(_state) {
1609
+ throw new Error(ERROR_SIGN_MESSAGE_NOT_SUPPORTED);
1610
+ });
1611
+ })();
1612
+ }
1613
+ },
1614
+ {
1615
+ key: "signTransaction",
1616
+ value: // signTransaction for Aleo uses the Sodot EdBls12377 `signRequest` ceremony.
1617
+ // That ceremony isn't wired up yet — coming in Phase 2 alongside transfer_public
1618
+ // and the other credits.aleo functions.
1619
+ function signTransaction(args) {
1620
+ return _async_to_generator(function() {
1621
+ return _ts_generator(this, function(_state) {
1622
+ if (!(args === null || args === void 0 ? void 0 : args.accountAddress)) {
1623
+ throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
1624
+ }
1625
+ throw new Error(ERROR_SIGN_TRANSACTION_NOT_SUPPORTED);
1626
+ });
1627
+ })();
1628
+ }
1629
+ },
1630
+ {
1631
+ key: "exportPrivateKey",
1632
+ value: function exportPrivateKey(param) {
1633
+ var accountAddress = param.accountAddress, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken;
1634
+ var _this = this;
1635
+ return _async_to_generator(function() {
1636
+ var derivedPrivateKey, error;
1637
+ return _ts_generator(this, function(_state) {
1638
+ switch(_state.label){
1639
+ case 0:
1640
+ _state.trys.push([
1641
+ 0,
1642
+ 2,
1643
+ ,
1644
+ 3
1645
+ ]);
1646
+ if (!accountAddress) {
1647
+ throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
1648
+ }
1649
+ return [
1650
+ 4,
1651
+ _this.exportKey({
1652
+ accountAddress: accountAddress,
1653
+ chainName: _this.chainName,
1654
+ password: password,
1655
+ signedSessionId: signedSessionId,
1656
+ mfaToken: mfaToken,
1657
+ elevatedAccessToken: elevatedAccessToken
1658
+ })
1659
+ ];
1660
+ case 1:
1661
+ derivedPrivateKey = _state.sent().derivedPrivateKey;
1662
+ if (!derivedPrivateKey) {
1663
+ throw new Error('Derived private key is undefined');
1664
+ }
1665
+ // For Aleo, `derivedPrivateKey` is the raw hex scalar produced by Sodot's
1666
+ // EdBls12377 exportFullPrivateKey. Aleo's canonical format is `APrivateKey1...`
1667
+ // (bech32-encoded via @provablehq/sdk). Encoding to that format requires the
1668
+ // Provable SDK and is done by the consumer (connector) for now.
1669
+ return [
1670
+ 2,
1671
+ derivedPrivateKey
1672
+ ];
1673
+ case 2:
1674
+ error = _state.sent();
1675
+ if (_instanceof(error, Error) && error.message === ERROR_PASSWORD_MISMATCH) {
1676
+ throw error;
1677
+ }
1678
+ _this.logger.error(ERROR_EXPORT_PRIVATE_KEY, error);
1679
+ throw new Error(ERROR_EXPORT_PRIVATE_KEY);
1680
+ case 3:
1681
+ return [
1682
+ 2
1683
+ ];
1684
+ }
1685
+ });
1686
+ })();
1687
+ }
1688
+ },
1689
+ {
1690
+ key: "importPrivateKey",
1691
+ value: // eslint-disable-next-line @typescript-eslint/no-unused-vars
1692
+ function importPrivateKey(_args) {
1693
+ return _async_to_generator(function() {
1694
+ return _ts_generator(this, function(_state) {
1695
+ throw new Error(ERROR_IMPORT_PRIVATE_KEY_NOT_SUPPORTED);
1696
+ });
1697
+ })();
1698
+ }
1699
+ },
1700
+ {
1701
+ key: "getAleoWallets",
1702
+ value: function getAleoWallets() {
1703
+ var _this = this;
1704
+ return _async_to_generator(function() {
1705
+ var wallets;
1706
+ return _ts_generator(this, function(_state) {
1707
+ switch(_state.label){
1708
+ case 0:
1709
+ return [
1710
+ 4,
1711
+ _this.getWallets()
1712
+ ];
1713
+ case 1:
1714
+ wallets = _state.sent();
1715
+ return [
1716
+ 2,
1717
+ wallets.filter(function(wallet) {
1718
+ return wallet.chainName === _this.chainName;
1719
+ })
1720
+ ];
1721
+ }
1722
+ });
1723
+ })();
1724
+ }
1725
+ },
1726
+ {
1727
+ key: "signAleoRequest",
1728
+ value: /**
1729
+ * Runs the Aleo signRequest MPC ceremony for the given structured payload.
1730
+ * The payload is Sodot's `EdBls12377RequestSignPayload` shape:
1731
+ * { function_id, is_root, program_checksum, inputs: [...] }.
1732
+ * Returns the signed request with { signature, tvk, signer, gammas? } which
1733
+ * the caller passes to `buildExecutionRequestFromExternallySignedData` to
1734
+ * produce an ExecutionRequest for proving via Provable DPS.
1735
+ */ function signAleoRequest(param) {
1736
+ var accountAddress = param.accountAddress, payload = param.payload, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken;
1737
+ var _this = this;
1738
+ return _async_to_generator(function() {
1739
+ var wallet, mpcSigner, reconstructedKeyShare, wirePayload, roomId, signedRequest;
1740
+ return _ts_generator(this, function(_state) {
1741
+ switch(_state.label){
1742
+ case 0:
1743
+ if (!accountAddress) {
1744
+ throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
1745
+ }
1746
+ return [
1747
+ 4,
1748
+ _this.verifyPassword({
1749
+ accountAddress: accountAddress,
1750
+ password: password,
1751
+ signedSessionId: signedSessionId
1752
+ })
1753
+ ];
1754
+ case 1:
1755
+ _state.sent();
1756
+ return [
1757
+ 4,
1758
+ _this.getWallet({
1759
+ accountAddress: accountAddress,
1760
+ password: password,
1761
+ signedSessionId: signedSessionId
1762
+ })
1763
+ ];
1764
+ case 2:
1765
+ wallet = _state.sent();
1766
+ mpcSigner = getMPCSigner({
1767
+ chainName: _this.chainName,
1768
+ baseRelayUrl: _this.baseMPCRelayApiUrl
1769
+ });
1770
+ return [
1771
+ 4,
1772
+ _this.getReconstructedKeyShare(accountAddress, mpcSigner)
1773
+ ];
1774
+ case 3:
1775
+ reconstructedKeyShare = _state.sent();
1776
+ // HTTP transport cannot carry Uint8Arrays — hex-encode for the wire.
1777
+ // The server decodes back to Uint8Array before calling Sodot, so both
1778
+ // parties end up signing the same byte arrays.
1779
+ wirePayload = (typeof payload === "undefined" ? "undefined" : _type_of(payload)) === 'object' && payload !== null && 'function_id' in payload ? _this.encodePayloadForTransport(payload) : payload;
1780
+ return [
1781
+ 4,
1782
+ _this.apiClient.signAleoRequest({
1783
+ walletId: wallet.walletId,
1784
+ payload: wirePayload,
1785
+ mfaToken: mfaToken,
1786
+ elevatedAccessToken: elevatedAccessToken
1787
+ })
1788
+ ];
1789
+ case 4:
1790
+ roomId = _state.sent().roomId;
1791
+ return [
1792
+ 4,
1793
+ mpcSigner.signRequest(roomId, reconstructedKeyShare, payload)
1794
+ ];
1795
+ case 5:
1796
+ signedRequest = _state.sent();
1797
+ if (!signedRequest) {
1798
+ throw new Error('Aleo signRequest returned empty — MPC ceremony failed');
1799
+ }
1800
+ return [
1801
+ 2,
1802
+ signedRequest
1803
+ ];
1804
+ }
1805
+ });
1806
+ })();
1807
+ }
1808
+ },
1809
+ {
1810
+ key: "getViewKeyCacheStorageKey",
1811
+ value: /**
1812
+ * LocalStorage key for caching the per-account Aleo view key in the iframe.
1813
+ * Scoped to iframe origin — the DApp cannot read this via same-origin policy.
1814
+ */ function getViewKeyCacheStorageKey(accountAddress) {
1815
+ return "dynamic-aleo-view-key:".concat(accountAddress);
1816
+ }
1817
+ },
1818
+ {
1819
+ key: "exportViewKey",
1820
+ value: /**
1821
+ * Returns the Aleo view key for the given account. On first call runs the
1822
+ * asymmetric exportViewKey MPC ceremony (client receives, server gets
1823
+ * nothing) and caches the result in iframe localStorage. Subsequent calls
1824
+ * return the cached value. View key never leaves the iframe — it is NOT
1825
+ * postMessage'd to the DApp.
1826
+ */ function exportViewKey(param) {
1827
+ var accountAddress = param.accountAddress, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken;
1828
+ var _this = this;
1829
+ return _async_to_generator(function() {
1830
+ var cacheKey, _globalThis_localStorage, cached, wallet, mpcSigner, reconstructedKeyShare, exportId, roomId, viewKey, _globalThis_localStorage1;
1831
+ return _ts_generator(this, function(_state) {
1832
+ switch(_state.label){
1833
+ case 0:
1834
+ if (!accountAddress) {
1835
+ throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
1836
+ }
1837
+ cacheKey = _this.getViewKeyCacheStorageKey(accountAddress);
1838
+ try {
1839
+ ;
1840
+ cached = (_globalThis_localStorage = globalThis.localStorage) === null || _globalThis_localStorage === void 0 ? void 0 : _globalThis_localStorage.getItem(cacheKey);
1841
+ if (cached) return [
1842
+ 2,
1843
+ cached
1844
+ ];
1845
+ } catch (e) {
1846
+ // localStorage unavailable (SSR / sandboxed) — fall through to ceremony.
1847
+ }
1848
+ return [
1849
+ 4,
1850
+ _this.verifyPassword({
1851
+ accountAddress: accountAddress,
1852
+ password: password,
1853
+ signedSessionId: signedSessionId
1854
+ })
1855
+ ];
1856
+ case 1:
1857
+ _state.sent();
1858
+ return [
1859
+ 4,
1860
+ _this.getWallet({
1861
+ accountAddress: accountAddress,
1862
+ password: password,
1863
+ signedSessionId: signedSessionId
1864
+ })
1865
+ ];
1866
+ case 2:
1867
+ wallet = _state.sent();
1868
+ // Re-use the base-class MPC signer + key-share reconstruction so this path
1869
+ // doesn't duplicate storage logic. The mpcSigner here is an EdBls12377.
1870
+ mpcSigner = getMPCSigner({
1871
+ chainName: _this.chainName,
1872
+ baseRelayUrl: _this.baseMPCRelayApiUrl
1873
+ });
1874
+ return [
1875
+ 4,
1876
+ _this.getReconstructedKeyShare(accountAddress, mpcSigner)
1877
+ ];
1878
+ case 3:
1879
+ reconstructedKeyShare = _state.sent();
1880
+ return [
1881
+ 4,
1882
+ _this.getExportId({
1883
+ chainName: _this.chainName,
1884
+ clientKeyShare: reconstructedKeyShare
1885
+ })
1886
+ ];
1887
+ case 4:
1888
+ exportId = _state.sent();
1889
+ return [
1890
+ 4,
1891
+ _this.apiClient.exportAleoViewKey({
1892
+ walletId: wallet.walletId,
1893
+ exportId: exportId,
1894
+ mfaToken: mfaToken,
1895
+ elevatedAccessToken: elevatedAccessToken
1896
+ })
1897
+ ];
1898
+ case 5:
1899
+ roomId = _state.sent().roomId;
1900
+ return [
1901
+ 4,
1902
+ mpcSigner.exportViewKey(roomId, reconstructedKeyShare, exportId)
1903
+ ];
1904
+ case 6:
1905
+ viewKey = _state.sent();
1906
+ if (!viewKey) {
1907
+ throw new Error('Aleo view key export returned empty — MPC ceremony failed');
1908
+ }
1909
+ try {
1910
+ ;
1911
+ (_globalThis_localStorage1 = globalThis.localStorage) === null || _globalThis_localStorage1 === void 0 ? void 0 : _globalThis_localStorage1.setItem(cacheKey, viewKey);
1912
+ } catch (e) {
1913
+ // best-effort cache — fine to proceed without persistence.
1914
+ }
1915
+ return [
1916
+ 2,
1917
+ viewKey
1918
+ ];
1919
+ }
1920
+ });
1921
+ })();
1922
+ }
1923
+ },
1924
+ {
1925
+ key: "toRequestSignPayload",
1926
+ value: /**
1927
+ * Convert a Provable `ExternalSigningInput<'bytes'>` into the Sodot
1928
+ * EdBls12377 signing payload shape. Mirrors the playground helper.
1929
+ * All Uint8Array fields are preserved — this shape is passed directly to
1930
+ * `mpcSigner.signRequest` locally. For HTTP transport, use
1931
+ * `encodePayloadForTransport` to hex-encode the byte fields.
1932
+ */ function toRequestSignPayload(signingInputs) {
1933
+ var _signingInputs_checksum;
1934
+ return {
1935
+ function_id: signingInputs.functionId,
1936
+ is_root: signingInputs.isRoot,
1937
+ program_checksum: (_signingInputs_checksum = signingInputs.checksum) !== null && _signingInputs_checksum !== void 0 ? _signingInputs_checksum : null,
1938
+ inputs: signingInputs.requestInputs.map(function(requestInput) {
1939
+ if (requestInput.signingInputType === 'record') {
1940
+ return {
1941
+ type: 'record',
1942
+ h: requestInput.h,
1943
+ tag: requestInput.tag
1944
+ };
1945
+ }
1946
+ return {
1947
+ type: requestInput.signingInputType,
1948
+ index: requestInput.index,
1949
+ fields: requestInput.data
1950
+ };
1951
+ })
1952
+ };
1953
+ }
1954
+ },
1955
+ {
1956
+ key: "encodePayloadForTransport",
1957
+ value: /**
1958
+ * Hex-encode the Uint8Array fields of an EdBls12377 signing payload so it
1959
+ * can travel through JSON HTTP without loss. Mirror of
1960
+ * `decodeAleoSigningPayload` in wallet-service — both sides must agree on
1961
+ * the wire format so the MPC ceremony sees identical byte arrays.
1962
+ */ function encodePayloadForTransport(payload) {
1963
+ var u8ToHex = function(u8) {
1964
+ return Array.from(u8, function(b) {
1965
+ return b.toString(16).padStart(2, '0');
1966
+ }).join('');
1967
+ };
1968
+ return {
1969
+ function_id: u8ToHex(payload.function_id),
1970
+ is_root: payload.is_root,
1971
+ program_checksum: payload.program_checksum == null ? null : u8ToHex(payload.program_checksum),
1972
+ inputs: payload.inputs.map(function(input) {
1973
+ if (input.type === 'record') {
1974
+ return {
1975
+ type: 'record',
1976
+ h: u8ToHex(input.h),
1977
+ tag: u8ToHex(input.tag)
1978
+ };
1979
+ }
1980
+ return {
1981
+ type: input.type,
1982
+ index: u8ToHex(input.index),
1983
+ fields: input.fields.map(function(f) {
1984
+ return u8ToHex(f);
1985
+ })
1986
+ };
1987
+ })
1988
+ };
1989
+ }
1990
+ },
1991
+ {
1992
+ key: "getProgramChecksum",
1993
+ value: /**
1994
+ * Fetches the on-chain `program_checksum` for a deployed program and
1995
+ * returns it as a 32-byte `Uint8Array` ready to feed into
1996
+ * `computeExternalSigningInputs({ checksum })` and Sodot's
1997
+ * `signRequest` payload (`program_checksum` field).
1998
+ *
1999
+ * Why we need this: the Aleo VM's external-signing path checks the
2000
+ * program checksum for any program that has a constructor. Constructor-
2001
+ * less programs (`credits.aleo`, `token_registry.aleo`) deploy without a
2002
+ * `program_checksum` field and work with `checksum: null`. Programs with
2003
+ * a constructor (USAD/USDCx Tier-3 stablecoins, any custom program)
2004
+ * trip a hardcoded `"Program ID must be credits.aleo"` error in the WASM
2005
+ * unless a real checksum is supplied.
2006
+ *
2007
+ * Returns `null` when the deployment has no checksum (constructor-less);
2008
+ * caller is expected to pass that `null` through to `signRequest`.
2009
+ *
2010
+ * Source: the deployment transaction's `deployment.program_checksum`
2011
+ * field, returned as a 32-element array of `<n>u8` literals (e.g.
2012
+ * `["207u8", "221u8", ...]`).
2013
+ */ function getProgramChecksum(programId, network) {
2014
+ var _this = this;
2015
+ return _async_to_generator(function() {
2016
+ var _txJson_deployment, cacheKey, cached, apiBase, txIdRes, txId, txRes, txJson, checksumU8s, _JSON_stringify, bytes, i, match;
2017
+ return _ts_generator(this, function(_state) {
2018
+ switch(_state.label){
2019
+ case 0:
2020
+ cacheKey = "".concat(network, ":").concat(programId);
2021
+ cached = _this.programChecksumCache.get(cacheKey);
2022
+ if (cached !== undefined) return [
2023
+ 2,
2024
+ cached
2025
+ ];
2026
+ apiBase = "https://api.explorer.provable.com/v2/".concat(network);
2027
+ return [
2028
+ 4,
2029
+ fetch("".concat(apiBase, "/find/transactionID/deployment/").concat(programId))
2030
+ ];
2031
+ case 1:
2032
+ txIdRes = _state.sent();
2033
+ if (!txIdRes.ok) {
2034
+ throw new Error("Failed to look up deployment transaction for ".concat(programId, " on ").concat(network, ": HTTP ").concat(txIdRes.status));
2035
+ }
2036
+ return [
2037
+ 4,
2038
+ txIdRes.text()
2039
+ ];
2040
+ case 2:
2041
+ txId = _state.sent().replaceAll(/^"|"$/g, '').trim();
2042
+ // Aleo deployment transaction IDs are bech32-encoded strings prefixed with
2043
+ // `at1`. Validate before interpolating into the next URL so a corrupted or
2044
+ // malicious upstream response can't redirect the request elsewhere.
2045
+ if (!/^at1[a-z0-9]{40,200}$/.test(txId)) {
2046
+ throw new Error("Invalid deployment transaction ID format for ".concat(programId, ": ").concat(txId.slice(0, 60)));
2047
+ }
2048
+ return [
2049
+ 4,
2050
+ fetch("".concat(apiBase, "/transaction/").concat(txId))
2051
+ ];
2052
+ case 3:
2053
+ txRes = _state.sent();
2054
+ if (!txRes.ok) {
2055
+ throw new Error("Failed to fetch deployment transaction ".concat(txId, ": HTTP ").concat(txRes.status));
2056
+ }
2057
+ return [
2058
+ 4,
2059
+ txRes.json()
2060
+ ];
2061
+ case 4:
2062
+ txJson = _state.sent();
2063
+ checksumU8s = txJson === null || txJson === void 0 ? void 0 : (_txJson_deployment = txJson.deployment) === null || _txJson_deployment === void 0 ? void 0 : _txJson_deployment.program_checksum;
2064
+ if (checksumU8s == null) {
2065
+ // Constructor-less program — checksum is genuinely absent on-chain.
2066
+ _this.programChecksumCache.set(cacheKey, null);
2067
+ return [
2068
+ 2,
2069
+ null
2070
+ ];
2071
+ }
2072
+ if (!Array.isArray(checksumU8s) || checksumU8s.length !== 32) {
2073
+ throw new Error("Unexpected program_checksum shape for ".concat(programId, ": expected 32-byte array, got ").concat((_JSON_stringify = JSON.stringify(checksumU8s)) === null || _JSON_stringify === void 0 ? void 0 : _JSON_stringify.slice(0, 100)));
2074
+ }
2075
+ bytes = new Uint8Array(32);
2076
+ for(i = 0; i < 32; i += 1){
2077
+ match = /^(\d+)u8$/.exec(String(checksumU8s[i]));
2078
+ if (!match) {
2079
+ throw new Error("Invalid u8 literal at index ".concat(i, " of program_checksum for ").concat(programId, ": ").concat(checksumU8s[i]));
2080
+ }
2081
+ bytes[i] = Number.parseInt(match[1], 10);
2082
+ }
2083
+ _this.programChecksumCache.set(cacheKey, bytes);
2084
+ return [
2085
+ 2,
2086
+ bytes
2087
+ ];
2088
+ }
2089
+ });
2090
+ })();
2091
+ }
2092
+ },
2093
+ {
2094
+ key: "getSealanceProof",
2095
+ value: /**
2096
+ * Computes (or returns from cache) the Sealance Merkle exclusion proof
2097
+ * for `accountAddress` against the given freezelist program's tree.
2098
+ *
2099
+ * The Sealance flow proves the sender is *not* on the freeze list. Recipe:
2100
+ * 1. Fetch the BigInt-string tree at
2101
+ * `/v2/{network}/programs/{freezelist}/compliance/freeze-list`.
2102
+ * 2. `tree[tree.length - 1]` is the Merkle root.
2103
+ * 3. `convertTreeToBigInt` → `getLeafIndices(addr)` → 2× `getSiblingPath`
2104
+ * → `formatMerkleProof` produces the formatted `[MerkleProof; 2u32]` literal.
2105
+ *
2106
+ * Cached per (accountAddress, freezelistProgram, root). On the next spend
2107
+ * we only refetch the tree and rebuild when the root has changed.
2108
+ */ function getSealanceProof(param) {
2109
+ var accountAddress = param.accountAddress, freezelistProgram = param.freezelistProgram, network = param.network;
2110
+ return _async_to_generator(function() {
2111
+ var url, response, treeStrings, currentRoot, cached, _cached_sealanceProofs, cachedProofs, cachedEntry, sdk, sealance, tree, _sealance_getLeafIndices, leftIdx, rightIdx, proofLeft, proofRight, formattedProof, _cached_records, _cached_spentNonces, _cached_lastScannedBlock;
2112
+ return _ts_generator(this, function(_state) {
2113
+ switch(_state.label){
2114
+ case 0:
2115
+ // Defense-in-depth: TS types don't enforce at runtime, so validate the
2116
+ // path segments before interpolating into the explorer URL.
2117
+ if (network !== 'testnet' && network !== 'mainnet') {
2118
+ throw new Error("Invalid network for Sealance proof: ".concat(network));
2119
+ }
2120
+ if (!/^\w+\.aleo$/.test(freezelistProgram)) {
2121
+ throw new Error("Invalid freezelist program ID: ".concat(freezelistProgram));
2122
+ }
2123
+ url = "https://api.explorer.provable.com/v2/".concat(network, "/programs/").concat(freezelistProgram, "/compliance/freeze-list");
2124
+ return [
2125
+ 4,
2126
+ fetch(url)
2127
+ ];
2128
+ case 1:
2129
+ response = _state.sent();
2130
+ if (!response.ok) {
2131
+ throw new Error("Failed to fetch Sealance freeze list (".concat(freezelistProgram, ", ").concat(network, "): HTTP ").concat(response.status));
2132
+ }
2133
+ return [
2134
+ 4,
2135
+ response.json()
2136
+ ];
2137
+ case 2:
2138
+ treeStrings = _state.sent();
2139
+ if (!Array.isArray(treeStrings) || treeStrings.length === 0) {
2140
+ throw new Error("Sealance freeze list response for ".concat(freezelistProgram, " on ").concat(network, " is empty or malformed."));
2141
+ }
2142
+ currentRoot = treeStrings.at(-1);
2143
+ return [
2144
+ 4,
2145
+ getWalletState(accountAddress, network)
2146
+ ];
2147
+ case 3:
2148
+ cached = _state.sent();
2149
+ cachedProofs = (_cached_sealanceProofs = cached === null || cached === void 0 ? void 0 : cached.sealanceProofs) !== null && _cached_sealanceProofs !== void 0 ? _cached_sealanceProofs : {};
2150
+ cachedEntry = cachedProofs[freezelistProgram];
2151
+ if ((cachedEntry === null || cachedEntry === void 0 ? void 0 : cachedEntry.root) === currentRoot) {
2152
+ return [
2153
+ 2,
2154
+ cachedEntry.formattedProof
2155
+ ];
2156
+ }
2157
+ return [
2158
+ 4,
2159
+ loadAleoSdk(network)
2160
+ ];
2161
+ case 4:
2162
+ sdk = _state.sent();
2163
+ sealance = new sdk.SealanceMerkleTree();
2164
+ tree = sealance.convertTreeToBigInt(treeStrings);
2165
+ _sealance_getLeafIndices = _sliced_to_array(sealance.getLeafIndices(tree, accountAddress), 2), leftIdx = _sealance_getLeafIndices[0], rightIdx = _sealance_getLeafIndices[1];
2166
+ proofLeft = sealance.getSiblingPath(tree, leftIdx, SEALANCE_TREE_DEPTH);
2167
+ proofRight = sealance.getSiblingPath(tree, rightIdx, SEALANCE_TREE_DEPTH);
2168
+ formattedProof = sealance.formatMerkleProof([
2169
+ proofLeft,
2170
+ proofRight
2171
+ ]);
2172
+ return [
2173
+ 4,
2174
+ putWalletState(accountAddress, network, {
2175
+ scannerUuid: cached === null || cached === void 0 ? void 0 : cached.scannerUuid,
2176
+ records: (_cached_records = cached === null || cached === void 0 ? void 0 : cached.records) !== null && _cached_records !== void 0 ? _cached_records : '[]',
2177
+ spentNonces: (_cached_spentNonces = cached === null || cached === void 0 ? void 0 : cached.spentNonces) !== null && _cached_spentNonces !== void 0 ? _cached_spentNonces : [],
2178
+ lastScannedBlock: (_cached_lastScannedBlock = cached === null || cached === void 0 ? void 0 : cached.lastScannedBlock) !== null && _cached_lastScannedBlock !== void 0 ? _cached_lastScannedBlock : 0,
2179
+ sealanceProofs: _object_spread_props(_object_spread({}, cachedProofs), _define_property({}, freezelistProgram, {
2180
+ root: currentRoot,
2181
+ formattedProof: formattedProof,
2182
+ computedAt: Date.now()
2183
+ }))
2184
+ })
2185
+ ];
2186
+ case 5:
2187
+ _state.sent();
2188
+ return [
2189
+ 2,
2190
+ formattedProof
2191
+ ];
2192
+ }
2193
+ });
2194
+ })();
2195
+ }
2196
+ },
2197
+ {
2198
+ key: "proveTransaction",
2199
+ value: /**
2200
+ * Full Aleo transaction flow:
2201
+ * viewKey (MPC exported, cached) → computeExternalSigningInputs
2202
+ * → Sodot signAleoRequest MPC ceremony
2203
+ * → buildExecutionRequestFromExternallySignedData
2204
+ * → Provable DPS submitProvingRequest (computes ZK proof + broadcasts)
2205
+ *
2206
+ * Handles both non-record functions (transfer_public) and record-consuming
2207
+ * functions (transfer_private, join, transfer_public_to_private).
2208
+ *
2209
+ * For Sealance-compliant tier-3 stablecoins (USAD, USDCx), the iframe also
2210
+ * auto-fetches/computes the Merkle exclusion proof and appends it to
2211
+ * `inputs`/`inputTypes` when the program/function pair calls for it. The
2212
+ * caller passes the same shape as a credits.aleo transfer.
2213
+ *
2214
+ * @param broadcast - if true, DPS broadcasts the transaction and returns a
2215
+ * txId. If false, DPS returns the proving response and the caller
2216
+ * decides what to do with it.
2217
+ */ function proveTransaction(param) {
2218
+ var accountAddress = param.accountAddress, programId = param.programId, functionName = param.functionName, inputs = param.inputs, inputTypes = param.inputTypes, _param_broadcast = param.broadcast, broadcast = _param_broadcast === void 0 ? true : _param_broadcast, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken, chainId = param.chainId;
2219
+ var _this = this;
2220
+ return _async_to_generator(function() {
2221
+ var viewKey, txNetwork, sdk, programManager, _ref, effectiveInputs, effectiveInputTypes, checksum, signingInputs, payload, signedRequest, executionRequestBase, executionRequest, provingRequest, provingResult, _provingResult_transaction;
2222
+ return _ts_generator(this, function(_state) {
2223
+ switch(_state.label){
2224
+ case 0:
2225
+ if (!accountAddress) {
2226
+ throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
2227
+ }
2228
+ return [
2229
+ 4,
2230
+ _this.exportViewKey({
2231
+ accountAddress: accountAddress,
2232
+ password: password,
2233
+ signedSessionId: signedSessionId,
2234
+ mfaToken: mfaToken,
2235
+ elevatedAccessToken: elevatedAccessToken
2236
+ })
2237
+ ];
2238
+ case 1:
2239
+ viewKey = _state.sent();
2240
+ // Network resolution: prefer the caller-supplied chainId. The
2241
+ // `networkFromProgramId` heuristic only works for programs whose
2242
+ // name varies by network (`test_` prefix on stablecoins / ARC-21);
2243
+ // it can't disambiguate `credits.aleo`. We trust the caller first
2244
+ // and only fall back to the heuristic when chainId is omitted.
2245
+ txNetwork = chainId !== undefined && chainId !== null ? resolveAleoNetwork(chainId) : networkFromProgramId(programId);
2246
+ return [
2247
+ 4,
2248
+ loadAleoSdk(txNetwork)
2249
+ ];
2250
+ case 2:
2251
+ sdk = _state.sent();
2252
+ return [
2253
+ 4,
2254
+ _this.getProgramManager(txNetwork)
2255
+ ];
2256
+ case 3:
2257
+ programManager = _state.sent();
2258
+ return [
2259
+ 4,
2260
+ _this.injectSealanceProofIfNeeded({
2261
+ accountAddress: accountAddress,
2262
+ functionName: functionName,
2263
+ inputTypes: inputTypes,
2264
+ inputs: inputs,
2265
+ programId: programId
2266
+ })
2267
+ ];
2268
+ case 4:
2269
+ _ref = _state.sent(), effectiveInputs = _ref.inputs, effectiveInputTypes = _ref.inputTypes;
2270
+ return [
2271
+ 4,
2272
+ _this.deriveProgramChecksumField({
2273
+ programId: programId,
2274
+ sdk: sdk,
2275
+ txNetwork: txNetwork
2276
+ })
2277
+ ];
2278
+ case 5:
2279
+ checksum = _state.sent();
2280
+ return [
2281
+ 4,
2282
+ sdk.computeExternalSigningInputs({
2283
+ programName: programId,
2284
+ functionName: functionName,
2285
+ inputs: effectiveInputs,
2286
+ inputTypes: effectiveInputTypes,
2287
+ isRoot: true,
2288
+ checksum: checksum,
2289
+ viewKey: viewKey,
2290
+ outputFormat: 'bytes'
2291
+ })
2292
+ ];
2293
+ case 6:
2294
+ signingInputs = _state.sent();
2295
+ payload = _this.toRequestSignPayload(signingInputs);
2296
+ return [
2297
+ 4,
2298
+ _this.signAleoRequest({
2299
+ accountAddress: accountAddress,
2300
+ payload: payload,
2301
+ password: password,
2302
+ signedSessionId: signedSessionId,
2303
+ mfaToken: mfaToken,
2304
+ elevatedAccessToken: elevatedAccessToken
2305
+ })
2306
+ ];
2307
+ case 7:
2308
+ signedRequest = _state.sent();
2309
+ executionRequestBase = {
2310
+ programId: programId,
2311
+ functionName: functionName,
2312
+ inputs: effectiveInputs,
2313
+ inputTypes: effectiveInputTypes,
2314
+ signature: signedRequest.signature,
2315
+ tvk: signedRequest.tvk,
2316
+ signer: signedRequest.signer,
2317
+ skTag: signingInputs.skTag
2318
+ };
2319
+ // Use the viewKey strategy — works for all function shapes:
2320
+ // - record-consuming: SDK derives recordViewKeys from the viewKey
2321
+ // - record-producing: gammas feed the output record's commitment derivation
2322
+ // - pure-public: both are no-ops, safe to pass
2323
+ // `signedRequest.gammas` comes from the MPC signature and is required
2324
+ // whenever the circuit references any record (input or output).
2325
+ executionRequest = sdk.buildExecutionRequestFromExternallySignedData(executionRequestBase, {
2326
+ viewKey: viewKey,
2327
+ gammas: signedRequest.gammas
2328
+ });
2329
+ return [
2330
+ 4,
2331
+ _this.buildProvingRequest({
2332
+ broadcast: broadcast,
2333
+ effectiveInputs: effectiveInputs,
2334
+ executionRequest: executionRequest,
2335
+ functionName: functionName,
2336
+ programId: programId,
2337
+ programManager: programManager,
2338
+ sdk: sdk,
2339
+ txNetwork: txNetwork
2340
+ })
2341
+ ];
2342
+ case 8:
2343
+ provingRequest = _state.sent();
2344
+ return [
2345
+ 4,
2346
+ programManager.networkClient.submitProvingRequest({
2347
+ provingRequest: provingRequest,
2348
+ dpsPrivacy: true
2349
+ })
2350
+ ];
2351
+ case 9:
2352
+ provingResult = _state.sent();
2353
+ if (broadcast) {
2354
+ return [
2355
+ 2,
2356
+ {
2357
+ txId: provingResult === null || provingResult === void 0 ? void 0 : (_provingResult_transaction = provingResult.transaction) === null || _provingResult_transaction === void 0 ? void 0 : _provingResult_transaction.id
2358
+ }
2359
+ ];
2360
+ }
2361
+ return [
2362
+ 2,
2363
+ {
2364
+ provingResponse: provingResult
2365
+ }
2366
+ ];
2367
+ }
2368
+ });
2369
+ })();
2370
+ }
2371
+ },
2372
+ {
2373
+ key: "injectSealanceProofIfNeeded",
2374
+ value: /**
2375
+ * Sealance auto-injection. For tier-3 stablecoin transfer functions that
2376
+ * require a freeze-list exclusion proof, append the formatted
2377
+ * `[MerkleProof; 2u32].private` literal to inputs/inputTypes. Programs
2378
+ * not in the registry / function not requiring proof → pass-through.
2379
+ */ function injectSealanceProofIfNeeded(param) {
2380
+ var accountAddress = param.accountAddress, functionName = param.functionName, inputTypes = param.inputTypes, inputs = param.inputs, programId = param.programId;
2381
+ var _this = this;
2382
+ return _async_to_generator(function() {
2383
+ var sealanceConfig, proof;
2384
+ return _ts_generator(this, function(_state) {
2385
+ switch(_state.label){
2386
+ case 0:
2387
+ sealanceConfig = lookupSealanceConfig(programId);
2388
+ if (!sealanceConfig || !SEALANCE_FUNCTIONS_REQUIRING_PROOF.has(functionName)) {
2389
+ return [
2390
+ 2,
2391
+ {
2392
+ inputTypes: inputTypes,
2393
+ inputs: inputs
2394
+ }
2395
+ ];
2396
+ }
2397
+ return [
2398
+ 4,
2399
+ _this.getSealanceProof({
2400
+ accountAddress: accountAddress,
2401
+ freezelistProgram: sealanceConfig.freezelistProgram,
2402
+ network: sealanceConfig.network
2403
+ })
2404
+ ];
2405
+ case 1:
2406
+ proof = _state.sent();
2407
+ return [
2408
+ 2,
2409
+ {
2410
+ inputTypes: _to_consumable_array(inputTypes).concat([
2411
+ SEALANCE_PROOF_INPUT_TYPE
2412
+ ]),
2413
+ inputs: _to_consumable_array(inputs).concat([
2414
+ proof
2415
+ ])
2416
+ }
2417
+ ];
2418
+ }
2419
+ });
2420
+ })();
2421
+ }
2422
+ },
2423
+ {
2424
+ key: "deriveProgramChecksumField",
2425
+ value: /**
2426
+ * Derive the program-checksum `Field` snarkVM's external-signing path
2427
+ * needs for non-credits programs. `credits.aleo` is special-cased in the
2428
+ * WASM and works with `null`. Other programs: fetch the on-chain 32-byte
2429
+ * checksum, expand bytes → bits LE, truncate to `Field::SIZE_IN_DATA_BITS`
2430
+ * (252 for Fr), and call `Field.fromBitsLe` — mirrors snarkVM's own
2431
+ * `Stack::program_checksum_as_field`.
2432
+ */ function deriveProgramChecksumField(param) {
2433
+ var programId = param.programId, sdk = param.sdk, txNetwork = param.txNetwork;
2434
+ var _this = this;
2435
+ return _async_to_generator(function() {
2436
+ var checksumBytes, bits, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, byte, i, SIZE_IN_DATA_BITS;
2437
+ return _ts_generator(this, function(_state) {
2438
+ switch(_state.label){
2439
+ case 0:
2440
+ if (programId === 'credits.aleo') return [
2441
+ 2,
2442
+ null
2443
+ ];
2444
+ return [
2445
+ 4,
2446
+ _this.getProgramChecksum(programId, txNetwork)
2447
+ ];
2448
+ case 1:
2449
+ checksumBytes = _state.sent();
2450
+ if (checksumBytes === null) return [
2451
+ 2,
2452
+ null
2453
+ ];
2454
+ bits = [];
2455
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2456
+ try {
2457
+ for(_iterator = checksumBytes[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2458
+ byte = _step.value;
2459
+ for(i = 0; i < 8; i += 1){
2460
+ bits.push((byte >> i & 1) === 1);
2461
+ }
2462
+ }
2463
+ } catch (err) {
2464
+ _didIteratorError = true;
2465
+ _iteratorError = err;
2466
+ } finally{
2467
+ try {
2468
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
2469
+ _iterator.return();
2470
+ }
2471
+ } finally{
2472
+ if (_didIteratorError) {
2473
+ throw _iteratorError;
2474
+ }
2475
+ }
2476
+ }
2477
+ // Aleo's `Field` is the BLS12-377 scalar field Fr (252 data bits).
2478
+ SIZE_IN_DATA_BITS = 252;
2479
+ return [
2480
+ 2,
2481
+ sdk.Field.fromBitsLe(bits.slice(0, SIZE_IN_DATA_BITS))
2482
+ ];
2483
+ }
2484
+ });
2485
+ })();
2486
+ }
2487
+ },
2488
+ {
2489
+ key: "buildProvingRequest",
2490
+ value: /**
2491
+ * Build the proving request — feemaster path when ANF covers the
2492
+ * (programId, functionName), user-paid fallback otherwise. Feemaster
2493
+ * failures fall through silently so a transient policy/quota issue
2494
+ * doesn't block the user; they just pay the fee themselves.
2495
+ */ function buildProvingRequest(param) {
2496
+ var broadcast = param.broadcast, effectiveInputs = param.effectiveInputs, executionRequest = param.executionRequest, functionName = param.functionName, programId = param.programId, programManager = param.programManager, sdk = param.sdk, txNetwork = param.txNetwork;
2497
+ var _this = this;
2498
+ return _async_to_generator(function() {
2499
+ var feemaster, _tmp, err;
2500
+ return _ts_generator(this, function(_state) {
2501
+ switch(_state.label){
2502
+ case 0:
2503
+ feemaster = _this.getFeemasterClient(txNetwork);
2504
+ _tmp = feemaster;
2505
+ if (!_tmp) return [
2506
+ 3,
2507
+ 2
2508
+ ];
2509
+ return [
2510
+ 4,
2511
+ feemaster.isCovered(programId, functionName)
2512
+ ];
2513
+ case 1:
2514
+ _tmp = _state.sent();
2515
+ _state.label = 2;
2516
+ case 2:
2517
+ if (!_tmp) return [
2518
+ 3,
2519
+ 6
2520
+ ];
2521
+ _state.label = 3;
2522
+ case 3:
2523
+ _state.trys.push([
2524
+ 3,
2525
+ 5,
2526
+ ,
2527
+ 6
2528
+ ]);
2529
+ return [
2530
+ 4,
2531
+ _this.buildFeemasterProvingRequest({
2532
+ broadcast: broadcast,
2533
+ executionRequest: executionRequest,
2534
+ feemaster: feemaster,
2535
+ programId: programId,
2536
+ programManager: programManager,
2537
+ sdk: sdk
2538
+ })
2539
+ ];
2540
+ case 4:
2541
+ return [
2542
+ 2,
2543
+ _state.sent()
2544
+ ];
2545
+ case 5:
2546
+ err = _state.sent();
2547
+ // eslint-disable-next-line no-console
2548
+ console.warn('[aleo:proveTransaction] Feemaster path failed; falling back to user-paid fee', err);
2549
+ return [
2550
+ 3,
2551
+ 6
2552
+ ];
2553
+ case 6:
2554
+ // User-paid fee path. The SDK's `provingRequest` short-circuits its
2555
+ // private-key check when `executionRequest` is provided — it forwards
2556
+ // the already-MPC-signed request straight to
2557
+ // `WasmProgramManager.buildProvingRequestFromExecutionRequest`.
2558
+ return [
2559
+ 2,
2560
+ programManager.provingRequest({
2561
+ programName: programId,
2562
+ functionName: functionName,
2563
+ inputs: effectiveInputs,
2564
+ priorityFee: 0,
2565
+ privateFee: false,
2566
+ broadcast: broadcast,
2567
+ executionRequest: executionRequest
2568
+ })
2569
+ ];
2570
+ }
2571
+ });
2572
+ })();
2573
+ }
2574
+ },
2575
+ {
2576
+ key: "buildFeemasterProvingRequest",
2577
+ value: /**
2578
+ * Feemaster-sponsored proving request. Builds the user authorization via
2579
+ * the WASM-direct ProgramManager static (no private key needed — the
2580
+ * request is already MPC-signed), exchanges it with the Feemaster for a
2581
+ * `feeAuthorization`, and returns the bundled `ProvingRequest`.
2582
+ */ function buildFeemasterProvingRequest(param) {
2583
+ var broadcast = param.broadcast, executionRequest = param.executionRequest, feemaster = param.feemaster, programId = param.programId, programManager = param.programManager, sdk = param.sdk;
2584
+ return _async_to_generator(function() {
2585
+ var networkClient, programSrc, edition, importedPrograms, authorization, feeAuthorizationString, feeAuthorization;
2586
+ return _ts_generator(this, function(_state) {
2587
+ switch(_state.label){
2588
+ case 0:
2589
+ networkClient = programManager.networkClient;
2590
+ return [
2591
+ 4,
2592
+ networkClient.getProgram(programId)
2593
+ ];
2594
+ case 1:
2595
+ programSrc = _state.sent();
2596
+ return [
2597
+ 4,
2598
+ networkClient.getLatestProgramEdition(programId)
2599
+ ];
2600
+ case 2:
2601
+ edition = _state.sent();
2602
+ return [
2603
+ 4,
2604
+ networkClient.getProgramImports(programId).catch(function() {
2605
+ return undefined;
2606
+ })
2607
+ ];
2608
+ case 3:
2609
+ importedPrograms = _state.sent();
2610
+ return [
2611
+ 4,
2612
+ sdk.ProgramManagerBase.buildAuthorizationFromExecutionRequest(executionRequest, programSrc, /* unchecked */ true, edition, importedPrograms, /* private_key */ null)
2613
+ ];
2614
+ case 4:
2615
+ authorization = _state.sent();
2616
+ return [
2617
+ 4,
2618
+ feemaster.requestFeeAuthorization({
2619
+ authorizationString: authorization.toString()
2620
+ })
2621
+ ];
2622
+ case 5:
2623
+ feeAuthorizationString = _state.sent().feeAuthorizationString;
2624
+ feeAuthorization = sdk.Authorization.fromString(feeAuthorizationString);
2625
+ return [
2626
+ 2,
2627
+ sdk.ProvingRequest.new(authorization, feeAuthorization, broadcast)
2628
+ ];
2629
+ }
2630
+ });
2631
+ })();
2632
+ }
2633
+ },
2634
+ {
2635
+ key: "isFeemasterCovered",
2636
+ value: /**
2637
+ * Standalone Feemaster coverage check for any (programId, functionName)
2638
+ * pair on the connector-selected network. Used by the widget to decide
2639
+ * whether a user-paid confirmation modal is needed before triggering a
2640
+ * shield/send/join. Resolves the network from the caller-supplied
2641
+ * `chainId`; defaults to testnet when omitted (mirrors `resolveAleoNetwork`).
2642
+ *
2643
+ * Never throws — returns `false` on any policy fetch failure so callers
2644
+ * can default to "show modal" rather than silently shielding.
2645
+ */ function isFeemasterCovered(param) {
2646
+ var programId = param.programId, functionName = param.functionName, chainId = param.chainId;
2647
+ var _this = this;
2648
+ return _async_to_generator(function() {
2649
+ var network, feemaster;
2650
+ return _ts_generator(this, function(_state) {
2651
+ switch(_state.label){
2652
+ case 0:
2653
+ network = chainId !== undefined && chainId !== null ? resolveAleoNetwork(chainId) : 'testnet';
2654
+ feemaster = _this.getFeemasterClient(network);
2655
+ if (!feemaster) return [
2656
+ 2,
2657
+ false
2658
+ ];
2659
+ _state.label = 1;
2660
+ case 1:
2661
+ _state.trys.push([
2662
+ 1,
2663
+ 3,
2664
+ ,
2665
+ 4
2666
+ ]);
2667
+ return [
2668
+ 4,
2669
+ feemaster.isCovered(programId, functionName)
2670
+ ];
2671
+ case 2:
2672
+ return [
2673
+ 2,
2674
+ _state.sent()
2675
+ ];
2676
+ case 3:
2677
+ _state.sent();
2678
+ return [
2679
+ 2,
2680
+ false
2681
+ ];
2682
+ case 4:
2683
+ return [
2684
+ 2
2685
+ ];
2686
+ }
2687
+ });
2688
+ })();
2689
+ }
2690
+ },
2691
+ {
2692
+ key: "getProgramManager",
2693
+ value: /**
2694
+ * Lazy-load the network-matching `@provablehq/sdk` build, instantiate a
2695
+ * ProgramManager, and cache it. The Provable WASM bundle is ~20MB, so
2696
+ * we avoid loading it eagerly at iframe init; both networks' bundles
2697
+ * load on first use of each.
2698
+ */ function getProgramManager(network) {
2699
+ var _this = this;
2700
+ return _async_to_generator(function() {
2701
+ var cached, sdk, programManager, sameOriginProxy;
2702
+ return _ts_generator(this, function(_state) {
2703
+ switch(_state.label){
2704
+ case 0:
2705
+ cached = _this.programManagersByNetwork.get(network);
2706
+ if (cached) return [
2707
+ 2,
2708
+ cached
2709
+ ];
2710
+ return [
2711
+ 4,
2712
+ loadAleoSdk(network)
2713
+ ];
2714
+ case 1:
2715
+ sdk = _state.sent();
2716
+ programManager = new sdk.ProgramManager();
2717
+ // accelerate.provable.com rejects the SDK's X-Aleo-* headers via CORS and
2718
+ // ships `Access-Control-Allow-Origin: *` alongside `credentials: include`
2719
+ // (incompatible). In dev, route through the iframe host's Vite proxy
2720
+ // (`/aleo-dps`) so the browser sees same-origin calls. In prod, the iframe
2721
+ // host must proxy `/aleo-dps/*` to accelerate.provable.com.
2722
+ sameOriginProxy = typeof globalThis !== 'undefined' && globalThis.location ? "".concat(globalThis.location.origin, "/aleo-dps") : DEFAULT_PROVABLE_PROVER_URI;
2723
+ programManager.networkClient.setProverUri(sameOriginProxy);
2724
+ _this.programManagersByNetwork.set(network, programManager);
2725
+ return [
2726
+ 2,
2727
+ programManager
2728
+ ];
2729
+ }
2730
+ });
2731
+ })();
2732
+ }
2733
+ },
2734
+ {
2735
+ key: "getFeemasterClient",
2736
+ value: function getFeemasterClient(network) {
2737
+ var cached = this.feemasterClients.get(network);
2738
+ if (cached) return cached;
2739
+ var client = new FeemasterClient({
2740
+ apiClient: this.apiClient,
2741
+ network: network
2742
+ });
2743
+ this.feemasterClients.set(network, client);
2744
+ return client;
2745
+ }
2746
+ },
2747
+ {
2748
+ key: "getRecordScanner",
2749
+ value: /**
2750
+ * Lazy-init RecordScanner for the given Aleo network using the shared
2751
+ * Provable consumer credentials (VITE_ALEO_SCANNER_API_KEY +
2752
+ * VITE_ALEO_SCANNER_CONSUMER_ID in iframe env). Scanner calls and JWT
2753
+ * refresh both route through the Vite dev proxy `/aleo-api/*` to work
2754
+ * around Provable's CORS 401 on preflight.
2755
+ *
2756
+ * The Provable SDK ships separate `testnet.js` / `mainnet.js` builds
2757
+ * (verified in `node_modules/@provablehq/sdk/package.json#exports`). Each
2758
+ * build pins the chain endpoints to that network, so the right scanner
2759
+ * comes from importing the matching build. We cache an instance per
2760
+ * network on `this.scannersByNetwork`; toggling networks at runtime is
2761
+ * a Map lookup, no teardown.
2762
+ */ function getRecordScanner(network) {
2763
+ var _this = this;
2764
+ return _async_to_generator(function() {
2765
+ var cached, sdk, scanner;
2766
+ return _ts_generator(this, function(_state) {
2767
+ switch(_state.label){
2768
+ case 0:
2769
+ cached = _this.scannersByNetwork.get(network);
2770
+ if (cached) return [
2771
+ 2,
2772
+ cached
2773
+ ];
2774
+ return [
2775
+ 4,
2776
+ loadAleoSdk(network)
2777
+ ];
2778
+ case 1:
2779
+ sdk = _state.sent();
2780
+ scanner = new RedcoastRecordScanner({
2781
+ apiClient: _this.apiClient,
2782
+ network: network,
2783
+ sdk: sdk
2784
+ });
2785
+ _this.scannersByNetwork.set(network, scanner);
2786
+ return [
2787
+ 2,
2788
+ scanner
2789
+ ];
2790
+ }
2791
+ });
2792
+ })();
2793
+ }
2794
+ },
2795
+ {
2796
+ key: "findOwnedRecords",
2797
+ value: /**
2798
+ * List all Aleo records owned by this wallet across every program (credits,
2799
+ * custom tokens, etc.). Uses Provable's hosted RecordScanner with our shared
2800
+ * consumer; per-wallet scanner UUID is cached in iframe IndexedDB
2801
+ * (walletStateStorage) so subsequent calls skip the register step.
2802
+ *
2803
+ * Each returned record carries `program_name` + `record_name` so callers
2804
+ * can classify by token. Credits records additionally get a `microcredits`
2805
+ * field parsed in-iframe for convenience (public WASM primitive). Other
2806
+ * tokens are returned as-is — the caller is responsible for amount parsing
2807
+ * per program schema.
2808
+ *
2809
+ * Records are decrypted locally in the iframe via view-key only.
2810
+ * Spent-tracking filters out locally-known spent nonces (records we
2811
+ * consumed in our own proveTransaction calls, before the scanner has
2812
+ * re-indexed).
2813
+ */ function findOwnedRecords(params) {
2814
+ var _this = this;
2815
+ return _async_to_generator(function() {
2816
+ var accountAddress, chainId, network, dedupeKey, inflight, promise;
2817
+ return _ts_generator(this, function(_state) {
2818
+ accountAddress = params.accountAddress, chainId = params.chainId;
2819
+ if (!accountAddress) {
2820
+ throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
2821
+ }
2822
+ // Dedupe concurrent scans on the same (wallet, network) so the recovery
2823
+ // path runs at most once. Including the network in the key lets a user
2824
+ // who toggles networks in flight kick off one scan per network without
2825
+ // the second being absorbed into the first.
2826
+ network = resolveAleoNetwork(chainId);
2827
+ dedupeKey = "".concat(accountAddress, ":").concat(network);
2828
+ inflight = _this.pendingFindOwnedRecords.get(dedupeKey);
2829
+ if (inflight) return [
2830
+ 2,
2831
+ inflight
2832
+ ];
2833
+ promise = _this.findOwnedRecordsInner(params).finally(function() {
2834
+ _this.pendingFindOwnedRecords.delete(dedupeKey);
2835
+ });
2836
+ _this.pendingFindOwnedRecords.set(dedupeKey, promise);
2837
+ return [
2838
+ 2,
2839
+ promise
2840
+ ];
2841
+ });
2842
+ })();
2843
+ }
2844
+ },
2845
+ {
2846
+ key: "findOwnedRecordsInner",
2847
+ value: function findOwnedRecordsInner(param) {
2848
+ var accountAddress = param.accountAddress, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken, chainId = param.chainId;
2849
+ var _this = this;
2850
+ return _async_to_generator(function() {
2851
+ var viewKey, network, sdk, cached, _cached_spentNonces, spentNonces, _ref, ownedRecords, scannerUuid, viewKeyObj, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, record, filtered, _cached_lastScannedBlock;
2852
+ return _ts_generator(this, function(_state) {
2853
+ switch(_state.label){
2854
+ case 0:
2855
+ return [
2856
+ 4,
2857
+ _this.exportViewKey({
2858
+ accountAddress: accountAddress,
2859
+ password: password,
2860
+ signedSessionId: signedSessionId,
2861
+ mfaToken: mfaToken,
2862
+ elevatedAccessToken: elevatedAccessToken
2863
+ })
2864
+ ];
2865
+ case 1:
2866
+ viewKey = _state.sent();
2867
+ network = resolveAleoNetwork(chainId);
2868
+ return [
2869
+ 4,
2870
+ _this.loadAleoSdkOrThrow(network)
2871
+ ];
2872
+ case 2:
2873
+ sdk = _state.sent();
2874
+ return [
2875
+ 4,
2876
+ _this.loadWalletStateOrThrow(accountAddress, network)
2877
+ ];
2878
+ case 3:
2879
+ cached = _state.sent();
2880
+ spentNonces = (_cached_spentNonces = cached === null || cached === void 0 ? void 0 : cached.spentNonces) !== null && _cached_spentNonces !== void 0 ? _cached_spentNonces : [];
2881
+ return [
2882
+ 4,
2883
+ _this.findRecordsWithUuidRetry({
2884
+ accountAddress: accountAddress,
2885
+ cached: cached,
2886
+ network: network,
2887
+ sdk: sdk,
2888
+ spentNonces: spentNonces,
2889
+ viewKey: viewKey
2890
+ })
2891
+ ];
2892
+ case 4:
2893
+ _ref = _state.sent(), ownedRecords = _ref.records, scannerUuid = _ref.scannerUuid;
2894
+ // Decrypt + annotate (microcredits / amount) per record so the DApp
2895
+ // doesn't need the Provable WASM in its own bundle.
2896
+ viewKeyObj = sdk.ViewKey.from_string(viewKey);
2897
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2898
+ try {
2899
+ for(_iterator = ownedRecords[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2900
+ record = _step.value;
2901
+ _this.enrichOwnedRecord(record, sdk, viewKeyObj);
2902
+ }
2903
+ } catch (err) {
2904
+ _didIteratorError = true;
2905
+ _iteratorError = err;
2906
+ } finally{
2907
+ try {
2908
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
2909
+ _iterator.return();
2910
+ }
2911
+ } finally{
2912
+ if (_didIteratorError) {
2913
+ throw _iteratorError;
2914
+ }
2915
+ }
2916
+ }
2917
+ filtered = _this.filterUnspentRecords(ownedRecords, sdk, spentNonces);
2918
+ // Persist the fresh set so subsequent calls can return immediately if
2919
+ // the scanner is unreachable.
2920
+ return [
2921
+ 4,
2922
+ putWalletState(accountAddress, network, {
2923
+ scannerUuid: scannerUuid,
2924
+ records: JSON.stringify(filtered),
2925
+ spentNonces: spentNonces,
2926
+ lastScannedBlock: (_cached_lastScannedBlock = cached === null || cached === void 0 ? void 0 : cached.lastScannedBlock) !== null && _cached_lastScannedBlock !== void 0 ? _cached_lastScannedBlock : 0
2927
+ })
2928
+ ];
2929
+ case 5:
2930
+ _state.sent();
2931
+ return [
2932
+ 2,
2933
+ {
2934
+ records: filtered
2935
+ }
2936
+ ];
2937
+ }
2938
+ });
2939
+ })();
2940
+ }
2941
+ },
2942
+ {
2943
+ key: "loadAleoSdkOrThrow",
2944
+ value: /**
2945
+ * Loads the network-specific Provable SDK build and surfaces a clear
2946
+ * error log to the iframe console when WASM init fails (so the failure
2947
+ * is debuggable; the throw still propagates).
2948
+ */ function loadAleoSdkOrThrow(network) {
2949
+ return _async_to_generator(function() {
2950
+ var err;
2951
+ return _ts_generator(this, function(_state) {
2952
+ switch(_state.label){
2953
+ case 0:
2954
+ _state.trys.push([
2955
+ 0,
2956
+ 2,
2957
+ ,
2958
+ 3
2959
+ ]);
2960
+ return [
2961
+ 4,
2962
+ loadAleoSdk(network)
2963
+ ];
2964
+ case 1:
2965
+ return [
2966
+ 2,
2967
+ _state.sent()
2968
+ ];
2969
+ case 2:
2970
+ err = _state.sent();
2971
+ // eslint-disable-next-line no-console
2972
+ console.error('[aleo-client:findOwnedRecordsInner] loadAleoSdk FAILED', {
2973
+ network: network,
2974
+ error: _instanceof(err, Error) ? err.message : String(err)
2975
+ });
2976
+ throw err;
2977
+ case 3:
2978
+ return [
2979
+ 2
2980
+ ];
2981
+ }
2982
+ });
2983
+ })();
2984
+ }
2985
+ },
2986
+ {
2987
+ key: "loadWalletStateOrThrow",
2988
+ value: /**
2989
+ * Reads the per-(account, network) wallet state from IndexedDB. Errors
2990
+ * are logged and rethrown — a wedged IDB blocks the find-records flow
2991
+ * entirely, so silent fallback isn't safe here.
2992
+ */ function loadWalletStateOrThrow(accountAddress, network) {
2993
+ return _async_to_generator(function() {
2994
+ var err;
2995
+ return _ts_generator(this, function(_state) {
2996
+ switch(_state.label){
2997
+ case 0:
2998
+ _state.trys.push([
2999
+ 0,
3000
+ 2,
3001
+ ,
3002
+ 3
3003
+ ]);
3004
+ return [
3005
+ 4,
3006
+ getWalletState(accountAddress, network)
3007
+ ];
3008
+ case 1:
3009
+ return [
3010
+ 2,
3011
+ _state.sent()
3012
+ ];
3013
+ case 2:
3014
+ err = _state.sent();
3015
+ // eslint-disable-next-line no-console
3016
+ console.error('[aleo-client:findOwnedRecordsInner] getWalletState FAILED', {
3017
+ error: _instanceof(err, Error) ? err.message : String(err)
3018
+ });
3019
+ throw err;
3020
+ case 3:
3021
+ return [
3022
+ 2
3023
+ ];
3024
+ }
3025
+ });
3026
+ })();
3027
+ }
3028
+ },
3029
+ {
3030
+ key: "findRecordsWithUuidRetry",
3031
+ value: /**
3032
+ * Provable's RecordScanner can throw a `UUIDError` for several reasons —
3033
+ * cached UUID expired server-side, consumer key rotated, scanner instance
3034
+ * stale after a JWT refresh blip. Recovery: drop the cached scanner
3035
+ * instance + cached UUID, re-register, retry up to twice. After that the
3036
+ * problem isn't UUID-related and we surface the underlying error.
3037
+ */ function findRecordsWithUuidRetry(param) {
3038
+ var accountAddress = param.accountAddress, cached = param.cached, network = param.network, sdk = param.sdk, spentNonces = param.spentNonces, viewKey = param.viewKey;
3039
+ var _this = this;
3040
+ return _async_to_generator(function() {
3041
+ var registerWallet, tryFind, _cached_scannerUuid, scannerUuid, _tmp, lastErr, attempt, _tmp1, err, _cached_records, _cached_lastScannedBlock;
3042
+ return _ts_generator(this, function(_state) {
3043
+ switch(_state.label){
3044
+ case 0:
3045
+ registerWallet = /*#__PURE__*/ function() {
3046
+ var _ref = _async_to_generator(function() {
3047
+ return _ts_generator(this, function(_state) {
3048
+ return [
3049
+ 2,
3050
+ _this.registerScannerWallet({
3051
+ accountAddress: accountAddress,
3052
+ cached: cached,
3053
+ network: network,
3054
+ sdk: sdk,
3055
+ spentNonces: spentNonces,
3056
+ viewKey: viewKey
3057
+ })
3058
+ ];
3059
+ });
3060
+ });
3061
+ return function registerWallet() {
3062
+ return _ref.apply(this, arguments);
3063
+ };
3064
+ }();
3065
+ tryFind = /*#__PURE__*/ function() {
3066
+ var _ref = _async_to_generator(function(uuid) {
3067
+ var scanner;
3068
+ return _ts_generator(this, function(_state) {
3069
+ switch(_state.label){
3070
+ case 0:
3071
+ return [
3072
+ 4,
3073
+ _this.getRecordScanner(network)
3074
+ ];
3075
+ case 1:
3076
+ scanner = _state.sent();
3077
+ return [
3078
+ 2,
3079
+ scanner.findRecords({
3080
+ uuid: uuid,
3081
+ decrypt: true,
3082
+ unspent: true,
3083
+ filter: {}
3084
+ })
3085
+ ];
3086
+ }
3087
+ });
3088
+ });
3089
+ return function tryFind(uuid) {
3090
+ return _ref.apply(this, arguments);
3091
+ };
3092
+ }();
3093
+ if (!((_cached_scannerUuid = cached === null || cached === void 0 ? void 0 : cached.scannerUuid) !== null && _cached_scannerUuid !== void 0)) return [
3094
+ 3,
3095
+ 1
3096
+ ];
3097
+ _tmp = _cached_scannerUuid;
3098
+ return [
3099
+ 3,
3100
+ 3
3101
+ ];
3102
+ case 1:
3103
+ return [
3104
+ 4,
3105
+ registerWallet()
3106
+ ];
3107
+ case 2:
3108
+ _tmp = _state.sent();
3109
+ _state.label = 3;
3110
+ case 3:
3111
+ scannerUuid = _tmp;
3112
+ attempt = 0;
3113
+ _state.label = 4;
3114
+ case 4:
3115
+ if (!(attempt < 3)) return [
3116
+ 3,
3117
+ 12
3118
+ ];
3119
+ _state.label = 5;
3120
+ case 5:
3121
+ _state.trys.push([
3122
+ 5,
3123
+ 7,
3124
+ ,
3125
+ 11
3126
+ ]);
3127
+ _tmp1 = {};
3128
+ return [
3129
+ 4,
3130
+ tryFind(scannerUuid)
3131
+ ];
3132
+ case 6:
3133
+ return [
3134
+ 2,
3135
+ (_tmp1.records = _state.sent(), _tmp1.scannerUuid = scannerUuid, _tmp1)
3136
+ ];
3137
+ case 7:
3138
+ err = _state.sent();
3139
+ lastErr = err;
3140
+ if (!isUuidScannerError(err)) throw err;
3141
+ // Reset this network's scanner instance + cached UUID, re-register.
3142
+ _this.scannersByNetwork.delete(network);
3143
+ return [
3144
+ 4,
3145
+ putWalletState(accountAddress, network, {
3146
+ scannerUuid: undefined,
3147
+ records: (_cached_records = cached === null || cached === void 0 ? void 0 : cached.records) !== null && _cached_records !== void 0 ? _cached_records : '[]',
3148
+ spentNonces: spentNonces,
3149
+ lastScannedBlock: (_cached_lastScannedBlock = cached === null || cached === void 0 ? void 0 : cached.lastScannedBlock) !== null && _cached_lastScannedBlock !== void 0 ? _cached_lastScannedBlock : 0
3150
+ })
3151
+ ];
3152
+ case 8:
3153
+ _state.sent();
3154
+ return [
3155
+ 4,
3156
+ new Promise(function(resolve) {
3157
+ return setTimeout(resolve, 100);
3158
+ })
3159
+ ];
3160
+ case 9:
3161
+ _state.sent();
3162
+ return [
3163
+ 4,
3164
+ registerWallet()
3165
+ ];
3166
+ case 10:
3167
+ scannerUuid = _state.sent();
3168
+ return [
3169
+ 3,
3170
+ 11
3171
+ ];
3172
+ case 11:
3173
+ attempt += 1;
3174
+ return [
3175
+ 3,
3176
+ 4
3177
+ ];
3178
+ case 12:
3179
+ throw new Error("Aleo RecordScanner kept rejecting the wallet UUID after re-registering. Try refreshing the page; underlying error: ".concat(_instanceof(lastErr, Error) ? lastErr.message : String(lastErr)));
3180
+ }
3181
+ });
3182
+ })();
3183
+ }
3184
+ },
3185
+ {
3186
+ key: "registerScannerWallet",
3187
+ value: /**
3188
+ * Wraps the encrypted view key and registers it with the scanner.
3189
+ * `registerEncrypted` (not `register`) ensures the view key crosses the
3190
+ * wire encrypted; same pattern Provable's `example-autojoin` uses.
3191
+ */ function registerScannerWallet(param) {
3192
+ var accountAddress = param.accountAddress, cached = param.cached, network = param.network, sdk = param.sdk, spentNonces = param.spentNonces, viewKey = param.viewKey;
3193
+ var _this = this;
3194
+ return _async_to_generator(function() {
3195
+ var scanner, regResult, _regResult_error, _regResult_status, status, _regResult_error_message, newUuid, _cached_records, _cached_lastScannedBlock;
3196
+ return _ts_generator(this, function(_state) {
3197
+ switch(_state.label){
3198
+ case 0:
3199
+ return [
3200
+ 4,
3201
+ _this.getRecordScanner(network)
3202
+ ];
3203
+ case 1:
3204
+ scanner = _state.sent();
3205
+ return [
3206
+ 4,
3207
+ scanner.registerEncrypted(sdk.ViewKey.from_string(viewKey), 0)
3208
+ ];
3209
+ case 2:
3210
+ regResult = _state.sent();
3211
+ if (!(regResult === null || regResult === void 0 ? void 0 : regResult.ok)) {
3212
+ status = (_regResult_status = regResult === null || regResult === void 0 ? void 0 : regResult.status) !== null && _regResult_status !== void 0 ? _regResult_status : 'unknown';
3213
+ throw new Error((_regResult_error_message = regResult === null || regResult === void 0 ? void 0 : (_regResult_error = regResult.error) === null || _regResult_error === void 0 ? void 0 : _regResult_error.message) !== null && _regResult_error_message !== void 0 ? _regResult_error_message : "register failed (".concat(status, ")"));
3214
+ }
3215
+ newUuid = regResult.data.uuid;
3216
+ return [
3217
+ 4,
3218
+ putWalletState(accountAddress, network, {
3219
+ scannerUuid: newUuid,
3220
+ records: (_cached_records = cached === null || cached === void 0 ? void 0 : cached.records) !== null && _cached_records !== void 0 ? _cached_records : '[]',
3221
+ spentNonces: spentNonces,
3222
+ lastScannedBlock: (_cached_lastScannedBlock = cached === null || cached === void 0 ? void 0 : cached.lastScannedBlock) !== null && _cached_lastScannedBlock !== void 0 ? _cached_lastScannedBlock : 0
3223
+ })
3224
+ ];
3225
+ case 3:
3226
+ _state.sent();
3227
+ return [
3228
+ 2,
3229
+ newUuid
3230
+ ];
3231
+ }
3232
+ });
3233
+ })();
3234
+ }
3235
+ },
3236
+ {
3237
+ key: "enrichOwnedRecord",
3238
+ value: /**
3239
+ * Decrypt the record's ciphertext locally (when missing) and surface
3240
+ * `microcredits` / `amount` as decimal strings so the DApp side can
3241
+ * display balances without needing the Provable WASM in its own bundle.
3242
+ * Mutates the record in place — same contract the original loop had.
3243
+ */ function enrichOwnedRecord(record, sdk, viewKeyObj) {
3244
+ if (!record.record_plaintext && record.record_ciphertext) {
3245
+ try {
3246
+ var ciphertext = sdk.RecordCiphertext.fromString(record.record_ciphertext);
3247
+ record.record_plaintext = ciphertext.decrypt(viewKeyObj).toString();
3248
+ } catch (e) {
3249
+ // Wrong view key or malformed ciphertext — record stays without
3250
+ // plaintext (renders as "#N" in the UI).
3251
+ }
3252
+ }
3253
+ var isCreditsRecord = record.program_name === 'credits.aleo' && record.record_name === 'credits';
3254
+ if (isCreditsRecord && record.record_plaintext && !record.microcredits) {
3255
+ try {
3256
+ var plaintext = sdk.RecordPlaintext.fromString(record.record_plaintext);
3257
+ record.microcredits = plaintext.microcredits().toString();
3258
+ } catch (e) {
3259
+ /* ignore — malformed plaintext */ }
3260
+ return;
3261
+ }
3262
+ // Non-credits Token records (stablecoins / ARC-21) carry their balance
3263
+ // in an `amount` field of type `u128.private`. `getMember('amount')`
3264
+ // returns e.g. "100u128.private" — strip the type suffix.
3265
+ if (!isCreditsRecord && record.record_plaintext && !record.amount) {
3266
+ try {
3267
+ var plaintext1 = sdk.RecordPlaintext.fromString(record.record_plaintext);
3268
+ var amountLiteral = plaintext1.getMember('amount').toString();
3269
+ var numericMatch = /^(\d+)/.exec(amountLiteral);
3270
+ if (numericMatch) {
3271
+ record.amount = numericMatch[1];
3272
+ }
3273
+ } catch (e) {
3274
+ /* not a Token record with an amount field — skip */ }
3275
+ }
3276
+ }
3277
+ },
3278
+ {
3279
+ key: "filterUnspentRecords",
3280
+ value: /**
3281
+ * Local spent-nonce filter — protects against the race where we've
3282
+ * broadcast a record-spending transaction but the scanner hasn't indexed
3283
+ * the spend yet.
3284
+ */ function filterUnspentRecords(records, sdk, spentNonces) {
3285
+ var nonceOf = function(r) {
3286
+ try {
3287
+ if (r.record_plaintext) {
3288
+ return sdk.RecordPlaintext.fromString(r.record_plaintext).nonce();
3289
+ }
3290
+ } catch (e) {
3291
+ /* ignore */ }
3292
+ return undefined;
3293
+ };
3294
+ return records.filter(function(r) {
3295
+ var n = nonceOf(r);
3296
+ return !n || !spentNonces.includes(n);
3297
+ });
3298
+ }
3299
+ }
3300
+ ]);
3301
+ return DynamicAleoWalletClient;
3302
+ }(DynamicWalletClient);
3303
+ /**
3304
+ * `findOwnedRecordsInner` retries on a UUID-stale signal — match the SDK's
3305
+ * own `UUIDError` message and the redcoast 422 forwarding (controller wraps
3306
+ * Provable's 422 with a "UUID invalid" body); plus any HTTP 422 on this
3307
+ * endpoint always indicates a stale/unknown UUID per Provable's contract.
3308
+ */ var isUuidScannerError = function(err) {
3309
+ var _err_response;
3310
+ var msg = _instanceof(err, Error) ? err.message : String(err);
3311
+ var _err_response_status;
3312
+ var status = (_err_response_status = err === null || err === void 0 ? void 0 : (_err_response = err.response) === null || _err_response === void 0 ? void 0 : _err_response.status) !== null && _err_response_status !== void 0 ? _err_response_status : err === null || err === void 0 ? void 0 : err.status;
3313
+ return /UUID/i.test(msg) || status === 422;
3314
+ };
3315
+
3316
+ export { ALEO_NETWORKS, DynamicAleoWalletClient };