starknet 11.4.0 → 11.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
@@ -23326,34 +24036,17 @@ ${indent}}` : "}";
23326
24036
  }
23327
24037
  async signDeclareTransaction(details) {
23328
24038
  const msgHash = calculateDeclareTransactionHash2({
23329
- ...details,
23330
- version: details.version,
23331
- nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
23332
- feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
23333
- });
23334
- return this.signRaw(msgHash);
23335
- }
23336
- async signRaw(msgHash) {
23337
- return starknet_exports.sign(msgHash, this.pk);
23338
- }
23339
- };
23340
-
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
- }
24039
+ ...details,
24040
+ version: details.version,
24041
+ nonceDataAvailabilityMode: intDAM(details.nonceDataAvailabilityMode),
24042
+ feeDataAvailabilityMode: intDAM(details.feeDataAvailabilityMode)
24043
+ });
24044
+ return this.signRaw(msgHash);
24045
+ }
24046
+ async signRaw(msgHash) {
24047
+ return starknet_exports.sign(msgHash, this.pk);
24048
+ }
24049
+ };
23357
24050
 
23358
24051
  // src/signer/ethSigner.ts
23359
24052
  var EthSigner = class {
@@ -23862,254 +24555,28 @@ ${indent}}` : "}";
23862
24555
  return { hash: h, signature: sign1 };
23863
24556
  }
