starknet 11.4.0 → 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
@@ -17567,38 +18276,19 @@ var Signer = class {
17567
18276
  async signDeclareTransaction(details) {
17568
18277
  const msgHash = calculateDeclareTransactionHash2({
17569
18278
  ...details,
17570
- version: details.version,
17571
- nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
17572
- feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
17573
- });
17574
- return this.signRaw(msgHash);
17575
- }
17576
- async signRaw(msgHash) {
17577
- return starkCurve.sign(msgHash, this.pk);
17578
- }
17579
- };
17580
-
17581
- // src/signer/ethSigner.ts
17582
- 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
- }
18279
+ version: details.version,
18280
+ nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
18281
+ feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
18282
+ });
18283
+ return this.signRaw(msgHash);
18284
+ }
18285
+ async signRaw(msgHash) {
18286
+ return starkCurve.sign(msgHash, this.pk);
18287
+ }
18288
+ };
17600
18289
 
17601
18290
  // src/signer/ethSigner.ts
18291
+ import { secp256k1 as secp256k12 } from "@noble/curves/secp256k1.js";
17602
18292
  var EthSigner = class {
17603
18293
  pk;
17604
18294
  // hex string without 0x and with an odd number of characters
@@ -18106,254 +18796,28 @@ var LedgerSigner221 = class extends LedgerSigner111 {
18106
18796
  return { hash: h, signature: sign1 };
18107
18797
  }
18108
18798
  /** 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);
18217
- }
18218
- /**
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
18222
- * @example
18223
- * ```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
- * // }
18245
- * ```
18246
- */
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)
18277
- );
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
- })
18285
- );
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
- })
18295
- );
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);
18305
- }
18306
- };
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);
18317
- const padded = addHexPrefix(removeHexPrefix(hex).padStart(8, "0"));
18318
- const path4buff = hexToBytes(padded);
18319
- const path5buff = new Uint8Array([0, 0, 0, 0]);
18320
- const pathBuff = concatenateArrayBuffer([
18321
- path0buff,
18322
- path1buff,
18323
- path2buff,
18324
- path3buff,
18325
- path4buff,
18326
- path5buff
18327
- ]);
18328
- return pathBuff;
18329
- }
18330
-
18331
- // src/signer/ledgerSigner231.ts
18332
- var LedgerSigner231 = class extends LedgerSigner221 {
18333
- /**
18334
- * constructor of the LedgerSigner class.
18335
- * @param {Transport} transport 5 transports are available to handle USB, bluetooth, Node, Web, Mobile.
18336
- * See Guides for more details.
18337
- * @param {number} accountID ID of Ledger Nano account (can handle 2**31 accounts).
18338
- * @param {string} [eip2645application='LedgerW'] A wallet is defined by an ERC2645 derivation path (6 items).
18339
- * One item is called `application` and can be customized.
18340
- * Default value is `LedgerW`.
18341
- * @param {LedgerPathCalculation} [pathFunction=getLedgerPathBuffer221]
18342
- * defines the function that will calculate the path. By default `getLedgerPathBuffer221` is selected.
18343
- *
18344
- * If you are using APP v2.3.1 with an account created with the v1.1.1, you need to use :
18345
- * ```typescript
18346
- * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0, undefined, getLedgerPathBuffer111);
18347
- * ```
18348
- * @example
18349
- * ```typescript
18350
- * import TransportNodeHid from "@ledgerhq/hw-transport-node-hid";
18351
- * const myNodeTransport = await TransportNodeHid.create();
18352
- * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0);
18353
- * ```
18799
+ * @param {Call} call A Call to convert.
18800
+ * @return {Uint8Array[]} Call encoded in an array of Uint8Array (each containing 7 u256).
18354
18801
  */
18355
- constructor(transport, accountID, eip2645application = "LedgerW", pathFunction = getLedgerPathBuffer221) {
18356
- super(transport, accountID, eip2645application, pathFunction);
18802
+ encodeCall(call) {
18803
+ const toBuf = this.convertBnToLedger(call.contractAddress);
18804
+ const selectorBuf = hexToBytes(addAddressPadding(getSelector(call.entrypoint)));
18805
+ let calldataBuf = new Uint8Array([]);
18806
+ if (call.calldata) {
18807
+ const compiledCalldata = CallData.compile(call.calldata);
18808
+ calldataBuf = concatenateArrayBuffer(
18809
+ compiledCalldata.map((parameter) => {
18810
+ const a = this.convertBnToLedger(parameter);
18811
+ return a;
18812
+ })
18813
+ );
18814
+ }
18815
+ const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
18816
+ const calldatas = [];
18817
+ const chunkSize = 7 * 32;
18818
+ for (let i = 0; i < callBuf.length; i += chunkSize)
18819
+ calldatas.push(callBuf.subarray(i, i + chunkSize));
18820
+ return calldatas;
18357
18821
  }
18358
18822
  /**
18359
18823
  * Ask to the Ledger Nano to display and sign a Starknet V3 transaction.
@@ -18391,61 +18855,53 @@ var LedgerSigner231 = class extends LedgerSigner221 {
18391
18855
  );
18392
18856
  await this._transporter.send(Number("0x5a"), 3, 0, 0, buffer_default.from(this.pathBuffer));
18393
18857
  const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
18858
+ const tipBuf = this.convertBnToLedger(txDetails.tip);
18394
18859
  const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
18395
18860
  const nonceBuf = this.convertBnToLedger(txDetails.nonce);
18396
18861
  const dAModeHashBuf = this.convertBnToLedger(
18397
18862
  hashDAMode(
18398
- intDAM(txDetails.nonceDataAvailabilityMode),
18399
- intDAM(txDetails.feeDataAvailabilityMode)
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
18400
18865
  )
18401
18866
  );
18867
+ const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
18868
+ const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
18402
18869
  const dataBuf = concatenateArrayBuffer([
18403
18870
  accountAddressBuf,
18871
+ tipBuf,
18872
+ l1_gasBuf,
18873
+ l2_gasBuf,
18404
18874
  chainIdBuf,
18405
18875
  nonceBuf,
18406
18876
  dAModeHashBuf
18407
18877
  ]);
18408
18878
  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
18879
  const paymasterBuf = concatenateArrayBuffer(
18425
18880
  txDetails.paymasterData.map((value) => {
18426
18881
  const a = this.convertBnToLedger(value);
18427
18882
  return a;
18428
18883
  })
18429
18884
  );
18430
- await this._transporter.send(Number("0x5a"), 3, 3, 0, buffer_default.from(paymasterBuf));
18885
+ await this._transporter.send(Number("0x5a"), 3, 2, 0, buffer_default.from(paymasterBuf));
18431
18886
  const accountDeployDataBuf = concatenateArrayBuffer(
18432
18887
  txDetails.paymasterData.map((value) => {
18433
18888
  const a = this.convertBnToLedger(value);
18434
18889
  return a;
18435
18890
  })
18436
18891
  );
18437
- await this._transporter.send(Number("0x5a"), 3, 4, 0, buffer_default.from(accountDeployDataBuf));
18892
+ await this._transporter.send(Number("0x5a"), 3, 3, 0, buffer_default.from(accountDeployDataBuf));
18438
18893
  const nbCallsBuf = this.convertBnToLedger(calls.length);
18439
- await this._transporter.send(Number("0x5a"), 3, 5, 0, buffer_default.from(nbCallsBuf));
18894
+ await this._transporter.send(Number("0x5a"), 3, 4, 0, buffer_default.from(nbCallsBuf));
18440
18895
  let respSign = new Uint8Array(0);
18441
18896
  for (const call of calls) {
18442
18897
  const calldatas = this.encodeCall(call);
18443
- respSign = await this._transporter.send(Number("0x5a"), 3, 6, 0, buffer_default.from(calldatas[0]));
18898
+ await this._transporter.send(Number("0x5a"), 3, 5, 0, buffer_default.from(calldatas[0]));
18444
18899
  if (calldatas.length > 1) {
18445
18900
  calldatas.slice(1).forEach(async (part) => {
18446
- respSign = await this._transporter.send(Number("0x5a"), 3, 6, 1, buffer_default.from(part));
18901
+ await this._transporter.send(Number("0x5a"), 3, 5, 1, buffer_default.from(part));
18447
18902
  });
18448
18903
  }
18904
+ respSign = await this._transporter.send(Number("0x5a"), 3, 5, 2);
18449
18905
  }
18450
18906
  return this.decodeSignatureLedger(respSign);
18451
18907
  }
@@ -18475,581 +18931,360 @@ var LedgerSigner231 = class extends LedgerSigner221 {
18475
18931
  * const res = await myLedgerSigner.signDeployAccountV3(deployData);
18476
18932
  * // res = {hash:
18477
18933
  * // signature:
18478
- * // }
18479
- * ```
18480
- */
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);
18549
- }
18550
- /** Internal function to convert a Call to an array of Uint8Array.
18551
- * @param {Call} call A Call to convert.
18552
- * @return {Uint8Array[]} Call encoded in an array of Uint8Array (each containing 7 u256).
18553
- */
18554
- encodeCall(call) {
18555
- const toBuf = this.convertBnToLedger(call.contractAddress);
18556
- const selectorBuf = hexToBytes(addAddressPadding(getSelector(call.entrypoint)));
18557
- let calldataBuf;
18558
- if (call.calldata) {
18559
- const compiledCalldata = CallData.compile(call.calldata);
18560
- const calldataSizeBuf = this.convertBnToLedger(compiledCalldata.length);
18561
- calldataBuf = concatenateArrayBuffer([
18562
- calldataSizeBuf,
18563
- ...compiledCalldata.map((parameter) => {
18564
- const a = this.convertBnToLedger(parameter);
18565
- return a;
18566
- })
18567
- ]);
18568
- } else {
18569
- calldataBuf = this.convertBnToLedger("0x00");
18570
- }
18571
- const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
18572
- const calldatas = [];
18573
- const chunkSize = 7 * 32;
18574
- for (let i = 0; i < callBuf.length; i += chunkSize)
18575
- calldatas.push(callBuf.subarray(i, i + chunkSize));
18576
- return calldatas;
18577
- }
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");
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
18941
+ );
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
+ )
18949
+ );
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)
18964
+ );
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));
18676
18993
  }
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;
18994
+ return this.decodeSignatureLedger(respSign);
18702
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;
18703
19019
  }
