@lumiapassport/core 1.17.3 → 1.17.5

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.
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var viem = require('viem');
4
- require('viem/account-abstraction');
4
+ var accountAbstraction = require('viem/account-abstraction');
5
5
  var nanoid = require('nanoid');
6
6
 
7
7
  var __defProp = Object.defineProperty;
@@ -306,12 +306,171 @@ var init_constants = __esm({
306
306
  });
307
307
 
308
308
  // src/read/cache.ts
309
+ function generateCacheKey(params) {
310
+ const keyParts = {
311
+ c: params.chainId,
312
+ a: params.address.toLowerCase(),
313
+ f: params.functionName,
314
+ r: params.args,
315
+ b: serializeBlockTag(params.blockTag),
316
+ s: params.from?.toLowerCase()
317
+ };
318
+ return JSON.stringify(keyParts);
319
+ }
320
+ function serializeBlockTag(blockTag) {
321
+ if (typeof blockTag === "bigint") {
322
+ return `n:${blockTag.toString()}`;
323
+ }
324
+ return blockTag;
325
+ }
326
+ var DEFAULT_CACHE_CONFIG, LRUCache;
309
327
  var init_cache = __esm({
310
328
  "src/read/cache.ts"() {
329
+ DEFAULT_CACHE_CONFIG = {
330
+ maxSize: 1e3,
331
+ ttl: 12e3
332
+ // 12 seconds (~1 block)
333
+ };
334
+ LRUCache = class {
335
+ cache;
336
+ maxSize;
337
+ ttl;
338
+ hits = 0;
339
+ misses = 0;
340
+ constructor(config = {}) {
341
+ this.maxSize = config.maxSize ?? DEFAULT_CACHE_CONFIG.maxSize;
342
+ this.ttl = config.ttl ?? DEFAULT_CACHE_CONFIG.ttl;
343
+ this.cache = /* @__PURE__ */ new Map();
344
+ }
345
+ /**
346
+ * Get a value from cache
347
+ * Returns undefined if not found or expired
348
+ */
349
+ get(key) {
350
+ const entry = this.cache.get(key);
351
+ if (!entry) {
352
+ this.misses++;
353
+ return void 0;
354
+ }
355
+ if (Date.now() > entry.expiresAt) {
356
+ this.cache.delete(key);
357
+ this.misses++;
358
+ return void 0;
359
+ }
360
+ this.cache.delete(key);
361
+ this.cache.set(key, entry);
362
+ this.hits++;
363
+ return entry.value;
364
+ }
365
+ /**
366
+ * Set a value in cache with optional custom TTL
367
+ */
368
+ set(key, value, customTtl) {
369
+ if (this.cache.has(key)) {
370
+ this.cache.delete(key);
371
+ }
372
+ while (this.cache.size >= this.maxSize) {
373
+ const oldestKey = this.cache.keys().next().value;
374
+ if (oldestKey !== void 0) {
375
+ this.cache.delete(oldestKey);
376
+ }
377
+ }
378
+ const ttlToUse = customTtl ?? this.ttl;
379
+ this.cache.set(key, {
380
+ value,
381
+ expiresAt: Date.now() + ttlToUse
382
+ });
383
+ }
384
+ /**
385
+ * Check if key exists and is not expired
386
+ */
387
+ has(key) {
388
+ const entry = this.cache.get(key);
389
+ if (!entry) return false;
390
+ if (Date.now() > entry.expiresAt) {
391
+ this.cache.delete(key);
392
+ return false;
393
+ }
394
+ return true;
395
+ }
396
+ /**
397
+ * Delete a specific key
398
+ */
399
+ delete(key) {
400
+ return this.cache.delete(key);
401
+ }
402
+ /**
403
+ * Clear all entries
404
+ */
405
+ clear() {
406
+ this.cache.clear();
407
+ this.hits = 0;
408
+ this.misses = 0;
409
+ }
410
+ /**
411
+ * Get cache statistics
412
+ */
413
+ getStats() {
414
+ this.cleanExpired();
415
+ return {
416
+ size: this.cache.size,
417
+ maxSize: this.maxSize,
418
+ hits: this.hits,
419
+ misses: this.misses
420
+ };
421
+ }
422
+ /**
423
+ * Remove expired entries
424
+ */
425
+ cleanExpired() {
426
+ const now = Date.now();
427
+ for (const [key, entry] of this.cache.entries()) {
428
+ if (now > entry.expiresAt) {
429
+ this.cache.delete(key);
430
+ }
431
+ }
432
+ }
433
+ };
311
434
  }
312
435
  });