23864
24557
  /** 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);
23973
- }
23974
- /**
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
23978
- * @example
23979
- * ```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
- * // }
24001
- * ```
24002
- */
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)
24033
- );
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
- })
24041
- );
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
- })
24051
- );
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);
24061
- }
24062
- };
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);
24073
- const padded = addHexPrefix(removeHexPrefix(hex).padStart(8, "0"));
24074
- const path4buff = hexToBytes3(padded);
24075
- const path5buff = new Uint8Array([0, 0, 0, 0]);
24076
- const pathBuff = concatenateArrayBuffer([
24077
- path0buff,
24078
- path1buff,
24079
- path2buff,
24080
- path3buff,
24081
- path4buff,
24082
- path5buff
24083
- ]);
24084
- return pathBuff;
24085
- }
24086
-
24087
- // src/signer/ledgerSigner231.ts
24088
- var LedgerSigner231 = class extends LedgerSigner221 {
24089
- /**
24090
- * constructor of the LedgerSigner class.
24091
- * @param {Transport} transport 5 transports are available to handle USB, bluetooth, Node, Web, Mobile.
24092
- * See Guides for more details.
24093
- * @param {number} accountID ID of Ledger Nano account (can handle 2**31 accounts).
24094
- * @param {string} [eip2645application='LedgerW'] A wallet is defined by an ERC2645 derivation path (6 items).
24095
- * One item is called `application` and can be customized.
24096
- * Default value is `LedgerW`.
24097
- * @param {LedgerPathCalculation} [pathFunction=getLedgerPathBuffer221]
24098
- * defines the function that will calculate the path. By default `getLedgerPathBuffer221` is selected.
24099
- *
24100
- * If you are using APP v2.3.1 with an account created with the v1.1.1, you need to use :
24101
- * ```typescript
24102
- * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0, undefined, getLedgerPathBuffer111);
24103
- * ```
24104
- * @example
24105
- * ```typescript
24106
- * import TransportNodeHid from "@ledgerhq/hw-transport-node-hid";
24107
- * const myNodeTransport = await TransportNodeHid.create();
24108
- * const myLedgerSigner = new LedgerSigner231(myNodeTransport, 0);
24109
- * ```
24558
+ * @param {Call} call A Call to convert.
24559
+ * @return {Uint8Array[]} Call encoded in an array of Uint8Array (each containing 7 u256).
24110
24560
  */
24111
- constructor(transport, accountID, eip2645application = "LedgerW", pathFunction = getLedgerPathBuffer221) {
24112
- super(transport, accountID, eip2645application, pathFunction);
24561
+ encodeCall(call) {
24562
+ const toBuf = this.convertBnToLedger(call.contractAddress);
24563
+ const selectorBuf = hexToBytes3(addAddressPadding(getSelector(call.entrypoint)));
24564
+ let calldataBuf = new Uint8Array([]);
24565
+ if (call.calldata) {
24566
+ const compiledCalldata = CallData.compile(call.calldata);
24567
+ calldataBuf = concatenateArrayBuffer(
24568
+ compiledCalldata.map((parameter) => {
24569
+ const a = this.convertBnToLedger(parameter);
24570
+ return a;
24571
+ })
24572
+ );
24573
+ }
24574
+ const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
24575
+ const calldatas = [];
24576
+ const chunkSize = 7 * 32;
24577
+ for (let i = 0; i < callBuf.length; i += chunkSize)
24578
+ calldatas.push(callBuf.subarray(i, i + chunkSize));
24579
+ return calldatas;
24113
24580
  }
24114
24581
  /**
24115
24582
  * Ask to the Ledger Nano to display and sign a Starknet V3 transaction.
@@ -24147,61 +24614,53 @@ ${indent}}` : "}";
24147
24614
  );
24148
24615
  await this._transporter.send(Number("0x5a"), 3, 0, 0, buffer_default.from(this.pathBuffer));
24149
24616
  const accountAddressBuf = this.convertBnToLedger(txDetails.walletAddress);
24617
+ const tipBuf = this.convertBnToLedger(txDetails.tip);
24150
24618
  const chainIdBuf = this.convertBnToLedger(txDetails.chainId);
24151
24619
  const nonceBuf = this.convertBnToLedger(txDetails.nonce);
24152
24620
  const dAModeHashBuf = this.convertBnToLedger(
24153
24621
  hashDAMode(
24154
- intDAM(txDetails.nonceDataAvailabilityMode),
24155
- intDAM(txDetails.feeDataAvailabilityMode)
24622
+ txDetails.nonceDataAvailabilityMode === EDataAvailabilityMode2.L1 ? EDAMode2.L1 : EDAMode2.L2,
24623
+ txDetails.feeDataAvailabilityMode === EDataAvailabilityMode2.L1 ? EDAMode2.L1 : EDAMode2.L2
24156
24624
  )
24157
24625
  );
24626
+ const l1_gasBuf = this.convertBnToLedger(encodeResourceBoundsL1(txDetails.resourceBounds));
24627
+ const l2_gasBuf = this.convertBnToLedger(encodeResourceBoundsL2(txDetails.resourceBounds));
24158
24628
  const dataBuf = concatenateArrayBuffer([
24159
24629
  accountAddressBuf,
24630
+ tipBuf,
24631
+ l1_gasBuf,
24632
+ l2_gasBuf,
24160
24633
  chainIdBuf,
24161
24634
  nonceBuf,
24162
24635
  dAModeHashBuf
24163
24636
  ]);
24164
24637
  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
24638
  const paymasterBuf = concatenateArrayBuffer(
24181
24639
  txDetails.paymasterData.map((value) => {
24182
24640
  const a = this.convertBnToLedger(value);
24183
24641
  return a;
24184
24642
  })
24185
24643
  );
24186
- await this._transporter.send(Number("0x5a"), 3, 3, 0, buffer_default.from(paymasterBuf));
24644
+ await this._transporter.send(Number("0x5a"), 3, 2, 0, buffer_default.from(paymasterBuf));
24187
24645
  const accountDeployDataBuf = concatenateArrayBuffer(
24188
24646
  txDetails.paymasterData.map((value) => {
24189
24647
  const a = this.convertBnToLedger(value);
24190
24648
  return a;
24191
24649
  })
24192
24650
  );
24193
- await this._transporter.send(Number("0x5a"), 3, 4, 0, buffer_default.from(accountDeployDataBuf));
24651
+ await this._transporter.send(Number("0x5a"), 3, 3, 0, buffer_default.from(accountDeployDataBuf));
24194
24652
  const nbCallsBuf = this.convertBnToLedger(calls.length);
24195
- await this._transporter.send(Number("0x5a"), 3, 5, 0, buffer_default.from(nbCallsBuf));
24653
+ await this._transporter.send(Number("0x5a"), 3, 4, 0, buffer_default.from(nbCallsBuf));
24196
24654
  let respSign = new Uint8Array(0);
24197
24655
  for (const call of calls) {
24198
24656
  const calldatas = this.encodeCall(call);
24199
- respSign = await this._transporter.send(Number("0x5a"), 3, 6, 0, buffer_default.from(calldatas[0]));
24657
+ await this._transporter.send(Number("0x5a"), 3, 5, 0, buffer_default.from(calldatas[0]));
24200
24658
  if (calldatas.length > 1) {
24201
24659
  calldatas.slice(1).forEach(async (part) => {
24202
- respSign = await this._transporter.send(Number("0x5a"), 3, 6, 1, buffer_default.from(part));
24660
+ await this._transporter.send(Number("0x5a"), 3, 5, 1, buffer_default.from(part));
24203
24661
  });
24204
24662
  }
24663
+ respSign = await this._transporter.send(Number("0x5a"), 3, 5, 2);
24205
24664
  }
24206
24665
  return this.decodeSignatureLedger(respSign);
24207
24666
  }
@@ -24231,581 +24690,360 @@ ${indent}}` : "}";
24231
24690
  * const res = await myLedgerSigner.signDeployAccountV3(deployData);
24232
24691
  * // res = {hash:
24233
24692
  * // signature:
24234
- * // }
24235
- * ```
24236
- */
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);
24305
- }
24306
- /** Internal function to convert a Call to an array of Uint8Array.
24307
- * @param {Call} call A Call to convert.
24308
- * @return {Uint8Array[]} Call encoded in an array of Uint8Array (each containing 7 u256).
24309
- */
24310
- encodeCall(call) {
24311
- const toBuf = this.convertBnToLedger(call.contractAddress);
24312
- const selectorBuf = hexToBytes3(addAddressPadding(getSelector(call.entrypoint)));
24313
- let calldataBuf;
24314
- if (call.calldata) {
24315
- const compiledCalldata = CallData.compile(call.calldata);
24316
- const calldataSizeBuf = this.convertBnToLedger(compiledCalldata.length);
24317
- calldataBuf = concatenateArrayBuffer([
24318
- calldataSizeBuf,
24319
- ...compiledCalldata.map((parameter) => {
24320
- const a = this.convertBnToLedger(parameter);
24321
- return a;
24322
- })
24323
- ]);
24324
- } else {
24325
- calldataBuf = this.convertBnToLedger("0x00");
24326
- }
24327
- const callBuf = concatenateArrayBuffer([toBuf, selectorBuf, calldataBuf]);
24328
- const calldatas = [];
24329
- const chunkSize = 7 * 32;
24330
- for (let i = 0; i < callBuf.length; i += chunkSize)
24331
- calldatas.push(callBuf.subarray(i, i + chunkSize));
24332
- return calldatas;
24333
- }
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");
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
24700
+ );
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
+ )
24708
+ );
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)
24723
+ );
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));
24432
24752
  }
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;
24753
+ return this.decodeSignatureLedger(respSign);
24458
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;
24459
24778
  }
