starknet 7.1.0 → 7.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -62,6 +62,7 @@ __export(index_exports, {
62
62
  LedgerSigner: () => LedgerSigner111,
63
63
  LedgerSigner111: () => LedgerSigner111,
64
64
  LedgerSigner221: () => LedgerSigner221,
65
+ LedgerSigner231: () => LedgerSigner231,
65
66
  LibraryError: () => LibraryError,
66
67
  Literal: () => Literal,
67
68
  LogLevelIndex: () => LogLevelIndex,
@@ -69,11 +70,13 @@ __export(index_exports, {
69
70
  OutsideExecutionTypesV1: () => OutsideExecutionTypesV1,
70
71
  OutsideExecutionTypesV2: () => OutsideExecutionTypesV2,
71
72
  OutsideExecutionVersion: () => OutsideExecutionVersion,
73
+ PaymasterInterface: () => PaymasterInterface,
74
+ PaymasterRpc: () => PaymasterRpc,
72
75
  Provider: () => RpcProvider2,
73
76
  ProviderInterface: () => ProviderInterface,
74
77
  RPC: () => api_exports,
75
- RPC07: () => rpc_0_7_exports,
76
- RPC08: () => rpc_0_8_exports,
78
+ RPC07: () => rpc_0_7_1_exports,
79
+ RPC08: () => rpc_0_8_1_exports,
77
80
  RPCResponseParser: () => RPCResponseParser,
78
81
  ReceiptTx: () => ReceiptTx,
79
82
  ResponseParser: () => ResponseParser,
@@ -107,6 +110,7 @@ __export(index_exports, {
107
110
  config: () => config,
108
111
  constants: () => constants_exports,
109
112
  contractClassResponseToLegacyCompiledContract: () => contractClassResponseToLegacyCompiledContract,
113
+ defaultPaymaster: () => defaultPaymaster,
110
114
  defaultProvider: () => defaultProvider,
111
115
  ec: () => ec_exports,
112
116
  encode: () => encode_exports,
@@ -121,21 +125,29 @@ __export(index_exports, {
121
125
  getLedgerPathBuffer111: () => getLedgerPathBuffer111,
122
126
  getLedgerPathBuffer221: () => getLedgerPathBuffer221,
123
127
  hash: () => hash_exports,
128
+ isPendingBlock: () => isPendingBlock,
129
+ isPendingStateUpdate: () => isPendingStateUpdate,
130
+ isPendingTransaction: () => isPendingTransaction,
124
131
  isRPC08_FeeEstimate: () => isRPC08_FeeEstimate,
125
132
  isRPC08_ResourceBounds: () => isRPC08_ResourceBounds,
126
133
  isSierra: () => isSierra,
134
+ isSupportedSpecVersion: () => isSupportedSpecVersion,
135
+ isV3Tx: () => isV3Tx,
136
+ isVersion: () => isVersion,
127
137
  json: () => json_exports,
128
138
  logger: () => logger,
129
139
  merkle: () => merkle_exports,
130
140
  num: () => num_exports,
131
141
  outsideExecution: () => outsideExecution_exports,
132
142
  parseCalldataField: () => parseCalldataField,
143
+ paymaster: () => paymaster_exports,
133
144
  provider: () => provider_exports,
134
145
  selector: () => selector_exports,
135
146
  shortString: () => shortString_exports,
136
147
  src5: () => src5_exports,
137
148
  stark: () => stark_exports,
138
149
  starknetId: () => starknetId_exports,
150
+ toAnyPatchVersion: () => toAnyPatchVersion,
139
151
  transaction: () => transaction_exports,
140
152
  typedData: () => typedData_exports,
141
153
  types: () => types_exports,
@@ -164,6 +176,7 @@ __export(constants_exports, {
164
176
  MAX_STORAGE_ITEM_SIZE: () => MAX_STORAGE_ITEM_SIZE,
165
177
  NetworkName: () => _NetworkName,
166
178
  OutsideExecutionCallerAny: () => OutsideExecutionCallerAny,
179
+ PAYMASTER_RPC_NODES: () => PAYMASTER_RPC_NODES,
167
180
  PRIME: () => PRIME,
168
181
  RANGE_FELT: () => RANGE_FELT,
169
182
  RANGE_I128: () => RANGE_I128,
@@ -185,6 +198,7 @@ __export(constants_exports, {
185
198
  var api_exports = {};
186
199
  __export(api_exports, {
187
200
  JRPC: () => jsonrpc_exports,
201
+ PAYMASTER_API: () => import_starknet_types_08.PAYMASTER_API,
188
202
  RPCSPEC07: () => RPCSPEC07,
189
203
  RPCSPEC08: () => RPCSPEC08
190
204
  });
@@ -195,6 +209,7 @@ var jsonrpc_exports = {};
195
209
  // src/types/api/index.ts
196
210
  var RPCSPEC07 = __toESM(require("starknet-types-07"));
197
211
  var RPCSPEC08 = __toESM(require("starknet-types-08"));
212
+ var import_starknet_types_08 = require("starknet-types-08");
198
213
  __reExport(api_exports, require("starknet-types-08"));
199
214
 
200
215
  // src/utils/encode.ts
@@ -326,14 +341,14 @@ var _TransactionHashPrefix = {
326
341
  // encodeShortString('l1_handler'),
327
342
  };
328
343
  var _SupportedRpcVersion = {
329
- 0.7: "0.7",
330
- 0.8: "0.8",
331
- v07: "0.7",
332
- v08: "0.8"
344
+ "0.7.1": "0.7.1",
345
+ "0.8.1": "0.8.1",
346
+ v0_7_1: "0.7.1",
347
+ v0_8_1: "0.8.1"
333
348
  };
334
349
  var DEFAULT_GLOBAL_CONFIG = {
335
350
  legacyMode: false,
336
- rpcVersion: "0.8",
351
+ rpcVersion: "0.8.1",
337
352
  transactionVersion: api_exports.ETransactionVersion.V3,
338
353
  logLevel: "INFO",
339
354
  feeMarginPercentage: {
@@ -352,7 +367,9 @@ var DEFAULT_GLOBAL_CONFIG = {
352
367
  }
353
368
  },
354
369
  maxFee: 50
355
- }
370
+ },
371
+ fetch: void 0,
372
+ websocket: void 0
356
373
  };
357
374
  var RPC_DEFAULT_NODES = {
358
375
  SN_MAIN: [
@@ -364,159 +381,239 @@ var RPC_DEFAULT_NODES = {
364
381
  `https://free-rpc.nethermind.io/sepolia-juno/`
365
382
  ]
366
383
  };
384
+ var PAYMASTER_RPC_NODES = {
385
+ SN_MAIN: [`https://starknet.paymaster.avnu.fi`],
386
+ SN_SEPOLIA: [`https://sepolia.paymaster.avnu.fi`]
387
+ };
367
388
  var SYSTEM_MESSAGES = {
368
389
  legacyTxWarningMessage: "You are using a deprecated transaction version (V0,V1,V2)!\nUpdate to the latest V3 transactions!",
369
390
  legacyTxRPC08Message: "RPC 0.8 do not support legacy transactions",
370
- SWOldV3: "RPC 0.7 V3 tx (improper resource bounds) not supported in RPC 0.8"
391
+ SWOldV3: "RPC 0.7 V3 tx (improper resource bounds) not supported in RPC 0.8",
392
+ channelVersionMismatch: "Channel specification version is not compatible with the connected node Specification Version",
393
+ unsupportedSpecVersion: "The connected node specification version is not supported by this library"
371
394
  };
372
395
 
373
- // src/channel/rpc_0_7.ts
374
- var rpc_0_7_exports = {};
375
- __export(rpc_0_7_exports, {
376
- RpcChannel: () => RpcChannel
377
- });
378
-
379
- // src/utils/json.ts
380
- var json_exports = {};
381
- __export(json_exports, {
382
- parse: () => parse2,
383
- parseAlwaysAsBig: () => parseAlwaysAsBig,
384
- stringify: () => stringify2
385
- });
386
- var json = __toESM(require("lossless-json"));
387
- var parseIntAsNumberOrBigInt = (str) => {
388
- if (!json.isInteger(str)) return parseFloat(str);
389
- const num = parseInt(str, 10);
390
- return Number.isSafeInteger(num) ? num : BigInt(str);
396
+ // src/global/config.ts
397
+ var Configuration = class _Configuration {
398
+ static instance;
399
+ config;
400
+ constructor() {
401
+ this.initialize();
402
+ }
403
+ initialize() {
404
+ this.config = { ...DEFAULT_GLOBAL_CONFIG };
405
+ }
406
+ static getInstance() {
407
+ if (!_Configuration.instance) {
408
+ _Configuration.instance = new _Configuration();
409
+ }
410
+ return _Configuration.instance;
411
+ }
412
+ get(key, defaultValue) {
413
+ return this.config[key] ?? defaultValue;
414
+ }
415
+ set(key, value) {
416
+ this.config[key] = value;
417
+ }
418
+ update(configData) {
419
+ this.config = {
420
+ ...this.config,
421
+ ...configData
422
+ };
423
+ }
424
+ getAll() {
425
+ return { ...this.config };
426
+ }
427
+ reset() {
428
+ this.initialize();
429
+ }
430
+ delete(key) {
431
+ delete this.config[key];
432
+ }
433
+ hasKey(key) {
434
+ return key in this.config;
435
+ }
391
436
  };
392
- var parse2 = (str) => json.parse(String(str), void 0, parseIntAsNumberOrBigInt);
393
- var parseAlwaysAsBig = (str) => json.parse(String(str), void 0, json.parseNumberAndBigInt);
394
- var stringify2 = (value, replacer, space, numberStringifiers) => json.stringify(value, replacer, space, numberStringifiers);
437
+ var config = Configuration.getInstance();
395
438
 
396
- // src/utils/errors/rpc.ts
397
- var errorCodes = {
398
- FAILED_TO_RECEIVE_TXN: 1,
399
- NO_TRACE_AVAILABLE: 10,
400
- CONTRACT_NOT_FOUND: 20,
401
- ENTRYPOINT_NOT_FOUND: 21,
402
- BLOCK_NOT_FOUND: 24,
403
- INVALID_TXN_INDEX: 27,
404
- CLASS_HASH_NOT_FOUND: 28,
405
- TXN_HASH_NOT_FOUND: 29,
406
- PAGE_SIZE_TOO_BIG: 31,
407
- NO_BLOCKS: 32,
408
- INVALID_CONTINUATION_TOKEN: 33,
409
- TOO_MANY_KEYS_IN_FILTER: 34,
410
- CONTRACT_ERROR: 40,
411
- TRANSACTION_EXECUTION_ERROR: 41,
412
- STORAGE_PROOF_NOT_SUPPORTED: 42,
413
- CLASS_ALREADY_DECLARED: 51,
414
- INVALID_TRANSACTION_NONCE: 52,
415
- INSUFFICIENT_RESOURCES_FOR_VALIDATE: 53,
416
- INSUFFICIENT_ACCOUNT_BALANCE: 54,
417
- VALIDATION_FAILURE: 55,
418
- COMPILATION_FAILED: 56,
419
- CONTRACT_CLASS_SIZE_IS_TOO_LARGE: 57,
420
- NON_ACCOUNT: 58,
421
- DUPLICATE_TX: 59,
422
- COMPILED_CLASS_HASH_MISMATCH: 60,
423
- UNSUPPORTED_TX_VERSION: 61,
424
- UNSUPPORTED_CONTRACT_CLASS_VERSION: 62,
425
- UNEXPECTED_ERROR: 63,
426
- INVALID_SUBSCRIPTION_ID: 66,
427
- TOO_MANY_ADDRESSES_IN_FILTER: 67,
428
- TOO_MANY_BLOCKS_BACK: 68,
429
- COMPILATION_ERROR: 100
439
+ // src/global/logger.type.ts
440
+ var LogLevelIndex = {
441
+ DEBUG: 5,
442
+ INFO: 4,
443
+ WARN: 3,
444
+ ERROR: 2,
445
+ FATAL: 1,
446
+ OFF: 0
430
447
  };
431
- var rpc_default = errorCodes;
432
448
 
433
- // src/utils/errors/index.ts
434
- function fixStack(target, fn = target.constructor) {
435
- const { captureStackTrace } = Error;
436
- captureStackTrace && captureStackTrace(target, fn);
437
- }
438
- function fixProto(target, prototype) {
439
- const { setPrototypeOf } = Object;
440
- setPrototypeOf ? setPrototypeOf(target, prototype) : target.__proto__ = prototype;
441
- }
442
- var CustomError = class extends Error {
443
- name;
444
- constructor(message) {
445
- super(message);
446
- Object.defineProperty(this, "name", {
447
- value: new.target.name,
448
- enumerable: false,
449
- configurable: true
450
- });
451
- fixProto(this, new.target.prototype);
452
- fixStack(this);
449
+ // src/global/logger.ts
450
+ var Logger = class _Logger {
451
+ static instance;
452
+ config;
453
+ constructor() {
454
+ this.config = config;
453
455
  }
454
- };
455
- var LibraryError = class extends CustomError {
456
- };
457
- var RpcError = class extends LibraryError {
458
- constructor(baseError, method, params) {
459
- super(`RPC: ${method} with params ${stringify2(params, null, 2)}
460
-
461
- ${baseError.code}: ${baseError.message}: ${stringify2(baseError.data)}`);
462
- this.baseError = baseError;
463
- this.request = { method, params };
456
+ static getInstance() {
457
+ if (!_Logger.instance) {
458
+ _Logger.instance = new _Logger();
459
+ }
460
+ return _Logger.instance;
464
461
  }
465
- request;
466
- get code() {
467
- return this.baseError.code;
462
+ getTimestamp() {
463
+ return (/* @__PURE__ */ new Date()).toISOString();
464
+ }
465
+ shouldLog(messageLevel) {
466
+ const configLevel = this.config.get("logLevel", "INFO");
467
+ return messageLevel <= LogLevelIndex[configLevel];
468
+ }
469
+ formatMessage(logMessage) {
470
+ const { level, message, timestamp, data } = logMessage;
471
+ let formattedMessage = `[${timestamp}] ${level}: ${message}`;
472
+ if (data) {
473
+ try {
474
+ formattedMessage += `
475
+ ${JSON.stringify(data, null, 2)}`;
476
+ } catch (error) {
477
+ formattedMessage += `
478
+ [JSON.stringify Error/Circular]: ${error}`;
479
+ }
480
+ }
481
+ return formattedMessage;
482
+ }
483
+ log(level, message, data) {
484
+ if (!this.shouldLog(LogLevelIndex[level])) {
485
+ return;
486
+ }
487
+ const logMessage = {
488
+ level,
489
+ message,
490
+ timestamp: this.getTimestamp(),
491
+ data
492
+ };
493
+ const formattedMessage = this.formatMessage(logMessage);
494
+ switch (level) {
495
+ case "DEBUG":
496
+ console.debug(formattedMessage);
497
+ break;
498
+ case "INFO":
499
+ console.info(formattedMessage);
500
+ break;
501
+ case "WARN":
502
+ console.warn(formattedMessage);
503
+ break;
504
+ case "ERROR":
505
+ case "FATAL":
506
+ console.error(formattedMessage);
507
+ break;
508
+ case "OFF":
509
+ break;
510
+ default:
511
+ console.log(formattedMessage);
512
+ break;
513
+ }
468
514
  }
469
515
  /**
470
- * Verifies the underlying RPC error, also serves as a type guard for the _baseError_ property
471
- * @example
472
- * ```typescript
473
- * SomeError.isType('UNEXPECTED_ERROR');
474
- * ```
516
+ * debug will be displayed when LogLevel level is set to DEBUG(5)
475
517
  */
476
- isType(typeName) {
477
- return rpc_default[typeName] === this.code;
518
+ debug(message, data) {
519
+ this.log("DEBUG", message, data);
478
520
  }
479
- };
480
-
481
- // src/types/index.ts
482
- var types_exports = {};
483
- __export(types_exports, {
484
- BlockStatus: () => BlockStatus,
485
- BlockTag: () => BlockTag,
486
- EDAMode: () => EDAMode,
487
- EDataAvailabilityMode: () => EDataAvailabilityMode,
488
- ETH_ADDRESS: () => ETH_ADDRESS,
489
- ETransactionExecutionStatus: () => ETransactionExecutionStatus,
490
- ETransactionStatus: () => ETransactionStatus,
491
- ETransactionVersion: () => ETransactionVersion2,
492
- ETransactionVersion2: () => ETransactionVersion22,
493
- ETransactionVersion3: () => ETransactionVersion3,
494
- EntryPointType: () => EntryPointType,
495
- Literal: () => Literal,
496
- NON_ZERO_PREFIX: () => NON_ZERO_PREFIX,
497
- OutsideExecutionTypesV1: () => OutsideExecutionTypesV1,
498
- OutsideExecutionTypesV2: () => OutsideExecutionTypesV2,
499
- OutsideExecutionVersion: () => OutsideExecutionVersion,
500
- RPC: () => api_exports,
501
- TransactionExecutionStatus: () => TransactionExecutionStatus,
502
- TransactionFinalityStatus: () => TransactionFinalityStatus,
503
- TransactionType: () => TransactionType,
504
- TypedDataRevision: () => import_starknet_types_07.TypedDataRevision,
505
- Uint: () => Uint,
506
- ValidateType: () => ValidateType,
507
- isRPC08_FeeEstimate: () => isRPC08_FeeEstimate,
508
- isRPC08_ResourceBounds: () => isRPC08_ResourceBounds
509
- });
510
-
511
- // src/types/lib/contract/index.ts
512
- var EntryPointType = {
513
- EXTERNAL: "EXTERNAL",
514
- L1_HANDLER: "L1_HANDLER",
515
- CONSTRUCTOR: "CONSTRUCTOR"
516
- };
517
-
518
- // src/types/lib/index.ts
519
- var TransactionType = {
521
+ /**
522
+ * info will be displayed when LogLevel level is set to DEBUG(5), INFO(4)
523
+ */
524
+ info(message, data) {
525
+ this.log("INFO", message, data);
526
+ }
527
+ /**
528
+ * warn will be displayed when LogLevel level is set to DEBUG(5), INFO(4), WARN(3)
529
+ */
530
+ warn(message, data) {
531
+ this.log("WARN", message, data);
532
+ }
533
+ /**
534
+ * error will be displayed when LogLevel level is set to DEBUG(5), INFO(4), WARN(3), ERROR(2)
535
+ */
536
+ error(message, data) {
537
+ this.log("ERROR", message, data);
538
+ }
539
+ /**
540
+ * fatal will be displayed when LogLevel level is set to DEBUG(5), INFO(4), WARN(3), ERROR(2), FATAL(1)
541
+ */
542
+ fatal(message, data) {
543
+ this.log("FATAL", message, data);
544
+ }
545
+ /**
546
+ * Set the logging level you would like system to display
547
+ * * 5 DEBUG - show all logs
548
+ * * 4 INFO
549
+ * * 3 WARN
550
+ * * 2 ERROR
551
+ * * 1 FATAL
552
+ * * 0 OFF - disable logs
553
+ */
554
+ setLogLevel(level) {
555
+ this.config.set("logLevel", level);
556
+ }
557
+ getLogLevel() {
558
+ return this.config.get("logLevel", "INFO");
559
+ }
560
+ /**
561
+ *
562
+ * @returns logs levels displayed on the configured LogLevel
563
+ */
564
+ getEnabledLogLevels() {
565
+ return Object.keys(LogLevelIndex).filter((s) => {
566
+ return this.shouldLog(LogLevelIndex[s]) && s !== "OFF";
567
+ });
568
+ }
569
+ };
570
+ var logger = Logger.getInstance();
571
+
572
+ // src/channel/rpc_0_7_1.ts
573
+ var rpc_0_7_1_exports = {};
574
+ __export(rpc_0_7_1_exports, {
575
+ RpcChannel: () => RpcChannel
576
+ });
577
+
578
+ // src/types/index.ts
579
+ var types_exports = {};
580
+ __export(types_exports, {
581
+ BlockStatus: () => BlockStatus,
582
+ BlockTag: () => BlockTag,
583
+ EDAMode: () => EDAMode,
584
+ EDataAvailabilityMode: () => EDataAvailabilityMode,
585
+ ETH_ADDRESS: () => ETH_ADDRESS,
586
+ ETransactionExecutionStatus: () => ETransactionExecutionStatus,
587
+ ETransactionStatus: () => ETransactionStatus,
588
+ ETransactionVersion: () => ETransactionVersion2,
589
+ ETransactionVersion2: () => ETransactionVersion22,
590
+ ETransactionVersion3: () => ETransactionVersion3,
591
+ EntryPointType: () => EntryPointType,
592
+ Literal: () => Literal,
593
+ NON_ZERO_PREFIX: () => NON_ZERO_PREFIX,
594
+ OutsideExecutionTypesV1: () => OutsideExecutionTypesV1,
595
+ OutsideExecutionTypesV2: () => OutsideExecutionTypesV2,
596
+ OutsideExecutionVersion: () => OutsideExecutionVersion,
597
+ RPC: () => api_exports,
598
+ TransactionExecutionStatus: () => TransactionExecutionStatus,
599
+ TransactionFinalityStatus: () => TransactionFinalityStatus,
600
+ TransactionType: () => TransactionType,
601
+ TypedDataRevision: () => import_starknet_types_07.TypedDataRevision,
602
+ Uint: () => Uint,
603
+ ValidateType: () => ValidateType,
604
+ isRPC08_FeeEstimate: () => isRPC08_FeeEstimate,
605
+ isRPC08_ResourceBounds: () => isRPC08_ResourceBounds
606
+ });
607
+
608
+ // src/types/lib/contract/index.ts
609
+ var EntryPointType = {
610
+ EXTERNAL: "EXTERNAL",
611
+ L1_HANDLER: "L1_HANDLER",
612
+ CONSTRUCTOR: "CONSTRUCTOR"
613
+ };
614
+
615
+ // src/types/lib/index.ts
616
+ var TransactionType = {
520
617
  DECLARE: "DECLARE",
521
618
  DEPLOY: "DEPLOY",
522
619
  DEPLOY_ACCOUNT: "DEPLOY_ACCOUNT",
@@ -639,6 +736,23 @@ var OutsideExecutionVersion = {
639
736
  // src/types/typedData.ts
640
737
  var import_starknet_types_07 = require("starknet-types-07");
641
738
 
739
+ // src/utils/json.ts
740
+ var json_exports = {};
741
+ __export(json_exports, {
742
+ parse: () => parse2,
743
+ parseAlwaysAsBig: () => parseAlwaysAsBig,
744
+ stringify: () => stringify2
745
+ });
746
+ var json = __toESM(require("lossless-json"));
747
+ var parseIntAsNumberOrBigInt = (str) => {
748
+ if (!json.isInteger(str)) return parseFloat(str);
749
+ const num = parseInt(str, 10);
750
+ return Number.isSafeInteger(num) ? num : BigInt(str);
751
+ };
752
+ var parse2 = (str) => json.parse(String(str), void 0, parseIntAsNumberOrBigInt);
753
+ var parseAlwaysAsBig = (str) => json.parse(String(str), void 0, json.parseNumberAndBigInt);
754
+ var stringify2 = (value, replacer, space, numberStringifiers) => json.stringify(value, replacer, space, numberStringifiers);
755
+
642
756
  // src/utils/batch/index.ts
643
757
  var BatchClient = class {
644
758
  nodeUrl;
@@ -3556,6 +3670,38 @@ __export(stark_exports, {
3556
3670
  var import_starknet4 = require("@scure/starknet");
3557
3671
  var import_pako = require("pako");
3558
3672
 
3673
+ // src/utils/resolve.ts
3674
+ function isV3Tx(details) {
3675
+ const version = details.version ? toHex(details.version) : ETransactionVersion2.V3;
3676
+ return version === ETransactionVersion2.V3 || version === ETransactionVersion2.F3;
3677
+ }
3678
+ function isVersion(expected, provided) {
3679
+ const expectedParts = expected.split(".");
3680
+ const providedParts = provided.split(".");
3681
+ return expectedParts.every((part, index) => part === "*" || part === providedParts[index]);
3682
+ }
3683
+ function isSupportedSpecVersion(version, options = { allowAnyPatchVersion: false }) {
3684
+ return Object.values(_SupportedRpcVersion).some(
3685
+ (v) => isVersion(options.allowAnyPatchVersion ? toAnyPatchVersion(v) : v, version)
3686
+ );
3687
+ }
3688
+ function toAnyPatchVersion(version) {
3689
+ const parts = version.split(".");
3690
+ if (parts.length < 3) {
3691
+ return version;
3692
+ }
3693
+ return `${parts[0]}.${parts[1]}.*`;
3694
+ }
3695
+ function isPendingBlock(response) {
3696
+ return response.status === "PENDING";
3697
+ }
3698
+ function isPendingTransaction(response) {
3699
+ return !("block_hash" in response);
3700
+ }
3701
+ function isPendingStateUpdate(response) {
3702
+ return !("block_hash" in response);
3703
+ }
3704
+
3559
3705
  // src/utils/stark/rpc07.ts
3560
3706
  function estimateFeeToBounds(estimate, overhead) {
3561
3707
  const maxUnits = estimate.data_gas_consumed !== void 0 && estimate.data_gas_price !== void 0 ? toHex(
@@ -3595,49 +3741,6 @@ function estimateFeeToBounds2(estimate, overhead) {
3595
3741
  };
3596
3742
  }
3597
3743
 
3598
- // src/global/config.ts
3599
- var Configuration = class _Configuration {
3600
- static instance;
3601
- config;
3602
- constructor() {
3603
- this.initialize();
3604
- }
3605
- initialize() {
3606
- this.config = { ...DEFAULT_GLOBAL_CONFIG };
3607
- }
3608
- static getInstance() {
3609
- if (!_Configuration.instance) {
3610
- _Configuration.instance = new _Configuration();
3611
- }
3612
- return _Configuration.instance;
3613
- }
3614
- get(key, defaultValue) {
3615
- return this.config[key] ?? defaultValue;
3616
- }
3617
- set(key, value) {
3618
- this.config[key] = value;
3619
- }
3620
- update(configData) {
3621
- this.config = {
3622
- ...this.config,
3623
- ...configData
3624
- };
3625
- }
3626
- getAll() {
3627
- return { ...this.config };
3628
- }
3629
- reset() {
3630
- this.initialize();
3631
- }
3632
- delete(key) {
3633
- delete this.config[key];
3634
- }
3635
- hasKey(key) {
3636
- return key in this.config;
3637
- }
3638
- };
3639
- var config = Configuration.getInstance();
3640
-
3641
3744
  // src/utils/stark/index.ts
3642
3745
  function compressProgram(jsonProgram) {
3643
3746
  const stringified = isString(jsonProgram) ? jsonProgram : stringify2(jsonProgram);
@@ -3679,7 +3782,7 @@ function estimateFeeToBounds3(estimate, overhead = config.get("feeMarginPercenta
3679
3782
  return {
3680
3783
  l2_gas: { max_amount: "0x0", max_price_per_unit: "0x0" },
3681
3784
  l1_gas: { max_amount: "0x0", max_price_per_unit: "0x0" },
3682
- ...specVersion === "0.8" && {
3785
+ ...specVersion && isVersion("0.8", specVersion) && {
3683
3786
  l1_data_gas: { max_amount: "0x0", max_price_per_unit: "0x0" }
3684
3787
  }
3685
3788
  };
@@ -3778,6 +3881,102 @@ function contractClassResponseToLegacyCompiledContract(ccr) {
3778
3881
  return { ...contract, program: decompressProgram(contract.program) };
3779
3882
  }
3780
3883
 
3884
+ // src/utils/errors/rpc.ts
3885
+ var errorCodes = {
3886
+ FAILED_TO_RECEIVE_TXN: 1,
3887
+ NO_TRACE_AVAILABLE: 10,
3888
+ CONTRACT_NOT_FOUND: 20,
3889
+ ENTRYPOINT_NOT_FOUND: 21,
3890
+ BLOCK_NOT_FOUND: 24,
3891
+ INVALID_TXN_INDEX: 27,
3892
+ CLASS_HASH_NOT_FOUND: 28,
3893
+ TXN_HASH_NOT_FOUND: 29,
3894
+ PAGE_SIZE_TOO_BIG: 31,
3895
+ NO_BLOCKS: 32,
3896
+ INVALID_CONTINUATION_TOKEN: 33,
3897
+ TOO_MANY_KEYS_IN_FILTER: 34,
3898
+ CONTRACT_ERROR: 40,
3899
+ TRANSACTION_EXECUTION_ERROR: 41,
3900
+ STORAGE_PROOF_NOT_SUPPORTED: 42,
3901
+ CLASS_ALREADY_DECLARED: 51,
3902
+ INVALID_TRANSACTION_NONCE: 52,
3903
+ INSUFFICIENT_RESOURCES_FOR_VALIDATE: 53,
3904
+ INSUFFICIENT_ACCOUNT_BALANCE: 54,
3905
+ VALIDATION_FAILURE: 55,
3906
+ COMPILATION_FAILED: 56,
3907
+ CONTRACT_CLASS_SIZE_IS_TOO_LARGE: 57,
3908
+ NON_ACCOUNT: 58,
3909
+ DUPLICATE_TX: 59,
3910
+ COMPILED_CLASS_HASH_MISMATCH: 60,
3911
+ UNSUPPORTED_TX_VERSION: 61,
3912
+ UNSUPPORTED_CONTRACT_CLASS_VERSION: 62,
3913
+ UNEXPECTED_ERROR: 63,
3914
+ INVALID_SUBSCRIPTION_ID: 66,
3915
+ TOO_MANY_ADDRESSES_IN_FILTER: 67,
3916
+ TOO_MANY_BLOCKS_BACK: 68,
3917
+ COMPILATION_ERROR: 100,
3918
+ INVALID_ADDRESS: 150,
3919
+ TOKEN_NOT_SUPPORTED: 151,
3920
+ INVALID_SIGNATURE: 153,
3921
+ MAX_AMOUNT_TOO_LOW: 154,
3922
+ CLASS_HASH_NOT_SUPPORTED: 155,
3923
+ PAYMASTER_TRANSACTION_EXECUTION_ERROR: 156,
3924
+ INVALID_TIME_BOUNDS: 157,
3925
+ INVALID_DEPLOYMENT_DATA: 158,
3926
+ INVALID_CLASS_HASH: 159,
3927
+ INVALID_ID: 160,
3928
+ UNKNOWN_ERROR: 163
3929
+ };
3930
+ var rpc_default = errorCodes;
3931
+
3932
+ // src/utils/errors/index.ts
3933
+ function fixStack(target, fn = target.constructor) {
3934
+ const { captureStackTrace } = Error;
3935
+ captureStackTrace && captureStackTrace(target, fn);
3936
+ }
3937
+ function fixProto(target, prototype) {
3938
+ const { setPrototypeOf } = Object;
3939
+ setPrototypeOf ? setPrototypeOf(target, prototype) : target.__proto__ = prototype;
3940
+ }
3941
+ var CustomError = class extends Error {
3942
+ name;
3943
+ constructor(message) {
3944
+ super(message);
3945
+ Object.defineProperty(this, "name", {
3946
+ value: new.target.name,
3947
+ enumerable: false,
3948
+ configurable: true
3949
+ });
3950
+ fixProto(this, new.target.prototype);
3951
+ fixStack(this);
3952
+ }
3953
+ };
3954
+ var LibraryError = class extends CustomError {
3955
+ };
3956
+ var RpcError = class extends LibraryError {
3957
+ constructor(baseError, method, params) {
3958
+ super(`RPC: ${method} with params ${stringify2(params, null, 2)}
3959
+
3960
+ ${baseError.code}: ${baseError.message}: ${stringify2(baseError.data)}`);
3961
+ this.baseError = baseError;
3962
+ this.request = { method, params };
3963
+ }
3964
+ request;
3965
+ get code() {
3966
+ return this.baseError.code;
3967
+ }
3968
+ /**
3969
+ * Verifies the underlying RPC error, also serves as a type guard for the _baseError_ property
3970
+ * @example
3971
+ * ```typescript
3972
+ * SomeError.isType('UNEXPECTED_ERROR');
3973
+ * ```
3974
+ */
3975
+ isType(typeName) {
3976
+ return rpc_default[typeName] === this.code;
3977
+ }
3978
+ };
3979
+
3781
3980
  // src/utils/eth.ts
3782
3981
  var eth_exports = {};
3783
3982
  __export(eth_exports, {
@@ -3795,11 +3994,8 @@ function validateAndParseEthAddress(address) {
3795
3994
  return result;
3796
3995
  }
3797
3996
 
3798
- // src/utils/fetch.ts
3799
- var fetch_default = IS_BROWSER && window.fetch.bind(window) || // use built-in fetch in browser if available
3800
- !isUndefined(global) && global.fetch || // use built-in fetch in node, react-native and service worker if available
3801
- // throw with instructions when no fetch is detected
3802
- (() => {
3997
+ // src/utils/connect/fetch.ts
3998
+ var fetch_default = typeof globalThis !== "undefined" && globalThis.fetch.bind(globalThis) || typeof window !== "undefined" && window.fetch.bind(window) || typeof global !== "undefined" && global.fetch.bind(global) || (() => {
3803
3999
  throw new LibraryError(
3804
4000
  "'fetch()' not detected, use the 'baseFetch' constructor parameter to set it"
3805
4001
  );
@@ -3812,151 +4008,10 @@ __export(provider_exports, {
3812
4008
  createSierraContractClass: () => createSierraContractClass,
3813
4009
  getDefaultNodeUrl: () => getDefaultNodeUrl,
3814
4010
  getDefaultNodes: () => getDefaultNodes,
3815
- isPendingBlock: () => isPendingBlock,
3816
- isPendingStateUpdate: () => isPendingStateUpdate,
3817
- isPendingTransaction: () => isPendingTransaction,
3818
- isV3Tx: () => isV3Tx,
3819
- isVersion: () => isVersion,
3820
4011
  parseContract: () => parseContract,
3821
- stringToSpecVersion: () => stringToSpecVersion,
3822
4012
  validBlockTags: () => validBlockTags,
3823
4013
  wait: () => wait
3824
4014
  });
3825
-
3826
- // src/global/logger.type.ts
3827
- var LogLevelIndex = {
3828
- DEBUG: 5,
3829
- INFO: 4,
3830
- WARN: 3,
3831
- ERROR: 2,
3832
- FATAL: 1,
3833
- OFF: 0
3834
- };
3835
-
3836
- // src/global/logger.ts
3837
- var Logger = class _Logger {
3838
- static instance;
3839
- config;
3840
- constructor() {
3841
- this.config = config;
3842
- }
3843
- static getInstance() {
3844
- if (!_Logger.instance) {
3845
- _Logger.instance = new _Logger();
3846
- }
3847
- return _Logger.instance;
3848
- }
3849
- getTimestamp() {
3850
- return (/* @__PURE__ */ new Date()).toISOString();
3851
- }
3852
- shouldLog(messageLevel) {
3853
- const configLevel = this.config.get("logLevel", "INFO");
3854
- return messageLevel <= LogLevelIndex[configLevel];
3855
- }
3856
- formatMessage(logMessage) {
3857
- const { level, message, timestamp, data } = logMessage;
3858
- let formattedMessage = `[${timestamp}] ${level}: ${message}`;
3859
- if (data) {
3860
- try {
3861
- formattedMessage += `
3862
- ${JSON.stringify(data, null, 2)}`;
3863
- } catch (error) {
3864
- formattedMessage += `
3865
- [JSON.stringify Error/Circular]: ${error}`;
3866
- }
3867
- }
3868
- return formattedMessage;
3869
- }
3870
- log(level, message, data) {
3871
- if (!this.shouldLog(LogLevelIndex[level])) {
3872
- return;
3873
- }
3874
- const logMessage = {
3875
- level,
3876
- message,
3877
- timestamp: this.getTimestamp(),
3878
- data
3879
- };
3880
- const formattedMessage = this.formatMessage(logMessage);
3881
- switch (level) {
3882
- case "DEBUG":
3883
- console.debug(formattedMessage);
3884
- break;
3885
- case "INFO":
3886
- console.info(formattedMessage);
3887
- break;
3888
- case "WARN":
3889
- console.warn(formattedMessage);
3890
- break;
3891
- case "ERROR":
3892
- case "FATAL":
3893
- console.error(formattedMessage);
3894
- break;
3895
- case "OFF":
3896
- break;
3897
- default:
3898
- console.log(formattedMessage);
3899
- break;
3900
- }
3901
- }
3902
- /**
3903
- * debug will be displayed when LogLevel level is set to DEBUG(5)
3904
- */
3905
- debug(message, data) {
3906
- this.log("DEBUG", message, data);
3907
- }
3908
- /**
3909
- * info will be displayed when LogLevel level is set to DEBUG(5), INFO(4)
3910
- */
3911
- info(message, data) {
3912
- this.log("INFO", message, data);
3913
- }
3914
- /**
3915
- * warn will be displayed when LogLevel level is set to DEBUG(5), INFO(4), WARN(3)
3916
- */
3917
- warn(message, data) {
3918
- this.log("WARN", message, data);
3919
- }
3920
- /**
3921
- * error will be displayed when LogLevel level is set to DEBUG(5), INFO(4), WARN(3), ERROR(2)
3922
- */
3923
- error(message, data) {
3924
- this.log("ERROR", message, data);
3925
- }
3926
- /**
3927
- * fatal will be displayed when LogLevel level is set to DEBUG(5), INFO(4), WARN(3), ERROR(2), FATAL(1)
3928
- */
3929
- fatal(message, data) {
3930
- this.log("FATAL", message, data);
3931
- }
3932
- /**
3933
- * Set the logging level you would like system to display
3934
- * * 5 DEBUG - show all logs
3935
- * * 4 INFO
3936
- * * 3 WARN
3937
- * * 2 ERROR
3938
- * * 1 FATAL
3939
- * * 0 OFF - disable logs
3940
- */
3941
- setLogLevel(level) {
3942
- this.config.set("logLevel", level);
3943
- }
3944
- getLogLevel() {
3945
- return this.config.get("logLevel", "INFO");
3946
- }
3947
- /**
3948
- *
3949
- * @returns logs levels displayed on the configured LogLevel
3950
- */
3951
- getEnabledLogLevels() {
3952
- return Object.keys(LogLevelIndex).filter((s) => {
3953
- return this.shouldLog(LogLevelIndex[s]) && s !== "OFF";
3954
- });
3955
- }
3956
- };
3957
- var logger = Logger.getInstance();
3958
-
3959
- // src/utils/provider.ts
3960
4015
  function wait(delay) {
3961
4016
  return new Promise((res) => {
3962
4017
  setTimeout(res, delay);
@@ -4097,28 +4152,6 @@ var Block = class {
4097
4152
  valueOf = () => this.number;
4098
4153
  toString = () => this.hash;
4099
4154
  };
4100
- function isV3Tx(details) {
4101
- const version = details.version ? toHex(details.version) : ETransactionVersion2.V3;
4102
- return version === ETransactionVersion2.V3 || version === ETransactionVersion2.F3;
4103
- }
4104
- function isVersion(version, response) {
4105
- const [majorS, minorS] = version.split(".");
4106
- const [majorR, minorR] = response.split(".");
4107
- return majorS === majorR && minorS === minorR;
4108
- }
4109
- function stringToSpecVersion(version) {
4110
- const [major, minor] = version.split(".");
4111
- return `${major}.${minor}`;
4112
- }
4113
- function isPendingBlock(response) {
4114
- return response.status === "PENDING";
4115
- }
4116
- function isPendingTransaction(response) {
4117
- return !("block_hash" in response);
4118
- }
4119
- function isPendingStateUpdate(response) {
4120
- return !("block_hash" in response);
4121
- }
4122
4155
 
4123
4156
  // src/utils/transaction.ts
4124
4157
  var transaction_exports = {};
@@ -4211,14 +4244,18 @@ function getVersionsByType(versionType) {
4211
4244
  } : { v1: ETransactionVersion2.V1, v2: ETransactionVersion2.V2, v3: ETransactionVersion2.V3 };
4212
4245
  }
4213
4246
 
4214
- // src/channel/rpc_0_7.ts
4247
+ // src/channel/rpc_0_7_1.ts
4215
4248
  var defaultOptions = {
4216
4249
  headers: { "Content-Type": "application/json" },
4217
4250
  blockIdentifier: BlockTag.PENDING,
4218
4251
  retries: 200
4219
4252
  };
4220
4253
  var RpcChannel = class {
4221
- id = "RPC07";
4254
+ id = "RPC071";
4255
+ /**
4256
+ * RPC specification version this Channel class implements
4257
+ */
4258
+ channelSpecVersion = _SupportedRpcVersion.v0_7_1;
4222
4259
  nodeUrl;
4223
4260
  headers;
4224
4261
  requestId;
@@ -4227,6 +4264,9 @@ var RpcChannel = class {
4227
4264
  waitMode;
4228
4265
  // behave like web2 rpc and return when tx is processed
4229
4266
  chainId;
4267
+ /**
4268
+ * RPC specification version of the connected node
4269
+ */
4230
4270
  specVersion;
4231
4271
  transactionRetryIntervalFallback;
4232
4272
  batchClient;
@@ -4245,13 +4285,21 @@ var RpcChannel = class {
4245
4285
  waitMode
4246
4286
  } = optionsOrProvider || {};
4247
4287
  if (Object.values(_NetworkName).includes(nodeUrl)) {
4248
- this.nodeUrl = getDefaultNodeUrl(nodeUrl, optionsOrProvider?.default, "0.7");
4288
+ this.nodeUrl = getDefaultNodeUrl(
4289
+ nodeUrl,
4290
+ optionsOrProvider?.default,
4291
+ this.channelSpecVersion
4292
+ );
4249
4293
  } else if (nodeUrl) {
4250
4294
  this.nodeUrl = nodeUrl;
4251
4295
  } else {
4252
- this.nodeUrl = getDefaultNodeUrl(void 0, optionsOrProvider?.default, "0.7");
4296
+ this.nodeUrl = getDefaultNodeUrl(
4297
+ void 0,
4298
+ optionsOrProvider?.default,
4299
+ this.channelSpecVersion
4300
+ );
4253
4301
  }
4254
- this.baseFetch = baseFetch ?? fetch_default;
4302
+ this.baseFetch = baseFetch || config.get("fetch") || fetch_default;
4255
4303
  this.blockIdentifier = blockIdentifier ?? defaultOptions.blockIdentifier;
4256
4304
  this.chainId = chainId;
4257
4305
  this.headers = { ...defaultOptions.headers, ...headers };
@@ -4329,24 +4377,32 @@ var RpcChannel = class {
4329
4377
  return this.chainId;
4330
4378
  }
4331
4379
  /**
4332
- * fetch if undefined else just return this.specVersion
4333
- * return this.specVersion as 'M.m'
4334
- * @example this.specVersion = "0.8"
4380
+ * fetch rpc node specVersion
4381
+ * @example this.specVersion = "0.7.1"
4335
4382
  */
4336
- async getSpecVersion() {
4337
- if (!this.specVersion) {
4338
- const extendedVersion = await this.getSpecificationVersion();
4339
- const [major, minor] = extendedVersion.split(".");
4340
- const specVerson = `${major}.${minor}`;
4341
- this.specVersion ??= specVerson;
4342
- }
4343
- return this.specVersion;
4383
+ getSpecVersion() {
4384
+ return this.fetchEndpoint("starknet_specVersion");
4344
4385
  }
4345
4386
  /**
4346
- * fetch spec version in extended format "M.m.p-?"
4387
+ * fetch if undefined test and set specVersion, else just return this.specVersion
4388
+ * @example this.specVersion = "0.7.1"
4347
4389
  */
4348
- getSpecificationVersion() {
4349
- return this.fetchEndpoint("starknet_specVersion");
4390
+ async setUpSpecVersion() {
4391
+ if (!this.specVersion) {
4392
+ const unknownSpecVersion = await this.fetchEndpoint("starknet_specVersion");
4393
+ if (!isVersion(this.channelSpecVersion, unknownSpecVersion)) {
4394
+ logger.error(SYSTEM_MESSAGES.channelVersionMismatch, {
4395
+ channelId: this.id,
4396
+ channelSpecVersion: this.channelSpecVersion,
4397
+ nodeSpecVersion: this.specVersion
4398
+ });
4399
+ }
4400
+ if (!isSupportedSpecVersion(unknownSpecVersion)) {
4401
+ throw new LibraryError(`${SYSTEM_MESSAGES.unsupportedSpecVersion}, channelId: ${this.id}`);
4402
+ }
4403
+ this.specVersion = unknownSpecVersion;
4404
+ }
4405
+ return this.specVersion;
4350
4406
  }
4351
4407
  getNonceForAddress(contractAddress, blockIdentifier = this.blockIdentifier) {
4352
4408
  const contract_address = toHex(contractAddress);
@@ -4813,9 +4869,9 @@ var RpcChannel = class {
4813
4869
  }
4814
4870
  };
4815
4871
 
4816
- // src/channel/rpc_0_8.ts
4817
- var rpc_0_8_exports = {};
4818
- __export(rpc_0_8_exports, {
4872
+ // src/channel/rpc_0_8_1.ts
4873
+ var rpc_0_8_1_exports = {};
4874
+ __export(rpc_0_8_1_exports, {
4819
4875
  RpcChannel: () => RpcChannel2
4820
4876
  });
4821
4877
  var defaultOptions2 = {
@@ -4824,7 +4880,11 @@ var defaultOptions2 = {
4824
4880
  retries: 200
4825
4881
  };
4826
4882
  var RpcChannel2 = class {
4827
- id = "RPC08";
4883
+ id = "RPC081";
4884
+ /**
4885
+ * RPC specification version this Channel class implements
4886
+ */
4887
+ channelSpecVersion = _SupportedRpcVersion.v0_8_1;
4828
4888
  nodeUrl;
4829
4889
  headers;
4830
4890
  requestId;
@@ -4833,6 +4893,9 @@ var RpcChannel2 = class {
4833
4893
  waitMode;
4834
4894
  // behave like web2 rpc and return when tx is processed
4835
4895
  chainId;
4896
+ /**
4897
+ * RPC specification version of the connected node
4898
+ */
4836
4899
  specVersion;
4837
4900
  transactionRetryIntervalFallback;
4838
4901
  batchClient;
@@ -4851,13 +4914,21 @@ var RpcChannel2 = class {
4851
4914
  waitMode
4852
4915
  } = optionsOrProvider || {};
4853
4916
  if (Object.values(_NetworkName).includes(nodeUrl)) {
4854
- this.nodeUrl = getDefaultNodeUrl(nodeUrl, optionsOrProvider?.default, "0.8");
4917
+ this.nodeUrl = getDefaultNodeUrl(
4918
+ nodeUrl,
4919
+ optionsOrProvider?.default,
4920
+ this.channelSpecVersion
4921
+ );
4855
4922
  } else if (nodeUrl) {
4856
4923
  this.nodeUrl = nodeUrl;
4857
4924
  } else {
4858
- this.nodeUrl = getDefaultNodeUrl(void 0, optionsOrProvider?.default, "0.8");
4925
+ this.nodeUrl = getDefaultNodeUrl(
4926
+ void 0,
4927
+ optionsOrProvider?.default,
4928
+ this.channelSpecVersion
4929
+ );
4859
4930
  }
4860
- this.baseFetch = baseFetch ?? fetch_default;
4931
+ this.baseFetch = baseFetch || config.get("fetch") || fetch_default;
4861
4932
  this.blockIdentifier = blockIdentifier ?? defaultOptions2.blockIdentifier;
4862
4933
  this.chainId = chainId;
4863
4934
  this.headers = { ...defaultOptions2.headers, ...headers };
@@ -4933,6 +5004,34 @@ var RpcChannel2 = class {
4933
5004
  this.chainId ??= await this.fetchEndpoint("starknet_chainId");
4934
5005
  return this.chainId;
4935
5006
  }
5007
+ /**
5008
+ * fetch rpc node specVersion
5009
+ * @example this.specVersion = "0.7.1"
5010
+ */
5011
+ getSpecVersion() {
5012
+ return this.fetchEndpoint("starknet_specVersion");
5013
+ }
5014
+ /**
5015
+ * fetch if undefined else just return this.specVersion
5016
+ * @example this.specVersion = "0.8.1"
5017
+ */
5018
+ async setUpSpecVersion() {
5019
+ if (!this.specVersion) {
5020
+ const unknownSpecVersion = await this.fetchEndpoint("starknet_specVersion");
5021
+ if (!isVersion(this.channelSpecVersion, unknownSpecVersion)) {
5022
+ logger.error(SYSTEM_MESSAGES.channelVersionMismatch, {
5023
+ channelId: this.id,
5024
+ channelSpecVersion: this.channelSpecVersion,
5025
+ nodeSpecVersion: this.specVersion
5026
+ });
5027
+ }
5028
+ if (!isSupportedSpecVersion(unknownSpecVersion)) {
5029
+ throw new LibraryError(`${SYSTEM_MESSAGES.unsupportedSpecVersion}, channelId: ${this.id}`);
5030
+ }
5031
+ this.specVersion = unknownSpecVersion;
5032
+ }
5033
+ return this.specVersion;
5034
+ }
4936
5035
  // TODO: New Method add test
4937
5036
  /**
4938
5037
  * Given an l1 tx hash, returns the associated l1_handler tx hashes and statuses for all L1 -> L2 messages sent by the l1 transaction, ordered by the l1 tx sending order
@@ -4962,26 +5061,6 @@ var RpcChannel2 = class {
4962
5061
  class_hash
4963
5062
  });
4964
5063
  }
4965
- /**
4966
- * fetch if undefined else just return this.specVersion
4967
- * return this.specVersion as 'M.m'
4968
- * @example this.specVersion = "0.8"
4969
- */
4970
- async getSpecVersion() {
4971
- if (!this.specVersion) {
4972
- const extendedVersion = await this.getSpecificationVersion();
4973
- const [major, minor] = extendedVersion.split(".");
4974
- const specVerson = `${major}.${minor}`;
4975
- this.specVersion ??= specVerson;
4976
- }
4977
- return this.specVersion;
4978
- }
4979
- /**
4980
- * fetch spec version in extended format "M.m.p-?"
4981
- */
4982
- getSpecificationVersion() {
4983
- return this.fetchEndpoint("starknet_specVersion");
4984
- }
4985
5064
  getNonceForAddress(contractAddress, blockIdentifier = this.blockIdentifier) {
4986
5065
  const contract_address = toHex(contractAddress);
4987
5066
  const block_id = new Block(blockIdentifier).identifier;
@@ -5363,8 +5442,16 @@ var RpcChannel2 = class {
5363
5442
  }
5364
5443
  };
5365
5444
 
5445
+ // src/utils/connect/ws.ts
5446
+ var ws_default = typeof WebSocket !== "undefined" && WebSocket || typeof globalThis !== "undefined" && globalThis.WebSocket || typeof window !== "undefined" && window.WebSocket.bind(window) || typeof global !== "undefined" && global.WebSocket || class {
5447
+ constructor() {
5448
+ throw new LibraryError(
5449
+ "WebSocket module not detected, use the 'websocket' constructor parameter to set a compatible connection"
5450
+ );
5451
+ }
5452
+ };
5453
+
5366
5454
  // src/channel/ws_0_8.ts
5367
- var import_isows = require("isows");
5368
5455
  var WSSubscriptions = {
5369
5456
  NEW_HEADS: "newHeads",
5370
5457
  EVENTS: "events",
@@ -5489,7 +5576,7 @@ var WebSocketChannel = class {
5489
5576
  constructor(options = {}) {
5490
5577
  const nodeUrl = options.nodeUrl || "http://localhost:3000 ";
5491
5578
  this.nodeUrl = options.websocket ? options.websocket.url : nodeUrl;
5492
- this.websocket = options.websocket ? options.websocket : new import_isows.WebSocket(nodeUrl);
5579
+ this.websocket = options.websocket || config.get("websocket") || new ws_default(nodeUrl);
5493
5580
  this.websocket.addEventListener("open", this.onOpen.bind(this));
5494
5581
  this.websocket.addEventListener("close", this.onCloseProxy.bind(this));
5495
5582
  this.websocket.addEventListener("message", this.onMessageProxy.bind(this));
@@ -5558,7 +5645,7 @@ var WebSocketChannel = class {
5558
5645
  * Helper to check connection is open
5559
5646
  */
5560
5647
  isConnected() {
5561
- return this.websocket.readyState === import_isows.WebSocket.OPEN;
5648
+ return this.websocket.readyState === ws_default.OPEN;
5562
5649
  }
5563
5650
  /**
5564
5651
  * await while websocket is connected
@@ -5569,7 +5656,7 @@ var WebSocketChannel = class {
5569
5656
  * ```
5570
5657
  */
5571
5658
  async waitForConnection() {
5572
- if (this.websocket.readyState !== import_isows.WebSocket.OPEN) {
5659
+ if (this.websocket.readyState !== ws_default.OPEN) {
5573
5660
  return new Promise((resolve, reject) => {
5574
5661
  if (!this.websocket) return;
5575
5662
  this.websocket.onopen = () => resolve(this.websocket.readyState);
@@ -5594,7 +5681,7 @@ var WebSocketChannel = class {
5594
5681
  * ```
5595
5682
  */
5596
5683
  async waitForDisconnection() {
5597
- if (this.websocket.readyState !== import_isows.WebSocket.CLOSED) {
5684
+ if (this.websocket.readyState !== ws_default.CLOSED) {
5598
5685
  return new Promise((resolve, reject) => {
5599
5686
  if (!this.websocket) return;
5600
5687
  this.websocket.onclose = () => resolve(this.websocket.readyState);
@@ -5647,7 +5734,7 @@ var WebSocketChannel = class {
5647
5734
  * Reconnect re-create this.websocket instance
5648
5735
  */
5649
5736
  reconnect() {
5650
- this.websocket = new import_isows.WebSocket(this.nodeUrl);
5737
+ this.websocket = new ws_default(this.nodeUrl);
5651
5738
  this.websocket.addEventListener("open", this.onOpen.bind(this));
5652
5739
  this.websocket.addEventListener("close", this.onCloseProxy.bind(this));
5653
5740
  this.websocket.addEventListener("message", this.onMessageProxy.bind(this));
@@ -6372,15 +6459,15 @@ var RpcProvider = class {
6372
6459
  } else {
6373
6460
  if (optionsOrProvider && optionsOrProvider.specVersion) {
6374
6461
  if (isVersion("0.8", optionsOrProvider.specVersion)) {
6375
- this.channel = new rpc_0_8_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6462
+ this.channel = new rpc_0_8_1_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6376
6463
  } else if (isVersion("0.7", optionsOrProvider.specVersion)) {
6377
- this.channel = new rpc_0_7_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6464
+ this.channel = new rpc_0_7_1_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6378
6465
  } else
6379
6466
  throw new Error(`unsupported channel for spec version: ${optionsOrProvider.specVersion}`);
6380
6467
  } else if (isVersion("0.8", config.get("rpcVersion"))) {
6381
- this.channel = new rpc_0_8_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6468
+ this.channel = new rpc_0_8_1_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6382
6469
  } else if (isVersion("0.7", config.get("rpcVersion"))) {
6383
- this.channel = new rpc_0_7_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6470
+ this.channel = new rpc_0_7_1_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6384
6471
  } else throw new Error("unable to define spec version for channel");
6385
6472
  this.responseParser = new RPCResponseParser(optionsOrProvider?.feeMarginPercentage);
6386
6473
  }
@@ -6391,15 +6478,26 @@ var RpcProvider = class {
6391
6478
  */
6392
6479
  // NOTE: the generic T and 'this' reference are used so that the expanded class is generated when a mixin is applied
6393
6480
  static async create(optionsOrProvider) {
6394
- const channel = new rpc_0_7_exports.RpcChannel({ ...optionsOrProvider });
6481
+ const channel = new rpc_0_7_1_exports.RpcChannel({ ...optionsOrProvider });
6395
6482
  const spec = await channel.getSpecVersion();
6483
+ if (!isSupportedSpecVersion(spec)) {
6484
+ logger.warn(`Using incompatible node spec version ${spec}`);
6485
+ }
6396
6486
  if (isVersion("0.7", spec)) {
6397
- return new this({ ...optionsOrProvider, specVersion: "0.7" });
6487
+ return new this({
6488
+ ...optionsOrProvider,
6489
+ specVersion: _SupportedRpcVersion.v0_7_1
6490
+ });
6398
6491
  }
6399
6492
  if (isVersion("0.8", spec)) {
6400
- return new this({ ...optionsOrProvider, specVersion: "0.8" });
6493
+ return new this({
6494
+ ...optionsOrProvider,
6495
+ specVersion: _SupportedRpcVersion.v0_8_1
6496
+ });
6401
6497
  }
6402
- throw new LibraryError("Unable to detect specification version");
6498
+ throw new LibraryError(
6499
+ `Provided RPC node specification version ${spec} is not compatible with the SDK. SDK supported RPC versions ${Object.keys(_SupportedRpcVersion).toString()}`
6500
+ );
6403
6501
  }
6404
6502
  fetch(method, params, id = 0) {
6405
6503
  return this.channel.fetch(method, params, id);
@@ -6408,16 +6506,22 @@ var RpcProvider = class {
6408
6506
  return this.channel.getChainId();
6409
6507
  }
6410
6508
  /**
6411
- * return spec version in format "M.m"
6509
+ * read channel spec version
6510
+ */
6511
+ readSpecVersion() {
6512
+ return this.channel.readSpecVersion();
6513
+ }
6514
+ /**
6515
+ * get channel spec version
6412
6516
  */
6413
6517
  async getSpecVersion() {
6414
6518
  return this.channel.getSpecVersion();
6415
6519
  }
6416
6520
  /**
6417
- * @returns return spec version in format 'M.m.p-rc'
6521
+ * setup channel spec version and return it
6418
6522
  */
6419
- async getSpecificationVersion() {
6420
- return this.channel.getSpecificationVersion();
6523
+ setUpSpecVersion() {
6524
+ return this.channel.setUpSpecVersion();
6421
6525
  }
6422
6526
  async getNonceForAddress(contractAddress, blockIdentifier) {
6423
6527
  return this.channel.getNonceForAddress(contractAddress, blockIdentifier);
@@ -6782,18 +6886,18 @@ var RpcProvider = class {
6782
6886
  /**
6783
6887
  * Given an l1 tx hash, returns the associated l1_handler tx hashes and statuses for all L1 -> L2 messages sent by the l1 transaction, ordered by the l1 tx sending order
6784
6888
  */
6785
- getL1MessagesStatus(transactionHash) {
6786
- if (this.channel instanceof rpc_0_8_exports.RpcChannel) {
6787
- this.channel.getMessagesStatus(transactionHash);
6889
+ async getL1MessagesStatus(transactionHash) {
6890
+ if (this.channel instanceof rpc_0_8_1_exports.RpcChannel) {
6891
+ return this.channel.getMessagesStatus(transactionHash);
6788
6892
  }
6789
6893
  throw new LibraryError("Unsupported method for RPC version");
6790
6894
  }
6791
6895
  /**
6792
6896
  * Get merkle paths in one of the state tries: global state, classes, individual contract
6793
6897
  */
6794
- getStorageProof(classHashes, contractAddresses, contractsStorageKeys, blockIdentifier) {
6795
- if (this.channel instanceof rpc_0_8_exports.RpcChannel) {
6796
- this.channel.getStorageProof(
6898
+ async getStorageProof(classHashes, contractAddresses, contractsStorageKeys, blockIdentifier) {
6899
+ if (this.channel instanceof rpc_0_8_1_exports.RpcChannel) {
6900
+ return this.channel.getStorageProof(
6797
6901
  classHashes,
6798
6902
  contractAddresses,
6799
6903
  contractsStorageKeys,
@@ -6805,9 +6909,9 @@ var RpcProvider = class {
6805
6909
  /**
6806
6910
  * Get the contract class definition in the given block associated with the given hash
6807
6911
  */
6808
- getCompiledCasm(classHash) {
6809
- if (this.channel instanceof rpc_0_8_exports.RpcChannel) {
6810
- this.channel.getCompiledCasm(classHash);
6912
+ async getCompiledCasm(classHash) {
6913
+ if (this.channel instanceof rpc_0_8_1_exports.RpcChannel) {
6914
+ return this.channel.getCompiledCasm(classHash);
6811
6915
  }
6812
6916
  throw new LibraryError("Unsupported method for RPC version");
6813
6917
  }
@@ -7887,7 +7991,7 @@ var LedgerSigner221 = class extends LedgerSigner111 {
7887
7991
  const ledgerResponse = await this.signTxV1(det, transactions);
7888
7992
  assert(
7889
7993
  toBigInt(msgHash) === ledgerResponse.hash,
7890
- "The transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
7994
+ "The V1 transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
7891
7995
  );
7892
7996
  return ledgerResponse.signature;
7893
7997
  }
@@ -7904,7 +8008,7 @@ var LedgerSigner221 = class extends LedgerSigner111 {
7904
8008
  const ledgerResponse = await this.signTxV3(det, transactions);
7905
8009
  assert(
7906
8010
  toBigInt(msgHash) === ledgerResponse.hash,
7907
- "The transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
8011
+ "The V3 transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
7908
8012
  );
7909
8013
  return ledgerResponse.signature;
7910
8014
  }
@@ -7985,25 +8089,369 @@ var LedgerSigner221 = class extends LedgerSigner111 {
7985
8089
  * @param {Call} call A Call to convert.
7986
8090
  * @return {Uint8Array[]} Call encoded in an array of Uint8Array (each containing 7 u256).
7987
8091
  */
7988
- encodeCall(call) {
7989
- const toBuf = this.convertBnToLedger(call.contractAddress);
7990
- const selectorBuf = hexToBytes(addAddressPadding(getSelector(call.entrypoint)));
7991
- let calldataBuf = new Uint8Array([]);
7992
- if (call.calldata) {
7993
- const compiledCalldata = CallData.compile(call.calldata);
7994
- calldataBuf = concatenateArrayBuffer(
7995
- compiledCalldata.map((parameter) => {
7996
- const a = this.convertBnToLedger(parameter);
7997
- return a;
7998
- })
7999
- );
8000
- }
8001
- const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
8002
- const calldatas = [];
8003
- const chunkSize = 7 * 32;
8004
- for (let i = 0; i < callBuf.length; i += chunkSize)
8005
- calldatas.push(callBuf.subarray(i, i + chunkSize));
8006
- return calldatas;
8092
+ encodeCall(call) {
8093
+ const toBuf = this.convertBnToLedger(call.contractAddress);
8094
+ const selectorBuf = hexToBytes(addAddressPadding(getSelector(call.entrypoint)));
8095
+ let calldataBuf = new Uint8Array([]);
8096
+ if (call.calldata) {
8097
+ const compiledCalldata = CallData.compile(call.calldata);
8098
+ calldataBuf = concatenateArrayBuffer(
8099
+ compiledCalldata.map((parameter) => {
8100
+ const a = this.convertBnToLedger(parameter);
8101
+ return a;
8102
+ })
8103
+ );
8104
+ }
8105
+ const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
8106
+ const calldatas = [];
8107
+ const chunkSize = 7 * 32;
8108
+ for (let i = 0; i < callBuf.length; i += chunkSize)
8109
+ calldatas.push(callBuf.subarray(i, i + chunkSize));
8110
+ return calldatas;
8111
+ }
8112
+ /**
8113
+ * Ask the Ledger Nano to display and sign a Starknet V1 transaction.
8114
+ * @param {V2InvocationsSignerDetails} txDetails All the details needed for a txV1.
8115
+ * @param {Call[]} calls array of Starknet invocations
8116
+ * @returns an object including the transaction Hash and the signature
8117
+ * @example
8118
+ * ```typescript
8119
+ * const calls: Call[] = [{contractAddress: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
8120
+ * entrypoint: "transfer",
8121
+ * calldata:["0x11f5fc2a92ac03434a7937fe982f5e5293b65ad438a989c5b78fb8f04a12016",
8122
+ * "0x9184e72a000", "0x0"]}];
8123
+ * const txDet: V2InvocationsSignerDetails = {
8124
+ * walletAddress: txDetails.accountAddress,
8125
+ * chainId: constants.StarknetChainId.SN_MAIN,
8126
+ * cairoVersion: "1", maxFee: txDetails.max_fee,
8127
+ * nonce: txDetails.nonce, version: "0x1"
8128
+ * };
8129
+ * const res = await myLedgerSigner.signTxV1(txDet, calls);
8130
+ * // res = {hash:
8131
+ * // signature:
8132
+ * // }
8133
+ * ```
8134
+ */
8135
+ async signTxV1(txDetails, calls) {
8136
+ await this._transporter.send(Number("0x5a"), 4, 0, 0, Buffer.from(this.pathBuffer));
8137
+ const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
8138
+ const maxFeeBuf = this.convertBnToLedger(txDetails.maxFee);
8139
+ const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
8140
+ const nonceBuf = this.convertBnToLedger(txDetails.nonce);
8141
+ const dataBuf = concatenateArrayBuffer([
8142
+ accountAddressBuf,
8143
+ maxFeeBuf,
8144
+ chainIdBuf,
8145
+ nonceBuf
8146
+ ]);
8147
+ await this._transporter.send(Number("0x5a"), 4, 1, 0, Buffer.from(dataBuf));
8148
+ const nbCallsBuf = this.convertBnToLedger(calls.length);
8149
+ await this._transporter.send(Number("0x5a"), 4, 2, 0, Buffer.from(nbCallsBuf));
8150
+ let respSign = new Uint8Array(0);
8151
+ for (const call of calls) {
8152
+ const calldatas = this.encodeCall(call);
8153
+ await this._transporter.send(Number("0x5a"), 4, 3, 0, Buffer.from(calldatas[0]));
8154
+ if (calldatas.length > 1) {
8155
+ calldatas.slice(1).forEach(async (part) => {
8156
+ await this._transporter.send(Number("0x5a"), 4, 3, 1, Buffer.from(part));
8157
+ });
8158
+ }
8159
+ respSign = await this._transporter.send(Number("0x5a"), 4, 3, 2);
8160
+ }
8161
+ return this.decodeSignatureLedger(respSign);
8162
+ }
8163
+ /**
8164
+ * Ask to the Ledger Nano to display and sign a Starknet V3 transaction.
8165
+ * @param {V3InvocationsSignerDetails} txDetails All the details needed for a txV3.
8166
+ * @param {Call[]} calls array of Starknet invocations
8167
+ * @returns an object including the transaction Hash and the signature
8168
+ * @example
8169
+ * ```typescript
8170
+ * const calls: Call[] = [{contractAddress: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
8171
+ * entrypoint: "transfer",
8172
+ * calldata:["0x11f5fc2a92ac03434a7937fe982f5e5293b65ad438a989c5b78fb8f04a12016",
8173
+ * "0x9184e72a000", "0x0"]}];
8174
+ * const txDetailsV3: V3InvocationsSignerDetails = {
8175
+ * chainId: constants.StarknetChainId.SN_MAIN,
8176
+ * nonce: "28", accountDeploymentData: [],
8177
+ * paymasterData: [], cairoVersion: "1",
8178
+ * feeDataAvailabilityMode: "L1", nonceDataAvailabilityMode: "L1",
8179
+ * resourceBounds: {
8180
+ * l1_gas: { max_amount: "0x2a00", max_price_per_unit: "0x5c00000"
8181
+ * },
8182
+ * l2_gas: { max_amount: "0x00", max_price_per_unit: "0x00"},
8183
+ * }, tip: 0, version: "0x3", walletAddress: account0.address
8184
+ * };
8185
+ * const res = await myLedgerSigner.signTxV3(txDetailsV3, calls);
8186
+ * // res = {hash:
8187
+ * // signature:
8188
+ * // }
8189
+ * ```
8190
+ */
8191
+ async signTxV3(txDetails, calls) {
8192
+ assert(txDetails.paymasterData.length <= 7, "Paymaster data includes more than 7 items.");
8193
+ assert(
8194
+ txDetails.accountDeploymentData.length <= 7,
8195
+ "accountDeploymentData includes more than 7 items"
8196
+ );
8197
+ await this._transporter.send(Number("0x5a"), 3, 0, 0, Buffer.from(this.pathBuffer));
8198
+ const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
8199
+ const tipBuf = this.convertBnToLedger(txDetails.tip);
8200
+ const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
8201
+ const nonceBuf = this.convertBnToLedger(txDetails.nonce);
8202
+ const dAModeHashBuf = this.convertBnToLedger(
8203
+ hashDAMode(
8204
+ txDetails.nonceDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2,
8205
+ txDetails.feeDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2
8206
+ )
8207
+ );
8208
+ const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
8209
+ const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
8210
+ const dataBuf = concatenateArrayBuffer([
8211
+ accountAddressBuf,
8212
+ tipBuf,
8213
+ l1_gasBuf,
8214
+ l2_gasBuf,
8215
+ chainIdBuf,
8216
+ nonceBuf,
8217
+ dAModeHashBuf
8218
+ ]);
8219
+ await this._transporter.send(Number("0x5a"), 3, 1, 0, Buffer.from(dataBuf));
8220
+ const paymasterBuf = concatenateArrayBuffer(
8221
+ txDetails.paymasterData.map((value) => {
8222
+ const a = this.convertBnToLedger(value);
8223
+ return a;
8224
+ })
8225
+ );
8226
+ await this._transporter.send(Number("0x5a"), 3, 2, 0, Buffer.from(paymasterBuf));
8227
+ const accountDeployDataBuf = concatenateArrayBuffer(
8228
+ txDetails.paymasterData.map((value) => {
8229
+ const a = this.convertBnToLedger(value);
8230
+ return a;
8231
+ })
8232
+ );
8233
+ await this._transporter.send(Number("0x5a"), 3, 3, 0, Buffer.from(accountDeployDataBuf));
8234
+ const nbCallsBuf = this.convertBnToLedger(calls.length);
8235
+ await this._transporter.send(Number("0x5a"), 3, 4, 0, Buffer.from(nbCallsBuf));
8236
+ let respSign = new Uint8Array(0);
8237
+ for (const call of calls) {
8238
+ const calldatas = this.encodeCall(call);
8239
+ await this._transporter.send(Number("0x5a"), 3, 5, 0, Buffer.from(calldatas[0]));
8240
+ if (calldatas.length > 1) {
8241
+ calldatas.slice(1).forEach(async (part) => {
8242
+ await this._transporter.send(Number("0x5a"), 3, 5, 1, Buffer.from(part));
8243
+ });
8244
+ }
8245
+ respSign = await this._transporter.send(Number("0x5a"), 3, 5, 2);
8246
+ }
8247
+ return this.decodeSignatureLedger(respSign);
8248
+ }
8249
+ /**
8250
+ * Ask the Ledger Nano to display and sign a Starknet V1 account deployment.
8251
+ * @param {V2DeployAccountSignerDetails} deployAccountDetail All the details needed for a V1 deploy account.
8252
+ * @returns an object including the transaction Hash and the signature
8253
+ * @example
8254
+ * ```typescript
8255
+ * const deployData: V2DeployAccountSignerDetails =
8256
+ * {
8257
+ * tip: 0, paymasterData: [], accountDeploymentData: [],
8258
+ * nonceDataAvailabilityMode: 'L1', feeDataAvailabilityMode: 'L1',
8259
+ * resourceBounds: {
8260
+ * l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' },
8261
+ * l1_gas: { max_amount: '0x0', max_price_per_unit: '0x0' }
8262
+ * },
8263
+ * classHash: '0x540d7f5ec7ecf317e68d48564934cb99259781b1ee3cedbbc37ec5337f8e688',
8264
+ * constructorCalldata: [
8265
+ * '89832696000889662999767022750851886674077821293893187900664573372145410755'
8266
+ * ],
8267
+ * contractAddress: '0x32c60fba64eb96831d064bbb2319375b7b7381543abe66da872e4344bcd72a0',
8268
+ * addressSalt: '0x0032d7efe2a9232f9b463e7206c68fdea4aeb13fec0cb308c6ba1d197d5922c3',
8269
+ * chainId: '0x534e5f5345504f4c4941', maxFee: 55050000000000n,
8270
+ * version: '0x1', nonce: 0n
8271
+ *}
8272
+ * const res = await myLedgerSigner.signDeployAccountV1(deployData);
8273
+ * // res = {hash:
8274
+ * // signature:
8275
+ * // }
8276
+ * ```
8277
+ */
8278
+ async signDeployAccountV1(deployAccountDetail) {
8279
+ await this._transporter.send(Number("0x5a"), 6, 0, 0, Buffer.from(this.pathBuffer));
8280
+ const accountAddressBuf = this.convertBnToLedger(
8281
+ deployAccountDetail.contractAddress
8282
+ );
8283
+ const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
8284
+ const saltBuf = this.convertBnToLedger(deployAccountDetail.addressSalt);
8285
+ const chainIdBuf = this.convertBnToLedger(deployAccountDetail.chainId);
8286
+ const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
8287
+ const dataBuf = concatenateArrayBuffer([
8288
+ accountAddressBuf,
8289
+ classHashBuf,
8290
+ saltBuf,
8291
+ chainIdBuf,
8292
+ nonceBuf
8293
+ ]);
8294
+ await this._transporter.send(Number("0x5a"), 6, 1, 0, Buffer.from(dataBuf));
8295
+ const maxFreeBuf = this.convertBnToLedger(deployAccountDetail.maxFee);
8296
+ await this._transporter.send(Number("0x5a"), 6, 2, 0, Buffer.from(maxFreeBuf));
8297
+ const compiledConstructor = CallData.compile(deployAccountDetail.constructorCalldata);
8298
+ const constructorLengthBuf = this.convertBnToLedger(compiledConstructor.length);
8299
+ await this._transporter.send(Number("0x5a"), 6, 3, 0, Buffer.from(constructorLengthBuf));
8300
+ const constructorBuf = concatenateArrayBuffer(
8301
+ compiledConstructor.map((parameter) => {
8302
+ const a = this.convertBnToLedger(parameter);
8303
+ return a;
8304
+ })
8305
+ );
8306
+ const constructorChunks = [];
8307
+ const chunkSize = 7 * 32;
8308
+ for (let i = 0; i < constructorBuf.length; i += chunkSize)
8309
+ constructorChunks.push(constructorBuf.subarray(i, i + chunkSize));
8310
+ let respSign = new Uint8Array(0);
8311
+ for (const chunk of constructorChunks) {
8312
+ respSign = await this._transporter.send(Number("0x5a"), 6, 4, 0, Buffer.from(chunk));
8313
+ }
8314
+ return this.decodeSignatureLedger(respSign);
8315
+ }
8316
+ /**
8317
+ *Ask the Ledger Nano to display and sign a Starknet V3 account deployment.
8318
+ * @param {V3DeployAccountSignerDetails} deployAccountDetail All the details needed for a V3 deploy account.
8319
+ * @returns an object including the transaction Hash and the signature
8320
+ * @example
8321
+ * ```typescript
8322
+ * const deployData: V3DeployAccountSignerDetails =
8323
+ * {
8324
+ * tip: 0, paymasterData: [], accountDeploymentData: [],
8325
+ * nonceDataAvailabilityMode: 'L1', feeDataAvailabilityMode: 'L1',
8326
+ * resourceBounds: {
8327
+ * l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' },
8328
+ * l1_gas: { max_amount: '0x226', max_price_per_unit: '0x22ecb25c00' }
8329
+ * },
8330
+ * classHash: '0x540d7f5ec7ecf317e68d48564934cb99259781b1ee3cedbbc37ec5337f8e688',
8331
+ * constructorCalldata: [
8332
+ * '3571125127744830445572285574469842579401255431821644822726857471463672199621'
8333
+ * ],
8334
+ * contractAddress: '0x4ca062add1cf12a107be1107af17981cf6e544a24d987693230ea481d3d5e34',
8335
+ * addressSalt: '0x07e52f68e3160e1ef698211cdf6d3792368fe347e7e2d4a8ace14d9b248f39c5',
8336
+ * chainId: '0x534e5f5345504f4c4941', maxFee: 0,
8337
+ * version: '0x3', nonce: 0n
8338
+ *}
8339
+ * const res = await myLedgerSigner.signDeployAccountV3(deployData);
8340
+ * // res = {hash:
8341
+ * // signature:
8342
+ * // }
8343
+ * ```
8344
+ */
8345
+ async signDeployAccountV3(deployAccountDetail) {
8346
+ await this._transporter.send(Number("0x5a"), 5, 0, 0, Buffer.from(this.pathBuffer));
8347
+ const accountAddressBuf = this.convertBnToLedger(
8348
+ deployAccountDetail.contractAddress
8349
+ );
8350
+ const chainIdBuf = this.convertBnToLedger(deployAccountDetail.chainId);
8351
+ const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
8352
+ const dAModeHashBuf = this.convertBnToLedger(
8353
+ hashDAMode(
8354
+ deployAccountDetail.nonceDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2,
8355
+ deployAccountDetail.feeDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2
8356
+ )
8357
+ );
8358
+ const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
8359
+ const saltBuf = this.convertBnToLedger(deployAccountDetail.addressSalt);
8360
+ const dataBuf = concatenateArrayBuffer([
8361
+ accountAddressBuf,
8362
+ chainIdBuf,
8363
+ nonceBuf,
8364
+ dAModeHashBuf,
8365
+ classHashBuf,
8366
+ saltBuf
8367
+ ]);
8368
+ await this._transporter.send(Number("0x5a"), 5, 1, 0, Buffer.from(dataBuf));
8369
+ const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
8370
+ const l1_gasBuf = this.convertBnToLedger(
8371
+ encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
8372
+ );
8373
+ const l2_gasBuf = this.convertBnToLedger(
8374
+ encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
8375
+ );
8376
+ const feeBuf = concatenateArrayBuffer([tipBuf, l1_gasBuf, l2_gasBuf]);
8377
+ await this._transporter.send(Number("0x5a"), 5, 2, 0, Buffer.from(feeBuf));
8378
+ const paymasterBuf = concatenateArrayBuffer(
8379
+ deployAccountDetail.paymasterData.map((value) => {
8380
+ const a = this.convertBnToLedger(value);
8381
+ return a;
8382
+ })
8383
+ );
8384
+ await this._transporter.send(Number("0x5a"), 5, 3, 0, Buffer.from(paymasterBuf));
8385
+ const compiledConstructor = CallData.compile(deployAccountDetail.constructorCalldata);
8386
+ const constructorLengthBuf = this.convertBnToLedger(compiledConstructor.length);
8387
+ await this._transporter.send(Number("0x5a"), 5, 4, 0, Buffer.from(constructorLengthBuf));
8388
+ const constructorBuf = concatenateArrayBuffer(
8389
+ compiledConstructor.map((parameter) => {
8390
+ const a = this.convertBnToLedger(parameter);
8391
+ return a;
8392
+ })
8393
+ );
8394
+ const constructorChunks = [];
8395
+ const chunkSize = 7 * 32;
8396
+ for (let i = 0; i < constructorBuf.length; i += chunkSize)
8397
+ constructorChunks.push(constructorBuf.subarray(i, i + chunkSize));
8398
+ let respSign = new Uint8Array(0);
8399
+ for (const chunk of constructorChunks) {
8400
+ respSign = await this._transporter.send(Number("0x5a"), 5, 5, 0, Buffer.from(chunk));
8401
+ }
8402
+ return this.decodeSignatureLedger(respSign);
8403
+ }
8404
+ };
8405
+ function getLedgerPathBuffer221(accountId, applicationName = "LedgerW") {
8406
+ const path0buff = new Uint8Array([HARDENING_BYTE, 0, 10, 85]);
8407
+ const path1buff = new Uint8Array([71 | HARDENING_BYTE, 65, 233, 201]);
8408
+ const path2Base = applicationName === "LedgerW" ? new Uint8Array([43, 206, 231, 219]) : stringToSha256ToArrayBuff4(applicationName);
8409
+ const path2buff = concatenateArrayBuffer([
8410
+ new Uint8Array([path2Base[0] | HARDENING_BYTE]),
8411
+ path2Base.subarray(1)
8412
+ ]);
8413
+ const path3buff = new Uint8Array([HARDENING_BYTE, 0, 0, 0]);
8414
+ const hex = toHex(BigInt(accountId) | HARDENING_4BYTES);
8415
+ const padded = addHexPrefix(removeHexPrefix(hex).padStart(8, "0"));
8416
+ const path4buff = hexToBytes(padded);
8417
+ const path5buff = new Uint8Array([0, 0, 0, 0]);
8418
+ const pathBuff = concatenateArrayBuffer([
8419
+ path0buff,
8420
+ path1buff,
8421
+ path2buff,
8422
+ path3buff,
8423
+ path4buff,
8424
+ path5buff
8425
+ ]);
8426
+ return pathBuff;
8427
+ }
8428
+
8429
+ // src/signer/ledgerSigner231.ts
8430
+ var LedgerSigner231 = class extends LedgerSigner221 {
8431
+ /**
8432
+ * constructor of the LedgerSigner class.
8433
+ * @param {Transport} transport 5 transports are available to handle USB, bluetooth, Node, Web, Mobile.
8434
+ * See Guides for more details.
8435
+ * @param {number} accountID ID of Ledger Nano account (can handle 2**31 accounts).
8436
+ * @param {string} [eip2645application='LedgerW'] A wallet is defined by an ERC2645 derivation path (6 items).
8437
+ * One item is called `application` and can be customized.
8438
+ * Default value is `LedgerW`.
8439
+ * @param {LedgerPathCalculation} [pathFunction=getLedgerPathBuffer221]
8440
+ * defines the function that will calculate the path. By default `getLedgerPathBuffer221` is selected.
8441
+ *
8442
+ * If you are using APP v2.3.1 with an account created with the v1.1.1, you need to use :
8443
+ * ```typescript
8444
+ * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0, undefined, getLedgerPathBuffer111);
8445
+ * ```
8446
+ * @example
8447
+ * ```typescript
8448
+ * import TransportNodeHid from "@ledgerhq/hw-transport-node-hid";
8449
+ * const myNodeTransport = await TransportNodeHid.create();
8450
+ * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0);
8451
+ * ```
8452
+ */
8453
+ constructor(transport, accountID, eip2645application = "LedgerW", pathFunction = getLedgerPathBuffer221) {
8454
+ super(transport, accountID, eip2645application, pathFunction);
8007
8455
  }
8008
8456
  /**
8009
8457
  * Ask the Ledger Nano to display and sign a Starknet V1 transaction.
@@ -8046,18 +8494,17 @@ var LedgerSigner221 = class extends LedgerSigner111 {
8046
8494
  let respSign = new Uint8Array(0);
8047
8495
  for (const call of calls) {
8048
8496
  const calldatas = this.encodeCall(call);
8049
- await this._transporter.send(Number("0x5a"), 4, 3, 0, Buffer.from(calldatas[0]));
8497
+ respSign = await this._transporter.send(Number("0x5a"), 4, 3, 0, Buffer.from(calldatas[0]));
8050
8498
  if (calldatas.length > 1) {
8051
8499
  calldatas.slice(1).forEach(async (part) => {
8052
- await this._transporter.send(Number("0x5a"), 4, 3, 1, Buffer.from(part));
8500
+ respSign = await this._transporter.send(Number("0x5a"), 4, 3, 1, Buffer.from(part));
8053
8501
  });
8054
8502
  }
8055
- respSign = await this._transporter.send(Number("0x5a"), 4, 3, 2);
8056
8503
  }
8057
8504
  return this.decodeSignatureLedger(respSign);
8058
8505
  }
8059
8506
  /**
8060
- * Ask to the Ledger Nano to display and sign a Starknet V3 transaction.
8507
+ * Ask to the Ledger Nano to display and sign a Starknet V3 transaction (Rpc 0.7 & Rpc 0.8).
8061
8508
  * @param {V3InvocationsSignerDetails} txDetails All the details needed for a txV3.
8062
8509
  * @param {Call[]} calls array of Starknet invocations
8063
8510
  * @returns an object including the transaction Hash and the signature
@@ -8077,7 +8524,7 @@ var LedgerSigner221 = class extends LedgerSigner111 {
8077
8524
  * },
8078
8525
  * l2_gas: { max_amount: "0x00", max_price_per_unit: "0x00"},
8079
8526
  * }, tip: 0, version: "0x3", walletAddress: account0.address
8080
- * };
8527
+ * }; // Rpc 0.7 transaction.
8081
8528
  * const res = await myLedgerSigner.signTxV3(txDetailsV3, calls);
8082
8529
  * // res = {hash:
8083
8530
  * // signature:
@@ -8092,53 +8539,67 @@ var LedgerSigner221 = class extends LedgerSigner111 {
8092
8539
  );
8093
8540
  await this._transporter.send(Number("0x5a"), 3, 0, 0, Buffer.from(this.pathBuffer));
8094
8541
  const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
8095
- const tipBuf = this.convertBnToLedger(txDetails.tip);
8096
8542
  const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
8097
8543
  const nonceBuf = this.convertBnToLedger(txDetails.nonce);
8098
8544
  const dAModeHashBuf = this.convertBnToLedger(
8099
8545
  hashDAMode(
8100
- txDetails.nonceDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2,
8101
- txDetails.feeDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2
8546
+ intDAM(txDetails.nonceDataAvailabilityMode),
8547
+ intDAM(txDetails.feeDataAvailabilityMode)
8102
8548
  )
8103
8549
  );
8104
- const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
8105
- const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
8106
8550
  const dataBuf = concatenateArrayBuffer([
8107
8551
  accountAddressBuf,
8108
- tipBuf,
8109
- l1_gasBuf,
8110
- l2_gasBuf,
8111
8552
  chainIdBuf,
8112
8553
  nonceBuf,
8113
8554
  dAModeHashBuf
8114
8555
  ]);
8115
8556
  await this._transporter.send(Number("0x5a"), 3, 1, 0, Buffer.from(dataBuf));
8557
+ if (isRPC08_ResourceBounds(txDetails.resourceBounds)) {
8558
+ const tipBuf = this.convertBnToLedger(txDetails.tip);
8559
+ const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
8560
+ const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
8561
+ const l1_data_gasBuf = this.convertBnToLedger(
8562
+ encodeDataResourceBoundsL1(txDetails.resourceBounds)
8563
+ );
8564
+ const feeBuf = concatenateArrayBuffer([
8565
+ tipBuf,
8566
+ l1_gasBuf,
8567
+ l2_gasBuf,
8568
+ l1_data_gasBuf
8569
+ ]);
8570
+ await this._transporter.send(Number("0x5a"), 3, 2, 0, Buffer.from(feeBuf));
8571
+ } else {
8572
+ const tipBuf = this.convertBnToLedger(txDetails.tip);
8573
+ const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
8574
+ const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
8575
+ const feeBuf = concatenateArrayBuffer([tipBuf, l1_gasBuf, l2_gasBuf]);
8576
+ await this._transporter.send(Number("0x5a"), 3, 2, 0, Buffer.from(feeBuf));
8577
+ }
8116
8578
  const paymasterBuf = concatenateArrayBuffer(
8117
8579
  txDetails.paymasterData.map((value) => {
8118
8580
  const a = this.convertBnToLedger(value);
8119
8581
  return a;
8120
8582
  })
8121
8583
  );
8122
- await this._transporter.send(Number("0x5a"), 3, 2, 0, Buffer.from(paymasterBuf));
8584
+ await this._transporter.send(Number("0x5a"), 3, 3, 0, Buffer.from(paymasterBuf));
8123
8585
  const accountDeployDataBuf = concatenateArrayBuffer(
8124
8586
  txDetails.paymasterData.map((value) => {
8125
8587
  const a = this.convertBnToLedger(value);
8126
8588
  return a;
8127
8589
  })
8128
8590
  );
8129
- await this._transporter.send(Number("0x5a"), 3, 3, 0, Buffer.from(accountDeployDataBuf));
8591
+ await this._transporter.send(Number("0x5a"), 3, 4, 0, Buffer.from(accountDeployDataBuf));
8130
8592
  const nbCallsBuf = this.convertBnToLedger(calls.length);
8131
- await this._transporter.send(Number("0x5a"), 3, 4, 0, Buffer.from(nbCallsBuf));
8593
+ await this._transporter.send(Number("0x5a"), 3, 5, 0, Buffer.from(nbCallsBuf));
8132
8594
  let respSign = new Uint8Array(0);
8133
8595
  for (const call of calls) {
8134
8596
  const calldatas = this.encodeCall(call);
8135
- await this._transporter.send(Number("0x5a"), 3, 5, 0, Buffer.from(calldatas[0]));
8597
+ respSign = await this._transporter.send(Number("0x5a"), 3, 6, 0, Buffer.from(calldatas[0]));
8136
8598
  if (calldatas.length > 1) {
8137
8599
  calldatas.slice(1).forEach(async (part) => {
8138
- await this._transporter.send(Number("0x5a"), 3, 5, 1, Buffer.from(part));
8600
+ respSign = await this._transporter.send(Number("0x5a"), 3, 6, 1, Buffer.from(part));
8139
8601
  });
8140
8602
  }
8141
- respSign = await this._transporter.send(Number("0x5a"), 3, 5, 2);
8142
8603
  }
8143
8604
  return this.decodeSignatureLedger(respSign);
8144
8605
  }
@@ -8178,21 +8639,21 @@ var LedgerSigner221 = class extends LedgerSigner111 {
8178
8639
  );
8179
8640
  const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
8180
8641
  const saltBuf = this.convertBnToLedger(deployAccountDetail.addressSalt);
8642
+ const maxFeeBuf = this.convertBnToLedger(deployAccountDetail.maxFee);
8181
8643
  const chainIdBuf = this.convertBnToLedger(deployAccountDetail.chainId);
8182
8644
  const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
8183
8645
  const dataBuf = concatenateArrayBuffer([
8184
8646
  accountAddressBuf,
8185
8647
  classHashBuf,
8186
8648
  saltBuf,
8649
+ maxFeeBuf,
8187
8650
  chainIdBuf,
8188
8651
  nonceBuf
8189
8652
  ]);
8190
8653
  await this._transporter.send(Number("0x5a"), 6, 1, 0, Buffer.from(dataBuf));
8191
- const maxFreeBuf = this.convertBnToLedger(deployAccountDetail.maxFee);
8192
- await this._transporter.send(Number("0x5a"), 6, 2, 0, Buffer.from(maxFreeBuf));
8193
8654
  const compiledConstructor = CallData.compile(deployAccountDetail.constructorCalldata);
8194
8655
  const constructorLengthBuf = this.convertBnToLedger(compiledConstructor.length);
8195
- await this._transporter.send(Number("0x5a"), 6, 3, 0, Buffer.from(constructorLengthBuf));
8656
+ await this._transporter.send(Number("0x5a"), 6, 2, 0, Buffer.from(constructorLengthBuf));
8196
8657
  const constructorBuf = concatenateArrayBuffer(
8197
8658
  compiledConstructor.map((parameter) => {
8198
8659
  const a = this.convertBnToLedger(parameter);
@@ -8205,12 +8666,12 @@ var LedgerSigner221 = class extends LedgerSigner111 {
8205
8666
  constructorChunks.push(constructorBuf.subarray(i, i + chunkSize));
8206
8667
  let respSign = new Uint8Array(0);
8207
8668
  for (const chunk of constructorChunks) {
8208
- respSign = await this._transporter.send(Number("0x5a"), 6, 4, 0, Buffer.from(chunk));
8669
+ respSign = await this._transporter.send(Number("0x5a"), 6, 3, 0, Buffer.from(chunk));
8209
8670
  }
8210
8671
  return this.decodeSignatureLedger(respSign);
8211
8672
  }
8212
8673
  /**
8213
- *Ask the Ledger Nano to display and sign a Starknet V3 account deployment.
8674
+ *Ask the Ledger Nano to display and sign a Starknet V3 account deployment (Rpc 0.7 & Rpc 0.8).
8214
8675
  * @param {V3DeployAccountSignerDetails} deployAccountDetail All the details needed for a V3 deploy account.
8215
8676
  * @returns an object including the transaction Hash and the signature
8216
8677
  * @example
@@ -8231,7 +8692,7 @@ var LedgerSigner221 = class extends LedgerSigner111 {
8231
8692
  * addressSalt: '0x07e52f68e3160e1ef698211cdf6d3792368fe347e7e2d4a8ace14d9b248f39c5',
8232
8693
  * chainId: '0x534e5f5345504f4c4941', maxFee: 0,
8233
8694
  * version: '0x3', nonce: 0n
8234
- *}
8695
+ *} // Rpc 0.7 transaction.
8235
8696
  * const res = await myLedgerSigner.signDeployAccountV3(deployData);
8236
8697
  * // res = {hash:
8237
8698
  * // signature:
@@ -8247,8 +8708,8 @@ var LedgerSigner221 = class extends LedgerSigner111 {
8247
8708
  const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
8248
8709
  const dAModeHashBuf = this.convertBnToLedger(
8249
8710
  hashDAMode(
8250
- deployAccountDetail.nonceDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2,
8251
- deployAccountDetail.feeDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2
8711
+ intDAM(deployAccountDetail.nonceDataAvailabilityMode),
8712
+ intDAM(deployAccountDetail.feeDataAvailabilityMode)
8252
8713
  )
8253
8714
  );
8254
8715
  const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
@@ -8262,15 +8723,35 @@ var LedgerSigner221 = class extends LedgerSigner111 {
8262
8723
  saltBuf
8263
8724
  ]);
8264
8725
  await this._transporter.send(Number("0x5a"), 5, 1, 0, Buffer.from(dataBuf));
8265
- const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
8266
- const l1_gasBuf = this.convertBnToLedger(
8267
- encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
8268
- );
8269
- const l2_gasBuf = this.convertBnToLedger(
8270
- encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
8271
- );
8272
- const feeBuf = concatenateArrayBuffer([tipBuf, l1_gasBuf, l2_gasBuf]);
8273
- await this._transporter.send(Number("0x5a"), 5, 2, 0, Buffer.from(feeBuf));
8726
+ if (isRPC08_ResourceBounds(deployAccountDetail.resourceBounds)) {
8727
+ const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
8728
+ const l1_gasBuf = this.convertBnToLedger(
8729
+ encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
8730
+ );
8731
+ const l2_gasBuf = this.convertBnToLedger(
8732
+ encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
8733
+ );
8734
+ const l1_data_gasBuf = this.convertBnToLedger(
8735
+ encodeDataResourceBoundsL1(deployAccountDetail.resourceBounds)
8736
+ );
8737
+ const feeBuf = concatenateArrayBuffer([
8738
+ tipBuf,
8739
+ l1_gasBuf,
8740
+ l2_gasBuf,
8741
+ l1_data_gasBuf
8742
+ ]);
8743
+ await this._transporter.send(Number("0x5a"), 5, 2, 0, Buffer.from(feeBuf));
8744
+ } else {
8745
+ const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
8746
+ const l1_gasBuf = this.convertBnToLedger(
8747
+ encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
8748
+ );
8749
+ const l2_gasBuf = this.convertBnToLedger(
8750
+ encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
8751
+ );
8752
+ const feeBuf = concatenateArrayBuffer([tipBuf, l1_gasBuf, l2_gasBuf]);
8753
+ await this._transporter.send(Number("0x5a"), 5, 2, 0, Buffer.from(feeBuf));
8754
+ }
8274
8755
  const paymasterBuf = concatenateArrayBuffer(
8275
8756
  deployAccountDetail.paymasterData.map((value) => {
8276
8757
  const a = this.convertBnToLedger(value);
@@ -8297,30 +8778,35 @@ var LedgerSigner221 = class extends LedgerSigner111 {
8297
8778
  }
8298
8779
  return this.decodeSignatureLedger(respSign);
8299
8780
  }
8781
+ /** Internal function to convert a Call to an array of Uint8Array.
8782
+ * @param {Call} call A Call to convert.
8783
+ * @return {Uint8Array[]} Call encoded in an array of Uint8Array (each containing 7 u256).
8784
+ */
8785
+ encodeCall(call) {
8786
+ const toBuf = this.convertBnToLedger(call.contractAddress);
8787
+ const selectorBuf = hexToBytes(addAddressPadding(getSelector(call.entrypoint)));
8788
+ let calldataBuf = new Uint8Array([]);
8789
+ if (call.calldata) {
8790
+ const compiledCalldata = CallData.compile(call.calldata);
8791
+ const calldataSizeBuf = this.convertBnToLedger(compiledCalldata.length);
8792
+ calldataBuf = concatenateArrayBuffer([
8793
+ calldataSizeBuf,
8794
+ ...compiledCalldata.map((parameter) => {
8795
+ const a = this.convertBnToLedger(parameter);
8796
+ return a;
8797
+ })
8798
+ ]);
8799
+ } else {
8800
+ calldataBuf = this.convertBnToLedger("0x00");
8801
+ }
8802
+ const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
8803
+ const calldatas = [];
8804
+ const chunkSize = 7 * 32;
8805
+ for (let i = 0; i < callBuf.length; i += chunkSize)
8806
+ calldatas.push(callBuf.subarray(i, i + chunkSize));
8807
+ return calldatas;
8808
+ }
8300
8809
  };
8301
- function getLedgerPathBuffer221(accountId, applicationName = "LedgerW") {
8302
- const path0buff = new Uint8Array([HARDENING_BYTE, 0, 10, 85]);
8303
- const path1buff = new Uint8Array([71 | HARDENING_BYTE, 65, 233, 201]);
8304
- const path2Base = applicationName === "LedgerW" ? new Uint8Array([43, 206, 231, 219]) : stringToSha256ToArrayBuff4(applicationName);
8305
- const path2buff = concatenateArrayBuffer([
8306
- new Uint8Array([path2Base[0] | HARDENING_BYTE]),
8307
- path2Base.subarray(1)
8308
- ]);
8309
- const path3buff = new Uint8Array([HARDENING_BYTE, 0, 0, 0]);
8310
- const hex = toHex(BigInt(accountId) | HARDENING_4BYTES);
8311
- const padded = addHexPrefix(removeHexPrefix(hex).padStart(8, "0"));
8312
- const path4buff = hexToBytes(padded);
8313
- const path5buff = new Uint8Array([0, 0, 0, 0]);
8314
- const pathBuff = concatenateArrayBuffer([
8315
- path0buff,
8316
- path1buff,
8317
- path2buff,
8318
- path3buff,
8319
- path4buff,
8320
- path5buff
8321
- ]);
8322
- return pathBuff;
8323
- }
8324
8810
 
8325
8811
  // src/utils/events/index.ts
8326
8812
  var events_exports = {};
@@ -8574,13 +9060,257 @@ async function supportsInterface(provider, contractAddress, interfaceId) {
8574
9060
  }
8575
9061
  }
8576
9062
 
9063
+ // src/utils/paymaster.ts
9064
+ var paymaster_exports = {};
9065
+ __export(paymaster_exports, {
9066
+ getDefaultPaymasterNodeUrl: () => getDefaultPaymasterNodeUrl
9067
+ });
9068
+ var getDefaultPaymasterNodeUrl = (networkName, mute = false) => {
9069
+ if (!mute) {
9070
+ logger.info("Using default public node url, please provide nodeUrl in provider options!");
9071
+ }
9072
+ const nodes = PAYMASTER_RPC_NODES[networkName ?? _NetworkName.SN_SEPOLIA];
9073
+ const randIdx = Math.floor(Math.random() * nodes.length);
9074
+ return nodes[randIdx];
9075
+ };
9076
+
9077
+ // src/paymaster/rpc.ts
9078
+ var convertCalls = (calls) => calls.map((call) => ({
9079
+ to: call.contractAddress,
9080
+ selector: getSelectorFromName(call.entrypoint),
9081
+ calldata: CallData.toHex(call.calldata)
9082
+ }));
9083
+ var convertFeeMode = (feeMode) => {
9084
+ if (feeMode.mode === "sponsored") {
9085
+ return { mode: "sponsored" };
9086
+ }
9087
+ return { mode: "default", gas_token: feeMode.gasToken };
9088
+ };
9089
+ var convertFEE_MODE = (feeMode) => {
9090
+ if (feeMode.mode === "sponsored") {
9091
+ return { mode: "sponsored" };
9092
+ }
9093
+ return { mode: "default", gasToken: feeMode.gas_token };
9094
+ };
9095
+ var convertTimeBounds = (timeBounds) => timeBounds && timeBounds.executeAfter && timeBounds.executeBefore ? {
9096
+ execute_after: timeBounds.executeAfter.getTime().toString(),
9097
+ execute_before: timeBounds.executeBefore.getTime().toString()
9098
+ } : void 0;
9099
+ var convertTIME_BOUNDS = (timeBounds) => timeBounds && timeBounds.execute_after && timeBounds.execute_before ? {
9100
+ executeAfter: new Date(timeBounds.execute_after),
9101
+ executeBefore: new Date(timeBounds.execute_before)
9102
+ } : void 0;
9103
+ var convertEXECUTION_PARAMETERS = (parameters) => ({
9104
+ version: parameters.version,
9105
+ feeMode: convertFEE_MODE(parameters.fee_mode),
9106
+ timeBounds: convertTIME_BOUNDS(parameters.time_bounds)
9107
+ });
9108
+ var defaultOptions3 = {
9109
+ headers: { "Content-Type": "application/json" }
9110
+ };
9111
+ var PaymasterRpc = class _PaymasterRpc {
9112
+ nodeUrl;
9113
+ headers;
9114
+ baseFetch;
9115
+ requestId;
9116
+ constructor(options) {
9117
+ if (options instanceof _PaymasterRpc) {
9118
+ this.nodeUrl = options.nodeUrl;
9119
+ this.headers = { ...defaultOptions3.headers, ...options.headers };
9120
+ this.baseFetch = options.baseFetch;
9121
+ this.requestId = options.requestId;
9122
+ return;
9123
+ }
9124
+ if (options && "nodeUrl" in options && "headers" in options && "baseFetch" in options) {
9125
+ this.nodeUrl = options.nodeUrl ?? getDefaultPaymasterNodeUrl(void 0);
9126
+ this.headers = { ...defaultOptions3.headers, ...options.headers };
9127
+ this.baseFetch = options.baseFetch ?? fetch_default;
9128
+ this.requestId = 0;
9129
+ return;
9130
+ }
9131
+ const { nodeUrl, headers, baseFetch } = options || {};
9132
+ if (nodeUrl && Object.values(_NetworkName).includes(nodeUrl)) {
9133
+ this.nodeUrl = getDefaultPaymasterNodeUrl(nodeUrl, options?.default);
9134
+ } else if (nodeUrl) {
9135
+ this.nodeUrl = nodeUrl;
9136
+ } else {
9137
+ this.nodeUrl = getDefaultPaymasterNodeUrl(void 0, options?.default);
9138
+ }
9139
+ this.baseFetch = baseFetch ?? fetch_default;
9140
+ this.headers = { ...defaultOptions3.headers, ...headers };
9141
+ this.requestId = 0;
9142
+ }
9143
+ fetch(method, params, id = 0) {
9144
+ const rpcRequestBody = {
9145
+ id,
9146
+ jsonrpc: "2.0",
9147
+ method,
9148
+ ...params && { params }
9149
+ };
9150
+ return this.baseFetch(this.nodeUrl, {
9151
+ method: "POST",
9152
+ body: stringify2(rpcRequestBody),
9153
+ headers: this.headers
9154
+ });
9155
+ }
9156
+ errorHandler(method, params, rpcError, otherError) {
9157
+ if (rpcError) {
9158
+ throw new RpcError(rpcError, method, params);
9159
+ }
9160
+ if (otherError instanceof LibraryError) {
9161
+ throw otherError;
9162
+ }
9163
+ if (otherError) {
9164
+ throw Error(otherError.message);
9165
+ }
9166
+ }
9167
+ async fetchEndpoint(method, params) {
9168
+ try {
9169
+ this.requestId += 1;
9170
+ const rawResult = await this.fetch(method, params, this.requestId);
9171
+ const { error, result } = await rawResult.json();
9172
+ this.errorHandler(method, params, error);
9173
+ return result;
9174
+ } catch (error) {
9175
+ this.errorHandler(method, params, error?.response?.data, error);
9176
+ throw error;
9177
+ }
9178
+ }
9179
+ async isAvailable() {
9180
+ return this.fetchEndpoint("paymaster_isAvailable");
9181
+ }
9182
+ async buildTransaction(transaction, parameters) {
9183
+ let userTransaction;
9184
+ switch (transaction.type) {
9185
+ case "invoke":
9186
+ userTransaction = {
9187
+ ...transaction,
9188
+ invoke: {
9189
+ user_address: transaction.invoke.userAddress,
9190
+ calls: convertCalls(transaction.invoke.calls)
9191
+ }
9192
+ };
9193
+ break;
9194
+ case "deploy_and_invoke":
9195
+ userTransaction = {
9196
+ ...transaction,
9197
+ invoke: {
9198
+ user_address: transaction.invoke.userAddress,
9199
+ calls: convertCalls(transaction.invoke.calls)
9200
+ }
9201
+ };
9202
+ break;
9203
+ case "deploy":
9204
+ default:
9205
+ userTransaction = transaction;
9206
+ break;
9207
+ }
9208
+ const executionParameters = {
9209
+ version: parameters.version,
9210
+ fee_mode: convertFeeMode(parameters.feeMode),
9211
+ time_bounds: convertTimeBounds(parameters.timeBounds)
9212
+ };
9213
+ const response = await this.fetchEndpoint("paymaster_buildTransaction", {
9214
+ transaction: userTransaction,
9215
+ parameters: executionParameters
9216
+ });
9217
+ const fee = {
9218
+ gas_token_price_in_strk: BigInt(response.fee.gas_token_price_in_strk),
9219
+ estimated_fee_in_strk: BigInt(response.fee.estimated_fee_in_strk),
9220
+ estimated_fee_in_gas_token: BigInt(response.fee.estimated_fee_in_gas_token),
9221
+ suggested_max_fee_in_strk: BigInt(response.fee.suggested_max_fee_in_strk),
9222
+ suggested_max_fee_in_gas_token: BigInt(response.fee.suggested_max_fee_in_gas_token)
9223
+ };
9224
+ switch (response.type) {
9225
+ case "invoke":
9226
+ return {
9227
+ type: "invoke",
9228
+ typed_data: response.typed_data,
9229
+ parameters: convertEXECUTION_PARAMETERS(response.parameters),
9230
+ fee
9231
+ };
9232
+ case "deploy_and_invoke":
9233
+ return {
9234
+ type: "deploy_and_invoke",
9235
+ deployment: response.deployment,
9236
+ typed_data: response.typed_data,
9237
+ parameters: convertEXECUTION_PARAMETERS(response.parameters),
9238
+ fee
9239
+ };
9240
+ case "deploy":
9241
+ default:
9242
+ return {
9243
+ type: "deploy",
9244
+ deployment: response.deployment,
9245
+ parameters: convertEXECUTION_PARAMETERS(response.parameters),
9246
+ fee
9247
+ };
9248
+ }
9249
+ }
9250
+ async executeTransaction(transaction, parameters) {
9251
+ let user_transaction;
9252
+ switch (transaction.type) {
9253
+ case "invoke":
9254
+ user_transaction = {
9255
+ ...transaction,
9256
+ invoke: {
9257
+ user_address: transaction.invoke.userAddress,
9258
+ typed_data: transaction.invoke.typedData,
9259
+ signature: signatureToHexArray(transaction.invoke.signature)
9260
+ }
9261
+ };
9262
+ break;
9263
+ case "deploy_and_invoke":
9264
+ user_transaction = {
9265
+ ...transaction,
9266
+ invoke: {
9267
+ user_address: transaction.invoke.userAddress,
9268
+ typed_data: transaction.invoke.typedData,
9269
+ signature: signatureToHexArray(transaction.invoke.signature)
9270
+ }
9271
+ };
9272
+ break;
9273
+ case "deploy":
9274
+ default:
9275
+ user_transaction = transaction;
9276
+ break;
9277
+ }
9278
+ const executionParameters = {
9279
+ version: parameters.version,
9280
+ fee_mode: convertFeeMode(parameters.feeMode),
9281
+ time_bounds: convertTimeBounds(parameters.timeBounds)
9282
+ };
9283
+ return this.fetchEndpoint("paymaster_executeTransaction", {
9284
+ transaction: user_transaction,
9285
+ parameters: executionParameters
9286
+ });
9287
+ }
9288
+ async getSupportedTokens() {
9289
+ return this.fetchEndpoint("paymaster_getSupportedTokens").then(
9290
+ (tokens) => tokens.map((token) => ({
9291
+ token_address: token.token_address,
9292
+ decimals: token.decimals,
9293
+ priceInStrk: BigInt(token.price_in_strk)
9294
+ }))
9295
+ );
9296
+ }
9297
+ };
9298
+
9299
+ // src/paymaster/interface.ts
9300
+ var PaymasterInterface = class {
9301
+ };
9302
+
9303
+ // src/paymaster/index.ts
9304
+ var defaultPaymaster = new PaymasterRpc({ default: true });
9305
+
8577
9306
  // src/account/default.ts
8578
9307
  var Account = class extends RpcProvider2 {
8579
9308
  signer;
8580
9309
  address;
8581
9310
  cairoVersion;
8582
9311
  transactionVersion;
8583
- constructor(providerOrOptions, address, pkOrSigner, cairoVersion, transactionVersion = config.get("transactionVersion")) {
9312
+ paymaster;
9313
+ constructor(providerOrOptions, address, pkOrSigner, cairoVersion, transactionVersion = config.get("transactionVersion"), paymaster) {
8584
9314
  super(providerOrOptions);
8585
9315
  this.address = address.toLowerCase();
8586
9316
  this.signer = isString(pkOrSigner) || pkOrSigner instanceof Uint8Array ? new Signer(pkOrSigner) : pkOrSigner;
@@ -8588,6 +9318,7 @@ var Account = class extends RpcProvider2 {
8588
9318
  this.cairoVersion = cairoVersion.toString();
8589
9319
  }
8590
9320
  this.transactionVersion = transactionVersion;
9321
+ this.paymaster = paymaster ? new PaymasterRpc(paymaster) : defaultPaymaster;
8591
9322
  logger.debug("Account setup", {
8592
9323
  transactionVersion: this.transactionVersion,
8593
9324
  cairoVersion: this.cairoVersion,
@@ -8645,7 +9376,7 @@ var Account = class extends RpcProvider2 {
8645
9376
  );
8646
9377
  const chainId = await this.getChainId();
8647
9378
  const signerDetails = {
8648
- ...v3Details(details, await this.channel.getSpecVersion()),
9379
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8649
9380
  walletAddress: this.address,
8650
9381
  nonce,
8651
9382
  maxFee: ZERO,
@@ -8657,7 +9388,7 @@ var Account = class extends RpcProvider2 {
8657
9388
  const invocation = await this.buildInvocation(transactions, signerDetails);
8658
9389
  return super.getInvokeEstimateFee(
8659
9390
  { ...invocation },
8660
- { ...v3Details(details, await this.channel.getSpecVersion()), version, nonce },
9391
+ { ...v3Details(details, await this.channel.setUpSpecVersion()), version, nonce },
8661
9392
  blockIdentifier,
8662
9393
  details.skipValidate
8663
9394
  );
@@ -8676,7 +9407,7 @@ var Account = class extends RpcProvider2 {
8676
9407
  );
8677
9408
  const chainId = await this.getChainId();
8678
9409
  const declareContractTransaction = await this.buildDeclarePayload(payload, {
8679
- ...v3Details(details, await this.channel.getSpecVersion()),
9410
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8680
9411
  nonce,
8681
9412
  chainId,
8682
9413
  version,
@@ -8688,7 +9419,7 @@ var Account = class extends RpcProvider2 {
8688
9419
  });
8689
9420
  return super.getDeclareEstimateFee(
8690
9421
  declareContractTransaction,
8691
- { ...v3Details(details, await this.channel.getSpecVersion()), version, nonce },
9422
+ { ...v3Details(details, await this.channel.setUpSpecVersion()), version, nonce },
8692
9423
  blockIdentifier,
8693
9424
  details.skipValidate
8694
9425
  );
@@ -8709,7 +9440,7 @@ var Account = class extends RpcProvider2 {
8709
9440
  const payload = await this.buildAccountDeployPayload(
8710
9441
  { classHash, addressSalt, constructorCalldata, contractAddress },
8711
9442
  {
8712
- ...v3Details(details, await this.channel.getSpecVersion()),
9443
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8713
9444
  nonce,
8714
9445
  chainId,
8715
9446
  version,
@@ -8723,7 +9454,7 @@ var Account = class extends RpcProvider2 {
8723
9454
  );
8724
9455
  return super.getDeployAccountEstimateFee(
8725
9456
  { ...payload },
8726
- { ...v3Details(details, await this.channel.getSpecVersion()), version, nonce },
9457
+ { ...v3Details(details, await this.channel.setUpSpecVersion()), version, nonce },
8727
9458
  blockIdentifier,
8728
9459
  details.skipValidate
8729
9460
  );
@@ -8736,7 +9467,7 @@ var Account = class extends RpcProvider2 {
8736
9467
  if (!invocations.length) throw TypeError("Invocations should be non-empty array");
8737
9468
  const { nonce, blockIdentifier, version, skipValidate } = details;
8738
9469
  const accountInvocations = await this.accountInvocationsFactory(invocations, {
8739
- ...v3Details(details, await this.channel.getSpecVersion()),
9470
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8740
9471
  versions: [
8741
9472
  ETransactionVersion2.F1,
8742
9473
  // non-sierra
@@ -8759,7 +9490,7 @@ var Account = class extends RpcProvider2 {
8759
9490
  if (!invocations.length) throw TypeError("Invocations should be non-empty array");
8760
9491
  const { nonce, blockIdentifier, skipValidate = true, skipExecute, version } = details;
8761
9492
  const accountInvocations = await this.accountInvocationsFactory(invocations, {
8762
- ...v3Details(details, await this.channel.getSpecVersion()),
9493
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8763
9494
  versions: [
8764
9495
  ETransactionVersion2.V1,
8765
9496
  // non-sierra
@@ -8780,6 +9511,13 @@ var Account = class extends RpcProvider2 {
8780
9511
  }
8781
9512
  async execute(transactions, transactionsDetail = {}) {
8782
9513
  const calls = Array.isArray(transactions) ? transactions : [transactions];
9514
+ if (transactionsDetail.paymaster) {
9515
+ return this.executePaymasterTransaction(
9516
+ calls,
9517
+ transactionsDetail.paymaster,
9518
+ transactionsDetail.maxFee
9519
+ );
9520
+ }
8783
9521
  const nonce = toBigInt(transactionsDetail.nonce ?? await this.getNonce());
8784
9522
  const version = toTransactionVersion(
8785
9523
  this.getPreferredVersion(ETransactionVersion2.V1, ETransactionVersion2.V3),
@@ -8796,7 +9534,7 @@ var Account = class extends RpcProvider2 {
8796
9534
  );
8797
9535
  const chainId = await this.getChainId();
8798
9536
  const signerDetails = {
8799
- ...v3Details(transactionsDetail, await this.channel.getSpecVersion()),
9537
+ ...v3Details(transactionsDetail, await this.channel.setUpSpecVersion()),
8800
9538
  resourceBounds: estimate.resourceBounds,
8801
9539
  walletAddress: this.address,
8802
9540
  nonce,
@@ -8810,7 +9548,7 @@ var Account = class extends RpcProvider2 {
8810
9548
  return this.invokeFunction(
8811
9549
  { contractAddress: this.address, calldata, signature },
8812
9550
  {
8813
- ...v3Details(transactionsDetail, await this.channel.getSpecVersion()),
9551
+ ...v3Details(transactionsDetail, await this.channel.setUpSpecVersion()),
8814
9552
  resourceBounds: estimate.resourceBounds,
8815
9553
  nonce,
8816
9554
  maxFee: estimate.maxFee,
@@ -8818,6 +9556,88 @@ var Account = class extends RpcProvider2 {
8818
9556
  }
8819
9557
  );
8820
9558
  }
9559
+ async buildPaymasterTransaction(calls, paymasterDetails) {
9560
+ if (!paymasterDetails.deploymentData) {
9561
+ const snip9Version = await this.getSnip9Version();
9562
+ if (snip9Version === OutsideExecutionVersion.UNSUPPORTED) {
9563
+ throw Error("Account is not compatible with SNIP-9");
9564
+ }
9565
+ }
9566
+ const parameters = {
9567
+ version: "0x1",
9568
+ feeMode: paymasterDetails.feeMode,
9569
+ timeBounds: paymasterDetails.timeBounds
9570
+ };
9571
+ let transaction;
9572
+ if (paymasterDetails.deploymentData) {
9573
+ if (calls.length > 0) {
9574
+ transaction = {
9575
+ type: "deploy_and_invoke",
9576
+ invoke: { userAddress: this.address, calls },
9577
+ deployment: paymasterDetails.deploymentData
9578
+ };
9579
+ } else {
9580
+ transaction = {
9581
+ type: "deploy",
9582
+ deployment: paymasterDetails.deploymentData
9583
+ };
9584
+ }
9585
+ } else {
9586
+ transaction = {
9587
+ type: "invoke",
9588
+ invoke: { userAddress: this.address, calls }
9589
+ };
9590
+ }
9591
+ return this.paymaster.buildTransaction(transaction, parameters);
9592
+ }
9593
+ async estimatePaymasterTransactionFee(calls, paymasterDetails) {
9594
+ const preparedTransaction = await this.buildPaymasterTransaction(calls, paymasterDetails);
9595
+ return preparedTransaction.fee;
9596
+ }
9597
+ async executePaymasterTransaction(calls, paymasterDetails, maxFee) {
9598
+ const preparedTransaction = await this.buildPaymasterTransaction(calls, paymasterDetails);
9599
+ if (maxFee && preparedTransaction.fee.gas_token_price_in_strk > maxFee) {
9600
+ throw Error("Gas token price is too high");
9601
+ }
9602
+ let transaction;
9603
+ switch (preparedTransaction.type) {
9604
+ case "deploy_and_invoke": {
9605
+ const signature = await this.signMessage(preparedTransaction.typed_data);
9606
+ transaction = {
9607
+ type: "deploy_and_invoke",
9608
+ invoke: {
9609
+ userAddress: this.address,
9610
+ typedData: preparedTransaction.typed_data,
9611
+ signature: signatureToHexArray(signature)
9612
+ },
9613
+ deployment: preparedTransaction.deployment
9614
+ };
9615
+ break;
9616
+ }
9617
+ case "invoke": {
9618
+ const signature = await this.signMessage(preparedTransaction.typed_data);
9619
+ transaction = {
9620
+ type: "invoke",
9621
+ invoke: {
9622
+ userAddress: this.address,
9623
+ typedData: preparedTransaction.typed_data,
9624
+ signature: signatureToHexArray(signature)
9625
+ }
9626
+ };
9627
+ break;
9628
+ }
9629
+ case "deploy": {
9630
+ transaction = {
9631
+ type: "deploy",
9632
+ deployment: preparedTransaction.deployment
9633
+ };
9634
+ break;
9635
+ }
9636
+ default:
9637
+ throw Error("Invalid transaction type");
9638
+ }
9639
+ return this.paymaster.executeTransaction(transaction, preparedTransaction.parameters).then((response) => ({ transaction_hash: response.transaction_hash }));
9640
+ }
8821
9641
  /**
8822
9642
  * First check if contract is already declared, if not declare it
8823
9643
  * If contract already declared returned transaction_hash is ''.
@@ -8855,7 +9675,7 @@ var Account = class extends RpcProvider2 {
8855
9675
  }
8856
9676
  );
8857
9677
  const declareDetails = {
8858
- ...v3Details(details, await this.channel.getSpecVersion()),
9678
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8859
9679
  resourceBounds: estimate.resourceBounds,
8860
9680
  maxFee: estimate.maxFee,
8861
9681
  nonce: toBigInt(nonce ?? await this.getNonce()),
@@ -8925,7 +9745,7 @@ var Account = class extends RpcProvider2 {
8925
9745
  details
8926
9746
  );
8927
9747
  const signature = await this.signer.signDeployAccountTransaction({
8928
- ...v3Details(details, await this.channel.getSpecVersion()),
9748
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8929
9749
  classHash,
8930
9750
  constructorCalldata: compiledCalldata,
8931
9751
  contractAddress,
@@ -8939,7 +9759,7 @@ var Account = class extends RpcProvider2 {
8939
9759
  return this.deployAccountContract(
8940
9760
  { classHash, addressSalt, constructorCalldata, signature },
8941
9761
  {
8942
- ...v3Details(details, await this.channel.getSpecVersion()),
9762
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8943
9763
  nonce,
8944
9764
  resourceBounds: estimate.resourceBounds,
8945
9765
  maxFee: estimate.maxFee,
@@ -9106,7 +9926,7 @@ var Account = class extends RpcProvider2 {
9106
9926
  let resourceBounds = estimateFeeToBounds3(
9107
9927
  ZERO,
9108
9928
  void 0,
9109
- await this.channel.getSpecVersion()
9929
+ await this.channel.setUpSpecVersion()
9110
9930
  );
9111
9931
  if (version === ETransactionVersion2.V3) {
9112
9932
  resourceBounds = details.resourceBounds ?? (await this.getSuggestedFee({ type, payload }, details)).resourceBounds;
@@ -9129,14 +9949,14 @@ var Account = class extends RpcProvider2 {
9129
9949
  case TransactionType.DEPLOY:
9130
9950
  return this.estimateDeployFee(payload, details);
9131
9951
  default:
9132
- return ZEROFee(await this.channel.getSpecVersion());
9952
+ return ZEROFee(await this.channel.setUpSpecVersion());
9133
9953
  }
9134
9954
  }
9135
9955
  async buildInvocation(call, details) {
9136
9956
  const calldata = getExecuteCalldata(call, await this.getCairoVersion());
9137
9957
  const signature = !details.skipValidate ? await this.signer.signTransaction(call, details) : [];
9138
9958
  return {
9139
- ...v3Details(details, await this.channel.getSpecVersion()),
9959
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
9140
9960
  contractAddress: this.address,
9141
9961
  calldata,
9142
9962
  signature
@@ -9150,7 +9970,7 @@ var Account = class extends RpcProvider2 {
9150
9970
  }
9151
9971
  const signature = !details.skipValidate ? await this.signer.signDeclareTransaction({
9152
9972
  ...details,
9153
- ...v3Details(details, await this.channel.getSpecVersion()),
9973
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
9154
9974
  classHash,
9155
9975
  compiledClassHash,
9156
9976
  // TODO: TS, cast because optional for v2 and required for v3, thrown if not present
@@ -9173,14 +9993,14 @@ var Account = class extends RpcProvider2 {
9173
9993
  const contractAddress = providedContractAddress ?? calculateContractAddressFromHash(addressSalt, classHash, compiledCalldata, 0);
9174
9994
  const signature = !details.skipValidate ? await this.signer.signDeployAccountTransaction({
9175
9995
  ...details,
9176
- ...v3Details(details, await this.channel.getSpecVersion()),
9996
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
9177
9997
  classHash,
9178
9998
  contractAddress,
9179
9999
  addressSalt,
9180
10000
  constructorCalldata: compiledCalldata
9181
10001
  }) : [];
9182
10002
  return {
9183
- ...v3Details(details, await this.channel.getSpecVersion()),
10003
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
9184
10004
  classHash,
9185
10005
  addressSalt,
9186
10006
  constructorCalldata: compiledCalldata,
@@ -9221,7 +10041,7 @@ var Account = class extends RpcProvider2 {
9221
10041
  [].concat(invocations).map(async (transaction, index) => {
9222
10042
  const txPayload = "payload" in transaction ? transaction.payload : transaction;
9223
10043
  const signerDetails = {
9224
- ...v3Details(details, await this.channel.getSpecVersion()),
10044
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
9225
10045
  walletAddress: this.address,
9226
10046
  nonce: toBigInt(Number(safeNonce) + index),
9227
10047
  maxFee: ZERO,
@@ -9364,8 +10184,8 @@ function onNetworkChanged(swo, callback) {
9364
10184
  // src/wallet/account.ts
9365
10185
  var WalletAccount = class _WalletAccount extends Account {
9366
10186
  walletProvider;
9367
- constructor(providerOrOptions, walletProvider, address, cairoVersion) {
9368
- super(providerOrOptions, address, "", cairoVersion);
10187
+ constructor(providerOrOptions, walletProvider, address, cairoVersion, paymaster) {
10188
+ super(providerOrOptions, address, "", cairoVersion, void 0, paymaster);
9369
10189
  this.walletProvider = walletProvider;
9370
10190
  this.walletProvider.on("accountsChanged", (res) => {
9371
10191
  if (!res) return;
@@ -9406,7 +10226,14 @@ var WalletAccount = class _WalletAccount extends Account {
9406
10226
  /**
9407
10227
  * ACCOUNT METHODS
9408
10228
  */
9409
- execute(calls) {
10229
+ execute(calls, arg2, transactionsDetail = {}) {
10230
+ const details = arg2 === void 0 || Array.isArray(arg2) ? transactionsDetail : arg2;
10231
+ if (details.paymaster) {
10232
+ return this.executePaymasterTransaction(
10233
+ Array.isArray(calls) ? calls : [calls],
10234
+ details.paymaster
10235
+ );
10236
+ }
9410
10237
  const txCalls = [].concat(calls).map((it) => {
9411
10238
  const { contractAddress, entrypoint, calldata } = it;
9412
10239
  return {
@@ -9447,12 +10274,12 @@ var WalletAccount = class _WalletAccount extends Account {
9447
10274
  signMessage(typedData) {
9448
10275
  return signMessage(this.walletProvider, typedData);
9449
10276
  }
9450
- static async connect(provider, walletProvider, cairoVersion, silentMode = false) {
10277
+ static async connect(provider, walletProvider, cairoVersion, paymaster, silentMode = false) {
9451
10278
  const [accountAddress] = await requestAccounts(walletProvider, silentMode);
9452
- return new _WalletAccount(provider, walletProvider, accountAddress, cairoVersion);
10279
+ return new _WalletAccount(provider, walletProvider, accountAddress, cairoVersion, paymaster);
9453
10280
  }
9454
- static async connectSilent(provider, walletProvider, cairoVersion) {
9455
- return _WalletAccount.connect(provider, walletProvider, cairoVersion, true);
10281
+ static async connectSilent(provider, walletProvider, cairoVersion, paymaster) {
10282
+ return _WalletAccount.connect(provider, walletProvider, cairoVersion, paymaster, true);
9456
10283
  }
9457
10284
  // TODO: MISSING ESTIMATES
9458
10285
  };
@@ -9863,6 +10690,7 @@ function units(amount, simbol = "fri") {
9863
10690
  LedgerSigner,
9864
10691
  LedgerSigner111,
9865
10692
  LedgerSigner221,
10693
+ LedgerSigner231,
9866
10694
  LibraryError,
9867
10695
  Literal,
9868
10696
  LogLevelIndex,
@@ -9870,6 +10698,8 @@ function units(amount, simbol = "fri") {
9870
10698
  OutsideExecutionTypesV1,
9871
10699
  OutsideExecutionTypesV2,
9872
10700
  OutsideExecutionVersion,
10701
+ PaymasterInterface,
10702
+ PaymasterRpc,
9873
10703
  Provider,
9874
10704
  ProviderInterface,
9875
10705
  RPC,
@@ -9908,6 +10738,7 @@ function units(amount, simbol = "fri") {
9908
10738
  config,
9909
10739
  constants,
9910
10740
  contractClassResponseToLegacyCompiledContract,
10741
+ defaultPaymaster,
9911
10742
  defaultProvider,
9912
10743
  ec,
9913
10744
  encode,
@@ -9922,21 +10753,29 @@ function units(amount, simbol = "fri") {
9922
10753
  getLedgerPathBuffer111,
9923
10754
  getLedgerPathBuffer221,
9924
10755
  hash,
10756
+ isPendingBlock,
10757
+ isPendingStateUpdate,
10758
+ isPendingTransaction,
9925
10759
  isRPC08_FeeEstimate,
9926
10760
  isRPC08_ResourceBounds,
9927
10761
  isSierra,
10762
+ isSupportedSpecVersion,
10763
+ isV3Tx,
10764
+ isVersion,
9928
10765
  json,
9929
10766
  logger,
9930
10767
  merkle,
9931
10768
  num,
9932
10769
  outsideExecution,
9933
10770
  parseCalldataField,
10771
+ paymaster,
9934
10772
  provider,
9935
10773
  selector,
9936
10774
  shortString,
9937
10775
  src5,
9938
10776
  stark,
9939
10777
  starknetId,
10778
+ toAnyPatchVersion,
9940
10779
  transaction,
9941
10780
  typedData,
9942
10781
  types,