@naculus/connect-appkit-core 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -141,6 +141,32 @@ function writeDecimals(cache, token, value) {
141
141
  cache.value = value;
142
142
  }
143
143
 
144
+ // src/erc20-calldata.ts
145
+ import { isChecksumAddress } from "@naculus/connect-core";
146
+ var UINT256_MAX = (1n << 256n) - 1n;
147
+ var EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
148
+ function addressWord(address) {
149
+ if (typeof address !== "string" || !EVM_ADDRESS.test(address) || address !== address.toLowerCase() && !isChecksumAddress(address)) {
150
+ throw new TypeError("Invalid EVM address checksum");
151
+ }
152
+ return address.slice(2).toLowerCase().padStart(64, "0");
153
+ }
154
+ function uint256Word(value) {
155
+ if (typeof value !== "bigint" || value < 0n || value > UINT256_MAX) {
156
+ throw new RangeError("Amount must be a uint256 bigint");
157
+ }
158
+ return value.toString(16).padStart(64, "0");
159
+ }
160
+ function encodeErc20Transfer(to, amount) {
161
+ return `0xa9059cbb${addressWord(to)}${uint256Word(amount)}`;
162
+ }
163
+ function encodeErc20Approve(spender, amount) {
164
+ return `0x095ea7b3${addressWord(spender)}${uint256Word(amount)}`;
165
+ }
166
+ function encodeErc20TransferFrom(from, to, amount) {
167
+ return `0x23b872dd${addressWord(from)}${addressWord(to)}${uint256Word(amount)}`;
168
+ }
169
+
144
170
  // src/provider-errors.ts
145
171
  import { WalletError as WalletError2 } from "@naculus/connect-core";
146
172
  var USER_REJECTED = 4001;
@@ -214,6 +240,173 @@ function resolveRevertReason(data, fallbackMessage) {
214
240
  return decodeRevertReason(data) ?? (fallbackMessage.includes("revert") ? fallbackMessage : "Transaction reverted");
215
241
  }
216
242
 
243
+ // src/simulation-endpoint.ts
244
+ import { WalletError as WalletError3 } from "@naculus/connect-core";
245
+ function resolveSimulationEndpoint(requestedChainId, fallbackChainId, requestedRpcUrl, fallbackRpcUrl) {
246
+ const chainId = requestedChainId ?? fallbackChainId;
247
+ if (chainId === void 0) {
248
+ throw new WalletError3(
249
+ "invalid_chain",
250
+ "No chain to simulate on. Connect a wallet or pass a chainId."
251
+ );
252
+ }
253
+ if (requestedChainId !== void 0 && fallbackChainId !== void 0 && requestedChainId !== fallbackChainId && requestedRpcUrl === void 0) {
254
+ throw new WalletError3(
255
+ "invalid_chain",
256
+ "Simulation chain override requires an RPC URL for that chain."
257
+ );
258
+ }
259
+ return { chainId, rpcUrl: requestedRpcUrl ?? fallbackRpcUrl };
260
+ }
261
+ function resolveContextSimulationEndpoint(requestedChainId, currentChain) {
262
+ const contextChainId = currentChain ? chainNumber(currentChain) ?? void 0 : void 0;
263
+ if (requestedChainId !== void 0 && currentChain && requestedChainId !== contextChainId) {
264
+ throw new WalletError3(
265
+ "invalid_chain",
266
+ "Simulation chain does not match the connected chain endpoint."
267
+ );
268
+ }
269
+ return resolveSimulationEndpoint(
270
+ requestedChainId,
271
+ contextChainId,
272
+ void 0,
273
+ currentChain?.rpcUrl
274
+ );
275
+ }
276
+
277
+ // src/transaction-simulation.ts
278
+ import { WalletError as WalletError4 } from "@naculus/connect-core";
279
+ var coverage = {
280
+ balanceChanges: false,
281
+ approvalChanges: false,
282
+ risk: false
283
+ };
284
+ function baseResult(status, summary, changesDetected, warnings = []) {
285
+ return {
286
+ status,
287
+ coverage,
288
+ balanceChanges: [],
289
+ approvalChanges: [],
290
+ riskAssessment: { level: "unknown", score: 0, warnings },
291
+ provider: "eth_call",
292
+ summary,
293
+ changesDetected
294
+ };
295
+ }
296
+ async function simulateTransactionPreview(tx, context) {
297
+ if (!tx)
298
+ return baseResult("unavailable", "No transaction to simulate", false);
299
+ const { chainId, rpcUrl } = resolveContextSimulationEndpoint(
300
+ context.chainId,
301
+ context.currentChain
302
+ );
303
+ const from = context.evmAccount?.includes(":") ? context.evmAccount.split(":").pop() : context.evmAccount;
304
+ if (context.publicClient) {
305
+ if (context.publicClient.chain?.id !== chainId) {
306
+ throw new WalletError4(
307
+ "invalid_chain",
308
+ "Simulation client chain does not match the requested chain."
309
+ );
310
+ }
311
+ try {
312
+ await context.publicClient.call({
313
+ to: tx.to,
314
+ data: tx.data ?? "0x",
315
+ value: tx.value ? BigInt(tx.value) : 0n,
316
+ ...from ? { from } : {}
317
+ });
318
+ return {
319
+ ...baseResult(
320
+ "success",
321
+ "Transaction simulation succeeded (basic revert check only)",
322
+ true
323
+ ),
324
+ gasInfo: tx.gas ? { gasLimit: BigInt(tx.gas), estimatedFeeEth: "0" } : void 0
325
+ };
326
+ } catch (cause) {
327
+ const error = cause;
328
+ const reason = resolveRevertReason(
329
+ error?.data ?? error?.cause?.data,
330
+ error?.message ?? String(cause)
331
+ );
332
+ return {
333
+ ...baseResult(
334
+ "reverted",
335
+ reason ? `Transaction reverted: ${reason}` : "Transaction reverted",
336
+ false,
337
+ [
338
+ {
339
+ category: "simulation_failed",
340
+ severity: "high",
341
+ message: reason ? `Transaction would revert: ${reason}` : "Transaction would revert"
342
+ }
343
+ ]
344
+ ),
345
+ revertReason: reason
346
+ };
347
+ }
348
+ }
349
+ if (!rpcUrl) {
350
+ return baseResult(
351
+ "unavailable",
352
+ "Simulation unavailable: no RPC URL",
353
+ false,
354
+ [
355
+ {
356
+ category: "simulation_failed",
357
+ severity: "low",
358
+ message: "No RPC URL or public client available for simulation"
359
+ }
360
+ ]
361
+ );
362
+ }
363
+ try {
364
+ const response = await (context.fetcher ?? fetch)(rpcUrl, {
365
+ method: "POST",
366
+ headers: { "Content-Type": "application/json" },
367
+ body: JSON.stringify({
368
+ jsonrpc: "2.0",
369
+ id: Date.now(),
370
+ method: "eth_call",
371
+ params: [
372
+ {
373
+ to: tx.to,
374
+ from,
375
+ data: tx.data ?? "0x",
376
+ value: tx.value ?? "0x0"
377
+ },
378
+ "latest"
379
+ ]
380
+ })
381
+ });
382
+ const json = await response.json();
383
+ if (json.error) {
384
+ return baseResult("reverted", "Transaction reverted", false, [
385
+ {
386
+ category: "simulation_failed",
387
+ severity: "high",
388
+ message: `Transaction would revert: ${json.error.message}`
389
+ }
390
+ ]);
391
+ }
392
+ return baseResult("success", "Transaction simulation succeeded", true);
393
+ } catch (cause) {
394
+ const error = cause;
395
+ return baseResult(
396
+ "unavailable",
397
+ "Simulation unavailable due to network error",
398
+ false,
399
+ [
400
+ {
401
+ category: "simulation_failed",
402
+ severity: "medium",
403
+ message: `Network error: ${error?.message ?? "Unknown"}`
404
+ }
405
+ ]
406
+ );
407
+ }
408
+ }
409
+
217
410
  // src/name-resolver.ts