18704
19020
 
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!");
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);
18715
19047
  }
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);
18762
- assert(
18763
- originalAddress === unsafeAddress,
18764
- `${baseError}: Contract address mismatch at call ${callIndex}. Expected: ${originalCall.contractAddress}, Got: ${unsafeCall.To}`
18765
- );
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.");
18766
19078
  assert(
18767
- getSelectorFromName(originalCall.entrypoint) === unsafeCall.Selector,
18768
- `${baseError}: Entrypoint mismatch at call ${callIndex}. Expected: ${originalCall.entrypoint}, Got: ${unsafeCall.Selector}`
19079
+ txDetails.accountDeploymentData.length <= 7,
19080
+ "accountDeploymentData includes more than 7 items"
18769
19081
  );
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}`
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
+ )
18775
19091
  );
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]}`
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)
18782
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));
18783
19113
  }
18784
- }
18785
- }
18786
- var domainFieldToFelt = (value) => {
18787
- try {
18788
- return toBigInt(value);
18789
- } catch {
18790
- return CairoBytes31.fromText(String(value)).toBigInt();
18791
- }
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;
18805
- assert(
18806
- hasV1Calls !== hasV2Calls,
18807
- 'Paymaster typed data must declare exactly one of "calls" (SNIP-9 V1) or "Calls" (SNIP-9 V2)'
19114
+ const paymasterBuf = concatenateArrayBuffer(
19115
+ txDetails.paymasterData.map((value) => {
19116
+ const a = this.convertBnToLedger(value);
19117
+ return a;
19118
+ })
18808
19119
  );
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
- );
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
+ })
19126
+ );
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
+ });
18822
19138
  }
