starknet 11.4.1 → 11.4.2

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
@@ -17003,11 +17003,720 @@ function fastExecute() {
17003
17003
  };
17004
17004
  }
17005
17005
 
17006
+ // src/plugins/paymaster/utils.ts
17007
+ var utils_exports = {};
17008
+ __export(utils_exports, {
17009
+ assertCallsAreStrictlyEqual: () => assertCallsAreStrictlyEqual,
17010
+ assertPaymasterTransactionSafety: () => assertPaymasterTransactionSafety,
17011
+ getDefaultPaymasterNodeUrl: () => getDefaultPaymasterNodeUrl
17012
+ });
17013
+
17014
+ // src/utils/outsideExecution.ts
17015
+ var outsideExecution_exports = {};
17016
+ __export(outsideExecution_exports, {
17017
+ buildExecuteFromOutsideCall: () => buildExecuteFromOutsideCall,
17018
+ buildExecuteFromOutsideCallData: () => buildExecuteFromOutsideCallData,
17019
+ getOutsideCall: () => getOutsideCall,
17020
+ getTypedData: () => getTypedData,
17021
+ toOutsideCallV2: () => toOutsideCallV2
17022
+ });
17023
+ function toOutsideCallV2(call) {
17024
+ if ("calldata_len" in call) {
17025
+ return {
17026
+ To: call.to,
17027
+ Selector: call.selector,
17028
+ Calldata: call.calldata
17029
+ };
17030
+ }
17031
+ return call;
17032
+ }
17033
+ function getOutsideCall(call) {
17034
+ const callData = call.calldata ?? [];
17035
+ const callDataCompiled = Array.isArray(callData) && "__compiled__" in callData ? callData : CallData.compile(callData);
17036
+ return {
17037
+ to: call.contractAddress,
17038
+ selector: getSelectorFromName(call.entrypoint),
17039
+ calldata: callDataCompiled
17040
+ };
17041
+ }
17042
+ function callToTypedData(call, version) {
17043
+ const outsideCall = getOutsideCall(call);
17044
+ if (version === "1") {
17045
+ return {
17046
+ ...outsideCall,
17047
+ calldata_len: outsideCall.calldata.length,
17048
+ calldata: outsideCall.calldata
17049
+ };
17050
+ }
17051
+ return {
17052
+ To: outsideCall.to,
17053
+ Selector: outsideCall.selector,
17054
+ Calldata: outsideCall.calldata
17055
+ };
17056
+ }
17057
+ function getDomain(chainId, version) {
17058
+ return {
17059
+ name: "Account.execute_from_outside",
17060
+ version,
17061
+ chainId,
17062
+ ...version === "2" ? { revision: "1" } : {}
17063
+ };
17064
+ }
17065
+ function getTypedData(chainId, options, nonce, myCalls, version) {
17066
+ if (version === "1") {
17067
+ return {
17068
+ types: OutsideExecutionTypesV1,
17069
+ primaryType: "OutsideExecution",
17070
+ domain: getDomain(chainId, version),
17071
+ message: {
17072
+ ...options,
17073
+ nonce,
17074
+ calls_len: myCalls.length,
17075
+ calls: myCalls.map((call) => callToTypedData(call, version))
17076
+ }
17077
+ };
17078
+ }
17079
+ return {
17080
+ types: OutsideExecutionTypesV2,
17081
+ primaryType: "OutsideExecution",
17082
+ domain: getDomain(chainId, version),
17083
+ message: {
17084
+ Caller: options.caller,
17085
+ Nonce: nonce,
17086
+ "Execute After": options.execute_after,
17087
+ "Execute Before": options.execute_before,
17088
+ Calls: myCalls.map((call) => callToTypedData(call, version))
17089
+ }
17090
+ };
17091
+ }
17092
+ function buildExecuteFromOutsideCallData(outsideTransaction) {
17093
+ const execution2 = outsideTransaction.outsideExecution;
17094
+ const formattedSignature = formatSignature(outsideTransaction.signature);
17095
+ return CallData.compile({
17096
+ outside_execution: execution2,
17097
+ signature: formattedSignature
17098
+ });
17099
+ }
17100
+ function buildExecuteFromOutsideCall(outsideTransaction) {
17101
+ const myOutsideTransactions = Array.isArray(outsideTransaction) ? outsideTransaction : [outsideTransaction];
17102
+ const multiCall = myOutsideTransactions.map((outsideTx) => {
17103
+ let entrypoint;
17104
+ if (outsideTx.version === OutsideExecutionVersion.V1) {
17105
+ entrypoint = "execute_from_outside";
17106
+ } else if (outsideTx.version === OutsideExecutionVersion.V2) {
17107
+ entrypoint = "execute_from_outside_v2";
17108
+ } else {
17109
+ throw new Error("Unsupported OutsideExecution version");
17110
+ }
17111
+ return {
17112
+ contractAddress: toHex(outsideTx.signerAddress),
17113
+ entrypoint,
17114
+ calldata: buildExecuteFromOutsideCallData(outsideTx)
17115
+ };
17116
+ });
17117
+ return multiCall;
17118
+ }
17119
+
17120
+ // src/utils/uint256.ts
17121
+ var uint256_exports = {};
17122
+ __export(uint256_exports, {
17123
+ bnToUint256: () => bnToUint256,
17124
+ isUint256: () => isUint256,
17125
+ uint256ToBN: () => uint256ToBN
17126
+ });
17127
+ function uint256ToBN(uint2562) {
17128
+ return new CairoUint256(uint2562).toBigInt();
17129
+ }
17130
+ function isUint256(bn) {
17131
+ return CairoUint256.is(bn);
17132
+ }
17133
+ function bnToUint256(bn) {
17134
+ return new CairoUint256(bn).toUint256HexString();
17135
+ }
17136
+
17137
+ // src/plugins/paymaster/utils.ts
17138
+ var getDefaultPaymasterNodeUrl = (networkName, mute = false) => {
17139
+ if (!mute) {
17140
+ logger.info("Using default public node url, please provide nodeUrl in provider options!");
17141
+ }
17142
+ const nodes = PAYMASTER_RPC_NODES[networkName ?? _NetworkName.SN_SEPOLIA];
17143
+ const randIdx = Math.floor(Math.random() * nodes.length);
17144
+ return nodes[randIdx];
17145
+ };
17146
+ var assertGasFeeFromUnsafeCalls = (unsafeCalls, fees) => {
17147
+ const unsafeCall = toOutsideCallV2(unsafeCalls[unsafeCalls.length - 1]);
17148
+ const unsafeGasTokenCalldata = CallData.toCalldata(unsafeCall.Calldata);
17149
+ const unsafeGasTokenValue = uint256ToBN({
17150
+ low: unsafeGasTokenCalldata[1],
17151
+ high: unsafeGasTokenCalldata[2]
17152
+ });
17153
+ assert(
17154
+ unsafeGasTokenValue === BigInt(fees),
17155
+ "Gas token value is not equal to the provided gas fees"
17156
+ );
17157
+ };
17158
+ var assertGasTokenFromUnsafeCalls = (unsafeCalls, gasToken) => {
17159
+ const unsafeCall = toOutsideCallV2(unsafeCalls[unsafeCalls.length - 1]);
17160
+ assert(
17161
+ BigInt(unsafeCall.To) === BigInt(gasToken),
17162
+ "Gas token address is not equal to the provided gas token"
17163
+ );
17164
+ assert(
17165
+ unsafeCall.Selector === getSelectorFromName("transfer"),
17166
+ "Gas token call selector is not a transfer"
17167
+ );
17168
+ assert(
17169
+ CallData.toCalldata(unsafeCall.Calldata).length === 3,
17170
+ "Gas token transfer calldata does not match the expected recipient/amount shape"
17171
+ );
17172
+ };
17173
+ function assertCallsAreStrictlyEqual(originalCalls, unsafeCalls, isSponsored = false) {
17174
+ const baseError = "Provided calls are not strictly equal to the returned calls";
17175
+ const expectedExtraCalls = isSponsored ? 0 : 1;
17176
+ assert(
17177
+ unsafeCalls.length - expectedExtraCalls === originalCalls.length,
17178
+ `${baseError}: Expected ${originalCalls.length + expectedExtraCalls} calls, got ${unsafeCalls.length}`
17179
+ );
17180
+ for (let callIndex = 0; callIndex < originalCalls.length; callIndex += 1) {
17181
+ const originalCall = originalCalls[callIndex];
17182
+ const unsafeCall = toOutsideCallV2(unsafeCalls[callIndex]);
17183
+ const normalizeAddress = (address) => {
17184
+ return toBigInt(address).toString(16).toLowerCase();
17185
+ };
17186
+ const originalAddress = normalizeAddress(originalCall.contractAddress);
17187
+ const unsafeAddress = normalizeAddress(unsafeCall.To);
17188
+ assert(
17189
+ originalAddress === unsafeAddress,
17190
+ `${baseError}: Contract address mismatch at call ${callIndex}. Expected: ${originalCall.contractAddress}, Got: ${unsafeCall.To}`
17191
+ );
17192
+ assert(
17193
+ getSelectorFromName(originalCall.entrypoint) === unsafeCall.Selector,
17194
+ `${baseError}: Entrypoint mismatch at call ${callIndex}. Expected: ${originalCall.entrypoint}, Got: ${unsafeCall.Selector}`
17195
+ );
17196
+ const originalCalldata = CallData.toCalldata(originalCall.calldata);
17197
+ const unsafeCalldata = CallData.toCalldata(unsafeCall.Calldata);
17198
+ assert(
17199
+ originalCalldata.length === unsafeCalldata.length,
17200
+ `${baseError}: Calldata length mismatch at call ${callIndex}. Expected length: ${originalCalldata.length}, Got length: ${unsafeCalldata.length}`
17201
+ );
17202
+ for (let dataIndex = 0; dataIndex < originalCalldata.length; dataIndex += 1) {
17203
+ const originalValue = BigInt(originalCalldata[dataIndex]);
17204
+ const unsafeValue = BigInt(unsafeCalldata[dataIndex]);
17205
+ assert(
17206
+ originalValue === unsafeValue,
17207
+ `${baseError}: Calldata value mismatch at call ${callIndex}, parameter ${dataIndex}. Expected: ${originalCalldata[dataIndex]}, Got: ${unsafeCalldata[dataIndex]}`
17208
+ );
17209
+ }
17210
+ }
17211
+ }
17212
+ var domainFieldToFelt = (value) => {
17213
+ try {
17214
+ return toBigInt(value);
17215
+ } catch {
17216
+ return CairoBytes31.fromText(String(value)).toBigInt();
17217
+ }
17218
+ };
17219
+ var assertChainIdFromTypedData = (typedData, chainId) => {
17220
+ assert(
17221
+ typedData.domain.chainId !== void 0 && domainFieldToFelt(typedData.domain.chainId) === BigInt(chainId),
17222
+ "Paymaster typed data domain chainId does not match the account's provider chain"
17223
+ );
17224
+ };
17225
+ var assertPaymasterTransactionSafety = (preparedTransaction, calls, paymasterDetails, chainId, maxFeeInGasToken) => {
17226
+ if (preparedTransaction.type === "invoke" || preparedTransaction.type === "deploy_and_invoke") {
17227
+ assertChainIdFromTypedData(preparedTransaction.typed_data, chainId);
17228
+ const { message } = preparedTransaction.typed_data;
17229
+ const hasV1Calls = "calls" in message;
17230
+ const hasV2Calls = "Calls" in message;
17231
+ assert(
17232
+ hasV1Calls !== hasV2Calls,
17233
+ 'Paymaster typed data must declare exactly one of "calls" (SNIP-9 V1) or "Calls" (SNIP-9 V2)'
17234
+ );
17235
+ const unsafeCalls = hasV1Calls ? message.calls : message.Calls;
17236
+ assertCallsAreStrictlyEqual(calls, unsafeCalls, paymasterDetails.feeMode.mode === "sponsored");
17237
+ if (paymasterDetails.feeMode.mode !== "sponsored") {
17238
+ assertGasTokenFromUnsafeCalls(unsafeCalls, paymasterDetails.feeMode.gasToken);
17239
+ assertGasFeeFromUnsafeCalls(
17240
+ unsafeCalls,
17241
+ preparedTransaction.fee.suggested_max_fee_in_gas_token
17242
+ );
17243
+ if (maxFeeInGasToken) {
17244
+ assert(
17245
+ preparedTransaction.fee.suggested_max_fee_in_gas_token <= maxFeeInGasToken,
17246
+ "Gas token price is too high"
17247
+ );
17248
+ }
17249
+ }
17250
+ const msg = message;
17251
+ const version = hasV1Calls ? OutsideExecutionVersion.V1 : OutsideExecutionVersion.V2;
17252
+ const [callerKey, nonceKey, afterKey, beforeKey] = hasV1Calls ? ["caller", "nonce", "execute_after", "execute_before"] : ["Caller", "Nonce", "Execute After", "Execute Before"];
17253
+ assert(
17254
+ [callerKey, nonceKey, afterKey, beforeKey].every((key) => msg[key] !== void 0),
17255
+ "Paymaster typed data does not match the expected outside execution"
17256
+ );
17257
+ const caller = msg[callerKey];
17258
+ const nonce = msg[nonceKey];
17259
+ const executeAfter = msg[afterKey];
17260
+ const executeBefore = msg[beforeKey];
17261
+ if (paymasterDetails.timeBounds) {
17262
+ const requestedAfter = toBigInt(paymasterDetails.timeBounds.executeAfter ?? 1);
17263
+ const requestedBefore = toBigInt(paymasterDetails.timeBounds.executeBefore);
17264
+ assert(
17265
+ toBigInt(executeAfter) >= requestedAfter && toBigInt(executeBefore) <= requestedBefore,
17266
+ "Paymaster typed data execution window is not within the requested time bounds"
17267
+ );
17268
+ }
17269
+ const expectedCalls = [...calls];
17270
+ if (paymasterDetails.feeMode.mode !== "sponsored") {
17271
+ const feeCall = toOutsideCallV2(unsafeCalls[unsafeCalls.length - 1]);
17272
+ const feeRecipient = CallData.toCalldata(feeCall.Calldata)[0];
17273
+ const feeAmount = bnToUint256(preparedTransaction.fee.suggested_max_fee_in_gas_token);
17274
+ expectedCalls.push({
17275
+ contractAddress: paymasterDetails.feeMode.gasToken,
17276
+ entrypoint: "transfer",
17277
+ calldata: [feeRecipient, feeAmount.low, feeAmount.high]
17278
+ });
17279
+ }
17280
+ const expectedTypedData = getTypedData(
17281
+ chainId,
17282
+ { caller, execute_after: executeAfter, execute_before: executeBefore },
17283
+ nonce,
17284
+ expectedCalls,
17285
+ version
17286
+ );
17287
+ assert(
17288
+ getMessageHash(expectedTypedData, 0) === getMessageHash(preparedTransaction.typed_data, 0),
17289
+ "Paymaster typed data does not match the expected outside execution"
17290
+ );
17291
+ }
17292
+ };
17293
+
17294
+ // src/plugins/paymaster/impl.ts
17295
+ var PaymasterImpl = class {
17296
+ /**
17297
+ * Asks the paymaster to build a transaction for the calls of an account.
17298
+ * @param {Account} account The account that will sign the transaction.
17299
+ * @param {Call[]} calls The calls to execute.
17300
+ * @param {PaymasterDetails} paymasterDetails The fee mode, and optionally the deployment data
17301
+ * and the time bounds.
17302
+ * @returns {Promise<PreparedTransaction>} The transaction prepared by the paymaster, with its
17303
+ * typed data to sign and its fees.
17304
+ * @example
17305
+ * ```typescript
17306
+ * const prepared = await PaymasterImpl.build(myAccount, [myCall], {
17307
+ * feeMode: { mode: 'sponsored' },
17308
+ * });
17309
+ * // prepared.type = 'invoke'
17310
+ * ```
17311
+ */
17312
+ static async build(account, calls, paymasterDetails) {
17313
+ if (!paymasterDetails.deploymentData) {
17314
+ const snip9Version = await account.getSnip9Version();
17315
+ if (snip9Version === OutsideExecutionVersion.UNSUPPORTED) {
17316
+ throw Error("Account is not compatible with SNIP-9");
17317
+ }
17318
+ }
17319
+ const parameters = {
17320
+ version: "0x1",
17321
+ feeMode: paymasterDetails.feeMode,
17322
+ timeBounds: paymasterDetails.timeBounds
17323
+ };
17324
+ let transaction;
17325
+ if (paymasterDetails.deploymentData) {
17326
+ if (calls.length > 0) {
17327
+ transaction = {
17328
+ type: "deploy_and_invoke",
17329
+ invoke: { userAddress: account.address, calls },
17330
+ deployment: paymasterDetails.deploymentData
17331
+ };
17332
+ } else {
17333
+ transaction = {
17334
+ type: "deploy",
17335
+ deployment: paymasterDetails.deploymentData
17336
+ };
17337
+ }
17338
+ } else {
17339
+ transaction = {
17340
+ type: "invoke",
17341
+ invoke: { userAddress: account.address, calls }
17342
+ };
17343
+ }
17344
+ return account.paymaster.buildTransaction(transaction, parameters);
17345
+ }
17346
+ /**
17347
+ * Asks the paymaster for the fees of the calls of an account.
17348
+ * @param {Account} account The account that will sign the transaction.
17349
+ * @param {Call[]} calls The calls to execute.
17350
+ * @param {PaymasterDetails} paymasterDetails The fee mode, and optionally the deployment data
17351
+ * and the time bounds.
17352
+ * @returns {Promise<PaymasterFeeEstimate>} The fees, in STRK and in the gas token.
17353
+ * @example
17354
+ * ```typescript
17355
+ * const fees = await PaymasterImpl.estimate(myAccount, [myCall], {
17356
+ * feeMode: { mode: 'default', gasToken: usdcAddress },
17357
+ * });
17358
+ * // fees.suggested_max_fee_in_gas_token is the fee to show to the user
17359
+ * ```
17360
+ */
17361
+ static async estimate(account, calls, paymasterDetails) {
17362
+ const preparedTransaction = await account.buildPaymasterTransaction(calls, paymasterDetails);
17363
+ return preparedTransaction.fee;
17364
+ }
17365
+ /**
17366
+ * Checks that a transaction prepared by the paymaster is safe to sign, then signs it.
17367
+ * @param {Account} account The account that signs the transaction.
17368
+ * @param {PreparedTransaction} preparedTransaction The transaction returned by the paymaster.
17369
+ * @param {Call[]} calls The calls the user requested.
17370
+ * @param {PaymasterDetails} paymasterDetails The fee mode and related paymaster details.
17371
+ * @param {BigNumberish} [maxFeeInGasToken] Optional user-approved ceiling on the gas-token fee.
17372
+ * @returns {Promise<ExecutableUserTransaction>} The transaction to send to the paymaster.
17373
+ * @example
17374
+ * ```typescript
17375
+ * const prepared = await PaymasterImpl.build(myAccount, [myCall], paymasterDetails);
17376
+ * const executable = await PaymasterImpl.prepare(myAccount, prepared, [myCall], paymasterDetails);
17377
+ * // executable.type = 'invoke'
17378
+ * ```
17379
+ */
17380
+ static async prepare(account, preparedTransaction, calls, paymasterDetails, maxFeeInGasToken) {
17381
+ assertPaymasterTransactionSafety(
17382
+ preparedTransaction,
17383
+ calls,
17384
+ paymasterDetails,
17385
+ await account.provider.getChainId(),
17386
+ maxFeeInGasToken
17387
+ );
17388
+ let transaction;
17389
+ switch (preparedTransaction.type) {
17390
+ case "deploy_and_invoke": {
17391
+ const signature = await account.signMessage(preparedTransaction.typed_data);
17392
+ transaction = {
17393
+ type: "deploy_and_invoke",
17394
+ invoke: {
17395
+ userAddress: account.address,
17396
+ typedData: preparedTransaction.typed_data,
17397
+ signature: signatureToHexArray(signature)
17398
+ },
17399
+ deployment: preparedTransaction.deployment
17400
+ };
17401
+ break;
17402
+ }
17403
+ case "invoke": {
17404
+ const signature = await account.signMessage(preparedTransaction.typed_data);
17405
+ transaction = {
17406
+ type: "invoke",
17407
+ invoke: {
17408
+ userAddress: account.address,
17409
+ typedData: preparedTransaction.typed_data,
17410
+ signature: signatureToHexArray(signature)
17411
+ }
17412
+ };
17413
+ break;
17414
+ }
17415
+ case "deploy": {
17416
+ transaction = {
17417
+ type: "deploy",
17418
+ deployment: preparedTransaction.deployment
17419
+ };
17420
+ break;
17421
+ }
17422
+ default:
17423
+ throw Error("Invalid transaction type");
17424
+ }
17425
+ return transaction;
17426
+ }
17427
+ /**
17428
+ * Builds, checks, signs and sends a paymaster transaction for the calls of an account.
17429
+ * @param {Account} account The account that signs the transaction.
17430
+ * @param {Call[]} calls The calls to execute.
17431
+ * @param {PaymasterDetails} paymasterDetails The fee mode, and optionally the deployment data
17432
+ * and the time bounds.
17433
+ * @param {BigNumberish} [maxFeeInGasToken] Optional user-approved ceiling on the gas-token fee.
17434
+ * @returns {Promise<InvokeFunctionResponse>} The hash of the transaction sent by the paymaster.
17435
+ * @example
17436
+ * ```typescript
17437
+ * const { transaction_hash } = await PaymasterImpl.execute(myAccount, [myCall], {
17438
+ * feeMode: { mode: 'sponsored' },
17439
+ * });
17440
+ * await myAccount.provider.waitForTransaction(transaction_hash);
17441
+ * ```
17442
+ */
17443
+ static async execute(account, calls, paymasterDetails, maxFeeInGasToken) {
17444
+ const preparedTransaction = await account.buildPaymasterTransaction(calls, paymasterDetails);
17445
+ const transaction = await account.preparePaymasterTransaction(
17446
+ preparedTransaction,
17447
+ calls,
17448
+ paymasterDetails,
17449
+ maxFeeInGasToken
17450
+ );
17451
+ return account.paymaster.executeTransaction(transaction, preparedTransaction.parameters).then((response) => ({ transaction_hash: response.transaction_hash }));
17452
+ }
17453
+ };
17454
+
17455
+ // src/plugins/paymaster/rpc.ts
17456
+ var convertCalls = (calls) => calls.map((call) => ({
17457
+ to: call.contractAddress,
17458
+ selector: getSelectorFromName(call.entrypoint),
17459
+ calldata: CallData.toHex(call.calldata)
17460
+ }));
17461
+ var convertFeeMode = (feeMode) => {
17462
+ if (feeMode.mode === "sponsored") {
17463
+ return { mode: "sponsored" };
17464
+ }
17465
+ return { mode: "default", gas_token: feeMode.gasToken };
17466
+ };
17467
+ var convertFEE_MODE = (feeMode) => {
17468
+ if (feeMode.mode === "sponsored") {
17469
+ return { mode: "sponsored" };
17470
+ }
17471
+ return { mode: "default", gasToken: feeMode.gas_token };
17472
+ };
17473
+ var convertTimeBounds = (timeBounds) => timeBounds ? {
17474
+ execute_after: timeBounds.executeAfter || 1,
17475
+ // If executeAfter is not provided, set it to 1, meaning the transaction can be executed immediately
17476
+ execute_before: timeBounds.executeBefore
17477
+ } : void 0;
17478
+ var convertTIME_BOUNDS = (timeBounds) => timeBounds ? {
17479
+ executeAfter: timeBounds.execute_after,
17480
+ executeBefore: timeBounds.execute_before
17481
+ } : void 0;
17482
+ var convertEXECUTION_PARAMETERS = (parameters) => ({
17483
+ version: parameters.version,
17484
+ feeMode: convertFEE_MODE(parameters.fee_mode),
17485
+ timeBounds: convertTIME_BOUNDS(parameters.time_bounds)
17486
+ });
17487
+ var defaultOptions = {
17488
+ headers: { "Content-Type": "application/json" }
17489
+ };
17490
+ var PaymasterRpc = class _PaymasterRpc {
17491
+ nodeUrl;
17492
+ headers;
17493
+ baseFetch;
17494
+ requestId;
17495
+ constructor(options) {
17496
+ if (options instanceof _PaymasterRpc) {
17497
+ this.nodeUrl = options.nodeUrl;
17498
+ this.headers = { ...defaultOptions.headers, ...options.headers };
17499
+ this.baseFetch = options.baseFetch;
17500
+ this.requestId = options.requestId;
17501
+ return;
17502
+ }
17503
+ if (options && "nodeUrl" in options && "headers" in options && "baseFetch" in options) {
17504
+ this.nodeUrl = options.nodeUrl ?? getDefaultPaymasterNodeUrl(void 0);
17505
+ this.headers = { ...defaultOptions.headers, ...options.headers };
17506
+ this.baseFetch = options.baseFetch ?? fetch_default;
17507
+ this.requestId = 0;
17508
+ return;
17509
+ }
17510
+ const { nodeUrl, headers, baseFetch } = options || {};
17511
+ if (nodeUrl && Object.values(_NetworkName).includes(nodeUrl)) {
17512
+ this.nodeUrl = getDefaultPaymasterNodeUrl(nodeUrl, options?.mute);
17513
+ } else if (nodeUrl) {
17514
+ this.nodeUrl = nodeUrl;
17515
+ } else {
17516
+ this.nodeUrl = getDefaultPaymasterNodeUrl(void 0, options?.mute);
17517
+ }
17518
+ this.baseFetch = baseFetch ?? fetch_default;
17519
+ this.headers = { ...defaultOptions.headers, ...headers };
17520
+ this.requestId = 0;
17521
+ }
17522
+ fetch(method, params, id = 0) {
17523
+ const rpcRequestBody = {
17524
+ id,
17525
+ jsonrpc: "2.0",
17526
+ method,
17527
+ ...params && { params }
17528
+ };
17529
+ return this.baseFetch(this.nodeUrl, {
17530
+ method: "POST",
17531
+ body: stringify2(rpcRequestBody),
17532
+ headers: this.headers
17533
+ });
17534
+ }
17535
+ errorHandler(method, params, rpcError, otherError) {
17536
+ if (rpcError) {
17537
+ throw new RpcError(rpcError, method, params);
17538
+ }
17539
+ if (otherError instanceof LibraryError) {
17540
+ throw otherError;
17541
+ }
17542
+ if (otherError) {
17543
+ throw Error(otherError.message);
17544
+ }
17545
+ }
17546
+ async fetchEndpoint(method, params) {
17547
+ try {
17548
+ this.requestId += 1;
17549
+ const rawResult = await this.fetch(method, params, this.requestId);
17550
+ const { error, result } = await rawResult.json();
17551
+ this.errorHandler(method, params, error);
17552
+ return result;
17553
+ } catch (error) {
17554
+ this.errorHandler(method, params, error?.response?.data, error);
17555
+ throw error;
17556
+ }
17557
+ }
17558
+ async isAvailable() {
17559
+ return this.fetchEndpoint("paymaster_isAvailable");
17560
+ }
17561
+ async buildTransaction(transaction, parameters) {
17562
+ let userTransaction;
17563
+ switch (transaction.type) {
17564
+ case "invoke":
17565
+ userTransaction = {
17566
+ ...transaction,
17567
+ invoke: {
17568
+ user_address: transaction.invoke.userAddress,
17569
+ calls: convertCalls(transaction.invoke.calls)
17570
+ }
17571
+ };
17572
+ break;
17573
+ case "deploy_and_invoke":
17574
+ userTransaction = {
17575
+ ...transaction,
17576
+ invoke: {
17577
+ user_address: transaction.invoke.userAddress,
17578
+ calls: convertCalls(transaction.invoke.calls)
17579
+ }
17580
+ };
17581
+ break;
17582
+ case "deploy":
17583
+ default:
17584
+ userTransaction = transaction;
17585
+ break;
17586
+ }
17587
+ const executionParameters = {
17588
+ version: parameters.version,
17589
+ fee_mode: convertFeeMode(parameters.feeMode),
17590
+ time_bounds: convertTimeBounds(parameters.timeBounds)
17591
+ };
17592
+ const response = await this.fetchEndpoint("paymaster_buildTransaction", {
17593
+ transaction: userTransaction,
17594
+ parameters: executionParameters
17595
+ });
17596
+ const fee = {
17597
+ gas_token_price_in_strk: BigInt(response.fee.gas_token_price_in_strk),
17598
+ estimated_fee_in_strk: BigInt(response.fee.estimated_fee_in_strk),
17599
+ estimated_fee_in_gas_token: BigInt(response.fee.estimated_fee_in_gas_token),
17600
+ suggested_max_fee_in_strk: BigInt(response.fee.suggested_max_fee_in_strk),
17601
+ suggested_max_fee_in_gas_token: BigInt(response.fee.suggested_max_fee_in_gas_token)
17602
+ };
17603
+ switch (response.type) {
17604
+ case "invoke":
17605
+ return {
17606
+ type: "invoke",
17607
+ typed_data: response.typed_data,
17608
+ parameters: convertEXECUTION_PARAMETERS(response.parameters),
17609
+ fee
17610
+ };
17611
+ case "deploy_and_invoke":
17612
+ return {
17613
+ type: "deploy_and_invoke",
17614
+ deployment: response.deployment,
17615
+ typed_data: response.typed_data,
17616
+ parameters: convertEXECUTION_PARAMETERS(response.parameters),
17617
+ fee
17618
+ };
17619
+ case "deploy":
17620
+ default:
17621
+ return {
17622
+ type: "deploy",
17623
+ deployment: response.deployment,
17624
+ parameters: convertEXECUTION_PARAMETERS(response.parameters),
17625
+ fee
17626
+ };
17627
+ }
17628
+ }
17629
+ async executeTransaction(transaction, parameters) {
17630
+ let user_transaction;
17631
+ switch (transaction.type) {
17632
+ case "invoke":
17633
+ user_transaction = {
17634
+ ...transaction,
17635
+ invoke: {
17636
+ user_address: transaction.invoke.userAddress,
17637
+ typed_data: transaction.invoke.typedData,
17638
+ signature: signatureToHexArray(transaction.invoke.signature)
17639
+ }
17640
+ };
17641
+ break;
17642
+ case "deploy_and_invoke":
17643
+ user_transaction = {
17644
+ ...transaction,
17645
+ invoke: {
17646
+ user_address: transaction.invoke.userAddress,
17647
+ typed_data: transaction.invoke.typedData,
17648
+ signature: signatureToHexArray(transaction.invoke.signature)
17649
+ }
17650
+ };
17651
+ break;
17652
+ case "deploy":
17653
+ default:
17654
+ user_transaction = transaction;
17655
+ break;
17656
+ }
17657
+ const executionParameters = {
17658
+ version: parameters.version,
17659
+ fee_mode: convertFeeMode(parameters.feeMode),
17660
+ time_bounds: convertTimeBounds(parameters.timeBounds)
17661
+ };
17662
+ return this.fetchEndpoint("paymaster_executeTransaction", {
17663
+ transaction: user_transaction,
17664
+ parameters: executionParameters
17665
+ });
17666
+ }
17667
+ async getSupportedTokens() {
17668
+ return this.fetchEndpoint("paymaster_getSupportedTokens").then(
17669
+ (tokens) => tokens.map((token) => ({
17670
+ token_address: token.token_address,
17671
+ decimals: token.decimals,
17672
+ priceInStrk: BigInt(token.price_in_strk)
17673
+ }))
17674
+ );
17675
+ }
17676
+ };
17677
+
17678
+ // src/plugins/paymaster/interface.ts
17679
+ var PaymasterInterface = class {
17680
+ };
17681
+
17682
+ // src/plugins/paymaster/index.ts
17683
+ var PAYMASTER_PLUGIN_NAME = "paymaster";
17684
+ function paymasterPlugin(options) {
17685
+ return {
17686
+ name: PAYMASTER_PLUGIN_NAME,
17687
+ accountExtend(account) {
17688
+ const target = account;
17689
+ const members = {
17690
+ paymaster: options ? new PaymasterRpc(options) : new PaymasterRpc({ mute: true }),
17691
+ buildPaymasterTransaction: (calls, paymasterDetails) => PaymasterImpl.build(target, calls, paymasterDetails),
17692
+ estimatePaymasterTransactionFee: (calls, paymasterDetails) => PaymasterImpl.estimate(target, calls, paymasterDetails),
17693
+ preparePaymasterTransaction: (preparedTransaction, calls, paymasterDetails, maxFeeInGasToken) => PaymasterImpl.prepare(
17694
+ target,
17695
+ preparedTransaction,
17696
+ calls,
17697
+ paymasterDetails,
17698
+ maxFeeInGasToken
17699
+ ),
17700
+ executePaymasterTransaction: (calls, paymasterDetails, maxFeeInGasToken) => PaymasterImpl.execute(target, calls, paymasterDetails, maxFeeInGasToken)
17701
+ };
17702
+ return Object.fromEntries(
17703
+ Object.entries(members).filter(([name]) => !(name in account))
17704
+ );
17705
+ }
17706
+ };
17707
+ }
17708
+ function applyPaymasterOption(plugins, paymaster) {
17709
+ if (!paymaster) return plugins;
17710
+ const configured = paymasterPlugin(paymaster);
17711
+ return plugins.some((plugin) => plugin.name === PAYMASTER_PLUGIN_NAME) ? plugins.map((plugin) => plugin.name === PAYMASTER_PLUGIN_NAME ? configured : plugin) : [...plugins, configured];
17712
+ }
17713
+
17006
17714
  // src/plugins/defaults.ts