24460
24779
 
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!");
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);
24471
24806
  }
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);
24518
- assert(
24519
- originalAddress === unsafeAddress,
24520
- `${baseError}: Contract address mismatch at call ${callIndex}. Expected: ${originalCall.contractAddress}, Got: ${unsafeCall.To}`
24521
- );
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.");
24522
24837
  assert(
24523
- getSelectorFromName(originalCall.entrypoint) === unsafeCall.Selector,
24524
- `${baseError}: Entrypoint mismatch at call ${callIndex}. Expected: ${originalCall.entrypoint}, Got: ${unsafeCall.Selector}`
24838
+ txDetails.accountDeploymentData.length <= 7,
24839
+ "accountDeploymentData includes more than 7 items"
24525
24840
  );
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}`
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
+ )
24531
24850
  );
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]}`
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)
24538
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));
24539
24872
  }
24540
- }
24541
- }
24542
- var domainFieldToFelt = (value) => {
24543
- try {
24544
- return toBigInt(value);
24545
- } catch {
24546
- return CairoBytes31.fromText(String(value)).toBigInt();
24547
- }
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;
24561
- assert(
24562
- hasV1Calls !== hasV2Calls,
24563
- 'Paymaster typed data must declare exactly one of "calls" (SNIP-9 V1) or "Calls" (SNIP-9 V2)'
24873
+ const paymasterBuf = concatenateArrayBuffer(
24874
+ txDetails.paymasterData.map((value) => {
24875
+ const a = this.convertBnToLedger(value);
24876
+ return a;
24877
+ })
24564
24878
  );
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
- );
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
+ })
24885
+ );
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
+ });
24578
24897
  }