18823
19139
  }
19140
+ return this.decodeSignatureLedger(respSign);
18824
19141
  }
18825
- };
18826
-
18827
- // src/paymaster/rpc.ts
18828
- var convertCalls = (calls) => calls.map((call) => ({
18829
- to: call.contractAddress,
18830
- selector: getSelectorFromName(call.entrypoint),
18831
- calldata: CallData.toHex(call.calldata)
18832
- }));
18833
- var convertFeeMode = (feeMode) => {
18834
- if (feeMode.mode === "sponsored") {
18835
- return { mode: "sponsored" };
18836
- }
18837
- return { mode: "default", gas_token: feeMode.gasToken };
18838
- };
18839
- var convertFEE_MODE = (feeMode) => {
18840
- if (feeMode.mode === "sponsored") {
18841
- return { mode: "sponsored" };
18842
- }
18843
- return { mode: "default", gasToken: feeMode.gas_token };
18844
- };
18845
- var convertTimeBounds = (timeBounds) => timeBounds ? {
18846
- execute_after: timeBounds.executeAfter || 1,
18847
- // If executeAfter is not provided, set it to 1, meaning the transaction can be executed immediately
18848
- execute_before: timeBounds.executeBefore
18849
- } : void 0;
18850
- var convertTIME_BOUNDS = (timeBounds) => timeBounds ? {
18851
- executeAfter: timeBounds.execute_after,
18852
- executeBefore: timeBounds.execute_before
18853
- } : void 0;
18854
- var convertEXECUTION_PARAMETERS = (parameters) => ({
18855
- version: parameters.version,
18856
- feeMode: convertFEE_MODE(parameters.fee_mode),
18857
- timeBounds: convertTIME_BOUNDS(parameters.time_bounds)
18858
- });
18859
- var defaultOptions = {
18860
- headers: { "Content-Type": "application/json" }
18861
- };
18862
- var PaymasterRpc = class _PaymasterRpc {
18863
- nodeUrl;
18864
- headers;
18865
- baseFetch;
18866
- requestId;
18867
- constructor(options) {
18868
- if (options instanceof _PaymasterRpc) {
18869
- this.nodeUrl = options.nodeUrl;
18870
- this.headers = { ...defaultOptions.headers, ...options.headers };
18871
- this.baseFetch = options.baseFetch;
18872
- this.requestId = options.requestId;
18873
- return;
18874
- }
18875
- if (options && "nodeUrl" in options && "headers" in options && "baseFetch" in options) {
18876
- this.nodeUrl = options.nodeUrl ?? getDefaultPaymasterNodeUrl(void 0);
18877
- this.headers = { ...defaultOptions.headers, ...options.headers };
18878
- this.baseFetch = options.baseFetch ?? fetch_default;
18879
- this.requestId = 0;
18880
- return;
18881
- }
18882
- const { nodeUrl, headers, baseFetch } = options || {};
18883
- if (nodeUrl && Object.values(_NetworkName).includes(nodeUrl)) {
18884
- this.nodeUrl = getDefaultPaymasterNodeUrl(nodeUrl, options?.mute);
18885
- } else if (nodeUrl) {
18886
- this.nodeUrl = nodeUrl;
18887
- } else {
18888
- this.nodeUrl = getDefaultPaymasterNodeUrl(void 0, options?.mute);
18889
- }
18890
- this.baseFetch = baseFetch ?? fetch_default;
18891
- this.headers = { ...defaultOptions.headers, ...headers };
18892
- this.requestId = 0;
18893
- }
18894
- fetch(method, params, id = 0) {
18895
- const rpcRequestBody = {
18896
- id,
18897
- jsonrpc: "2.0",
18898
- method,
18899
- ...params && { params }
18900
- };
18901
- return this.baseFetch(this.nodeUrl, {
18902
- method: "POST",
18903
- body: stringify2(rpcRequestBody),
18904
- headers: this.headers
18905
- });
18906
- }
18907
- errorHandler(method, params, rpcError, otherError) {
18908
- if (rpcError) {
18909
- throw new RpcError(rpcError, method, params);
18910
- }
18911
- if (otherError instanceof LibraryError) {
18912
- throw otherError;
18913
- }
18914
- if (otherError) {
18915
- throw Error(otherError.message);
18916
- }
18917
- }
18918
- async fetchEndpoint(method, params) {
18919
- try {
18920
- this.requestId += 1;
18921
- const rawResult = await this.fetch(method, params, this.requestId);
18922
- const { error, result } = await rawResult.json();
18923
- this.errorHandler(method, params, error);
18924
- return result;
18925
- } catch (error) {
18926
- this.errorHandler(method, params, error?.response?.data, error);
18927
- throw error;
18928
- }
18929
- }
18930
- async isAvailable() {
18931
- return this.fetchEndpoint("paymaster_isAvailable");
18932
- }
18933
- async buildTransaction(transaction, parameters) {
18934
- let userTransaction;
18935
- switch (transaction.type) {
18936
- case "invoke":
18937
- userTransaction = {
18938
- ...transaction,
18939
- invoke: {
18940
- user_address: transaction.invoke.userAddress,
18941
- calls: convertCalls(transaction.invoke.calls)
18942
- }
18943
- };
18944
- break;
18945
- case "deploy_and_invoke":
18946
- userTransaction = {
18947
- ...transaction,
18948
- invoke: {
18949
- user_address: transaction.invoke.userAddress,
18950
- calls: convertCalls(transaction.invoke.calls)
18951
- }
18952
- };
18953
- break;
18954
- case "deploy":
18955
- default:
18956
- userTransaction = transaction;
18957
- 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));
18958
19213
  }