436
+ function createFallbackClient(chain, config) {
437
+ const {
438
+ urls,
439
+ retriesPerEndpoint = DEFAULT_CONFIG.retriesPerEndpoint,
440
+ timeout = DEFAULT_CONFIG.timeout
441
+ } = config;
442
+ if (urls.length === 0) {
443
+ throw new Error("At least one RPC URL is required");
444
+ }
445
+ if (urls.length === 1) {
446
+ return viem.createPublicClient({
447
+ chain,
448
+ transport: viem.http(urls[0], { timeout })
449
+ });
450
+ }
451
+ const transports = urls.map(
452
+ (url) => viem.http(url, {
453
+ timeout,
454
+ retryCount: retriesPerEndpoint,
455
+ retryDelay: 150
456
+ })
457
+ );
458
+ return viem.createPublicClient({
459
+ chain,
460
+ transport: viem.fallback(transports, {
461
+ rank: true,
462
+ // Automatically rank transports by latency
463
+ retryCount: 1
464
+ })
465
+ });
466
+ }
467
+ var DEFAULT_CONFIG;
313
468
  var init_rpc_fallback = __esm({
314
469
  "src/read/rpc-fallback.ts"() {
470
+ DEFAULT_CONFIG = {
471
+ retriesPerEndpoint: 1,
472
+ timeout: 1e4
473
+ };
315
474
  }
316
475
  });
317
476
  var ARBITRUM_SEPOLIA_CHAIN_ID, ARBITRUM_SEPOLIA_MULTICALL3_ADDRESS, ARBITRUM_SEPOLIA, arbitrumSepoliaChain;