24579
24898
  }
24899
+ return this.decodeSignatureLedger(respSign);
24580
24900
  }
24581
- };
24582
-
24583
- // src/paymaster/rpc.ts
24584
- var convertCalls = (calls) => calls.map((call) => ({
24585
- to: call.contractAddress,
24586
- selector: getSelectorFromName(call.entrypoint),
24587
- calldata: CallData.toHex(call.calldata)
24588
- }));
24589
- var convertFeeMode = (feeMode) => {
24590
- if (feeMode.mode === "sponsored") {
24591
- return { mode: "sponsored" };
24592
- }
24593
- return { mode: "default", gas_token: feeMode.gasToken };
24594
- };
24595
- var convertFEE_MODE = (feeMode) => {
24596
- if (feeMode.mode === "sponsored") {
24597
- return { mode: "sponsored" };
24598
- }
24599
- return { mode: "default", gasToken: feeMode.gas_token };
24600
- };
24601
- var convertTimeBounds = (timeBounds) => timeBounds ? {
24602
- execute_after: timeBounds.executeAfter || 1,
24603
- // If executeAfter is not provided, set it to 1, meaning the transaction can be executed immediately
24604
- execute_before: timeBounds.executeBefore
24605
- } : void 0;
24606
- var convertTIME_BOUNDS = (timeBounds) => timeBounds ? {
24607
- executeAfter: timeBounds.execute_after,
24608
- executeBefore: timeBounds.execute_before
24609
- } : void 0;
24610
- var convertEXECUTION_PARAMETERS = (parameters) => ({
24611
- version: parameters.version,
24612
- feeMode: convertFEE_MODE(parameters.fee_mode),
24613
- timeBounds: convertTIME_BOUNDS(parameters.time_bounds)
24614
- });
24615
- var defaultOptions = {
24616
- headers: { "Content-Type": "application/json" }
24617
- };
24618
- var PaymasterRpc = class _PaymasterRpc {
24619
- nodeUrl;
24620
- headers;
24621
- baseFetch;
24622
- requestId;
24623
- constructor(options) {
24624
- if (options instanceof _PaymasterRpc) {
24625
- this.nodeUrl = options.nodeUrl;
24626
- this.headers = { ...defaultOptions.headers, ...options.headers };
24627
- this.baseFetch = options.baseFetch;
24628
- this.requestId = options.requestId;
24629
- return;
24630
- }
24631
- if (options && "nodeUrl" in options && "headers" in options && "baseFetch" in options) {
24632
- this.nodeUrl = options.nodeUrl ?? getDefaultPaymasterNodeUrl(void 0);
24633
- this.headers = { ...defaultOptions.headers, ...options.headers };
24634
- this.baseFetch = options.baseFetch ?? fetch_default;
24635
- this.requestId = 0;
24636
- return;
24637
- }
24638
- const { nodeUrl, headers, baseFetch } = options || {};
24639
- if (nodeUrl && Object.values(_NetworkName).includes(nodeUrl)) {
24640
- this.nodeUrl = getDefaultPaymasterNodeUrl(nodeUrl, options?.mute);
24641
- } else if (nodeUrl) {
24642
- this.nodeUrl = nodeUrl;
24643
- } else {
24644
- this.nodeUrl = getDefaultPaymasterNodeUrl(void 0, options?.mute);
24645
- }
24646
- this.baseFetch = baseFetch ?? fetch_default;
24647
- this.headers = { ...defaultOptions.headers, ...headers };
24648
- this.requestId = 0;
24649
- }
24650
- fetch(method, params, id = 0) {
24651
- const rpcRequestBody = {
24652
- id,
24653
- jsonrpc: "2.0",
24654
- method,
24655
- ...params && { params }
24656
- };
24657
- return this.baseFetch(this.nodeUrl, {
24658
- method: "POST",
24659
- body: stringify2(rpcRequestBody),
24660
- headers: this.headers
24661
- });
24662
- }
24663
- errorHandler(method, params, rpcError, otherError) {
24664
- if (rpcError) {
24665
- throw new RpcError(rpcError, method, params);
24666
- }
24667
- if (otherError instanceof LibraryError) {
24668
- throw otherError;
24669
- }
24670
- if (otherError) {
24671
- throw Error(otherError.message);
24672
- }
24673
- }
24674
- async fetchEndpoint(method, params) {
24675
- try {
24676
- this.requestId += 1;
24677
- const rawResult = await this.fetch(method, params, this.requestId);
24678
- const { error, result } = await rawResult.json();
24679
- this.errorHandler(method, params, error);
24680
- return result;
24681
- } catch (error) {
24682
- this.errorHandler(method, params, error?.response?.data, error);
24683
- throw error;
24684
- }
24685
- }
24686
- async isAvailable() {
24687
- return this.fetchEndpoint("paymaster_isAvailable");
24688
- }
24689
- async buildTransaction(transaction, parameters) {
24690
- let userTransaction;
24691
- switch (transaction.type) {
24692
- case "invoke":
24693
- userTransaction = {
24694
- ...transaction,
24695
- invoke: {
24696
- user_address: transaction.invoke.userAddress,
24697
- calls: convertCalls(transaction.invoke.calls)
24698
- }
24699
- };
24700
- break;
24701
- case "deploy_and_invoke":
24702
- userTransaction = {
24703
- ...transaction,
24704
- invoke: {
24705
- user_address: transaction.invoke.userAddress,
24706
- calls: convertCalls(transaction.invoke.calls)
24707
- }
24708
- };
24709
- break;
24710
- case "deploy":
24711
- default:
24712
- userTransaction = transaction;
24713
- 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));
24714
24972
  }