18959
- const executionParameters = {
18960
- version: parameters.version,
18961
- fee_mode: convertFeeMode(parameters.feeMode),
18962
- time_bounds: convertTimeBounds(parameters.timeBounds)
18963
- };
18964
- const response = await this.fetchEndpoint("paymaster_buildTransaction", {
18965
- transaction: userTransaction,
18966
- parameters: executionParameters
18967
- });
18968
- const fee = {
18969
- gas_token_price_in_strk: BigInt(response.fee.gas_token_price_in_strk),
18970
- estimated_fee_in_strk: BigInt(response.fee.estimated_fee_in_strk),
18971
- estimated_fee_in_gas_token: BigInt(response.fee.estimated_fee_in_gas_token),
18972
- suggested_max_fee_in_strk: BigInt(response.fee.suggested_max_fee_in_strk),
18973
- suggested_max_fee_in_gas_token: BigInt(response.fee.suggested_max_fee_in_gas_token)
18974
- };
18975
- switch (response.type) {
18976
- case "invoke":
18977
- return {
18978
- type: "invoke",
18979
- typed_data: response.typed_data,
18980
- parameters: convertEXECUTION_PARAMETERS(response.parameters),
18981
- fee
18982
- };
18983
- case "deploy_and_invoke":
18984
- return {
18985
- type: "deploy_and_invoke",
18986
- deployment: response.deployment,
18987
- typed_data: response.typed_data,
18988
- parameters: convertEXECUTION_PARAMETERS(response.parameters),
18989
- fee
18990
- };
18991
- case "deploy":
18992
- default:
18993
- return {
18994
- type: "deploy",
18995
- deployment: response.deployment,
18996
- parameters: convertEXECUTION_PARAMETERS(response.parameters),
18997
- fee
18998
- };
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));
18999
19237
  }