218
411
  import { NameResolver } from "@naculus/connect-core";
219
412
  var sharedResolver = null;
@@ -226,6 +419,665 @@ function __resetResolverForTests() {
226
419
  sharedResolver = null;
227
420
  }
228
421
 
422
+ // src/notification.ts
423
+ import {
424
+ createStorageAdapter
425
+ } from "@naculus/connect-core";
426
+ var NOTIFICATION_SETTINGS_KEY = "naculus_notif_react_settings";
427
+ var DEFAULT_NOTIFICATION_SETTINGS = {
428
+ telegram: false,
429
+ webpush: false,
430
+ inapp: true,
431
+ frequency: "final-only",
432
+ mutedChains: [],
433
+ mutedTypes: []
434
+ };
435
+ function createNotificationSettingsStorage() {
436
+ const storage = createStorageAdapter("local", "naculus_notif_");
437
+ return {
438
+ getItem: async (key) => {
439
+ try {
440
+ return await storage.get(key);
441
+ } catch (cause) {
442
+ console.warn(
443
+ "notification settings: failed to read from storage:",
444
+ cause
445
+ );
446
+ return null;
447
+ }
448
+ },
449
+ setItem: async (key, value) => {
450
+ try {
451
+ await storage.set(key, value);
452
+ } catch (cause) {
453
+ console.warn(
454
+ "notification settings: failed to write to storage:",
455
+ cause
456
+ );
457
+ }
458
+ },
459
+ removeItem: async (key) => {
460
+ try {
461
+ await storage.remove(key);
462
+ } catch (cause) {
463
+ console.warn(
464
+ "notification settings: failed to remove from storage:",
465
+ cause
466
+ );
467
+ }
468
+ }
469
+ };
470
+ }
471
+ async function loadNotificationSettings(storage) {
472
+ return storage.getItem(NOTIFICATION_SETTINGS_KEY);
473
+ }
474
+ function saveNotificationSettings(storage, settings) {
475
+ storage.setItem(NOTIFICATION_SETTINGS_KEY, settings).catch(() => {
476
+ });
477
+ }
478
+ function updateNotificationSettings(current, update) {
479
+ return { ...current, ...update };
480
+ }
481
+ function channelsUpdate(channels) {
482
+ const update = {};
483
+ if (channels.includes("telegram")) update.telegram = true;
484
+ if (channels.includes("webpush")) update.webpush = true;
485
+ if (channels.includes("inapp")) update.inapp = true;
486
+ return update;
487
+ }
488
+ function mutedChainSettings(settings, chainId, muted) {
489
+ return {
490
+ mutedChains: muted ? [.../* @__PURE__ */ new Set([...settings.mutedChains, chainId])] : settings.mutedChains.filter((id) => id !== chainId)
491
+ };
492
+ }
493
+ function createNotification(item) {
494
+ return {
495
+ ...item,
496
+ id: `notif_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
497
+ timestamp: Date.now()
498
+ };
499
+ }
500
+ function sendItem(channel, item) {
501
+ return channel.send({
502
+ id: item.id,
503
+ userId: "",
504
+ txHash: item.txHash,
505
+ chainId: "",
506
+ chainName: item.chainName,
507
+ status: item.status,
508
+ title: item.title,
509
+ body: item.body,
510
+ valueFormatted: item.valueFormatted,
511
+ explorerUrl: item.explorerUrl,
512
+ timestamp: item.timestamp
513
+ });
514
+ }
515
+ function addInAppNotification(channel, item) {
516
+ void sendItem(channel, createNotification(item));
517
+ }
518
+ async function clearOneInAppNotification(channel, id) {
519
+ const remaining = channel.getHistory().filter((item) => item.id !== id);
520
+ channel.clear();
521
+ await Promise.all(remaining.map((item) => sendItem(channel, item)));
522
+ return channel.getHistory();
523
+ }
524
+
525
+ // src/destination.ts
526
+ import { isEvmAddress, isZeroAddress } from "@naculus/connect-core";
527
+ var DEAD_ADDRESSES = /* @__PURE__ */ new Set([
528
+ "0x0000000000000000000000000000000000000001",
529
+ "0x000000000000000000000000000000000000dead"
530
+ ]);
531
+ function isBurnDestination(address) {
532
+ const lower = address.toLowerCase();
533
+ return DEAD_ADDRESSES.has(lower) || lower.includes("dead");
534
+ }
535
+ function validateDestination(address) {
536
+ if (!address) return { isValid: false, level: "blocked", issue: "empty" };
537
+ if (!isEvmAddress(address)) {
538
+ return { isValid: false, level: "blocked", issue: "invalid_format" };
539
+ }
540
+ if (isZeroAddress(address)) {
541
+ return { isValid: false, level: "blocked", issue: "zero_address" };
542
+ }
543
+ if (isBurnDestination(address)) {
544
+ return { isValid: false, level: "blocked", issue: "burn_address" };
545
+ }
546
+ return { isValid: true, level: "ok", issue: null };
547
+ }
548
+ function bareEvmAddress(account) {
549
+ if (!account) return null;
550
+ const value = account.includes(":") ? account.split(":").pop() : account;
551
+ return value && isEvmAddress(value) ? value : null;
552
+ }
553
+
554
+ // src/routing.ts
555
+ import { isValidAddress } from "@naculus/connect-core";
556
+ function isPositiveIntegerAmount(amount) {
557
+ return /^(?:0|[1-9][0-9]*)$/.test(amount) && BigInt(amount) > 0n;
558
+ }
559
+ function isQuotableInput(input) {
560
+ return Boolean(
561
+ input.fromChain && input.toChain && input.fromToken && isPositiveIntegerAmount(input.amount)
562
+ );
563
+ }
564
+ function compareCostsKey(input) {
565
+ const options = input.options;
566
+ const optionsKey = options ? Object.keys(options).sort().map((key) => {
567
+ const value = options[key];
568
+ return `${key}=${typeof value === "object" && value !== null ? "[object]" : String(value)}`;
569
+ }).join("&") : "";
570
+ return `${input.operation}|${(input.chains ?? []).join(",")}|${optionsKey}`;
571
+ }
572
+ function validateRouteRecipient(quote, recipient) {
573
+ if (typeof recipient !== "string" || recipient.trim() === "") {
574
+ return {
575
+ code: "invalid_recipient",
576
+ message: "A recipient address is required"
577
+ };
578
+ }
579
+ const namespace = quote?.toChain?.split(":")[0];
580
+ if (namespace && !isValidAddress(recipient, namespace)) {
581
+ return {
582
+ code: "invalid_recipient",
583
+ message: `"${recipient}" is not a valid ${namespace} address for the destination chain ${quote?.toChain}`
584
+ };
585
+ }
586
+ return null;
587
+ }
588
+ function toExecuteRouteError(cause) {
589
+ const error = cause;
590
+ return {
591
+ code: error?.code ?? "execution_failed",
592
+ message: error?.message ?? String(cause),
593
+ details: error?.details
594
+ };
595
+ }
596
+
597
+ // src/session-key-manager.ts
598
+ import {
599
+ DEFAULT_SESSION_KEY_CONFIG,
600
+ LocalStorageAdapter,
601
+ MemoryStorageAdapter,
602
+ SessionKeyManager,
603
+ WalletError as WalletError5
604
+ } from "@naculus/connect-core";
605
+ var sharedManager = null;
606
+ var sharedFingerprint = null;
607
+ function sessionKeyConfigFingerprint(config) {
608
+ if (!config) return "";
609
+ return JSON.stringify({
610
+ defaultMaxTotalValue: config.defaultMaxTotalValue?.toString(),
611
+ defaultMaxTxCount: config.defaultMaxTxCount,
612
+ defaultExpiryMs: config.defaultExpiryMs,
613
+ requireAllowedContracts: config.requireAllowedContracts,
614
+ forbiddenMethods: config.forbiddenMethods,
615
+ pbkdf2Iterations: config.pbkdf2Iterations,
616
+ unsafeAllowWeakKdf: config.unsafeAllowWeakKdf,
617
+ storagePrefix: config.storagePrefix,
618
+ encryptionKey: config.encryptionKey,
619
+ encryptionSalt: config.encryptionSalt
620
+ });
621
+ }
622
+ function getSharedSessionKeyManager(config) {
623
+ const fingerprint = sessionKeyConfigFingerprint(config);
624
+ if (!sharedManager) {
625
+ const storagePrefix = config?.storagePrefix ?? DEFAULT_SESSION_KEY_CONFIG.storagePrefix;
626
+ sharedManager = new SessionKeyManager(
627
+ config,
628
+ typeof window !== "undefined" ? new LocalStorageAdapter(`${storagePrefix}:`) : new MemoryStorageAdapter()
629
+ );
630
+ sharedFingerprint = fingerprint;
631
+ return sharedManager;
632
+ }
633
+ if (fingerprint !== "" && fingerprint !== sharedFingerprint) {
634
+ throw new WalletError5(
635
+ "invalid_input",
636
+ "useSessionKeys is backed by a process-wide SessionKeyManager, and a different spending configuration was supplied after it was created. The second configuration would be ignored, so the caller would be operating under limits it did not set. Use one configuration per application, or construct a SessionKeyManager directly."
637
+ );
638
+ }
639
+ return sharedManager;
640
+ }
641
+ function resetSharedSessionKeyManager() {
642
+ sharedManager = null;
643
+ sharedFingerprint = null;
644
+ }
645
+
646
+ // src/user-op-receipt.ts
647
+ var InvalidUserOperationReceiptError = class extends Error {
648
+ constructor(message) {
649
+ super(message);
650
+ this.name = "InvalidUserOperationReceiptError";
651
+ }
652
+ };
653
+ function isRecord(value) {
654
+ return typeof value === "object" && value !== null && !Array.isArray(value);
655
+ }
656
+ function isAddress(value) {
657
+ return typeof value === "string" && /^0x[0-9a-fA-F]{40}$/.test(value);
658
+ }
659
+ function isHash(value) {
660
+ return typeof value === "string" && /^0x[0-9a-fA-F]{64}$/.test(value);
661
+ }
662
+ function isHexData(value) {
663
+ return typeof value === "string" && /^0x(?:[0-9a-fA-F]{2})*$/.test(value);
664
+ }
665
+ function parseQuantity(value, field) {
666
+ if (typeof value !== "string" || !/^(?:0x(?:0|[1-9a-fA-F][0-9a-fA-F]*)|(?:0|[1-9][0-9]*))$/.test(value)) {
667
+ throw new InvalidUserOperationReceiptError(
668
+ `Bundler returned an invalid ${field}.`
669
+ );
670
+ }
671
+ return BigInt(value);
672
+ }
673
+ function parseUserOperationReceipt(value, expectedHash) {
674
+ if (!isRecord(value)) {
675
+ throw new InvalidUserOperationReceiptError(
676
+ "Bundler returned an invalid UserOperation receipt."
677
+ );
678
+ }
679
+ if (!isHash(value.userOpHash) || value.userOpHash.toLowerCase() !== expectedHash.toLowerCase()) {
680
+ throw new InvalidUserOperationReceiptError(
681
+ "Bundler receipt does not match the requested UserOperation hash."
682
+ );
683
+ }
684
+ if (!isAddress(value.entryPoint) || !isAddress(value.sender)) {
685
+ throw new InvalidUserOperationReceiptError(
686
+ "Bundler receipt contains an invalid account address."
687
+ );
688
+ }
689
+ if (value.paymaster !== void 0 && value.paymaster !== null && !isAddress(value.paymaster)) {
690
+ throw new InvalidUserOperationReceiptError(
691
+ "Bundler receipt contains an invalid paymaster address."
692
+ );
693
+ }
694
+ if (typeof value.success !== "boolean" || !isHash(value.transactionHash)) {
695
+ throw new InvalidUserOperationReceiptError(
696
+ "Bundler receipt contains an invalid execution result."
697
+ );
698
+ }
699
+ if (!Array.isArray(value.logs)) {
700
+ throw new InvalidUserOperationReceiptError(
701
+ "Bundler receipt contains invalid logs."
702
+ );
703
+ }
704
+ const logs = value.logs.map((candidate) => {
705
+ if (!isRecord(candidate) || !isAddress(candidate.address) || !Array.isArray(candidate.topics) || !candidate.topics.every(isHash) || !isHexData(candidate.data)) {
706
+ throw new InvalidUserOperationReceiptError(
707
+ "Bundler receipt contains an invalid log entry."
708
+ );
709
+ }
710
+ return {
711
+ address: candidate.address,
712
+ topics: candidate.topics,
713
+ data: candidate.data
714
+ };
715
+ });
716
+ return {
717
+ userOpHash: value.userOpHash,
718
+ entryPoint: value.entryPoint,
719
+ sender: value.sender,
720
+ nonce: parseQuantity(value.nonce, "nonce"),
721
+ ...value.paymaster === void 0 || value.paymaster === null ? {} : { paymaster: value.paymaster },
722
+ actualGasUsed: parseQuantity(value.actualGasUsed, "actualGasUsed"),
723
+ actualGasCost: parseQuantity(value.actualGasCost, "actualGasCost"),
724
+ success: value.success,
725
+ transactionHash: value.transactionHash,
726
+ logs
727
+ };
728
+ }
729
+ async function fetchUserOperationReceipt(bundlerUrl, hash, signal) {
730
+ const response = await fetch(bundlerUrl, {
731
+ method: "POST",
732
+ headers: { "Content-Type": "application/json" },
733
+ body: JSON.stringify({
734
+ jsonrpc: "2.0",
735
+ id: 1,
736
+ method: "eth_getUserOperationReceipt",
737
+ params: [hash]
738
+ }),
739
+ signal
740
+ });
741
+ if (!response.ok) {
742
+ throw new Error(
743
+ `Bundler returned HTTP ${response.status} while reading UserOperation status.`
744
+ );
745
+ }
746
+ const json = await response.json();
747
+ if (json.error) {
748
+ throw new Error(
749
+ typeof json.error.message === "string" ? json.error.message : "Bundler returned a JSON-RPC error."
750
+ );
751
+ }
752
+ if (json.result === void 0 || json.result === null) return null;
753
+ return parseUserOperationReceipt(json.result, hash);
754
+ }
755
+
756
+ // src/smart-account.ts
757
+ import {
758
+ AA_SUPPORTED_CHAINS,
759
+ DEFAULT_ENTRY_POINT,
760
+ WalletError as WalletError6
761
+ } from "@naculus/connect-core";
762
+ function resolveUserOpChain(optionsChainId, connectedChainId) {
763
+ const chainId = resolveEvmChainId(optionsChainId, connectedChainId);
764
+ if (!chainId) {
765
+ throw new WalletError6(
766
+ "invalid_chain",
767
+ optionsChainId || connectedChainId ? `Invalid EVM chain ID: ${optionsChainId ?? connectedChainId}` : "No EVM chain to send on. Connect a wallet or pass options.chainId."
768
+ );
769
+ }
770
+ if (connectedChainId && connectedChainId !== chainId) {
771
+ throw new WalletError6(
772
+ "chain_mismatch",
773
+ `Connected chain ${connectedChainId} does not match UserOperation chain ${chainId}.`
774
+ );
775
+ }
776
+ return chainId;
777
+ }
778
+ function buildSmartAccountConfig(owner, chainId, options = {}) {
779
+ return {
780
+ owner,
781
+ accountType: options.accountType ?? "simple",
782
+ entryPoint: options.entryPoint ?? AA_SUPPORTED_CHAINS[chainId]?.entryPoint ?? DEFAULT_ENTRY_POINT,
783
+ chainId,
784
+ salt: options.salt
785
+ };
786
+ }
787
+ function assertHexSignature(value) {
788
+ if (typeof value !== "string" || !/^0x(?:[0-9a-fA-F]{2})+$/.test(value)) {
789
+ throw new WalletError6(
790
+ "signature_rejected",
791
+ "Wallet returned an invalid UserOperation signature."
792
+ );
793
+ }
794
+ return value;
795
+ }
796
+
797
+ // src/delegation-policy.ts
798
+ import { WalletError as WalletError7 } from "@naculus/connect-core";
799
+ function sorted(values) {
800
+ return values ? [...values].map((value) => value.toLowerCase()).sort() : null;
801
+ }
802
+ function sameExecutionIntent(requested, prepared) {
803
+ const sameHex = (left, right, empty) => {
804
+ const l = left === void 0 ? empty : left.toLowerCase();
805
+ const r = right === void 0 ? empty : right.toLowerCase();
806
+ return l === r;
807
+ };
808
+ const sameQuantity = (left, right) => {
809
+ try {
810
+ return BigInt(left ?? "0") === BigInt(right ?? "0");
811
+ } catch {
812
+ return false;
813
+ }
814
+ };
815
+ return sameHex(requested.to, prepared.to) && sameHex(requested.data, prepared.data, "0x") && sameQuantity(requested.value, prepared.value) && requested.chainId === prepared.chainId;
816
+ }
817
+ function buildDelegationPolicyMessage(policy, origin) {
818
+ const tokenAllowances = policy.scope.tokenAllowances ? Object.entries(policy.scope.tokenAllowances).map(
819
+ ([token, value]) => [token.toLowerCase(), value.toString()]
820
+ ).sort(([left], [right]) => left.localeCompare(right)) : null;
821
+ const payload = {
822
+ version: 1,
823
+ origin,
824
+ signer: policy.signerAddress.toLowerCase(),
825
+ sessionId: policy.id,
826
+ sessionPublicKey: policy.publicKey.toLowerCase(),
827
+ expiresAt: new Date(policy.expiresAt).toISOString(),
828
+ mode: policy.scope.mode,
829
+ limits: {
830
+ maxTotalGas: policy.scope.maxTotalGas?.toString() ?? null,
831
+ maxGasPerTx: policy.scope.maxGasPerTx?.toString() ?? null,
832
+ maxTotalValue: policy.scope.maxTotalValue?.toString() ?? null,
833
+ maxValuePerTx: policy.scope.maxValuePerTx?.toString() ?? null,
834
+ maxTxCount: policy.scope.maxTxCount ?? null
835
+ },
836
+ allowedContracts: sorted(policy.scope.allowedContracts),
837
+ allowedMethods: sorted(policy.scope.allowedMethods),
838
+ allowedChainIds: policy.scope.allowedChainIds ? [...policy.scope.allowedChainIds].sort((left, right) => left - right) : null,
839
+ tokenAllowances
840
+ };
841
+ return `Naculus Session Policy v1
842
+ ${JSON.stringify(payload)}`;
843
+ }
844
+ function isVerifiablePolicy(policy) {
845
+ return policy.status === "active" && Boolean(policy.authorized) && policy.scope.mode === "offchain";
846
+ }
847
+ function createDelegationPolicyFlow(deps) {
848
+ const { manager, origin } = deps;
849
+ const verifyStoredPolicy = async (policy) => {
850
+ if (!isVerifiablePolicy(policy)) return false;
851
+ return manager.verifyOffchainAuthorization(
852
+ policy.id,
853
+ buildDelegationPolicyMessage(policy, origin),
854
+ deps.verifySignature
855
+ );
856
+ };
857
+ const createPolicy = async (scope) => {
858
+ const signer = deps.signer();
859
+ if (!signer) {
860
+ throw new WalletError7("wallet_unavailable", "No active EVM account");
861
+ }
862
+ if (scope.mode && scope.mode !== "offchain") {
863
+ throw new WalletError7(
864
+ "method_not_allowed",
865
+ "This flow creates signed off-chain policies only. EIP-7702 and AA-module policies require a configured on-chain execution adapter."
866
+ );
867
+ }
868
+ if (!deps.encryptionKeyConfigured) {
869
+ throw new WalletError7(
870
+ "method_not_allowed",
871
+ "Persistent delegation policies require a host-provided encryptionKey. The deterministic compatibility fallback is not a production key boundary."
872
+ );
873
+ }
874
+ if (!deps.storageAvailable()) {
875
+ throw new WalletError7(
876
+ "storage_unavailable",
877
+ "Persistent delegation policy storage is unavailable in this browser"
878
+ );
879
+ }
880
+ let draft = null;
881
+ try {
882
+ draft = await manager.createSessionKey(
883
+ { ...scope, mode: "offchain" },
884
+ signer
885
+ );
886
+ const message = buildDelegationPolicyMessage(draft, origin);
887
+ const signature = await deps.signMessage(message);
888
+ if (!/^0x[0-9a-fA-F]{130}$/.test(signature)) {
889
+ throw new WalletError7(
890
+ "invalid_input",
891
+ "Wallet did not return a valid 65-byte EVM policy signature"
892
+ );
893
+ }
894
+ const recovers = await deps.verifySignature({
895
+ message,
896
+ signature,
897
+ signerAddress: signer
898
+ });
899
+ if (!recovers) {
900
+ throw new WalletError7(
901
+ "invalid_input",
902
+ "Policy signature does not recover to the connected EVM account"
903
+ );
904
+ }
905
+ await manager.setAuthorization(draft.id, {
906
+ signerAddress: signer,
907
+ type: "offchain",
908
+ rawSignature: signature,
909
+ message
910
+ });
911
+ const authorized = (await manager.listSessions()).find(
912
+ (policy) => policy.id === draft?.id
913
+ );
914
+ if (!authorized?.authorized) {
915
+ throw new WalletError7(
916
+ "invalid_input",
917
+ "Policy authorization was not persisted"
918
+ );
919
+ }
920
+ if (!await verifyStoredPolicy(authorized)) {
921
+ throw new WalletError7(
922
+ "invalid_input",
923
+ "Persisted policy signature did not verify against its stored scope and origin"
924
+ );
925
+ }
926
+ await deps.refresh();
927
+ return authorized;
928
+ } catch (cause) {
929
+ if (draft) {
930
+ try {
931
+ await manager.revokeSession(draft.id);
932
+ } catch {
933
+ }
934
+ }
935
+ throw cause instanceof Error ? cause : new Error("Policy creation failed");
936
+ }
937
+ };
938
+ const revokePolicy = async (policyId) => {
939
+ await manager.revokeSession(policyId);
940
+ await deps.refresh();
941
+ };
942
+ const previewPolicyExecution = async (policyId, tx, callCount = 1, atomicity = "preferred") => {
943
+ const policy = (await manager.listSessions()).find((item) => item.id === policyId) ?? null;
944
+ const scope = await manager.checkSessionScope(policyId, tx);
945
+ const plan = deps.previewExecution(callCount, atomicity);
946
+ const signer = deps.signer();
947
+ const authorizationVerified = policy ? await verifyStoredPolicy(policy) : false;
948
+ const signerMatches = Boolean(
949
+ policy && signer && policy.signerAddress.toLowerCase() === signer.toLowerCase()
950
+ );
951
+ const adapter = deps.adapter;
952
+ let adapterCheck = null;
953
+ if (policy && adapter && authorizationVerified && signerMatches && scope.valid) {
954
+ try {
955
+ adapterCheck = await adapter.check({ policy, transaction: tx });
956
+ } catch (cause) {
957
+ adapterCheck = {
958
+ ready: false,
959
+ authorizationInstalled: false,
960
+ sponsored: false,
961
+ promptless: false,
962
+ reason: cause instanceof Error ? `Execution adapter check failed: ${cause.message}` : "Execution adapter check failed."
963
+ };
964
+ }
965
+ }
966
+ const delegation = deps.delegation();
967
+ const delegationMatches = Boolean(
968
+ adapter?.route !== "eip7702" || delegation.delegated === true && adapterCheck?.executorAddress && delegation.delegate?.toLowerCase() === adapterCheck.executorAddress.toLowerCase()
969
+ );
970
+ const policyReady = Boolean(
971
+ policy?.status === "active" && policy.authorized && authorizationVerified && policy.scope.mode === "offchain" && signerMatches && scope.valid
972
+ );
973
+ const adapterSponsorshipReady = Boolean(
974
+ deps.sponsorship !== "required" || adapterCheck?.sponsored
975
+ );
976
+ const broadcastReady = Boolean(
977
+ policyReady && callCount === 1 && adapterCheck?.ready && adapterCheck.authorizationInstalled && adapterCheck.promptless && adapterSponsorshipReady && delegationMatches
978
+ );
979
+ const ready = Boolean(policyReady && (plan.route || broadcastReady));
980
+ const reason = !policy ? "Policy not found." : policy.status !== "active" ? `Policy is ${policy.status}.` : !policy.authorized ? "The main wallet has not signed this policy." : !authorizationVerified ? "The persisted policy signature no longer matches its scope, signer, or origin." : !signerMatches ? "The connected account is not the policy signer." : !scope.valid ? scope.reason ?? "The transaction is outside the policy scope." : broadcastReady ? `The configured ${adapter?.route ?? "AA/7702"} adapter can submit this policy-authorized operation without another main-wallet prompt.${adapterCheck?.sponsored ? " Gas sponsorship is guaranteed." : ""} ${adapterCheck?.reason ?? "The on-chain execution adapter is ready."}` : !adapter ? `${plan.reason} The signed off-chain policy permits this request; an AA/7702 adapter is still required to broadcast without another wallet prompt.` : !adapterCheck?.ready || !adapterCheck.authorizationInstalled ? `${plan.reason} ${adapterCheck?.reason ?? "The execution adapter is not ready."}` : !adapterCheck.promptless ? `${plan.reason} The configured adapter would invoke the main wallet again, so promptless broadcast is not ready.` : !adapterSponsorshipReady ? `${plan.reason} Sponsored gas is required, but the configured adapter does not guarantee sponsorship.` : callCount !== 1 ? `${plan.reason} This policy adapter prepares one execution at a time and cannot claim a multi-call broadcast.` : !delegationMatches ? `${plan.reason} The configured EIP-7702 executor does not match the account's on-chain delegation.` : !plan.route ? plan.reason : `${plan.reason} ${adapterCheck.reason}`;
981
+ return {
982
+ policy,
983
+ scope,
984
+ execution: plan,
985
+ signerMatches,
986
+ authorizationVerified,
987
+ ready,
988
+ broadcastReady,
989
+ broadcastRoute: broadcastReady ? adapter?.route ?? null : null,
990
+ onchainAuthorizationVerified: Boolean(
991
+ adapterCheck?.authorizationInstalled && delegationMatches
992
+ ),
993
+ broadcastSponsored: broadcastReady ? adapterCheck?.sponsored ?? false : null,
994
+ broadcastPromptless: Boolean(broadcastReady && adapterCheck?.promptless),
995
+ reason
996
+ };
997
+ };
998
+ const signVerified = (policyId, digest, tx) => manager.signWithVerifiedOffchainAuthorization(
999
+ policyId,
1000
+ (authoritativePolicy) => buildDelegationPolicyMessage(authoritativePolicy, origin),
1001
+ deps.verifySignature,
1002
+ digest,
1003
+ tx
1004
+ );
1005
+ const signPolicyDigest = async (policyId, digest, tx) => {
1006
+ const preview = await previewPolicyExecution(policyId, tx, 1, "any");
1007
+ if (!preview.ready) {
1008
+ throw new WalletError7("method_not_allowed", preview.reason);
1009
+ }
1010
+ return signVerified(policyId, digest, tx);
1011
+ };
1012
+ const executePolicy = async (policyId, tx) => {
1013
+ const adapter = deps.adapter;
1014
+ if (!adapter) {
1015
+ throw new WalletError7(
1016
+ "method_not_allowed",
1017
+ "No session-policy-aware AA/7702 execution adapter is configured."
1018
+ );
1019
+ }
1020
+ const preview = await previewPolicyExecution(policyId, tx, 1, "any");
1021
+ if (!preview.broadcastReady || !preview.policy) {
1022
+ throw new WalletError7("method_not_allowed", preview.reason);
1023
+ }
1024
+ const prepared = await adapter.prepare({
1025
+ policy: preview.policy,
1026
+ transaction: tx
1027
+ });
1028
+ if (!/^0x[0-9a-fA-F]{64}$/.test(prepared.digest)) {
1029
+ throw new WalletError7(
1030
+ "invalid_input",
1031
+ "Execution adapter returned a digest that is not 32 bytes."
1032
+ );
1033
+ }
1034
+ if (!sameExecutionIntent(tx, prepared.transaction)) {
1035
+ throw new WalletError7(
1036
+ "invalid_input",
1037
+ "Execution adapter changed the requested target, value, data, or chain."
1038
+ );
1039
+ }
1040
+ const currentCheck = await adapter.check({
1041
+ policy: preview.policy,
1042
+ transaction: prepared.transaction
1043
+ });
1044
+ const delegation = deps.delegation();
1045
+ const currentDelegationMatches = adapter.route !== "eip7702" || delegation.delegated === true && currentCheck.executorAddress !== void 0 && delegation.delegate?.toLowerCase() === currentCheck.executorAddress.toLowerCase();
1046
+ if (!currentCheck.ready || !currentCheck.authorizationInstalled || !currentCheck.promptless || deps.sponsorship === "required" && !currentCheck.sponsored || !currentDelegationMatches) {
1047
+ throw new WalletError7(
1048
+ "method_not_allowed",
1049
+ currentCheck.reason || "The on-chain policy authorization is not ready."
1050
+ );
1051
+ }
1052
+ const signature = await signVerified(
1053
+ policyId,
1054
+ prepared.digest,
1055
+ prepared.transaction
1056
+ );
1057
+ const submission = await adapter.broadcast({
1058
+ policy: preview.policy,
1059
+ prepared,
1060
+ signature
1061
+ });
1062
+ if (submission.route !== adapter.route || submission.status !== "submitted" || !/^0x[0-9a-fA-F]{64}$/.test(submission.hash)) {
1063
+ throw new WalletError7(
1064
+ "invalid_input",
1065
+ "Execution adapter returned an invalid submission result."
1066
+ );
1067
+ }
1068
+ await deps.refresh();
1069
+ return submission;
1070
+ };
1071
+ return {
1072
+ verifyStoredPolicy,
1073
+ createPolicy,
1074
+ revokePolicy,
1075
+ previewPolicyExecution,
1076
+ signPolicyDigest,
1077
+ executePolicy
1078
+ };
1079
+ }
1080
+
229
1081
  // src/web3-store.ts