24715
- const executionParameters = {
24716
- version: parameters.version,
24717
- fee_mode: convertFeeMode(parameters.feeMode),
24718
- time_bounds: convertTimeBounds(parameters.timeBounds)
24719
- };
24720
- const response = await this.fetchEndpoint("paymaster_buildTransaction", {
24721
- transaction: userTransaction,
24722
- parameters: executionParameters
24723
- });
24724
- const fee = {
24725
- gas_token_price_in_strk: BigInt(response.fee.gas_token_price_in_strk),
24726
- estimated_fee_in_strk: BigInt(response.fee.estimated_fee_in_strk),
24727
- estimated_fee_in_gas_token: BigInt(response.fee.estimated_fee_in_gas_token),
24728
- suggested_max_fee_in_strk: BigInt(response.fee.suggested_max_fee_in_strk),
24729
- suggested_max_fee_in_gas_token: BigInt(response.fee.suggested_max_fee_in_gas_token)
24730
- };
24731
- switch (response.type) {
24732
- case "invoke":
24733
- return {
24734
- type: "invoke",
24735
- typed_data: response.typed_data,
24736
- parameters: convertEXECUTION_PARAMETERS(response.parameters),
24737
- fee
24738
- };
24739
- case "deploy_and_invoke":
24740
- return {
24741
- type: "deploy_and_invoke",
24742
- deployment: response.deployment,
24743
- typed_data: response.typed_data,
24744
- parameters: convertEXECUTION_PARAMETERS(response.parameters),
24745
- fee
24746
- };
24747
- case "deploy":
24748
- default:
24749
- return {
24750
- type: "deploy",
24751
- deployment: response.deployment,
24752
- parameters: convertEXECUTION_PARAMETERS(response.parameters),
24753
- fee
24754
- };
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));
24755
24996
  }
24997
+ return this.decodeSignatureLedger(respSign);
24756
24998
  }