19238
+ return this.decodeSignatureLedger(respSign);
19000
19239
  }
19001
- async executeTransaction(transaction, parameters) {
19002
- let user_transaction;
19003
- switch (transaction.type) {
19004
- case "invoke":
19005
- user_transaction = {
19006
- ...transaction,
19007
- invoke: {
19008
- user_address: transaction.invoke.userAddress,
19009
- typed_data: transaction.invoke.typedData,
19010
- signature: signatureToHexArray(transaction.invoke.signature)
19011
- }
19012
- };
19013
- break;
19014
- case "deploy_and_invoke":
19015
- user_transaction = {
19016
- ...transaction,
19017
- invoke: {
19018
- user_address: transaction.invoke.userAddress,
19019
- typed_data: transaction.invoke.typedData,
19020
- signature: signatureToHexArray(transaction.invoke.signature)
19021
- }
19022
- };
19023
- break;
19024
- case "deploy":
19025
- default:
19026
- user_transaction = transaction;
19027
- 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");
19028
19260
  }
19029
- const executionParameters = {
19030
- version: parameters.version,
19031
- fee_mode: convertFeeMode(parameters.feeMode),
19032
- time_bounds: convertTimeBounds(parameters.timeBounds)
19033
- };
19034
- return this.fetchEndpoint("paymaster_executeTransaction", {
19035
- transaction: user_transaction,
19036
- parameters: executionParameters
19037
- });
19038
- }
19039
- async getSupportedTokens() {
19040
- return this.fetchEndpoint("paymaster_getSupportedTokens").then(
19041
- (tokens) => tokens.map((token) => ({
19042
- token_address: token.token_address,
19043
- decimals: token.decimals,
19044
- priceInStrk: BigInt(token.price_in_strk)
19045
- }))
19046
- );
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;
19047
19267
  }
