starknet 7.0.1 → 7.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -21,7 +21,7 @@ var constants_exports = {};
21
21
  __export(constants_exports, {
22
22
  ADDR_BOUND: () => ADDR_BOUND,
23
23
  API_VERSION: () => API_VERSION,
24
- BaseUrl: () => BaseUrl,
24
+ BaseUrl: () => _BaseUrl,
25
25
  DEFAULT_GLOBAL_CONFIG: () => DEFAULT_GLOBAL_CONFIG,
26
26
  HARDENING_4BYTES: () => HARDENING_4BYTES,
27
27
  HARDENING_BYTE: () => HARDENING_BYTE,
@@ -29,7 +29,7 @@ __export(constants_exports, {
29
29
  MASK_250: () => MASK_250,
30
30
  MASK_31: () => MASK_31,
31
31
  MAX_STORAGE_ITEM_SIZE: () => MAX_STORAGE_ITEM_SIZE,
32
- NetworkName: () => NetworkName,
32
+ NetworkName: () => _NetworkName,
33
33
  OutsideExecutionCallerAny: () => OutsideExecutionCallerAny,
34
34
  PRIME: () => PRIME,
35
35
  RANGE_FELT: () => RANGE_FELT,
@@ -39,11 +39,11 @@ __export(constants_exports, {
39
39
  SNIP9_V1_INTERFACE_ID: () => SNIP9_V1_INTERFACE_ID,
40
40
  SNIP9_V2_INTERFACE_ID: () => SNIP9_V2_INTERFACE_ID,
41
41
  SYSTEM_MESSAGES: () => SYSTEM_MESSAGES,
42
- StarknetChainId: () => StarknetChainId,
43
- SupportedRpcVersion: () => SupportedRpcVersion,
42
+ StarknetChainId: () => _StarknetChainId,
43
+ SupportedRpcVersion: () => _SupportedRpcVersion,
44
44
  TEXT_TO_FELT_MAX_LEN: () => TEXT_TO_FELT_MAX_LEN,
45
45
  TRANSACTION_VERSION: () => TRANSACTION_VERSION,
46
- TransactionHashPrefix: () => TransactionHashPrefix,
46
+ TransactionHashPrefix: () => _TransactionHashPrefix,
47
47
  UDC: () => UDC,
48
48
  ZERO: () => ZERO
49
49
  });
@@ -158,29 +158,6 @@ var range = (min, max) => ({ min, max });
158
158
  var RANGE_FELT = range(ZERO, PRIME - 1n);
159
159
  var RANGE_I128 = range(-(2n ** 127n), 2n ** 127n - 1n);
160
160
  var RANGE_U128 = range(ZERO, 2n ** 128n - 1n);
161
- var BaseUrl = /* @__PURE__ */ ((BaseUrl2) => {
162
- BaseUrl2["SN_MAIN"] = "https://alpha-mainnet.starknet.io";
163
- BaseUrl2["SN_SEPOLIA"] = "https://alpha-sepolia.starknet.io";
164
- return BaseUrl2;
165
- })(BaseUrl || {});
166
- var NetworkName = /* @__PURE__ */ ((NetworkName2) => {
167
- NetworkName2["SN_MAIN"] = "SN_MAIN";
168
- NetworkName2["SN_SEPOLIA"] = "SN_SEPOLIA";
169
- return NetworkName2;
170
- })(NetworkName || {});
171
- var StarknetChainId = /* @__PURE__ */ ((StarknetChainId6) => {
172
- StarknetChainId6["SN_MAIN"] = "0x534e5f4d41494e";
173
- StarknetChainId6["SN_SEPOLIA"] = "0x534e5f5345504f4c4941";
174
- return StarknetChainId6;
175
- })(StarknetChainId || {});
176
- var TransactionHashPrefix = /* @__PURE__ */ ((TransactionHashPrefix2) => {
177
- TransactionHashPrefix2["DECLARE"] = "0x6465636c617265";
178
- TransactionHashPrefix2["DEPLOY"] = "0x6465706c6f79";
179
- TransactionHashPrefix2["DEPLOY_ACCOUNT"] = "0x6465706c6f795f6163636f756e74";
180
- TransactionHashPrefix2["INVOKE"] = "0x696e766f6b65";
181
- TransactionHashPrefix2["L1_HANDLER"] = "0x6c315f68616e646c6572";
182
- return TransactionHashPrefix2;
183
- })(TransactionHashPrefix || {});
184
161
  var UDC = {
185
162
  ADDRESS: "0x041a78e741e5af2fec34b695679bc6891742439f7afb8484ecd7766661ad02bf",
186
163
  ENTRYPOINT: "deployContract"
@@ -190,13 +167,41 @@ var SNIP9_V1_INTERFACE_ID = "0x68cfd18b92d1907b8ba3cc324900277f5a3622099431ea85d
190
167
  var SNIP9_V2_INTERFACE_ID = "0x1d1144bb2138366ff28d8e9ab57456b1d332ac42196230c3a602003c89872";
191
168
  var HARDENING_BYTE = 128;
192
169
  var HARDENING_4BYTES = 2147483648n;
193
- var SupportedRpcVersion = {
194
- 0.7: "0.7",
195
- 0.8: "0.8"
170
+ var _BaseUrl = {
171
+ SN_MAIN: "https://alpha-mainnet.starknet.io",
172
+ SN_SEPOLIA: "https://alpha-sepolia.starknet.io"
173
+ };
174
+ var _NetworkName = {
175
+ SN_MAIN: "SN_MAIN",
176
+ SN_SEPOLIA: "SN_SEPOLIA"
177
+ };
178
+ var _StarknetChainId = {
179
+ SN_MAIN: "0x534e5f4d41494e",
180
+ // encodeShortString('SN_MAIN'),
181
+ SN_SEPOLIA: "0x534e5f5345504f4c4941"
182
+ // encodeShortString('SN_SEPOLIA')
183
+ };
184
+ var _TransactionHashPrefix = {
185
+ DECLARE: "0x6465636c617265",
186
+ // encodeShortString('declare'),
187
+ DEPLOY: "0x6465706c6f79",
188
+ // encodeShortString('deploy'),
189
+ DEPLOY_ACCOUNT: "0x6465706c6f795f6163636f756e74",
190
+ // encodeShortString('deploy_account'),
191
+ INVOKE: "0x696e766f6b65",
192
+ // encodeShortString('invoke'),
193
+ L1_HANDLER: "0x6c315f68616e646c6572"
194
+ // encodeShortString('l1_handler'),
195
+ };
196
+ var _SupportedRpcVersion = {
197
+ "0.7.1": "0.7.1",
198
+ "0.8.1": "0.8.1",
199
+ v0_7_1: "0.7.1",
200
+ v0_8_1: "0.8.1"
196
201
  };
197
202
  var DEFAULT_GLOBAL_CONFIG = {
198
203
  legacyMode: false,
199
- rpcVersion: "0.8",
204
+ rpcVersion: "0.8.1",
200
205
  transactionVersion: api_exports.ETransactionVersion.V3,
201
206
  logLevel: "INFO",
202
207
  feeMarginPercentage: {
@@ -215,7 +220,9 @@ var DEFAULT_GLOBAL_CONFIG = {
215
220
  }
216
221
  },
217
222
  maxFee: 50
218
- }
223
+ },
224
+ fetch: void 0,
225
+ websocket: void 0
219
226
  };
220
227
  var RPC_DEFAULT_NODES = {
221
228
  SN_MAIN: [
@@ -230,157 +237,233 @@ var RPC_DEFAULT_NODES = {
230
237
  var SYSTEM_MESSAGES = {
231
238
  legacyTxWarningMessage: "You are using a deprecated transaction version (V0,V1,V2)!\nUpdate to the latest V3 transactions!",
232
239
  legacyTxRPC08Message: "RPC 0.8 do not support legacy transactions",
233
- SWOldV3: "RPC 0.7 V3 tx (improper resource bounds) not supported in RPC 0.8"
240
+ SWOldV3: "RPC 0.7 V3 tx (improper resource bounds) not supported in RPC 0.8",
241
+ channelVersionMismatch: "Channel specification version is not compatible with the connected node Specification Version",
242
+ unsupportedSpecVersion: "The connected node specification version is not supported by this library"
234
243
  };
235
244
 
236
- // src/channel/rpc_0_7.ts
237
- var rpc_0_7_exports = {};
238
- __export(rpc_0_7_exports, {
239
- RpcChannel: () => RpcChannel
240
- });
241
-
242
- // src/utils/json.ts
243
- var json_exports = {};
244
- __export(json_exports, {
245
- parse: () => parse2,
246
- parseAlwaysAsBig: () => parseAlwaysAsBig,
247
- stringify: () => stringify2
248
- });
249
- import * as json from "lossless-json";
250
- var parseIntAsNumberOrBigInt = (str) => {
251
- if (!json.isInteger(str)) return parseFloat(str);
252
- const num = parseInt(str, 10);
253
- return Number.isSafeInteger(num) ? num : BigInt(str);
245
+ // src/global/config.ts
246
+ var Configuration = class _Configuration {
247
+ static instance;
248
+ config;
249
+ constructor() {
250
+ this.initialize();
251
+ }
252
+ initialize() {
253
+ this.config = { ...DEFAULT_GLOBAL_CONFIG };
254
+ }
255
+ static getInstance() {
256
+ if (!_Configuration.instance) {
257
+ _Configuration.instance = new _Configuration();
258
+ }
259
+ return _Configuration.instance;
260
+ }
261
+ get(key, defaultValue) {
262
+ return this.config[key] ?? defaultValue;
263
+ }
264
+ set(key, value) {
265
+ this.config[key] = value;
266
+ }
267
+ update(configData) {
268
+ this.config = {
269
+ ...this.config,
270
+ ...configData
271
+ };
272
+ }
273
+ getAll() {
274
+ return { ...this.config };
275
+ }
276
+ reset() {
277
+ this.initialize();
278
+ }
279
+ delete(key) {
280
+ delete this.config[key];
281
+ }
282
+ hasKey(key) {
283
+ return key in this.config;
284
+ }
254
285
  };
255
- var parse2 = (str) => json.parse(String(str), void 0, parseIntAsNumberOrBigInt);
256
- var parseAlwaysAsBig = (str) => json.parse(String(str), void 0, json.parseNumberAndBigInt);
257
- var stringify2 = (value, replacer, space, numberStringifiers) => json.stringify(value, replacer, space, numberStringifiers);
286
+ var config = Configuration.getInstance();
258
287
 
259
- // src/utils/errors/rpc.ts
260
- var errorCodes = {
261
- FAILED_TO_RECEIVE_TXN: 1,
262
- NO_TRACE_AVAILABLE: 10,
263
- CONTRACT_NOT_FOUND: 20,
264
- ENTRYPOINT_NOT_FOUND: 21,
265
- BLOCK_NOT_FOUND: 24,
266
- INVALID_TXN_INDEX: 27,
267
- CLASS_HASH_NOT_FOUND: 28,
268
- TXN_HASH_NOT_FOUND: 29,
269
- PAGE_SIZE_TOO_BIG: 31,
270
- NO_BLOCKS: 32,
271
- INVALID_CONTINUATION_TOKEN: 33,
272
- TOO_MANY_KEYS_IN_FILTER: 34,
273
- CONTRACT_ERROR: 40,
274
- TRANSACTION_EXECUTION_ERROR: 41,
275
- STORAGE_PROOF_NOT_SUPPORTED: 42,
276
- CLASS_ALREADY_DECLARED: 51,
277
- INVALID_TRANSACTION_NONCE: 52,
278
- INSUFFICIENT_RESOURCES_FOR_VALIDATE: 53,
279
- INSUFFICIENT_ACCOUNT_BALANCE: 54,
280
- VALIDATION_FAILURE: 55,
281
- COMPILATION_FAILED: 56,
282
- CONTRACT_CLASS_SIZE_IS_TOO_LARGE: 57,
283
- NON_ACCOUNT: 58,
284
- DUPLICATE_TX: 59,
285
- COMPILED_CLASS_HASH_MISMATCH: 60,
286
- UNSUPPORTED_TX_VERSION: 61,
287
- UNSUPPORTED_CONTRACT_CLASS_VERSION: 62,
288
- UNEXPECTED_ERROR: 63,
289
- INVALID_SUBSCRIPTION_ID: 66,
290
- TOO_MANY_ADDRESSES_IN_FILTER: 67,
291
- TOO_MANY_BLOCKS_BACK: 68,
292
- COMPILATION_ERROR: 100
288
+ // src/global/logger.type.ts
289
+ var LogLevelIndex = {
290
+ DEBUG: 5,
291
+ INFO: 4,
292
+ WARN: 3,
293
+ ERROR: 2,
294
+ FATAL: 1,
295
+ OFF: 0
293
296
  };
294
- var rpc_default = errorCodes;
295
297
 
296
- // src/utils/errors/index.ts
297
- function fixStack(target, fn = target.constructor) {
298
- const { captureStackTrace } = Error;
299
- captureStackTrace && captureStackTrace(target, fn);
300
- }
301
- function fixProto(target, prototype) {
302
- const { setPrototypeOf } = Object;
303
- setPrototypeOf ? setPrototypeOf(target, prototype) : target.__proto__ = prototype;
304
- }
305
- var CustomError = class extends Error {
306
- name;
307
- constructor(message) {
308
- super(message);
309
- Object.defineProperty(this, "name", {
310
- value: new.target.name,
311
- enumerable: false,
312
- configurable: true
313
- });
314
- fixProto(this, new.target.prototype);
315
- fixStack(this);
298
+ // src/global/logger.ts
299
+ var Logger = class _Logger {
300
+ static instance;
301
+ config;
302
+ constructor() {
303
+ this.config = config;
316
304
  }
317
- };
318
- var LibraryError = class extends CustomError {
319
- };
320
- var RpcError = class extends LibraryError {
321
- constructor(baseError, method, params) {
322
- super(`RPC: ${method} with params ${stringify2(params, null, 2)}
323
-
324
- ${baseError.code}: ${baseError.message}: ${stringify2(baseError.data)}`);
325
- this.baseError = baseError;
326
- this.request = { method, params };
305
+ static getInstance() {
306
+ if (!_Logger.instance) {
307
+ _Logger.instance = new _Logger();
308
+ }
309
+ return _Logger.instance;
327
310
  }
328
- request;
329
- get code() {
330
- return this.baseError.code;
311
+ getTimestamp() {
312
+ return (/* @__PURE__ */ new Date()).toISOString();
313
+ }
314
+ shouldLog(messageLevel) {
315
+ const configLevel = this.config.get("logLevel", "INFO");
316
+ return messageLevel <= LogLevelIndex[configLevel];
317
+ }
318
+ formatMessage(logMessage) {
319
+ const { level, message, timestamp, data } = logMessage;
320
+ let formattedMessage = `[${timestamp}] ${level}: ${message}`;
321
+ if (data) {
322
+ try {
323
+ formattedMessage += `
324
+ ${JSON.stringify(data, null, 2)}`;
325
+ } catch (error) {
326
+ formattedMessage += `
327
+ [JSON.stringify Error/Circular]: ${error}`;
328
+ }
329
+ }
330
+ return formattedMessage;
331
+ }
332
+ log(level, message, data) {
333
+ if (!this.shouldLog(LogLevelIndex[level])) {
334
+ return;
335
+ }
336
+ const logMessage = {
337
+ level,
338
+ message,
339
+ timestamp: this.getTimestamp(),
340
+ data
341
+ };
342
+ const formattedMessage = this.formatMessage(logMessage);
343
+ switch (level) {
344
+ case "DEBUG":
345
+ console.debug(formattedMessage);
346
+ break;
347
+ case "INFO":
348
+ console.info(formattedMessage);
349
+ break;
350
+ case "WARN":
351
+ console.warn(formattedMessage);
352
+ break;
353
+ case "ERROR":
354
+ case "FATAL":
355
+ console.error(formattedMessage);
356
+ break;
357
+ case "OFF":
358
+ break;
359
+ default:
360
+ console.log(formattedMessage);
361
+ break;
362
+ }
331
363
  }
332
364
  /**
333
- * Verifies the underlying RPC error, also serves as a type guard for the _baseError_ property
334
- * @example
335
- * ```typescript
336
- * SomeError.isType('UNEXPECTED_ERROR');
337
- * ```
365
+ * debug will be displayed when LogLevel level is set to DEBUG(5)
338
366
  */
339
- isType(typeName) {
340
- return rpc_default[typeName] === this.code;
367
+ debug(message, data) {
368
+ this.log("DEBUG", message, data);
341
369
  }
342
- };
343
-
344
- // src/types/index.ts
345
- var types_exports = {};
346
- __export(types_exports, {
347
- BlockStatus: () => BlockStatus,
348
- BlockTag: () => BlockTag,
349
- EDAMode: () => EDAMode,
350
- EDataAvailabilityMode: () => EDataAvailabilityMode,
351
- ETH_ADDRESS: () => ETH_ADDRESS,
352
- ETransactionExecutionStatus: () => ETransactionExecutionStatus,
353
- ETransactionStatus: () => ETransactionStatus,
354
- ETransactionVersion: () => ETransactionVersion2,
355
- ETransactionVersion2: () => ETransactionVersion22,
356
- ETransactionVersion3: () => ETransactionVersion3,
357
- EntryPointType: () => EntryPointType,
358
- Literal: () => Literal,
359
- NON_ZERO_PREFIX: () => NON_ZERO_PREFIX,
360
- OutsideExecutionTypesV1: () => OutsideExecutionTypesV1,
361
- OutsideExecutionTypesV2: () => OutsideExecutionTypesV2,
362
- OutsideExecutionVersion: () => OutsideExecutionVersion,
363
- RPC: () => api_exports,
364
- TransactionExecutionStatus: () => TransactionExecutionStatus,
365
- TransactionFinalityStatus: () => TransactionFinalityStatus,
366
- TransactionType: () => TransactionType,
367
- TypedDataRevision: () => TypedDataRevision,
368
- Uint: () => Uint,
369
- ValidateType: () => ValidateType,
370
- isRPC08_FeeEstimate: () => isRPC08_FeeEstimate,
371
- isRPC08_ResourceBounds: () => isRPC08_ResourceBounds
372
- });
373
-
374
- // src/types/lib/contract/index.ts
375
- var EntryPointType = {
376
- EXTERNAL: "EXTERNAL",
377
- L1_HANDLER: "L1_HANDLER",
378
- CONSTRUCTOR: "CONSTRUCTOR"
379
- };
380
-
381
- // src/types/lib/index.ts
382
- var TransactionType = {
383
- DECLARE: "DECLARE",
370
+ /**
371
+ * info will be displayed when LogLevel level is set to DEBUG(5), INFO(4)
372
+ */
373
+ info(message, data) {
374
+ this.log("INFO", message, data);
375
+ }
376
+ /**
377
+ * warn will be displayed when LogLevel level is set to DEBUG(5), INFO(4), WARN(3)
378
+ */
379
+ warn(message, data) {
380
+ this.log("WARN", message, data);
381
+ }
382
+ /**
383
+ * error will be displayed when LogLevel level is set to DEBUG(5), INFO(4), WARN(3), ERROR(2)
384
+ */
385
+ error(message, data) {
386
+ this.log("ERROR", message, data);
387
+ }
388
+ /**
389
+ * fatal will be displayed when LogLevel level is set to DEBUG(5), INFO(4), WARN(3), ERROR(2), FATAL(1)
390
+ */
391
+ fatal(message, data) {
392
+ this.log("FATAL", message, data);
393
+ }
394
+ /**
395
+ * Set the logging level you would like system to display
396
+ * * 5 DEBUG - show all logs
397
+ * * 4 INFO
398
+ * * 3 WARN
399
+ * * 2 ERROR
400
+ * * 1 FATAL
401
+ * * 0 OFF - disable logs
402
+ */
403
+ setLogLevel(level) {
404
+ this.config.set("logLevel", level);
405
+ }
406
+ getLogLevel() {
407
+ return this.config.get("logLevel", "INFO");
408
+ }
409
+ /**
410
+ *
411
+ * @returns logs levels displayed on the configured LogLevel
412
+ */
413
+ getEnabledLogLevels() {
414
+ return Object.keys(LogLevelIndex).filter((s) => {
415
+ return this.shouldLog(LogLevelIndex[s]) && s !== "OFF";
416
+ });
417
+ }
418
+ };
419
+ var logger = Logger.getInstance();
420
+
421
+ // src/channel/rpc_0_7_1.ts
422
+ var rpc_0_7_1_exports = {};
423
+ __export(rpc_0_7_1_exports, {
424
+ RpcChannel: () => RpcChannel
425
+ });
426
+
427
+ // src/types/index.ts
428
+ var types_exports = {};
429
+ __export(types_exports, {
430
+ BlockStatus: () => BlockStatus,
431
+ BlockTag: () => BlockTag,
432
+ EDAMode: () => EDAMode,
433
+ EDataAvailabilityMode: () => EDataAvailabilityMode,
434
+ ETH_ADDRESS: () => ETH_ADDRESS,
435
+ ETransactionExecutionStatus: () => ETransactionExecutionStatus,
436
+ ETransactionStatus: () => ETransactionStatus,
437
+ ETransactionVersion: () => ETransactionVersion2,
438
+ ETransactionVersion2: () => ETransactionVersion22,
439
+ ETransactionVersion3: () => ETransactionVersion3,
440
+ EntryPointType: () => EntryPointType,
441
+ Literal: () => Literal,
442
+ NON_ZERO_PREFIX: () => NON_ZERO_PREFIX,
443
+ OutsideExecutionTypesV1: () => OutsideExecutionTypesV1,
444
+ OutsideExecutionTypesV2: () => OutsideExecutionTypesV2,
445
+ OutsideExecutionVersion: () => OutsideExecutionVersion,
446
+ RPC: () => api_exports,
447
+ TransactionExecutionStatus: () => TransactionExecutionStatus,
448
+ TransactionFinalityStatus: () => TransactionFinalityStatus,
449
+ TransactionType: () => TransactionType,
450
+ TypedDataRevision: () => TypedDataRevision,
451
+ Uint: () => Uint,
452
+ ValidateType: () => ValidateType,
453
+ isRPC08_FeeEstimate: () => isRPC08_FeeEstimate,
454
+ isRPC08_ResourceBounds: () => isRPC08_ResourceBounds
455
+ });
456
+
457
+ // src/types/lib/contract/index.ts
458
+ var EntryPointType = {
459
+ EXTERNAL: "EXTERNAL",
460
+ L1_HANDLER: "L1_HANDLER",
461
+ CONSTRUCTOR: "CONSTRUCTOR"
462
+ };
463
+
464
+ // src/types/lib/index.ts
465
+ var TransactionType = {
466
+ DECLARE: "DECLARE",
384
467
  DEPLOY: "DEPLOY",
385
468
  DEPLOY_ACCOUNT: "DEPLOY_ACCOUNT",
386
469
  INVOKE: "INVOKE_FUNCTION"
@@ -493,18 +576,34 @@ var OutsideExecutionTypesV2 = {
493
576
  { name: "Calldata", type: "felt*" }
494
577
  ]
495
578
  };
496
- var OutsideExecutionVersion = /* @__PURE__ */ ((OutsideExecutionVersion2) => {
497
- OutsideExecutionVersion2["UNSUPPORTED"] = "0";
498
- OutsideExecutionVersion2["V1"] = "1";
499
- OutsideExecutionVersion2["V2"] = "2";
500
- return OutsideExecutionVersion2;
501
- })(OutsideExecutionVersion || {});
579
+ var OutsideExecutionVersion = {
580
+ UNSUPPORTED: "0",
581
+ V1: "1",
582
+ V2: "2"
583
+ };
502
584
 
503
585
  // src/types/typedData.ts
504
586
  import {
505
587
  TypedDataRevision
506
588
  } from "starknet-types-07";
507
589
 
590
+ // src/utils/json.ts
591
+ var json_exports = {};
592
+ __export(json_exports, {
593
+ parse: () => parse2,
594
+ parseAlwaysAsBig: () => parseAlwaysAsBig,
595
+ stringify: () => stringify2
596
+ });
597
+ import * as json from "lossless-json";
598
+ var parseIntAsNumberOrBigInt = (str) => {
599
+ if (!json.isInteger(str)) return parseFloat(str);
600
+ const num = parseInt(str, 10);
601
+ return Number.isSafeInteger(num) ? num : BigInt(str);
602
+ };
603
+ var parse2 = (str) => json.parse(String(str), void 0, parseIntAsNumberOrBigInt);
604
+ var parseAlwaysAsBig = (str) => json.parse(String(str), void 0, json.parseNumberAndBigInt);
605
+ var stringify2 = (value, replacer, space, numberStringifiers) => json.stringify(value, replacer, space, numberStringifiers);
606
+
508
607
  // src/utils/batch/index.ts
509
608
  var BatchClient = class {
510
609
  nodeUrl;
@@ -2990,7 +3089,7 @@ function calculateTransactionHashCommon(txHashPrefix, version, contractAddress,
2990
3089
  }
2991
3090
  function calculateDeclareTransactionHash(classHash, senderAddress, version, maxFee, chainId, nonce, compiledClassHash) {
2992
3091
  return calculateTransactionHashCommon(
2993
- "0x6465636c617265" /* DECLARE */,
3092
+ _TransactionHashPrefix.DECLARE,
2994
3093
  version,
2995
3094
  senderAddress,
2996
3095
  0,
@@ -3003,7 +3102,7 @@ function calculateDeclareTransactionHash(classHash, senderAddress, version, maxF
3003
3102
  function calculateDeployAccountTransactionHash(contractAddress, classHash, constructorCalldata, salt, version, maxFee, chainId, nonce) {
3004
3103
  const calldata = [classHash, salt, ...constructorCalldata];
3005
3104
  return calculateTransactionHashCommon(
3006
- "0x6465706c6f795f6163636f756e74" /* DEPLOY_ACCOUNT */,
3105
+ _TransactionHashPrefix.DEPLOY_ACCOUNT,
3007
3106
  version,
3008
3107
  contractAddress,
3009
3108
  0,
@@ -3015,7 +3114,7 @@ function calculateDeployAccountTransactionHash(contractAddress, classHash, const
3015
3114
  }
3016
3115
  function calculateTransactionHash(contractAddress, version, calldata, maxFee, chainId, nonce) {
3017
3116
  return calculateTransactionHashCommon(
3018
- "0x696e766f6b65" /* INVOKE */,
3117
+ _TransactionHashPrefix.INVOKE,
3019
3118
  version,
3020
3119
  contractAddress,
3021
3120
  0,
@@ -3028,7 +3127,7 @@ function calculateTransactionHash(contractAddress, version, calldata, maxFee, ch
3028
3127
  function calculateL2MessageTxHash(l1FromAddress, l2ToAddress, l2Selector, l2Calldata, l2ChainId, l1Nonce) {
3029
3128
  const payload = [l1FromAddress, ...l2Calldata];
3030
3129
  return calculateTransactionHashCommon(
3031
- "0x6c315f68616e646c6572" /* L1_HANDLER */,
3130
+ _TransactionHashPrefix.L1_HANDLER,
3032
3131
  0,
3033
3132
  l2ToAddress,
3034
3133
  getSelector(l2Selector),
@@ -3103,7 +3202,7 @@ function calculateTransactionHashCommon2(txHashPrefix, version, senderAddress, c
3103
3202
  }
3104
3203
  function calculateDeployAccountTransactionHash2(contractAddress, classHash, compiledConstructorCalldata, salt, version, chainId, nonce, nonceDataAvailabilityMode, feeDataAvailabilityMode, resourceBounds, tip, paymasterData) {
3105
3204
  return calculateTransactionHashCommon2(
3106
- "0x6465706c6f795f6163636f756e74" /* DEPLOY_ACCOUNT */,
3205
+ _TransactionHashPrefix.DEPLOY_ACCOUNT,
3107
3206
  version,
3108
3207
  contractAddress,
3109
3208
  chainId,
@@ -3118,7 +3217,7 @@ function calculateDeployAccountTransactionHash2(contractAddress, classHash, comp
3118
3217
  }
3119
3218
  function calculateDeclareTransactionHash2(classHash, compiledClassHash, senderAddress, version, chainId, nonce, accountDeploymentData, nonceDataAvailabilityMode, feeDataAvailabilityMode, resourceBounds, tip, paymasterData) {
3120
3219
  return calculateTransactionHashCommon2(
3121
- "0x6465636c617265" /* DECLARE */,
3220
+ _TransactionHashPrefix.DECLARE,
3122
3221
  version,
3123
3222
  senderAddress,
3124
3223
  chainId,
@@ -3133,7 +3232,7 @@ function calculateDeclareTransactionHash2(classHash, compiledClassHash, senderAd
3133
3232
  }
3134
3233
  function calculateInvokeTransactionHash(senderAddress, version, compiledCalldata, chainId, nonce, accountDeploymentData, nonceDataAvailabilityMode, feeDataAvailabilityMode, resourceBounds, tip, paymasterData) {
3135
3234
  return calculateTransactionHashCommon2(
3136
- "0x696e766f6b65" /* INVOKE */,
3235
+ _TransactionHashPrefix.INVOKE,
3137
3236
  version,
3138
3237
  senderAddress,
3139
3238
  chainId,
@@ -3422,6 +3521,38 @@ __export(stark_exports, {
3422
3521
  import { getPublicKey, getStarkKey, utils } from "@scure/starknet";
3423
3522
  import { gzip, ungzip } from "pako";
3424
3523
 
3524
+ // src/utils/resolve.ts
3525
+ function isV3Tx(details) {
3526
+ const version = details.version ? toHex(details.version) : ETransactionVersion2.V3;
3527
+ return version === ETransactionVersion2.V3 || version === ETransactionVersion2.F3;
3528
+ }
3529
+ function isVersion(expected, provided) {
3530
+ const expectedParts = expected.split(".");
3531
+ const providedParts = provided.split(".");
3532
+ return expectedParts.every((part, index) => part === "*" || part === providedParts[index]);
3533
+ }
3534
+ function isSupportedSpecVersion(version, options = { allowAnyPatchVersion: false }) {
3535
+ return Object.values(_SupportedRpcVersion).some(
3536
+ (v) => isVersion(options.allowAnyPatchVersion ? toAnyPatchVersion(v) : v, version)
3537
+ );
3538
+ }
3539
+ function toAnyPatchVersion(version) {
3540
+ const parts = version.split(".");
3541
+ if (parts.length < 3) {
3542
+ return version;
3543
+ }
3544
+ return `${parts[0]}.${parts[1]}.*`;
3545
+ }
3546
+ function isPendingBlock(response) {
3547
+ return response.status === "PENDING";
3548
+ }
3549
+ function isPendingTransaction(response) {
3550
+ return !("block_hash" in response);
3551
+ }
3552
+ function isPendingStateUpdate(response) {
3553
+ return !("block_hash" in response);
3554
+ }
3555
+
3425
3556
  // src/utils/stark/rpc07.ts
3426
3557
  function estimateFeeToBounds(estimate, overhead) {
3427
3558
  const maxUnits = estimate.data_gas_consumed !== void 0 && estimate.data_gas_price !== void 0 ? toHex(
@@ -3461,49 +3592,6 @@ function estimateFeeToBounds2(estimate, overhead) {
3461
3592
  };
3462
3593
  }
3463
3594
 
3464
- // src/global/config.ts
3465
- var Configuration = class _Configuration {
3466
- static instance;
3467
- config;
3468
- constructor() {
3469
- this.initialize();
3470
- }
3471
- initialize() {
3472
- this.config = { ...DEFAULT_GLOBAL_CONFIG };
3473
- }
3474
- static getInstance() {
3475
- if (!_Configuration.instance) {
3476
- _Configuration.instance = new _Configuration();
3477
- }
3478
- return _Configuration.instance;
3479
- }
3480
- get(key, defaultValue) {
3481
- return this.config[key] ?? defaultValue;
3482
- }
3483
- set(key, value) {
3484
- this.config[key] = value;
3485
- }
3486
- update(configData) {
3487
- this.config = {
3488
- ...this.config,
3489
- ...configData
3490
- };
3491
- }
3492
- getAll() {
3493
- return { ...this.config };
3494
- }
3495
- reset() {
3496
- this.initialize();
3497
- }
3498
- delete(key) {
3499
- delete this.config[key];
3500
- }
3501
- hasKey(key) {
3502
- return key in this.config;
3503
- }
3504
- };
3505
- var config = Configuration.getInstance();
3506
-
3507
3595
  // src/utils/stark/index.ts
3508
3596
  function compressProgram(jsonProgram) {
3509
3597
  const stringified = isString(jsonProgram) ? jsonProgram : stringify2(jsonProgram);
@@ -3545,7 +3633,7 @@ function estimateFeeToBounds3(estimate, overhead = config.get("feeMarginPercenta
3545
3633
  return {
3546
3634
  l2_gas: { max_amount: "0x0", max_price_per_unit: "0x0" },
3547
3635
  l1_gas: { max_amount: "0x0", max_price_per_unit: "0x0" },
3548
- ...specVersion === "0.8" && {
3636
+ ...specVersion && isVersion("0.8", specVersion) && {
3549
3637
  l1_data_gas: { max_amount: "0x0", max_price_per_unit: "0x0" }
3550
3638
  }
3551
3639
  };
@@ -3644,185 +3732,126 @@ function contractClassResponseToLegacyCompiledContract(ccr) {
3644
3732
  return { ...contract, program: decompressProgram(contract.program) };
3645
3733
  }
3646
3734
 
3647
- // src/utils/eth.ts
3648
- var eth_exports = {};
3649
- __export(eth_exports, {
3650
- ethRandomPrivateKey: () => ethRandomPrivateKey,
3651
- validateAndParseEthAddress: () => validateAndParseEthAddress
3652
- });
3653
- import { secp256k1 } from "@noble/curves/secp256k1";
3654
- function ethRandomPrivateKey() {
3655
- return sanitizeHex(buf2hex(secp256k1.utils.randomPrivateKey()));
3735
+ // src/utils/errors/rpc.ts
3736
+ var errorCodes = {
3737
+ FAILED_TO_RECEIVE_TXN: 1,
3738
+ NO_TRACE_AVAILABLE: 10,
3739
+ CONTRACT_NOT_FOUND: 20,
3740
+ ENTRYPOINT_NOT_FOUND: 21,
3741
+ BLOCK_NOT_FOUND: 24,
3742
+ INVALID_TXN_INDEX: 27,
3743
+ CLASS_HASH_NOT_FOUND: 28,
3744
+ TXN_HASH_NOT_FOUND: 29,
3745
+ PAGE_SIZE_TOO_BIG: 31,
3746
+ NO_BLOCKS: 32,
3747
+ INVALID_CONTINUATION_TOKEN: 33,
3748
+ TOO_MANY_KEYS_IN_FILTER: 34,
3749
+ CONTRACT_ERROR: 40,
3750
+ TRANSACTION_EXECUTION_ERROR: 41,
3751
+ STORAGE_PROOF_NOT_SUPPORTED: 42,
3752
+ CLASS_ALREADY_DECLARED: 51,
3753
+ INVALID_TRANSACTION_NONCE: 52,
3754
+ INSUFFICIENT_RESOURCES_FOR_VALIDATE: 53,
3755
+ INSUFFICIENT_ACCOUNT_BALANCE: 54,
3756
+ VALIDATION_FAILURE: 55,
3757
+ COMPILATION_FAILED: 56,
3758
+ CONTRACT_CLASS_SIZE_IS_TOO_LARGE: 57,
3759
+ NON_ACCOUNT: 58,
3760
+ DUPLICATE_TX: 59,
3761
+ COMPILED_CLASS_HASH_MISMATCH: 60,
3762
+ UNSUPPORTED_TX_VERSION: 61,
3763
+ UNSUPPORTED_CONTRACT_CLASS_VERSION: 62,
3764
+ UNEXPECTED_ERROR: 63,
3765
+ INVALID_SUBSCRIPTION_ID: 66,
3766
+ TOO_MANY_ADDRESSES_IN_FILTER: 67,
3767
+ TOO_MANY_BLOCKS_BACK: 68,
3768
+ COMPILATION_ERROR: 100
3769
+ };
3770
+ var rpc_default = errorCodes;
3771
+
3772
+ // src/utils/errors/index.ts
3773
+ function fixStack(target, fn = target.constructor) {
3774
+ const { captureStackTrace } = Error;
3775
+ captureStackTrace && captureStackTrace(target, fn);
3656
3776
  }
3657
- function validateAndParseEthAddress(address) {
3658
- assertInRange(address, ZERO, 2n ** 160n - 1n, "Ethereum Address ");
3659
- const result = addHexPrefix(removeHexPrefix(toHex(address)).padStart(40, "0"));
3660
- assert(Boolean(result.match(/^(0x)?[0-9a-f]{40}$/)), "Invalid Ethereum Address Format");
3661
- return result;
3777
+ function fixProto(target, prototype) {
3778
+ const { setPrototypeOf } = Object;
3779
+ setPrototypeOf ? setPrototypeOf(target, prototype) : target.__proto__ = prototype;
3662
3780
  }
3781
+ var CustomError = class extends Error {
3782
+ name;
3783
+ constructor(message) {
3784
+ super(message);
3785
+ Object.defineProperty(this, "name", {
3786
+ value: new.target.name,
3787
+ enumerable: false,
3788
+ configurable: true
3789
+ });
3790
+ fixProto(this, new.target.prototype);
3791
+ fixStack(this);
3792
+ }
3793
+ };
3794
+ var LibraryError = class extends CustomError {
3795
+ };
3796
+ var RpcError = class extends LibraryError {
3797
+ constructor(baseError, method, params) {
3798
+ super(`RPC: ${method} with params ${stringify2(params, null, 2)}
3663
3799
 
3664
- // src/utils/fetch.ts
3665
- var fetch_default = IS_BROWSER && window.fetch.bind(window) || // use built-in fetch in browser if available
3666
- !isUndefined(global) && global.fetch || // use built-in fetch in node, react-native and service worker if available
3667
- // throw with instructions when no fetch is detected
3668
- (() => {
3669
- throw new LibraryError(
3670
- "'fetch()' not detected, use the 'baseFetch' constructor parameter to set it"
3671
- );
3672
- });
3673
-
3674
- // src/utils/provider.ts
3800
+ ${baseError.code}: ${baseError.message}: ${stringify2(baseError.data)}`);
3801
+ this.baseError = baseError;
3802
+ this.request = { method, params };
3803
+ }
3804
+ request;
3805
+ get code() {
3806
+ return this.baseError.code;
3807
+ }
3808
+ /**
3809
+ * Verifies the underlying RPC error, also serves as a type guard for the _baseError_ property
3810
+ * @example
3811
+ * ```typescript
3812
+ * SomeError.isType('UNEXPECTED_ERROR');
3813
+ * ```
3814
+ */
3815
+ isType(typeName) {
3816
+ return rpc_default[typeName] === this.code;
3817
+ }
3818
+ };
3819
+
3820
+ // src/utils/eth.ts
3821
+ var eth_exports = {};
3822
+ __export(eth_exports, {
3823
+ ethRandomPrivateKey: () => ethRandomPrivateKey,
3824
+ validateAndParseEthAddress: () => validateAndParseEthAddress
3825
+ });
3826
+ import { secp256k1 } from "@noble/curves/secp256k1";
3827
+ function ethRandomPrivateKey() {
3828
+ return sanitizeHex(buf2hex(secp256k1.utils.randomPrivateKey()));
3829
+ }
3830
+ function validateAndParseEthAddress(address) {
3831
+ assertInRange(address, ZERO, 2n ** 160n - 1n, "Ethereum Address ");
3832
+ const result = addHexPrefix(removeHexPrefix(toHex(address)).padStart(40, "0"));
3833
+ assert(Boolean(result.match(/^(0x)?[0-9a-f]{40}$/)), "Invalid Ethereum Address Format");
3834
+ return result;
3835
+ }
3836
+
3837
+ // src/utils/connect/fetch.ts
3838
+ var fetch_default = typeof globalThis !== "undefined" && globalThis.fetch.bind(globalThis) || typeof window !== "undefined" && window.fetch.bind(window) || typeof global !== "undefined" && global.fetch.bind(global) || (() => {
3839
+ throw new LibraryError(
3840
+ "'fetch()' not detected, use the 'baseFetch' constructor parameter to set it"
3841
+ );
3842
+ });
3843
+
3844
+ // src/utils/provider.ts
3675
3845
  var provider_exports = {};
3676
3846
  __export(provider_exports, {
3677
3847
  Block: () => Block,
3678
3848
  createSierraContractClass: () => createSierraContractClass,
3679
3849
  getDefaultNodeUrl: () => getDefaultNodeUrl,
3680
3850
  getDefaultNodes: () => getDefaultNodes,
3681
- isPendingBlock: () => isPendingBlock,
3682
- isPendingStateUpdate: () => isPendingStateUpdate,
3683
- isPendingTransaction: () => isPendingTransaction,
3684
- isV3Tx: () => isV3Tx,
3685
- isVersion: () => isVersion,
3686
3851
  parseContract: () => parseContract,
3687
- stringToSpecVersion: () => stringToSpecVersion,
3688
3852
  validBlockTags: () => validBlockTags,
3689
3853
  wait: () => wait
3690
3854
  });
3691
-
3692
- // src/global/logger.type.ts
3693
- var LogLevelIndex = {
3694
- DEBUG: 5,
3695
- INFO: 4,
3696
- WARN: 3,
3697
- ERROR: 2,
3698
- FATAL: 1,
3699
- OFF: 0
3700
- };
3701
-
3702
- // src/global/logger.ts
3703
- var Logger = class _Logger {
3704
- static instance;
3705
- config;
3706
- constructor() {
3707
- this.config = config;
3708
- }
3709
- static getInstance() {
3710
- if (!_Logger.instance) {
3711
- _Logger.instance = new _Logger();
3712
- }
3713
- return _Logger.instance;
3714
- }
3715
- getTimestamp() {
3716
- return (/* @__PURE__ */ new Date()).toISOString();
3717
- }
3718
- shouldLog(messageLevel) {
3719
- const configLevel = this.config.get("logLevel", "INFO");
3720
- return messageLevel <= LogLevelIndex[configLevel];
3721
- }
3722
- formatMessage(logMessage) {
3723
- const { level, message, timestamp, data } = logMessage;
3724
- let formattedMessage = `[${timestamp}] ${level}: ${message}`;
3725
- if (data) {
3726
- try {
3727
- formattedMessage += `
3728
- ${JSON.stringify(data, null, 2)}`;
3729
- } catch (error) {
3730
- formattedMessage += `
3731
- [JSON.stringify Error/Circular]: ${error}`;
3732
- }
3733
- }
3734
- return formattedMessage;
3735
- }
3736
- log(level, message, data) {
3737
- if (!this.shouldLog(LogLevelIndex[level])) {
3738
- return;
3739
- }
3740
- const logMessage = {
3741
- level,
3742
- message,
3743
- timestamp: this.getTimestamp(),
3744
- data
3745
- };
3746
- const formattedMessage = this.formatMessage(logMessage);
3747
- switch (level) {
3748
- case "DEBUG":
3749
- console.debug(formattedMessage);
3750
- break;
3751
- case "INFO":
3752
- console.info(formattedMessage);
3753
- break;
3754
- case "WARN":
3755
- console.warn(formattedMessage);
3756
- break;
3757
- case "ERROR":
3758
- case "FATAL":
3759
- console.error(formattedMessage);
3760
- break;
3761
- case "OFF":
3762
- break;
3763
- default:
3764
- console.log(formattedMessage);
3765
- break;
3766
- }
3767
- }
3768
- /**
3769
- * debug will be displayed when LogLevel level is set to DEBUG(5)
3770
- */
3771
- debug(message, data) {
3772
- this.log("DEBUG", message, data);
3773
- }
3774
- /**
3775
- * info will be displayed when LogLevel level is set to DEBUG(5), INFO(4)
3776
- */
3777
- info(message, data) {
3778
- this.log("INFO", message, data);
3779
- }
3780
- /**
3781
- * warn will be displayed when LogLevel level is set to DEBUG(5), INFO(4), WARN(3)
3782
- */
3783
- warn(message, data) {
3784
- this.log("WARN", message, data);
3785
- }
3786
- /**
3787
- * error will be displayed when LogLevel level is set to DEBUG(5), INFO(4), WARN(3), ERROR(2)
3788
- */
3789
- error(message, data) {
3790
- this.log("ERROR", message, data);
3791
- }
3792
- /**
3793
- * fatal will be displayed when LogLevel level is set to DEBUG(5), INFO(4), WARN(3), ERROR(2), FATAL(1)
3794
- */
3795
- fatal(message, data) {
3796
- this.log("FATAL", message, data);
3797
- }
3798
- /**
3799
- * Set the logging level you would like system to display
3800
- * * 5 DEBUG - show all logs
3801
- * * 4 INFO
3802
- * * 3 WARN
3803
- * * 2 ERROR
3804
- * * 1 FATAL
3805
- * * 0 OFF - disable logs
3806
- */
3807
- setLogLevel(level) {
3808
- this.config.set("logLevel", level);
3809
- }
3810
- getLogLevel() {
3811
- return this.config.get("logLevel", "INFO");
3812
- }
3813
- /**
3814
- *
3815
- * @returns logs levels displayed on the configured LogLevel
3816
- */
3817
- getEnabledLogLevels() {
3818
- return Object.keys(LogLevelIndex).filter((s) => {
3819
- return this.shouldLog(LogLevelIndex[s]) && s !== "OFF";
3820
- });
3821
- }
3822
- };
3823
- var logger = Logger.getInstance();
3824
-
3825
- // src/utils/provider.ts
3826
3855
  function wait(delay) {
3827
3856
  return new Promise((res) => {
3828
3857
  setTimeout(res, delay);
@@ -3851,7 +3880,7 @@ var getDefaultNodeUrl = (networkName, mute = false, rpcVersion) => {
3851
3880
  logger.info("Using default public node url, please provide nodeUrl in provider options!");
3852
3881
  }
3853
3882
  const rpcNodes = getDefaultNodes(rpcVersion ?? config.get("rpcVersion"));
3854
- const nodes = rpcNodes[networkName ?? "SN_SEPOLIA" /* SN_SEPOLIA */];
3883
+ const nodes = rpcNodes[networkName ?? _NetworkName.SN_SEPOLIA];
3855
3884
  const randIdx = Math.floor(Math.random() * nodes.length);
3856
3885
  return nodes[randIdx];
3857
3886
  };
@@ -3963,28 +3992,6 @@ var Block = class {
3963
3992
  valueOf = () => this.number;
3964
3993
  toString = () => this.hash;
3965
3994
  };
3966
- function isV3Tx(details) {
3967
- const version = details.version ? toHex(details.version) : ETransactionVersion2.V3;
3968
- return version === ETransactionVersion2.V3 || version === ETransactionVersion2.F3;
3969
- }
3970
- function isVersion(version, response) {
3971
- const [majorS, minorS] = version.split(".");
3972
- const [majorR, minorR] = response.split(".");
3973
- return majorS === majorR && minorS === minorR;
3974
- }
3975
- function stringToSpecVersion(version) {
3976
- const [major, minor] = version.split(".");
3977
- return `${major}.${minor}`;
3978
- }
3979
- function isPendingBlock(response) {
3980
- return response.status === "PENDING";
3981
- }
3982
- function isPendingTransaction(response) {
3983
- return !("block_hash" in response);
3984
- }
3985
- function isPendingStateUpdate(response) {
3986
- return !("block_hash" in response);
3987
- }
3988
3995
 
3989
3996
  // src/utils/transaction.ts
3990
3997
  var transaction_exports = {};
@@ -4077,14 +4084,18 @@ function getVersionsByType(versionType) {
4077
4084
  } : { v1: ETransactionVersion2.V1, v2: ETransactionVersion2.V2, v3: ETransactionVersion2.V3 };
4078
4085
  }
4079
4086
 
4080
- // src/channel/rpc_0_7.ts
4087
+ // src/channel/rpc_0_7_1.ts
4081
4088
  var defaultOptions = {
4082
4089
  headers: { "Content-Type": "application/json" },
4083
4090
  blockIdentifier: BlockTag.PENDING,
4084
4091
  retries: 200
4085
4092
  };
4086
4093
  var RpcChannel = class {
4087
- id = "RPC07";
4094
+ id = "RPC071";
4095
+ /**
4096
+ * RPC specification version this Channel class implements
4097
+ */
4098
+ channelSpecVersion = _SupportedRpcVersion.v0_7_1;
4088
4099
  nodeUrl;
4089
4100
  headers;
4090
4101
  requestId;
@@ -4093,6 +4104,9 @@ var RpcChannel = class {
4093
4104
  waitMode;
4094
4105
  // behave like web2 rpc and return when tx is processed
4095
4106
  chainId;
4107
+ /**
4108
+ * RPC specification version of the connected node
4109
+ */
4096
4110
  specVersion;
4097
4111
  transactionRetryIntervalFallback;
4098
4112
  batchClient;
@@ -4110,14 +4124,22 @@ var RpcChannel = class {
4110
4124
  transactionRetryIntervalFallback,
4111
4125
  waitMode
4112
4126
  } = optionsOrProvider || {};
4113
- if (Object.values(NetworkName).includes(nodeUrl)) {
4114
- this.nodeUrl = getDefaultNodeUrl(nodeUrl, optionsOrProvider?.default, "0.7");
4127
+ if (Object.values(_NetworkName).includes(nodeUrl)) {
4128
+ this.nodeUrl = getDefaultNodeUrl(
4129
+ nodeUrl,
4130
+ optionsOrProvider?.default,
4131
+ this.channelSpecVersion
4132
+ );
4115
4133
  } else if (nodeUrl) {
4116
4134
  this.nodeUrl = nodeUrl;
4117
4135
  } else {
4118
- this.nodeUrl = getDefaultNodeUrl(void 0, optionsOrProvider?.default, "0.7");
4136
+ this.nodeUrl = getDefaultNodeUrl(
4137
+ void 0,
4138
+ optionsOrProvider?.default,
4139
+ this.channelSpecVersion
4140
+ );
4119
4141
  }
4120
- this.baseFetch = baseFetch ?? fetch_default;
4142
+ this.baseFetch = baseFetch || config.get("fetch") || fetch_default;
4121
4143
  this.blockIdentifier = blockIdentifier ?? defaultOptions.blockIdentifier;
4122
4144
  this.chainId = chainId;
4123
4145
  this.headers = { ...defaultOptions.headers, ...headers };
@@ -4195,24 +4217,32 @@ var RpcChannel = class {
4195
4217
  return this.chainId;
4196
4218
  }
4197
4219
  /**
4198
- * fetch if undefined else just return this.specVersion
4199
- * return this.specVersion as 'M.m'
4200
- * @example this.specVersion = "0.8"
4220
+ * fetch rpc node specVersion
4221
+ * @example this.specVersion = "0.7.1"
4201
4222
  */
4202
- async getSpecVersion() {
4203
- if (!this.specVersion) {
4204
- const extendedVersion = await this.getSpecificationVersion();
4205
- const [major, minor] = extendedVersion.split(".");
4206
- const specVerson = `${major}.${minor}`;
4207
- this.specVersion ??= specVerson;
4208
- }
4209
- return this.specVersion;
4223
+ getSpecVersion() {
4224
+ return this.fetchEndpoint("starknet_specVersion");
4210
4225
  }
4211
4226
  /**
4212
- * fetch spec version in extended format "M.m.p-?"
4227
+ * fetch if undefined test and set specVersion, else just return this.specVersion
4228
+ * @example this.specVersion = "0.7.1"
4213
4229
  */
4214
- getSpecificationVersion() {
4215
- return this.fetchEndpoint("starknet_specVersion");
4230
+ async setUpSpecVersion() {
4231
+ if (!this.specVersion) {
4232
+ const unknownSpecVersion = await this.fetchEndpoint("starknet_specVersion");
4233
+ if (!isVersion(this.channelSpecVersion, unknownSpecVersion)) {
4234
+ logger.error(SYSTEM_MESSAGES.channelVersionMismatch, {
4235
+ channelId: this.id,
4236
+ channelSpecVersion: this.channelSpecVersion,
4237
+ nodeSpecVersion: this.specVersion
4238
+ });
4239
+ }
4240
+ if (!isSupportedSpecVersion(unknownSpecVersion)) {
4241
+ throw new LibraryError(`${SYSTEM_MESSAGES.unsupportedSpecVersion}, channelId: ${this.id}`);
4242
+ }
4243
+ this.specVersion = unknownSpecVersion;
4244
+ }
4245
+ return this.specVersion;
4216
4246
  }
4217
4247
  getNonceForAddress(contractAddress, blockIdentifier = this.blockIdentifier) {
4218
4248
  const contract_address = toHex(contractAddress);
@@ -4679,9 +4709,9 @@ var RpcChannel = class {
4679
4709
  }
4680
4710
  };
4681
4711
 
4682
- // src/channel/rpc_0_8.ts
4683
- var rpc_0_8_exports = {};
4684
- __export(rpc_0_8_exports, {
4712
+ // src/channel/rpc_0_8_1.ts
4713
+ var rpc_0_8_1_exports = {};
4714
+ __export(rpc_0_8_1_exports, {
4685
4715
  RpcChannel: () => RpcChannel2
4686
4716
  });
4687
4717
  var defaultOptions2 = {
@@ -4690,7 +4720,11 @@ var defaultOptions2 = {
4690
4720
  retries: 200
4691
4721
  };
4692
4722
  var RpcChannel2 = class {
4693
- id = "RPC08";
4723
+ id = "RPC081";
4724
+ /**
4725
+ * RPC specification version this Channel class implements
4726
+ */
4727
+ channelSpecVersion = _SupportedRpcVersion.v0_8_1;
4694
4728
  nodeUrl;
4695
4729
  headers;
4696
4730
  requestId;
@@ -4699,6 +4733,9 @@ var RpcChannel2 = class {
4699
4733
  waitMode;
4700
4734
  // behave like web2 rpc and return when tx is processed
4701
4735
  chainId;
4736
+ /**
4737
+ * RPC specification version of the connected node
4738
+ */
4702
4739
  specVersion;
4703
4740
  transactionRetryIntervalFallback;
4704
4741
  batchClient;
@@ -4716,14 +4753,22 @@ var RpcChannel2 = class {
4716
4753
  transactionRetryIntervalFallback,
4717
4754
  waitMode
4718
4755
  } = optionsOrProvider || {};
4719
- if (Object.values(NetworkName).includes(nodeUrl)) {
4720
- this.nodeUrl = getDefaultNodeUrl(nodeUrl, optionsOrProvider?.default, "0.8");
4756
+ if (Object.values(_NetworkName).includes(nodeUrl)) {
4757
+ this.nodeUrl = getDefaultNodeUrl(
4758
+ nodeUrl,
4759
+ optionsOrProvider?.default,
4760
+ this.channelSpecVersion
4761
+ );
4721
4762
  } else if (nodeUrl) {
4722
4763
  this.nodeUrl = nodeUrl;
4723
4764
  } else {
4724
- this.nodeUrl = getDefaultNodeUrl(void 0, optionsOrProvider?.default, "0.8");
4765
+ this.nodeUrl = getDefaultNodeUrl(
4766
+ void 0,
4767
+ optionsOrProvider?.default,
4768
+ this.channelSpecVersion
4769
+ );
4725
4770
  }
4726
- this.baseFetch = baseFetch ?? fetch_default;
4771
+ this.baseFetch = baseFetch || config.get("fetch") || fetch_default;
4727
4772
  this.blockIdentifier = blockIdentifier ?? defaultOptions2.blockIdentifier;
4728
4773
  this.chainId = chainId;
4729
4774
  this.headers = { ...defaultOptions2.headers, ...headers };
@@ -4799,6 +4844,34 @@ var RpcChannel2 = class {
4799
4844
  this.chainId ??= await this.fetchEndpoint("starknet_chainId");
4800
4845
  return this.chainId;
4801
4846
  }
4847
+ /**
4848
+ * fetch rpc node specVersion
4849
+ * @example this.specVersion = "0.7.1"
4850
+ */
4851
+ getSpecVersion() {
4852
+ return this.fetchEndpoint("starknet_specVersion");
4853
+ }
4854
+ /**
4855
+ * fetch if undefined else just return this.specVersion
4856
+ * @example this.specVersion = "0.8.1"
4857
+ */
4858
+ async setUpSpecVersion() {
4859
+ if (!this.specVersion) {
4860
+ const unknownSpecVersion = await this.fetchEndpoint("starknet_specVersion");
4861
+ if (!isVersion(this.channelSpecVersion, unknownSpecVersion)) {
4862
+ logger.error(SYSTEM_MESSAGES.channelVersionMismatch, {
4863
+ channelId: this.id,
4864
+ channelSpecVersion: this.channelSpecVersion,
4865
+ nodeSpecVersion: this.specVersion
4866
+ });
4867
+ }
4868
+ if (!isSupportedSpecVersion(unknownSpecVersion)) {
4869
+ throw new LibraryError(`${SYSTEM_MESSAGES.unsupportedSpecVersion}, channelId: ${this.id}`);
4870
+ }
4871
+ this.specVersion = unknownSpecVersion;
4872
+ }
4873
+ return this.specVersion;
4874
+ }
4802
4875
  // TODO: New Method add test
4803
4876
  /**
4804
4877
  * 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
@@ -4828,26 +4901,6 @@ var RpcChannel2 = class {
4828
4901
  class_hash
4829
4902
  });
4830
4903
  }
4831
- /**
4832
- * fetch if undefined else just return this.specVersion
4833
- * return this.specVersion as 'M.m'
4834
- * @example this.specVersion = "0.8"
4835
- */
4836
- async getSpecVersion() {
4837
- if (!this.specVersion) {
4838
- const extendedVersion = await this.getSpecificationVersion();
4839
- const [major, minor] = extendedVersion.split(".");
4840
- const specVerson = `${major}.${minor}`;
4841
- this.specVersion ??= specVerson;
4842
- }
4843
- return this.specVersion;
4844
- }
4845
- /**
4846
- * fetch spec version in extended format "M.m.p-?"
4847
- */
4848
- getSpecificationVersion() {
4849
- return this.fetchEndpoint("starknet_specVersion");
4850
- }
4851
4904
  getNonceForAddress(contractAddress, blockIdentifier = this.blockIdentifier) {
4852
4905
  const contract_address = toHex(contractAddress);
4853
4906
  const block_id = new Block(blockIdentifier).identifier;
@@ -5229,8 +5282,16 @@ var RpcChannel2 = class {
5229
5282
  }
5230
5283
  };
5231
5284
 
5285
+ // src/utils/connect/ws.ts
5286
+ 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 {
5287
+ constructor() {
5288
+ throw new LibraryError(
5289
+ "WebSocket module not detected, use the 'websocket' constructor parameter to set a compatible connection"
5290
+ );
5291
+ }
5292
+ };
5293
+
5232
5294
  // src/channel/ws_0_8.ts
5233
- import { WebSocket } from "isows";
5234
5295
  var WSSubscriptions = {
5235
5296
  NEW_HEADS: "newHeads",
5236
5297
  EVENTS: "events",
@@ -5355,7 +5416,7 @@ var WebSocketChannel = class {
5355
5416
  constructor(options = {}) {
5356
5417
  const nodeUrl = options.nodeUrl || "http://localhost:3000 ";
5357
5418
  this.nodeUrl = options.websocket ? options.websocket.url : nodeUrl;
5358
- this.websocket = options.websocket ? options.websocket : new WebSocket(nodeUrl);
5419
+ this.websocket = options.websocket || config.get("websocket") || new ws_default(nodeUrl);
5359
5420
  this.websocket.addEventListener("open", this.onOpen.bind(this));
5360
5421
  this.websocket.addEventListener("close", this.onCloseProxy.bind(this));
5361
5422
  this.websocket.addEventListener("message", this.onMessageProxy.bind(this));
@@ -5424,7 +5485,7 @@ var WebSocketChannel = class {
5424
5485
  * Helper to check connection is open
5425
5486
  */
5426
5487
  isConnected() {
5427
- return this.websocket.readyState === WebSocket.OPEN;
5488
+ return this.websocket.readyState === ws_default.OPEN;
5428
5489
  }
5429
5490
  /**
5430
5491
  * await while websocket is connected
@@ -5435,7 +5496,7 @@ var WebSocketChannel = class {
5435
5496
  * ```
5436
5497
  */
5437
5498
  async waitForConnection() {
5438
- if (this.websocket.readyState !== WebSocket.OPEN) {
5499
+ if (this.websocket.readyState !== ws_default.OPEN) {
5439
5500
  return new Promise((resolve, reject) => {
5440
5501
  if (!this.websocket) return;
5441
5502
  this.websocket.onopen = () => resolve(this.websocket.readyState);
@@ -5460,7 +5521,7 @@ var WebSocketChannel = class {
5460
5521
  * ```
5461
5522
  */
5462
5523
  async waitForDisconnection() {
5463
- if (this.websocket.readyState !== WebSocket.CLOSED) {
5524
+ if (this.websocket.readyState !== ws_default.CLOSED) {
5464
5525
  return new Promise((resolve, reject) => {
5465
5526
  if (!this.websocket) return;
5466
5527
  this.websocket.onclose = () => resolve(this.websocket.readyState);
@@ -5513,7 +5574,7 @@ var WebSocketChannel = class {
5513
5574
  * Reconnect re-create this.websocket instance
5514
5575
  */
5515
5576
  reconnect() {
5516
- this.websocket = new WebSocket(this.nodeUrl);
5577
+ this.websocket = new ws_default(this.nodeUrl);
5517
5578
  this.websocket.addEventListener("open", this.onOpen.bind(this));
5518
5579
  this.websocket.addEventListener("close", this.onCloseProxy.bind(this));
5519
5580
  this.websocket.addEventListener("message", this.onMessageProxy.bind(this));
@@ -6228,7 +6289,7 @@ function verifyMessage(message, signature, fullPublicKey, accountAddress) {
6228
6289
  }
6229
6290
 
6230
6291
  // src/provider/rpc.ts
6231
- var RpcProvider = class _RpcProvider {
6292
+ var RpcProvider = class {
6232
6293
  responseParser;
6233
6294
  channel;
6234
6295
  constructor(optionsOrProvider) {
@@ -6238,15 +6299,15 @@ var RpcProvider = class _RpcProvider {
6238
6299
  } else {
6239
6300
  if (optionsOrProvider && optionsOrProvider.specVersion) {
6240
6301
  if (isVersion("0.8", optionsOrProvider.specVersion)) {
6241
- this.channel = new rpc_0_8_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6302
+ this.channel = new rpc_0_8_1_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6242
6303
  } else if (isVersion("0.7", optionsOrProvider.specVersion)) {
6243
- this.channel = new rpc_0_7_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6304
+ this.channel = new rpc_0_7_1_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6244
6305
  } else
6245
6306
  throw new Error(`unsupported channel for spec version: ${optionsOrProvider.specVersion}`);
6246
6307
  } else if (isVersion("0.8", config.get("rpcVersion"))) {
6247
- this.channel = new rpc_0_8_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6308
+ this.channel = new rpc_0_8_1_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6248
6309
  } else if (isVersion("0.7", config.get("rpcVersion"))) {
6249
- this.channel = new rpc_0_7_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6310
+ this.channel = new rpc_0_7_1_exports.RpcChannel({ ...optionsOrProvider, waitMode: false });
6250
6311
  } else throw new Error("unable to define spec version for channel");
6251
6312
  this.responseParser = new RPCResponseParser(optionsOrProvider?.feeMarginPercentage);
6252
6313
  }
@@ -6255,16 +6316,28 @@ var RpcProvider = class _RpcProvider {
6255
6316
  * auto configure channel based on provided node
6256
6317
  * leave space for other async before constructor
6257
6318
  */
6319
+ // NOTE: the generic T and 'this' reference are used so that the expanded class is generated when a mixin is applied
6258
6320
  static async create(optionsOrProvider) {
6259
- const channel = new rpc_0_7_exports.RpcChannel({ ...optionsOrProvider });
6321
+ const channel = new rpc_0_7_1_exports.RpcChannel({ ...optionsOrProvider });
6260
6322
  const spec = await channel.getSpecVersion();
6323
+ if (!isSupportedSpecVersion(spec)) {
6324
+ logger.warn(`Using incompatible node spec version ${spec}`);
6325
+ }
6261
6326
  if (isVersion("0.7", spec)) {
6262
- return new _RpcProvider({ ...optionsOrProvider, specVersion: "0.7" });
6327
+ return new this({
6328
+ ...optionsOrProvider,
6329
+ specVersion: _SupportedRpcVersion.v0_7_1
6330
+ });
6263
6331
  }
6264
6332
  if (isVersion("0.8", spec)) {
6265
- return new _RpcProvider({ ...optionsOrProvider, specVersion: "0.8" });
6333
+ return new this({
6334
+ ...optionsOrProvider,
6335
+ specVersion: _SupportedRpcVersion.v0_8_1
6336
+ });
6266
6337
  }
6267
- throw new Error("unable to detect specification version");
6338
+ throw new LibraryError(
6339
+ `Provided RPC node specification version ${spec} is not compatible with the SDK. SDK supported RPC versions ${Object.keys(_SupportedRpcVersion).toString()}`
6340
+ );
6268
6341
  }
6269
6342
  fetch(method, params, id = 0) {
6270
6343
  return this.channel.fetch(method, params, id);
@@ -6273,16 +6346,22 @@ var RpcProvider = class _RpcProvider {
6273
6346
  return this.channel.getChainId();
6274
6347
  }
6275
6348
  /**
6276
- * return spec version in format "M.m"
6349
+ * read channel spec version
6277
6350
  */
6278
- async getSpecVersion() {
6279
- return this.channel.getSpecVersion();
6351
+ readSpecVersion() {
6352
+ return this.channel.readSpecVersion();
6280
6353
  }
6281
6354
  /**
6282
- * @returns return spec version in format 'M.m.p-rc'
6355
+ * get channel spec version
6283
6356
  */
6284
- async getSpecificationVersion() {
6285
- return this.channel.getSpecificationVersion();
6357
+ async getSpecVersion() {
6358
+ return this.channel.getSpecVersion();
6359
+ }
6360
+ /**
6361
+ * setup channel spec version and return it
6362
+ */
6363
+ setUpSpecVersion() {
6364
+ return this.channel.setUpSpecVersion();
6286
6365
  }
6287
6366
  async getNonceForAddress(contractAddress, blockIdentifier) {
6288
6367
  return this.channel.getNonceForAddress(contractAddress, blockIdentifier);
@@ -6647,18 +6726,18 @@ var RpcProvider = class _RpcProvider {
6647
6726
  /**
6648
6727
  * 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
6649
6728
  */
6650
- getL1MessagesStatus(transactionHash) {
6651
- if (this.channel instanceof rpc_0_8_exports.RpcChannel) {
6652
- this.channel.getMessagesStatus(transactionHash);
6729
+ async getL1MessagesStatus(transactionHash) {
6730
+ if (this.channel instanceof rpc_0_8_1_exports.RpcChannel) {
6731
+ return this.channel.getMessagesStatus(transactionHash);
6653
6732
  }
6654
6733
  throw new LibraryError("Unsupported method for RPC version");
6655
6734
  }
6656
6735
  /**
6657
6736
  * Get merkle paths in one of the state tries: global state, classes, individual contract
6658
6737
  */
6659
- getStorageProof(classHashes, contractAddresses, contractsStorageKeys, blockIdentifier) {
6660
- if (this.channel instanceof rpc_0_8_exports.RpcChannel) {
6661
- this.channel.getStorageProof(
6738
+ async getStorageProof(classHashes, contractAddresses, contractsStorageKeys, blockIdentifier) {
6739
+ if (this.channel instanceof rpc_0_8_1_exports.RpcChannel) {
6740
+ return this.channel.getStorageProof(
6662
6741
  classHashes,
6663
6742
  contractAddresses,
6664
6743
  contractsStorageKeys,
@@ -6670,9 +6749,9 @@ var RpcProvider = class _RpcProvider {
6670
6749
  /**
6671
6750
  * Get the contract class definition in the given block associated with the given hash
6672
6751
  */
6673
- getCompiledCasm(classHash) {
6674
- if (this.channel instanceof rpc_0_8_exports.RpcChannel) {
6675
- this.channel.getCompiledCasm(classHash);
6752
+ async getCompiledCasm(classHash) {
6753
+ if (this.channel instanceof rpc_0_8_1_exports.RpcChannel) {
6754
+ return this.channel.getCompiledCasm(classHash);
6676
6755
  }
6677
6756
  throw new LibraryError("Unsupported method for RPC version");
6678
6757
  }
@@ -6786,9 +6865,9 @@ var StarknetIdContract = {
6786
6865
  };
6787
6866
  function getStarknetIdContract(chainId) {
6788
6867
  switch (chainId) {
6789
- case "0x534e5f4d41494e" /* SN_MAIN */:
6868
+ case _StarknetChainId.SN_MAIN:
6790
6869
  return StarknetIdContract.MAINNET;
6791
- case "0x534e5f5345504f4c4941" /* SN_SEPOLIA */:
6870
+ case _StarknetChainId.SN_SEPOLIA:
6792
6871
  return StarknetIdContract.TESTNET_SEPOLIA;
6793
6872
  default:
6794
6873
  throw new Error("Starknet.id is not yet deployed on this network");
@@ -6800,9 +6879,9 @@ var StarknetIdIdentityContract = {
6800
6879
  };
6801
6880
  function getStarknetIdIdentityContract(chainId) {
6802
6881
  switch (chainId) {
6803
- case "0x534e5f4d41494e" /* SN_MAIN */:
6882
+ case _StarknetChainId.SN_MAIN:
6804
6883
  return StarknetIdIdentityContract.MAINNET;
6805
- case "0x534e5f5345504f4c4941" /* SN_SEPOLIA */:
6884
+ case _StarknetChainId.SN_SEPOLIA:
6806
6885
  return StarknetIdIdentityContract.TESTNET_SEPOLIA;
6807
6886
  default:
6808
6887
  throw new Error("Starknet.id verifier contract is not yet deployed on this network");
@@ -6811,9 +6890,9 @@ function getStarknetIdIdentityContract(chainId) {
6811
6890
  var StarknetIdMulticallContract = "0x034ffb8f4452df7a613a0210824d6414dbadcddce6c6e19bf4ddc9e22ce5f970";
6812
6891
  function getStarknetIdMulticallContract(chainId) {
6813
6892
  switch (chainId) {
6814
- case "0x534e5f4d41494e" /* SN_MAIN */:
6893
+ case _StarknetChainId.SN_MAIN:
6815
6894
  return StarknetIdMulticallContract;
6816
- case "0x534e5f5345504f4c4941" /* SN_SEPOLIA */:
6895
+ case _StarknetChainId.SN_SEPOLIA:
6817
6896
  return StarknetIdMulticallContract;
6818
6897
  default:
6819
6898
  throw new Error("Starknet.id multicall contract is not yet deployed on this network");
@@ -6825,9 +6904,9 @@ var StarknetIdVerifierContract = {
6825
6904
  };
6826
6905
  function getStarknetIdVerifierContract(chainId) {
6827
6906
  switch (chainId) {
6828
- case "0x534e5f4d41494e" /* SN_MAIN */:
6907
+ case _StarknetChainId.SN_MAIN:
6829
6908
  return StarknetIdVerifierContract.MAINNET;
6830
- case "0x534e5f5345504f4c4941" /* SN_SEPOLIA */:
6909
+ case _StarknetChainId.SN_SEPOLIA:
6831
6910
  return StarknetIdVerifierContract.TESTNET_SEPOLIA;
6832
6911
  default:
6833
6912
  throw new Error("Starknet.id verifier contract is not yet deployed on this network");
@@ -6839,9 +6918,9 @@ var StarknetIdPfpContract = {
6839
6918
  };
6840
6919
  function getStarknetIdPfpContract(chainId) {
6841
6920
  switch (chainId) {
6842
- case "0x534e5f4d41494e" /* SN_MAIN */:
6921
+ case _StarknetChainId.SN_MAIN:
6843
6922
  return StarknetIdPfpContract.MAINNET;
6844
- case "0x534e5f5345504f4c4941" /* SN_SEPOLIA */:
6923
+ case _StarknetChainId.SN_SEPOLIA:
6845
6924
  return StarknetIdPfpContract.TESTNET_SEPOLIA;
6846
6925
  default:
6847
6926
  throw new Error(
@@ -6855,9 +6934,9 @@ var StarknetIdPopContract = {
6855
6934
  };
6856
6935
  function getStarknetIdPopContract(chainId) {
6857
6936
  switch (chainId) {
6858
- case "0x534e5f4d41494e" /* SN_MAIN */:
6937
+ case _StarknetChainId.SN_MAIN:
6859
6938
  return StarknetIdPopContract.MAINNET;
6860
- case "0x534e5f5345504f4c4941" /* SN_SEPOLIA */:
6939
+ case _StarknetChainId.SN_SEPOLIA:
6861
6940
  return StarknetIdPopContract.TESTNET_SEPOLIA;
6862
6941
  default:
6863
6942
  throw new Error(
@@ -7752,7 +7831,7 @@ var LedgerSigner221 = class extends LedgerSigner111 {
7752
7831
  const ledgerResponse = await this.signTxV1(det, transactions);
7753
7832
  assert(
7754
7833
  toBigInt(msgHash) === ledgerResponse.hash,
7755
- "The transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
7834
+ "The V1 transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
7756
7835
  );
7757
7836
  return ledgerResponse.signature;
7758
7837
  }
@@ -7767,108 +7846,452 @@ var LedgerSigner221 = class extends LedgerSigner111 {
7767
7846
  feeDataAvailabilityMode: intDAM(det.feeDataAvailabilityMode)
7768
7847
  });
7769
7848
  const ledgerResponse = await this.signTxV3(det, transactions);
7849
+ assert(
7850
+ toBigInt(msgHash) === ledgerResponse.hash,
7851
+ "The V3 transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
7852
+ );
7853
+ return ledgerResponse.signature;
7854
+ }
7855
+ throw Error("unsupported signTransaction version");
7856
+ }
7857
+ /**
7858
+ * Sign in a Ledger the deployment of a new account. The details are displayed on the Ledger screen.
7859
+ * @param {DeployAccountSignerDetails} details An object that includes all necessary data to calculate the Hash. It can be `V2DeployAccountSignerDetails` or `V3DeployAccountSignerDetails` types.
7860
+ * @returns {Signature} The deploy account signature.
7861
+ * @example
7862
+ * ```typescript
7863
+ * const result = myLedgerSigner.signDeployAccountTransaction(details);
7864
+ * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
7865
+ * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
7866
+ * // recovery: 0}
7867
+ * ```
7868
+ */
7869
+ async signDeployAccountTransaction(details) {
7870
+ const compiledConstructorCalldata = CallData.compile(details.constructorCalldata);
7871
+ let msgHash;
7872
+ if (Object.values(api_exports.ETransactionVersion2).includes(details.version)) {
7873
+ const det = details;
7874
+ msgHash = calculateDeployAccountTransactionHash3({
7875
+ ...det,
7876
+ salt: det.addressSalt,
7877
+ constructorCalldata: compiledConstructorCalldata,
7878
+ version: det.version
7879
+ });
7880
+ const ledgerResponse = await this.signDeployAccountV1(det);
7770
7881
  assert(
7771
7882
  toBigInt(msgHash) === ledgerResponse.hash,
7772
7883
  "The transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
7773
7884
  );
7774
7885
  return ledgerResponse.signature;
7775
7886
  }
7776
- throw Error("unsupported signTransaction version");
7887
+ if (Object.values(api_exports.ETransactionVersion3).includes(details.version)) {
7888
+ const det = details;
7889
+ msgHash = calculateDeployAccountTransactionHash3({
7890
+ ...det,
7891
+ salt: det.addressSalt,
7892
+ compiledConstructorCalldata,
7893
+ version: det.version,
7894
+ nonceDataAvailabilityMode: intDAM(det.nonceDataAvailabilityMode),
7895
+ feeDataAvailabilityMode: intDAM(det.feeDataAvailabilityMode)
7896
+ });
7897
+ const ledgerResponse = await this.signDeployAccountV3(det);
7898
+ assert(
7899
+ toBigInt(msgHash) === ledgerResponse.hash,
7900
+ "The transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
7901
+ );
7902
+ return ledgerResponse.signature;
7903
+ }
7904
+ throw Error("unsupported signDeployAccountTransaction version");
7905
+ }
7906
+ /**
7907
+ * Internal function to convert a bigNumberish to an Uint8array of 256 bits
7908
+ * @param {BigNumberish} input input value
7909
+ * @returns {Uint8Array} a Uint8Array containing 32 bytes.
7910
+ */
7911
+ convertBnToLedger(input) {
7912
+ return hexToBytes(addAddressPadding(toHex(input)));
7913
+ }
7914
+ /**
7915
+ * Internal function to decode the response of the Ledger signature
7916
+ * @param {Uint8Array} respSign the Buffer response of the Ledger
7917
+ * @returns { hash: bigint; signature: Signature } transaction hash & signature
7918
+ */
7919
+ decodeSignatureLedger(respSign) {
7920
+ const h = BigInt(addHexPrefix(buf2hex(respSign.subarray(0, 32))));
7921
+ const r = BigInt(addHexPrefix(buf2hex(respSign.subarray(33, 65))));
7922
+ const s = BigInt(addHexPrefix(buf2hex(respSign.subarray(65, 97))));
7923
+ const v = respSign[97];
7924
+ const sign0 = new starkCurve.Signature(r, s);
7925
+ const sign1 = sign0.addRecoveryBit(v);
7926
+ return { hash: h, signature: sign1 };
7927
+ }
7928
+ /** Internal function to convert a Call to an array of Uint8Array.
7929
+ * @param {Call} call A Call to convert.
7930
+ * @return {Uint8Array[]} Call encoded in an array of Uint8Array (each containing 7 u256).
7931
+ */
7932
+ encodeCall(call) {
7933
+ const toBuf = this.convertBnToLedger(call.contractAddress);
7934
+ const selectorBuf = hexToBytes(addAddressPadding(getSelector(call.entrypoint)));
7935
+ let calldataBuf = new Uint8Array([]);
7936
+ if (call.calldata) {
7937
+ const compiledCalldata = CallData.compile(call.calldata);
7938
+ calldataBuf = concatenateArrayBuffer(
7939
+ compiledCalldata.map((parameter) => {
7940
+ const a = this.convertBnToLedger(parameter);
7941
+ return a;
7942
+ })
7943
+ );
7944
+ }
7945
+ const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
7946
+ const calldatas = [];
7947
+ const chunkSize = 7 * 32;
7948
+ for (let i = 0; i < callBuf.length; i += chunkSize)
7949
+ calldatas.push(callBuf.subarray(i, i + chunkSize));
7950
+ return calldatas;
7951
+ }
7952
+ /**
7953
+ * Ask the Ledger Nano to display and sign a Starknet V1 transaction.
7954
+ * @param {V2InvocationsSignerDetails} txDetails All the details needed for a txV1.
7955
+ * @param {Call[]} calls array of Starknet invocations
7956
+ * @returns an object including the transaction Hash and the signature
7957
+ * @example
7958
+ * ```typescript
7959
+ * const calls: Call[] = [{contractAddress: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
7960
+ * entrypoint: "transfer",
7961
+ * calldata:["0x11f5fc2a92ac03434a7937fe982f5e5293b65ad438a989c5b78fb8f04a12016",
7962
+ * "0x9184e72a000", "0x0"]}];
7963
+ * const txDet: V2InvocationsSignerDetails = {
7964
+ * walletAddress: txDetails.accountAddress,
7965
+ * chainId: constants.StarknetChainId.SN_MAIN,
7966
+ * cairoVersion: "1", maxFee: txDetails.max_fee,
7967
+ * nonce: txDetails.nonce, version: "0x1"
7968
+ * };
7969
+ * const res = await myLedgerSigner.signTxV1(txDet, calls);
7970
+ * // res = {hash:
7971
+ * // signature:
7972
+ * // }
7973
+ * ```
7974
+ */
7975
+ async signTxV1(txDetails, calls) {
7976
+ await this._transporter.send(Number("0x5a"), 4, 0, 0, Buffer.from(this.pathBuffer));
7977
+ const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
7978
+ const maxFeeBuf = this.convertBnToLedger(txDetails.maxFee);
7979
+ const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
7980
+ const nonceBuf = this.convertBnToLedger(txDetails.nonce);
7981
+ const dataBuf = concatenateArrayBuffer([
7982
+ accountAddressBuf,
7983
+ maxFeeBuf,
7984
+ chainIdBuf,
7985
+ nonceBuf
7986
+ ]);
7987
+ await this._transporter.send(Number("0x5a"), 4, 1, 0, Buffer.from(dataBuf));
7988
+ const nbCallsBuf = this.convertBnToLedger(calls.length);
7989
+ await this._transporter.send(Number("0x5a"), 4, 2, 0, Buffer.from(nbCallsBuf));
7990
+ let respSign = new Uint8Array(0);
7991
+ for (const call of calls) {
7992
+ const calldatas = this.encodeCall(call);
7993
+ await this._transporter.send(Number("0x5a"), 4, 3, 0, Buffer.from(calldatas[0]));
7994
+ if (calldatas.length > 1) {
7995
+ calldatas.slice(1).forEach(async (part) => {
7996
+ await this._transporter.send(Number("0x5a"), 4, 3, 1, Buffer.from(part));
7997
+ });
7998
+ }
7999
+ respSign = await this._transporter.send(Number("0x5a"), 4, 3, 2);
8000
+ }
8001
+ return this.decodeSignatureLedger(respSign);
8002
+ }
8003
+ /**
8004
+ * Ask to the Ledger Nano to display and sign a Starknet V3 transaction.
8005
+ * @param {V3InvocationsSignerDetails} txDetails All the details needed for a txV3.
8006
+ * @param {Call[]} calls array of Starknet invocations
8007
+ * @returns an object including the transaction Hash and the signature
8008
+ * @example
8009
+ * ```typescript
8010
+ * const calls: Call[] = [{contractAddress: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
8011
+ * entrypoint: "transfer",
8012
+ * calldata:["0x11f5fc2a92ac03434a7937fe982f5e5293b65ad438a989c5b78fb8f04a12016",
8013
+ * "0x9184e72a000", "0x0"]}];
8014
+ * const txDetailsV3: V3InvocationsSignerDetails = {
8015
+ * chainId: constants.StarknetChainId.SN_MAIN,
8016
+ * nonce: "28", accountDeploymentData: [],
8017
+ * paymasterData: [], cairoVersion: "1",
8018
+ * feeDataAvailabilityMode: "L1", nonceDataAvailabilityMode: "L1",
8019
+ * resourceBounds: {
8020
+ * l1_gas: { max_amount: "0x2a00", max_price_per_unit: "0x5c00000"
8021
+ * },
8022
+ * l2_gas: { max_amount: "0x00", max_price_per_unit: "0x00"},
8023
+ * }, tip: 0, version: "0x3", walletAddress: account0.address
8024
+ * };
8025
+ * const res = await myLedgerSigner.signTxV3(txDetailsV3, calls);
8026
+ * // res = {hash:
8027
+ * // signature:
8028
+ * // }
8029
+ * ```
8030
+ */
8031
+ async signTxV3(txDetails, calls) {
8032
+ assert(txDetails.paymasterData.length <= 7, "Paymaster data includes more than 7 items.");
8033
+ assert(
8034
+ txDetails.accountDeploymentData.length <= 7,
8035
+ "accountDeploymentData includes more than 7 items"
8036
+ );
8037
+ await this._transporter.send(Number("0x5a"), 3, 0, 0, Buffer.from(this.pathBuffer));
8038
+ const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
8039
+ const tipBuf = this.convertBnToLedger(txDetails.tip);
8040
+ const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
8041
+ const nonceBuf = this.convertBnToLedger(txDetails.nonce);
8042
+ const dAModeHashBuf = this.convertBnToLedger(
8043
+ hashDAMode(
8044
+ txDetails.nonceDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2,
8045
+ txDetails.feeDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2
8046
+ )
8047
+ );
8048
+ const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
8049
+ const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
8050
+ const dataBuf = concatenateArrayBuffer([
8051
+ accountAddressBuf,
8052
+ tipBuf,
8053
+ l1_gasBuf,
8054
+ l2_gasBuf,
8055
+ chainIdBuf,
8056
+ nonceBuf,
8057
+ dAModeHashBuf
8058
+ ]);
8059
+ await this._transporter.send(Number("0x5a"), 3, 1, 0, Buffer.from(dataBuf));
8060
+ const paymasterBuf = concatenateArrayBuffer(
8061
+ txDetails.paymasterData.map((value) => {
8062
+ const a = this.convertBnToLedger(value);
8063
+ return a;
8064
+ })
8065
+ );
8066
+ await this._transporter.send(Number("0x5a"), 3, 2, 0, Buffer.from(paymasterBuf));
8067
+ const accountDeployDataBuf = concatenateArrayBuffer(
8068
+ txDetails.paymasterData.map((value) => {
8069
+ const a = this.convertBnToLedger(value);
8070
+ return a;
8071
+ })
8072
+ );
8073
+ await this._transporter.send(Number("0x5a"), 3, 3, 0, Buffer.from(accountDeployDataBuf));
8074
+ const nbCallsBuf = this.convertBnToLedger(calls.length);
8075
+ await this._transporter.send(Number("0x5a"), 3, 4, 0, Buffer.from(nbCallsBuf));
8076
+ let respSign = new Uint8Array(0);
8077
+ for (const call of calls) {
8078
+ const calldatas = this.encodeCall(call);
8079
+ await this._transporter.send(Number("0x5a"), 3, 5, 0, Buffer.from(calldatas[0]));
8080
+ if (calldatas.length > 1) {
8081
+ calldatas.slice(1).forEach(async (part) => {
8082
+ await this._transporter.send(Number("0x5a"), 3, 5, 1, Buffer.from(part));
8083
+ });
8084
+ }
8085
+ respSign = await this._transporter.send(Number("0x5a"), 3, 5, 2);
8086
+ }
8087
+ return this.decodeSignatureLedger(respSign);
8088
+ }
8089
+ /**
8090
+ * Ask the Ledger Nano to display and sign a Starknet V1 account deployment.
8091
+ * @param {V2DeployAccountSignerDetails} deployAccountDetail All the details needed for a V1 deploy account.
8092
+ * @returns an object including the transaction Hash and the signature
8093
+ * @example
8094
+ * ```typescript
8095
+ * const deployData: V2DeployAccountSignerDetails =
8096
+ * {
8097
+ * tip: 0, paymasterData: [], accountDeploymentData: [],
8098
+ * nonceDataAvailabilityMode: 'L1', feeDataAvailabilityMode: 'L1',
8099
+ * resourceBounds: {
8100
+ * l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' },
8101
+ * l1_gas: { max_amount: '0x0', max_price_per_unit: '0x0' }
8102
+ * },
8103
+ * classHash: '0x540d7f5ec7ecf317e68d48564934cb99259781b1ee3cedbbc37ec5337f8e688',
8104
+ * constructorCalldata: [
8105
+ * '89832696000889662999767022750851886674077821293893187900664573372145410755'
8106
+ * ],
8107
+ * contractAddress: '0x32c60fba64eb96831d064bbb2319375b7b7381543abe66da872e4344bcd72a0',
8108
+ * addressSalt: '0x0032d7efe2a9232f9b463e7206c68fdea4aeb13fec0cb308c6ba1d197d5922c3',
8109
+ * chainId: '0x534e5f5345504f4c4941', maxFee: 55050000000000n,
8110
+ * version: '0x1', nonce: 0n
8111
+ *}
8112
+ * const res = await myLedgerSigner.signDeployAccountV1(deployData);
8113
+ * // res = {hash:
8114
+ * // signature:
8115
+ * // }
8116
+ * ```
8117
+ */
8118
+ async signDeployAccountV1(deployAccountDetail) {
8119
+ await this._transporter.send(Number("0x5a"), 6, 0, 0, Buffer.from(this.pathBuffer));
8120
+ const accountAddressBuf = this.convertBnToLedger(
8121
+ deployAccountDetail.contractAddress
8122
+ );
8123
+ const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
8124
+ const saltBuf = this.convertBnToLedger(deployAccountDetail.addressSalt);
8125
+ const chainIdBuf = this.convertBnToLedger(deployAccountDetail.chainId);
8126
+ const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
8127
+ const dataBuf = concatenateArrayBuffer([
8128
+ accountAddressBuf,
8129
+ classHashBuf,
8130
+ saltBuf,
8131
+ chainIdBuf,
8132
+ nonceBuf
8133
+ ]);
8134
+ await this._transporter.send(Number("0x5a"), 6, 1, 0, Buffer.from(dataBuf));
8135
+ const maxFreeBuf = this.convertBnToLedger(deployAccountDetail.maxFee);
8136
+ await this._transporter.send(Number("0x5a"), 6, 2, 0, Buffer.from(maxFreeBuf));
8137
+ const compiledConstructor = CallData.compile(deployAccountDetail.constructorCalldata);
8138
+ const constructorLengthBuf = this.convertBnToLedger(compiledConstructor.length);
8139
+ await this._transporter.send(Number("0x5a"), 6, 3, 0, Buffer.from(constructorLengthBuf));
8140
+ const constructorBuf = concatenateArrayBuffer(
8141
+ compiledConstructor.map((parameter) => {
8142
+ const a = this.convertBnToLedger(parameter);
8143
+ return a;
8144
+ })
8145
+ );
8146
+ const constructorChunks = [];
8147
+ const chunkSize = 7 * 32;
8148
+ for (let i = 0; i < constructorBuf.length; i += chunkSize)
8149
+ constructorChunks.push(constructorBuf.subarray(i, i + chunkSize));
8150
+ let respSign = new Uint8Array(0);
8151
+ for (const chunk of constructorChunks) {
8152
+ respSign = await this._transporter.send(Number("0x5a"), 6, 4, 0, Buffer.from(chunk));
8153
+ }
8154
+ return this.decodeSignatureLedger(respSign);
8155
+ }
8156
+ /**
8157
+ *Ask the Ledger Nano to display and sign a Starknet V3 account deployment.
8158
+ * @param {V3DeployAccountSignerDetails} deployAccountDetail All the details needed for a V3 deploy account.
8159
+ * @returns an object including the transaction Hash and the signature
8160
+ * @example
8161
+ * ```typescript
8162
+ * const deployData: V3DeployAccountSignerDetails =
8163
+ * {
8164
+ * tip: 0, paymasterData: [], accountDeploymentData: [],
8165
+ * nonceDataAvailabilityMode: 'L1', feeDataAvailabilityMode: 'L1',
8166
+ * resourceBounds: {
8167
+ * l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' },
8168
+ * l1_gas: { max_amount: '0x226', max_price_per_unit: '0x22ecb25c00' }
8169
+ * },
8170
+ * classHash: '0x540d7f5ec7ecf317e68d48564934cb99259781b1ee3cedbbc37ec5337f8e688',
8171
+ * constructorCalldata: [
8172
+ * '3571125127744830445572285574469842579401255431821644822726857471463672199621'
8173
+ * ],
8174
+ * contractAddress: '0x4ca062add1cf12a107be1107af17981cf6e544a24d987693230ea481d3d5e34',
8175
+ * addressSalt: '0x07e52f68e3160e1ef698211cdf6d3792368fe347e7e2d4a8ace14d9b248f39c5',
8176
+ * chainId: '0x534e5f5345504f4c4941', maxFee: 0,
8177
+ * version: '0x3', nonce: 0n
8178
+ *}
8179
+ * const res = await myLedgerSigner.signDeployAccountV3(deployData);
8180
+ * // res = {hash:
8181
+ * // signature:
8182
+ * // }
8183
+ * ```
8184
+ */
8185
+ async signDeployAccountV3(deployAccountDetail) {
8186
+ await this._transporter.send(Number("0x5a"), 5, 0, 0, Buffer.from(this.pathBuffer));
8187
+ const accountAddressBuf = this.convertBnToLedger(
8188
+ deployAccountDetail.contractAddress
8189
+ );
8190
+ const chainIdBuf = this.convertBnToLedger(deployAccountDetail.chainId);
8191
+ const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
8192
+ const dAModeHashBuf = this.convertBnToLedger(
8193
+ hashDAMode(
8194
+ deployAccountDetail.nonceDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2,
8195
+ deployAccountDetail.feeDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2
8196
+ )
8197
+ );
8198
+ const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
8199
+ const saltBuf = this.convertBnToLedger(deployAccountDetail.addressSalt);
8200
+ const dataBuf = concatenateArrayBuffer([
8201
+ accountAddressBuf,
8202
+ chainIdBuf,
8203
+ nonceBuf,
8204
+ dAModeHashBuf,
8205
+ classHashBuf,
8206
+ saltBuf
8207
+ ]);
8208
+ await this._transporter.send(Number("0x5a"), 5, 1, 0, Buffer.from(dataBuf));
8209
+ const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
8210
+ const l1_gasBuf = this.convertBnToLedger(
8211
+ encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
8212
+ );
8213
+ const l2_gasBuf = this.convertBnToLedger(
8214
+ encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
8215
+ );
8216
+ const feeBuf = concatenateArrayBuffer([tipBuf, l1_gasBuf, l2_gasBuf]);
8217
+ await this._transporter.send(Number("0x5a"), 5, 2, 0, Buffer.from(feeBuf));
8218
+ const paymasterBuf = concatenateArrayBuffer(
8219
+ deployAccountDetail.paymasterData.map((value) => {
8220
+ const a = this.convertBnToLedger(value);
8221
+ return a;
8222
+ })
8223
+ );
8224
+ await this._transporter.send(Number("0x5a"), 5, 3, 0, Buffer.from(paymasterBuf));
8225
+ const compiledConstructor = CallData.compile(deployAccountDetail.constructorCalldata);
8226
+ const constructorLengthBuf = this.convertBnToLedger(compiledConstructor.length);
8227
+ await this._transporter.send(Number("0x5a"), 5, 4, 0, Buffer.from(constructorLengthBuf));
8228
+ const constructorBuf = concatenateArrayBuffer(
8229
+ compiledConstructor.map((parameter) => {
8230
+ const a = this.convertBnToLedger(parameter);
8231
+ return a;
8232
+ })
8233
+ );
8234
+ const constructorChunks = [];
8235
+ const chunkSize = 7 * 32;
8236
+ for (let i = 0; i < constructorBuf.length; i += chunkSize)
8237
+ constructorChunks.push(constructorBuf.subarray(i, i + chunkSize));
8238
+ let respSign = new Uint8Array(0);
8239
+ for (const chunk of constructorChunks) {
8240
+ respSign = await this._transporter.send(Number("0x5a"), 5, 5, 0, Buffer.from(chunk));
8241
+ }
8242
+ return this.decodeSignatureLedger(respSign);
7777
8243
  }
8244
+ };
8245
+ function getLedgerPathBuffer221(accountId, applicationName = "LedgerW") {
8246
+ const path0buff = new Uint8Array([HARDENING_BYTE, 0, 10, 85]);
8247
+ const path1buff = new Uint8Array([71 | HARDENING_BYTE, 65, 233, 201]);
8248
+ const path2Base = applicationName === "LedgerW" ? new Uint8Array([43, 206, 231, 219]) : stringToSha256ToArrayBuff4(applicationName);
8249
+ const path2buff = concatenateArrayBuffer([
8250
+ new Uint8Array([path2Base[0] | HARDENING_BYTE]),
8251
+ path2Base.subarray(1)
8252
+ ]);
8253
+ const path3buff = new Uint8Array([HARDENING_BYTE, 0, 0, 0]);
8254
+ const hex = toHex(BigInt(accountId) | HARDENING_4BYTES);
8255
+ const padded = addHexPrefix(removeHexPrefix(hex).padStart(8, "0"));
8256
+ const path4buff = hexToBytes(padded);
8257
+ const path5buff = new Uint8Array([0, 0, 0, 0]);
8258
+ const pathBuff = concatenateArrayBuffer([
8259
+ path0buff,
8260
+ path1buff,
8261
+ path2buff,
8262
+ path3buff,
8263
+ path4buff,
8264
+ path5buff
8265
+ ]);
8266
+ return pathBuff;
8267
+ }
8268
+
8269
+ // src/signer/ledgerSigner231.ts
8270
+ var LedgerSigner231 = class extends LedgerSigner221 {
7778
8271
  /**
7779
- * Sign in a Ledger the deployment of a new account. The details are displayed on the Ledger screen.
7780
- * @param {DeployAccountSignerDetails} details An object that includes all necessary data to calculate the Hash. It can be `V2DeployAccountSignerDetails` or `V3DeployAccountSignerDetails` types.
7781
- * @returns {Signature} The deploy account signature.
8272
+ * constructor of the LedgerSigner class.
8273
+ * @param {Transport} transport 5 transports are available to handle USB, bluetooth, Node, Web, Mobile.
8274
+ * See Guides for more details.
8275
+ * @param {number} accountID ID of Ledger Nano account (can handle 2**31 accounts).
8276
+ * @param {string} [eip2645application='LedgerW'] A wallet is defined by an ERC2645 derivation path (6 items).
8277
+ * One item is called `application` and can be customized.
8278
+ * Default value is `LedgerW`.
8279
+ * @param {LedgerPathCalculation} [pathFunction=getLedgerPathBuffer221]
8280
+ * defines the function that will calculate the path. By default `getLedgerPathBuffer221` is selected.
8281
+ *
8282
+ * If you are using APP v2.3.1 with an account created with the v1.1.1, you need to use :
8283
+ * ```typescript
8284
+ * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0, undefined, getLedgerPathBuffer111);
8285
+ * ```
7782
8286
  * @example
7783
8287
  * ```typescript
7784
- * const result = myLedgerSigner.signDeployAccountTransaction(details);
7785
- * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
7786
- * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
7787
- * // recovery: 0}
8288
+ * import TransportNodeHid from "@ledgerhq/hw-transport-node-hid";
8289
+ * const myNodeTransport = await TransportNodeHid.create();
8290
+ * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0);
7788
8291
  * ```
7789
8292
  */
7790
- async signDeployAccountTransaction(details) {
7791
- const compiledConstructorCalldata = CallData.compile(details.constructorCalldata);
7792
- let msgHash;
7793
- if (Object.values(api_exports.ETransactionVersion2).includes(details.version)) {
7794
- const det = details;
7795
- msgHash = calculateDeployAccountTransactionHash3({
7796
- ...det,
7797
- salt: det.addressSalt,
7798
- constructorCalldata: compiledConstructorCalldata,
7799
- version: det.version
7800
- });
7801
- const ledgerResponse = await this.signDeployAccountV1(det);
7802
- assert(
7803
- toBigInt(msgHash) === ledgerResponse.hash,
7804
- "The transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
7805
- );
7806
- return ledgerResponse.signature;
7807
- }
7808
- if (Object.values(api_exports.ETransactionVersion3).includes(details.version)) {
7809
- const det = details;
7810
- msgHash = calculateDeployAccountTransactionHash3({
7811
- ...det,
7812
- salt: det.addressSalt,
7813
- compiledConstructorCalldata,
7814
- version: det.version,
7815
- nonceDataAvailabilityMode: intDAM(det.nonceDataAvailabilityMode),
7816
- feeDataAvailabilityMode: intDAM(det.feeDataAvailabilityMode)
7817
- });
7818
- const ledgerResponse = await this.signDeployAccountV3(det);
7819
- assert(
7820
- toBigInt(msgHash) === ledgerResponse.hash,
7821
- "The transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
7822
- );
7823
- return ledgerResponse.signature;
7824
- }
7825
- throw Error("unsupported signDeployAccountTransaction version");
7826
- }
7827
- /**
7828
- * Internal function to convert a bigNumberish to an Uint8array of 256 bits
7829
- * @param {BigNumberish} input input value
7830
- * @returns {Uint8Array} a Uint8Array containing 32 bytes.
7831
- */
7832
- convertBnToLedger(input) {
7833
- return hexToBytes(addAddressPadding(toHex(input)));
7834
- }
7835
- /**
7836
- * Internal function to decode the response of the Ledger signature
7837
- * @param {Uint8Array} respSign the Buffer response of the Ledger
7838
- * @returns { hash: bigint; signature: Signature } transaction hash & signature
7839
- */
7840
- decodeSignatureLedger(respSign) {
7841
- const h = BigInt(addHexPrefix(buf2hex(respSign.subarray(0, 32))));
7842
- const r = BigInt(addHexPrefix(buf2hex(respSign.subarray(33, 65))));
7843
- const s = BigInt(addHexPrefix(buf2hex(respSign.subarray(65, 97))));
7844
- const v = respSign[97];
7845
- const sign0 = new starkCurve.Signature(r, s);
7846
- const sign1 = sign0.addRecoveryBit(v);
7847
- return { hash: h, signature: sign1 };
7848
- }
7849
- /** Internal function to convert a Call to an array of Uint8Array.
7850
- * @param {Call} call A Call to convert.
7851
- * @return {Uint8Array[]} Call encoded in an array of Uint8Array (each containing 7 u256).
7852
- */
7853
- encodeCall(call) {
7854
- const toBuf = this.convertBnToLedger(call.contractAddress);
7855
- const selectorBuf = hexToBytes(addAddressPadding(getSelector(call.entrypoint)));
7856
- let calldataBuf = new Uint8Array([]);
7857
- if (call.calldata) {
7858
- const compiledCalldata = CallData.compile(call.calldata);
7859
- calldataBuf = concatenateArrayBuffer(
7860
- compiledCalldata.map((parameter) => {
7861
- const a = this.convertBnToLedger(parameter);
7862
- return a;
7863
- })
7864
- );
7865
- }
7866
- const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
7867
- const calldatas = [];
7868
- const chunkSize = 7 * 32;
7869
- for (let i = 0; i < callBuf.length; i += chunkSize)
7870
- calldatas.push(callBuf.subarray(i, i + chunkSize));
7871
- return calldatas;
8293
+ constructor(transport, accountID, eip2645application = "LedgerW", pathFunction = getLedgerPathBuffer221) {
8294
+ super(transport, accountID, eip2645application, pathFunction);
7872
8295
  }
7873
8296
  /**
7874
8297
  * Ask the Ledger Nano to display and sign a Starknet V1 transaction.
@@ -7911,18 +8334,17 @@ var LedgerSigner221 = class extends LedgerSigner111 {
7911
8334
  let respSign = new Uint8Array(0);
7912
8335
  for (const call of calls) {
7913
8336
  const calldatas = this.encodeCall(call);
7914
- await this._transporter.send(Number("0x5a"), 4, 3, 0, Buffer.from(calldatas[0]));
8337
+ respSign = await this._transporter.send(Number("0x5a"), 4, 3, 0, Buffer.from(calldatas[0]));
7915
8338
  if (calldatas.length > 1) {
7916
8339
  calldatas.slice(1).forEach(async (part) => {
7917
- await this._transporter.send(Number("0x5a"), 4, 3, 1, Buffer.from(part));
8340
+ respSign = await this._transporter.send(Number("0x5a"), 4, 3, 1, Buffer.from(part));
7918
8341
  });
7919
8342
  }
7920
- respSign = await this._transporter.send(Number("0x5a"), 4, 3, 2);
7921
8343
  }
7922
8344
  return this.decodeSignatureLedger(respSign);
7923
8345
  }
7924
8346
  /**
7925
- * Ask to the Ledger Nano to display and sign a Starknet V3 transaction.
8347
+ * Ask to the Ledger Nano to display and sign a Starknet V3 transaction (Rpc 0.7 & Rpc 0.8).
7926
8348
  * @param {V3InvocationsSignerDetails} txDetails All the details needed for a txV3.
7927
8349
  * @param {Call[]} calls array of Starknet invocations
7928
8350
  * @returns an object including the transaction Hash and the signature
@@ -7942,7 +8364,7 @@ var LedgerSigner221 = class extends LedgerSigner111 {
7942
8364
  * },
7943
8365
  * l2_gas: { max_amount: "0x00", max_price_per_unit: "0x00"},
7944
8366
  * }, tip: 0, version: "0x3", walletAddress: account0.address
7945
- * };
8367
+ * }; // Rpc 0.7 transaction.
7946
8368
  * const res = await myLedgerSigner.signTxV3(txDetailsV3, calls);
7947
8369
  * // res = {hash:
7948
8370
  * // signature:
@@ -7957,53 +8379,67 @@ var LedgerSigner221 = class extends LedgerSigner111 {
7957
8379
  );
7958
8380
  await this._transporter.send(Number("0x5a"), 3, 0, 0, Buffer.from(this.pathBuffer));
7959
8381
  const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
7960
- const tipBuf = this.convertBnToLedger(txDetails.tip);
7961
8382
  const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
7962
8383
  const nonceBuf = this.convertBnToLedger(txDetails.nonce);
7963
8384
  const dAModeHashBuf = this.convertBnToLedger(
7964
8385
  hashDAMode(
7965
- txDetails.nonceDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2,
7966
- txDetails.feeDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2
8386
+ intDAM(txDetails.nonceDataAvailabilityMode),
8387
+ intDAM(txDetails.feeDataAvailabilityMode)
7967
8388
  )
7968
8389
  );
7969
- const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
7970
- const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
7971
8390
  const dataBuf = concatenateArrayBuffer([
7972
8391
  accountAddressBuf,
7973
- tipBuf,
7974
- l1_gasBuf,
7975
- l2_gasBuf,
7976
8392
  chainIdBuf,
7977
8393
  nonceBuf,
7978
8394
  dAModeHashBuf
7979
8395
  ]);
7980
8396
  await this._transporter.send(Number("0x5a"), 3, 1, 0, Buffer.from(dataBuf));
8397
+ if (isRPC08_ResourceBounds(txDetails.resourceBounds)) {
8398
+ const tipBuf = this.convertBnToLedger(txDetails.tip);
8399
+ const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
8400
+ const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
8401
+ const l1_data_gasBuf = this.convertBnToLedger(
8402
+ encodeDataResourceBoundsL1(txDetails.resourceBounds)
8403
+ );
8404
+ const feeBuf = concatenateArrayBuffer([
8405
+ tipBuf,
8406
+ l1_gasBuf,
8407
+ l2_gasBuf,
8408
+ l1_data_gasBuf
8409
+ ]);
8410
+ await this._transporter.send(Number("0x5a"), 3, 2, 0, Buffer.from(feeBuf));
8411
+ } else {
8412
+ const tipBuf = this.convertBnToLedger(txDetails.tip);
8413
+ const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
8414
+ const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
8415
+ const feeBuf = concatenateArrayBuffer([tipBuf, l1_gasBuf, l2_gasBuf]);
8416
+ await this._transporter.send(Number("0x5a"), 3, 2, 0, Buffer.from(feeBuf));
8417
+ }
7981
8418
  const paymasterBuf = concatenateArrayBuffer(
7982
8419
  txDetails.paymasterData.map((value) => {
7983
8420
  const a = this.convertBnToLedger(value);
7984
8421
  return a;
7985
8422
  })
7986
8423
  );
7987
- await this._transporter.send(Number("0x5a"), 3, 2, 0, Buffer.from(paymasterBuf));
8424
+ await this._transporter.send(Number("0x5a"), 3, 3, 0, Buffer.from(paymasterBuf));
7988
8425
  const accountDeployDataBuf = concatenateArrayBuffer(
7989
8426
  txDetails.paymasterData.map((value) => {
7990
8427
  const a = this.convertBnToLedger(value);
7991
8428
  return a;
7992
8429
  })
7993
8430
  );
7994
- await this._transporter.send(Number("0x5a"), 3, 3, 0, Buffer.from(accountDeployDataBuf));
8431
+ await this._transporter.send(Number("0x5a"), 3, 4, 0, Buffer.from(accountDeployDataBuf));
7995
8432
  const nbCallsBuf = this.convertBnToLedger(calls.length);
7996
- await this._transporter.send(Number("0x5a"), 3, 4, 0, Buffer.from(nbCallsBuf));
8433
+ await this._transporter.send(Number("0x5a"), 3, 5, 0, Buffer.from(nbCallsBuf));
7997
8434
  let respSign = new Uint8Array(0);
7998
8435
  for (const call of calls) {
7999
8436
  const calldatas = this.encodeCall(call);
8000
- await this._transporter.send(Number("0x5a"), 3, 5, 0, Buffer.from(calldatas[0]));
8437
+ respSign = await this._transporter.send(Number("0x5a"), 3, 6, 0, Buffer.from(calldatas[0]));
8001
8438
  if (calldatas.length > 1) {
8002
8439
  calldatas.slice(1).forEach(async (part) => {
8003
- await this._transporter.send(Number("0x5a"), 3, 5, 1, Buffer.from(part));
8440
+ respSign = await this._transporter.send(Number("0x5a"), 3, 6, 1, Buffer.from(part));
8004
8441
  });
8005
8442
  }
8006
- respSign = await this._transporter.send(Number("0x5a"), 3, 5, 2);
8007
8443
  }
8008
8444
  return this.decodeSignatureLedger(respSign);
8009
8445
  }
@@ -8043,21 +8479,21 @@ var LedgerSigner221 = class extends LedgerSigner111 {
8043
8479
  );
8044
8480
  const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
8045
8481
  const saltBuf = this.convertBnToLedger(deployAccountDetail.addressSalt);
8482
+ const maxFeeBuf = this.convertBnToLedger(deployAccountDetail.maxFee);
8046
8483
  const chainIdBuf = this.convertBnToLedger(deployAccountDetail.chainId);
8047
8484
  const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
8048
8485
  const dataBuf = concatenateArrayBuffer([
8049
8486
  accountAddressBuf,
8050
8487
  classHashBuf,
8051
8488
  saltBuf,
8489
+ maxFeeBuf,
8052
8490
  chainIdBuf,
8053
8491
  nonceBuf
8054
8492
  ]);
8055
8493
  await this._transporter.send(Number("0x5a"), 6, 1, 0, Buffer.from(dataBuf));
8056
- const maxFreeBuf = this.convertBnToLedger(deployAccountDetail.maxFee);
8057
- await this._transporter.send(Number("0x5a"), 6, 2, 0, Buffer.from(maxFreeBuf));
8058
8494
  const compiledConstructor = CallData.compile(deployAccountDetail.constructorCalldata);
8059
8495
  const constructorLengthBuf = this.convertBnToLedger(compiledConstructor.length);
8060
- await this._transporter.send(Number("0x5a"), 6, 3, 0, Buffer.from(constructorLengthBuf));
8496
+ await this._transporter.send(Number("0x5a"), 6, 2, 0, Buffer.from(constructorLengthBuf));
8061
8497
  const constructorBuf = concatenateArrayBuffer(
8062
8498
  compiledConstructor.map((parameter) => {
8063
8499
  const a = this.convertBnToLedger(parameter);
@@ -8070,12 +8506,12 @@ var LedgerSigner221 = class extends LedgerSigner111 {
8070
8506
  constructorChunks.push(constructorBuf.subarray(i, i + chunkSize));
8071
8507
  let respSign = new Uint8Array(0);
8072
8508
  for (const chunk of constructorChunks) {
8073
- respSign = await this._transporter.send(Number("0x5a"), 6, 4, 0, Buffer.from(chunk));
8509
+ respSign = await this._transporter.send(Number("0x5a"), 6, 3, 0, Buffer.from(chunk));
8074
8510
  }
8075
8511
  return this.decodeSignatureLedger(respSign);
8076
8512
  }
8077
8513
  /**
8078
- *Ask the Ledger Nano to display and sign a Starknet V3 account deployment.
8514
+ *Ask the Ledger Nano to display and sign a Starknet V3 account deployment (Rpc 0.7 & Rpc 0.8).
8079
8515
  * @param {V3DeployAccountSignerDetails} deployAccountDetail All the details needed for a V3 deploy account.
8080
8516
  * @returns an object including the transaction Hash and the signature
8081
8517
  * @example
@@ -8096,7 +8532,7 @@ var LedgerSigner221 = class extends LedgerSigner111 {
8096
8532
  * addressSalt: '0x07e52f68e3160e1ef698211cdf6d3792368fe347e7e2d4a8ace14d9b248f39c5',
8097
8533
  * chainId: '0x534e5f5345504f4c4941', maxFee: 0,
8098
8534
  * version: '0x3', nonce: 0n
8099
- *}
8535
+ *} // Rpc 0.7 transaction.
8100
8536
  * const res = await myLedgerSigner.signDeployAccountV3(deployData);
8101
8537
  * // res = {hash:
8102
8538
  * // signature:
@@ -8112,8 +8548,8 @@ var LedgerSigner221 = class extends LedgerSigner111 {
8112
8548
  const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
8113
8549
  const dAModeHashBuf = this.convertBnToLedger(
8114
8550
  hashDAMode(
8115
- deployAccountDetail.nonceDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2,
8116
- deployAccountDetail.feeDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2
8551
+ intDAM(deployAccountDetail.nonceDataAvailabilityMode),
8552
+ intDAM(deployAccountDetail.feeDataAvailabilityMode)
8117
8553
  )
8118
8554
  );
8119
8555
  const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
@@ -8127,15 +8563,35 @@ var LedgerSigner221 = class extends LedgerSigner111 {
8127
8563
  saltBuf
8128
8564
  ]);
8129
8565
  await this._transporter.send(Number("0x5a"), 5, 1, 0, Buffer.from(dataBuf));
8130
- const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
8131
- const l1_gasBuf = this.convertBnToLedger(
8132
- encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
8133
- );
8134
- const l2_gasBuf = this.convertBnToLedger(
8135
- encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
8136
- );
8137
- const feeBuf = concatenateArrayBuffer([tipBuf, l1_gasBuf, l2_gasBuf]);
8138
- await this._transporter.send(Number("0x5a"), 5, 2, 0, Buffer.from(feeBuf));
8566
+ if (isRPC08_ResourceBounds(deployAccountDetail.resourceBounds)) {
8567
+ const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
8568
+ const l1_gasBuf = this.convertBnToLedger(
8569
+ encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
8570
+ );
8571
+ const l2_gasBuf = this.convertBnToLedger(
8572
+ encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
8573
+ );
8574
+ const l1_data_gasBuf = this.convertBnToLedger(
8575
+ encodeDataResourceBoundsL1(deployAccountDetail.resourceBounds)
8576
+ );
8577
+ const feeBuf = concatenateArrayBuffer([
8578
+ tipBuf,
8579
+ l1_gasBuf,
8580
+ l2_gasBuf,
8581
+ l1_data_gasBuf
8582
+ ]);
8583
+ await this._transporter.send(Number("0x5a"), 5, 2, 0, Buffer.from(feeBuf));
8584
+ } else {
8585
+ const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
8586
+ const l1_gasBuf = this.convertBnToLedger(
8587
+ encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
8588
+ );
8589
+ const l2_gasBuf = this.convertBnToLedger(
8590
+ encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
8591
+ );
8592
+ const feeBuf = concatenateArrayBuffer([tipBuf, l1_gasBuf, l2_gasBuf]);
8593
+ await this._transporter.send(Number("0x5a"), 5, 2, 0, Buffer.from(feeBuf));
8594
+ }
8139
8595
  const paymasterBuf = concatenateArrayBuffer(
8140
8596
  deployAccountDetail.paymasterData.map((value) => {
8141
8597
  const a = this.convertBnToLedger(value);
@@ -8162,30 +8618,35 @@ var LedgerSigner221 = class extends LedgerSigner111 {
8162
8618
  }
8163
8619
  return this.decodeSignatureLedger(respSign);
8164
8620
  }
8621
+ /** Internal function to convert a Call to an array of Uint8Array.
8622
+ * @param {Call} call A Call to convert.
8623
+ * @return {Uint8Array[]} Call encoded in an array of Uint8Array (each containing 7 u256).
8624
+ */
8625
+ encodeCall(call) {
8626
+ const toBuf = this.convertBnToLedger(call.contractAddress);
8627
+ const selectorBuf = hexToBytes(addAddressPadding(getSelector(call.entrypoint)));
8628
+ let calldataBuf = new Uint8Array([]);
8629
+ if (call.calldata) {
8630
+ const compiledCalldata = CallData.compile(call.calldata);
8631
+ const calldataSizeBuf = this.convertBnToLedger(compiledCalldata.length);
8632
+ calldataBuf = concatenateArrayBuffer([
8633
+ calldataSizeBuf,
8634
+ ...compiledCalldata.map((parameter) => {
8635
+ const a = this.convertBnToLedger(parameter);
8636
+ return a;
8637
+ })
8638
+ ]);
8639
+ } else {
8640
+ calldataBuf = this.convertBnToLedger("0x00");
8641
+ }
8642
+ const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
8643
+ const calldatas = [];
8644
+ const chunkSize = 7 * 32;
8645
+ for (let i = 0; i < callBuf.length; i += chunkSize)
8646
+ calldatas.push(callBuf.subarray(i, i + chunkSize));
8647
+ return calldatas;
8648
+ }
8165
8649
  };
8166
- function getLedgerPathBuffer221(accountId, applicationName = "LedgerW") {
8167
- const path0buff = new Uint8Array([HARDENING_BYTE, 0, 10, 85]);
8168
- const path1buff = new Uint8Array([71 | HARDENING_BYTE, 65, 233, 201]);
8169
- const path2Base = applicationName === "LedgerW" ? new Uint8Array([43, 206, 231, 219]) : stringToSha256ToArrayBuff4(applicationName);
8170
- const path2buff = concatenateArrayBuffer([
8171
- new Uint8Array([path2Base[0] | HARDENING_BYTE]),
8172
- path2Base.subarray(1)
8173
- ]);
8174
- const path3buff = new Uint8Array([HARDENING_BYTE, 0, 0, 0]);
8175
- const hex = toHex(BigInt(accountId) | HARDENING_4BYTES);
8176
- const padded = addHexPrefix(removeHexPrefix(hex).padStart(8, "0"));
8177
- const path4buff = hexToBytes(padded);
8178
- const path5buff = new Uint8Array([0, 0, 0, 0]);
8179
- const pathBuff = concatenateArrayBuffer([
8180
- path0buff,
8181
- path1buff,
8182
- path2buff,
8183
- path3buff,
8184
- path4buff,
8185
- path5buff
8186
- ]);
8187
- return pathBuff;
8188
- }
8189
8650
 
8190
8651
  // src/utils/events/index.ts
8191
8652
  var events_exports = {};
@@ -8404,9 +8865,9 @@ function buildExecuteFromOutsideCall(outsideTransaction) {
8404
8865
  const myOutsideTransactions = Array.isArray(outsideTransaction) ? outsideTransaction : [outsideTransaction];
8405
8866
  const multiCall = myOutsideTransactions.map((outsideTx) => {
8406
8867
  let entrypoint;
8407
- if (outsideTx.version === "1" /* V1 */) {
8868
+ if (outsideTx.version === OutsideExecutionVersion.V1) {
8408
8869
  entrypoint = "execute_from_outside";
8409
- } else if (outsideTx.version === "2" /* V2 */) {
8870
+ } else if (outsideTx.version === OutsideExecutionVersion.V2) {
8410
8871
  entrypoint = "execute_from_outside_v2";
8411
8872
  } else {
8412
8873
  throw new Error("Unsupported OutsideExecution version");
@@ -8459,6 +8920,12 @@ var Account = class extends RpcProvider2 {
8459
8920
  channel: this.channel.id
8460
8921
  });
8461
8922
  }
8923
+ /** @deprecated @hidden */
8924
+ // The deprecation tag is meant to discourage use, not to signal future removal
8925
+ // it should only be removed if the relationship with the corresponding Provider.create(...) method changes
8926
+ static async create() {
8927
+ throw new LibraryError("Not supported");
8928
+ }
8462
8929
  // provided version or contract based preferred transactionVersion
8463
8930
  getPreferredVersion(type12, type3) {
8464
8931
  if (this.transactionVersion === ETransactionVersion2.V3) return type3;
@@ -8504,7 +8971,7 @@ var Account = class extends RpcProvider2 {
8504
8971
  );
8505
8972
  const chainId = await this.getChainId();
8506
8973
  const signerDetails = {
8507
- ...v3Details(details, await this.channel.getSpecVersion()),
8974
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8508
8975
  walletAddress: this.address,
8509
8976
  nonce,
8510
8977
  maxFee: ZERO,
@@ -8516,7 +8983,7 @@ var Account = class extends RpcProvider2 {
8516
8983
  const invocation = await this.buildInvocation(transactions, signerDetails);
8517
8984
  return super.getInvokeEstimateFee(
8518
8985
  { ...invocation },
8519
- { ...v3Details(details, await this.channel.getSpecVersion()), version, nonce },
8986
+ { ...v3Details(details, await this.channel.setUpSpecVersion()), version, nonce },
8520
8987
  blockIdentifier,
8521
8988
  details.skipValidate
8522
8989
  );
@@ -8535,7 +9002,7 @@ var Account = class extends RpcProvider2 {
8535
9002
  );
8536
9003
  const chainId = await this.getChainId();
8537
9004
  const declareContractTransaction = await this.buildDeclarePayload(payload, {
8538
- ...v3Details(details, await this.channel.getSpecVersion()),
9005
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8539
9006
  nonce,
8540
9007
  chainId,
8541
9008
  version,
@@ -8547,7 +9014,7 @@ var Account = class extends RpcProvider2 {
8547
9014
  });
8548
9015
  return super.getDeclareEstimateFee(
8549
9016
  declareContractTransaction,
8550
- { ...v3Details(details, await this.channel.getSpecVersion()), version, nonce },
9017
+ { ...v3Details(details, await this.channel.setUpSpecVersion()), version, nonce },
8551
9018
  blockIdentifier,
8552
9019
  details.skipValidate
8553
9020
  );
@@ -8568,7 +9035,7 @@ var Account = class extends RpcProvider2 {
8568
9035
  const payload = await this.buildAccountDeployPayload(
8569
9036
  { classHash, addressSalt, constructorCalldata, contractAddress },
8570
9037
  {
8571
- ...v3Details(details, await this.channel.getSpecVersion()),
9038
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8572
9039
  nonce,
8573
9040
  chainId,
8574
9041
  version,
@@ -8582,7 +9049,7 @@ var Account = class extends RpcProvider2 {
8582
9049
  );
8583
9050
  return super.getDeployAccountEstimateFee(
8584
9051
  { ...payload },
8585
- { ...v3Details(details, await this.channel.getSpecVersion()), version, nonce },
9052
+ { ...v3Details(details, await this.channel.setUpSpecVersion()), version, nonce },
8586
9053
  blockIdentifier,
8587
9054
  details.skipValidate
8588
9055
  );
@@ -8595,7 +9062,7 @@ var Account = class extends RpcProvider2 {
8595
9062
  if (!invocations.length) throw TypeError("Invocations should be non-empty array");
8596
9063
  const { nonce, blockIdentifier, version, skipValidate } = details;
8597
9064
  const accountInvocations = await this.accountInvocationsFactory(invocations, {
8598
- ...v3Details(details, await this.channel.getSpecVersion()),
9065
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8599
9066
  versions: [
8600
9067
  ETransactionVersion2.F1,
8601
9068
  // non-sierra
@@ -8618,7 +9085,7 @@ var Account = class extends RpcProvider2 {
8618
9085
  if (!invocations.length) throw TypeError("Invocations should be non-empty array");
8619
9086
  const { nonce, blockIdentifier, skipValidate = true, skipExecute, version } = details;
8620
9087
  const accountInvocations = await this.accountInvocationsFactory(invocations, {
8621
- ...v3Details(details, await this.channel.getSpecVersion()),
9088
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8622
9089
  versions: [
8623
9090
  ETransactionVersion2.V1,
8624
9091
  // non-sierra
@@ -8655,7 +9122,7 @@ var Account = class extends RpcProvider2 {
8655
9122
  );
8656
9123
  const chainId = await this.getChainId();
8657
9124
  const signerDetails = {
8658
- ...v3Details(transactionsDetail, await this.channel.getSpecVersion()),
9125
+ ...v3Details(transactionsDetail, await this.channel.setUpSpecVersion()),
8659
9126
  resourceBounds: estimate.resourceBounds,
8660
9127
  walletAddress: this.address,
8661
9128
  nonce,
@@ -8669,7 +9136,7 @@ var Account = class extends RpcProvider2 {
8669
9136
  return this.invokeFunction(
8670
9137
  { contractAddress: this.address, calldata, signature },
8671
9138
  {
8672
- ...v3Details(transactionsDetail, await this.channel.getSpecVersion()),
9139
+ ...v3Details(transactionsDetail, await this.channel.setUpSpecVersion()),
8673
9140
  resourceBounds: estimate.resourceBounds,
8674
9141
  nonce,
8675
9142
  maxFee: estimate.maxFee,
@@ -8714,7 +9181,7 @@ var Account = class extends RpcProvider2 {
8714
9181
  }
8715
9182
  );
8716
9183
  const declareDetails = {
8717
- ...v3Details(details, await this.channel.getSpecVersion()),
9184
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8718
9185
  resourceBounds: estimate.resourceBounds,
8719
9186
  maxFee: estimate.maxFee,
8720
9187
  nonce: toBigInt(nonce ?? await this.getNonce()),
@@ -8784,7 +9251,7 @@ var Account = class extends RpcProvider2 {
8784
9251
  details
8785
9252
  );
8786
9253
  const signature = await this.signer.signDeployAccountTransaction({
8787
- ...v3Details(details, await this.channel.getSpecVersion()),
9254
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8788
9255
  classHash,
8789
9256
  constructorCalldata: compiledCalldata,
8790
9257
  contractAddress,
@@ -8798,7 +9265,7 @@ var Account = class extends RpcProvider2 {
8798
9265
  return this.deployAccountContract(
8799
9266
  { classHash, addressSalt, constructorCalldata, signature },
8800
9267
  {
8801
- ...v3Details(details, await this.channel.getSpecVersion()),
9268
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8802
9269
  nonce,
8803
9270
  resourceBounds: estimate.resourceBounds,
8804
9271
  maxFee: estimate.maxFee,
@@ -8823,12 +9290,12 @@ var Account = class extends RpcProvider2 {
8823
9290
  */
8824
9291
  async getSnip9Version() {
8825
9292
  if (await supportsInterface(this, this.address, SNIP9_V2_INTERFACE_ID)) {
8826
- return "2" /* V2 */;
9293
+ return OutsideExecutionVersion.V2;
8827
9294
  }
8828
9295
  if (await supportsInterface(this, this.address, SNIP9_V1_INTERFACE_ID)) {
8829
- return "1" /* V1 */;
9296
+ return OutsideExecutionVersion.V1;
8830
9297
  }
8831
- return "0" /* UNSUPPORTED */;
9298
+ return OutsideExecutionVersion.UNSUPPORTED;
8832
9299
  }
8833
9300
  /**
8834
9301
  * Verify if a SNIP-9 nonce has not yet been used by the account.
@@ -8965,7 +9432,7 @@ var Account = class extends RpcProvider2 {
8965
9432
  let resourceBounds = estimateFeeToBounds3(
8966
9433
  ZERO,
8967
9434
  void 0,
8968
- await this.channel.getSpecVersion()
9435
+ await this.channel.setUpSpecVersion()
8969
9436
  );
8970
9437
  if (version === ETransactionVersion2.V3) {
8971
9438
  resourceBounds = details.resourceBounds ?? (await this.getSuggestedFee({ type, payload }, details)).resourceBounds;
@@ -8988,14 +9455,14 @@ var Account = class extends RpcProvider2 {
8988
9455
  case TransactionType.DEPLOY:
8989
9456
  return this.estimateDeployFee(payload, details);
8990
9457
  default:
8991
- return ZEROFee(await this.channel.getSpecVersion());
9458
+ return ZEROFee(await this.channel.setUpSpecVersion());
8992
9459
  }
8993
9460
  }
8994
9461
  async buildInvocation(call, details) {
8995
9462
  const calldata = getExecuteCalldata(call, await this.getCairoVersion());
8996
9463
  const signature = !details.skipValidate ? await this.signer.signTransaction(call, details) : [];
8997
9464
  return {
8998
- ...v3Details(details, await this.channel.getSpecVersion()),
9465
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
8999
9466
  contractAddress: this.address,
9000
9467
  calldata,
9001
9468
  signature
@@ -9009,7 +9476,7 @@ var Account = class extends RpcProvider2 {
9009
9476
  }
9010
9477
  const signature = !details.skipValidate ? await this.signer.signDeclareTransaction({
9011
9478
  ...details,
9012
- ...v3Details(details, await this.channel.getSpecVersion()),
9479
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
9013
9480
  classHash,
9014
9481
  compiledClassHash,
9015
9482
  // TODO: TS, cast because optional for v2 and required for v3, thrown if not present
@@ -9032,14 +9499,14 @@ var Account = class extends RpcProvider2 {
9032
9499
  const contractAddress = providedContractAddress ?? calculateContractAddressFromHash(addressSalt, classHash, compiledCalldata, 0);
9033
9500
  const signature = !details.skipValidate ? await this.signer.signDeployAccountTransaction({
9034
9501
  ...details,
9035
- ...v3Details(details, await this.channel.getSpecVersion()),
9502
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
9036
9503
  classHash,
9037
9504
  contractAddress,
9038
9505
  addressSalt,
9039
9506
  constructorCalldata: compiledCalldata
9040
9507
  }) : [];
9041
9508
  return {
9042
- ...v3Details(details, await this.channel.getSpecVersion()),
9509
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
9043
9510
  classHash,
9044
9511
  addressSalt,
9045
9512
  constructorCalldata: compiledCalldata,
@@ -9080,7 +9547,7 @@ var Account = class extends RpcProvider2 {
9080
9547
  [].concat(invocations).map(async (transaction, index) => {
9081
9548
  const txPayload = "payload" in transaction ? transaction.payload : transaction;
9082
9549
  const signerDetails = {
9083
- ...v3Details(details, await this.channel.getSpecVersion()),
9550
+ ...v3Details(details, await this.channel.setUpSpecVersion()),
9084
9551
  walletAddress: this.address,
9085
9552
  nonce: toBigInt(Number(safeNonce) + index),
9086
9553
  maxFee: ZERO,
@@ -9721,6 +10188,7 @@ export {
9721
10188
  LedgerSigner111 as LedgerSigner,
9722
10189
  LedgerSigner111,
9723
10190
  LedgerSigner221,
10191
+ LedgerSigner231,
9724
10192
  LibraryError,
9725
10193
  Literal,
9726
10194
  LogLevelIndex,
@@ -9731,8 +10199,8 @@ export {
9731
10199
  RpcProvider2 as Provider,
9732
10200
  ProviderInterface,
9733
10201
  api_exports as RPC,
9734
- rpc_0_7_exports as RPC07,
9735
- rpc_0_8_exports as RPC08,
10202
+ rpc_0_7_1_exports as RPC07,
10203
+ rpc_0_8_1_exports as RPC08,
9736
10204
  RPCResponseParser,
9737
10205
  ReceiptTx,
9738
10206
  ResponseParser,
@@ -9780,9 +10248,15 @@ export {
9780
10248
  getLedgerPathBuffer111,
9781
10249
  getLedgerPathBuffer221,
9782
10250
  hash_exports as hash,
10251
+ isPendingBlock,
10252
+ isPendingStateUpdate,
10253
+ isPendingTransaction,
9783
10254
  isRPC08_FeeEstimate,
9784
10255
  isRPC08_ResourceBounds,
9785
10256
  isSierra,
10257
+ isSupportedSpecVersion,
10258
+ isV3Tx,
10259
+ isVersion,
9786
10260
  json_exports as json,
9787
10261
  logger,
9788
10262
  merkle_exports as merkle,
@@ -9795,6 +10269,7 @@ export {
9795
10269
  src5_exports as src5,
9796
10270
  stark_exports as stark,
9797
10271
  starknetId_exports as starknetId,
10272
+ toAnyPatchVersion,
9798
10273
  transaction_exports as transaction,
9799
10274
  typedData_exports as typedData,
9800
10275
  types_exports as types,