24757
- async executeTransaction(transaction, parameters) {
24758
- let user_transaction;
24759
- switch (transaction.type) {
24760
- case "invoke":
24761
- user_transaction = {
24762
- ...transaction,
24763
- invoke: {
24764
- user_address: transaction.invoke.userAddress,
24765
- typed_data: transaction.invoke.typedData,
24766
- signature: signatureToHexArray(transaction.invoke.signature)
24767
- }
24768
- };
24769
- break;
24770
- case "deploy_and_invoke":
24771
- user_transaction = {
24772
- ...transaction,
24773
- invoke: {
24774
- user_address: transaction.invoke.userAddress,
24775
- typed_data: transaction.invoke.typedData,
24776
- signature: signatureToHexArray(transaction.invoke.signature)
24777
- }
24778
- };
24779
- break;
24780
- case "deploy":
24781
- default:
24782
- user_transaction = transaction;
24783
- 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");
24784
25019
  }
24785
- const executionParameters = {
24786
- version: parameters.version,
24787
- fee_mode: convertFeeMode(parameters.feeMode),
24788
- time_bounds: convertTimeBounds(parameters.timeBounds)
24789
- };
24790
- return this.fetchEndpoint("paymaster_executeTransaction", {
24791
- transaction: user_transaction,
24792
- parameters: executionParameters
24793
- });
24794
- }
24795
- async getSupportedTokens() {
24796
- return this.fetchEndpoint("paymaster_getSupportedTokens").then(
24797
- (tokens) => tokens.map((token) => ({
24798
- token_address: token.token_address,
24799
- decimals: token.decimals,
24800
- priceInStrk: BigInt(token.price_in_strk)
24801
- }))
24802
- );
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;
24803
25026
  }
24804
25027
  };
24805
25028
 
24806
- // src/paymaster/interface.ts
24807
- var PaymasterInterface = class {
24808
- };
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
+ }
24809
25047
 
24810
25048
  // src/deployer/compileConstructorCalldata.ts
24811
25049
  function checkCompiledConstructorCalldata(calldata, abi) {
@@ -24962,7 +25200,6 @@ ${indent}}` : "}";
24962
25200
  // holds Cairo 0 contracts, to refuse a Cairo 0 account; otherwise remove it.
24963
25201
  cairoVersion;
24964
25202
  transactionVersion;
24965
- paymaster;
24966
25203
  deployer;
24967
25204
  defaultTipType;
24968
25205
  /** @internal Account-level plugin management */
@@ -24984,11 +25221,13 @@ ${indent}}` : "}";
24984
25221
  this.cairoVersion = cairoVersion.toString();
24985
25222
  }
24986
25223
  this.transactionVersion = transactionVersion ?? config.get("transactionVersion");
24987
- this.paymaster = paymaster ? new PaymasterRpc(paymaster) : new PaymasterRpc({ mute: true });
24988
25224
  this.deployer = options.deployer ?? defaultDeployer;
24989
25225
  this.defaultTipType = defaultTipType ?? config.get("defaultTipType");
24990
25226
  this.accountPluginManager = new PluginManager();
24991
- const plugins = options.plugins === false ? [] : options.plugins ?? defaultPlugins;
25227
+ const plugins = applyPaymasterOption(
25228
+ options.plugins === false ? [] : options.plugins ?? defaultPlugins,
25229
+ paymaster
25230
+ );
24992
25231
  plugins.forEach((plugin) => {
24993
25232
  this.accountPluginManager.installOnAccount(plugin, this);
24994
25233
  });