19048
19268
  };
19049
19269
 
19050
- // src/paymaster/interface.ts
19051
- var PaymasterInterface = class {
19052
- };
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
+ }
19053
19288
 
19054
19289
  // src/deployer/compileConstructorCalldata.ts
19055
19290
  function checkCompiledConstructorCalldata(calldata, abi) {
@@ -19206,7 +19441,6 @@ var Account = class {
19206
19441
  // holds Cairo 0 contracts, to refuse a Cairo 0 account; otherwise remove it.
19207
19442
  cairoVersion;
19208
19443
  transactionVersion;
19209
- paymaster;
19210
19444
  deployer;
19211
19445
  defaultTipType;
19212
19446
  /** @internal Account-level plugin management */
@@ -19228,11 +19462,13 @@ var Account = class {
19228
19462
  this.cairoVersion = cairoVersion.toString();
19229
19463
  }
19230
19464
  this.transactionVersion = transactionVersion ?? config.get("transactionVersion");
19231
- this.paymaster = paymaster ? new PaymasterRpc(paymaster) : new PaymasterRpc({ mute: true });
19232
19465
  this.deployer = options.deployer ?? defaultDeployer;
19233
19466
  this.defaultTipType = defaultTipType ?? config.get("defaultTipType");
19234
19467
  this.accountPluginManager = new PluginManager();
19235
- const plugins = options.plugins === false ? [] : options.plugins ?? defaultPlugins;
19468
+ const plugins = applyPaymasterOption(
19469
+ options.plugins === false ? [] : options.plugins ?? defaultPlugins,
19470
+ paymaster
19471
+ );
19236
19472
  plugins.forEach((plugin) => {
19237
19473
  this.accountPluginManager.installOnAccount(plugin, this);
19238
19474
  });
@@ -19943,99 +20179,6 @@ var Account = class {
19943
20179
  })
19944
20180
  );
19945
20181
  }
19946
- /*
19947
- * SNIP-29 Paymaster
19948
- */
19949
- async buildPaymasterTransaction(calls, paymasterDetails) {
19950
- if (!paymasterDetails.deploymentData) {
19951
- const snip9Version = await this.getSnip9Version();
19952
- if (snip9Version === OutsideExecutionVersion.UNSUPPORTED) {
19953
- throw Error("Account is not compatible with SNIP-9");
19954
- }
19955
- }
19956
- const parameters = {
19957
- version: "0x1",
19958
- feeMode: paymasterDetails.feeMode,
19959
- timeBounds: paymasterDetails.timeBounds
19960
- };
19961
- let transaction;
19962
- if (paymasterDetails.deploymentData) {
19963
- if (calls.length > 0) {
19964
- transaction = {
19965
- type: "deploy_and_invoke",
19966
- invoke: { userAddress: this.address, calls },
19967
- deployment: paymasterDetails.deploymentData
19968
- };
19969
- } else {
19970
- transaction = {
19971
- type: "deploy",
19972
- deployment: paymasterDetails.deploymentData
19973
- };
19974
- }
19975
- } else {
19976
- transaction = {
19977
- type: "invoke",
19978
- invoke: { userAddress: this.address, calls }
19979
- };
19980
- }
19981
- return this.paymaster.buildTransaction(transaction, parameters);
19982
- }
19983
- async estimatePaymasterTransactionFee(calls, paymasterDetails) {
19984
- const preparedTransaction = await this.buildPaymasterTransaction(calls, paymasterDetails);
19985
- return preparedTransaction.fee;
19986
- }
19987
- async preparePaymasterTransaction(preparedTransaction) {
19988
- let transaction;
19989
- switch (preparedTransaction.type) {
19990
- case "deploy_and_invoke": {
19991
- const signature = await this.signMessage(preparedTransaction.typed_data);
19992
- transaction = {
19993
- type: "deploy_and_invoke",
19994
- invoke: {
19995
- userAddress: this.address,
19996
- typedData: preparedTransaction.typed_data,
19997
- signature: signatureToHexArray(signature)
19998
- },
19999
- deployment: preparedTransaction.deployment
20000
- };
20001
- break;
20002
- }
20003
- case "invoke": {
20004
- const signature = await this.signMessage(preparedTransaction.typed_data);
20005
- transaction = {
20006
- type: "invoke",
20007
- invoke: {
20008
- userAddress: this.address,
20009
- typedData: preparedTransaction.typed_data,
20010
- signature: signatureToHexArray(signature)
20011
- }
20012
- };
20013
- break;
20014
- }
20015
- case "deploy": {
20016
- transaction = {
20017
- type: "deploy",
20018
- deployment: preparedTransaction.deployment
20019
- };
20020
- break;
20021
- }
20022
- default:
20023
- throw Error("Invalid transaction type");
20024
- }
20025
- return transaction;
20026
- }
20027
- async executePaymasterTransaction(calls, paymasterDetails, maxFeeInGasToken) {
20028
- const preparedTransaction = await this.buildPaymasterTransaction(calls, paymasterDetails);
20029
- assertPaymasterTransactionSafety(
20030
- preparedTransaction,
20031
- calls,
20032
- paymasterDetails,
20033
- await this.provider.getChainId(),
20034
- maxFeeInGasToken
20035
- );
20036
- const transaction = await this.preparePaymasterTransaction(preparedTransaction);
20037
- return this.paymaster.executeTransaction(transaction, preparedTransaction.parameters).then((response) => ({ transaction_hash: response.transaction_hash }));
20038
- }
20039
20182
  };