230
1082
  import { logger } from "@naculus/connect-core";
231
1083
  function withTimeout(promise, ms, label = "Operation") {
@@ -314,32 +1166,115 @@ function web3Reducer(state, action) {
314
1166
  return state;
315
1167
  }
316
1168
  }
1169
+
1170
+ // src/siwx-policy.ts
1171
+ function defaultSiwxDomain(location) {
1172
+ return location?.host ?? "localhost";
1173
+ }
1174
+ function defaultSiwxUri(location) {
1175
+ return location?.origin ?? "http://localhost";
1176
+ }
1177
+ function isSiwxExpired(result, now) {
1178
+ const value = result.message.expirationTime;
1179
+ if (!value) return false;
1180
+ const timestamp = new Date(value).getTime();
1181
+ return !Number.isFinite(timestamp) || timestamp <= now.getTime();
1182
+ }
1183
+ function isSiwxNotBeforeValid(result, now) {
1184
+ const value = result.message.notBefore;
1185
+ if (!value) return true;
1186
+ const timestamp = new Date(value).getTime();
1187
+ return Number.isFinite(timestamp) && timestamp <= now.getTime();
1188
+ }
1189
+ function randomSuffix() {
1190
+ const bytes = new Uint8Array(8);
1191
+ crypto.getRandomValues(bytes);
1192
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(
1193
+ ""
1194
+ );
1195
+ }
1196
+ function siwxResultToSession(result, now = /* @__PURE__ */ new Date()) {
1197
+ return {
1198
+ id: `siwx_${now.getTime().toString(36)}_${randomSuffix()}`,
1199
+ chainId: result.message.chainId,
1200
+ address: result.message.address,
1201
+ domain: result.message.domain,
1202
+ message: result.message,
1203
+ signature: result.signature,
1204
+ issuedAt: result.message.issuedAt ?? now.toISOString(),
1205
+ expiresAt: result.message.expirationTime ?? null,
1206
+ refreshedAt: null
1207
+ };
1208
+ }
317
1209
  export {
1210
+ DEFAULT_NOTIFICATION_SETTINGS,
1211
+ InvalidUserOperationReceiptError,
1212
+ NOTIFICATION_SETTINGS_KEY,
318
1213
  __resetResolverForTests,
1214
+ addInAppNotification,
1215
+ assertHexSignature,
319
1216
  atomicSupportFor,
1217
+ bareEvmAddress,
1218
+ buildDelegationPolicyMessage,
1219
+ buildSmartAccountConfig,
320
1220
  chainNamespace,
321
1221
  chainNumber,
322
1222
  chainsForNamespace,
1223
+ channelsUpdate,
1224
+ clearOneInAppNotification,
1225
+ compareCostsKey,
323
1226
  createDecimalsCache,
1227
+ createDelegationPolicyFlow,
1228
+ createNotification,
1229
+ createNotificationSettingsStorage,
324
1230
  decodeRevertReason,
1231
+ defaultSiwxDomain,
1232
+ defaultSiwxUri,
325
1233
  describeChain,
326
1234
  eip155ChainIdToNumber,
1235
+ encodeErc20Approve,
1236
+ encodeErc20Transfer,
1237
+ encodeErc20TransferFrom,
1238
+ fetchUserOperationReceipt,
327
1239
  getResolver,
1240
+ getSharedSessionKeyManager,
328
1241
  initialWeb3State,
1242
+ isBurnDestination,
329
1243
  isEvmChainId,
1244
+ isPositiveIntegerAmount,
1245
+ isQuotableInput,
1246
+ isSiwxExpired,
1247
+ isSiwxNotBeforeValid,
1248
+ isVerifiablePolicy,
1249
+ loadNotificationSettings,
1250
+ mutedChainSettings,
330
1251
  normalizeCapabilities,
331
1252
  normalizeEip155ChainId,
1253
+ parseUserOperationReceipt,
332
1254
  readDecimals,
333
1255
  readSolanaRoles,
1256
+ resetSharedSessionKeyManager,
334
1257
  resolveChain,
1258
+ resolveContextSimulationEndpoint,
335
1259
  resolveEvmChainId,
336
1260
  resolveRevertReason,
1261
+ resolveSimulationEndpoint,
1262
+ resolveUserOpChain,
1263
+ sameExecutionIntent,
1264
+ saveNotificationSettings,
337
1265
  selectChainCapabilities,
1266
+ sessionKeyConfigFingerprint,
1267
+ simulateTransactionPreview,
1268
+ siwxResultToSession,
338
1269
  toChainSwitchError,
339
1270
  toEip155Accounts,
1271
+ toExecuteRouteError,
340
1272
  toViemChain,
341
1273
  tokenChainMismatch,
342
1274
  tokenKey,
1275
+ updateNotificationSettings,
1276
+ validateDestination,
1277
+ validateRouteRecipient,
343
1278
  web3Reducer,
344
1279
  withRetry,
345
1280
  withTimeout,