starknet 11.4.1 → 11.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -219,7 +219,8 @@ var starknet = (() => {
219
219
  num: () => num_exports,
220
220
  outsideExecution: () => outsideExecution_exports,
221
221
  parseCalldataField: () => parseCalldataField,
222
- paymaster: () => paymaster_exports,
222
+ paymaster: () => utils_exports2,
223
+ paymasterPlugin: () => paymasterPlugin,
223
224
  provider: () => provider_exports,
224
225
  selector: () => selector_exports,
225
226
  shortString: () => shortString_exports,
@@ -22763,11 +22764,720 @@ ${indent}}` : "}";
22763
22764
  };
22764
22765
  }
22765
22766
 
22767
+ // src/plugins/paymaster/utils.ts
22768
+ var utils_exports2 = {};
22769
+ __export(utils_exports2, {
22770
+ assertCallsAreStrictlyEqual: () => assertCallsAreStrictlyEqual,
22771
+ assertPaymasterTransactionSafety: () => assertPaymasterTransactionSafety,
22772
+ getDefaultPaymasterNodeUrl: () => getDefaultPaymasterNodeUrl
22773
+ });
22774
+
22775
+ // src/utils/outsideExecution.ts
22776
+ var outsideExecution_exports = {};
22777
+ __export(outsideExecution_exports, {
22778
+ buildExecuteFromOutsideCall: () => buildExecuteFromOutsideCall,
22779
+ buildExecuteFromOutsideCallData: () => buildExecuteFromOutsideCallData,
22780
+ getOutsideCall: () => getOutsideCall,
22781
+ getTypedData: () => getTypedData,
22782
+ toOutsideCallV2: () => toOutsideCallV2
22783
+ });
22784
+ function toOutsideCallV2(call) {
22785
+ if ("calldata_len" in call) {
22786
+ return {
22787
+ To: call.to,
22788
+ Selector: call.selector,
22789
+ Calldata: call.calldata
22790
+ };
22791
+ }
22792
+ return call;
22793
+ }
22794
+ function getOutsideCall(call) {
22795
+ const callData = call.calldata ?? [];
22796
+ const callDataCompiled = Array.isArray(callData) && "__compiled__" in callData ? callData : CallData.compile(callData);
22797
+ return {
22798
+ to: call.contractAddress,
22799
+ selector: getSelectorFromName(call.entrypoint),
22800
+ calldata: callDataCompiled
22801
+ };
22802
+ }
22803
+ function callToTypedData(call, version) {
22804
+ const outsideCall = getOutsideCall(call);
22805
+ if (version === "1") {
22806
+ return {
22807
+ ...outsideCall,
22808
+ calldata_len: outsideCall.calldata.length,
22809
+ calldata: outsideCall.calldata
22810
+ };
22811
+ }
22812
+ return {
22813
+ To: outsideCall.to,
22814
+ Selector: outsideCall.selector,
22815
+ Calldata: outsideCall.calldata
22816
+ };
22817
+ }
22818
+ function getDomain(chainId, version) {
22819
+ return {
22820
+ name: "Account.execute_from_outside",
22821
+ version,
22822
+ chainId,
22823
+ ...version === "2" ? { revision: "1" } : {}
22824
+ };
22825
+ }
22826
+ function getTypedData(chainId, options, nonce, myCalls, version) {
22827
+ if (version === "1") {
22828
+ return {
22829
+ types: OutsideExecutionTypesV1,
22830
+ primaryType: "OutsideExecution",
22831
+ domain: getDomain(chainId, version),
22832
+ message: {
22833
+ ...options,
22834
+ nonce,
22835
+ calls_len: myCalls.length,
22836
+ calls: myCalls.map((call) => callToTypedData(call, version))
22837
+ }
22838
+ };
22839
+ }
22840
+ return {
22841
+ types: OutsideExecutionTypesV2,
22842
+ primaryType: "OutsideExecution",
22843
+ domain: getDomain(chainId, version),
22844
+ message: {
22845
+ Caller: options.caller,
22846
+ Nonce: nonce,
22847
+ "Execute After": options.execute_after,
22848
+ "Execute Before": options.execute_before,
22849
+ Calls: myCalls.map((call) => callToTypedData(call, version))
22850
+ }
22851
+ };
22852
+ }
22853
+ function buildExecuteFromOutsideCallData(outsideTransaction) {
22854
+ const execution2 = outsideTransaction.outsideExecution;
22855
+ const formattedSignature = formatSignature(outsideTransaction.signature);
22856
+ return CallData.compile({
22857
+ outside_execution: execution2,
22858
+ signature: formattedSignature
22859
+ });
22860
+ }
22861
+ function buildExecuteFromOutsideCall(outsideTransaction) {
22862
+ const myOutsideTransactions = Array.isArray(outsideTransaction) ? outsideTransaction : [outsideTransaction];
22863
+ const multiCall = myOutsideTransactions.map((outsideTx) => {
22864
+ let entrypoint;
22865
+ if (outsideTx.version === OutsideExecutionVersion.V1) {
22866
+ entrypoint = "execute_from_outside";
22867
+ } else if (outsideTx.version === OutsideExecutionVersion.V2) {
22868
+ entrypoint = "execute_from_outside_v2";
22869
+ } else {
22870
+ throw new Error("Unsupported OutsideExecution version");
22871
+ }
22872
+ return {
22873
+ contractAddress: toHex(outsideTx.signerAddress),
22874
+ entrypoint,
22875
+ calldata: buildExecuteFromOutsideCallData(outsideTx)
22876
+ };
22877
+ });
22878
+ return multiCall;
22879
+ }
22880
+
22881
+ // src/utils/uint256.ts
22882
+ var uint256_exports = {};
22883
+ __export(uint256_exports, {
22884
+ bnToUint256: () => bnToUint256,
22885
+ isUint256: () => isUint256,
22886
+ uint256ToBN: () => uint256ToBN
22887
+ });
22888
+ function uint256ToBN(uint2562) {
22889
+ return new CairoUint256(uint2562).toBigInt();
22890
+ }
22891
+ function isUint256(bn) {
22892
+ return CairoUint256.is(bn);
22893
+ }
22894
+ function bnToUint256(bn) {
22895
+ return new CairoUint256(bn).toUint256HexString();
22896
+ }
22897
+
22898
+ // src/plugins/paymaster/utils.ts
22899
+ var getDefaultPaymasterNodeUrl = (networkName, mute = false) => {
22900
+ if (!mute) {
22901
+ logger.info("Using default public node url, please provide nodeUrl in provider options!");
22902
+ }
22903
+ const nodes = PAYMASTER_RPC_NODES[networkName ?? _NetworkName.SN_SEPOLIA];
22904
+ const randIdx = Math.floor(Math.random() * nodes.length);
22905
+ return nodes[randIdx];
22906
+ };
22907
+ var assertGasFeeFromUnsafeCalls = (unsafeCalls, fees) => {
22908
+ const unsafeCall = toOutsideCallV2(unsafeCalls[unsafeCalls.length - 1]);
22909
+ const unsafeGasTokenCalldata = CallData.toCalldata(unsafeCall.Calldata);
22910
+ const unsafeGasTokenValue = uint256ToBN({
22911
+ low: unsafeGasTokenCalldata[1],
22912
+ high: unsafeGasTokenCalldata[2]
22913
+ });
22914
+ assert(
22915
+ unsafeGasTokenValue === BigInt(fees),
22916
+ "Gas token value is not equal to the provided gas fees"
22917
+ );
22918
+ };
22919
+ var assertGasTokenFromUnsafeCalls = (unsafeCalls, gasToken) => {
22920
+ const unsafeCall = toOutsideCallV2(unsafeCalls[unsafeCalls.length - 1]);
22921
+ assert(
22922
+ BigInt(unsafeCall.To) === BigInt(gasToken),
22923
+ "Gas token address is not equal to the provided gas token"
22924
+ );
22925
+ assert(
22926
+ unsafeCall.Selector === getSelectorFromName("transfer"),
22927
+ "Gas token call selector is not a transfer"
22928
+ );
22929
+ assert(
22930
+ CallData.toCalldata(unsafeCall.Calldata).length === 3,
22931
+ "Gas token transfer calldata does not match the expected recipient/amount shape"
22932
+ );
22933
+ };
22934
+ function assertCallsAreStrictlyEqual(originalCalls, unsafeCalls, isSponsored = false) {
22935
+ const baseError = "Provided calls are not strictly equal to the returned calls";
22936
+ const expectedExtraCalls = isSponsored ? 0 : 1;
22937
+ assert(
22938
+ unsafeCalls.length - expectedExtraCalls === originalCalls.length,
22939
+ `${baseError}: Expected ${originalCalls.length + expectedExtraCalls} calls, got ${unsafeCalls.length}`
22940
+ );
22941
+ for (let callIndex = 0; callIndex < originalCalls.length; callIndex += 1) {
22942
+ const originalCall = originalCalls[callIndex];
22943
+ const unsafeCall = toOutsideCallV2(unsafeCalls[callIndex]);
22944
+ const normalizeAddress = (address) => {
22945
+ return toBigInt(address).toString(16).toLowerCase();
22946
+ };
22947
+ const originalAddress = normalizeAddress(originalCall.contractAddress);
22948
+ const unsafeAddress = normalizeAddress(unsafeCall.To);
22949
+ assert(
22950
+ originalAddress === unsafeAddress,
22951
+ `${baseError}: Contract address mismatch at call ${callIndex}. Expected: ${originalCall.contractAddress}, Got: ${unsafeCall.To}`
22952
+ );
22953
+ assert(
22954
+ getSelectorFromName(originalCall.entrypoint) === unsafeCall.Selector,
22955
+ `${baseError}: Entrypoint mismatch at call ${callIndex}. Expected: ${originalCall.entrypoint}, Got: ${unsafeCall.Selector}`
22956
+ );
22957
+ const originalCalldata = CallData.toCalldata(originalCall.calldata);
22958
+ const unsafeCalldata = CallData.toCalldata(unsafeCall.Calldata);
22959
+ assert(
22960
+ originalCalldata.length === unsafeCalldata.length,
22961
+ `${baseError}: Calldata length mismatch at call ${callIndex}. Expected length: ${originalCalldata.length}, Got length: ${unsafeCalldata.length}`
22962
+ );
22963
+ for (let dataIndex = 0; dataIndex < originalCalldata.length; dataIndex += 1) {
22964
+ const originalValue = BigInt(originalCalldata[dataIndex]);
22965
+ const unsafeValue = BigInt(unsafeCalldata[dataIndex]);
22966
+ assert(
22967
+ originalValue === unsafeValue,
22968
+ `${baseError}: Calldata value mismatch at call ${callIndex}, parameter ${dataIndex}. Expected: ${originalCalldata[dataIndex]}, Got: ${unsafeCalldata[dataIndex]}`
22969
+ );
22970
+ }
22971
+ }
22972
+ }
22973
+ var domainFieldToFelt = (value) => {
22974
+ try {
22975
+ return toBigInt(value);
22976
+ } catch {
22977
+ return CairoBytes31.fromText(String(value)).toBigInt();
22978
+ }
22979
+ };
22980
+ var assertChainIdFromTypedData = (typedData, chainId) => {
22981
+ assert(
22982
+ typedData.domain.chainId !== void 0 && domainFieldToFelt(typedData.domain.chainId) === BigInt(chainId),
22983
+ "Paymaster typed data domain chainId does not match the account's provider chain"
22984
+ );
22985
+ };
22986
+ var assertPaymasterTransactionSafety = (preparedTransaction, calls, paymasterDetails, chainId, maxFeeInGasToken) => {
22987
+ if (preparedTransaction.type === "invoke" || preparedTransaction.type === "deploy_and_invoke") {
22988
+ assertChainIdFromTypedData(preparedTransaction.typed_data, chainId);
22989
+ const { message } = preparedTransaction.typed_data;
22990
+ const hasV1Calls = "calls" in message;
22991
+ const hasV2Calls = "Calls" in message;
22992
+ assert(
22993
+ hasV1Calls !== hasV2Calls,
22994
+ 'Paymaster typed data must declare exactly one of "calls" (SNIP-9 V1) or "Calls" (SNIP-9 V2)'
22995
+ );
22996
+ const unsafeCalls = hasV1Calls ? message.calls : message.Calls;
22997
+ assertCallsAreStrictlyEqual(calls, unsafeCalls, paymasterDetails.feeMode.mode === "sponsored");
22998
+ if (paymasterDetails.feeMode.mode !== "sponsored") {
22999
+ assertGasTokenFromUnsafeCalls(unsafeCalls, paymasterDetails.feeMode.gasToken);
23000
+ assertGasFeeFromUnsafeCalls(
23001
+ unsafeCalls,
23002
+ preparedTransaction.fee.suggested_max_fee_in_gas_token
23003
+ );
23004
+ if (maxFeeInGasToken) {
23005
+ assert(
23006
+ preparedTransaction.fee.suggested_max_fee_in_gas_token <= maxFeeInGasToken,
23007
+ "Gas token price is too high"
23008
+ );
23009
+ }
23010
+ }
23011
+ const msg = message;
23012
+ const version = hasV1Calls ? OutsideExecutionVersion.V1 : OutsideExecutionVersion.V2;
23013
+ const [callerKey, nonceKey, afterKey, beforeKey] = hasV1Calls ? ["caller", "nonce", "execute_after", "execute_before"] : ["Caller", "Nonce", "Execute After", "Execute Before"];
23014
+ assert(
23015
+ [callerKey, nonceKey, afterKey, beforeKey].every((key) => msg[key] !== void 0),
23016
+ "Paymaster typed data does not match the expected outside execution"
23017
+ );
23018
+ const caller = msg[callerKey];
23019
+ const nonce = msg[nonceKey];
23020
+ const executeAfter = msg[afterKey];
23021
+ const executeBefore = msg[beforeKey];
23022
+ if (paymasterDetails.timeBounds) {
23023
+ const requestedAfter = toBigInt(paymasterDetails.timeBounds.executeAfter ?? 1);
23024
+ const requestedBefore = toBigInt(paymasterDetails.timeBounds.executeBefore);
23025
+ assert(
23026
+ toBigInt(executeAfter) >= requestedAfter && toBigInt(executeBefore) <= requestedBefore,
23027
+ "Paymaster typed data execution window is not within the requested time bounds"
23028
+ );
23029
+ }
23030
+ const expectedCalls = [...calls];
23031
+ if (paymasterDetails.feeMode.mode !== "sponsored") {
23032
+ const feeCall = toOutsideCallV2(unsafeCalls[unsafeCalls.length - 1]);
23033
+ const feeRecipient = CallData.toCalldata(feeCall.Calldata)[0];
23034
+ const feeAmount = bnToUint256(preparedTransaction.fee.suggested_max_fee_in_gas_token);
23035
+ expectedCalls.push({
23036
+ contractAddress: paymasterDetails.feeMode.gasToken,
23037
+ entrypoint: "transfer",
23038
+ calldata: [feeRecipient, feeAmount.low, feeAmount.high]
23039
+ });
23040
+ }
23041
+ const expectedTypedData = getTypedData(
23042
+ chainId,
23043
+ { caller, execute_after: executeAfter, execute_before: executeBefore },
23044
+ nonce,
23045
+ expectedCalls,
23046
+ version
23047
+ );
23048
+ assert(
23049
+ getMessageHash(expectedTypedData, 0) === getMessageHash(preparedTransaction.typed_data, 0),
23050
+ "Paymaster typed data does not match the expected outside execution"
23051
+ );
23052
+ }
23053
+ };
23054
+
23055
+ // src/plugins/paymaster/impl.ts
23056
+ var PaymasterImpl = class {
23057
+ /**
23058
+ * Asks the paymaster to build a transaction for the calls of an account.
23059
+ * @param {Account} account The account that will sign the transaction.
23060
+ * @param {Call[]} calls The calls to execute.
23061
+ * @param {PaymasterDetails} paymasterDetails The fee mode, and optionally the deployment data
23062
+ * and the time bounds.
23063
+ * @returns {Promise<PreparedTransaction>} The transaction prepared by the paymaster, with its
23064
+ * typed data to sign and its fees.
23065
+ * @example
23066
+ * ```typescript
23067
+ * const prepared = await PaymasterImpl.build(myAccount, [myCall], {
23068
+ * feeMode: { mode: 'sponsored' },
23069
+ * });
23070
+ * // prepared.type = 'invoke'
23071
+ * ```
23072
+ */
23073
+ static async build(account, calls, paymasterDetails) {
23074
+ if (!paymasterDetails.deploymentData) {
23075
+ const snip9Version = await account.getSnip9Version();
23076
+ if (snip9Version === OutsideExecutionVersion.UNSUPPORTED) {
23077
+ throw Error("Account is not compatible with SNIP-9");
23078
+ }
23079
+ }
23080
+ const parameters = {
23081
+ version: "0x1",
23082
+ feeMode: paymasterDetails.feeMode,
23083
+ timeBounds: paymasterDetails.timeBounds
23084
+ };
23085
+ let transaction;
23086
+ if (paymasterDetails.deploymentData) {
23087
+ if (calls.length > 0) {
23088
+ transaction = {
23089
+ type: "deploy_and_invoke",
23090
+ invoke: { userAddress: account.address, calls },
23091
+ deployment: paymasterDetails.deploymentData
23092
+ };
23093
+ } else {
23094
+ transaction = {
23095
+ type: "deploy",
23096
+ deployment: paymasterDetails.deploymentData
23097
+ };
23098
+ }
23099
+ } else {
23100
+ transaction = {
23101
+ type: "invoke",
23102
+ invoke: { userAddress: account.address, calls }
23103
+ };
23104
+ }
23105
+ return account.paymaster.buildTransaction(transaction, parameters);
23106
+ }
23107
+ /**
23108
+ * Asks the paymaster for the fees of the calls of an account.
23109
+ * @param {Account} account The account that will sign the transaction.
23110
+ * @param {Call[]} calls The calls to execute.
23111
+ * @param {PaymasterDetails} paymasterDetails The fee mode, and optionally the deployment data
23112
+ * and the time bounds.
23113
+ * @returns {Promise<PaymasterFeeEstimate>} The fees, in STRK and in the gas token.
23114
+ * @example
23115
+ * ```typescript
23116
+ * const fees = await PaymasterImpl.estimate(myAccount, [myCall], {
23117
+ * feeMode: { mode: 'default', gasToken: usdcAddress },
23118
+ * });
23119
+ * // fees.suggested_max_fee_in_gas_token is the fee to show to the user
23120
+ * ```
23121
+ */
23122
+ static async estimate(account, calls, paymasterDetails) {
23123
+ const preparedTransaction = await account.buildPaymasterTransaction(calls, paymasterDetails);
23124
+ return preparedTransaction.fee;
23125
+ }
23126
+ /**
23127
+ * Checks that a transaction prepared by the paymaster is safe to sign, then signs it.
23128
+ * @param {Account} account The account that signs the transaction.
23129
+ * @param {PreparedTransaction} preparedTransaction The transaction returned by the paymaster.
23130
+ * @param {Call[]} calls The calls the user requested.
23131
+ * @param {PaymasterDetails} paymasterDetails The fee mode and related paymaster details.
23132
+ * @param {BigNumberish} [maxFeeInGasToken] Optional user-approved ceiling on the gas-token fee.
23133
+ * @returns {Promise<ExecutableUserTransaction>} The transaction to send to the paymaster.
23134
+ * @example
23135
+ * ```typescript
23136
+ * const prepared = await PaymasterImpl.build(myAccount, [myCall], paymasterDetails);
23137
+ * const executable = await PaymasterImpl.prepare(myAccount, prepared, [myCall], paymasterDetails);
23138
+ * // executable.type = 'invoke'
23139
+ * ```
23140
+ */
23141
+ static async prepare(account, preparedTransaction, calls, paymasterDetails, maxFeeInGasToken) {
23142
+ assertPaymasterTransactionSafety(
23143
+ preparedTransaction,
23144
+ calls,
23145
+ paymasterDetails,
23146
+ await account.provider.getChainId(),
23147
+ maxFeeInGasToken
23148
+ );
23149
+ let transaction;
23150
+ switch (preparedTransaction.type) {
23151
+ case "deploy_and_invoke": {
23152
+ const signature = await account.signMessage(preparedTransaction.typed_data);
23153
+ transaction = {
23154
+ type: "deploy_and_invoke",
23155
+ invoke: {
23156
+ userAddress: account.address,
23157
+ typedData: preparedTransaction.typed_data,
23158
+ signature: signatureToHexArray(signature)
23159
+ },
23160
+ deployment: preparedTransaction.deployment
23161
+ };
23162
+ break;
23163
+ }
23164
+ case "invoke": {
23165
+ const signature = await account.signMessage(preparedTransaction.typed_data);
23166
+ transaction = {
23167
+ type: "invoke",
23168
+ invoke: {
23169
+ userAddress: account.address,
23170
+ typedData: preparedTransaction.typed_data,
23171
+ signature: signatureToHexArray(signature)
23172
+ }
23173
+ };
23174
+ break;
23175
+ }
23176
+ case "deploy": {
23177
+ transaction = {
23178
+ type: "deploy",
23179
+ deployment: preparedTransaction.deployment
23180
+ };
23181
+ break;
23182
+ }
23183
+ default:
23184
+ throw Error("Invalid transaction type");
23185
+ }
23186
+ return transaction;
23187
+ }
23188
+ /**
23189
+ * Builds, checks, signs and sends a paymaster transaction for the calls of an account.
23190
+ * @param {Account} account The account that signs the transaction.
23191
+ * @param {Call[]} calls The calls to execute.
23192
+ * @param {PaymasterDetails} paymasterDetails The fee mode, and optionally the deployment data
23193
+ * and the time bounds.
23194
+ * @param {BigNumberish} [maxFeeInGasToken] Optional user-approved ceiling on the gas-token fee.
23195
+ * @returns {Promise<InvokeFunctionResponse>} The hash of the transaction sent by the paymaster.
23196
+ * @example
23197
+ * ```typescript
23198
+ * const { transaction_hash } = await PaymasterImpl.execute(myAccount, [myCall], {
23199
+ * feeMode: { mode: 'sponsored' },
23200
+ * });
23201
+ * await myAccount.provider.waitForTransaction(transaction_hash);
23202
+ * ```
23203
+ */
23204
+ static async execute(account, calls, paymasterDetails, maxFeeInGasToken) {
23205
+ const preparedTransaction = await account.buildPaymasterTransaction(calls, paymasterDetails);
23206
+ const transaction = await account.preparePaymasterTransaction(
23207
+ preparedTransaction,
23208
+ calls,
23209
+ paymasterDetails,
23210
+ maxFeeInGasToken
23211
+ );
23212
+ return account.paymaster.executeTransaction(transaction, preparedTransaction.parameters).then((response) => ({ transaction_hash: response.transaction_hash }));
23213
+ }
23214
+ };
23215
+
23216
+ // src/plugins/paymaster/rpc.ts
23217
+ var convertCalls = (calls) => calls.map((call) => ({
23218
+ to: call.contractAddress,
23219
+ selector: getSelectorFromName(call.entrypoint),
23220
+ calldata: CallData.toHex(call.calldata)
23221
+ }));
23222
+ var convertFeeMode = (feeMode) => {
23223
+ if (feeMode.mode === "sponsored") {
23224
+ return { mode: "sponsored" };
23225
+ }
23226
+ return { mode: "default", gas_token: feeMode.gasToken };
23227
+ };
23228
+ var convertFEE_MODE = (feeMode) => {
23229
+ if (feeMode.mode === "sponsored") {
23230
+ return { mode: "sponsored" };
23231
+ }
23232
+ return { mode: "default", gasToken: feeMode.gas_token };
23233
+ };
23234
+ var convertTimeBounds = (timeBounds) => timeBounds ? {
23235
+ execute_after: timeBounds.executeAfter || 1,
23236
+ // If executeAfter is not provided, set it to 1, meaning the transaction can be executed immediately
23237
+ execute_before: timeBounds.executeBefore
23238
+ } : void 0;
23239
+ var convertTIME_BOUNDS = (timeBounds) => timeBounds ? {
23240
+ executeAfter: timeBounds.execute_after,
23241
+ executeBefore: timeBounds.execute_before
23242
+ } : void 0;
23243
+ var convertEXECUTION_PARAMETERS = (parameters) => ({
23244
+ version: parameters.version,
23245
+ feeMode: convertFEE_MODE(parameters.fee_mode),
23246
+ timeBounds: convertTIME_BOUNDS(parameters.time_bounds)
23247
+ });
23248
+ var defaultOptions = {
23249
+ headers: { "Content-Type": "application/json" }
23250
+ };
23251
+ var PaymasterRpc = class _PaymasterRpc {
23252
+ nodeUrl;
23253
+ headers;
23254
+ baseFetch;
23255
+ requestId;
23256
+ constructor(options) {
23257
+ if (options instanceof _PaymasterRpc) {
23258
+ this.nodeUrl = options.nodeUrl;
23259
+ this.headers = { ...defaultOptions.headers, ...options.headers };
23260
+ this.baseFetch = options.baseFetch;
23261
+ this.requestId = options.requestId;
23262
+ return;
23263
+ }
23264
+ if (options && "nodeUrl" in options && "headers" in options && "baseFetch" in options) {
23265
+ this.nodeUrl = options.nodeUrl ?? getDefaultPaymasterNodeUrl(void 0);
23266
+ this.headers = { ...defaultOptions.headers, ...options.headers };
23267
+ this.baseFetch = options.baseFetch ?? fetch_default;
23268
+ this.requestId = 0;
23269
+ return;
23270
+ }
23271
+ const { nodeUrl, headers, baseFetch } = options || {};
23272
+ if (nodeUrl && Object.values(_NetworkName).includes(nodeUrl)) {
23273
+ this.nodeUrl = getDefaultPaymasterNodeUrl(nodeUrl, options?.mute);
23274
+ } else if (nodeUrl) {
23275
+ this.nodeUrl = nodeUrl;
23276
+ } else {
23277
+ this.nodeUrl = getDefaultPaymasterNodeUrl(void 0, options?.mute);
23278
+ }
23279
+ this.baseFetch = baseFetch ?? fetch_default;
23280
+ this.headers = { ...defaultOptions.headers, ...headers };
23281
+ this.requestId = 0;
23282
+ }
23283
+ fetch(method, params, id = 0) {
23284
+ const rpcRequestBody = {
23285
+ id,
23286
+ jsonrpc: "2.0",
23287
+ method,
23288
+ ...params && { params }
23289
+ };
23290
+ return this.baseFetch(this.nodeUrl, {
23291
+ method: "POST",
23292
+ body: stringify2(rpcRequestBody),
23293
+ headers: this.headers
23294
+ });
23295
+ }
23296
+ errorHandler(method, params, rpcError, otherError) {
23297
+ if (rpcError) {
23298
+ throw new RpcError(rpcError, method, params);
23299
+ }
23300
+ if (otherError instanceof LibraryError) {
23301
+ throw otherError;
23302
+ }
23303
+ if (otherError) {
23304
+ throw Error(otherError.message);
23305
+ }
23306
+ }
23307
+ async fetchEndpoint(method, params) {
23308
+ try {
23309
+ this.requestId += 1;
23310
+ const rawResult = await this.fetch(method, params, this.requestId);
23311
+ const { error, result } = await rawResult.json();
23312
+ this.errorHandler(method, params, error);
23313
+ return result;
23314
+ } catch (error) {
23315
+ this.errorHandler(method, params, error?.response?.data, error);
23316
+ throw error;
23317
+ }
23318
+ }
23319
+ async isAvailable() {
23320
+ return this.fetchEndpoint("paymaster_isAvailable");
23321
+ }
23322
+ async buildTransaction(transaction, parameters) {
23323
+ let userTransaction;
23324
+ switch (transaction.type) {
23325
+ case "invoke":
23326
+ userTransaction = {
23327
+ ...transaction,
23328
+ invoke: {
23329
+ user_address: transaction.invoke.userAddress,
23330
+ calls: convertCalls(transaction.invoke.calls)
23331
+ }
23332
+ };
23333
+ break;
23334
+ case "deploy_and_invoke":
23335
+ userTransaction = {
23336
+ ...transaction,
23337
+ invoke: {
23338
+ user_address: transaction.invoke.userAddress,
23339
+ calls: convertCalls(transaction.invoke.calls)
23340
+ }
23341
+ };
23342
+ break;
23343
+ case "deploy":
23344
+ default:
23345
+ userTransaction = transaction;
23346
+ break;
23347
+ }
23348
+ const executionParameters = {
23349
+ version: parameters.version,
23350
+ fee_mode: convertFeeMode(parameters.feeMode),
23351
+ time_bounds: convertTimeBounds(parameters.timeBounds)
23352
+ };
23353
+ const response = await this.fetchEndpoint("paymaster_buildTransaction", {
23354
+ transaction: userTransaction,
23355
+ parameters: executionParameters
23356
+ });
23357
+ const fee = {
23358
+ gas_token_price_in_strk: BigInt(response.fee.gas_token_price_in_strk),
23359
+ estimated_fee_in_strk: BigInt(response.fee.estimated_fee_in_strk),
23360
+ estimated_fee_in_gas_token: BigInt(response.fee.estimated_fee_in_gas_token),
23361
+ suggested_max_fee_in_strk: BigInt(response.fee.suggested_max_fee_in_strk),
23362
+ suggested_max_fee_in_gas_token: BigInt(response.fee.suggested_max_fee_in_gas_token)
23363
+ };
23364
+ switch (response.type) {
23365
+ case "invoke":
23366
+ return {
23367
+ type: "invoke",
23368
+ typed_data: response.typed_data,
23369
+ parameters: convertEXECUTION_PARAMETERS(response.parameters),
23370
+ fee
23371
+ };
23372
+ case "deploy_and_invoke":
23373
+ return {
23374
+ type: "deploy_and_invoke",
23375
+ deployment: response.deployment,
23376
+ typed_data: response.typed_data,
23377
+ parameters: convertEXECUTION_PARAMETERS(response.parameters),
23378
+ fee
23379
+ };
23380
+ case "deploy":
23381
+ default:
23382
+ return {
23383
+ type: "deploy",
23384
+ deployment: response.deployment,
23385
+ parameters: convertEXECUTION_PARAMETERS(response.parameters),
23386
+ fee
23387
+ };
23388
+ }
23389
+ }
23390
+ async executeTransaction(transaction, parameters) {
23391
+ let user_transaction;
23392
+ switch (transaction.type) {
23393
+ case "invoke":
23394
+ user_transaction = {
23395
+ ...transaction,
23396
+ invoke: {
23397
+ user_address: transaction.invoke.userAddress,
23398
+ typed_data: transaction.invoke.typedData,
23399
+ signature: signatureToHexArray(transaction.invoke.signature)
23400
+ }
23401
+ };
23402
+ break;
23403
+ case "deploy_and_invoke":
23404
+ user_transaction = {
23405
+ ...transaction,
23406
+ invoke: {
23407
+ user_address: transaction.invoke.userAddress,
23408
+ typed_data: transaction.invoke.typedData,
23409
+ signature: signatureToHexArray(transaction.invoke.signature)
23410
+ }
23411
+ };
23412
+ break;
23413
+ case "deploy":
23414
+ default:
23415
+ user_transaction = transaction;
23416
+ break;
23417
+ }
23418
+ const executionParameters = {
23419
+ version: parameters.version,
23420
+ fee_mode: convertFeeMode(parameters.feeMode),
23421
+ time_bounds: convertTimeBounds(parameters.timeBounds)
23422
+ };
23423
+ return this.fetchEndpoint("paymaster_executeTransaction", {
23424
+ transaction: user_transaction,
23425
+ parameters: executionParameters
23426
+ });
23427
+ }
23428
+ async getSupportedTokens() {
23429
+ return this.fetchEndpoint("paymaster_getSupportedTokens").then(
23430
+ (tokens) => tokens.map((token) => ({
23431
+ token_address: token.token_address,
23432
+ decimals: token.decimals,
23433
+ priceInStrk: BigInt(token.price_in_strk)
23434
+ }))
23435
+ );
23436
+ }
23437
+ };
23438
+
23439
+ // src/plugins/paymaster/interface.ts
23440
+ var PaymasterInterface = class {
23441
+ };
23442
+
23443
+ // src/plugins/paymaster/index.ts
23444
+ var PAYMASTER_PLUGIN_NAME = "paymaster";
23445
+ function paymasterPlugin(options) {
23446
+ return {
23447
+ name: PAYMASTER_PLUGIN_NAME,
23448
+ accountExtend(account) {
23449
+ const target = account;
23450
+ const members = {
23451
+ paymaster: options ? new PaymasterRpc(options) : new PaymasterRpc({ mute: true }),
23452
+ buildPaymasterTransaction: (calls, paymasterDetails) => PaymasterImpl.build(target, calls, paymasterDetails),
23453
+ estimatePaymasterTransactionFee: (calls, paymasterDetails) => PaymasterImpl.estimate(target, calls, paymasterDetails),
23454
+ preparePaymasterTransaction: (preparedTransaction, calls, paymasterDetails, maxFeeInGasToken) => PaymasterImpl.prepare(
23455
+ target,
23456
+ preparedTransaction,
23457
+ calls,
23458
+ paymasterDetails,
23459
+ maxFeeInGasToken
23460
+ ),
23461
+ executePaymasterTransaction: (calls, paymasterDetails, maxFeeInGasToken) => PaymasterImpl.execute(target, calls, paymasterDetails, maxFeeInGasToken)
23462
+ };
23463
+ return Object.fromEntries(
23464
+ Object.entries(members).filter(([name]) => !(name in account))
23465
+ );
23466
+ }
23467
+ };
23468
+ }
23469
+ function applyPaymasterOption(plugins, paymaster) {
23470
+ if (!paymaster) return plugins;
23471
+ const configured = paymasterPlugin(paymaster);
23472
+ return plugins.some((plugin) => plugin.name === PAYMASTER_PLUGIN_NAME) ? plugins.map((plugin) => plugin.name === PAYMASTER_PLUGIN_NAME ? configured : plugin) : [...plugins, configured];
23473
+ }
23474
+
22766
23475
  // src/plugins/defaults.ts
22767
23476
  var defaultPlugins = [
22768
23477
  starknetId(),
22769
23478
  brotherId(),
22770
- fastExecute()
23479
+ fastExecute(),
23480
+ paymasterPlugin()
22771
23481
  ];
22772
23482
 
22773
23483
  // src/provider/rpc.ts
@@ -23338,23 +24048,6 @@ ${indent}}` : "}";
23338
24048
  }