20040
20183
 
20041
20184
  // src/account/interface.ts
@@ -21067,6 +21210,7 @@ function filterEventsByAddress(events, contractAddress) {
21067
21210
  }
21068
21211
 
21069
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.";
21070
21214
  function buildCall(contract, functionAbi) {
21071
21215
  return async function(...args) {
21072
21216
  const options = { ...contract.withOptionsProps };
@@ -21305,13 +21449,12 @@ var Contract = class _Contract {
21305
21449
  await this.ensureProvider();
21306
21450
  if (isAccount(this.providerOrAccount)) {
21307
21451
  if (restInvokeOptions.paymasterDetails) {
21308
- const myCall = {
21309
- contractAddress: this.address,
21310
- entrypoint: method,
21311
- calldata: args
21312
- };
21452
+ assert(
21453
+ typeof this.providerOrAccount.executePaymasterTransaction === "function",
21454
+ NO_PAYMASTER_MESSAGE
21455
+ );
21313
21456
  return this.providerOrAccount.executePaymasterTransaction(
21314
- [myCall],
21457
+ [invocation],
21315
21458
  restInvokeOptions.paymasterDetails,
21316
21459
  restInvokeOptions.maxFeeInGasToken
21317
21460
  );
@@ -21355,13 +21498,12 @@ var Contract = class _Contract {
21355
21498
  await this.ensureProvider();
21356
21499
  if (isAccount(this.providerOrAccount)) {
21357
21500
  if (estimateDetails.paymasterDetails) {
21358
- const myCall = {
21359
- contractAddress: this.address,
21360
- entrypoint: method,
21361
- calldata: args
21362
- };
21501
+ assert(
21502
+ typeof this.providerOrAccount.estimatePaymasterTransactionFee === "function",
21503
+ NO_PAYMASTER_MESSAGE
21504
+ );
21363
21505
  return this.providerOrAccount.estimatePaymasterTransactionFee(
21364
- [myCall],
21506
+ [invocation],
21365
21507
  estimateDetails.paymasterDetails
21366
21508
  );
21367
21509
  }
@@ -21733,7 +21875,8 @@ export {
21733
21875
  num_exports as num,
21734
21876
  outsideExecution_exports as outsideExecution,
21735
21877
  parseCalldataField,
21736
- paymaster_exports as paymaster,
21878
+ utils_exports as paymaster,
21879
+ paymasterPlugin,
21737
21880
  provider_exports as provider,
21738
21881
  selector_exports as selector,
21739
21882
  shortString_exports as shortString,