17007
17715
  var defaultPlugins = [
17008
17716
  starknetId(),
17009
17717
  brotherId(),
17010
- fastExecute()
17718
+ fastExecute(),
17719
+ paymasterPlugin()
17011
17720
  ];
17012
17721
 
17013
17722
  // src/provider/rpc.ts
@@ -17580,25 +18289,6 @@ var Signer = class {
17580
18289
 
17581
18290
  // src/signer/ethSigner.ts
17582
18291
  import { secp256k1 as secp256k12 } from "@noble/curves/secp256k1.js";
17583
-
17584
- // src/utils/uint256.ts
17585
- var uint256_exports = {};
17586
- __export(uint256_exports, {
17587
- bnToUint256: () => bnToUint256,
17588
- isUint256: () => isUint256,
17589
- uint256ToBN: () => uint256ToBN
17590
- });
17591
- function uint256ToBN(uint2562) {
17592
- return new CairoUint256(uint2562).toBigInt();
17593
- }
17594
- function isUint256(bn) {
17595
- return CairoUint256.is(bn);
17596
- }
17597
- function bnToUint256(bn) {
17598
- return new CairoUint256(bn).toUint256HexString();
17599
- }
17600
-
17601
- // src/signer/ethSigner.ts
17602
18292
  var EthSigner = class {
17603
18293
  pk;
17604
18294
  // hex string without 0x and with an odd number of characters
@@ -17747,264 +18437,59 @@ var LedgerSigner111 = class {
17747
18437
  * // result= "0x03681417ba3e1f050dd3ccdceb8d22b5e44fa70ee7844d472c6a768bded5174e"
17748
18438
  * ```
17749
18439
  */
17750
- async getPubKey() {
17751
- if (!this.pubKey) await this.getPublicKeys();
17752
- return this.pubKey;
17753
- }
17754
- /**
17755
- * provides the full public key (with parity prefix)
17756
- * @returns an hex string : 2 first characters are the parity, the 64 following characters are Point X coordinate. 64 last characters are Point Y coordinate.
17757
- * @example
17758
- * ```typescript
17759
- * const result = await myLedgerSigner.getFullPubKey();
17760
- * // result= "0x0403681417ba3e1f050dd3ccdceb8d22b5e44fa70ee7844d472c6a768bded5174e03cbc86f805dcfcb0c1922dd4daf181afa289d86223a18bc856276615bcc7787"
17761
- * ```
17762
- */
17763
- async getFullPubKey() {
17764
- if (!this.fullPubKey) await this.getPublicKeys();
17765
- return this.fullPubKey;
17766
- }
17767
- /**
17768
- * Returns the version of the Starknet APP implemented in the Ledger.
17769
- * @returns {string} version.
17770
- * @example
17771
- * ```typescript
17772
- * const result = await myLedgerSigner.getAppVersion();
17773
- * // result= "1.1.1"
17774
- * ```
17775
- */
17776
- async getAppVersion() {
17777
- if (!this.appVersion) {
17778
- const resp = await this._transporter.send(Number("0x5a"), 0, 0, 0);
17779
- this.appVersion = `${resp[0]}.${resp[1]}.${resp[2]}`;
17780
- }
17781
- return this.appVersion;
17782
- }
17783
- /**
17784
- * Sign a TypedData message (SNIP-12) in a Ledger.
17785
- * @param {typedDataToHash} typedDataToHash A TypedData message compatible with SNIP-12.
17786
- * @param {string} accountAddress Signer account address (Hex or num string)
17787
- * @returns {Signature} The signed message.
17788
- * @example
17789
- * ```typescript
17790
- * const result = myLedgerSigner.signMessage(snip12Message, account0.address);
17791
- * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
17792
- * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
17793
- * // recovery: 0}
17794
- * ```
17795
- */
17796
- async signMessage(typedDataToHash, accountAddress) {
17797
- const msgHash = getMessageHash(typedDataToHash, accountAddress);
17798
- return this.signRaw(msgHash);
17799
- }
17800
- /**
17801
- * Sign in a Ledger a V3 transaction. This is a blind sign on the Ledger screen.
17802
- * @param {Call1[]} transactions An array of `Call` transactions (generated for example by `myContract.populate()`).
17803
- * @param {InvocationsSignerDetails} transactionsDetail An object that includes all the necessary inputs to hash the transaction.
17804
- * @returns {Signature} The signed transaction.
17805
- * @example
17806
- * ```typescript
17807
- * const txDetailsV3: V3InvocationsSignerDetails = {
17808
- * chainId: constants.StarknetChainId.SN_MAIN,
17809
- * nonce: "28",
17810
- * accountDeploymentData: [],
17811
- * paymasterData: [],
17812
- * cairoVersion: "1",
17813
- * feeDataAvailabilityMode: "L1",
17814
- * nonceDataAvailabilityMode: "L1",
17815
- * resourceBounds: {
17816
- * l1_gas: {
17817
- * max_amount: "0x2a00",
17818
- * max_price_per_unit: "0x5c00000"
17819
- * },
17820
- * l2_gas: {
17821
- * max_amount: "0x00",
17822
- * max_price_per_unit: "0x00"
17823
- * },
17824
- * },
17825
- * tip: 0,
17826
- * version: "0x3",
17827
- * walletAddress: account0.address
17828
- * }
17829
- * const result = myLedgerSigner.signTransaction([call0, call1], txDetailsV3);
17830
- * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
17831
- * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
17832
- * // recovery: 0}
17833
- * ```
17834
- */
17835
- async signTransaction(transactions, transactionsDetail) {
17836
- const compiledCalldata = getExecuteCalldata(transactions, transactionsDetail.cairoVersion);
17837
- const msgHash = calculateInvokeTransactionHash2({
17838
- ...transactionsDetail,
17839
- senderAddress: transactionsDetail.walletAddress,
17840
- compiledCalldata,
17841
- version: transactionsDetail.version,
17842
- nonceDataAvailabilityMode: intDAM(transactionsDetail.nonceDataAvailabilityMode),
17843
- feeDataAvailabilityMode: intDAM(transactionsDetail.feeDataAvailabilityMode)
17844
- });
17845
- return this.signRaw(msgHash);
17846
- }
17847
- /**
17848
- * Sign in a Ledger the deployment of a new account. This is a blind sign on the Ledger screen.
17849
- * @param {DeployAccountSignerDetails} details An object that includes all necessary data to calculate the Hash.
17850
- * @returns {Signature} The deploy account signature.
17851
- * @example
17852
- * ```typescript
17853
- * const result = myLedgerSigner.signDeployAccountTransaction(details);
17854
- * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
17855
- * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
17856
- * // recovery: 0}
17857
- * ```
17858
- */
17859
- async signDeployAccountTransaction(details) {
17860
- const compiledConstructorCalldata = CallData.compile(details.constructorCalldata);
17861
- const msgHash = calculateDeployAccountTransactionHash2({
17862
- ...details,
17863
- salt: details.addressSalt,
17864
- compiledConstructorCalldata,
17865
- version: details.version,
17866
- nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
17867
- feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
17868
- });
17869
- return this.signRaw(msgHash);
17870
- }
17871
- /**
17872
- * Sign in a Ledger the declaration of a new class. This is a blind sign on the Ledger screen.
17873
- * @param {DeclareSignerDetails} details An object that includes all necessary data to calculate the Hash.
17874
- * @returns {Signature} The declare Signature.
17875
- * @example
17876
- * ```typescript
17877
- * const result = myLedgerSigner.signDeclareTransaction(details);
17878
- * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
17879
- * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
17880
- * // recovery: 0}
17881
- * ```
17882
- */
17883
- async signDeclareTransaction(details) {
17884
- const msgHash = calculateDeclareTransactionHash2({
17885
- ...details,
17886
- version: details.version,
17887
- nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
17888
- feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
17889
- });
17890
- return this.signRaw(msgHash);
17891
- }
17892
- /**
17893
- * Internal function to sign a hash in a Ledger Nano.
17894
- * This is a blind sign in the Ledger ; no display of what you are signing.
17895
- */
17896
- async signRaw(msgHash) {
17897
- addHexPrefix(
17898
- buf2hex(await this._transporter.send(Number("0x5a"), 2, 0, 0, buffer_default.from(this.pathBuffer)))
17899
- );
17900
- const shiftedHash = toHex(BigInt(msgHash) << 4n);
17901
- const buff2 = hexToBytes(shiftedHash);
17902
- const respSign2 = Uint8Array.from(
17903
- await this._transporter.send(Number("0x5a"), 2, 1, 0, buffer_default.from(buff2))
17904
- );
17905
- const r = BigInt(addHexPrefix(buf2hex(respSign2.subarray(1, 33))));
17906
- const s = BigInt(addHexPrefix(buf2hex(respSign2.subarray(33, 65))));
17907
- const v = respSign2[65];
17908
- const sign0 = new starkCurve.Signature(r, s);
17909
- const sign1 = sign0.addRecoveryBit(v);
17910
- return sign1;
17911
- }
17912
- /** internal function to get both the Starknet public key and the full public key */
17913
- async getPublicKeys() {
17914
- const pathBuff = this.pathBuffer;
17915
- const respGetPublic = Uint8Array.from(
17916
- await this._transporter.send(Number("0x5a"), 1, 0, 0, buffer_default.from(pathBuff))
17917
- );
17918
- this.pubKey = addHexPrefix(buf2hex(respGetPublic.subarray(1, 33)));
17919
- this.fullPubKey = addHexPrefix(buf2hex(respGetPublic.subarray(0, 65)));
17920
- }
17921
- };
17922
- function getLedgerPathBuffer111(accountId, applicationName = "LedgerW") {
17923
- const path0buff = new Uint8Array([128, 0, 10, 85]);
17924
- const path1buff = new Uint8Array([71, 65, 233, 201]);
17925
- const path2buff = applicationName === "LedgerW" ? new Uint8Array([43, 206, 231, 219]) : stringToSha256ToArrayBuff4(applicationName);
17926
- const path3buff = new Uint8Array([0, 0, 0, 0]);
17927
- const hex = toHex(accountId);
17928
- const padded = addHexPrefix(removeHexPrefix(hex).padStart(8, "0"));
17929
- const path4buff = hexToBytes(padded);
17930
- const path5buff = new Uint8Array([0, 0, 0, 0]);
17931
- const pathBuff = concatenateArrayBuffer([
17932
- path0buff,
17933
- path1buff,
17934
- path2buff,
17935
- path3buff,
17936
- path4buff,
17937
- path5buff
17938
- ]);
17939
- return pathBuff;
17940
- }
17941
-
17942
- // src/utils/address.ts
17943
- import { hexToBytes as hexToBytes2 } from "@noble/curves/utils.js";
17944
- function addAddressPadding(address) {
17945
- const hex = toHex(isString(address) ? addHexPrefix(address) : address);
17946
- const padded = removeHexPrefix(hex).padStart(64, "0");
17947
- return addHexPrefix(padded);
17948
- }
17949
- function validateAndParseAddress(address) {
17950
- if (isString(address) && !/^(0x)?[0-9a-f]+$/i.test(address)) {
17951
- throw new Error("Invalid Address Format");
17952
- }
17953
- const result = addAddressPadding(address);
17954
- if (!result.match(/^(0x)?[0-9a-fA-F]{64}$/)) {
17955
- throw new Error("Invalid Address Format");
17956
- }
17957
- assertInRange(result, ZERO, ADDR_BOUND - 1n, "Starknet Address");
17958
- return result;
17959
- }
17960
- function getChecksumAddress(address) {
17961
- const chars = removeHexPrefix(validateAndParseAddress(address)).toLowerCase().split("");
17962
- const hex = removeHexPrefix(keccakBn(address));
17963
- const hashed = hexToBytes2(hex.padStart(64, "0"));
17964
- for (let i = 0; i < chars.length; i += 2) {
17965
- if (hashed[i >> 1] >> 4 >= 8) {
17966
- chars[i] = chars[i].toUpperCase();
17967
- }
17968
- if ((hashed[i >> 1] & 15) >= 8) {
17969
- chars[i + 1] = chars[i + 1].toUpperCase();
17970
- }
18440
+ async getPubKey() {
18441
+ if (!this.pubKey) await this.getPublicKeys();
18442
+ return this.pubKey;
17971
18443
  }
17972
- return addHexPrefix(chars.join(""));
17973
- }
17974
- function validateChecksumAddress(address) {
17975
- return getChecksumAddress(address) === address;
17976
- }
17977
-
17978
- // src/signer/ledgerSigner221.ts
17979
- var LedgerSigner221 = class extends LedgerSigner111 {
17980
18444
  /**
17981
- * constructor of the LedgerSigner class.
17982
- * @param {Transport} transport 5 transports are available to handle USB, bluetooth, Node, Web, Mobile.
17983
- * See Guides for more details.
17984
- * @param {number} accountID ID of Ledger Nano (can handle 2**31 accounts).
17985
- * @param {string} [eip2645application='LedgerW'] A wallet is defined by an ERC2645 derivation path (6 items).
17986
- * One item is called `application` and can be customized.
17987
- * Default value is `LedgerW`.
17988
- * @param {LedgerPathCalculation} [pathFunction=getLedgerPathBuffer221]
17989
- * defines the function that will calculate the path. By default `getLedgerPathBuffer221` is selected.
17990
- *
17991
- * If you are using APP v2.2.1 with an account created with the v1.1.1, you need to use :
18445
+ * provides the full public key (with parity prefix)
18446
+ * @returns an hex string : 2 first characters are the parity, the 64 following characters are Point X coordinate. 64 last characters are Point Y coordinate.
18447
+ * @example
17992
18448
  * ```typescript
17993
- * const myLedgerSigner = new LedgerSigner221(myNodeTransport, 0, undefined, getLedgerPathBuffer111);
18449
+ * const result = await myLedgerSigner.getFullPubKey();
18450
+ * // result= "0x0403681417ba3e1f050dd3ccdceb8d22b5e44fa70ee7844d472c6a768bded5174e03cbc86f805dcfcb0c1922dd4daf181afa289d86223a18bc856276615bcc7787"
17994
18451
  * ```
18452
+ */
18453
+ async getFullPubKey() {
18454
+ if (!this.fullPubKey) await this.getPublicKeys();
18455
+ return this.fullPubKey;
18456
+ }
18457
+ /**
18458
+ * Returns the version of the Starknet APP implemented in the Ledger.
18459
+ * @returns {string} version.
17995
18460
  * @example
17996
18461
  * ```typescript
17997
- * import TransportNodeHid from "@ledgerhq/hw-transport-node-hid";
17998
- * const myNodeTransport = await TransportNodeHid.create();
17999
- * const myLedgerSigner = new LedgerSigner221(myNodeTransport, 0);
18462
+ * const result = await myLedgerSigner.getAppVersion();
18463
+ * // result= "1.1.1"
18000
18464
  * ```
18001
18465
  */
18002
- constructor(transport, accountID, eip2645application = "LedgerW", pathFunction = getLedgerPathBuffer221) {
18003
- super(transport, accountID, eip2645application, pathFunction);
18466
+ async getAppVersion() {
18467
+ if (!this.appVersion) {
18468
+ const resp = await this._transporter.send(Number("0x5a"), 0, 0, 0);
18469
+ this.appVersion = `${resp[0]}.${resp[1]}.${resp[2]}`;
18470
+ }
18471
+ return this.appVersion;
18004
18472
  }
18005
18473
  /**
18006
- * Sign in a Ledger a V3 transaction. The details are displayed on the Ledger screen.
18007
- * @param {Call[]} transactions An array of `Call` transactions (generated for example by `myContract.populate()`).
18474
+ * Sign a TypedData message (SNIP-12) in a Ledger.
18475
+ * @param {typedDataToHash} typedDataToHash A TypedData message compatible with SNIP-12.
18476
+ * @param {string} accountAddress Signer account address (Hex or num string)
18477
+ * @returns {Signature} The signed message.
18478
+ * @example
18479
+ * ```typescript
18480
+ * const result = myLedgerSigner.signMessage(snip12Message, account0.address);
18481
+ * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
18482
+ * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
18483
+ * // recovery: 0}
18484
+ * ```
18485
+ */
18486
+ async signMessage(typedDataToHash, accountAddress) {
18487
+ const msgHash = getMessageHash(typedDataToHash, accountAddress);
18488
+ return this.signRaw(msgHash);
18489
+ }
18490
+ /**
18491
+ * Sign in a Ledger a V3 transaction. This is a blind sign on the Ledger screen.
18492
+ * @param {Call1[]} transactions An array of `Call` transactions (generated for example by `myContract.populate()`).
18008
18493
  * @param {InvocationsSignerDetails} transactionsDetail An object that includes all the necessary inputs to hash the transaction.
18009
18494
  * @returns {Signature} The signed transaction.
18010
18495
  * @example
@@ -18028,292 +18513,108 @@ var LedgerSigner221 = class extends LedgerSigner111 {
18028
18513
  * },
18029
18514
  * },
18030
18515
  * tip: 0,
18031
- * version: "0x3",
18032
- * walletAddress: account0.address
18033
- * }
18034
- * const result = myLedgerSigner.signTransaction([call0, call1], txDetailsV3);
18035
- * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
18036
- * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
18037
- * // recovery: 0}
18038
- * ```
18039
- */
18040
- async signTransaction(transactions, transactionsDetail) {
18041
- const compiledCalldata = getExecuteCalldata(transactions, transactionsDetail.cairoVersion);
18042
- const msgHash = calculateInvokeTransactionHash2({
18043
- ...transactionsDetail,
18044
- senderAddress: transactionsDetail.walletAddress,
18045
- compiledCalldata,
18046
- version: transactionsDetail.version,
18047
- nonceDataAvailabilityMode: intDAM(transactionsDetail.nonceDataAvailabilityMode),
18048
- feeDataAvailabilityMode: intDAM(transactionsDetail.feeDataAvailabilityMode)
18049
- });
18050
- const ledgerResponse = await this.signTxV3(transactionsDetail, transactions);
18051
- assert(
18052
- toBigInt(msgHash) === ledgerResponse.hash,
18053
- "The V3 transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
18054
- );
18055
- return ledgerResponse.signature;
18056
- }
18057
- /**
18058
- * Sign in a Ledger the deployment of a new account. The details are displayed on the Ledger screen.
18059
- * @param {DeployAccountSignerDetails} details An object that includes all necessary data to calculate the Hash.
18060
- * @returns {Signature} The deploy account signature.
18061
- * @example
18062
- * ```typescript
18063
- * const result = myLedgerSigner.signDeployAccountTransaction(details);
18064
- * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
18065
- * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
18066
- * // recovery: 0}
18067
- * ```
18068
- */
18069
- async signDeployAccountTransaction(details) {
18070
- const compiledConstructorCalldata = CallData.compile(details.constructorCalldata);
18071
- const msgHash = calculateDeployAccountTransactionHash2({
18072
- ...details,
18073
- salt: details.addressSalt,
18074
- compiledConstructorCalldata,
18075
- version: details.version,
18076
- nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
18077
- feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
18078
- });
18079
- const ledgerResponse = await this.signDeployAccountV3(details);
18080
- assert(
18081
- toBigInt(msgHash) === ledgerResponse.hash,
18082
- "The transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
18083
- );
18084
- return ledgerResponse.signature;
18085
- }
18086
- /**
18087
- * Internal function to convert a bigNumberish to an Uint8array of 256 bits
18088
- * @param {BigNumberish} input input value
18089
- * @returns {Uint8Array} a Uint8Array containing 32 bytes.
18090
- */
18091
- convertBnToLedger(input) {
18092
- return hexToBytes(addAddressPadding(toHex(input)));
18093
- }
18094
- /**
18095
- * Internal function to decode the response of the Ledger signature
18096
- * @param {Uint8Array} respSign the Buffer response of the Ledger
18097
- * @returns { hash: bigint; signature: Signature } transaction hash & signature
18098
- */
18099
- decodeSignatureLedger(respSign) {
18100
- const h = BigInt(addHexPrefix(buf2hex(respSign.subarray(0, 32))));
18101
- const r = BigInt(addHexPrefix(buf2hex(respSign.subarray(33, 65))));
18102
- const s = BigInt(addHexPrefix(buf2hex(respSign.subarray(65, 97))));
18103
- const v = respSign[97];
18104
- const sign0 = new starkCurve.Signature(r, s);
18105
- const sign1 = sign0.addRecoveryBit(v);
18106
- return { hash: h, signature: sign1 };
18107
- }
18108
- /** Internal function to convert a Call to an array of Uint8Array.
18109
- * @param {Call} call A Call to convert.
18110
- * @return {Uint8Array[]} Call encoded in an array of Uint8Array (each containing 7 u256).
18111
- */
18112
- encodeCall(call) {
18113
- const toBuf = this.convertBnToLedger(call.contractAddress);
18114
- const selectorBuf = hexToBytes(addAddressPadding(getSelector(call.entrypoint)));
18115
- let calldataBuf = new Uint8Array([]);
18116
- if (call.calldata) {
18117
- const compiledCalldata = CallData.compile(call.calldata);
18118
- calldataBuf = concatenateArrayBuffer(
18119
- compiledCalldata.map((parameter) => {
18120
- const a = this.convertBnToLedger(parameter);
18121
- return a;
18122
- })
18123
- );
18124
- }
18125
- const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
18126
- const calldatas = [];
18127
- const chunkSize = 7 * 32;
18128
- for (let i = 0; i < callBuf.length; i += chunkSize)
18129
- calldatas.push(callBuf.subarray(i, i + chunkSize));
18130
- return calldatas;
18131
- }
18132
- /**
18133
- * Ask to the Ledger Nano to display and sign a Starknet V3 transaction.
18134
- * @param {V3InvocationsSignerDetails} txDetails All the details needed for a txV3.
18135
- * @param {Call[]} calls array of Starknet invocations
18136
- * @returns an object including the transaction Hash and the signature
18137
- * @example
18138
- * ```typescript
18139
- * const calls: Call[] = [{contractAddress: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
18140
- * entrypoint: "transfer",
18141
- * calldata:["0x11f5fc2a92ac03434a7937fe982f5e5293b65ad438a989c5b78fb8f04a12016",
18142
- * "0x9184e72a000", "0x0"]}];
18143
- * const txDetailsV3: V3InvocationsSignerDetails = {
18144
- * chainId: constants.StarknetChainId.SN_MAIN,
18145
- * nonce: "28", accountDeploymentData: [],
18146
- * paymasterData: [], cairoVersion: "1",
18147
- * feeDataAvailabilityMode: "L1", nonceDataAvailabilityMode: "L1",
18148
- * resourceBounds: {
18149
- * l1_gas: { max_amount: "0x2a00", max_price_per_unit: "0x5c00000"
18150
- * },
18151
- * l2_gas: { max_amount: "0x00", max_price_per_unit: "0x00"},
18152
- * }, tip: 0, version: "0x3", walletAddress: account0.address
18153
- * };
18154
- * const res = await myLedgerSigner.signTxV3(txDetailsV3, calls);
18155
- * // res = {hash:
18156
- * // signature:
18157
- * // }
18158
- * ```
18159
- */
18160
- async signTxV3(txDetails, calls) {
18161
- assert(txDetails.paymasterData.length <= 7, "Paymaster data includes more than 7 items.");
18162
- assert(
18163
- txDetails.accountDeploymentData.length <= 7,
18164
- "accountDeploymentData includes more than 7 items"
18165
- );
18166
- await this._transporter.send(Number("0x5a"), 3, 0, 0, buffer_default.from(this.pathBuffer));
18167
- const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
18168
- const tipBuf = this.convertBnToLedger(txDetails.tip);
18169
- const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
18170
- const nonceBuf = this.convertBnToLedger(txDetails.nonce);
18171
- const dAModeHashBuf = this.convertBnToLedger(
18172
- hashDAMode(
18173
- txDetails.nonceDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2,
18174
- txDetails.feeDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2
18175
- )
18176
- );
18177
- const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
18178
- const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
18179
- const dataBuf = concatenateArrayBuffer([
18180
- accountAddressBuf,
18181
- tipBuf,
18182
- l1_gasBuf,
18183
- l2_gasBuf,
18184
- chainIdBuf,
18185
- nonceBuf,
18186
- dAModeHashBuf
18187
- ]);
18188
- await this._transporter.send(Number("0x5a"), 3, 1, 0, buffer_default.from(dataBuf));
18189
- const paymasterBuf = concatenateArrayBuffer(
18190
- txDetails.paymasterData.map((value) => {
18191
- const a = this.convertBnToLedger(value);
18192
- return a;
18193
- })
18194
- );
18195
- await this._transporter.send(Number("0x5a"), 3, 2, 0, buffer_default.from(paymasterBuf));
18196
- const accountDeployDataBuf = concatenateArrayBuffer(
18197
- txDetails.paymasterData.map((value) => {
18198
- const a = this.convertBnToLedger(value);
18199
- return a;
18200
- })
18201
- );
18202
- await this._transporter.send(Number("0x5a"), 3, 3, 0, buffer_default.from(accountDeployDataBuf));
18203
- const nbCallsBuf = this.convertBnToLedger(calls.length);
18204
- await this._transporter.send(Number("0x5a"), 3, 4, 0, buffer_default.from(nbCallsBuf));
18205
- let respSign = new Uint8Array(0);
18206
- for (const call of calls) {
18207
- const calldatas = this.encodeCall(call);
18208
- await this._transporter.send(Number("0x5a"), 3, 5, 0, buffer_default.from(calldatas[0]));
18209
- if (calldatas.length > 1) {
18210
- calldatas.slice(1).forEach(async (part) => {
18211
- await this._transporter.send(Number("0x5a"), 3, 5, 1, buffer_default.from(part));
18212
- });
18213
- }
18214
- respSign = await this._transporter.send(Number("0x5a"), 3, 5, 2);
18215
- }
18216
- return this.decodeSignatureLedger(respSign);
18516
+ * version: "0x3",
18517
+ * walletAddress: account0.address
18518
+ * }
18519
+ * const result = myLedgerSigner.signTransaction([call0, call1], txDetailsV3);
18520
+ * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
18521
+ * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
18522
+ * // recovery: 0}
18523
+ * ```
18524
+ */
18525
+ async signTransaction(transactions, transactionsDetail) {
18526
+ const compiledCalldata = getExecuteCalldata(transactions, transactionsDetail.cairoVersion);
18527
+ const msgHash = calculateInvokeTransactionHash2({
18528
+ ...transactionsDetail,
18529
+ senderAddress: transactionsDetail.walletAddress,
18530
+ compiledCalldata,
18531
+ version: transactionsDetail.version,
18532
+ nonceDataAvailabilityMode: intDAM(transactionsDetail.nonceDataAvailabilityMode),
18533
+ feeDataAvailabilityMode: intDAM(transactionsDetail.feeDataAvailabilityMode)
18534
+ });
18535
+ return this.signRaw(msgHash);
18217
18536
  }
18218
18537
  /**
18219
- *Ask the Ledger Nano to display and sign a Starknet V3 account deployment.
18220
- * @param {V3DeployAccountSignerDetails} deployAccountDetail All the details needed for a V3 deploy account.
18221
- * @returns an object including the transaction Hash and the signature
18538
+ * Sign in a Ledger the deployment of a new account. This is a blind sign on the Ledger screen.
18539
+ * @param {DeployAccountSignerDetails} details An object that includes all necessary data to calculate the Hash.
18540
+ * @returns {Signature} The deploy account signature.
18222
18541
  * @example
18223
18542
  * ```typescript
18224
- * const deployData: V3DeployAccountSignerDetails =
18225
- * {
18226
- * tip: 0, paymasterData: [], accountDeploymentData: [],
18227
- * nonceDataAvailabilityMode: 'L1', feeDataAvailabilityMode: 'L1',
18228
- * resourceBounds: {
18229
- * l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' },
18230
- * l1_gas: { max_amount: '0x226', max_price_per_unit: '0x22ecb25c00' }
18231
- * },
18232
- * classHash: '0x540d7f5ec7ecf317e68d48564934cb99259781b1ee3cedbbc37ec5337f8e688',
18233
- * constructorCalldata: [
18234
- * '3571125127744830445572285574469842579401255431821644822726857471463672199621'
18235
- * ],
18236
- * contractAddress: '0x4ca062add1cf12a107be1107af17981cf6e544a24d987693230ea481d3d5e34',
18237
- * addressSalt: '0x07e52f68e3160e1ef698211cdf6d3792368fe347e7e2d4a8ace14d9b248f39c5',
18238
- * chainId: '0x534e5f5345504f4c4941',
18239
- * version: '0x3', nonce: 0n
18240
- *}
18241
- * const res = await myLedgerSigner.signDeployAccountV3(deployData);
18242
- * // res = {hash:
18243
- * // signature:
18244
- * // }
18543
+ * const result = myLedgerSigner.signDeployAccountTransaction(details);
18544
+ * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
18545
+ * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
18546
+ * // recovery: 0}
18245
18547
  * ```
18246
18548
  */
18247
- async signDeployAccountV3(deployAccountDetail) {
18248
- await this._transporter.send(Number("0x5a"), 5, 0, 0, buffer_default.from(this.pathBuffer));
18249
- const accountAddressBuf = this.convertBnToLedger(
18250
- deployAccountDetail.contractAddress
18251
- );
18252
- const chainIdBuf = this.convertBnToLedger(deployAccountDetail.chainId);
18253
- const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
18254
- const dAModeHashBuf = this.convertBnToLedger(
18255
- hashDAMode(
18256
- deployAccountDetail.nonceDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2,
18257
- deployAccountDetail.feeDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2
18258
- )
18259
- );
18260
- const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
18261
- const saltBuf = this.convertBnToLedger(deployAccountDetail.addressSalt);
18262
- const dataBuf = concatenateArrayBuffer([
18263
- accountAddressBuf,
18264
- chainIdBuf,
18265
- nonceBuf,
18266
- dAModeHashBuf,
18267
- classHashBuf,
18268
- saltBuf
18269
- ]);
18270
- await this._transporter.send(Number("0x5a"), 5, 1, 0, buffer_default.from(dataBuf));
18271
- const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
18272
- const l1_gasBuf = this.convertBnToLedger(
18273
- encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
18274
- );
18275
- const l2_gasBuf = this.convertBnToLedger(
18276
- encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
18549
+ async signDeployAccountTransaction(details) {
18550
+ const compiledConstructorCalldata = CallData.compile(details.constructorCalldata);
18551
+ const msgHash = calculateDeployAccountTransactionHash2({
18552
+ ...details,
18553
+ salt: details.addressSalt,
18554
+ compiledConstructorCalldata,
18555
+ version: details.version,
18556
+ nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
18557
+ feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
18558
+ });
18559
+ return this.signRaw(msgHash);
18560
+ }
18561
+ /**
18562
+ * Sign in a Ledger the declaration of a new class. This is a blind sign on the Ledger screen.
18563
+ * @param {DeclareSignerDetails} details An object that includes all necessary data to calculate the Hash.
18564
+ * @returns {Signature} The declare Signature.
18565
+ * @example
18566
+ * ```typescript
18567
+ * const result = myLedgerSigner.signDeclareTransaction(details);
18568
+ * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
18569
+ * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
18570
+ * // recovery: 0}
18571
+ * ```
18572
+ */
18573
+ async signDeclareTransaction(details) {
18574
+ const msgHash = calculateDeclareTransactionHash2({
18575
+ ...details,
18576
+ version: details.version,
18577
+ nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
18578
+ feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
18579
+ });
18580
+ return this.signRaw(msgHash);
18581
+ }
18582
+ /**
18583
+ * Internal function to sign a hash in a Ledger Nano.
18584
+ * This is a blind sign in the Ledger ; no display of what you are signing.
18585
+ */
18586
+ async signRaw(msgHash) {
18587
+ addHexPrefix(
18588
+ buf2hex(await this._transporter.send(Number("0x5a"), 2, 0, 0, buffer_default.from(this.pathBuffer)))
18277
18589
  );
18278
- const feeBuf = concatenateArrayBuffer([tipBuf, l1_gasBuf, l2_gasBuf]);
18279
- await this._transporter.send(Number("0x5a"), 5, 2, 0, buffer_default.from(feeBuf));
18280
- const paymasterBuf = concatenateArrayBuffer(
18281
- deployAccountDetail.paymasterData.map((value) => {
18282
- const a = this.convertBnToLedger(value);
18283
- return a;
18284
- })
18590
+ const shiftedHash = toHex(BigInt(msgHash) << 4n);
18591
+ const buff2 = hexToBytes(shiftedHash);
18592
+ const respSign2 = Uint8Array.from(
18593
+ await this._transporter.send(Number("0x5a"), 2, 1, 0, buffer_default.from(buff2))
18285
18594
  );
18286
- await this._transporter.send(Number("0x5a"), 5, 3, 0, buffer_default.from(paymasterBuf));
18287
- const compiledConstructor = CallData.compile(deployAccountDetail.constructorCalldata);
18288
- const constructorLengthBuf = this.convertBnToLedger(compiledConstructor.length);
18289
- await this._transporter.send(Number("0x5a"), 5, 4, 0, buffer_default.from(constructorLengthBuf));
18290
- const constructorBuf = concatenateArrayBuffer(
18291
- compiledConstructor.map((parameter) => {
18292
- const a = this.convertBnToLedger(parameter);
18293
- return a;
18294
- })
18595
+ const r = BigInt(addHexPrefix(buf2hex(respSign2.subarray(1, 33))));
18596
+ const s = BigInt(addHexPrefix(buf2hex(respSign2.subarray(33, 65))));
18597
+ const v = respSign2[65];
18598
+ const sign0 = new starkCurve.Signature(r, s);
18599
+ const sign1 = sign0.addRecoveryBit(v);
18600
+ return sign1;
18601
+ }
18602
+ /** internal function to get both the Starknet public key and the full public key */
18603
+ async getPublicKeys() {
18604
+ const pathBuff = this.pathBuffer;
18605
+ const respGetPublic = Uint8Array.from(
18606
+ await this._transporter.send(Number("0x5a"), 1, 0, 0, buffer_default.from(pathBuff))
18295
18607
  );
18296
- const constructorChunks = [];
18297
- const chunkSize = 7 * 32;
18298
- for (let i = 0; i < constructorBuf.length; i += chunkSize)
18299
- constructorChunks.push(constructorBuf.subarray(i, i + chunkSize));
18300
- let respSign = new Uint8Array(0);
18301
- for (const chunk of constructorChunks) {
18302
- respSign = await this._transporter.send(Number("0x5a"), 5, 5, 0, buffer_default.from(chunk));
18303
- }
18304
- return this.decodeSignatureLedger(respSign);
18608
+ this.pubKey = addHexPrefix(buf2hex(respGetPublic.subarray(1, 33)));
18609
+ this.fullPubKey = addHexPrefix(buf2hex(respGetPublic.subarray(0, 65)));
18305
18610
  }
18306
18611
  };
18307
- function getLedgerPathBuffer221(accountId, applicationName = "LedgerW") {
18308
- const path0buff = new Uint8Array([HARDENING_BYTE, 0, 10, 85]);
18309
- const path1buff = new Uint8Array([71 | HARDENING_BYTE, 65, 233, 201]);
18310
- const path2Base = applicationName === "LedgerW" ? new Uint8Array([43, 206, 231, 219]) : stringToSha256ToArrayBuff4(applicationName);
18311
- const path2buff = concatenateArrayBuffer([
18312
- new Uint8Array([path2Base[0] | HARDENING_BYTE]),
18313
- path2Base.subarray(1)
18314
- ]);
18315
- const path3buff = new Uint8Array([HARDENING_BYTE, 0, 0, 0]);
18316
- const hex = toHex(BigInt(accountId) | HARDENING_4BYTES);
18612
+ function getLedgerPathBuffer111(accountId, applicationName = "LedgerW") {
18613
+ const path0buff = new Uint8Array([128, 0, 10, 85]);
18614
+ const path1buff = new Uint8Array([71, 65, 233, 201]);
18615
+ const path2buff = applicationName === "LedgerW" ? new Uint8Array([43, 206, 231, 219]) : stringToSha256ToArrayBuff4(applicationName);
18616
+ const path3buff = new Uint8Array([0, 0, 0, 0]);
18617
+ const hex = toHex(accountId);
18317
18618
  const padded = addHexPrefix(removeHexPrefix(hex).padStart(8, "0"));
18318
18619
  const path4buff = hexToBytes(padded);
18319
18620
  const path5buff = new Uint8Array([0, 0, 0, 0]);
@@ -18328,224 +18629,171 @@ function getLedgerPathBuffer221(accountId, applicationName = "LedgerW") {
18328
18629
  return pathBuff;
18329
18630
  }
18330
18631
 
18331
- // src/signer/ledgerSigner231.ts
18332
- var LedgerSigner231 = class extends LedgerSigner221 {
18632
+ // src/utils/address.ts
18633
+ import { hexToBytes as hexToBytes2 } from "@noble/curves/utils.js";
18634
+ function addAddressPadding(address) {
18635
+ const hex = toHex(isString(address) ? addHexPrefix(address) : address);
18636
+ const padded = removeHexPrefix(hex).padStart(64, "0");
18637
+ return addHexPrefix(padded);
18638
+ }
18639
+ function validateAndParseAddress(address) {
18640
+ if (isString(address) && !/^(0x)?[0-9a-f]+$/i.test(address)) {
18641
+ throw new Error("Invalid Address Format");
18642
+ }
18643
+ const result = addAddressPadding(address);
18644
+ if (!result.match(/^(0x)?[0-9a-fA-F]{64}$/)) {
18645
+ throw new Error("Invalid Address Format");
18646
+ }
18647
+ assertInRange(result, ZERO, ADDR_BOUND - 1n, "Starknet Address");
18648
+ return result;
18649
+ }
18650
+ function getChecksumAddress(address) {
18651
+ const chars = removeHexPrefix(validateAndParseAddress(address)).toLowerCase().split("");
18652
+ const hex = removeHexPrefix(keccakBn(address));
18653
+ const hashed = hexToBytes2(hex.padStart(64, "0"));
18654
+ for (let i = 0; i < chars.length; i += 2) {
18655
+ if (hashed[i >> 1] >> 4 >= 8) {
18656
+ chars[i] = chars[i].toUpperCase();
18657
+ }
18658
+ if ((hashed[i >> 1] & 15) >= 8) {
18659
+ chars[i + 1] = chars[i + 1].toUpperCase();
18660
+ }
18661
+ }
18662
+ return addHexPrefix(chars.join(""));
18663
+ }
18664
+ function validateChecksumAddress(address) {
18665
+ return getChecksumAddress(address) === address;
18666
+ }
18667
+
18668
+ // src/signer/ledgerSigner221.ts
18669
+ var LedgerSigner221 = class extends LedgerSigner111 {
18333
18670
  /**
18334
18671
  * constructor of the LedgerSigner class.
18335
18672
  * @param {Transport} transport 5 transports are available to handle USB, bluetooth, Node, Web, Mobile.
18336
18673
  * See Guides for more details.
18337
- * @param {number} accountID ID of Ledger Nano account (can handle 2**31 accounts).
18674
+ * @param {number} accountID ID of Ledger Nano (can handle 2**31 accounts).
18338
18675
  * @param {string} [eip2645application='LedgerW'] A wallet is defined by an ERC2645 derivation path (6 items).
18339
18676
  * One item is called `application` and can be customized.
18340
18677
  * Default value is `LedgerW`.
18341
18678
  * @param {LedgerPathCalculation} [pathFunction=getLedgerPathBuffer221]
18342
18679
  * defines the function that will calculate the path. By default `getLedgerPathBuffer221` is selected.
18343
18680
  *
18344
- * If you are using APP v2.3.1 with an account created with the v1.1.1, you need to use :
18681
+ * If you are using APP v2.2.1 with an account created with the v1.1.1, you need to use :
18345
18682
  * ```typescript
18346
- * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0, undefined, getLedgerPathBuffer111);
18683
+ * const myLedgerSigner = new LedgerSigner221(myNodeTransport, 0, undefined, getLedgerPathBuffer111);
18347
18684
  * ```
18348
18685
  * @example
18349
18686
  * ```typescript
18350
18687
  * import TransportNodeHid from "@ledgerhq/hw-transport-node-hid";
18351
18688
  * const myNodeTransport = await TransportNodeHid.create();
18352
- * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0);
18689
+ * const myLedgerSigner = new LedgerSigner221(myNodeTransport, 0);
18690
+ * ```
18691
+ */
18692
+ constructor(transport, accountID, eip2645application = "LedgerW", pathFunction = getLedgerPathBuffer221) {
18693
+ super(transport, accountID, eip2645application, pathFunction);
18694
+ }
18695
+ /**
18696
+ * Sign in a Ledger a V3 transaction. The details are displayed on the Ledger screen.
18697
+ * @param {Call[]} transactions An array of `Call` transactions (generated for example by `myContract.populate()`).
18698
+ * @param {InvocationsSignerDetails} transactionsDetail An object that includes all the necessary inputs to hash the transaction.
18699
+ * @returns {Signature} The signed transaction.
18700
+ * @example
18701
+ * ```typescript
18702
+ * const txDetailsV3: V3InvocationsSignerDetails = {
18703
+ * chainId: constants.StarknetChainId.SN_MAIN,
18704
+ * nonce: "28",
18705
+ * accountDeploymentData: [],
18706
+ * paymasterData: [],
18707
+ * cairoVersion: "1",
18708
+ * feeDataAvailabilityMode: "L1",
18709
+ * nonceDataAvailabilityMode: "L1",
18710
+ * resourceBounds: {
18711
+ * l1_gas: {
18712
+ * max_amount: "0x2a00",
18713
+ * max_price_per_unit: "0x5c00000"
18714
+ * },
18715
+ * l2_gas: {
18716
+ * max_amount: "0x00",
18717
+ * max_price_per_unit: "0x00"
18718
+ * },
18719
+ * },
18720
+ * tip: 0,
18721
+ * version: "0x3",
18722
+ * walletAddress: account0.address
18723
+ * }
18724
+ * const result = myLedgerSigner.signTransaction([call0, call1], txDetailsV3);
18725
+ * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
18726
+ * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
18727
+ * // recovery: 0}
18353
18728
  * ```
18354
18729
  */
18355
- constructor(transport, accountID, eip2645application = "LedgerW", pathFunction = getLedgerPathBuffer221) {
18356
- super(transport, accountID, eip2645application, pathFunction);
18730
+ async signTransaction(transactions, transactionsDetail) {
18731
+ const compiledCalldata = getExecuteCalldata(transactions, transactionsDetail.cairoVersion);
18732
+ const msgHash = calculateInvokeTransactionHash2({
18733
+ ...transactionsDetail,
18734
+ senderAddress: transactionsDetail.walletAddress,
18735
+ compiledCalldata,
18736
+ version: transactionsDetail.version,
18737
+ nonceDataAvailabilityMode: intDAM(transactionsDetail.nonceDataAvailabilityMode),
18738
+ feeDataAvailabilityMode: intDAM(transactionsDetail.feeDataAvailabilityMode)
18739
+ });
18740
+ const ledgerResponse = await this.signTxV3(transactionsDetail, transactions);
18741
+ assert(
18742
+ toBigInt(msgHash) === ledgerResponse.hash,
18743
+ "The V3 transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
18744
+ );
18745
+ return ledgerResponse.signature;
18357
18746
  }
18358
18747
  /**
18359
- * Ask to the Ledger Nano to display and sign a Starknet V3 transaction.
18360
- * @param {V3InvocationsSignerDetails} txDetails All the details needed for a txV3.
18361
- * @param {Call[]} calls array of Starknet invocations
18362
- * @returns an object including the transaction Hash and the signature
18748
+ * Sign in a Ledger the deployment of a new account. The details are displayed on the Ledger screen.
18749
+ * @param {DeployAccountSignerDetails} details An object that includes all necessary data to calculate the Hash.
18750
+ * @returns {Signature} The deploy account signature.
18363
18751
  * @example
18364
18752
  * ```typescript
18365
- * const calls: Call[] = [{contractAddress: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
18366
- * entrypoint: "transfer",
18367
- * calldata:["0x11f5fc2a92ac03434a7937fe982f5e5293b65ad438a989c5b78fb8f04a12016",
18368
- * "0x9184e72a000", "0x0"]}];
18369
- * const txDetailsV3: V3InvocationsSignerDetails = {
18370
- * chainId: constants.StarknetChainId.SN_MAIN,
18371
- * nonce: "28", accountDeploymentData: [],
18372
- * paymasterData: [], cairoVersion: "1",
18373
- * feeDataAvailabilityMode: "L1", nonceDataAvailabilityMode: "L1",
18374
- * resourceBounds: {
18375
- * l1_gas: { max_amount: "0x2a00", max_price_per_unit: "0x5c00000"
18376
- * },
18377
- * l2_gas: { max_amount: "0x00", max_price_per_unit: "0x00"},
18378
- * }, tip: 0, version: "0x3", walletAddress: account0.address
18379
- * };
18380
- * const res = await myLedgerSigner.signTxV3(txDetailsV3, calls);
18381
- * // res = {hash:
18382
- * // signature:
18383
- * // }
18753
+ * const result = myLedgerSigner.signDeployAccountTransaction(details);
18754
+ * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
18755
+ * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
18756
+ * // recovery: 0}
18384
18757
  * ```
18385
18758
  */
18386
- async signTxV3(txDetails, calls) {
18387
- assert(txDetails.paymasterData.length <= 7, "Paymaster data includes more than 7 items.");
18759
+ async signDeployAccountTransaction(details) {
18760
+ const compiledConstructorCalldata = CallData.compile(details.constructorCalldata);
18761
+ const msgHash = calculateDeployAccountTransactionHash2({
18762
+ ...details,
18763
+ salt: details.addressSalt,
18764
+ compiledConstructorCalldata,
18765
+ version: details.version,
18766
+ nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
18767
+ feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
18768
+ });
18769
+ const ledgerResponse = await this.signDeployAccountV3(details);
18388
18770
  assert(
18389
- txDetails.accountDeploymentData.length <= 7,
18390
- "accountDeploymentData includes more than 7 items"
18391
- );
18392
- await this._transporter.send(Number("0x5a"), 3, 0, 0, buffer_default.from(this.pathBuffer));
18393
- const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
18394
- const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
18395
- const nonceBuf = this.convertBnToLedger(txDetails.nonce);
18396
- const dAModeHashBuf = this.convertBnToLedger(
18397
- hashDAMode(
18398
- intDAM(txDetails.nonceDataAvailabilityMode),
18399
- intDAM(txDetails.feeDataAvailabilityMode)
18400
- )
18401
- );
18402
- const dataBuf = concatenateArrayBuffer([
18403
- accountAddressBuf,
18404
- chainIdBuf,
18405
- nonceBuf,
18406
- dAModeHashBuf
18407
- ]);
18408
- await this._transporter.send(Number("0x5a"), 3, 1, 0, buffer_default.from(dataBuf));
18409
- if (isRPC08Plus_ResourceBoundsBN(txDetails.resourceBounds)) {
18410
- const tipBuf = this.convertBnToLedger(txDetails.tip);
18411
- const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
18412
- const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
18413
- const l1_data_gasBuf = this.convertBnToLedger(
18414
- encodeDataResourceBoundsL1(txDetails.resourceBounds)
18415
- );
18416
- const feeBuf = concatenateArrayBuffer([
18417
- tipBuf,
18418
- l1_gasBuf,
18419
- l2_gasBuf,
18420
- l1_data_gasBuf
18421
- ]);
18422
- await this._transporter.send(Number("0x5a"), 3, 2, 0, buffer_default.from(feeBuf));
18423
- }
18424
- const paymasterBuf = concatenateArrayBuffer(
18425
- txDetails.paymasterData.map((value) => {
18426
- const a = this.convertBnToLedger(value);
18427
- return a;
18428
- })
18429
- );
18430
- await this._transporter.send(Number("0x5a"), 3, 3, 0, buffer_default.from(paymasterBuf));
18431
- const accountDeployDataBuf = concatenateArrayBuffer(
18432
- txDetails.paymasterData.map((value) => {
18433
- const a = this.convertBnToLedger(value);
18434
- return a;
18435
- })
18771
+ toBigInt(msgHash) === ledgerResponse.hash,
18772
+ "The transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
18436
18773
  );
18437
- await this._transporter.send(Number("0x5a"), 3, 4, 0, buffer_default.from(accountDeployDataBuf));
18438
- const nbCallsBuf = this.convertBnToLedger(calls.length);
18439
- await this._transporter.send(Number("0x5a"), 3, 5, 0, buffer_default.from(nbCallsBuf));
18440
- let respSign = new Uint8Array(0);
18441
- for (const call of calls) {
18442
- const calldatas = this.encodeCall(call);
18443
- respSign = await this._transporter.send(Number("0x5a"), 3, 6, 0, buffer_default.from(calldatas[0]));
18444
- if (calldatas.length > 1) {
18445
- calldatas.slice(1).forEach(async (part) => {
18446
- respSign = await this._transporter.send(Number("0x5a"), 3, 6, 1, buffer_default.from(part));
18447
- });
18448
- }
18449
- }
18450
- return this.decodeSignatureLedger(respSign);
18774
+ return ledgerResponse.signature;
18451
18775
  }
18452
18776
  /**
18453
- *Ask the Ledger Nano to display and sign a Starknet V3 account deployment.
18454
- * @param {V3DeployAccountSignerDetails} deployAccountDetail All the details needed for a V3 deploy account.
18455
- * @returns an object including the transaction Hash and the signature
18456
- * @example
18457
- * ```typescript
18458
- * const deployData: V3DeployAccountSignerDetails =
18459
- * {
18460
- * tip: 0, paymasterData: [], accountDeploymentData: [],
18461
- * nonceDataAvailabilityMode: 'L1', feeDataAvailabilityMode: 'L1',
18462
- * resourceBounds: {
18463
- * l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' },
18464
- * l1_gas: { max_amount: '0x226', max_price_per_unit: '0x22ecb25c00' }
18465
- * },
18466
- * classHash: '0x540d7f5ec7ecf317e68d48564934cb99259781b1ee3cedbbc37ec5337f8e688',
18467
- * constructorCalldata: [
18468
- * '3571125127744830445572285574469842579401255431821644822726857471463672199621'
18469
- * ],
18470
- * contractAddress: '0x4ca062add1cf12a107be1107af17981cf6e544a24d987693230ea481d3d5e34',
18471
- * addressSalt: '0x07e52f68e3160e1ef698211cdf6d3792368fe347e7e2d4a8ace14d9b248f39c5',
18472
- * chainId: '0x534e5f5345504f4c4941',
18473
- * version: '0x3', nonce: 0n
18474
- *}
18475
- * const res = await myLedgerSigner.signDeployAccountV3(deployData);
18476
- * // res = {hash:
18477
- * // signature:
18478
- * // }
18479
- * ```
18777
+ * Internal function to convert a bigNumberish to an Uint8array of 256 bits
18778
+ * @param {BigNumberish} input input value
18779
+ * @returns {Uint8Array} a Uint8Array containing 32 bytes.
18480
18780
  */
18481
- async signDeployAccountV3(deployAccountDetail) {
18482
- await this._transporter.send(Number("0x5a"), 5, 0, 0, buffer_default.from(this.pathBuffer));
18483
- const accountAddressBuf = this.convertBnToLedger(
18484
- deployAccountDetail.contractAddress
18485
- );
18486
- const chainIdBuf = this.convertBnToLedger(deployAccountDetail.chainId);
18487
- const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
18488
- const dAModeHashBuf = this.convertBnToLedger(
18489
- hashDAMode(
18490
- intDAM(deployAccountDetail.nonceDataAvailabilityMode),
18491
- intDAM(deployAccountDetail.feeDataAvailabilityMode)
18492
- )
18493
- );
18494
- const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
18495
- const saltBuf = this.convertBnToLedger(deployAccountDetail.addressSalt);
18496
- const dataBuf = concatenateArrayBuffer([
18497
- accountAddressBuf,
18498
- chainIdBuf,
18499
- nonceBuf,
18500
- dAModeHashBuf,
18501
- classHashBuf,
18502
- saltBuf
18503
- ]);
18504
- await this._transporter.send(Number("0x5a"), 5, 1, 0, buffer_default.from(dataBuf));
18505
- if (isRPC08Plus_ResourceBoundsBN(deployAccountDetail.resourceBounds)) {
18506
- const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
18507
- const l1_gasBuf = this.convertBnToLedger(
18508
- encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
18509
- );
18510
- const l2_gasBuf = this.convertBnToLedger(
18511
- encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
18512
- );
18513
- const l1_data_gasBuf = this.convertBnToLedger(
18514
- encodeDataResourceBoundsL1(deployAccountDetail.resourceBounds)
18515
- );
18516
- const feeBuf = concatenateArrayBuffer([
18517
- tipBuf,
18518
- l1_gasBuf,
18519
- l2_gasBuf,
18520
- l1_data_gasBuf
18521
- ]);
18522
- await this._transporter.send(Number("0x5a"), 5, 2, 0, buffer_default.from(feeBuf));
18523
- }
18524
- const paymasterBuf = concatenateArrayBuffer(
18525
- deployAccountDetail.paymasterData.map((value) => {
18526
- const a = this.convertBnToLedger(value);
18527
- return a;
18528
- })
18529
- );
18530
- await this._transporter.send(Number("0x5a"), 5, 3, 0, buffer_default.from(paymasterBuf));
18531
- const compiledConstructor = CallData.compile(deployAccountDetail.constructorCalldata);
18532
- const constructorLengthBuf = this.convertBnToLedger(compiledConstructor.length);
18533
- await this._transporter.send(Number("0x5a"), 5, 4, 0, buffer_default.from(constructorLengthBuf));
18534
- const constructorBuf = concatenateArrayBuffer(
18535
- compiledConstructor.map((parameter) => {
18536
- const a = this.convertBnToLedger(parameter);
18537
- return a;
18538
- })
18539
- );
18540
- const constructorChunks = [];
18541
- const chunkSize = 7 * 32;
18542
- for (let i = 0; i < constructorBuf.length; i += chunkSize)
18543
- constructorChunks.push(constructorBuf.subarray(i, i + chunkSize));
18544
- let respSign = new Uint8Array(0);
18545
- for (const chunk of constructorChunks) {
18546
- respSign = await this._transporter.send(Number("0x5a"), 5, 5, 0, buffer_default.from(chunk));
18547
- }
18548
- return this.decodeSignatureLedger(respSign);
18781
+ convertBnToLedger(input) {
18782
+ return hexToBytes(addAddressPadding(toHex(input)));
18783
+ }
18784
+ /**
18785
+ * Internal function to decode the response of the Ledger signature
18786
+ * @param {Uint8Array} respSign the Buffer response of the Ledger
18787
+ * @returns { hash: bigint; signature: Signature } transaction hash & signature
18788
+ */
18789
+ decodeSignatureLedger(respSign) {
18790
+ const h = BigInt(addHexPrefix(buf2hex(respSign.subarray(0, 32))));
18791
+ const r = BigInt(addHexPrefix(buf2hex(respSign.subarray(33, 65))));
18792
+ const s = BigInt(addHexPrefix(buf2hex(respSign.subarray(65, 97))));
18793
+ const v = respSign[97];
18794
+ const sign0 = new starkCurve.Signature(r, s);
18795
+ const sign1 = sign0.addRecoveryBit(v);
18796
+ return { hash: h, signature: sign1 };
18549
18797
  }
18550
18798
  /** Internal function to convert a Call to an array of Uint8Array.
18551
18799
  * @param {Call} call A Call to convert.
@@ -18554,19 +18802,15 @@ var LedgerSigner231 = class extends LedgerSigner221 {
18554
18802
  encodeCall(call) {
18555
18803
  const toBuf = this.convertBnToLedger(call.contractAddress);
18556
18804
  const selectorBuf = hexToBytes(addAddressPadding(getSelector(call.entrypoint)));
18557
- let calldataBuf;
18805
+ let calldataBuf = new Uint8Array([]);
18558
18806
  if (call.calldata) {
18559
18807
  const compiledCalldata = CallData.compile(call.calldata);
18560
- const calldataSizeBuf = this.convertBnToLedger(compiledCalldata.length);
18561
- calldataBuf = concatenateArrayBuffer([
18562
- calldataSizeBuf,
18563
- ...compiledCalldata.map((parameter) => {
18808
+ calldataBuf = concatenateArrayBuffer(
18809
+ compiledCalldata.map((parameter) => {
18564
18810
  const a = this.convertBnToLedger(parameter);
18565
18811
  return a;
18566
18812
  })
18567
- ]);
18568
- } else {
18569
- calldataBuf = this.convertBnToLedger("0x00");
18813
+ );
18570
18814
  }
18571
18815
  const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
18572
18816
  const calldatas = [];
@@ -18575,522 +18819,472 @@ var LedgerSigner231 = class extends LedgerSigner221 {
18575
18819
  calldatas.push(callBuf.subarray(i, i + chunkSize));
18576
18820
  return calldatas;
18577
18821
  }
18578
- };
18579
-
18580
- // src/utils/outsideExecution.ts
18581
- var outsideExecution_exports = {};
18582
- __export(outsideExecution_exports, {
18583
- buildExecuteFromOutsideCall: () => buildExecuteFromOutsideCall,
18584
- buildExecuteFromOutsideCallData: () => buildExecuteFromOutsideCallData,
18585
- getOutsideCall: () => getOutsideCall,
18586
- getTypedData: () => getTypedData,
18587
- toOutsideCallV2: () => toOutsideCallV2
18588
- });
18589
- function toOutsideCallV2(call) {
18590
- if ("calldata_len" in call) {
18591
- return {
18592
- To: call.to,
18593
- Selector: call.selector,
18594
- Calldata: call.calldata
18595
- };
18596
- }
18597
- return call;
18598
- }
18599
- function getOutsideCall(call) {
18600
- const callData = call.calldata ?? [];
18601
- const callDataCompiled = Array.isArray(callData) ? callData : CallData.compile(callData);
18602
- return {
18603
- to: call.contractAddress,
18604
- selector: getSelectorFromName(call.entrypoint),
18605
- calldata: callDataCompiled
18606
- };
18607
- }
18608
- function callToTypedData(call, version) {
18609
- const outsideCall = getOutsideCall(call);
18610
- if (version === "1") {
18611
- return {
18612
- ...outsideCall,
18613
- calldata_len: outsideCall.calldata.length,
18614
- calldata: outsideCall.calldata
18615
- };
18616
- }
18617
- return {
18618
- To: outsideCall.to,
18619
- Selector: outsideCall.selector,
18620
- Calldata: outsideCall.calldata
18621
- };
18622
- }
18623
- function getDomain(chainId, version) {
18624
- return {
18625
- name: "Account.execute_from_outside",
18626
- version,
18627
- chainId,
18628
- ...version === "2" ? { revision: "1" } : {}
18629
- };
18630
- }
18631
- function getTypedData(chainId, options, nonce, myCalls, version) {
18632
- if (version === "1") {
18633
- return {
18634
- types: OutsideExecutionTypesV1,
18635
- primaryType: "OutsideExecution",
18636
- domain: getDomain(chainId, version),
18637
- message: {
18638
- ...options,
18639
- nonce,
18640
- calls_len: myCalls.length,
18641
- calls: myCalls.map((call) => callToTypedData(call, version))
18642
- }
18643
- };
18644
- }
18645
- return {
18646
- types: OutsideExecutionTypesV2,
18647
- primaryType: "OutsideExecution",
18648
- domain: getDomain(chainId, version),
18649
- message: {
18650
- Caller: options.caller,
18651
- Nonce: nonce,
18652
- "Execute After": options.execute_after,
18653
- "Execute Before": options.execute_before,
18654
- Calls: myCalls.map((call) => callToTypedData(call, version))
18655
- }
18656
- };
18657
- }
18658
- function buildExecuteFromOutsideCallData(outsideTransaction) {
18659
- const execution2 = outsideTransaction.outsideExecution;
18660
- const formattedSignature = formatSignature(outsideTransaction.signature);
18661
- return CallData.compile({
18662
- outside_execution: execution2,
18663
- signature: formattedSignature
18664
- });
18665
- }
18666
- function buildExecuteFromOutsideCall(outsideTransaction) {
18667
- const myOutsideTransactions = Array.isArray(outsideTransaction) ? outsideTransaction : [outsideTransaction];
18668
- const multiCall = myOutsideTransactions.map((outsideTx) => {
18669
- let entrypoint;
18670
- if (outsideTx.version === OutsideExecutionVersion.V1) {
18671
- entrypoint = "execute_from_outside";
18672
- } else if (outsideTx.version === OutsideExecutionVersion.V2) {
18673
- entrypoint = "execute_from_outside_v2";
18674
- } else {
18675
- throw new Error("Unsupported OutsideExecution version");
18676
- }
18677
- return {
18678
- contractAddress: toHex(outsideTx.signerAddress),
18679
- entrypoint,
18680
- calldata: buildExecuteFromOutsideCallData(outsideTx)
18681
- };
18682
- });
18683
- return multiCall;
18684
- }
18685
-
18686
- // src/utils/src5.ts
18687
- var src5_exports = {};
18688
- __export(src5_exports, {
18689
- supportsInterface: () => supportsInterface
18690
- });
18691
- async function supportsInterface(provider, contractAddress, interfaceId) {
18692
- const call = {
18693
- contractAddress: toHex(contractAddress),
18694
- entrypoint: "supports_interface",
18695
- calldata: [toHex(interfaceId)]
18696
- };
18697
- try {
18698
- const resp = await provider.callContract(call);
18699
- return BigInt(resp[0]) !== 0n;
18700
- } catch {
18701
- return false;
18702
- }
18703
- }
18704
-
18705
- // src/utils/paymaster.ts
18706
- var paymaster_exports = {};
18707
- __export(paymaster_exports, {
18708
- assertCallsAreStrictlyEqual: () => assertCallsAreStrictlyEqual,
18709
- assertPaymasterTransactionSafety: () => assertPaymasterTransactionSafety,
18710
- getDefaultPaymasterNodeUrl: () => getDefaultPaymasterNodeUrl
18711
- });
18712
- var getDefaultPaymasterNodeUrl = (networkName, mute = false) => {
18713
- if (!mute) {
18714
- logger.info("Using default public node url, please provide nodeUrl in provider options!");
18715
- }
18716
- const nodes = PAYMASTER_RPC_NODES[networkName ?? _NetworkName.SN_SEPOLIA];
18717
- const randIdx = Math.floor(Math.random() * nodes.length);
18718
- return nodes[randIdx];
18719
- };
18720
- var assertGasFeeFromUnsafeCalls = (unsafeCalls, fees) => {
18721
- const unsafeCall = toOutsideCallV2(unsafeCalls[unsafeCalls.length - 1]);
18722
- const unsafeGasTokenCalldata = CallData.toCalldata(unsafeCall.Calldata);
18723
- const unsafeGasTokenValue = uint256ToBN({
18724
- low: unsafeGasTokenCalldata[1],
18725
- high: unsafeGasTokenCalldata[2]
18726
- });
18727
- assert(
18728
- unsafeGasTokenValue === BigInt(fees),
18729
- "Gas token value is not equal to the provided gas fees"
18730
- );
18731
- };
18732
- var assertGasTokenFromUnsafeCalls = (unsafeCalls, gasToken) => {
18733
- const unsafeCall = toOutsideCallV2(unsafeCalls[unsafeCalls.length - 1]);
18734
- assert(
18735
- BigInt(unsafeCall.To) === BigInt(gasToken),
18736
- "Gas token address is not equal to the provided gas token"
18737
- );
18738
- assert(
18739
- unsafeCall.Selector === getSelectorFromName("transfer"),
18740
- "Gas token call selector is not a transfer"
18741
- );
18742
- assert(
18743
- CallData.toCalldata(unsafeCall.Calldata).length === 3,
18744
- "Gas token transfer calldata does not match the expected recipient/amount shape"
18745
- );
18746
- };
18747
- function assertCallsAreStrictlyEqual(originalCalls, unsafeCalls, isSponsored = false) {
18748
- const baseError = "Provided calls are not strictly equal to the returned calls";
18749
- const expectedExtraCalls = isSponsored ? 0 : 1;
18750
- assert(
18751
- unsafeCalls.length - expectedExtraCalls === originalCalls.length,
18752
- `${baseError}: Expected ${originalCalls.length + expectedExtraCalls} calls, got ${unsafeCalls.length}`
18753
- );
18754
- for (let callIndex = 0; callIndex < originalCalls.length; callIndex += 1) {
18755
- const originalCall = originalCalls[callIndex];
18756
- const unsafeCall = toOutsideCallV2(unsafeCalls[callIndex]);
18757
- const normalizeAddress = (address) => {
18758
- return toBigInt(address).toString(16).toLowerCase();
18759
- };
18760
- const originalAddress = normalizeAddress(originalCall.contractAddress);
18761
- const unsafeAddress = normalizeAddress(unsafeCall.To);
18822
+ /**
18823
+ * Ask to the Ledger Nano to display and sign a Starknet V3 transaction.
18824
+ * @param {V3InvocationsSignerDetails} txDetails All the details needed for a txV3.
18825
+ * @param {Call[]} calls array of Starknet invocations
18826
+ * @returns an object including the transaction Hash and the signature
18827
+ * @example
18828
+ * ```typescript
18829
+ * const calls: Call[] = [{contractAddress: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
18830
+ * entrypoint: "transfer",
18831
+ * calldata:["0x11f5fc2a92ac03434a7937fe982f5e5293b65ad438a989c5b78fb8f04a12016",
18832
+ * "0x9184e72a000", "0x0"]}];
18833
+ * const txDetailsV3: V3InvocationsSignerDetails = {
18834
+ * chainId: constants.StarknetChainId.SN_MAIN,
18835
+ * nonce: "28", accountDeploymentData: [],
18836
+ * paymasterData: [], cairoVersion: "1",
18837
+ * feeDataAvailabilityMode: "L1", nonceDataAvailabilityMode: "L1",
18838
+ * resourceBounds: {
18839
+ * l1_gas: { max_amount: "0x2a00", max_price_per_unit: "0x5c00000"
18840
+ * },
18841
+ * l2_gas: { max_amount: "0x00", max_price_per_unit: "0x00"},
18842
+ * }, tip: 0, version: "0x3", walletAddress: account0.address
18843
+ * };
18844
+ * const res = await myLedgerSigner.signTxV3(txDetailsV3, calls);
18845
+ * // res = {hash:
18846
+ * // signature:
18847
+ * // }
18848
+ * ```
18849
+ */
18850
+ async signTxV3(txDetails, calls) {
18851
+ assert(txDetails.paymasterData.length <= 7, "Paymaster data includes more than 7 items.");
18762
18852
  assert(
18763
- originalAddress === unsafeAddress,
18764
- `${baseError}: Contract address mismatch at call ${callIndex}. Expected: ${originalCall.contractAddress}, Got: ${unsafeCall.To}`
18853
+ txDetails.accountDeploymentData.length <= 7,
18854
+ "accountDeploymentData includes more than 7 items"
18855
+ );
18856
+ await this._transporter.send(Number("0x5a"), 3, 0, 0, buffer_default.from(this.pathBuffer));
18857
+ const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
18858
+ const tipBuf = this.convertBnToLedger(txDetails.tip);
18859
+ const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
18860
+ const nonceBuf = this.convertBnToLedger(txDetails.nonce);
18861
+ const dAModeHashBuf = this.convertBnToLedger(
18862
+ hashDAMode(
18863
+ txDetails.nonceDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2,
18864
+ txDetails.feeDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2
18865
+ )
18866
+ );
18867
+ const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
18868
+ const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
18869
+ const dataBuf = concatenateArrayBuffer([
18870
+ accountAddressBuf,
18871
+ tipBuf,
18872
+ l1_gasBuf,
18873
+ l2_gasBuf,
18874
+ chainIdBuf,
18875
+ nonceBuf,
18876
+ dAModeHashBuf
18877
+ ]);
18878
+ await this._transporter.send(Number("0x5a"), 3, 1, 0, buffer_default.from(dataBuf));
18879
+ const paymasterBuf = concatenateArrayBuffer(
18880
+ txDetails.paymasterData.map((value) => {
18881
+ const a = this.convertBnToLedger(value);
18882
+ return a;
18883
+ })
18884
+ );
18885
+ await this._transporter.send(Number("0x5a"), 3, 2, 0, buffer_default.from(paymasterBuf));
18886
+ const accountDeployDataBuf = concatenateArrayBuffer(
18887
+ txDetails.paymasterData.map((value) => {
18888
+ const a = this.convertBnToLedger(value);
18889
+ return a;
18890
+ })
18891
+ );
18892
+ await this._transporter.send(Number("0x5a"), 3, 3, 0, buffer_default.from(accountDeployDataBuf));
18893
+ const nbCallsBuf = this.convertBnToLedger(calls.length);
18894
+ await this._transporter.send(Number("0x5a"), 3, 4, 0, buffer_default.from(nbCallsBuf));
18895
+ let respSign = new Uint8Array(0);
18896
+ for (const call of calls) {
18897
+ const calldatas = this.encodeCall(call);
18898
+ await this._transporter.send(Number("0x5a"), 3, 5, 0, buffer_default.from(calldatas[0]));
18899
+ if (calldatas.length > 1) {
18900
+ calldatas.slice(1).forEach(async (part) => {
18901
+ await this._transporter.send(Number("0x5a"), 3, 5, 1, buffer_default.from(part));
18902
+ });
18903
+ }
18904
+ respSign = await this._transporter.send(Number("0x5a"), 3, 5, 2);
18905
+ }
18906
+ return this.decodeSignatureLedger(respSign);
18907
+ }
18908
+ /**
18909
+ *Ask the Ledger Nano to display and sign a Starknet V3 account deployment.
18910
+ * @param {V3DeployAccountSignerDetails} deployAccountDetail All the details needed for a V3 deploy account.
18911
+ * @returns an object including the transaction Hash and the signature
18912
+ * @example
18913
+ * ```typescript
18914
+ * const deployData: V3DeployAccountSignerDetails =
18915
+ * {
18916
+ * tip: 0, paymasterData: [], accountDeploymentData: [],
18917
+ * nonceDataAvailabilityMode: 'L1', feeDataAvailabilityMode: 'L1',
18918
+ * resourceBounds: {
18919
+ * l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' },
18920
+ * l1_gas: { max_amount: '0x226', max_price_per_unit: '0x22ecb25c00' }
18921
+ * },
18922
+ * classHash: '0x540d7f5ec7ecf317e68d48564934cb99259781b1ee3cedbbc37ec5337f8e688',
18923
+ * constructorCalldata: [
18924
+ * '3571125127744830445572285574469842579401255431821644822726857471463672199621'
18925
+ * ],
18926
+ * contractAddress: '0x4ca062add1cf12a107be1107af17981cf6e544a24d987693230ea481d3d5e34',
18927
+ * addressSalt: '0x07e52f68e3160e1ef698211cdf6d3792368fe347e7e2d4a8ace14d9b248f39c5',
18928
+ * chainId: '0x534e5f5345504f4c4941',
18929
+ * version: '0x3', nonce: 0n
18930
+ *}
18931
+ * const res = await myLedgerSigner.signDeployAccountV3(deployData);
18932
+ * // res = {hash:
18933
+ * // signature:
18934
+ * // }
18935
+ * ```
18936
+ */
18937
+ async signDeployAccountV3(deployAccountDetail) {
18938
+ await this._transporter.send(Number("0x5a"), 5, 0, 0, buffer_default.from(this.pathBuffer));
18939
+ const accountAddressBuf = this.convertBnToLedger(
18940
+ deployAccountDetail.contractAddress
18765
18941
  );
18766
- assert(
18767
- getSelectorFromName(originalCall.entrypoint) === unsafeCall.Selector,
18768
- `${baseError}: Entrypoint mismatch at call ${callIndex}. Expected: ${originalCall.entrypoint}, Got: ${unsafeCall.Selector}`
18942
+ const chainIdBuf = this.convertBnToLedger(deployAccountDetail.chainId);
18943
+ const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
18944
+ const dAModeHashBuf = this.convertBnToLedger(
18945
+ hashDAMode(
18946
+ deployAccountDetail.nonceDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2,
18947
+ deployAccountDetail.feeDataAvailabilityMode === api_exports.EDataAvailabilityMode.L1 ? api_exports.EDAMode.L1 : api_exports.EDAMode.L2
18948
+ )
18769
18949
  );
18770
- const originalCalldata = CallData.toCalldata(originalCall.calldata);
18771
- const unsafeCalldata = CallData.toCalldata(unsafeCall.Calldata);
18772
- assert(
18773
- originalCalldata.length === unsafeCalldata.length,
18774
- `${baseError}: Calldata length mismatch at call ${callIndex}. Expected length: ${originalCalldata.length}, Got length: ${unsafeCalldata.length}`
18950
+ const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
18951
+ const saltBuf = this.convertBnToLedger(deployAccountDetail.addressSalt);
18952
+ const dataBuf = concatenateArrayBuffer([
18953
+ accountAddressBuf,
18954
+ chainIdBuf,
18955
+ nonceBuf,
18956
+ dAModeHashBuf,
18957
+ classHashBuf,
18958
+ saltBuf
18959
+ ]);
18960
+ await this._transporter.send(Number("0x5a"), 5, 1, 0, buffer_default.from(dataBuf));
18961
+ const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
18962
+ const l1_gasBuf = this.convertBnToLedger(
18963
+ encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
18775
18964
  );
18776
- for (let dataIndex = 0; dataIndex < originalCalldata.length; dataIndex += 1) {
18777
- const originalValue = BigInt(originalCalldata[dataIndex]);
18778
- const unsafeValue = BigInt(unsafeCalldata[dataIndex]);
18779
- assert(
18780
- originalValue === unsafeValue,
18781
- `${baseError}: Calldata value mismatch at call ${callIndex}, parameter ${dataIndex}. Expected: ${originalCalldata[dataIndex]}, Got: ${unsafeCalldata[dataIndex]}`
18782
- );
18965
+ const l2_gasBuf = this.convertBnToLedger(
18966
+ encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
18967
+ );
18968
+ const feeBuf = concatenateArrayBuffer([tipBuf, l1_gasBuf, l2_gasBuf]);
18969
+ await this._transporter.send(Number("0x5a"), 5, 2, 0, buffer_default.from(feeBuf));
18970
+ const paymasterBuf = concatenateArrayBuffer(
18971
+ deployAccountDetail.paymasterData.map((value) => {
18972
+ const a = this.convertBnToLedger(value);
18973
+ return a;
18974
+ })
18975
+ );
18976
+ await this._transporter.send(Number("0x5a"), 5, 3, 0, buffer_default.from(paymasterBuf));
18977
+ const compiledConstructor = CallData.compile(deployAccountDetail.constructorCalldata);
18978
+ const constructorLengthBuf = this.convertBnToLedger(compiledConstructor.length);
18979
+ await this._transporter.send(Number("0x5a"), 5, 4, 0, buffer_default.from(constructorLengthBuf));
18980
+ const constructorBuf = concatenateArrayBuffer(
18981
+ compiledConstructor.map((parameter) => {
18982
+ const a = this.convertBnToLedger(parameter);
18983
+ return a;
18984
+ })
18985
+ );
18986
+ const constructorChunks = [];
18987
+ const chunkSize = 7 * 32;
18988
+ for (let i = 0; i < constructorBuf.length; i += chunkSize)
18989
+ constructorChunks.push(constructorBuf.subarray(i, i + chunkSize));
18990
+ let respSign = new Uint8Array(0);
18991
+ for (const chunk of constructorChunks) {
18992
+ respSign = await this._transporter.send(Number("0x5a"), 5, 5, 0, buffer_default.from(chunk));
18783
18993
  }
18994
+ return this.decodeSignatureLedger(respSign);
18784
18995
  }
18996
+ };
18997
+ function getLedgerPathBuffer221(accountId, applicationName = "LedgerW") {
18998
+ const path0buff = new Uint8Array([HARDENING_BYTE, 0, 10, 85]);
18999
+ const path1buff = new Uint8Array([71 | HARDENING_BYTE, 65, 233, 201]);
19000
+ const path2Base = applicationName === "LedgerW" ? new Uint8Array([43, 206, 231, 219]) : stringToSha256ToArrayBuff4(applicationName);
19001
+ const path2buff = concatenateArrayBuffer([
19002
+ new Uint8Array([path2Base[0] | HARDENING_BYTE]),
19003
+ path2Base.subarray(1)
19004
+ ]);
19005
+ const path3buff = new Uint8Array([HARDENING_BYTE, 0, 0, 0]);
19006
+ const hex = toHex(BigInt(accountId) | HARDENING_4BYTES);
19007
+ const padded = addHexPrefix(removeHexPrefix(hex).padStart(8, "0"));
19008
+ const path4buff = hexToBytes(padded);
19009
+ const path5buff = new Uint8Array([0, 0, 0, 0]);
19010
+ const pathBuff = concatenateArrayBuffer([
19011
+ path0buff,
19012
+ path1buff,
19013
+ path2buff,
19014
+ path3buff,
19015
+ path4buff,
19016
+ path5buff
19017
+ ]);
19018
+ return pathBuff;
18785
19019
  }
18786
- var domainFieldToFelt = (value) => {
18787
- try {
18788
- return toBigInt(value);
18789
- } catch {
18790
- return CairoBytes31.fromText(String(value)).toBigInt();
19020
+
19021
+ // src/signer/ledgerSigner231.ts
19022
+ var LedgerSigner231 = class extends LedgerSigner221 {
19023
+ /**
19024
+ * constructor of the LedgerSigner class.
19025
+ * @param {Transport} transport 5 transports are available to handle USB, bluetooth, Node, Web, Mobile.
19026
+ * See Guides for more details.
19027
+ * @param {number} accountID ID of Ledger Nano account (can handle 2**31 accounts).
19028
+ * @param {string} [eip2645application='LedgerW'] A wallet is defined by an ERC2645 derivation path (6 items).
19029
+ * One item is called `application` and can be customized.
19030
+ * Default value is `LedgerW`.
19031
+ * @param {LedgerPathCalculation} [pathFunction=getLedgerPathBuffer221]
19032
+ * defines the function that will calculate the path. By default `getLedgerPathBuffer221` is selected.
19033
+ *
19034
+ * If you are using APP v2.3.1 with an account created with the v1.1.1, you need to use :
19035
+ * ```typescript
19036
+ * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0, undefined, getLedgerPathBuffer111);
19037
+ * ```
19038
+ * @example
19039
+ * ```typescript
19040
+ * import TransportNodeHid from "@ledgerhq/hw-transport-node-hid";
19041
+ * const myNodeTransport = await TransportNodeHid.create();
19042
+ * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0);
19043
+ * ```
19044
+ */
19045
+ constructor(transport, accountID, eip2645application = "LedgerW", pathFunction = getLedgerPathBuffer221) {
19046
+ super(transport, accountID, eip2645application, pathFunction);
18791
19047
  }
18792
- };
18793
- var assertChainIdFromTypedData = (typedData, chainId) => {
18794
- assert(
18795
- typedData.domain.chainId !== void 0 && domainFieldToFelt(typedData.domain.chainId) === BigInt(chainId),
18796
- "Paymaster typed data domain chainId does not match the account's provider chain"
18797
- );
18798
- };
18799
- var assertPaymasterTransactionSafety = (preparedTransaction, calls, paymasterDetails, chainId, maxFeeInGasToken) => {
18800
- if (preparedTransaction.type === "invoke" || preparedTransaction.type === "deploy_and_invoke") {
18801
- assertChainIdFromTypedData(preparedTransaction.typed_data, chainId);
18802
- const { message } = preparedTransaction.typed_data;
18803
- const hasV1Calls = "calls" in message;
18804
- const hasV2Calls = "Calls" in message;
19048
+ /**
19049
+ * Ask to the Ledger Nano to display and sign a Starknet V3 transaction.
19050
+ * @param {V3InvocationsSignerDetails} txDetails All the details needed for a txV3.
19051
+ * @param {Call[]} calls array of Starknet invocations
19052
+ * @returns an object including the transaction Hash and the signature
19053
+ * @example
19054
+ * ```typescript
19055
+ * const calls: Call[] = [{contractAddress: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
19056
+ * entrypoint: "transfer",
19057
+ * calldata:["0x11f5fc2a92ac03434a7937fe982f5e5293b65ad438a989c5b78fb8f04a12016",
19058
+ * "0x9184e72a000", "0x0"]}];
19059
+ * const txDetailsV3: V3InvocationsSignerDetails = {
19060
+ * chainId: constants.StarknetChainId.SN_MAIN,
19061
+ * nonce: "28", accountDeploymentData: [],
19062
+ * paymasterData: [], cairoVersion: "1",
19063
+ * feeDataAvailabilityMode: "L1", nonceDataAvailabilityMode: "L1",
19064
+ * resourceBounds: {
19065
+ * l1_gas: { max_amount: "0x2a00", max_price_per_unit: "0x5c00000"
19066
+ * },
19067
+ * l2_gas: { max_amount: "0x00", max_price_per_unit: "0x00"},
19068
+ * }, tip: 0, version: "0x3", walletAddress: account0.address
19069
+ * };
19070
+ * const res = await myLedgerSigner.signTxV3(txDetailsV3, calls);
19071
+ * // res = {hash:
19072
+ * // signature:
19073
+ * // }
19074
+ * ```
19075
+ */
19076
+ async signTxV3(txDetails, calls) {
19077
+ assert(txDetails.paymasterData.length <= 7, "Paymaster data includes more than 7 items.");
18805
19078
  assert(
18806
- hasV1Calls !== hasV2Calls,
18807
- 'Paymaster typed data must declare exactly one of "calls" (SNIP-9 V1) or "Calls" (SNIP-9 V2)'
19079
+ txDetails.accountDeploymentData.length <= 7,
19080
+ "accountDeploymentData includes more than 7 items"
18808
19081
  );
18809
- const unsafeCalls = hasV1Calls ? message.calls : message.Calls;
18810
- assertCallsAreStrictlyEqual(calls, unsafeCalls, paymasterDetails.feeMode.mode === "sponsored");
18811
- if (paymasterDetails.feeMode.mode !== "sponsored") {
18812
- assertGasTokenFromUnsafeCalls(unsafeCalls, paymasterDetails.feeMode.gasToken);
18813
- assertGasFeeFromUnsafeCalls(
18814
- unsafeCalls,
18815
- preparedTransaction.fee.suggested_max_fee_in_gas_token
18816
- );
18817
- if (maxFeeInGasToken) {
18818
- assert(
18819
- preparedTransaction.fee.suggested_max_fee_in_gas_token <= maxFeeInGasToken,
18820
- "Gas token price is too high"
18821
- );
18822
- }
18823
- }
18824
- const msg = message;
18825
- const version = hasV1Calls ? OutsideExecutionVersion.V1 : OutsideExecutionVersion.V2;
18826
- const [callerKey, nonceKey, afterKey, beforeKey] = hasV1Calls ? ["caller", "nonce", "execute_after", "execute_before"] : ["Caller", "Nonce", "Execute After", "Execute Before"];
18827
- assert(
18828
- [callerKey, nonceKey, afterKey, beforeKey].every((key) => msg[key] !== void 0),
18829
- "Paymaster typed data does not match the expected outside execution"
19082
+ await this._transporter.send(Number("0x5a"), 3, 0, 0, buffer_default.from(this.pathBuffer));
19083
+ const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
19084
+ const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
19085
+ const nonceBuf = this.convertBnToLedger(txDetails.nonce);
19086
+ const dAModeHashBuf = this.convertBnToLedger(
19087
+ hashDAMode(
19088
+ intDAM(txDetails.nonceDataAvailabilityMode),
19089
+ intDAM(txDetails.feeDataAvailabilityMode)
19090
+ )
18830
19091
  );
18831
- const caller = msg[callerKey];
18832
- const nonce = msg[nonceKey];
18833
- const executeAfter = msg[afterKey];
18834
- const executeBefore = msg[beforeKey];
18835
- if (paymasterDetails.timeBounds) {
18836
- const requestedAfter = toBigInt(paymasterDetails.timeBounds.executeAfter ?? 1);
18837
- const requestedBefore = toBigInt(paymasterDetails.timeBounds.executeBefore);
18838
- assert(
18839
- toBigInt(executeAfter) >= requestedAfter && toBigInt(executeBefore) <= requestedBefore,
18840
- "Paymaster typed data execution window is not within the requested time bounds"
19092
+ const dataBuf = concatenateArrayBuffer([
19093
+ accountAddressBuf,
19094
+ chainIdBuf,
19095
+ nonceBuf,
19096
+ dAModeHashBuf
19097
+ ]);
19098
+ await this._transporter.send(Number("0x5a"), 3, 1, 0, buffer_default.from(dataBuf));
19099
+ if (isRPC08Plus_ResourceBoundsBN(txDetails.resourceBounds)) {
19100
+ const tipBuf = this.convertBnToLedger(txDetails.tip);
19101
+ const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
19102
+ const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
19103
+ const l1_data_gasBuf = this.convertBnToLedger(
19104
+ encodeDataResourceBoundsL1(txDetails.resourceBounds)
18841
19105
  );
19106
+ const feeBuf = concatenateArrayBuffer([
19107
+ tipBuf,
19108
+ l1_gasBuf,
19109
+ l2_gasBuf,
19110
+ l1_data_gasBuf
19111
+ ]);
19112
+ await this._transporter.send(Number("0x5a"), 3, 2, 0, buffer_default.from(feeBuf));
18842
19113
  }
18843
- const expectedCalls = [...calls];
18844
- if (paymasterDetails.feeMode.mode !== "sponsored") {
18845
- const feeCall = toOutsideCallV2(unsafeCalls[unsafeCalls.length - 1]);
18846
- const feeRecipient = CallData.toCalldata(feeCall.Calldata)[0];
18847
- const feeAmount = bnToUint256(preparedTransaction.fee.suggested_max_fee_in_gas_token);
18848
- expectedCalls.push({
18849
- contractAddress: paymasterDetails.feeMode.gasToken,
18850
- entrypoint: "transfer",
18851
- calldata: [feeRecipient, feeAmount.low, feeAmount.high]
18852
- });
18853
- }
18854
- const expectedTypedData = getTypedData(
18855
- chainId,
18856
- { caller, execute_after: executeAfter, execute_before: executeBefore },
18857
- nonce,
18858
- expectedCalls,
18859
- version
19114
+ const paymasterBuf = concatenateArrayBuffer(
19115
+ txDetails.paymasterData.map((value) => {
19116
+ const a = this.convertBnToLedger(value);
19117
+ return a;
19118
+ })
18860
19119
  );
18861
- assert(
18862
- getMessageHash(expectedTypedData, 0) === getMessageHash(preparedTransaction.typed_data, 0),
18863
- "Paymaster typed data does not match the expected outside execution"
19120
+ await this._transporter.send(Number("0x5a"), 3, 3, 0, buffer_default.from(paymasterBuf));
19121
+ const accountDeployDataBuf = concatenateArrayBuffer(
19122
+ txDetails.paymasterData.map((value) => {
19123
+ const a = this.convertBnToLedger(value);
19124
+ return a;
19125
+ })
18864
19126
  );
18865
- }
18866
- };
18867
-
18868
- // src/paymaster/rpc.ts
18869
- var convertCalls = (calls) => calls.map((call) => ({
18870
- to: call.contractAddress,
18871
- selector: getSelectorFromName(call.entrypoint),
18872
- calldata: CallData.toHex(call.calldata)
18873
- }));
18874
- var convertFeeMode = (feeMode) => {
18875
- if (feeMode.mode === "sponsored") {
18876
- return { mode: "sponsored" };
18877
- }
18878
- return { mode: "default", gas_token: feeMode.gasToken };
18879
- };
18880
- var convertFEE_MODE = (feeMode) => {
18881
- if (feeMode.mode === "sponsored") {
18882
- return { mode: "sponsored" };
18883
- }
18884
- return { mode: "default", gasToken: feeMode.gas_token };
18885
- };
18886
- var convertTimeBounds = (timeBounds) => timeBounds ? {
18887
- execute_after: timeBounds.executeAfter || 1,
18888
- // If executeAfter is not provided, set it to 1, meaning the transaction can be executed immediately
18889
- execute_before: timeBounds.executeBefore
18890
- } : void 0;
18891
- var convertTIME_BOUNDS = (timeBounds) => timeBounds ? {
18892
- executeAfter: timeBounds.execute_after,
18893
- executeBefore: timeBounds.execute_before
18894
- } : void 0;
18895
- var convertEXECUTION_PARAMETERS = (parameters) => ({
18896
- version: parameters.version,
18897
- feeMode: convertFEE_MODE(parameters.fee_mode),
18898
- timeBounds: convertTIME_BOUNDS(parameters.time_bounds)
18899
- });
18900
- var defaultOptions = {
18901
- headers: { "Content-Type": "application/json" }
18902
- };
18903
- var PaymasterRpc = class _PaymasterRpc {
18904
- nodeUrl;
18905
- headers;
18906
- baseFetch;
18907
- requestId;
18908
- constructor(options) {
18909
- if (options instanceof _PaymasterRpc) {
18910
- this.nodeUrl = options.nodeUrl;
18911
- this.headers = { ...defaultOptions.headers, ...options.headers };
18912
- this.baseFetch = options.baseFetch;
18913
- this.requestId = options.requestId;
18914
- return;
18915
- }
18916
- if (options && "nodeUrl" in options && "headers" in options && "baseFetch" in options) {
18917
- this.nodeUrl = options.nodeUrl ?? getDefaultPaymasterNodeUrl(void 0);
18918
- this.headers = { ...defaultOptions.headers, ...options.headers };
18919
- this.baseFetch = options.baseFetch ?? fetch_default;
18920
- this.requestId = 0;
18921
- return;
18922
- }
18923
- const { nodeUrl, headers, baseFetch } = options || {};
18924
- if (nodeUrl && Object.values(_NetworkName).includes(nodeUrl)) {
18925
- this.nodeUrl = getDefaultPaymasterNodeUrl(nodeUrl, options?.mute);
18926
- } else if (nodeUrl) {
18927
- this.nodeUrl = nodeUrl;
18928
- } else {
18929
- this.nodeUrl = getDefaultPaymasterNodeUrl(void 0, options?.mute);
18930
- }
18931
- this.baseFetch = baseFetch ?? fetch_default;
18932
- this.headers = { ...defaultOptions.headers, ...headers };
18933
- this.requestId = 0;
18934
- }
18935
- fetch(method, params, id = 0) {
18936
- const rpcRequestBody = {
18937
- id,
18938
- jsonrpc: "2.0",
18939
- method,
18940
- ...params && { params }
18941
- };
18942
- return this.baseFetch(this.nodeUrl, {
18943
- method: "POST",
18944
- body: stringify2(rpcRequestBody),
18945
- headers: this.headers
18946
- });
18947
- }
18948
- errorHandler(method, params, rpcError, otherError) {
18949
- if (rpcError) {
18950
- throw new RpcError(rpcError, method, params);
18951
- }
18952
- if (otherError instanceof LibraryError) {
18953
- throw otherError;
18954
- }
18955
- if (otherError) {
18956
- throw Error(otherError.message);
18957
- }
18958
- }
18959
- async fetchEndpoint(method, params) {
18960
- try {
18961
- this.requestId += 1;
18962
- const rawResult = await this.fetch(method, params, this.requestId);
18963
- const { error, result } = await rawResult.json();
18964
- this.errorHandler(method, params, error);
18965
- return result;
18966
- } catch (error) {
18967
- this.errorHandler(method, params, error?.response?.data, error);
18968
- throw error;
19127
+ await this._transporter.send(Number("0x5a"), 3, 4, 0, buffer_default.from(accountDeployDataBuf));
19128
+ const nbCallsBuf = this.convertBnToLedger(calls.length);
19129
+ await this._transporter.send(Number("0x5a"), 3, 5, 0, buffer_default.from(nbCallsBuf));
19130
+ let respSign = new Uint8Array(0);
19131
+ for (const call of calls) {
19132
+ const calldatas = this.encodeCall(call);
19133
+ respSign = await this._transporter.send(Number("0x5a"), 3, 6, 0, buffer_default.from(calldatas[0]));
19134
+ if (calldatas.length > 1) {
19135
+ calldatas.slice(1).forEach(async (part) => {
19136
+ respSign = await this._transporter.send(Number("0x5a"), 3, 6, 1, buffer_default.from(part));
19137
+ });
19138
+ }
18969
19139
  }
19140
+ return this.decodeSignatureLedger(respSign);
18970
19141
  }
18971
- async isAvailable() {
18972
- return this.fetchEndpoint("paymaster_isAvailable");
18973
- }
18974
- async buildTransaction(transaction, parameters) {
18975
- let userTransaction;
18976
- switch (transaction.type) {
18977
- case "invoke":
18978
- userTransaction = {
18979
- ...transaction,
18980
- invoke: {
18981
- user_address: transaction.invoke.userAddress,
18982
- calls: convertCalls(transaction.invoke.calls)
18983
- }
18984
- };
18985
- break;
18986
- case "deploy_and_invoke":
18987
- userTransaction = {
18988
- ...transaction,
18989
- invoke: {
18990
- user_address: transaction.invoke.userAddress,
18991
- calls: convertCalls(transaction.invoke.calls)
18992
- }
18993
- };
18994
- break;
18995
- case "deploy":
18996
- default:
18997
- userTransaction = transaction;
18998
- break;
19142
+ /**
19143
+ *Ask the Ledger Nano to display and sign a Starknet V3 account deployment.
19144
+ * @param {V3DeployAccountSignerDetails} deployAccountDetail All the details needed for a V3 deploy account.
19145
+ * @returns an object including the transaction Hash and the signature
19146
+ * @example
19147
+ * ```typescript
19148
+ * const deployData: V3DeployAccountSignerDetails =
19149
+ * {
19150
+ * tip: 0, paymasterData: [], accountDeploymentData: [],
19151
+ * nonceDataAvailabilityMode: 'L1', feeDataAvailabilityMode: 'L1',
19152
+ * resourceBounds: {
19153
+ * l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' },
19154
+ * l1_gas: { max_amount: '0x226', max_price_per_unit: '0x22ecb25c00' }
19155
+ * },
19156
+ * classHash: '0x540d7f5ec7ecf317e68d48564934cb99259781b1ee3cedbbc37ec5337f8e688',
19157
+ * constructorCalldata: [
19158
+ * '3571125127744830445572285574469842579401255431821644822726857471463672199621'
19159
+ * ],
19160
+ * contractAddress: '0x4ca062add1cf12a107be1107af17981cf6e544a24d987693230ea481d3d5e34',
19161
+ * addressSalt: '0x07e52f68e3160e1ef698211cdf6d3792368fe347e7e2d4a8ace14d9b248f39c5',
19162
+ * chainId: '0x534e5f5345504f4c4941',
19163
+ * version: '0x3', nonce: 0n
19164
+ *}
19165
+ * const res = await myLedgerSigner.signDeployAccountV3(deployData);
19166
+ * // res = {hash:
19167
+ * // signature:
19168
+ * // }
19169
+ * ```
19170
+ */
19171
+ async signDeployAccountV3(deployAccountDetail) {
19172
+ await this._transporter.send(Number("0x5a"), 5, 0, 0, buffer_default.from(this.pathBuffer));
19173
+ const accountAddressBuf = this.convertBnToLedger(
19174
+ deployAccountDetail.contractAddress
19175
+ );
19176
+ const chainIdBuf = this.convertBnToLedger(deployAccountDetail.chainId);
19177
+ const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
19178
+ const dAModeHashBuf = this.convertBnToLedger(
19179
+ hashDAMode(
19180
+ intDAM(deployAccountDetail.nonceDataAvailabilityMode),
19181
+ intDAM(deployAccountDetail.feeDataAvailabilityMode)
19182
+ )
19183
+ );
19184
+ const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
19185
+ const saltBuf = this.convertBnToLedger(deployAccountDetail.addressSalt);
19186
+ const dataBuf = concatenateArrayBuffer([
19187
+ accountAddressBuf,
19188
+ chainIdBuf,
19189
+ nonceBuf,
19190
+ dAModeHashBuf,
19191
+ classHashBuf,
19192
+ saltBuf
19193
+ ]);
19194
+ await this._transporter.send(Number("0x5a"), 5, 1, 0, buffer_default.from(dataBuf));
19195
+ if (isRPC08Plus_ResourceBoundsBN(deployAccountDetail.resourceBounds)) {
19196
+ const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
19197
+ const l1_gasBuf = this.convertBnToLedger(
19198
+ encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
19199
+ );
19200
+ const l2_gasBuf = this.convertBnToLedger(
19201
+ encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
19202
+ );
19203
+ const l1_data_gasBuf = this.convertBnToLedger(
19204
+ encodeDataResourceBoundsL1(deployAccountDetail.resourceBounds)
19205
+ );
19206
+ const feeBuf = concatenateArrayBuffer([
19207
+ tipBuf,
19208
+ l1_gasBuf,
19209
+ l2_gasBuf,
19210
+ l1_data_gasBuf
19211
+ ]);
19212
+ await this._transporter.send(Number("0x5a"), 5, 2, 0, buffer_default.from(feeBuf));
18999
19213
  }
19000
- const executionParameters = {
19001
- version: parameters.version,
19002
- fee_mode: convertFeeMode(parameters.feeMode),
19003
- time_bounds: convertTimeBounds(parameters.timeBounds)
19004
- };
19005
- const response = await this.fetchEndpoint("paymaster_buildTransaction", {
19006
- transaction: userTransaction,
19007
- parameters: executionParameters
19008
- });
19009
- const fee = {
19010
- gas_token_price_in_strk: BigInt(response.fee.gas_token_price_in_strk),
19011
- estimated_fee_in_strk: BigInt(response.fee.estimated_fee_in_strk),
19012
- estimated_fee_in_gas_token: BigInt(response.fee.estimated_fee_in_gas_token),
19013
- suggested_max_fee_in_strk: BigInt(response.fee.suggested_max_fee_in_strk),
19014
- suggested_max_fee_in_gas_token: BigInt(response.fee.suggested_max_fee_in_gas_token)
19015
- };
19016
- switch (response.type) {
19017
- case "invoke":
19018
- return {
19019
- type: "invoke",
19020
- typed_data: response.typed_data,
19021
- parameters: convertEXECUTION_PARAMETERS(response.parameters),
19022
- fee
19023
- };
19024
- case "deploy_and_invoke":
19025
- return {
19026
- type: "deploy_and_invoke",
19027
- deployment: response.deployment,
19028
- typed_data: response.typed_data,
19029
- parameters: convertEXECUTION_PARAMETERS(response.parameters),
19030
- fee
19031
- };
19032
- case "deploy":
19033
- default:
19034
- return {
19035
- type: "deploy",
19036
- deployment: response.deployment,
19037
- parameters: convertEXECUTION_PARAMETERS(response.parameters),
19038
- fee
19039
- };
19214
+ const paymasterBuf = concatenateArrayBuffer(
19215
+ deployAccountDetail.paymasterData.map((value) => {
19216
+ const a = this.convertBnToLedger(value);
19217
+ return a;
19218
+ })
19219
+ );
19220
+ await this._transporter.send(Number("0x5a"), 5, 3, 0, buffer_default.from(paymasterBuf));
19221
+ const compiledConstructor = CallData.compile(deployAccountDetail.constructorCalldata);
19222
+ const constructorLengthBuf = this.convertBnToLedger(compiledConstructor.length);
19223
+ await this._transporter.send(Number("0x5a"), 5, 4, 0, buffer_default.from(constructorLengthBuf));
19224
+ const constructorBuf = concatenateArrayBuffer(
19225
+ compiledConstructor.map((parameter) => {
19226
+ const a = this.convertBnToLedger(parameter);
19227
+ return a;
19228
+ })
19229
+ );
19230
+ const constructorChunks = [];
19231
+ const chunkSize = 7 * 32;
19232
+ for (let i = 0; i < constructorBuf.length; i += chunkSize)
19233
+ constructorChunks.push(constructorBuf.subarray(i, i + chunkSize));
19234
+ let respSign = new Uint8Array(0);
19235
+ for (const chunk of constructorChunks) {
19236
+ respSign = await this._transporter.send(Number("0x5a"), 5, 5, 0, buffer_default.from(chunk));
19040
19237
  }
19238
+ return this.decodeSignatureLedger(respSign);
19041
19239
  }
19042
- async executeTransaction(transaction, parameters) {
19043
- let user_transaction;
19044
- switch (transaction.type) {
19045
- case "invoke":
19046
- user_transaction = {
19047
- ...transaction,
19048
- invoke: {
19049
- user_address: transaction.invoke.userAddress,
19050
- typed_data: transaction.invoke.typedData,
19051
- signature: signatureToHexArray(transaction.invoke.signature)
19052
- }
19053
- };
19054
- break;
19055
- case "deploy_and_invoke":
19056
- user_transaction = {
19057
- ...transaction,
19058
- invoke: {
19059
- user_address: transaction.invoke.userAddress,
19060
- typed_data: transaction.invoke.typedData,
19061
- signature: signatureToHexArray(transaction.invoke.signature)
19062
- }
19063
- };
19064
- break;
19065
- case "deploy":
19066
- default:
19067
- user_transaction = transaction;
19068
- break;
19240
+ /** Internal function to convert a Call to an array of Uint8Array.
19241
+ * @param {Call} call A Call to convert.
19242
+ * @return {Uint8Array[]} Call encoded in an array of Uint8Array (each containing 7 u256).
19243
+ */
19244
+ encodeCall(call) {
19245
+ const toBuf = this.convertBnToLedger(call.contractAddress);
19246
+ const selectorBuf = hexToBytes(addAddressPadding(getSelector(call.entrypoint)));
19247
+ let calldataBuf;
19248
+ if (call.calldata) {
19249
+ const compiledCalldata = CallData.compile(call.calldata);
19250
+ const calldataSizeBuf = this.convertBnToLedger(compiledCalldata.length);
19251
+ calldataBuf = concatenateArrayBuffer([
19252
+ calldataSizeBuf,
19253
+ ...compiledCalldata.map((parameter) => {
19254
+ const a = this.convertBnToLedger(parameter);
19255
+ return a;
19256
+ })
19257
+ ]);
19258
+ } else {
19259
+ calldataBuf = this.convertBnToLedger("0x00");
19069
19260
  }
19070
- const executionParameters = {
19071
- version: parameters.version,
19072
- fee_mode: convertFeeMode(parameters.feeMode),
19073
- time_bounds: convertTimeBounds(parameters.timeBounds)
19074
- };
19075
- return this.fetchEndpoint("paymaster_executeTransaction", {
19076
- transaction: user_transaction,
19077
- parameters: executionParameters
19078
- });
19079
- }
19080
- async getSupportedTokens() {
19081
- return this.fetchEndpoint("paymaster_getSupportedTokens").then(
19082
- (tokens) => tokens.map((token) => ({
19083
- token_address: token.token_address,
19084
- decimals: token.decimals,
19085
- priceInStrk: BigInt(token.price_in_strk)
19086
- }))
19087
- );
19261
+ const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
19262
+ const calldatas = [];
19263
+ const chunkSize = 7 * 32;
19264
+ for (let i = 0; i < callBuf.length; i += chunkSize)
19265
+ calldatas.push(callBuf.subarray(i, i + chunkSize));
19266
+ return calldatas;
19088
19267
  }
19089
19268
  };
19090
19269
 
19091
- // src/paymaster/interface.ts
19092
- var PaymasterInterface = class {
19093
- };
19270
+ // src/utils/src5.ts
19271
+ var src5_exports = {};
19272
+ __export(src5_exports, {
19273
+ supportsInterface: () => supportsInterface
19274
+ });
19275
+ async function supportsInterface(provider, contractAddress, interfaceId) {
19276
+ const call = {
19277
+ contractAddress: toHex(contractAddress),
19278
+ entrypoint: "supports_interface",
19279
+ calldata: [toHex(interfaceId)]
19280
+ };
19281
+ try {
19282
+ const resp = await provider.callContract(call);
19283
+ return BigInt(resp[0]) !== 0n;
19284
+ } catch {
19285
+ return false;
19286
+ }
19287
+ }
19094
19288
 
19095
19289
  // src/deployer/compileConstructorCalldata.ts
19096
19290
  function checkCompiledConstructorCalldata(calldata, abi) {
@@ -19247,7 +19441,6 @@ var Account = class {
19247
19441
  // holds Cairo 0 contracts, to refuse a Cairo 0 account; otherwise remove it.
19248
19442
  cairoVersion;
19249
19443
  transactionVersion;
19250
- paymaster;
19251
19444
  deployer;
19252
19445
  defaultTipType;
19253
19446
  /** @internal Account-level plugin management */
@@ -19269,11 +19462,13 @@ var Account = class {
19269
19462
  this.cairoVersion = cairoVersion.toString();
19270
19463
  }
19271
19464
  this.transactionVersion = transactionVersion ?? config.get("transactionVersion");
19272
- this.paymaster = paymaster ? new PaymasterRpc(paymaster) : new PaymasterRpc({ mute: true });
19273
19465
  this.deployer = options.deployer ?? defaultDeployer;
19274
19466
  this.defaultTipType = defaultTipType ?? config.get("defaultTipType");
19275
19467
  this.accountPluginManager = new PluginManager();
19276
- const plugins = options.plugins === false ? [] : options.plugins ?? defaultPlugins;
19468
+ const plugins = applyPaymasterOption(
19469
+ options.plugins === false ? [] : options.plugins ?? defaultPlugins,
19470
+ paymaster
19471
+ );
19277
19472
  plugins.forEach((plugin) => {
19278
19473
  this.accountPluginManager.installOnAccount(plugin, this);
19279
19474
  });
@@ -19984,114 +20179,6 @@ var Account = class {
19984
20179
  })
19985
20180
  );
19986
20181
  }
19987
- /*
19988
- * SNIP-29 Paymaster
19989
- */
19990
- async buildPaymasterTransaction(calls, paymasterDetails) {
19991
- if (!paymasterDetails.deploymentData) {
19992
- const snip9Version = await this.getSnip9Version();
19993
- if (snip9Version === OutsideExecutionVersion.UNSUPPORTED) {
19994
- throw Error("Account is not compatible with SNIP-9");
19995
- }
19996
- }
19997
- const parameters = {
19998
- version: "0x1",
19999
- feeMode: paymasterDetails.feeMode,
20000
- timeBounds: paymasterDetails.timeBounds
20001
- };
20002
- let transaction;
20003
- if (paymasterDetails.deploymentData) {
20004
- if (calls.length > 0) {
20005
- transaction = {
20006
- type: "deploy_and_invoke",
20007
- invoke: { userAddress: this.address, calls },
20008
- deployment: paymasterDetails.deploymentData
20009
- };
20010
- } else {
20011
- transaction = {
20012
- type: "deploy",
20013
- deployment: paymasterDetails.deploymentData
20014
- };
20015
- }
20016
- } else {
20017
- transaction = {
20018
- type: "invoke",
20019
- invoke: { userAddress: this.address, calls }
20020
- };
20021
- }
20022
- return this.paymaster.buildTransaction(transaction, parameters);
20023
- }
20024
- async estimatePaymasterTransactionFee(calls, paymasterDetails) {
20025
- const preparedTransaction = await this.buildPaymasterTransaction(calls, paymasterDetails);
20026
- return preparedTransaction.fee;
20027
- }
20028
- /**
20029
- * Signs a transaction prepared by the paymaster, after checking it is safe to sign. The safety
20030
- * check needs the calls and the fee details the user actually requested, so a caller that uses
20031
- * this low-level method directly must pass them, the same way `executePaymasterTransaction`
20032
- * does.
20033
- * @param preparedTransaction the transaction returned by the paymaster.
20034
- * @param calls the calls the user requested.
20035
- * @param paymasterDetails the fee mode and related paymaster details.
20036
- * @param maxFeeInGasToken optional user-approved ceiling on the gas-token fee.
20037
- */
20038
- async preparePaymasterTransaction(preparedTransaction, calls, paymasterDetails, maxFeeInGasToken) {
20039
- assertPaymasterTransactionSafety(
20040
- preparedTransaction,
20041
- calls,
20042
- paymasterDetails,
20043
- await this.provider.getChainId(),
20044
- maxFeeInGasToken
20045
- );
20046
- let transaction;
20047
- switch (preparedTransaction.type) {
20048
- case "deploy_and_invoke": {
20049
- const signature = await this.signMessage(preparedTransaction.typed_data);
20050
- transaction = {
20051
- type: "deploy_and_invoke",
20052
- invoke: {
20053
- userAddress: this.address,
20054
- typedData: preparedTransaction.typed_data,
20055
- signature: signatureToHexArray(signature)
20056
- },
20057
- deployment: preparedTransaction.deployment
20058
- };
20059
- break;
20060
- }
20061
- case "invoke": {
20062
- const signature = await this.signMessage(preparedTransaction.typed_data);
20063
- transaction = {
20064
- type: "invoke",
20065
- invoke: {
20066
- userAddress: this.address,
20067
- typedData: preparedTransaction.typed_data,
20068
- signature: signatureToHexArray(signature)
20069
- }
20070
- };
20071
- break;
20072
- }
20073
- case "deploy": {
20074
- transaction = {
20075
- type: "deploy",
20076
- deployment: preparedTransaction.deployment
20077
- };
20078
- break;
20079
- }
20080
- default:
20081
- throw Error("Invalid transaction type");
20082
- }
20083
- return transaction;
20084
- }
20085
- async executePaymasterTransaction(calls, paymasterDetails, maxFeeInGasToken) {
20086
- const preparedTransaction = await this.buildPaymasterTransaction(calls, paymasterDetails);
20087
- const transaction = await this.preparePaymasterTransaction(
20088
- preparedTransaction,
20089
- calls,
20090
- paymasterDetails,
20091
- maxFeeInGasToken
20092
- );
20093
- return this.paymaster.executeTransaction(transaction, preparedTransaction.parameters).then((response) => ({ transaction_hash: response.transaction_hash }));
20094
- }
20095
20182
  };
20096
20183
 
20097
20184
  // src/account/interface.ts
@@ -21123,6 +21210,7 @@ function filterEventsByAddress(events, contractAddress) {
21123
21210
  }
21124
21211
 
21125
21212
  // src/contract/default.ts
21213
+ var NO_PAYMASTER_MESSAGE = "This account has no paymaster methods: add paymasterPlugin() to its plugins, or set its paymaster option.";
21126
21214
  function buildCall(contract, functionAbi) {
21127
21215
  return async function(...args) {
21128
21216
  const options = { ...contract.withOptionsProps };
@@ -21361,13 +21449,12 @@ var Contract = class _Contract {
21361
21449
  await this.ensureProvider();
21362
21450
  if (isAccount(this.providerOrAccount)) {
21363
21451
  if (restInvokeOptions.paymasterDetails) {
21364
- const myCall = {
21365
- contractAddress: this.address,
21366
- entrypoint: method,
21367
- calldata: args
21368
- };
21452
+ assert(
21453
+ typeof this.providerOrAccount.executePaymasterTransaction === "function",
21454
+ NO_PAYMASTER_MESSAGE
21455
+ );
21369
21456
  return this.providerOrAccount.executePaymasterTransaction(
21370
- [myCall],
21457
+ [invocation],
21371
21458
  restInvokeOptions.paymasterDetails,
21372
21459
  restInvokeOptions.maxFeeInGasToken
21373
21460
  );
@@ -21411,13 +21498,12 @@ var Contract = class _Contract {
21411
21498
  await this.ensureProvider();
21412
21499
  if (isAccount(this.providerOrAccount)) {
21413
21500
  if (estimateDetails.paymasterDetails) {
21414
- const myCall = {
21415
- contractAddress: this.address,
21416
- entrypoint: method,
21417
- calldata: args
21418
- };
21501
+ assert(
21502
+ typeof this.providerOrAccount.estimatePaymasterTransactionFee === "function",
21503
+ NO_PAYMASTER_MESSAGE
21504
+ );
21419
21505
  return this.providerOrAccount.estimatePaymasterTransactionFee(
21420
- [myCall],
21506
+ [invocation],
21421
21507
  estimateDetails.paymasterDetails
21422
21508
  );
21423
21509
  }
@@ -21789,7 +21875,8 @@ export {
21789
21875
  num_exports as num,
21790
21876
  outsideExecution_exports as outsideExecution,
21791
21877
  parseCalldataField,
21792
- paymaster_exports as paymaster,
21878
+ utils_exports as paymaster,
21879
+ paymasterPlugin,
21793
21880
  provider_exports as provider,
21794
21881
  selector_exports as selector,
21795
21882
  shortString_exports as shortString,