@@ -25699,99 +25938,6 @@ ${indent}}` : "}";
25699
25938
  })
25700
25939
  );
25701
25940
  }
25702
- /*
25703
- * SNIP-29 Paymaster
25704
- */
25705
- async buildPaymasterTransaction(calls, paymasterDetails) {
25706
- if (!paymasterDetails.deploymentData) {
25707
- const snip9Version = await this.getSnip9Version();
25708
- if (snip9Version === OutsideExecutionVersion.UNSUPPORTED) {
25709
- throw Error("Account is not compatible with SNIP-9");
25710
- }
25711
- }
25712
- const parameters = {
25713
- version: "0x1",
25714
- feeMode: paymasterDetails.feeMode,
25715
- timeBounds: paymasterDetails.timeBounds
25716
- };
25717
- let transaction;
25718
- if (paymasterDetails.deploymentData) {
25719
- if (calls.length > 0) {
25720
- transaction = {
25721
- type: "deploy_and_invoke",
25722
- invoke: { userAddress: this.address, calls },
25723
- deployment: paymasterDetails.deploymentData
25724
- };
25725
- } else {
25726
- transaction = {
25727
- type: "deploy",
25728
- deployment: paymasterDetails.deploymentData
25729
- };
25730
- }
25731
- } else {
25732
- transaction = {
25733
- type: "invoke",
25734
- invoke: { userAddress: this.address, calls }
25735
- };
25736
- }
25737
- return this.paymaster.buildTransaction(transaction, parameters);
25738
- }
25739
- async estimatePaymasterTransactionFee(calls, paymasterDetails) {
25740
- const preparedTransaction = await this.buildPaymasterTransaction(calls, paymasterDetails);
25741
- return preparedTransaction.fee;
25742
- }
25743
- async preparePaymasterTransaction(preparedTransaction) {
25744
- let transaction;
25745
- switch (preparedTransaction.type) {
25746
- case "deploy_and_invoke": {
25747
- const signature = await this.signMessage(preparedTransaction.typed_data);
25748
- transaction = {
25749
- type: "deploy_and_invoke",
25750
- invoke: {
25751
- userAddress: this.address,
25752
- typedData: preparedTransaction.typed_data,
25753
- signature: signatureToHexArray(signature)
25754
- },
25755
- deployment: preparedTransaction.deployment
25756
- };
25757
- break;
25758
- }
25759
- case "invoke": {
25760
- const signature = await this.signMessage(preparedTransaction.typed_data);
25761
- transaction = {
25762
- type: "invoke",
25763
- invoke: {
25764
- userAddress: this.address,
25765
- typedData: preparedTransaction.typed_data,
25766
- signature: signatureToHexArray(signature)
25767
- }
25768
- };
25769
- break;
25770
- }
25771
- case "deploy": {
25772
- transaction = {
25773
- type: "deploy",
25774
- deployment: preparedTransaction.deployment
25775
- };
25776
- break;
25777
- }
25778
- default:
25779
- throw Error("Invalid transaction type");
25780
- }
25781
- return transaction;
25782
- }
25783
- async executePaymasterTransaction(calls, paymasterDetails, maxFeeInGasToken) {
25784
- const preparedTransaction = await this.buildPaymasterTransaction(calls, paymasterDetails);
25785
- assertPaymasterTransactionSafety(
25786
- preparedTransaction,
25787
- calls,
25788
- paymasterDetails,
25789
- await this.provider.getChainId(),
25790
- maxFeeInGasToken
25791
- );
25792
- const transaction = await this.preparePaymasterTransaction(preparedTransaction);
25793
- return this.paymaster.executeTransaction(transaction, preparedTransaction.parameters).then((response) => ({ transaction_hash: response.transaction_hash }));
25794
- }
25795
25941
  };
25796
25942
 
25797
25943
  // src/account/interface.ts
@@ -26823,6 +26969,7 @@ ${indent}}` : "}";
26823
26969
  }
26824
26970
 
26825
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.";
26826
26973
  function buildCall(contract, functionAbi) {
26827
26974
  return async function(...args) {
26828
26975
  const options = { ...contract.withOptionsProps };
@@ -27061,13 +27208,12 @@ ${indent}}` : "}";
27061
27208
  await this.ensureProvider();
27062
27209
  if (isAccount(this.providerOrAccount)) {
27063
27210
  if (restInvokeOptions.paymasterDetails) {
27064
- const myCall = {
27065
- contractAddress: this.address,
27066
- entrypoint: method,
27067
- calldata: args
27068
- };
27211
+ assert(
27212
+ typeof this.providerOrAccount.executePaymasterTransaction === "function",
27213
+ NO_PAYMASTER_MESSAGE
27214
+ );
27069
27215
  return this.providerOrAccount.executePaymasterTransaction(
27070
- [myCall],
27216
+ [invocation],
27071
27217
  restInvokeOptions.paymasterDetails,
27072
27218
  restInvokeOptions.maxFeeInGasToken
27073
27219
  );
@@ -27111,13 +27257,12 @@ ${indent}}` : "}";
27111
27257
  await this.ensureProvider();
27112
27258
  if (isAccount(this.providerOrAccount)) {
27113
27259
  if (estimateDetails.paymasterDetails) {
27114
- const myCall = {
27115
- contractAddress: this.address,
27116
- entrypoint: method,
27117
- calldata: args
27118
- };
27260
+ assert(
27261
+ typeof this.providerOrAccount.estimatePaymasterTransactionFee === "function",
27262
+ NO_PAYMASTER_MESSAGE
27263
+ );
27119
27264
  return this.providerOrAccount.estimatePaymasterTransactionFee(
27120
- [myCall],
27265
+ [invocation],
27121
27266
  estimateDetails.paymasterDetails
27122
27267
  );
27123
27268
  }