@@ -529,10 +688,13 @@ var init_sepolia = __esm({
529
688
  function getChainConfig(chainId) {
530
689
  return SUPPORTED_CHAINS.get(chainId);
531
690
  }
691
+ function isChainSupported(chainId) {
692
+ return SUPPORTED_CHAINS.has(chainId);
693
+ }
532
694
  function getViemChain(chainId) {
533
695
  return VIEM_CHAINS.get(chainId);
534
696
  }
535
- var SUPPORTED_CHAINS, VIEM_CHAINS;
697
+ var DEFAULT_CHAIN_ID, SUPPORTED_CHAINS, VIEM_CHAINS, DEFAULT_CACHE_TTL, DEFAULT_CACHE_MAX_SIZE, DEFAULT_MULTICALL_BATCH_SIZE;
536
698
  var init_networks = __esm({
537
699
  "src/config/networks/index.ts"() {
538
700
  init_arbitrum_sepolia();
@@ -548,6 +710,7 @@ var init_networks = __esm({
548
710
  init_arbitrum_sepolia();
549
711
  init_base_sepolia();
550
712
  init_testnet();
713
+ DEFAULT_CHAIN_ID = LUMIA_TESTNET_CHAIN_ID;
551
714
  SUPPORTED_CHAINS = /* @__PURE__ */ new Map([
552
715
  [LUMIA_MAINNET_CHAIN_ID, LUMIA_MAINNET],
553
716
  [LUMIA_TESTNET_CHAIN_ID, LUMIA_TESTNET],
@@ -564,6 +727,9 @@ var init_networks = __esm({
564
727
  [ARBITRUM_SEPOLIA_CHAIN_ID, arbitrumSepoliaChain],
565
728
  [BASE_SEPOLIA_CHAIN_ID, baseSepoliaChain]
566
729
  ]);
730
+ DEFAULT_CACHE_TTL = 12e3;
731
+ DEFAULT_CACHE_MAX_SIZE = 1e3;
732
+ DEFAULT_MULTICALL_BATCH_SIZE = 100;
567
733
  }
568
734
  });
569
735
 
@@ -599,7 +765,7 @@ var init_errors = __esm({
599
765
  });
600
766
 
601
767
  // src/read/errors.ts
602
- var ReadLayerError, ChainNotSupportedError;
768
+ var ReadLayerError, ContractNotFoundError, ContractRevertError, RpcConnectionError, AllRpcsFailedError, RateLimitedError, BlockPrunedError, InvalidAbiError, ChainNotSupportedError, TransactionReceiptTimeoutError;
603
769
  var init_errors2 = __esm({
604
770
  "src/read/errors.ts"() {
605
771
  init_errors();
@@ -609,6 +775,80 @@ var init_errors2 = __esm({
609
775
  this.name = "ReadLayerError";
610
776
  }
611
777
  };
778
+ ContractNotFoundError = class extends ReadLayerError {
779
+ constructor(address, chainId) {
780
+ super(
781
+ `Contract not found at ${address} on chain ${chainId}`,
782
+ "CONTRACT_NOT_FOUND"
783
+ );
784
+ this.address = address;
785
+ this.chainId = chainId;
786
+ this.name = "ContractNotFoundError";
787
+ }
788
+ };
789
+ ContractRevertError = class extends ReadLayerError {
790
+ constructor(address, functionName, reason) {
791
+ super(
792
+ `Contract call to ${functionName} at ${address} reverted: ${reason}`,
793
+ "CONTRACT_REVERTED"
794
+ );
795
+ this.address = address;
796
+ this.functionName = functionName;
797
+ this.reason = reason;
798
+ this.name = "ContractRevertError";
799
+ }
800
+ };
801
+ RpcConnectionError = class extends ReadLayerError {
802
+ constructor(url, cause) {
803
+ super(`Failed to connect to RPC: ${url}`, "RPC_CONNECTION_FAILED");
804
+ this.url = url;
805
+ this.cause = cause;
806
+ this.name = "RpcConnectionError";
807
+ }
808
+ };
809
+ AllRpcsFailedError = class extends ReadLayerError {
810
+ constructor(urls, errors) {
811
+ super(
812
+ `All ${urls.length} RPC endpoint(s) failed`,
813
+ "ALL_RPCS_FAILED"
814
+ );
815
+ this.urls = urls;
816
+ this.errors = errors;
817
+ this.name = "AllRpcsFailedError";
818
+ }
819
+ };
820
+ RateLimitedError = class extends ReadLayerError {
821
+ constructor(url, retryAfter) {
822
+ super(
823
+ `Rate limited by RPC: ${url}${retryAfter ? `, retry after ${retryAfter}s` : ""}`,
824
+ "RATE_LIMITED"
825
+ );
826
+ this.url = url;
827
+ this.retryAfter = retryAfter;
828
+ this.name = "RateLimitedError";
829
+ }
830
+ };
831
+ BlockPrunedError = class extends ReadLayerError {
832
+ constructor(blockNumber) {
833
+ super(
834
+ `Block ${blockNumber} has been pruned and is not available`,
835
+ "BLOCK_PRUNED"
836
+ );
837
+ this.blockNumber = blockNumber;
838
+ this.name = "BlockPrunedError";
839
+ }
840
+ };
841
+ InvalidAbiError = class extends ReadLayerError {
842
+ constructor(functionName, address) {
843
+ super(
844
+ `Function '${functionName}' not found in ABI for contract at ${address}`,
845
+ "INVALID_ABI"
846
+ );
847
+ this.functionName = functionName;
848
+ this.address = address;
849
+ this.name = "InvalidAbiError";
850
+ }
851
+ };
612
852
  ChainNotSupportedError = class extends ReadLayerError {
613
853
  /** List of supported chain IDs */
614
854
  supportedChains;
@@ -622,16 +862,338 @@ var init_errors2 = __esm({
622
862
  this.supportedChains = supportedChains;
623
863
  }
624
864
  };
865
+ TransactionReceiptTimeoutError = class extends ReadLayerError {
866
+ constructor(hash, timeout) {
867
+ super(
868
+ `Transaction receipt not found within ${timeout}ms: ${hash}`,
869
+ "TRANSACTION_RECEIPT_TIMEOUT"
870
+ );
871
+ this.hash = hash;
872
+ this.timeout = timeout;
873
+ this.name = "TransactionReceiptTimeoutError";
874
+ }
875
+ };
625
876
  }
626
877
  });
878
+ function getPublicClient2(config) {
879
+ const {
880
+ chainId,
881
+ rpcUrls,
882
+ multicall3Address,
883
+ cacheTtl = DEFAULT_CACHE_TTL,
884
+ cacheMaxSize = DEFAULT_CACHE_MAX_SIZE,
885
+ disableCache = false
886
+ } = config;
887
+ const urls = resolveRpcUrls(chainId, rpcUrls);
888
+ const chainConfig = getChainConfig(chainId);
889
+ const chain = {
890
+ id: chainId,
891
+ name: chainConfig?.name ?? `Chain ${chainId}`,
892
+ nativeCurrency: { name: "ETH", symbol: "ETH", decimals: 18 },
893
+ rpcUrls: {
894
+ default: { http: urls }
895
+ }
896
+ };
897
+ let viemClient;
898
+ if (urls.length === 1) {
899
+ viemClient = viem.createPublicClient({
900
+ chain,
901
+ transport: viem.http(urls[0])
902
+ });
903
+ } else {
904
+ viemClient = createFallbackClient(chain, { urls });
905
+ }
906
+ const cache = disableCache ? null : new LRUCache({ maxSize: cacheMaxSize, ttl: cacheTtl });
907
+ const resolvedMulticall3 = multicall3Address ?? chainConfig?.multicall3 ?? MULTICALL3_ADDRESS2;
908
+ return new PublicReadClientImpl(chainId, viemClient, cache, resolvedMulticall3);
909
+ }
910
+ function resolveRpcUrls(chainId, rpcUrls) {
911
+ if (rpcUrls) {
912
+ return Array.isArray(rpcUrls) ? rpcUrls : [rpcUrls];
913
+ }
914
+ const chainConfig = getChainConfig(chainId);
915
+ if (chainConfig) {
916
+ return chainConfig.rpcUrls;
917
+ }
918
+ throw new ChainNotSupportedError(chainId);
919
+ }
920
+ function normalizeBlockTag(blockTag) {
921
+ if (typeof blockTag === "bigint") {
922
+ return blockTag;
923
+ }
924
+ return blockTag;
925
+ }
926
+ var PublicReadClientImpl;
627
927
  var init_public_client = __esm({
628
928
  "src/read/public-client.ts"() {
629
929
  init_cache();
630
930
  init_rpc_fallback();
631
931
  init_networks();
632
932
  init_errors2();
933
+ PublicReadClientImpl = class {
934
+ chainId;
935
+ viemClient;
936
+ cache;
937
+ multicall3Address;
938
+ constructor(chainId, viemClient, cache, multicall3Address) {
939
+ this.chainId = chainId;
940
+ this.viemClient = viemClient;
941
+ this.cache = cache;
942
+ this.multicall3Address = multicall3Address;
943
+ }
944
+ async readContract(params) {
945
+ const {
946
+ address,
947
+ abi,
948
+ functionName,
949
+ args = [],
950
+ blockTag = "latest",
951
+ from,
952
+ forceRefresh = false
953
+ } = params;
954
+ if (this.cache && !forceRefresh) {
955
+ const cacheKey = generateCacheKey({
956
+ chainId: this.chainId,
957
+ address,
958
+ functionName,
959
+ args,
960
+ blockTag,
961
+ from
962
+ });
963
+ const cached = this.cache.get(cacheKey);
964
+ if (cached !== void 0) {
965
+ return cached;
966
+ }
967
+ }
968
+ const result = await this.viemClient.readContract({
969
+ address,
970
+ abi,
971
+ functionName,
972
+ args,
973
+ blockTag: normalizeBlockTag(blockTag),
974
+ account: from
975
+ });
976
+ if (this.cache) {
977
+ const cacheKey = generateCacheKey({
978
+ chainId: this.chainId,
979
+ address,
980
+ functionName,
981
+ args,
982
+ blockTag,
983
+ from
984
+ });
985
+ this.cache.set(cacheKey, result);
986
+ }
987
+ return result;
988
+ }
989
+ async multicall(params) {
990
+ const {
991
+ contracts,
992
+ allowFailure = true,
993
+ blockTag = "latest",
994
+ batchSize = 100
995
+ } = params;
996
+ if (!this.multicall3Address || contracts.length === 1) {
997
+ return this.sequentialMulticall(contracts, allowFailure, blockTag);
998
+ }
999
+ const results = [];
1000
+ for (let i = 0; i < contracts.length; i += batchSize) {
1001
+ const chunk = contracts.slice(i, i + batchSize);
1002
+ const chunkResults = await this.executeMulticallBatch(
1003
+ chunk,
1004
+ allowFailure,
1005
+ blockTag
1006
+ );
1007
+ results.push(...chunkResults);
1008
+ }
1009
+ return results;
1010
+ }
1011
+ async executeMulticallBatch(contracts, allowFailure, blockTag) {
1012
+ try {
1013
+ const results = await this.viemClient.multicall({
1014
+ contracts: contracts.map((c) => ({
1015
+ address: c.address,
1016
+ abi: c.abi,
1017
+ functionName: c.functionName,
1018
+ args: c.args
1019
+ })),
1020
+ allowFailure,
1021
+ blockTag,
1022
+ multicallAddress: this.multicall3Address
1023
+ });
1024
+ const typedResults = results;
1025
+ return typedResults.map((r) => {
1026
+ if (r.status === "success") {
1027
+ return { status: "success", result: r.result };
1028
+ } else {
1029
+ return { status: "failure", error: r.error };
1030
+ }
1031
+ });
1032
+ } catch (error) {
1033
+ return this.sequentialMulticall(contracts, allowFailure, blockTag);
1034
+ }
1035
+ }
1036
+ async sequentialMulticall(contracts, allowFailure, blockTag) {
1037
+ const results = [];
1038
+ for (const contract of contracts) {
1039
+ try {
1040
+ const result = await this.readContract({
1041
+ address: contract.address,
1042
+ abi: contract.abi,
1043
+ functionName: contract.functionName,
1044
+ args: contract.args,
1045
+ blockTag
1046
+ });
1047
+ results.push({ status: "success", result });
1048
+ } catch (error) {
1049
+ if (allowFailure) {
1050
+ results.push({
1051
+ status: "failure",
1052
+ error: error instanceof Error ? error : new Error(String(error))
1053
+ });
1054
+ } else {
1055
+ throw error;
1056
+ }
1057
+ }
1058
+ }
1059
+ return results;
1060
+ }
1061
+ async getLogs(params) {
1062
+ const { address, event, args, fromBlock, toBlock, blockHash } = params;
1063
+ const logsParams = {};
1064
+ if (address !== void 0) {
1065
+ logsParams.address = address;
1066
+ }
1067
+ if (event !== void 0) {
1068
+ logsParams.event = event;
1069
+ }
1070
+ if (args !== void 0) {
1071
+ logsParams.args = args;
1072
+ }
1073
+ if (blockHash !== void 0) {
1074
+ logsParams.blockHash = blockHash;
1075
+ } else {
1076
+ if (fromBlock !== void 0) {
1077
+ logsParams.fromBlock = normalizeBlockTag(fromBlock);
1078
+ }
1079
+ if (toBlock !== void 0) {
1080
+ logsParams.toBlock = normalizeBlockTag(toBlock);
1081
+ }
1082
+ }
1083
+ const logs = await this.viemClient.getLogs(logsParams);
1084
+ return logs.map((log) => ({
1085
+ address: log.address,
1086
+ topics: log.topics,
1087
+ data: log.data,
1088
+ blockNumber: log.blockNumber,
1089
+ blockHash: log.blockHash,
1090
+ transactionHash: log.transactionHash,
1091
+ transactionIndex: log.transactionIndex,
1092
+ logIndex: log.logIndex,
1093
+ removed: log.removed,
1094
+ // These properties only exist when an event ABI is provided
1095
+ args: "args" in log ? log.args : void 0,
1096
+ eventName: "eventName" in log ? log.eventName : void 0
1097
+ }));
1098
+ }
1099
+ async getTransactionReceipt(params) {
1100
+ const { hash } = params;
1101
+ try {
1102
+ const receipt = await this.viemClient.getTransactionReceipt({ hash });
1103
+ return this.mapReceipt(receipt);
1104
+ } catch (error) {
1105
+ if (error instanceof Error && (error.message.includes("could not be found") || error.message.includes("not found"))) {
1106
+ return null;
1107
+ }
1108
+ throw error;
1109
+ }
1110
+ }
1111
+ async waitForTransactionReceipt(params) {
1112
+ const {
1113
+ hash,
1114
+ confirmations = 1,
1115
+ pollingInterval = 4e3,
1116
+ timeout = 6e4,
1117
+ onReplaced
1118
+ } = params;
1119
+ try {
1120
+ const receipt = await this.viemClient.waitForTransactionReceipt({
1121
+ hash,
1122
+ confirmations,
1123
+ pollingInterval,
1124
+ timeout,
1125
+ onReplaced: onReplaced ? (response) => {
1126
+ onReplaced({
1127
+ reason: response.reason,
1128
+ replacedTransaction: { hash: response.replacedTransaction.hash },
1129
+ transaction: { hash: response.transaction.hash },
1130
+ transactionReceipt: this.mapReceipt(response.transactionReceipt)
1131
+ });
1132
+ } : void 0
1133
+ });
1134
+ return this.mapReceipt(receipt);
1135
+ } catch (error) {
1136
+ if (error instanceof Error && error.message.includes("timed out")) {
1137
+ throw new TransactionReceiptTimeoutError(hash, timeout);
1138
+ }
1139
+ throw error;
1140
+ }
1141
+ }
1142
+ mapReceipt(receipt) {
1143
+ return {
1144
+ blockHash: receipt.blockHash,
1145
+ blockNumber: receipt.blockNumber,
1146
+ contractAddress: receipt.contractAddress,
1147
+ cumulativeGasUsed: receipt.cumulativeGasUsed,
1148
+ effectiveGasPrice: receipt.effectiveGasPrice,
1149
+ from: receipt.from,
1150
+ gasUsed: receipt.gasUsed,
1151
+ logs: receipt.logs.map((log) => ({
1152
+ address: log.address,
1153
+ topics: log.topics,
1154
+ data: log.data,
1155
+ blockNumber: log.blockNumber,
1156
+ blockHash: log.blockHash,
1157
+ transactionHash: log.transactionHash,
1158
+ transactionIndex: log.transactionIndex,
1159
+ logIndex: log.logIndex,
1160
+ removed: log.removed
1161
+ })),
1162
+ logsBloom: receipt.logsBloom,
1163
+ status: receipt.status,
1164
+ to: receipt.to,
1165
+ transactionHash: receipt.transactionHash,
1166
+ transactionIndex: receipt.transactionIndex,
1167
+ type: receipt.type
1168
+ };
1169
+ }
1170
+ clearCache() {
1171
+ this.cache?.clear();
1172
+ }
1173
+ getCacheStats() {
1174
+ if (!this.cache) {
1175
+ return { size: 0, maxSize: 0, hits: 0, misses: 0 };
1176
+ }
1177
+ return this.cache.getStats();
1178
+ }
1179
+ };
633
1180
  }
634
1181
  });
1182
+ function createChainFromConfig(chainConfig) {
1183
+ return viem.defineChain({
1184
+ id: chainConfig.id,
1185
+ name: chainConfig.name,
1186
+ nativeCurrency: {
1187
+ name: "LUMIA",
1188
+ symbol: "LUMIA",
1189
+ decimals: 18
1190
+ },
1191
+ rpcUrls: {
1192
+ default: { http: chainConfig.rpcUrls },
1193
+ public: { http: chainConfig.rpcUrls }
1194
+ }
1195
+ });
1196
+ }
635
1197
  function createPublicClientForChain(chainId) {
636
1198
  const chainConfig = getChainConfig(chainId);
637
1199
  if (!chainConfig) {
@@ -648,6 +1210,27 @@ function createPublicClientForChain(chainId) {
648
1210
  })
649
1211
  });
650
1212
  }
1213
+ function createBundlerClientForChain(chainId) {
1214
+ const chainConfig = getChainConfig(chainId);
1215
+ if (!chainConfig) {
1216
+ const supportedChainIds = Array.from(SUPPORTED_CHAINS.keys());
1217
+ throw new ChainNotSupportedError(chainId, supportedChainIds);
1218
+ }
1219
+ if (!chainConfig.bundlerUrl) {
1220
+ throw new Error(
1221
+ `Chain ${chainId} (${chainConfig.name}) has no bundlerUrl configured`
1222
+ );
1223
+ }
1224
+ const viemChain = getViemChain(chainId);
1225
+ return accountAbstraction.createBundlerClient({
1226
+ chain: viemChain,
1227
+ transport: viem.http(chainConfig.bundlerUrl, {
1228
+ timeout: 1e4,
1229
+ retryCount: 0,
1230
+ fetchOptions: { mode: "cors" }
1231
+ })
1232
+ });
1233
+ }
651
1234
  var init_client_factories = __esm({
652
1235
  "src/read/client-factories.ts"() {
653
1236
  init_networks();
@@ -656,6 +1239,52 @@ var init_client_factories = __esm({
656
1239
  });
657
1240
 
658
1241
  // src/read/index.ts
1242
+ var read_exports = {};
1243
+ __export(read_exports, {
1244
+ ARBITRUM_SEPOLIA: () => ARBITRUM_SEPOLIA,
1245
+ ARBITRUM_SEPOLIA_CHAIN_ID: () => ARBITRUM_SEPOLIA_CHAIN_ID,
1246
+ AllRpcsFailedError: () => AllRpcsFailedError,
1247
+ BASE_SEPOLIA: () => BASE_SEPOLIA,
1248
+ BASE_SEPOLIA_CHAIN_ID: () => BASE_SEPOLIA_CHAIN_ID,
1249
+ BSC_TESTNET: () => BSC_TESTNET,
1250
+ BSC_TESTNET_CHAIN_ID: () => BSC_TESTNET_CHAIN_ID,
1251
+ BlockPrunedError: () => BlockPrunedError,
1252
+ ChainNotSupportedError: () => ChainNotSupportedError,
1253
+ ContractNotFoundError: () => ContractNotFoundError,
1254
+ ContractRevertError: () => ContractRevertError,
1255
+ DEFAULT_CACHE_CONFIG: () => DEFAULT_CACHE_CONFIG,
1256
+ DEFAULT_CACHE_MAX_SIZE: () => DEFAULT_CACHE_MAX_SIZE,
1257
+ DEFAULT_CACHE_TTL: () => DEFAULT_CACHE_TTL,
1258
+ DEFAULT_CHAIN_ID: () => DEFAULT_CHAIN_ID,
1259
+ DEFAULT_MULTICALL_BATCH_SIZE: () => DEFAULT_MULTICALL_BATCH_SIZE,
1260
+ InvalidAbiError: () => InvalidAbiError,
1261
+ LRUCache: () => LRUCache,
1262
+ LUMIA_MAINNET: () => LUMIA_MAINNET,
1263
+ LUMIA_MAINNET_CHAIN_ID: () => LUMIA_MAINNET_CHAIN_ID,
1264
+ LUMIA_TESTNET: () => LUMIA_TESTNET,
1265
+ LUMIA_TESTNET_CHAIN_ID: () => LUMIA_TESTNET_CHAIN_ID,
1266
+ MULTICALL3_ADDRESS: () => MULTICALL3_ADDRESS2,
1267
+ RateLimitedError: () => RateLimitedError,
1268
+ ReadLayerError: () => ReadLayerError,
1269
+ RpcConnectionError: () => RpcConnectionError,
1270
+ SEPOLIA: () => SEPOLIA,
1271
+ SEPOLIA_CHAIN_ID: () => SEPOLIA_CHAIN_ID,
1272
+ TransactionReceiptTimeoutError: () => TransactionReceiptTimeoutError,
1273
+ arbitrumSepoliaChain: () => arbitrumSepoliaChain,
1274
+ baseSepoliaChain: () => baseSepoliaChain,
1275
+ bscTestnetChain: () => bscTestnetChain,
1276
+ createBundlerClientForChain: () => createBundlerClientForChain,
1277
+ createChainFromConfig: () => createChainFromConfig,
1278
+ createPublicClientForChain: () => createPublicClientForChain,
1279
+ generateCacheKey: () => generateCacheKey,
1280
+ getChainConfig: () => getChainConfig,
1281
+ getPublicClient: () => getPublicClient2,
1282
+ getViemChain: () => getViemChain,
1283
+ isChainSupported: () => isChainSupported,
1284
+ lumiaMainnetChain: () => lumiaMainnetChain,
1285
+ lumiaTestnetChain: () => lumiaTestnetChain,
1286
+ sepoliaChain: () => sepoliaChain
1287
+ });
659
1288
  var init_read = __esm({
660
1289
  "src/read/index.ts"() {
661
1290
  init_public_client();
@@ -1407,8 +2036,15 @@ async function sendUserOperationForServerWallet(params, bundlerUrl) {
1407
2036
  maxCallGasLimit,
1408
2037
  maxVerificationGasLimit,
1409
2038
  debug = false,
2039
+ chainId,
1410
2040
  nonceKey = 0n
1411
2041
  } = params;
2042
+ const { getChainConfig: getChainConfig2 } = await Promise.resolve().then(() => (init_read(), read_exports));
2043
+ const chainConfig = getChainConfig2(chainId);
2044
+ if (!chainConfig) {
2045
+ throw new Error(`Chain ID ${chainId} is not supported. Make sure to register it with registerChainConfig().`);
2046
+ }
2047
+ const effectiveBundlerUrl = bundlerUrl || chainConfig.bundlerUrl;
1412
2048
  if (nonceKey < 0n || nonceKey > exports.MAX_NONCE_KEY) {
1413
2049
  throw new Error(`Nonce key must be between 0 and 2^192-1. Got: ${nonceKey}`);
1414
2050
  }
@@ -1418,7 +2054,7 @@ async function sendUserOperationForServerWallet(params, bundlerUrl) {
1418
2054
  const {
1419
2055
  createUserOperationWithDynamicFees: createUserOperationWithDynamicFees2,
1420
2056
  estimateUserOperationGas: estimateUserOperationGas2,
1421
- sendUserOperationWithRetry: sendUserOperationWithRetry2
2057
+ sendUserOperationRaw: sendUserOperationRaw2
1422
2058
  } = bundler;
1423
2059
  const amountWeiBigInt = BigInt(value);
1424
2060
  const isMinimalTest = to === "0x0000000000000000000000000000000000000000" && value === "0" && data === "0x";
@@ -1508,7 +2144,7 @@ async function sendUserOperationForServerWallet(params, bundlerUrl) {
1508
2144
  factoryData,
1509
2145
  feeType
1510
2146
  },
1511
- { providedClient: publicClient, bundlerUrl }
2147
+ { client: publicClient, bundlerUrl: effectiveBundlerUrl, chainConfig }
1512
2148
  );
1513
2149
  } else {
1514
2150
  userOp = await createUserOperationWithDynamicFees2(
@@ -1519,7 +2155,7 @@ async function sendUserOperationForServerWallet(params, bundlerUrl) {
1519
2155
  includeFactory: false,
1520
2156
  feeType
1521
2157
  },
1522
- { providedClient: publicClient, bundlerUrl }
2158
+ { client: publicClient, bundlerUrl: effectiveBundlerUrl, chainConfig }
1523
2159
  );
1524
2160
  }
1525
2161
  if (paymasterAddress && paymasterAddress !== "0x0000000000000000000000000000000000000000") {
@@ -1534,7 +2170,7 @@ async function sendUserOperationForServerWallet(params, bundlerUrl) {
1534
2170
  debug
1535
2171
  };
1536
2172
  try {
1537
- const gasEst = await estimateUserOperationGas2(userOp, true, bundlerUrl);
2173
+ const gasEst = await estimateUserOperationGas2(userOp, { chainId, retryWithoutFactory: true });
1538
2174
  if (debug) {
1539
2175
  console.log("[ServerWallet] Gas estimation from bundler:", {
1540
2176
  callGasLimit: gasEst.callGasLimit,
@@ -1638,7 +2274,7 @@ async function sendUserOperationForServerWallet(params, bundlerUrl) {
1638
2274
  console.log("[ServerWallet] Signature created and normalized");
1639
2275
  console.log("[ServerWallet] Submitting UserOperation to bundler...");
1640
2276
  }
1641
- const userOpHashResult = await sendUserOperationWithRetry2(userOp);
2277
+ const userOpHashResult = await sendUserOperationRaw2(userOp, { chainId });
1642
2278
  if (debug) {
1643
2279
  console.log("[ServerWallet] UserOperation submitted:", userOpHashResult);
1644
2280
  }
@@ -1692,6 +2328,7 @@ async function sendBatchUserOperationForServerWallet(params) {
1692
2328
  maxCallGasLimit,
1693
2329
  maxVerificationGasLimit,
1694
2330
  debug = false,
2331
+ chainId,
1695
2332
  nonceKey = 0n
1696
2333
  } = params;
1697
2334
  if (!operations || operations.length === 0) {
@@ -1700,13 +2337,18 @@ async function sendBatchUserOperationForServerWallet(params) {
1700
2337
  if (nonceKey < 0n || nonceKey > exports.MAX_NONCE_KEY) {
1701
2338
  throw new Error(`Nonce key must be between 0 and 2^192-1. Got: ${nonceKey}`);
1702
2339
  }
2340
+ const { getChainConfig: getChainConfig2 } = await Promise.resolve().then(() => (init_read(), read_exports));
2341
+ const chainConfig = getChainConfig2(chainId);
2342
+ if (!chainConfig) {
2343
+ throw new Error(`Chain ID ${chainId} is not supported. Make sure to register it with registerChainConfig().`);
2344
+ }
1703
2345
  const viem = await loadViem();
1704
2346
  const bundler = await loadBundler();
1705
2347
  const { encodeFunctionData } = viem;
1706
2348
  const {
1707
2349
  createUserOperationWithDynamicFees: createUserOperationWithDynamicFees2,
1708
2350
  estimateUserOperationGas: estimateUserOperationGas2,
1709
- sendUserOperationWithRetry: sendUserOperationWithRetry2
2351
+ sendUserOperationRaw: sendUserOperationRaw2
1710
2352
  } = bundler;
1711
2353
  const destinations = [];
1712
2354
  const values = [];
@@ -1792,25 +2434,27 @@ async function sendBatchUserOperationForServerWallet(params) {
1792
2434
  args: [wallet.ownerAddress, saltZero]
1793
2435
  });
1794
2436
  userOp = await createUserOperationWithDynamicFees2(
1795
- wallet.smartAccountAddress,
1796
- nonce,
1797
- callData,
1798
- true,
1799
- // includeFactory
1800
- factoryAddress,
1801
- factoryData,
1802
- feeType
2437
+ {
2438
+ sender: wallet.smartAccountAddress,
2439
+ nonce,
2440
+ callData,
2441
+ includeFactory: true,
2442
+ factoryAddress,
2443
+ factoryData,
2444
+ feeType
2445
+ },
2446
+ { client: publicClient, bundlerUrl: chainConfig.bundlerUrl, chainConfig }
1803
2447
  );
1804
2448
  } else {
1805
2449
  userOp = await createUserOperationWithDynamicFees2(
1806
- wallet.smartAccountAddress,
1807
- nonce,
1808
- callData,
1809
- false,
1810
- // includeFactory
1811
- void 0,
1812
- void 0,
1813
- feeType
2450
+ {
2451
+ sender: wallet.smartAccountAddress,
2452
+ nonce,
2453
+ callData,
2454
+ includeFactory: false,
2455
+ feeType
2456
+ },
2457
+ { client: publicClient, bundlerUrl: chainConfig.bundlerUrl, chainConfig }
1814
2458
  );
1815
2459
  }
1816
2460
  if (paymasterAddress && paymasterAddress !== "0x0000000000000000000000000000000000000000") {
@@ -1825,7 +2469,7 @@ async function sendBatchUserOperationForServerWallet(params) {
1825
2469
  debug
1826
2470
  };
1827
2471
  try {
1828
- const gasEst = await estimateUserOperationGas2(userOp);
2472
+ const gasEst = await estimateUserOperationGas2(userOp, { chainId, retryWithoutFactory: true });
1829
2473
  if (debug) {
1830
2474
  console.log("[ServerWallet] Gas estimation from bundler:", {
1831
2475
  callGasLimit: gasEst.callGasLimit,
@@ -1929,7 +2573,7 @@ async function sendBatchUserOperationForServerWallet(params) {
1929
2573
  console.log("[ServerWallet] Signature created and normalized");
1930
2574
  console.log("[ServerWallet] Submitting batch UserOperation to bundler...");
1931
2575
  }
1932
- const userOpHashResult = await sendUserOperationWithRetry2(userOp);
2576
+ const userOpHashResult = await sendUserOperationRaw2(userOp, { chainId });
1933
2577
  if (debug) {
1934
2578
  console.log("[ServerWallet] Batch UserOperation submitted:", userOpHashResult);
1935
2579
  }
@@ -3042,6 +3686,7 @@ var ServerWalletManager = class {
3042
3686
  maxCallGasLimit: this.maxCallGasLimit,
3043
3687
  maxVerificationGasLimit: this.maxVerificationGasLimit,
3044
3688
  debug: this.debug,
3689
+ chainId: this.chainId,
3045
3690
  nonceKey
3046
3691
  }, this.bundlerUrl);
3047
3692
  if (this.debug) {
@@ -3089,6 +3734,7 @@ var ServerWalletManager = class {
3089
3734
  maxCallGasLimit: this.maxCallGasLimit,
3090
3735
  maxVerificationGasLimit: this.maxVerificationGasLimit,
3091
3736
  debug: this.debug,
3737
+ chainId: this.chainId,
3092
3738
  nonceKey
3093
3739
  });
3094
3740
  if (this.debug) {