23339
24049
  };
23340
24050
 
23341
- // src/utils/uint256.ts
23342
- var uint256_exports = {};
23343
- __export(uint256_exports, {
23344
- bnToUint256: () => bnToUint256,
23345
- isUint256: () => isUint256,
23346
- uint256ToBN: () => uint256ToBN
23347
- });
23348
- function uint256ToBN(uint2562) {
23349
- return new CairoUint256(uint2562).toBigInt();
23350
- }
23351
- function isUint256(bn) {
23352
- return CairoUint256.is(bn);
23353
- }
23354
- function bnToUint256(bn) {
23355
- return new CairoUint256(bn).toUint256HexString();
23356
- }
23357
-
23358
24051
  // src/signer/ethSigner.ts
23359
24052
  var EthSigner = class {
23360
24053
  pk;
@@ -23505,262 +24198,58 @@ ${indent}}` : "}";
23505
24198
  * ```
23506
24199
  */
23507
24200
  async getPubKey() {
23508
- if (!this.pubKey) await this.getPublicKeys();
23509
- return this.pubKey;
23510
- }
23511
- /**
23512
- * provides the full public key (with parity prefix)
23513
- * @returns an hex string : 2 first characters are the parity, the 64 following characters are Point X coordinate. 64 last characters are Point Y coordinate.
23514
- * @example
23515
- * ```typescript
23516
- * const result = await myLedgerSigner.getFullPubKey();
23517
- * // result= "0x0403681417ba3e1f050dd3ccdceb8d22b5e44fa70ee7844d472c6a768bded5174e03cbc86f805dcfcb0c1922dd4daf181afa289d86223a18bc856276615bcc7787"
23518
- * ```
23519
- */
23520
- async getFullPubKey() {
23521
- if (!this.fullPubKey) await this.getPublicKeys();
23522
- return this.fullPubKey;
23523
- }
23524
- /**
23525
- * Returns the version of the Starknet APP implemented in the Ledger.
23526
- * @returns {string} version.
23527
- * @example
23528
- * ```typescript
23529
- * const result = await myLedgerSigner.getAppVersion();
23530
- * // result= "1.1.1"
23531
- * ```
23532
- */
23533
- async getAppVersion() {
23534
- if (!this.appVersion) {
23535
- const resp = await this._transporter.send(Number("0x5a"), 0, 0, 0);
23536
- this.appVersion = `${resp[0]}.${resp[1]}.${resp[2]}`;
23537
- }
23538
- return this.appVersion;
23539
- }
23540
- /**
23541
- * Sign a TypedData message (SNIP-12) in a Ledger.
23542
- * @param {typedDataToHash} typedDataToHash A TypedData message compatible with SNIP-12.
23543
- * @param {string} accountAddress Signer account address (Hex or num string)
23544
- * @returns {Signature} The signed message.
23545
- * @example
23546
- * ```typescript
23547
- * const result = myLedgerSigner.signMessage(snip12Message, account0.address);
23548
- * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
23549
- * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
23550
- * // recovery: 0}
23551
- * ```
23552
- */
23553
- async signMessage(typedDataToHash, accountAddress) {
23554
- const msgHash = getMessageHash(typedDataToHash, accountAddress);
23555
- return this.signRaw(msgHash);
23556
- }
23557
- /**
23558
- * Sign in a Ledger a V3 transaction. This is a blind sign on the Ledger screen.
23559
- * @param {Call1[]} transactions An array of `Call` transactions (generated for example by `myContract.populate()`).
23560
- * @param {InvocationsSignerDetails} transactionsDetail An object that includes all the necessary inputs to hash the transaction.
23561
- * @returns {Signature} The signed transaction.
23562
- * @example
23563
- * ```typescript
23564
- * const txDetailsV3: V3InvocationsSignerDetails = {
23565
- * chainId: constants.StarknetChainId.SN_MAIN,
23566
- * nonce: "28",
23567
- * accountDeploymentData: [],
23568
- * paymasterData: [],
23569
- * cairoVersion: "1",
23570
- * feeDataAvailabilityMode: "L1",
23571
- * nonceDataAvailabilityMode: "L1",
23572
- * resourceBounds: {
23573
- * l1_gas: {
23574
- * max_amount: "0x2a00",
23575
- * max_price_per_unit: "0x5c00000"
23576
- * },
23577
- * l2_gas: {
23578
- * max_amount: "0x00",
23579
- * max_price_per_unit: "0x00"
23580
- * },
23581
- * },
23582
- * tip: 0,
23583
- * version: "0x3",
23584
- * walletAddress: account0.address
23585
- * }
23586
- * const result = myLedgerSigner.signTransaction([call0, call1], txDetailsV3);
23587
- * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
23588
- * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
23589
- * // recovery: 0}
23590
- * ```
23591
- */
23592
- async signTransaction(transactions, transactionsDetail) {
23593
- const compiledCalldata = getExecuteCalldata(transactions, transactionsDetail.cairoVersion);
23594
- const msgHash = calculateInvokeTransactionHash2({
23595
- ...transactionsDetail,
23596
- senderAddress: transactionsDetail.walletAddress,
23597
- compiledCalldata,
23598
- version: transactionsDetail.version,
23599
- nonceDataAvailabilityMode: intDAM(transactionsDetail.nonceDataAvailabilityMode),
23600
- feeDataAvailabilityMode: intDAM(transactionsDetail.feeDataAvailabilityMode)
23601
- });
23602
- return this.signRaw(msgHash);
23603
- }
23604
- /**
23605
- * Sign in a Ledger the deployment of a new account. This is a blind sign on the Ledger screen.
23606
- * @param {DeployAccountSignerDetails} details An object that includes all necessary data to calculate the Hash.
23607
- * @returns {Signature} The deploy account signature.
23608
- * @example
23609
- * ```typescript
23610
- * const result = myLedgerSigner.signDeployAccountTransaction(details);
23611
- * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
23612
- * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
23613
- * // recovery: 0}
23614
- * ```
23615
- */
23616
- async signDeployAccountTransaction(details) {
23617
- const compiledConstructorCalldata = CallData.compile(details.constructorCalldata);
23618
- const msgHash = calculateDeployAccountTransactionHash2({
23619
- ...details,
23620
- salt: details.addressSalt,
23621
- compiledConstructorCalldata,
23622
- version: details.version,
23623
- nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
23624
- feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
23625
- });
23626
- return this.signRaw(msgHash);
23627
- }
23628
- /**
23629
- * Sign in a Ledger the declaration of a new class. This is a blind sign on the Ledger screen.
23630
- * @param {DeclareSignerDetails} details An object that includes all necessary data to calculate the Hash.
23631
- * @returns {Signature} The declare Signature.
23632
- * @example
23633
- * ```typescript
23634
- * const result = myLedgerSigner.signDeclareTransaction(details);
23635
- * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
23636
- * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
23637
- * // recovery: 0}
23638
- * ```
23639
- */
23640
- async signDeclareTransaction(details) {
23641
- const msgHash = calculateDeclareTransactionHash2({
23642
- ...details,
23643
- version: details.version,
23644
- nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
23645
- feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
23646
- });
23647
- return this.signRaw(msgHash);
23648
- }
23649
- /**
23650
- * Internal function to sign a hash in a Ledger Nano.
23651
- * This is a blind sign in the Ledger ; no display of what you are signing.
23652
- */
23653
- async signRaw(msgHash) {
23654
- addHexPrefix(
23655
- buf2hex(await this._transporter.send(Number("0x5a"), 2, 0, 0, buffer_default.from(this.pathBuffer)))
23656
- );
23657
- const shiftedHash = toHex(BigInt(msgHash) << 4n);
23658
- const buff2 = hexToBytes3(shiftedHash);
23659
- const respSign2 = Uint8Array.from(
23660
- await this._transporter.send(Number("0x5a"), 2, 1, 0, buffer_default.from(buff2))
23661
- );
23662
- const r = BigInt(addHexPrefix(buf2hex(respSign2.subarray(1, 33))));
23663
- const s = BigInt(addHexPrefix(buf2hex(respSign2.subarray(33, 65))));
23664
- const v = respSign2[65];
23665
- const sign0 = new starknet_exports.Signature(r, s);
23666
- const sign1 = sign0.addRecoveryBit(v);
23667
- return sign1;
23668
- }
23669
- /** internal function to get both the Starknet public key and the full public key */
23670
- async getPublicKeys() {
23671
- const pathBuff = this.pathBuffer;
23672
- const respGetPublic = Uint8Array.from(
23673
- await this._transporter.send(Number("0x5a"), 1, 0, 0, buffer_default.from(pathBuff))
23674
- );
23675
- this.pubKey = addHexPrefix(buf2hex(respGetPublic.subarray(1, 33)));
23676
- this.fullPubKey = addHexPrefix(buf2hex(respGetPublic.subarray(0, 65)));
23677
- }
23678
- };
23679
- function getLedgerPathBuffer111(accountId, applicationName = "LedgerW") {
23680
- const path0buff = new Uint8Array([128, 0, 10, 85]);
23681
- const path1buff = new Uint8Array([71, 65, 233, 201]);
23682
- const path2buff = applicationName === "LedgerW" ? new Uint8Array([43, 206, 231, 219]) : stringToSha256ToArrayBuff4(applicationName);
23683
- const path3buff = new Uint8Array([0, 0, 0, 0]);
23684
- const hex = toHex(accountId);
23685
- const padded = addHexPrefix(removeHexPrefix(hex).padStart(8, "0"));
23686
- const path4buff = hexToBytes3(padded);
23687
- const path5buff = new Uint8Array([0, 0, 0, 0]);
23688
- const pathBuff = concatenateArrayBuffer([
23689
- path0buff,
23690
- path1buff,
23691
- path2buff,
23692
- path3buff,
23693
- path4buff,
23694
- path5buff
23695
- ]);
23696
- return pathBuff;
23697
- }
23698
-
23699
- // src/utils/address.ts
23700
- function addAddressPadding(address) {
23701
- const hex = toHex(isString(address) ? addHexPrefix(address) : address);
23702
- const padded = removeHexPrefix(hex).padStart(64, "0");
23703
- return addHexPrefix(padded);
23704
- }
23705
- function validateAndParseAddress(address) {
23706
- if (isString(address) && !/^(0x)?[0-9a-f]+$/i.test(address)) {
23707
- throw new Error("Invalid Address Format");
23708
- }
23709
- const result = addAddressPadding(address);
23710
- if (!result.match(/^(0x)?[0-9a-fA-F]{64}$/)) {
23711
- throw new Error("Invalid Address Format");
23712
- }
23713
- assertInRange(result, ZERO, ADDR_BOUND - 1n, "Starknet Address");
23714
- return result;
23715
- }
23716
- function getChecksumAddress(address) {
23717
- const chars = removeHexPrefix(validateAndParseAddress(address)).toLowerCase().split("");
23718
- const hex = removeHexPrefix(keccakBn(address));
23719
- const hashed = hexToBytes2(hex.padStart(64, "0"));
23720
- for (let i = 0; i < chars.length; i += 2) {
23721
- if (hashed[i >> 1] >> 4 >= 8) {
23722
- chars[i] = chars[i].toUpperCase();
23723
- }
23724
- if ((hashed[i >> 1] & 15) >= 8) {
23725
- chars[i + 1] = chars[i + 1].toUpperCase();
23726
- }
24201
+ if (!this.pubKey) await this.getPublicKeys();
24202
+ return this.pubKey;
23727
24203
  }
23728
- return addHexPrefix(chars.join(""));
23729
- }
23730
- function validateChecksumAddress(address) {
23731
- return getChecksumAddress(address) === address;
23732
- }
23733
-
23734
- // src/signer/ledgerSigner221.ts
23735
- var LedgerSigner221 = class extends LedgerSigner111 {
23736
24204
  /**
23737
- * constructor of the LedgerSigner class.
23738
- * @param {Transport} transport 5 transports are available to handle USB, bluetooth, Node, Web, Mobile.
23739
- * See Guides for more details.
23740
- * @param {number} accountID ID of Ledger Nano (can handle 2**31 accounts).
23741
- * @param {string} [eip2645application='LedgerW'] A wallet is defined by an ERC2645 derivation path (6 items).
23742
- * One item is called `application` and can be customized.
23743
- * Default value is `LedgerW`.
23744
- * @param {LedgerPathCalculation} [pathFunction=getLedgerPathBuffer221]
23745
- * defines the function that will calculate the path. By default `getLedgerPathBuffer221` is selected.
23746
- *
23747
- * If you are using APP v2.2.1 with an account created with the v1.1.1, you need to use :
24205
+ * provides the full public key (with parity prefix)
24206
+ * @returns an hex string : 2 first characters are the parity, the 64 following characters are Point X coordinate. 64 last characters are Point Y coordinate.
24207
+ * @example
23748
24208
  * ```typescript
23749
- * const myLedgerSigner = new LedgerSigner221(myNodeTransport, 0, undefined, getLedgerPathBuffer111);
24209
+ * const result = await myLedgerSigner.getFullPubKey();
24210
+ * // result= "0x0403681417ba3e1f050dd3ccdceb8d22b5e44fa70ee7844d472c6a768bded5174e03cbc86f805dcfcb0c1922dd4daf181afa289d86223a18bc856276615bcc7787"
23750
24211
  * ```
24212
+ */
24213
+ async getFullPubKey() {
24214
+ if (!this.fullPubKey) await this.getPublicKeys();
24215
+ return this.fullPubKey;
24216
+ }
24217
+ /**
24218
+ * Returns the version of the Starknet APP implemented in the Ledger.
24219
+ * @returns {string} version.
23751
24220
  * @example
23752
24221
  * ```typescript
23753
- * import TransportNodeHid from "@ledgerhq/hw-transport-node-hid";
23754
- * const myNodeTransport = await TransportNodeHid.create();
23755
- * const myLedgerSigner = new LedgerSigner221(myNodeTransport, 0);
24222
+ * const result = await myLedgerSigner.getAppVersion();
24223
+ * // result= "1.1.1"
23756
24224
  * ```
23757
24225
  */
23758
- constructor(transport, accountID, eip2645application = "LedgerW", pathFunction = getLedgerPathBuffer221) {
23759
- super(transport, accountID, eip2645application, pathFunction);
24226
+ async getAppVersion() {
24227
+ if (!this.appVersion) {
24228
+ const resp = await this._transporter.send(Number("0x5a"), 0, 0, 0);
24229
+ this.appVersion = `${resp[0]}.${resp[1]}.${resp[2]}`;
24230
+ }
24231
+ return this.appVersion;
23760
24232
  }
23761
24233
  /**
23762
- * Sign in a Ledger a V3 transaction. The details are displayed on the Ledger screen.
23763
- * @param {Call[]} transactions An array of `Call` transactions (generated for example by `myContract.populate()`).
24234
+ * Sign a TypedData message (SNIP-12) in a Ledger.
24235
+ * @param {typedDataToHash} typedDataToHash A TypedData message compatible with SNIP-12.
24236
+ * @param {string} accountAddress Signer account address (Hex or num string)
24237
+ * @returns {Signature} The signed message.
24238
+ * @example
24239
+ * ```typescript
24240
+ * const result = myLedgerSigner.signMessage(snip12Message, account0.address);
24241
+ * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
24242
+ * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
24243
+ * // recovery: 0}
24244
+ * ```
24245
+ */
24246
+ async signMessage(typedDataToHash, accountAddress) {
24247
+ const msgHash = getMessageHash(typedDataToHash, accountAddress);
24248
+ return this.signRaw(msgHash);
24249
+ }
24250
+ /**
24251
+ * Sign in a Ledger a V3 transaction. This is a blind sign on the Ledger screen.
24252
+ * @param {Call1[]} transactions An array of `Call` transactions (generated for example by `myContract.populate()`).
23764
24253
  * @param {InvocationsSignerDetails} transactionsDetail An object that includes all the necessary inputs to hash the transaction.
23765
24254
  * @returns {Signature} The signed transaction.
23766
24255
  * @example
@@ -23783,293 +24272,109 @@ ${indent}}` : "}";
23783
24272
  * max_price_per_unit: "0x00"
23784
24273
  * },
23785
24274
  * },
23786
- * tip: 0,
23787
- * version: "0x3",
23788
- * walletAddress: account0.address
23789
- * }
23790
- * const result = myLedgerSigner.signTransaction([call0, call1], txDetailsV3);
23791
- * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
23792
- * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
23793
- * // recovery: 0}
23794
- * ```
23795
- */
23796
- async signTransaction(transactions, transactionsDetail) {
23797
- const compiledCalldata = getExecuteCalldata(transactions, transactionsDetail.cairoVersion);
23798
- const msgHash = calculateInvokeTransactionHash2({
23799
- ...transactionsDetail,
23800
- senderAddress: transactionsDetail.walletAddress,
23801
- compiledCalldata,
23802
- version: transactionsDetail.version,
23803
- nonceDataAvailabilityMode: intDAM(transactionsDetail.nonceDataAvailabilityMode),
23804
- feeDataAvailabilityMode: intDAM(transactionsDetail.feeDataAvailabilityMode)
23805
- });
23806
- const ledgerResponse = await this.signTxV3(transactionsDetail, transactions);
23807
- assert(
23808
- toBigInt(msgHash) === ledgerResponse.hash,
23809
- "The V3 transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
23810
- );
23811
- return ledgerResponse.signature;
23812
- }
23813
- /**
23814
- * Sign in a Ledger the deployment of a new account. The details are displayed on the Ledger screen.
23815
- * @param {DeployAccountSignerDetails} details An object that includes all necessary data to calculate the Hash.
23816
- * @returns {Signature} The deploy account signature.
23817
- * @example
23818
- * ```typescript
23819
- * const result = myLedgerSigner.signDeployAccountTransaction(details);
23820
- * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
23821
- * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
23822
- * // recovery: 0}
23823
- * ```
23824
- */
23825
- async signDeployAccountTransaction(details) {
23826
- const compiledConstructorCalldata = CallData.compile(details.constructorCalldata);
23827
- const msgHash = calculateDeployAccountTransactionHash2({
23828
- ...details,
23829
- salt: details.addressSalt,
23830
- compiledConstructorCalldata,
23831
- version: details.version,
23832
- nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
23833
- feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
23834
- });
23835
- const ledgerResponse = await this.signDeployAccountV3(details);
23836
- assert(
23837
- toBigInt(msgHash) === ledgerResponse.hash,
23838
- "The transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
23839
- );
23840
- return ledgerResponse.signature;
23841
- }
23842
- /**
23843
- * Internal function to convert a bigNumberish to an Uint8array of 256 bits
23844
- * @param {BigNumberish} input input value
23845
- * @returns {Uint8Array} a Uint8Array containing 32 bytes.
23846
- */
23847
- convertBnToLedger(input) {
23848
- return hexToBytes3(addAddressPadding(toHex(input)));
23849
- }
23850
- /**
23851
- * Internal function to decode the response of the Ledger signature
23852
- * @param {Uint8Array} respSign the Buffer response of the Ledger
23853
- * @returns { hash: bigint; signature: Signature } transaction hash & signature
23854
- */
23855
- decodeSignatureLedger(respSign) {
23856
- const h = BigInt(addHexPrefix(buf2hex(respSign.subarray(0, 32))));
23857
- const r = BigInt(addHexPrefix(buf2hex(respSign.subarray(33, 65))));
23858
- const s = BigInt(addHexPrefix(buf2hex(respSign.subarray(65, 97))));
23859
- const v = respSign[97];
23860
- const sign0 = new starknet_exports.Signature(r, s);
23861
- const sign1 = sign0.addRecoveryBit(v);
23862
- return { hash: h, signature: sign1 };
23863
- }
23864
- /** Internal function to convert a Call to an array of Uint8Array.
23865
- * @param {Call} call A Call to convert.
23866
- * @return {Uint8Array[]} Call encoded in an array of Uint8Array (each containing 7 u256).
23867
- */
23868
- encodeCall(call) {
23869
- const toBuf = this.convertBnToLedger(call.contractAddress);
23870
- const selectorBuf = hexToBytes3(addAddressPadding(getSelector(call.entrypoint)));
23871
- let calldataBuf = new Uint8Array([]);
23872
- if (call.calldata) {
23873
- const compiledCalldata = CallData.compile(call.calldata);
23874
- calldataBuf = concatenateArrayBuffer(
23875
- compiledCalldata.map((parameter) => {
23876
- const a = this.convertBnToLedger(parameter);
23877
- return a;
23878
- })
23879
- );
23880
- }
23881
- const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
23882
- const calldatas = [];
23883
- const chunkSize = 7 * 32;
23884
- for (let i = 0; i < callBuf.length; i += chunkSize)
23885
- calldatas.push(callBuf.subarray(i, i + chunkSize));
23886
- return calldatas;
23887
- }
23888
- /**
23889
- * Ask to the Ledger Nano to display and sign a Starknet V3 transaction.
23890
- * @param {V3InvocationsSignerDetails} txDetails All the details needed for a txV3.
23891
- * @param {Call[]} calls array of Starknet invocations
23892
- * @returns an object including the transaction Hash and the signature
23893
- * @example
23894
- * ```typescript
23895
- * const calls: Call[] = [{contractAddress: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
23896
- * entrypoint: "transfer",
23897
- * calldata:["0x11f5fc2a92ac03434a7937fe982f5e5293b65ad438a989c5b78fb8f04a12016",
23898
- * "0x9184e72a000", "0x0"]}];
23899
- * const txDetailsV3: V3InvocationsSignerDetails = {
23900
- * chainId: constants.StarknetChainId.SN_MAIN,
23901
- * nonce: "28", accountDeploymentData: [],
23902
- * paymasterData: [], cairoVersion: "1",
23903
- * feeDataAvailabilityMode: "L1", nonceDataAvailabilityMode: "L1",
23904
- * resourceBounds: {
23905
- * l1_gas: { max_amount: "0x2a00", max_price_per_unit: "0x5c00000"
23906
- * },
23907
- * l2_gas: { max_amount: "0x00", max_price_per_unit: "0x00"},
23908
- * }, tip: 0, version: "0x3", walletAddress: account0.address
23909
- * };
23910
- * const res = await myLedgerSigner.signTxV3(txDetailsV3, calls);
23911
- * // res = {hash:
23912
- * // signature:
23913
- * // }
23914
- * ```
23915
- */
23916
- async signTxV3(txDetails, calls) {
23917
- assert(txDetails.paymasterData.length <= 7, "Paymaster data includes more than 7 items.");
23918
- assert(
23919
- txDetails.accountDeploymentData.length <= 7,
23920
- "accountDeploymentData includes more than 7 items"
23921
- );
23922
- await this._transporter.send(Number("0x5a"), 3, 0, 0, buffer_default.from(this.pathBuffer));
23923
- const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
23924
- const tipBuf = this.convertBnToLedger(txDetails.tip);
23925
- const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
23926
- const nonceBuf = this.convertBnToLedger(txDetails.nonce);
23927
- const dAModeHashBuf = this.convertBnToLedger(
23928
- hashDAMode(
23929
- txDetails.nonceDataAvailabilityMode === EDataAvailabilityMode2.L1 ? EDAMode2.L1 : EDAMode2.L2,
23930
- txDetails.feeDataAvailabilityMode === EDataAvailabilityMode2.L1 ? EDAMode2.L1 : EDAMode2.L2
23931
- )
23932
- );
23933
- const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
23934
- const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
23935
- const dataBuf = concatenateArrayBuffer([
23936
- accountAddressBuf,
23937
- tipBuf,
23938
- l1_gasBuf,
23939
- l2_gasBuf,
23940
- chainIdBuf,
23941
- nonceBuf,
23942
- dAModeHashBuf
23943
- ]);
23944
- await this._transporter.send(Number("0x5a"), 3, 1, 0, buffer_default.from(dataBuf));
23945
- const paymasterBuf = concatenateArrayBuffer(
23946
- txDetails.paymasterData.map((value) => {
23947
- const a = this.convertBnToLedger(value);
23948
- return a;
23949
- })
23950
- );
23951
- await this._transporter.send(Number("0x5a"), 3, 2, 0, buffer_default.from(paymasterBuf));
23952
- const accountDeployDataBuf = concatenateArrayBuffer(
23953
- txDetails.paymasterData.map((value) => {
23954
- const a = this.convertBnToLedger(value);
23955
- return a;
23956
- })
23957
- );
23958
- await this._transporter.send(Number("0x5a"), 3, 3, 0, buffer_default.from(accountDeployDataBuf));
23959
- const nbCallsBuf = this.convertBnToLedger(calls.length);
23960
- await this._transporter.send(Number("0x5a"), 3, 4, 0, buffer_default.from(nbCallsBuf));
23961
- let respSign = new Uint8Array(0);
23962
- for (const call of calls) {
23963
- const calldatas = this.encodeCall(call);
23964
- await this._transporter.send(Number("0x5a"), 3, 5, 0, buffer_default.from(calldatas[0]));
23965
- if (calldatas.length > 1) {
23966
- calldatas.slice(1).forEach(async (part) => {
23967
- await this._transporter.send(Number("0x5a"), 3, 5, 1, buffer_default.from(part));
23968
- });
23969
- }
23970
- respSign = await this._transporter.send(Number("0x5a"), 3, 5, 2);
23971
- }
23972
- return this.decodeSignatureLedger(respSign);
24275
+ * tip: 0,
24276
+ * version: "0x3",
24277
+ * walletAddress: account0.address
24278
+ * }
24279
+ * const result = myLedgerSigner.signTransaction([call0, call1], txDetailsV3);
24280
+ * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
24281
+ * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
24282
+ * // recovery: 0}
24283
+ * ```
24284
+ */
24285
+ async signTransaction(transactions, transactionsDetail) {
24286
+ const compiledCalldata = getExecuteCalldata(transactions, transactionsDetail.cairoVersion);
24287
+ const msgHash = calculateInvokeTransactionHash2({
24288
+ ...transactionsDetail,
24289
+ senderAddress: transactionsDetail.walletAddress,
24290
+ compiledCalldata,
24291
+ version: transactionsDetail.version,
24292
+ nonceDataAvailabilityMode: intDAM(transactionsDetail.nonceDataAvailabilityMode),
24293
+ feeDataAvailabilityMode: intDAM(transactionsDetail.feeDataAvailabilityMode)
24294
+ });
24295
+ return this.signRaw(msgHash);
23973
24296
  }
23974
24297
  /**
23975
- *Ask the Ledger Nano to display and sign a Starknet V3 account deployment.
23976
- * @param {V3DeployAccountSignerDetails} deployAccountDetail All the details needed for a V3 deploy account.
23977
- * @returns an object including the transaction Hash and the signature
24298
+ * Sign in a Ledger the deployment of a new account. This is a blind sign on the Ledger screen.
24299
+ * @param {DeployAccountSignerDetails} details An object that includes all necessary data to calculate the Hash.
24300
+ * @returns {Signature} The deploy account signature.
23978
24301
  * @example
23979
24302
  * ```typescript
23980
- * const deployData: V3DeployAccountSignerDetails =
23981
- * {
23982
- * tip: 0, paymasterData: [], accountDeploymentData: [],
23983
- * nonceDataAvailabilityMode: 'L1', feeDataAvailabilityMode: 'L1',
23984
- * resourceBounds: {
23985
- * l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' },
23986
- * l1_gas: { max_amount: '0x226', max_price_per_unit: '0x22ecb25c00' }
23987
- * },
23988
- * classHash: '0x540d7f5ec7ecf317e68d48564934cb99259781b1ee3cedbbc37ec5337f8e688',
23989
- * constructorCalldata: [
23990
- * '3571125127744830445572285574469842579401255431821644822726857471463672199621'
23991
- * ],
23992
- * contractAddress: '0x4ca062add1cf12a107be1107af17981cf6e544a24d987693230ea481d3d5e34',
23993
- * addressSalt: '0x07e52f68e3160e1ef698211cdf6d3792368fe347e7e2d4a8ace14d9b248f39c5',
23994
- * chainId: '0x534e5f5345504f4c4941',
23995
- * version: '0x3', nonce: 0n
23996
- *}
23997
- * const res = await myLedgerSigner.signDeployAccountV3(deployData);
23998
- * // res = {hash:
23999
- * // signature:
24000
- * // }
24303
+ * const result = myLedgerSigner.signDeployAccountTransaction(details);
24304
+ * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
24305
+ * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
24306
+ * // recovery: 0}
24001
24307
  * ```
24002
24308
  */
24003
- async signDeployAccountV3(deployAccountDetail) {
24004
- await this._transporter.send(Number("0x5a"), 5, 0, 0, buffer_default.from(this.pathBuffer));
24005
- const accountAddressBuf = this.convertBnToLedger(
24006
- deployAccountDetail.contractAddress
24007
- );
24008
- const chainIdBuf = this.convertBnToLedger(deployAccountDetail.chainId);
24009
- const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
24010
- const dAModeHashBuf = this.convertBnToLedger(
24011
- hashDAMode(
24012
- deployAccountDetail.nonceDataAvailabilityMode === EDataAvailabilityMode2.L1 ? EDAMode2.L1 : EDAMode2.L2,
24013
- deployAccountDetail.feeDataAvailabilityMode === EDataAvailabilityMode2.L1 ? EDAMode2.L1 : EDAMode2.L2
24014
- )
24015
- );
24016
- const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
24017
- const saltBuf = this.convertBnToLedger(deployAccountDetail.addressSalt);
24018
- const dataBuf = concatenateArrayBuffer([
24019
- accountAddressBuf,
24020
- chainIdBuf,
24021
- nonceBuf,
24022
- dAModeHashBuf,
24023
- classHashBuf,
24024
- saltBuf
24025
- ]);
24026
- await this._transporter.send(Number("0x5a"), 5, 1, 0, buffer_default.from(dataBuf));
24027
- const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
24028
- const l1_gasBuf = this.convertBnToLedger(
24029
- encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
24030
- );
24031
- const l2_gasBuf = this.convertBnToLedger(
24032
- encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
24309
+ async signDeployAccountTransaction(details) {
24310
+ const compiledConstructorCalldata = CallData.compile(details.constructorCalldata);
24311
+ const msgHash = calculateDeployAccountTransactionHash2({
24312
+ ...details,
24313
+ salt: details.addressSalt,
24314
+ compiledConstructorCalldata,
24315
+ version: details.version,
24316
+ nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
24317
+ feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
24318
+ });
24319
+ return this.signRaw(msgHash);
24320
+ }
24321
+ /**
24322
+ * Sign in a Ledger the declaration of a new class. This is a blind sign on the Ledger screen.
24323
+ * @param {DeclareSignerDetails} details An object that includes all necessary data to calculate the Hash.
24324
+ * @returns {Signature} The declare Signature.
24325
+ * @example
24326
+ * ```typescript
24327
+ * const result = myLedgerSigner.signDeclareTransaction(details);
24328
+ * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
24329
+ * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
24330
+ * // recovery: 0}
24331
+ * ```
24332
+ */
24333
+ async signDeclareTransaction(details) {
24334
+ const msgHash = calculateDeclareTransactionHash2({
24335
+ ...details,
24336
+ version: details.version,
24337
+ nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
24338
+ feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
24339
+ });
24340
+ return this.signRaw(msgHash);
24341
+ }
24342
+ /**
24343
+ * Internal function to sign a hash in a Ledger Nano.
24344
+ * This is a blind sign in the Ledger ; no display of what you are signing.
24345
+ */
24346
+ async signRaw(msgHash) {
24347
+ addHexPrefix(
24348
+ buf2hex(await this._transporter.send(Number("0x5a"), 2, 0, 0, buffer_default.from(this.pathBuffer)))
24033
24349
  );
24034
- const feeBuf = concatenateArrayBuffer([tipBuf, l1_gasBuf, l2_gasBuf]);
24035
- await this._transporter.send(Number("0x5a"), 5, 2, 0, buffer_default.from(feeBuf));
24036
- const paymasterBuf = concatenateArrayBuffer(
24037
- deployAccountDetail.paymasterData.map((value) => {
24038
- const a = this.convertBnToLedger(value);
24039
- return a;
24040
- })
24350
+ const shiftedHash = toHex(BigInt(msgHash) << 4n);
24351
+ const buff2 = hexToBytes3(shiftedHash);
24352
+ const respSign2 = Uint8Array.from(
24353
+ await this._transporter.send(Number("0x5a"), 2, 1, 0, buffer_default.from(buff2))
24041
24354
  );
24042
- await this._transporter.send(Number("0x5a"), 5, 3, 0, buffer_default.from(paymasterBuf));
24043
- const compiledConstructor = CallData.compile(deployAccountDetail.constructorCalldata);
24044
- const constructorLengthBuf = this.convertBnToLedger(compiledConstructor.length);
24045
- await this._transporter.send(Number("0x5a"), 5, 4, 0, buffer_default.from(constructorLengthBuf));
24046
- const constructorBuf = concatenateArrayBuffer(
24047
- compiledConstructor.map((parameter) => {
24048
- const a = this.convertBnToLedger(parameter);
24049
- return a;
24050
- })
24355
+ const r = BigInt(addHexPrefix(buf2hex(respSign2.subarray(1, 33))));
24356
+ const s = BigInt(addHexPrefix(buf2hex(respSign2.subarray(33, 65))));
24357
+ const v = respSign2[65];
24358
+ const sign0 = new starknet_exports.Signature(r, s);
24359
+ const sign1 = sign0.addRecoveryBit(v);
24360
+ return sign1;
24361
+ }
24362
+ /** internal function to get both the Starknet public key and the full public key */
24363
+ async getPublicKeys() {
24364
+ const pathBuff = this.pathBuffer;
24365
+ const respGetPublic = Uint8Array.from(
24366
+ await this._transporter.send(Number("0x5a"), 1, 0, 0, buffer_default.from(pathBuff))
24051
24367
  );
24052
- const constructorChunks = [];
24053
- const chunkSize = 7 * 32;
24054
- for (let i = 0; i < constructorBuf.length; i += chunkSize)
24055
- constructorChunks.push(constructorBuf.subarray(i, i + chunkSize));
24056
- let respSign = new Uint8Array(0);
24057
- for (const chunk of constructorChunks) {
24058
- respSign = await this._transporter.send(Number("0x5a"), 5, 5, 0, buffer_default.from(chunk));
24059
- }
24060
- return this.decodeSignatureLedger(respSign);
24368
+ this.pubKey = addHexPrefix(buf2hex(respGetPublic.subarray(1, 33)));
24369
+ this.fullPubKey = addHexPrefix(buf2hex(respGetPublic.subarray(0, 65)));
24061
24370
  }
24062
24371
  };
24063
- function getLedgerPathBuffer221(accountId, applicationName = "LedgerW") {
24064
- const path0buff = new Uint8Array([HARDENING_BYTE, 0, 10, 85]);
24065
- const path1buff = new Uint8Array([71 | HARDENING_BYTE, 65, 233, 201]);
24066
- const path2Base = applicationName === "LedgerW" ? new Uint8Array([43, 206, 231, 219]) : stringToSha256ToArrayBuff4(applicationName);
24067
- const path2buff = concatenateArrayBuffer([
24068
- new Uint8Array([path2Base[0] | HARDENING_BYTE]),
24069
- path2Base.subarray(1)
24070
- ]);
24071
- const path3buff = new Uint8Array([HARDENING_BYTE, 0, 0, 0]);
24072
- const hex = toHex(BigInt(accountId) | HARDENING_4BYTES);
24372
+ function getLedgerPathBuffer111(accountId, applicationName = "LedgerW") {
24373
+ const path0buff = new Uint8Array([128, 0, 10, 85]);
24374
+ const path1buff = new Uint8Array([71, 65, 233, 201]);
24375
+ const path2buff = applicationName === "LedgerW" ? new Uint8Array([43, 206, 231, 219]) : stringToSha256ToArrayBuff4(applicationName);
24376
+ const path3buff = new Uint8Array([0, 0, 0, 0]);
24377
+ const hex = toHex(accountId);
24073
24378
  const padded = addHexPrefix(removeHexPrefix(hex).padStart(8, "0"));
24074
24379
  const path4buff = hexToBytes3(padded);
24075
24380
  const path5buff = new Uint8Array([0, 0, 0, 0]);
@@ -24084,224 +24389,170 @@ ${indent}}` : "}";
24084
24389
  return pathBuff;
24085
24390
  }
24086
24391
 
24087
- // src/signer/ledgerSigner231.ts
24088
- var LedgerSigner231 = class extends LedgerSigner221 {
24392
+ // src/utils/address.ts
24393
+ function addAddressPadding(address) {
24394
+ const hex = toHex(isString(address) ? addHexPrefix(address) : address);
24395
+ const padded = removeHexPrefix(hex).padStart(64, "0");
24396
+ return addHexPrefix(padded);
24397
+ }
24398
+ function validateAndParseAddress(address) {
24399
+ if (isString(address) && !/^(0x)?[0-9a-f]+$/i.test(address)) {
24400
+ throw new Error("Invalid Address Format");
24401
+ }
24402
+ const result = addAddressPadding(address);
24403
+ if (!result.match(/^(0x)?[0-9a-fA-F]{64}$/)) {
24404
+ throw new Error("Invalid Address Format");
24405
+ }
24406
+ assertInRange(result, ZERO, ADDR_BOUND - 1n, "Starknet Address");
24407
+ return result;
24408
+ }
24409
+ function getChecksumAddress(address) {
24410
+ const chars = removeHexPrefix(validateAndParseAddress(address)).toLowerCase().split("");
24411
+ const hex = removeHexPrefix(keccakBn(address));
24412
+ const hashed = hexToBytes2(hex.padStart(64, "0"));
24413
+ for (let i = 0; i < chars.length; i += 2) {
24414
+ if (hashed[i >> 1] >> 4 >= 8) {
24415
+ chars[i] = chars[i].toUpperCase();
24416
+ }
24417
+ if ((hashed[i >> 1] & 15) >= 8) {
24418
+ chars[i + 1] = chars[i + 1].toUpperCase();
24419
+ }
24420
+ }
24421
+ return addHexPrefix(chars.join(""));
24422
+ }
24423
+ function validateChecksumAddress(address) {
24424
+ return getChecksumAddress(address) === address;
24425
+ }
24426
+
24427
+ // src/signer/ledgerSigner221.ts
24428
+ var LedgerSigner221 = class extends LedgerSigner111 {
24089
24429
  /**
24090
24430
  * constructor of the LedgerSigner class.
24091
24431
  * @param {Transport} transport 5 transports are available to handle USB, bluetooth, Node, Web, Mobile.
24092
24432
  * See Guides for more details.
24093
- * @param {number} accountID ID of Ledger Nano account (can handle 2**31 accounts).
24433
+ * @param {number} accountID ID of Ledger Nano (can handle 2**31 accounts).
24094
24434
  * @param {string} [eip2645application='LedgerW'] A wallet is defined by an ERC2645 derivation path (6 items).
24095
24435
  * One item is called `application` and can be customized.
24096
24436
  * Default value is `LedgerW`.
24097
24437
  * @param {LedgerPathCalculation} [pathFunction=getLedgerPathBuffer221]
24098
24438
  * defines the function that will calculate the path. By default `getLedgerPathBuffer221` is selected.
24099
24439
  *
24100
- * If you are using APP v2.3.1 with an account created with the v1.1.1, you need to use :
24440
+ * If you are using APP v2.2.1 with an account created with the v1.1.1, you need to use :
24101
24441
  * ```typescript
24102
- * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0, undefined, getLedgerPathBuffer111);
24442
+ * const myLedgerSigner = new LedgerSigner221(myNodeTransport, 0, undefined, getLedgerPathBuffer111);
24103
24443
  * ```
24104
24444
  * @example
24105
24445
  * ```typescript
24106
24446
  * import TransportNodeHid from "@ledgerhq/hw-transport-node-hid";
24107
24447
  * const myNodeTransport = await TransportNodeHid.create();
24108
- * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0);
24448
+ * const myLedgerSigner = new LedgerSigner221(myNodeTransport, 0);
24449
+ * ```
24450
+ */
24451
+ constructor(transport, accountID, eip2645application = "LedgerW", pathFunction = getLedgerPathBuffer221) {
24452
+ super(transport, accountID, eip2645application, pathFunction);
24453
+ }
24454
+ /**
24455
+ * Sign in a Ledger a V3 transaction. The details are displayed on the Ledger screen.
24456
+ * @param {Call[]} transactions An array of `Call` transactions (generated for example by `myContract.populate()`).
24457
+ * @param {InvocationsSignerDetails} transactionsDetail An object that includes all the necessary inputs to hash the transaction.
24458
+ * @returns {Signature} The signed transaction.
24459
+ * @example
24460
+ * ```typescript
24461
+ * const txDetailsV3: V3InvocationsSignerDetails = {
24462
+ * chainId: constants.StarknetChainId.SN_MAIN,
24463
+ * nonce: "28",
24464
+ * accountDeploymentData: [],
24465
+ * paymasterData: [],
24466
+ * cairoVersion: "1",
24467
+ * feeDataAvailabilityMode: "L1",
24468
+ * nonceDataAvailabilityMode: "L1",
24469
+ * resourceBounds: {
24470
+ * l1_gas: {
24471
+ * max_amount: "0x2a00",
24472
+ * max_price_per_unit: "0x5c00000"
24473
+ * },
24474
+ * l2_gas: {
24475
+ * max_amount: "0x00",
24476
+ * max_price_per_unit: "0x00"
24477
+ * },
24478
+ * },
24479
+ * tip: 0,
24480
+ * version: "0x3",
24481
+ * walletAddress: account0.address
24482
+ * }
24483
+ * const result = myLedgerSigner.signTransaction([call0, call1], txDetailsV3);
24484
+ * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
24485
+ * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
24486
+ * // recovery: 0}
24109
24487
  * ```
24110
24488
  */
24111
- constructor(transport, accountID, eip2645application = "LedgerW", pathFunction = getLedgerPathBuffer221) {
24112
- super(transport, accountID, eip2645application, pathFunction);
24489
+ async signTransaction(transactions, transactionsDetail) {
24490
+ const compiledCalldata = getExecuteCalldata(transactions, transactionsDetail.cairoVersion);
24491
+ const msgHash = calculateInvokeTransactionHash2({
24492
+ ...transactionsDetail,
24493
+ senderAddress: transactionsDetail.walletAddress,
24494
+ compiledCalldata,
24495
+ version: transactionsDetail.version,
24496
+ nonceDataAvailabilityMode: intDAM(transactionsDetail.nonceDataAvailabilityMode),
24497
+ feeDataAvailabilityMode: intDAM(transactionsDetail.feeDataAvailabilityMode)
24498
+ });
24499
+ const ledgerResponse = await this.signTxV3(transactionsDetail, transactions);
24500
+ assert(
24501
+ toBigInt(msgHash) === ledgerResponse.hash,
24502
+ "The V3 transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
24503
+ );
24504
+ return ledgerResponse.signature;
24113
24505
  }
24114
24506
  /**
24115
- * Ask to the Ledger Nano to display and sign a Starknet V3 transaction.
24116
- * @param {V3InvocationsSignerDetails} txDetails All the details needed for a txV3.
24117
- * @param {Call[]} calls array of Starknet invocations
24118
- * @returns an object including the transaction Hash and the signature
24507
+ * Sign in a Ledger the deployment of a new account. The details are displayed on the Ledger screen.
24508
+ * @param {DeployAccountSignerDetails} details An object that includes all necessary data to calculate the Hash.
24509
+ * @returns {Signature} The deploy account signature.
24119
24510
  * @example
24120
24511
  * ```typescript
24121
- * const calls: Call[] = [{contractAddress: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
24122
- * entrypoint: "transfer",
24123
- * calldata:["0x11f5fc2a92ac03434a7937fe982f5e5293b65ad438a989c5b78fb8f04a12016",
24124
- * "0x9184e72a000", "0x0"]}];
24125
- * const txDetailsV3: V3InvocationsSignerDetails = {
24126
- * chainId: constants.StarknetChainId.SN_MAIN,
24127
- * nonce: "28", accountDeploymentData: [],
24128
- * paymasterData: [], cairoVersion: "1",
24129
- * feeDataAvailabilityMode: "L1", nonceDataAvailabilityMode: "L1",
24130
- * resourceBounds: {
24131
- * l1_gas: { max_amount: "0x2a00", max_price_per_unit: "0x5c00000"
24132
- * },
24133
- * l2_gas: { max_amount: "0x00", max_price_per_unit: "0x00"},
24134
- * }, tip: 0, version: "0x3", walletAddress: account0.address
24135
- * };
24136
- * const res = await myLedgerSigner.signTxV3(txDetailsV3, calls);
24137
- * // res = {hash:
24138
- * // signature:
24139
- * // }
24512
+ * const result = myLedgerSigner.signDeployAccountTransaction(details);
24513
+ * // result = Signature { r: 611475243393396148729326917410546146405234155928298353899191529090923298688n,
24514
+ * // s: 798839819213540985856952481651392652149797817551686626114697493101433761982n,
24515
+ * // recovery: 0}
24140
24516
  * ```
24141
24517
  */
24142
- async signTxV3(txDetails, calls) {
24143
- assert(txDetails.paymasterData.length <= 7, "Paymaster data includes more than 7 items.");
24518
+ async signDeployAccountTransaction(details) {
24519
+ const compiledConstructorCalldata = CallData.compile(details.constructorCalldata);
24520
+ const msgHash = calculateDeployAccountTransactionHash2({
24521
+ ...details,
24522
+ salt: details.addressSalt,
24523
+ compiledConstructorCalldata,
24524
+ version: details.version,
24525
+ nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
24526
+ feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
24527
+ });
24528
+ const ledgerResponse = await this.signDeployAccountV3(details);
24144
24529
  assert(
24145
- txDetails.accountDeploymentData.length <= 7,
24146
- "accountDeploymentData includes more than 7 items"
24147
- );
24148
- await this._transporter.send(Number("0x5a"), 3, 0, 0, buffer_default.from(this.pathBuffer));
24149
- const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
24150
- const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
24151
- const nonceBuf = this.convertBnToLedger(txDetails.nonce);
24152
- const dAModeHashBuf = this.convertBnToLedger(
24153
- hashDAMode(
24154
- intDAM(txDetails.nonceDataAvailabilityMode),
24155
- intDAM(txDetails.feeDataAvailabilityMode)
24156
- )
24157
- );
24158
- const dataBuf = concatenateArrayBuffer([
24159
- accountAddressBuf,
24160
- chainIdBuf,
24161
- nonceBuf,
24162
- dAModeHashBuf
24163
- ]);
24164
- await this._transporter.send(Number("0x5a"), 3, 1, 0, buffer_default.from(dataBuf));
24165
- if (isRPC08Plus_ResourceBoundsBN(txDetails.resourceBounds)) {
24166
- const tipBuf = this.convertBnToLedger(txDetails.tip);
24167
- const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
24168
- const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
24169
- const l1_data_gasBuf = this.convertBnToLedger(
24170
- encodeDataResourceBoundsL1(txDetails.resourceBounds)
24171
- );
24172
- const feeBuf = concatenateArrayBuffer([
24173
- tipBuf,
24174
- l1_gasBuf,
24175
- l2_gasBuf,
24176
- l1_data_gasBuf
24177
- ]);
24178
- await this._transporter.send(Number("0x5a"), 3, 2, 0, buffer_default.from(feeBuf));
24179
- }
24180
- const paymasterBuf = concatenateArrayBuffer(
24181
- txDetails.paymasterData.map((value) => {
24182
- const a = this.convertBnToLedger(value);
24183
- return a;
24184
- })
24185
- );
24186
- await this._transporter.send(Number("0x5a"), 3, 3, 0, buffer_default.from(paymasterBuf));
24187
- const accountDeployDataBuf = concatenateArrayBuffer(
24188
- txDetails.paymasterData.map((value) => {
24189
- const a = this.convertBnToLedger(value);
24190
- return a;
24191
- })
24530
+ toBigInt(msgHash) === ledgerResponse.hash,
24531
+ "The transaction hash calculated by Starknet.js is different from the one calculated by the Ledger."
24192
24532
  );
24193
- await this._transporter.send(Number("0x5a"), 3, 4, 0, buffer_default.from(accountDeployDataBuf));
24194
- const nbCallsBuf = this.convertBnToLedger(calls.length);
24195
- await this._transporter.send(Number("0x5a"), 3, 5, 0, buffer_default.from(nbCallsBuf));
24196
- let respSign = new Uint8Array(0);
24197
- for (const call of calls) {
24198
- const calldatas = this.encodeCall(call);
24199
- respSign = await this._transporter.send(Number("0x5a"), 3, 6, 0, buffer_default.from(calldatas[0]));
24200
- if (calldatas.length > 1) {
24201
- calldatas.slice(1).forEach(async (part) => {
24202
- respSign = await this._transporter.send(Number("0x5a"), 3, 6, 1, buffer_default.from(part));
24203
- });
24204
- }
24205
- }
24206
- return this.decodeSignatureLedger(respSign);
24533
+ return ledgerResponse.signature;
24207
24534
  }
24208
24535
  /**
24209
- *Ask the Ledger Nano to display and sign a Starknet V3 account deployment.
24210
- * @param {V3DeployAccountSignerDetails} deployAccountDetail All the details needed for a V3 deploy account.
24211
- * @returns an object including the transaction Hash and the signature
24212
- * @example
24213
- * ```typescript
24214
- * const deployData: V3DeployAccountSignerDetails =
24215
- * {
24216
- * tip: 0, paymasterData: [], accountDeploymentData: [],
24217
- * nonceDataAvailabilityMode: 'L1', feeDataAvailabilityMode: 'L1',
24218
- * resourceBounds: {
24219
- * l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' },
24220
- * l1_gas: { max_amount: '0x226', max_price_per_unit: '0x22ecb25c00' }
24221
- * },
24222
- * classHash: '0x540d7f5ec7ecf317e68d48564934cb99259781b1ee3cedbbc37ec5337f8e688',
24223
- * constructorCalldata: [
24224
- * '3571125127744830445572285574469842579401255431821644822726857471463672199621'
24225
- * ],
24226
- * contractAddress: '0x4ca062add1cf12a107be1107af17981cf6e544a24d987693230ea481d3d5e34',
24227
- * addressSalt: '0x07e52f68e3160e1ef698211cdf6d3792368fe347e7e2d4a8ace14d9b248f39c5',
24228
- * chainId: '0x534e5f5345504f4c4941',
24229
- * version: '0x3', nonce: 0n
24230
- *}
24231
- * const res = await myLedgerSigner.signDeployAccountV3(deployData);
24232
- * // res = {hash:
24233
- * // signature:
24234
- * // }
24235
- * ```
24536
+ * Internal function to convert a bigNumberish to an Uint8array of 256 bits
24537
+ * @param {BigNumberish} input input value
24538
+ * @returns {Uint8Array} a Uint8Array containing 32 bytes.
24236
24539
  */
24237
- async signDeployAccountV3(deployAccountDetail) {
24238
- await this._transporter.send(Number("0x5a"), 5, 0, 0, buffer_default.from(this.pathBuffer));
24239
- const accountAddressBuf = this.convertBnToLedger(
24240
- deployAccountDetail.contractAddress
24241
- );
24242
- const chainIdBuf = this.convertBnToLedger(deployAccountDetail.chainId);
24243
- const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
24244
- const dAModeHashBuf = this.convertBnToLedger(
24245
- hashDAMode(
24246
- intDAM(deployAccountDetail.nonceDataAvailabilityMode),
24247
- intDAM(deployAccountDetail.feeDataAvailabilityMode)
24248
- )
24249
- );
24250
- const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
24251
- const saltBuf = this.convertBnToLedger(deployAccountDetail.addressSalt);
24252
- const dataBuf = concatenateArrayBuffer([
24253
- accountAddressBuf,
24254
- chainIdBuf,
24255
- nonceBuf,
24256
- dAModeHashBuf,
24257
- classHashBuf,
24258
- saltBuf
24259
- ]);
24260
- await this._transporter.send(Number("0x5a"), 5, 1, 0, buffer_default.from(dataBuf));
24261
- if (isRPC08Plus_ResourceBoundsBN(deployAccountDetail.resourceBounds)) {
24262
- const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
24263
- const l1_gasBuf = this.convertBnToLedger(
24264
- encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
24265
- );
24266
- const l2_gasBuf = this.convertBnToLedger(
24267
- encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
24268
- );
24269
- const l1_data_gasBuf = this.convertBnToLedger(
24270
- encodeDataResourceBoundsL1(deployAccountDetail.resourceBounds)
24271
- );
24272
- const feeBuf = concatenateArrayBuffer([
24273
- tipBuf,
24274
- l1_gasBuf,
24275
- l2_gasBuf,
24276
- l1_data_gasBuf
24277
- ]);
24278
- await this._transporter.send(Number("0x5a"), 5, 2, 0, buffer_default.from(feeBuf));
24279
- }
24280
- const paymasterBuf = concatenateArrayBuffer(
24281
- deployAccountDetail.paymasterData.map((value) => {
24282
- const a = this.convertBnToLedger(value);
24283
- return a;
24284
- })
24285
- );
24286
- await this._transporter.send(Number("0x5a"), 5, 3, 0, buffer_default.from(paymasterBuf));
24287
- const compiledConstructor = CallData.compile(deployAccountDetail.constructorCalldata);
24288
- const constructorLengthBuf = this.convertBnToLedger(compiledConstructor.length);
24289
- await this._transporter.send(Number("0x5a"), 5, 4, 0, buffer_default.from(constructorLengthBuf));
24290
- const constructorBuf = concatenateArrayBuffer(
24291
- compiledConstructor.map((parameter) => {
24292
- const a = this.convertBnToLedger(parameter);
24293
- return a;
24294
- })
24295
- );
24296
- const constructorChunks = [];
24297
- const chunkSize = 7 * 32;
24298
- for (let i = 0; i < constructorBuf.length; i += chunkSize)
24299
- constructorChunks.push(constructorBuf.subarray(i, i + chunkSize));
24300
- let respSign = new Uint8Array(0);
24301
- for (const chunk of constructorChunks) {
24302
- respSign = await this._transporter.send(Number("0x5a"), 5, 5, 0, buffer_default.from(chunk));
24303
- }
24304
- return this.decodeSignatureLedger(respSign);
24540
+ convertBnToLedger(input) {
24541
+ return hexToBytes3(addAddressPadding(toHex(input)));
24542
+ }
24543
+ /**
24544
+ * Internal function to decode the response of the Ledger signature
24545
+ * @param {Uint8Array} respSign the Buffer response of the Ledger
24546
+ * @returns { hash: bigint; signature: Signature } transaction hash & signature
24547
+ */
24548
+ decodeSignatureLedger(respSign) {
24549
+ const h = BigInt(addHexPrefix(buf2hex(respSign.subarray(0, 32))));
24550
+ const r = BigInt(addHexPrefix(buf2hex(respSign.subarray(33, 65))));
24551
+ const s = BigInt(addHexPrefix(buf2hex(respSign.subarray(65, 97))));
24552
+ const v = respSign[97];
24553
+ const sign0 = new starknet_exports.Signature(r, s);
24554
+ const sign1 = sign0.addRecoveryBit(v);
24555
+ return { hash: h, signature: sign1 };
24305
24556
  }
24306
24557
  /** Internal function to convert a Call to an array of Uint8Array.
24307
24558
  * @param {Call} call A Call to convert.
@@ -24310,19 +24561,15 @@ ${indent}}` : "}";
24310
24561
  encodeCall(call) {
24311
24562
  const toBuf = this.convertBnToLedger(call.contractAddress);
24312
24563
  const selectorBuf = hexToBytes3(addAddressPadding(getSelector(call.entrypoint)));
24313
- let calldataBuf;
24564
+ let calldataBuf = new Uint8Array([]);
24314
24565
  if (call.calldata) {
24315
24566
  const compiledCalldata = CallData.compile(call.calldata);
24316
- const calldataSizeBuf = this.convertBnToLedger(compiledCalldata.length);
24317
- calldataBuf = concatenateArrayBuffer([
24318
- calldataSizeBuf,
24319
- ...compiledCalldata.map((parameter) => {
24567
+ calldataBuf = concatenateArrayBuffer(
24568
+ compiledCalldata.map((parameter) => {
24320
24569
  const a = this.convertBnToLedger(parameter);
24321
24570
  return a;
24322
24571
  })
24323
- ]);
24324
- } else {
24325
- calldataBuf = this.convertBnToLedger("0x00");
24572
+ );
24326
24573
  }
24327
24574
  const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
24328
24575
  const calldatas = [];
@@ -24331,522 +24578,472 @@ ${indent}}` : "}";
24331
24578
  calldatas.push(callBuf.subarray(i, i + chunkSize));
24332
24579
  return calldatas;
24333
24580
  }
24334
- };
24335
-
24336
- // src/utils/outsideExecution.ts
24337
- var outsideExecution_exports = {};
24338
- __export(outsideExecution_exports, {
24339
- buildExecuteFromOutsideCall: () => buildExecuteFromOutsideCall,
24340
- buildExecuteFromOutsideCallData: () => buildExecuteFromOutsideCallData,
24341
- getOutsideCall: () => getOutsideCall,
24342
- getTypedData: () => getTypedData,
24343
- toOutsideCallV2: () => toOutsideCallV2
24344
- });
24345
- function toOutsideCallV2(call) {
24346
- if ("calldata_len" in call) {
24347
- return {
24348
- To: call.to,
24349
- Selector: call.selector,
24350
- Calldata: call.calldata
24351
- };
24352
- }
24353
- return call;
24354
- }
24355
- function getOutsideCall(call) {
24356
- const callData = call.calldata ?? [];
24357
- const callDataCompiled = Array.isArray(callData) ? callData : CallData.compile(callData);
24358
- return {
24359
- to: call.contractAddress,
24360
- selector: getSelectorFromName(call.entrypoint),
24361
- calldata: callDataCompiled
24362
- };
24363
- }
24364
- function callToTypedData(call, version) {
24365
- const outsideCall = getOutsideCall(call);
24366
- if (version === "1") {
24367
- return {
24368
- ...outsideCall,
24369
- calldata_len: outsideCall.calldata.length,
24370
- calldata: outsideCall.calldata
24371
- };
24372
- }
24373
- return {
24374
- To: outsideCall.to,
24375
- Selector: outsideCall.selector,
24376
- Calldata: outsideCall.calldata
24377
- };
24378
- }
24379
- function getDomain(chainId, version) {
24380
- return {
24381
- name: "Account.execute_from_outside",
24382
- version,
24383
- chainId,
24384
- ...version === "2" ? { revision: "1" } : {}
24385
- };
24386
- }
24387
- function getTypedData(chainId, options, nonce, myCalls, version) {
24388
- if (version === "1") {
24389
- return {
24390
- types: OutsideExecutionTypesV1,
24391
- primaryType: "OutsideExecution",
24392
- domain: getDomain(chainId, version),
24393
- message: {
24394
- ...options,
24395
- nonce,
24396
- calls_len: myCalls.length,
24397
- calls: myCalls.map((call) => callToTypedData(call, version))
24398
- }
24399
- };
24400
- }
24401
- return {
24402
- types: OutsideExecutionTypesV2,
24403
- primaryType: "OutsideExecution",
24404
- domain: getDomain(chainId, version),
24405
- message: {
24406
- Caller: options.caller,
24407
- Nonce: nonce,
24408
- "Execute After": options.execute_after,
24409
- "Execute Before": options.execute_before,
24410
- Calls: myCalls.map((call) => callToTypedData(call, version))
24411
- }
24412
- };
24413
- }
24414
- function buildExecuteFromOutsideCallData(outsideTransaction) {
24415
- const execution2 = outsideTransaction.outsideExecution;
24416
- const formattedSignature = formatSignature(outsideTransaction.signature);
24417
- return CallData.compile({
24418
- outside_execution: execution2,
24419
- signature: formattedSignature
24420
- });
24421
- }
24422
- function buildExecuteFromOutsideCall(outsideTransaction) {
24423
- const myOutsideTransactions = Array.isArray(outsideTransaction) ? outsideTransaction : [outsideTransaction];
24424
- const multiCall = myOutsideTransactions.map((outsideTx) => {
24425
- let entrypoint;
24426
- if (outsideTx.version === OutsideExecutionVersion.V1) {
24427
- entrypoint = "execute_from_outside";
24428
- } else if (outsideTx.version === OutsideExecutionVersion.V2) {
24429
- entrypoint = "execute_from_outside_v2";
24430
- } else {
24431
- throw new Error("Unsupported OutsideExecution version");
24432
- }
24433
- return {
24434
- contractAddress: toHex(outsideTx.signerAddress),
24435
- entrypoint,
24436
- calldata: buildExecuteFromOutsideCallData(outsideTx)
24437
- };
24438
- });
24439
- return multiCall;
24440
- }
24441
-
24442
- // src/utils/src5.ts
24443
- var src5_exports = {};
24444
- __export(src5_exports, {
24445
- supportsInterface: () => supportsInterface
24446
- });
24447
- async function supportsInterface(provider, contractAddress, interfaceId) {
24448
- const call = {
24449
- contractAddress: toHex(contractAddress),
24450
- entrypoint: "supports_interface",
24451
- calldata: [toHex(interfaceId)]
24452
- };
24453
- try {
24454
- const resp = await provider.callContract(call);
24455
- return BigInt(resp[0]) !== 0n;
24456
- } catch {
24457
- return false;
24458
- }
24459
- }
24460
-
24461
- // src/utils/paymaster.ts
24462
- var paymaster_exports = {};
24463
- __export(paymaster_exports, {
24464
- assertCallsAreStrictlyEqual: () => assertCallsAreStrictlyEqual,
24465
- assertPaymasterTransactionSafety: () => assertPaymasterTransactionSafety,
24466
- getDefaultPaymasterNodeUrl: () => getDefaultPaymasterNodeUrl
24467
- });
24468
- var getDefaultPaymasterNodeUrl = (networkName, mute = false) => {
24469
- if (!mute) {
24470
- logger.info("Using default public node url, please provide nodeUrl in provider options!");
24471
- }
24472
- const nodes = PAYMASTER_RPC_NODES[networkName ?? _NetworkName.SN_SEPOLIA];
24473
- const randIdx = Math.floor(Math.random() * nodes.length);
24474
- return nodes[randIdx];
24475
- };
24476
- var assertGasFeeFromUnsafeCalls = (unsafeCalls, fees) => {
24477
- const unsafeCall = toOutsideCallV2(unsafeCalls[unsafeCalls.length - 1]);
24478
- const unsafeGasTokenCalldata = CallData.toCalldata(unsafeCall.Calldata);
24479
- const unsafeGasTokenValue = uint256ToBN({
24480
- low: unsafeGasTokenCalldata[1],
24481
- high: unsafeGasTokenCalldata[2]
24482
- });
24483
- assert(
24484
- unsafeGasTokenValue === BigInt(fees),
24485
- "Gas token value is not equal to the provided gas fees"
24486
- );
24487
- };
24488
- var assertGasTokenFromUnsafeCalls = (unsafeCalls, gasToken) => {
24489
- const unsafeCall = toOutsideCallV2(unsafeCalls[unsafeCalls.length - 1]);
24490
- assert(
24491
- BigInt(unsafeCall.To) === BigInt(gasToken),
24492
- "Gas token address is not equal to the provided gas token"
24493
- );
24494
- assert(
24495
- unsafeCall.Selector === getSelectorFromName("transfer"),
24496
- "Gas token call selector is not a transfer"
24497
- );
24498
- assert(
24499
- CallData.toCalldata(unsafeCall.Calldata).length === 3,
24500
- "Gas token transfer calldata does not match the expected recipient/amount shape"
24501
- );
24502
- };
24503
- function assertCallsAreStrictlyEqual(originalCalls, unsafeCalls, isSponsored = false) {
24504
- const baseError = "Provided calls are not strictly equal to the returned calls";
24505
- const expectedExtraCalls = isSponsored ? 0 : 1;
24506
- assert(
24507
- unsafeCalls.length - expectedExtraCalls === originalCalls.length,
24508
- `${baseError}: Expected ${originalCalls.length + expectedExtraCalls} calls, got ${unsafeCalls.length}`
24509
- );
24510
- for (let callIndex = 0; callIndex < originalCalls.length; callIndex += 1) {
24511
- const originalCall = originalCalls[callIndex];
24512
- const unsafeCall = toOutsideCallV2(unsafeCalls[callIndex]);
24513
- const normalizeAddress = (address) => {
24514
- return toBigInt(address).toString(16).toLowerCase();
24515
- };
24516
- const originalAddress = normalizeAddress(originalCall.contractAddress);
24517
- const unsafeAddress = normalizeAddress(unsafeCall.To);
24581
+ /**
24582
+ * Ask to the Ledger Nano to display and sign a Starknet V3 transaction.
24583
+ * @param {V3InvocationsSignerDetails} txDetails All the details needed for a txV3.
24584
+ * @param {Call[]} calls array of Starknet invocations
24585
+ * @returns an object including the transaction Hash and the signature
24586
+ * @example
24587
+ * ```typescript
24588
+ * const calls: Call[] = [{contractAddress: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
24589
+ * entrypoint: "transfer",
24590
+ * calldata:["0x11f5fc2a92ac03434a7937fe982f5e5293b65ad438a989c5b78fb8f04a12016",
24591
+ * "0x9184e72a000", "0x0"]}];
24592
+ * const txDetailsV3: V3InvocationsSignerDetails = {
24593
+ * chainId: constants.StarknetChainId.SN_MAIN,
24594
+ * nonce: "28", accountDeploymentData: [],
24595
+ * paymasterData: [], cairoVersion: "1",
24596
+ * feeDataAvailabilityMode: "L1", nonceDataAvailabilityMode: "L1",
24597
+ * resourceBounds: {
24598
+ * l1_gas: { max_amount: "0x2a00", max_price_per_unit: "0x5c00000"
24599
+ * },
24600
+ * l2_gas: { max_amount: "0x00", max_price_per_unit: "0x00"},
24601
+ * }, tip: 0, version: "0x3", walletAddress: account0.address
24602
+ * };
24603
+ * const res = await myLedgerSigner.signTxV3(txDetailsV3, calls);
24604
+ * // res = {hash:
24605
+ * // signature:
24606
+ * // }
24607
+ * ```
24608
+ */
24609
+ async signTxV3(txDetails, calls) {
24610
+ assert(txDetails.paymasterData.length <= 7, "Paymaster data includes more than 7 items.");
24518
24611
  assert(
24519
- originalAddress === unsafeAddress,
24520
- `${baseError}: Contract address mismatch at call ${callIndex}. Expected: ${originalCall.contractAddress}, Got: ${unsafeCall.To}`
24612
+ txDetails.accountDeploymentData.length <= 7,
24613
+ "accountDeploymentData includes more than 7 items"
24614
+ );
24615
+ await this._transporter.send(Number("0x5a"), 3, 0, 0, buffer_default.from(this.pathBuffer));
24616
+ const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
24617
+ const tipBuf = this.convertBnToLedger(txDetails.tip);
24618
+ const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
24619
+ const nonceBuf = this.convertBnToLedger(txDetails.nonce);
24620
+ const dAModeHashBuf = this.convertBnToLedger(
24621
+ hashDAMode(
24622
+ txDetails.nonceDataAvailabilityMode === EDataAvailabilityMode2.L1 ? EDAMode2.L1 : EDAMode2.L2,
24623
+ txDetails.feeDataAvailabilityMode === EDataAvailabilityMode2.L1 ? EDAMode2.L1 : EDAMode2.L2
24624
+ )
24625
+ );
24626
+ const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
24627
+ const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
24628
+ const dataBuf = concatenateArrayBuffer([
24629
+ accountAddressBuf,
24630
+ tipBuf,
24631
+ l1_gasBuf,
24632
+ l2_gasBuf,
24633
+ chainIdBuf,
24634
+ nonceBuf,
24635
+ dAModeHashBuf
24636
+ ]);
24637
+ await this._transporter.send(Number("0x5a"), 3, 1, 0, buffer_default.from(dataBuf));
24638
+ const paymasterBuf = concatenateArrayBuffer(
24639
+ txDetails.paymasterData.map((value) => {
24640
+ const a = this.convertBnToLedger(value);
24641
+ return a;
24642
+ })
24643
+ );
24644
+ await this._transporter.send(Number("0x5a"), 3, 2, 0, buffer_default.from(paymasterBuf));
24645
+ const accountDeployDataBuf = concatenateArrayBuffer(
24646
+ txDetails.paymasterData.map((value) => {
24647
+ const a = this.convertBnToLedger(value);
24648
+ return a;
24649
+ })
24650
+ );
24651
+ await this._transporter.send(Number("0x5a"), 3, 3, 0, buffer_default.from(accountDeployDataBuf));
24652
+ const nbCallsBuf = this.convertBnToLedger(calls.length);
24653
+ await this._transporter.send(Number("0x5a"), 3, 4, 0, buffer_default.from(nbCallsBuf));
24654
+ let respSign = new Uint8Array(0);
24655
+ for (const call of calls) {
24656
+ const calldatas = this.encodeCall(call);
24657
+ await this._transporter.send(Number("0x5a"), 3, 5, 0, buffer_default.from(calldatas[0]));
24658
+ if (calldatas.length > 1) {
24659
+ calldatas.slice(1).forEach(async (part) => {
24660
+ await this._transporter.send(Number("0x5a"), 3, 5, 1, buffer_default.from(part));
24661
+ });
24662
+ }
24663
+ respSign = await this._transporter.send(Number("0x5a"), 3, 5, 2);
24664
+ }
24665
+ return this.decodeSignatureLedger(respSign);
24666
+ }
24667
+ /**
24668
+ *Ask the Ledger Nano to display and sign a Starknet V3 account deployment.
24669
+ * @param {V3DeployAccountSignerDetails} deployAccountDetail All the details needed for a V3 deploy account.
24670
+ * @returns an object including the transaction Hash and the signature
24671
+ * @example
24672
+ * ```typescript
24673
+ * const deployData: V3DeployAccountSignerDetails =
24674
+ * {
24675
+ * tip: 0, paymasterData: [], accountDeploymentData: [],
24676
+ * nonceDataAvailabilityMode: 'L1', feeDataAvailabilityMode: 'L1',
24677
+ * resourceBounds: {
24678
+ * l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' },
24679
+ * l1_gas: { max_amount: '0x226', max_price_per_unit: '0x22ecb25c00' }
24680
+ * },
24681
+ * classHash: '0x540d7f5ec7ecf317e68d48564934cb99259781b1ee3cedbbc37ec5337f8e688',
24682
+ * constructorCalldata: [
24683
+ * '3571125127744830445572285574469842579401255431821644822726857471463672199621'
24684
+ * ],
24685
+ * contractAddress: '0x4ca062add1cf12a107be1107af17981cf6e544a24d987693230ea481d3d5e34',
24686
+ * addressSalt: '0x07e52f68e3160e1ef698211cdf6d3792368fe347e7e2d4a8ace14d9b248f39c5',
24687
+ * chainId: '0x534e5f5345504f4c4941',
24688
+ * version: '0x3', nonce: 0n
24689
+ *}
24690
+ * const res = await myLedgerSigner.signDeployAccountV3(deployData);
24691
+ * // res = {hash:
24692
+ * // signature:
24693
+ * // }
24694
+ * ```
24695
+ */
24696
+ async signDeployAccountV3(deployAccountDetail) {
24697
+ await this._transporter.send(Number("0x5a"), 5, 0, 0, buffer_default.from(this.pathBuffer));
24698
+ const accountAddressBuf = this.convertBnToLedger(
24699
+ deployAccountDetail.contractAddress
24521
24700
  );
24522
- assert(
24523
- getSelectorFromName(originalCall.entrypoint) === unsafeCall.Selector,
24524
- `${baseError}: Entrypoint mismatch at call ${callIndex}. Expected: ${originalCall.entrypoint}, Got: ${unsafeCall.Selector}`
24701
+ const chainIdBuf = this.convertBnToLedger(deployAccountDetail.chainId);
24702
+ const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
24703
+ const dAModeHashBuf = this.convertBnToLedger(
24704
+ hashDAMode(
24705
+ deployAccountDetail.nonceDataAvailabilityMode === EDataAvailabilityMode2.L1 ? EDAMode2.L1 : EDAMode2.L2,
24706
+ deployAccountDetail.feeDataAvailabilityMode === EDataAvailabilityMode2.L1 ? EDAMode2.L1 : EDAMode2.L2
24707
+ )
24525
24708
  );
24526
- const originalCalldata = CallData.toCalldata(originalCall.calldata);
24527
- const unsafeCalldata = CallData.toCalldata(unsafeCall.Calldata);
24528
- assert(
24529
- originalCalldata.length === unsafeCalldata.length,
24530
- `${baseError}: Calldata length mismatch at call ${callIndex}. Expected length: ${originalCalldata.length}, Got length: ${unsafeCalldata.length}`
24709
+ const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
24710
+ const saltBuf = this.convertBnToLedger(deployAccountDetail.addressSalt);
24711
+ const dataBuf = concatenateArrayBuffer([
24712
+ accountAddressBuf,
24713
+ chainIdBuf,
24714
+ nonceBuf,
24715
+ dAModeHashBuf,
24716
+ classHashBuf,
24717
+ saltBuf
24718
+ ]);
24719
+ await this._transporter.send(Number("0x5a"), 5, 1, 0, buffer_default.from(dataBuf));
24720
+ const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
24721
+ const l1_gasBuf = this.convertBnToLedger(
24722
+ encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
24531
24723
  );
24532
- for (let dataIndex = 0; dataIndex < originalCalldata.length; dataIndex += 1) {
24533
- const originalValue = BigInt(originalCalldata[dataIndex]);
24534
- const unsafeValue = BigInt(unsafeCalldata[dataIndex]);
24535
- assert(
24536
- originalValue === unsafeValue,
24537
- `${baseError}: Calldata value mismatch at call ${callIndex}, parameter ${dataIndex}. Expected: ${originalCalldata[dataIndex]}, Got: ${unsafeCalldata[dataIndex]}`
24538
- );
24724
+ const l2_gasBuf = this.convertBnToLedger(
24725
+ encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
24726
+ );
24727
+ const feeBuf = concatenateArrayBuffer([tipBuf, l1_gasBuf, l2_gasBuf]);
24728
+ await this._transporter.send(Number("0x5a"), 5, 2, 0, buffer_default.from(feeBuf));
24729
+ const paymasterBuf = concatenateArrayBuffer(
24730
+ deployAccountDetail.paymasterData.map((value) => {
24731
+ const a = this.convertBnToLedger(value);
24732
+ return a;
24733
+ })
24734
+ );
24735
+ await this._transporter.send(Number("0x5a"), 5, 3, 0, buffer_default.from(paymasterBuf));
24736
+ const compiledConstructor = CallData.compile(deployAccountDetail.constructorCalldata);
24737
+ const constructorLengthBuf = this.convertBnToLedger(compiledConstructor.length);
24738
+ await this._transporter.send(Number("0x5a"), 5, 4, 0, buffer_default.from(constructorLengthBuf));
24739
+ const constructorBuf = concatenateArrayBuffer(
24740
+ compiledConstructor.map((parameter) => {
24741
+ const a = this.convertBnToLedger(parameter);
24742
+ return a;
24743
+ })
24744
+ );
24745
+ const constructorChunks = [];
24746
+ const chunkSize = 7 * 32;
24747
+ for (let i = 0; i < constructorBuf.length; i += chunkSize)
24748
+ constructorChunks.push(constructorBuf.subarray(i, i + chunkSize));
24749
+ let respSign = new Uint8Array(0);
24750
+ for (const chunk of constructorChunks) {
24751
+ respSign = await this._transporter.send(Number("0x5a"), 5, 5, 0, buffer_default.from(chunk));
24539
24752
  }
24753
+ return this.decodeSignatureLedger(respSign);
24540
24754
  }
24755
+ };
24756
+ function getLedgerPathBuffer221(accountId, applicationName = "LedgerW") {
24757
+ const path0buff = new Uint8Array([HARDENING_BYTE, 0, 10, 85]);
24758
+ const path1buff = new Uint8Array([71 | HARDENING_BYTE, 65, 233, 201]);
24759
+ const path2Base = applicationName === "LedgerW" ? new Uint8Array([43, 206, 231, 219]) : stringToSha256ToArrayBuff4(applicationName);
24760
+ const path2buff = concatenateArrayBuffer([
24761
+ new Uint8Array([path2Base[0] | HARDENING_BYTE]),
24762
+ path2Base.subarray(1)
24763
+ ]);
24764
+ const path3buff = new Uint8Array([HARDENING_BYTE, 0, 0, 0]);
24765
+ const hex = toHex(BigInt(accountId) | HARDENING_4BYTES);
24766
+ const padded = addHexPrefix(removeHexPrefix(hex).padStart(8, "0"));
24767
+ const path4buff = hexToBytes3(padded);
24768
+ const path5buff = new Uint8Array([0, 0, 0, 0]);
24769
+ const pathBuff = concatenateArrayBuffer([
24770
+ path0buff,
24771
+ path1buff,
24772
+ path2buff,
24773
+ path3buff,
24774
+ path4buff,
24775
+ path5buff
24776
+ ]);
24777
+ return pathBuff;
24541
24778
  }
24542
- var domainFieldToFelt = (value) => {
24543
- try {
24544
- return toBigInt(value);
24545
- } catch {
24546
- return CairoBytes31.fromText(String(value)).toBigInt();
24779
+
24780
+ // src/signer/ledgerSigner231.ts
24781
+ var LedgerSigner231 = class extends LedgerSigner221 {
24782
+ /**
24783
+ * constructor of the LedgerSigner class.
24784
+ * @param {Transport} transport 5 transports are available to handle USB, bluetooth, Node, Web, Mobile.
24785
+ * See Guides for more details.
24786
+ * @param {number} accountID ID of Ledger Nano account (can handle 2**31 accounts).
24787
+ * @param {string} [eip2645application='LedgerW'] A wallet is defined by an ERC2645 derivation path (6 items).
24788
+ * One item is called `application` and can be customized.
24789
+ * Default value is `LedgerW`.
24790
+ * @param {LedgerPathCalculation} [pathFunction=getLedgerPathBuffer221]
24791
+ * defines the function that will calculate the path. By default `getLedgerPathBuffer221` is selected.
24792
+ *
24793
+ * If you are using APP v2.3.1 with an account created with the v1.1.1, you need to use :
24794
+ * ```typescript
24795
+ * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0, undefined, getLedgerPathBuffer111);
24796
+ * ```
24797
+ * @example
24798
+ * ```typescript
24799
+ * import TransportNodeHid from "@ledgerhq/hw-transport-node-hid";
24800
+ * const myNodeTransport = await TransportNodeHid.create();
24801
+ * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0);
24802
+ * ```
24803
+ */
24804
+ constructor(transport, accountID, eip2645application = "LedgerW", pathFunction = getLedgerPathBuffer221) {
24805
+ super(transport, accountID, eip2645application, pathFunction);
24547
24806
  }
24548
- };
24549
- var assertChainIdFromTypedData = (typedData, chainId) => {
24550
- assert(
24551
- typedData.domain.chainId !== void 0 && domainFieldToFelt(typedData.domain.chainId) === BigInt(chainId),
24552
- "Paymaster typed data domain chainId does not match the account's provider chain"
24553
- );
24554
- };
24555
- var assertPaymasterTransactionSafety = (preparedTransaction, calls, paymasterDetails, chainId, maxFeeInGasToken) => {
24556
- if (preparedTransaction.type === "invoke" || preparedTransaction.type === "deploy_and_invoke") {
24557
- assertChainIdFromTypedData(preparedTransaction.typed_data, chainId);
24558
- const { message } = preparedTransaction.typed_data;
24559
- const hasV1Calls = "calls" in message;
24560
- const hasV2Calls = "Calls" in message;
24807
+ /**
24808
+ * Ask to the Ledger Nano to display and sign a Starknet V3 transaction.
24809
+ * @param {V3InvocationsSignerDetails} txDetails All the details needed for a txV3.
24810
+ * @param {Call[]} calls array of Starknet invocations
24811
+ * @returns an object including the transaction Hash and the signature
24812
+ * @example
24813
+ * ```typescript
24814
+ * const calls: Call[] = [{contractAddress: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
24815
+ * entrypoint: "transfer",
24816
+ * calldata:["0x11f5fc2a92ac03434a7937fe982f5e5293b65ad438a989c5b78fb8f04a12016",
24817
+ * "0x9184e72a000", "0x0"]}];
24818
+ * const txDetailsV3: V3InvocationsSignerDetails = {
24819
+ * chainId: constants.StarknetChainId.SN_MAIN,
24820
+ * nonce: "28", accountDeploymentData: [],
24821
+ * paymasterData: [], cairoVersion: "1",
24822
+ * feeDataAvailabilityMode: "L1", nonceDataAvailabilityMode: "L1",
24823
+ * resourceBounds: {
24824
+ * l1_gas: { max_amount: "0x2a00", max_price_per_unit: "0x5c00000"
24825
+ * },
24826
+ * l2_gas: { max_amount: "0x00", max_price_per_unit: "0x00"},
24827
+ * }, tip: 0, version: "0x3", walletAddress: account0.address
24828
+ * };
24829
+ * const res = await myLedgerSigner.signTxV3(txDetailsV3, calls);
24830
+ * // res = {hash:
24831
+ * // signature:
24832
+ * // }
24833
+ * ```
24834
+ */
24835
+ async signTxV3(txDetails, calls) {
24836
+ assert(txDetails.paymasterData.length <= 7, "Paymaster data includes more than 7 items.");
24561
24837
  assert(
24562
- hasV1Calls !== hasV2Calls,
24563
- 'Paymaster typed data must declare exactly one of "calls" (SNIP-9 V1) or "Calls" (SNIP-9 V2)'
24838
+ txDetails.accountDeploymentData.length <= 7,
24839
+ "accountDeploymentData includes more than 7 items"
24564
24840
  );
24565
- const unsafeCalls = hasV1Calls ? message.calls : message.Calls;
24566
- assertCallsAreStrictlyEqual(calls, unsafeCalls, paymasterDetails.feeMode.mode === "sponsored");
24567
- if (paymasterDetails.feeMode.mode !== "sponsored") {
24568
- assertGasTokenFromUnsafeCalls(unsafeCalls, paymasterDetails.feeMode.gasToken);
24569
- assertGasFeeFromUnsafeCalls(
24570
- unsafeCalls,
24571
- preparedTransaction.fee.suggested_max_fee_in_gas_token
24572
- );
24573
- if (maxFeeInGasToken) {
24574
- assert(
24575
- preparedTransaction.fee.suggested_max_fee_in_gas_token <= maxFeeInGasToken,
24576
- "Gas token price is too high"
24577
- );
24578
- }
24579
- }
24580
- const msg = message;
24581
- const version = hasV1Calls ? OutsideExecutionVersion.V1 : OutsideExecutionVersion.V2;
24582
- const [callerKey, nonceKey, afterKey, beforeKey] = hasV1Calls ? ["caller", "nonce", "execute_after", "execute_before"] : ["Caller", "Nonce", "Execute After", "Execute Before"];
24583
- assert(
24584
- [callerKey, nonceKey, afterKey, beforeKey].every((key) => msg[key] !== void 0),
24585
- "Paymaster typed data does not match the expected outside execution"
24841
+ await this._transporter.send(Number("0x5a"), 3, 0, 0, buffer_default.from(this.pathBuffer));
24842
+ const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
24843
+ const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
24844
+ const nonceBuf = this.convertBnToLedger(txDetails.nonce);
24845
+ const dAModeHashBuf = this.convertBnToLedger(
24846
+ hashDAMode(
24847
+ intDAM(txDetails.nonceDataAvailabilityMode),
24848
+ intDAM(txDetails.feeDataAvailabilityMode)
24849
+ )
24586
24850
  );
24587
- const caller = msg[callerKey];
24588
- const nonce = msg[nonceKey];
24589
- const executeAfter = msg[afterKey];
24590
- const executeBefore = msg[beforeKey];
24591
- if (paymasterDetails.timeBounds) {
24592
- const requestedAfter = toBigInt(paymasterDetails.timeBounds.executeAfter ?? 1);
24593
- const requestedBefore = toBigInt(paymasterDetails.timeBounds.executeBefore);
24594
- assert(
24595
- toBigInt(executeAfter) >= requestedAfter && toBigInt(executeBefore) <= requestedBefore,
24596
- "Paymaster typed data execution window is not within the requested time bounds"
24851
+ const dataBuf = concatenateArrayBuffer([
24852
+ accountAddressBuf,
24853
+ chainIdBuf,
24854
+ nonceBuf,
24855
+ dAModeHashBuf
24856
+ ]);
24857
+ await this._transporter.send(Number("0x5a"), 3, 1, 0, buffer_default.from(dataBuf));
24858
+ if (isRPC08Plus_ResourceBoundsBN(txDetails.resourceBounds)) {
24859
+ const tipBuf = this.convertBnToLedger(txDetails.tip);
24860
+ const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
24861
+ const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
24862
+ const l1_data_gasBuf = this.convertBnToLedger(
24863
+ encodeDataResourceBoundsL1(txDetails.resourceBounds)
24597
24864
  );
24865
+ const feeBuf = concatenateArrayBuffer([
24866
+ tipBuf,
24867
+ l1_gasBuf,
24868
+ l2_gasBuf,
24869
+ l1_data_gasBuf
24870
+ ]);
24871
+ await this._transporter.send(Number("0x5a"), 3, 2, 0, buffer_default.from(feeBuf));
24598
24872
  }
24599
- const expectedCalls = [...calls];
24600
- if (paymasterDetails.feeMode.mode !== "sponsored") {
24601
- const feeCall = toOutsideCallV2(unsafeCalls[unsafeCalls.length - 1]);
24602
- const feeRecipient = CallData.toCalldata(feeCall.Calldata)[0];
24603
- const feeAmount = bnToUint256(preparedTransaction.fee.suggested_max_fee_in_gas_token);
24604
- expectedCalls.push({
24605
- contractAddress: paymasterDetails.feeMode.gasToken,
24606
- entrypoint: "transfer",
24607
- calldata: [feeRecipient, feeAmount.low, feeAmount.high]
24608
- });
24609
- }
24610
- const expectedTypedData = getTypedData(
24611
- chainId,
24612
- { caller, execute_after: executeAfter, execute_before: executeBefore },
24613
- nonce,
24614
- expectedCalls,
24615
- version
24873
+ const paymasterBuf = concatenateArrayBuffer(
24874
+ txDetails.paymasterData.map((value) => {
24875
+ const a = this.convertBnToLedger(value);
24876
+ return a;
24877
+ })
24616
24878
  );
24617
- assert(
24618
- getMessageHash(expectedTypedData, 0) === getMessageHash(preparedTransaction.typed_data, 0),
24619
- "Paymaster typed data does not match the expected outside execution"
24879
+ await this._transporter.send(Number("0x5a"), 3, 3, 0, buffer_default.from(paymasterBuf));
24880
+ const accountDeployDataBuf = concatenateArrayBuffer(
24881
+ txDetails.paymasterData.map((value) => {
24882
+ const a = this.convertBnToLedger(value);
24883
+ return a;
24884
+ })
24620
24885
  );
24621
- }
24622
- };
24623
-
24624
- // src/paymaster/rpc.ts
24625
- var convertCalls = (calls) => calls.map((call) => ({
24626
- to: call.contractAddress,
24627
- selector: getSelectorFromName(call.entrypoint),
24628
- calldata: CallData.toHex(call.calldata)
24629
- }));
24630
- var convertFeeMode = (feeMode) => {
24631
- if (feeMode.mode === "sponsored") {
24632
- return { mode: "sponsored" };
24633
- }
24634
- return { mode: "default", gas_token: feeMode.gasToken };
24635
- };
24636
- var convertFEE_MODE = (feeMode) => {
24637
- if (feeMode.mode === "sponsored") {
24638
- return { mode: "sponsored" };
24639
- }
24640
- return { mode: "default", gasToken: feeMode.gas_token };
24641
- };
24642
- var convertTimeBounds = (timeBounds) => timeBounds ? {
24643
- execute_after: timeBounds.executeAfter || 1,
24644
- // If executeAfter is not provided, set it to 1, meaning the transaction can be executed immediately
24645
- execute_before: timeBounds.executeBefore
24646
- } : void 0;
24647
- var convertTIME_BOUNDS = (timeBounds) => timeBounds ? {
24648
- executeAfter: timeBounds.execute_after,
24649
- executeBefore: timeBounds.execute_before
24650
- } : void 0;
24651
- var convertEXECUTION_PARAMETERS = (parameters) => ({
24652
- version: parameters.version,
24653
- feeMode: convertFEE_MODE(parameters.fee_mode),
24654
- timeBounds: convertTIME_BOUNDS(parameters.time_bounds)
24655
- });
24656
- var defaultOptions = {
24657
- headers: { "Content-Type": "application/json" }
24658
- };
24659
- var PaymasterRpc = class _PaymasterRpc {
24660
- nodeUrl;
24661
- headers;
24662
- baseFetch;
24663
- requestId;
24664
- constructor(options) {
24665
- if (options instanceof _PaymasterRpc) {
24666
- this.nodeUrl = options.nodeUrl;
24667
- this.headers = { ...defaultOptions.headers, ...options.headers };
24668
- this.baseFetch = options.baseFetch;
24669
- this.requestId = options.requestId;
24670
- return;
24671
- }
24672
- if (options && "nodeUrl" in options && "headers" in options && "baseFetch" in options) {
24673
- this.nodeUrl = options.nodeUrl ?? getDefaultPaymasterNodeUrl(void 0);
24674
- this.headers = { ...defaultOptions.headers, ...options.headers };
24675
- this.baseFetch = options.baseFetch ?? fetch_default;
24676
- this.requestId = 0;
24677
- return;
24678
- }
24679
- const { nodeUrl, headers, baseFetch } = options || {};
24680
- if (nodeUrl && Object.values(_NetworkName).includes(nodeUrl)) {
24681
- this.nodeUrl = getDefaultPaymasterNodeUrl(nodeUrl, options?.mute);
24682
- } else if (nodeUrl) {
24683
- this.nodeUrl = nodeUrl;
24684
- } else {
24685
- this.nodeUrl = getDefaultPaymasterNodeUrl(void 0, options?.mute);
24686
- }
24687
- this.baseFetch = baseFetch ?? fetch_default;
24688
- this.headers = { ...defaultOptions.headers, ...headers };
24689
- this.requestId = 0;
24690
- }
24691
- fetch(method, params, id = 0) {
24692
- const rpcRequestBody = {
24693
- id,
24694
- jsonrpc: "2.0",
24695
- method,
24696
- ...params && { params }
24697
- };
24698
- return this.baseFetch(this.nodeUrl, {
24699
- method: "POST",
24700
- body: stringify2(rpcRequestBody),
24701
- headers: this.headers
24702
- });
24703
- }
24704
- errorHandler(method, params, rpcError, otherError) {
24705
- if (rpcError) {
24706
- throw new RpcError(rpcError, method, params);
24707
- }
24708
- if (otherError instanceof LibraryError) {
24709
- throw otherError;
24710
- }
24711
- if (otherError) {
24712
- throw Error(otherError.message);
24713
- }
24714
- }
24715
- async fetchEndpoint(method, params) {
24716
- try {
24717
- this.requestId += 1;
24718
- const rawResult = await this.fetch(method, params, this.requestId);
24719
- const { error, result } = await rawResult.json();
24720
- this.errorHandler(method, params, error);
24721
- return result;
24722
- } catch (error) {
24723
- this.errorHandler(method, params, error?.response?.data, error);
24724
- throw error;
24886
+ await this._transporter.send(Number("0x5a"), 3, 4, 0, buffer_default.from(accountDeployDataBuf));
24887
+ const nbCallsBuf = this.convertBnToLedger(calls.length);
24888
+ await this._transporter.send(Number("0x5a"), 3, 5, 0, buffer_default.from(nbCallsBuf));
24889
+ let respSign = new Uint8Array(0);
24890
+ for (const call of calls) {
24891
+ const calldatas = this.encodeCall(call);
24892
+ respSign = await this._transporter.send(Number("0x5a"), 3, 6, 0, buffer_default.from(calldatas[0]));
24893
+ if (calldatas.length > 1) {
24894
+ calldatas.slice(1).forEach(async (part) => {
24895
+ respSign = await this._transporter.send(Number("0x5a"), 3, 6, 1, buffer_default.from(part));
24896
+ });
24897
+ }
24725
24898
  }
24899
+ return this.decodeSignatureLedger(respSign);
24726
24900
  }
24727
- async isAvailable() {
24728
- return this.fetchEndpoint("paymaster_isAvailable");
24729
- }
24730
- async buildTransaction(transaction, parameters) {
24731
- let userTransaction;
24732
- switch (transaction.type) {
24733
- case "invoke":
24734
- userTransaction = {
24735
- ...transaction,
24736
- invoke: {
24737
- user_address: transaction.invoke.userAddress,
24738
- calls: convertCalls(transaction.invoke.calls)
24739
- }
24740
- };
24741
- break;
24742
- case "deploy_and_invoke":
24743
- userTransaction = {
24744
- ...transaction,
24745
- invoke: {
24746
- user_address: transaction.invoke.userAddress,
24747
- calls: convertCalls(transaction.invoke.calls)
24748
- }
24749
- };
24750
- break;
24751
- case "deploy":
24752
- default:
24753
- userTransaction = transaction;
24754
- break;
24901
+ /**
24902
+ *Ask the Ledger Nano to display and sign a Starknet V3 account deployment.
24903
+ * @param {V3DeployAccountSignerDetails} deployAccountDetail All the details needed for a V3 deploy account.
24904
+ * @returns an object including the transaction Hash and the signature
24905
+ * @example
24906
+ * ```typescript
24907
+ * const deployData: V3DeployAccountSignerDetails =
24908
+ * {
24909
+ * tip: 0, paymasterData: [], accountDeploymentData: [],
24910
+ * nonceDataAvailabilityMode: 'L1', feeDataAvailabilityMode: 'L1',
24911
+ * resourceBounds: {
24912
+ * l2_gas: { max_amount: '0x0', max_price_per_unit: '0x0' },
24913
+ * l1_gas: { max_amount: '0x226', max_price_per_unit: '0x22ecb25c00' }
24914
+ * },
24915
+ * classHash: '0x540d7f5ec7ecf317e68d48564934cb99259781b1ee3cedbbc37ec5337f8e688',
24916
+ * constructorCalldata: [
24917
+ * '3571125127744830445572285574469842579401255431821644822726857471463672199621'
24918
+ * ],
24919
+ * contractAddress: '0x4ca062add1cf12a107be1107af17981cf6e544a24d987693230ea481d3d5e34',
24920
+ * addressSalt: '0x07e52f68e3160e1ef698211cdf6d3792368fe347e7e2d4a8ace14d9b248f39c5',
24921
+ * chainId: '0x534e5f5345504f4c4941',
24922
+ * version: '0x3', nonce: 0n
24923
+ *}
24924
+ * const res = await myLedgerSigner.signDeployAccountV3(deployData);
24925
+ * // res = {hash:
24926
+ * // signature:
24927
+ * // }
24928
+ * ```
24929
+ */
24930
+ async signDeployAccountV3(deployAccountDetail) {
24931
+ await this._transporter.send(Number("0x5a"), 5, 0, 0, buffer_default.from(this.pathBuffer));
24932
+ const accountAddressBuf = this.convertBnToLedger(
24933
+ deployAccountDetail.contractAddress
24934
+ );
24935
+ const chainIdBuf = this.convertBnToLedger(deployAccountDetail.chainId);
24936
+ const nonceBuf = this.convertBnToLedger(deployAccountDetail.nonce);
24937
+ const dAModeHashBuf = this.convertBnToLedger(
24938
+ hashDAMode(
24939
+ intDAM(deployAccountDetail.nonceDataAvailabilityMode),
24940
+ intDAM(deployAccountDetail.feeDataAvailabilityMode)
24941
+ )
24942
+ );
24943
+ const classHashBuf = this.convertBnToLedger(deployAccountDetail.classHash);
24944
+ const saltBuf = this.convertBnToLedger(deployAccountDetail.addressSalt);
24945
+ const dataBuf = concatenateArrayBuffer([
24946
+ accountAddressBuf,
24947
+ chainIdBuf,
24948
+ nonceBuf,
24949
+ dAModeHashBuf,
24950
+ classHashBuf,
24951
+ saltBuf
24952
+ ]);
24953
+ await this._transporter.send(Number("0x5a"), 5, 1, 0, buffer_default.from(dataBuf));
24954
+ if (isRPC08Plus_ResourceBoundsBN(deployAccountDetail.resourceBounds)) {
24955
+ const tipBuf = this.convertBnToLedger(deployAccountDetail.tip);
24956
+ const l1_gasBuf = this.convertBnToLedger(
24957
+ encodeResourceBoundsL1(deployAccountDetail.resourceBounds)
24958
+ );
24959
+ const l2_gasBuf = this.convertBnToLedger(
24960
+ encodeResourceBoundsL2(deployAccountDetail.resourceBounds)
24961
+ );
24962
+ const l1_data_gasBuf = this.convertBnToLedger(
24963
+ encodeDataResourceBoundsL1(deployAccountDetail.resourceBounds)
24964
+ );
24965
+ const feeBuf = concatenateArrayBuffer([
24966
+ tipBuf,
24967
+ l1_gasBuf,
24968
+ l2_gasBuf,
24969
+ l1_data_gasBuf
24970
+ ]);
24971
+ await this._transporter.send(Number("0x5a"), 5, 2, 0, buffer_default.from(feeBuf));
24755
24972
  }
24756
- const executionParameters = {
24757
- version: parameters.version,
24758
- fee_mode: convertFeeMode(parameters.feeMode),
24759
- time_bounds: convertTimeBounds(parameters.timeBounds)
24760
- };
24761
- const response = await this.fetchEndpoint("paymaster_buildTransaction", {
24762
- transaction: userTransaction,
24763
- parameters: executionParameters
24764
- });
24765
- const fee = {
24766
- gas_token_price_in_strk: BigInt(response.fee.gas_token_price_in_strk),
24767
- estimated_fee_in_strk: BigInt(response.fee.estimated_fee_in_strk),
24768
- estimated_fee_in_gas_token: BigInt(response.fee.estimated_fee_in_gas_token),
24769
- suggested_max_fee_in_strk: BigInt(response.fee.suggested_max_fee_in_strk),
24770
- suggested_max_fee_in_gas_token: BigInt(response.fee.suggested_max_fee_in_gas_token)
24771
- };
24772
- switch (response.type) {
24773
- case "invoke":
24774
- return {
24775
- type: "invoke",
24776
- typed_data: response.typed_data,
24777
- parameters: convertEXECUTION_PARAMETERS(response.parameters),
24778
- fee
24779
- };
24780
- case "deploy_and_invoke":
24781
- return {
24782
- type: "deploy_and_invoke",
24783
- deployment: response.deployment,
24784
- typed_data: response.typed_data,
24785
- parameters: convertEXECUTION_PARAMETERS(response.parameters),
24786
- fee
24787
- };
24788
- case "deploy":
24789
- default:
24790
- return {
24791
- type: "deploy",
24792
- deployment: response.deployment,
24793
- parameters: convertEXECUTION_PARAMETERS(response.parameters),
24794
- fee
24795
- };
24973
+ const paymasterBuf = concatenateArrayBuffer(
24974
+ deployAccountDetail.paymasterData.map((value) => {
24975
+ const a = this.convertBnToLedger(value);
24976
+ return a;
24977
+ })
24978
+ );
24979
+ await this._transporter.send(Number("0x5a"), 5, 3, 0, buffer_default.from(paymasterBuf));
24980
+ const compiledConstructor = CallData.compile(deployAccountDetail.constructorCalldata);
24981
+ const constructorLengthBuf = this.convertBnToLedger(compiledConstructor.length);
24982
+ await this._transporter.send(Number("0x5a"), 5, 4, 0, buffer_default.from(constructorLengthBuf));
24983
+ const constructorBuf = concatenateArrayBuffer(
24984
+ compiledConstructor.map((parameter) => {
24985
+ const a = this.convertBnToLedger(parameter);
24986
+ return a;
24987
+ })
24988
+ );
24989
+ const constructorChunks = [];
24990
+ const chunkSize = 7 * 32;
24991
+ for (let i = 0; i < constructorBuf.length; i += chunkSize)
24992
+ constructorChunks.push(constructorBuf.subarray(i, i + chunkSize));
24993
+ let respSign = new Uint8Array(0);
24994
+ for (const chunk of constructorChunks) {
24995
+ respSign = await this._transporter.send(Number("0x5a"), 5, 5, 0, buffer_default.from(chunk));
24796
24996
  }
24997
+ return this.decodeSignatureLedger(respSign);
24797
24998
  }
24798
- async executeTransaction(transaction, parameters) {
24799
- let user_transaction;
24800
- switch (transaction.type) {
24801
- case "invoke":
24802
- user_transaction = {
24803
- ...transaction,
24804
- invoke: {
24805
- user_address: transaction.invoke.userAddress,
24806
- typed_data: transaction.invoke.typedData,
24807
- signature: signatureToHexArray(transaction.invoke.signature)
24808
- }
24809
- };
24810
- break;
24811
- case "deploy_and_invoke":
24812
- user_transaction = {
24813
- ...transaction,
24814
- invoke: {
24815
- user_address: transaction.invoke.userAddress,
24816
- typed_data: transaction.invoke.typedData,
24817
- signature: signatureToHexArray(transaction.invoke.signature)
24818
- }
24819
- };
24820
- break;
24821
- case "deploy":
24822
- default:
24823
- user_transaction = transaction;
24824
- break;
24999
+ /** Internal function to convert a Call to an array of Uint8Array.
25000
+ * @param {Call} call A Call to convert.
25001
+ * @return {Uint8Array[]} Call encoded in an array of Uint8Array (each containing 7 u256).
25002
+ */
25003
+ encodeCall(call) {
25004
+ const toBuf = this.convertBnToLedger(call.contractAddress);
25005
+ const selectorBuf = hexToBytes3(addAddressPadding(getSelector(call.entrypoint)));
25006
+ let calldataBuf;
25007
+ if (call.calldata) {
25008
+ const compiledCalldata = CallData.compile(call.calldata);
25009
+ const calldataSizeBuf = this.convertBnToLedger(compiledCalldata.length);
25010
+ calldataBuf = concatenateArrayBuffer([
25011
+ calldataSizeBuf,
25012
+ ...compiledCalldata.map((parameter) => {
25013
+ const a = this.convertBnToLedger(parameter);
25014
+ return a;
25015
+ })
25016
+ ]);
25017
+ } else {
25018
+ calldataBuf = this.convertBnToLedger("0x00");
24825
25019
  }
24826
- const executionParameters = {
24827
- version: parameters.version,
24828
- fee_mode: convertFeeMode(parameters.feeMode),
24829
- time_bounds: convertTimeBounds(parameters.timeBounds)
24830
- };
24831
- return this.fetchEndpoint("paymaster_executeTransaction", {
24832
- transaction: user_transaction,
24833
- parameters: executionParameters
24834
- });
24835
- }
24836
- async getSupportedTokens() {
24837
- return this.fetchEndpoint("paymaster_getSupportedTokens").then(
24838
- (tokens) => tokens.map((token) => ({
24839
- token_address: token.token_address,
24840
- decimals: token.decimals,
24841
- priceInStrk: BigInt(token.price_in_strk)
24842
- }))
24843
- );
25020
+ const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
25021
+ const calldatas = [];
25022
+ const chunkSize = 7 * 32;
25023
+ for (let i = 0; i < callBuf.length; i += chunkSize)
25024
+ calldatas.push(callBuf.subarray(i, i + chunkSize));
25025
+ return calldatas;
24844
25026
  }
24845
25027
  };
24846
25028
 
24847
- // src/paymaster/interface.ts
24848
- var PaymasterInterface = class {
24849
- };
25029
+ // src/utils/src5.ts
25030
+ var src5_exports = {};
25031
+ __export(src5_exports, {
25032
+ supportsInterface: () => supportsInterface
25033
+ });
25034
+ async function supportsInterface(provider, contractAddress, interfaceId) {
25035
+ const call = {
25036
+ contractAddress: toHex(contractAddress),
25037
+ entrypoint: "supports_interface",
25038
+ calldata: [toHex(interfaceId)]
25039
+ };
25040
+ try {
25041
+ const resp = await provider.callContract(call);
25042
+ return BigInt(resp[0]) !== 0n;
25043
+ } catch {
25044
+ return false;
25045
+ }
25046
+ }
24850
25047
 
24851
25048
  // src/deployer/compileConstructorCalldata.ts
24852
25049
  function checkCompiledConstructorCalldata(calldata, abi) {
@@ -25003,7 +25200,6 @@ ${indent}}` : "}";
25003
25200
  // holds Cairo 0 contracts, to refuse a Cairo 0 account; otherwise remove it.
25004
25201
  cairoVersion;
25005
25202
  transactionVersion;
25006
- paymaster;
25007
25203
  deployer;
25008
25204
  defaultTipType;
25009
25205
  /** @internal Account-level plugin management */
@@ -25025,11 +25221,13 @@ ${indent}}` : "}";
25025
25221
  this.cairoVersion = cairoVersion.toString();
25026
25222
  }
25027
25223
  this.transactionVersion = transactionVersion ?? config.get("transactionVersion");
25028
- this.paymaster = paymaster ? new PaymasterRpc(paymaster) : new PaymasterRpc({ mute: true });
25029
25224
  this.deployer = options.deployer ?? defaultDeployer;
25030
25225
  this.defaultTipType = defaultTipType ?? config.get("defaultTipType");
25031
25226
  this.accountPluginManager = new PluginManager();
25032
- const plugins = options.plugins === false ? [] : options.plugins ?? defaultPlugins;
25227
+ const plugins = applyPaymasterOption(
25228
+ options.plugins === false ? [] : options.plugins ?? defaultPlugins,
25229
+ paymaster
25230
+ );
25033
25231
  plugins.forEach((plugin) => {
25034
25232
  this.accountPluginManager.installOnAccount(plugin, this);
25035
25233
  });
@@ -25740,114 +25938,6 @@ ${indent}}` : "}";
25740
25938
  })
25741
25939
  );
25742
25940
  }
25743
- /*
25744
- * SNIP-29 Paymaster
25745
- */
25746
- async buildPaymasterTransaction(calls, paymasterDetails) {
25747
- if (!paymasterDetails.deploymentData) {
25748
- const snip9Version = await this.getSnip9Version();
25749
- if (snip9Version === OutsideExecutionVersion.UNSUPPORTED) {
25750
- throw Error("Account is not compatible with SNIP-9");
25751
- }
25752
- }
25753
- const parameters = {
25754
- version: "0x1",
25755
- feeMode: paymasterDetails.feeMode,
25756
- timeBounds: paymasterDetails.timeBounds
25757
- };
25758
- let transaction;
25759
- if (paymasterDetails.deploymentData) {
25760
- if (calls.length > 0) {
25761
- transaction = {
25762
- type: "deploy_and_invoke",
25763
- invoke: { userAddress: this.address, calls },
25764
- deployment: paymasterDetails.deploymentData
25765
- };
25766
- } else {
25767
- transaction = {
25768
- type: "deploy",
25769
- deployment: paymasterDetails.deploymentData
25770
- };
25771
- }
25772
- } else {
25773
- transaction = {
25774
- type: "invoke",
25775
- invoke: { userAddress: this.address, calls }
25776
- };
25777
- }
25778
- return this.paymaster.buildTransaction(transaction, parameters);
25779
- }
25780
- async estimatePaymasterTransactionFee(calls, paymasterDetails) {
25781
- const preparedTransaction = await this.buildPaymasterTransaction(calls, paymasterDetails);
25782
- return preparedTransaction.fee;
25783
- }
25784
- /**
25785
- * Signs a transaction prepared by the paymaster, after checking it is safe to sign. The safety
25786
- * check needs the calls and the fee details the user actually requested, so a caller that uses
25787
- * this low-level method directly must pass them, the same way `executePaymasterTransaction`
25788
- * does.
25789
- * @param preparedTransaction the transaction returned by the paymaster.
25790
- * @param calls the calls the user requested.
25791
- * @param paymasterDetails the fee mode and related paymaster details.
25792
- * @param maxFeeInGasToken optional user-approved ceiling on the gas-token fee.
25793
- */
25794
- async preparePaymasterTransaction(preparedTransaction, calls, paymasterDetails, maxFeeInGasToken) {
25795
- assertPaymasterTransactionSafety(
25796
- preparedTransaction,
25797
- calls,
25798
- paymasterDetails,
25799
- await this.provider.getChainId(),
25800
- maxFeeInGasToken
25801
- );
25802
- let transaction;
25803
- switch (preparedTransaction.type) {
25804
- case "deploy_and_invoke": {
25805
- const signature = await this.signMessage(preparedTransaction.typed_data);
25806
- transaction = {
25807
- type: "deploy_and_invoke",
25808
- invoke: {
25809
- userAddress: this.address,
25810
- typedData: preparedTransaction.typed_data,
25811
- signature: signatureToHexArray(signature)
25812
- },
25813
- deployment: preparedTransaction.deployment
25814
- };
25815
- break;
25816
- }
25817
- case "invoke": {
25818
- const signature = await this.signMessage(preparedTransaction.typed_data);
25819
- transaction = {
25820
- type: "invoke",
25821
- invoke: {
25822
- userAddress: this.address,
25823
- typedData: preparedTransaction.typed_data,
25824
- signature: signatureToHexArray(signature)
25825
- }
25826
- };
25827
- break;
25828
- }
25829
- case "deploy": {
25830
- transaction = {
25831
- type: "deploy",
25832
- deployment: preparedTransaction.deployment
25833
- };
25834
- break;
25835
- }
25836
- default:
25837
- throw Error("Invalid transaction type");
25838
- }
25839
- return transaction;
25840
- }
25841
- async executePaymasterTransaction(calls, paymasterDetails, maxFeeInGasToken) {
25842
- const preparedTransaction = await this.buildPaymasterTransaction(calls, paymasterDetails);
25843
- const transaction = await this.preparePaymasterTransaction(
25844
- preparedTransaction,
25845
- calls,
25846
- paymasterDetails,
25847
- maxFeeInGasToken
25848
- );
25849
- return this.paymaster.executeTransaction(transaction, preparedTransaction.parameters).then((response) => ({ transaction_hash: response.transaction_hash }));
25850
- }
25851
25941
  };
25852
25942
 
25853
25943
  // src/account/interface.ts
@@ -26879,6 +26969,7 @@ ${indent}}` : "}";
26879
26969
  }
26880
26970
 
26881
26971
  // src/contract/default.ts
26972
+ var NO_PAYMASTER_MESSAGE = "This account has no paymaster methods: add paymasterPlugin() to its plugins, or set its paymaster option.";
26882
26973
  function buildCall(contract, functionAbi) {
26883
26974
  return async function(...args) {
26884
26975
  const options = { ...contract.withOptionsProps };
@@ -27117,13 +27208,12 @@ ${indent}}` : "}";
27117
27208
  await this.ensureProvider();
27118
27209
  if (isAccount(this.providerOrAccount)) {
27119
27210
  if (restInvokeOptions.paymasterDetails) {
27120
- const myCall = {
27121
- contractAddress: this.address,
27122
- entrypoint: method,
27123
- calldata: args
27124
- };
27211
+ assert(
27212
+ typeof this.providerOrAccount.executePaymasterTransaction === "function",
27213
+ NO_PAYMASTER_MESSAGE
27214
+ );
27125
27215
  return this.providerOrAccount.executePaymasterTransaction(
27126
- [myCall],
27216
+ [invocation],
27127
27217
  restInvokeOptions.paymasterDetails,
27128
27218
  restInvokeOptions.maxFeeInGasToken
27129
27219
  );
@@ -27167,13 +27257,12 @@ ${indent}}` : "}";
27167
27257
  await this.ensureProvider();
27168
27258
  if (isAccount(this.providerOrAccount)) {
27169
27259
  if (estimateDetails.paymasterDetails) {
27170
- const myCall = {
27171
- contractAddress: this.address,
27172
- entrypoint: method,
27173
- calldata: args
27174
- };
27260
+ assert(
27261
+ typeof this.providerOrAccount.estimatePaymasterTransactionFee === "function",
27262
+ NO_PAYMASTER_MESSAGE
27263
+ );
27175
27264
  return this.providerOrAccount.estimatePaymasterTransactionFee(
27176
- [myCall],
27265
+ [invocation],
27177
27266
  estimateDetails.paymasterDetails
27178
27267
  );
27179
27268
  }