@safe-global/relay-kit 3.4.3 → 4.0.0-alpha.1

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.
Files changed (93) hide show
  1. package/dist/cjs/src/index.cjs +1497 -0
  2. package/dist/cjs/test-utils/index.cjs +1360 -0
  3. package/dist/esm/src/index.mjs +1487 -0
  4. package/dist/esm/test-utils/index.mjs +1348 -0
  5. package/dist/src/RelayKitBasePack.d.ts +1 -0
  6. package/dist/src/RelayKitBasePack.d.ts.map +1 -0
  7. package/dist/src/constants.d.ts +1 -0
  8. package/dist/src/constants.d.ts.map +1 -0
  9. package/dist/src/deprecated.d.ts +1 -0
  10. package/dist/src/deprecated.d.ts.map +1 -0
  11. package/dist/src/index.d.ts +6 -1
  12. package/dist/src/index.d.ts.map +1 -0
  13. package/dist/src/packs/gelato/GelatoRelayPack.d.ts +1 -0
  14. package/dist/src/packs/gelato/GelatoRelayPack.d.ts.map +1 -0
  15. package/dist/src/packs/gelato/types.d.ts +1 -0
  16. package/dist/src/packs/gelato/types.d.ts.map +1 -0
  17. package/dist/src/packs/safe-4337/BaseSafeOperation.d.ts +18 -0
  18. package/dist/src/packs/safe-4337/BaseSafeOperation.d.ts.map +1 -0
  19. package/dist/src/packs/safe-4337/Safe4337Pack.d.ts +17 -17
  20. package/dist/src/packs/safe-4337/Safe4337Pack.d.ts.map +1 -0
  21. package/dist/src/packs/safe-4337/SafeOperationFactory.d.ts +13 -0
  22. package/dist/src/packs/safe-4337/SafeOperationFactory.d.ts.map +1 -0
  23. package/dist/src/packs/safe-4337/SafeOperationV06.d.ts +16 -0
  24. package/dist/src/packs/safe-4337/SafeOperationV06.d.ts.map +1 -0
  25. package/dist/src/packs/safe-4337/SafeOperationV07.d.ts +16 -0
  26. package/dist/src/packs/safe-4337/SafeOperationV07.d.ts.map +1 -0
  27. package/dist/src/packs/safe-4337/constants.d.ts +11 -3
  28. package/dist/src/packs/safe-4337/constants.d.ts.map +1 -0
  29. package/dist/src/packs/safe-4337/estimators/index.d.ts +2 -1
  30. package/dist/src/packs/safe-4337/estimators/index.d.ts.map +1 -0
  31. package/dist/src/packs/safe-4337/estimators/pimlico/PimlicoFeeEstimator.d.ts +13 -0
  32. package/dist/src/packs/safe-4337/estimators/pimlico/PimlicoFeeEstimator.d.ts.map +1 -0
  33. package/dist/src/packs/safe-4337/estimators/pimlico/types.d.ts +48 -0
  34. package/dist/src/packs/safe-4337/estimators/pimlico/types.d.ts.map +1 -0
  35. package/dist/src/packs/safe-4337/types.d.ts +50 -44
  36. package/dist/src/packs/safe-4337/types.d.ts.map +1 -0
  37. package/dist/src/packs/safe-4337/utils/encodeNonce.d.ts +5 -0
  38. package/dist/src/packs/safe-4337/utils/encodeNonce.d.ts.map +1 -0
  39. package/dist/src/packs/safe-4337/utils/entrypoint.d.ts +4 -0
  40. package/dist/src/packs/safe-4337/utils/entrypoint.d.ts.map +1 -0
  41. package/dist/src/packs/safe-4337/utils/getRelayKitVersion.d.ts +1 -0
  42. package/dist/src/packs/safe-4337/utils/getRelayKitVersion.d.ts.map +1 -0
  43. package/dist/src/packs/safe-4337/utils/index.d.ts +22 -0
  44. package/dist/src/packs/safe-4337/utils/index.d.ts.map +1 -0
  45. package/dist/src/packs/safe-4337/utils/signing.d.ts +37 -0
  46. package/dist/src/packs/safe-4337/utils/signing.d.ts.map +1 -0
  47. package/dist/src/packs/safe-4337/utils/userOperations.d.ts +27 -0
  48. package/dist/src/packs/safe-4337/utils/userOperations.d.ts.map +1 -0
  49. package/dist/{src/packs/safe-4337/testing-utils → test-utils}/fixtures.d.ts +28 -5
  50. package/dist/test-utils/fixtures.d.ts.map +1 -0
  51. package/dist/{src/packs/safe-4337/testing-utils → test-utils}/helpers.d.ts +3 -2
  52. package/dist/test-utils/helpers.d.ts.map +1 -0
  53. package/dist/test-utils/index.d.ts +4 -0
  54. package/dist/test-utils/index.d.ts.map +1 -0
  55. package/dist/tsconfig.build.tsbuildinfo +1 -1
  56. package/package.json +23 -6
  57. package/dist/src/RelayKitBasePack.js +0 -26
  58. package/dist/src/RelayKitBasePack.js.map +0 -1
  59. package/dist/src/constants.js +0 -12
  60. package/dist/src/constants.js.map +0 -1
  61. package/dist/src/deprecated.js +0 -3
  62. package/dist/src/deprecated.js.map +0 -1
  63. package/dist/src/index.js +0 -30
  64. package/dist/src/index.js.map +0 -1
  65. package/dist/src/packs/gelato/GelatoRelayPack.js +0 -327
  66. package/dist/src/packs/gelato/GelatoRelayPack.js.map +0 -1
  67. package/dist/src/packs/gelato/types.js +0 -3
  68. package/dist/src/packs/gelato/types.js.map +0 -1
  69. package/dist/src/packs/safe-4337/Safe4337Pack.js +0 -644
  70. package/dist/src/packs/safe-4337/Safe4337Pack.js.map +0 -1
  71. package/dist/src/packs/safe-4337/SafeOperation.d.ts +0 -22
  72. package/dist/src/packs/safe-4337/SafeOperation.js +0 -68
  73. package/dist/src/packs/safe-4337/SafeOperation.js.map +0 -1
  74. package/dist/src/packs/safe-4337/constants.js +0 -55
  75. package/dist/src/packs/safe-4337/constants.js.map +0 -1
  76. package/dist/src/packs/safe-4337/estimators/PimlicoFeeEstimator.d.ts +0 -8
  77. package/dist/src/packs/safe-4337/estimators/PimlicoFeeEstimator.js +0 -49
  78. package/dist/src/packs/safe-4337/estimators/PimlicoFeeEstimator.js.map +0 -1
  79. package/dist/src/packs/safe-4337/estimators/index.js +0 -6
  80. package/dist/src/packs/safe-4337/estimators/index.js.map +0 -1
  81. package/dist/src/packs/safe-4337/testing-utils/fixtures.js +0 -128
  82. package/dist/src/packs/safe-4337/testing-utils/fixtures.js.map +0 -1
  83. package/dist/src/packs/safe-4337/testing-utils/helpers.js +0 -58
  84. package/dist/src/packs/safe-4337/testing-utils/helpers.js.map +0 -1
  85. package/dist/src/packs/safe-4337/types.js +0 -3
  86. package/dist/src/packs/safe-4337/types.js.map +0 -1
  87. package/dist/src/packs/safe-4337/utils/entrypoint.js +0 -23
  88. package/dist/src/packs/safe-4337/utils/entrypoint.js.map +0 -1
  89. package/dist/src/packs/safe-4337/utils/getRelayKitVersion.js +0 -6
  90. package/dist/src/packs/safe-4337/utils/getRelayKitVersion.js.map +0 -1
  91. package/dist/src/packs/safe-4337/utils.d.ts +0 -91
  92. package/dist/src/packs/safe-4337/utils.js +0 -190
  93. package/dist/src/packs/safe-4337/utils.js.map +0 -1
@@ -0,0 +1,1497 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ BaseSafeOperation: () => BaseSafeOperation_default,
34
+ DUMMY_AUTHENTICATOR_DATA: () => DUMMY_AUTHENTICATOR_DATA,
35
+ DUMMY_CLIENT_DATA_FIELDS: () => DUMMY_CLIENT_DATA_FIELDS,
36
+ EQ_OR_GT_0_3_0: () => EQ_OR_GT_0_3_0,
37
+ GelatoRelayPack: () => GelatoRelayPack,
38
+ PimlicoFeeEstimator: () => PimlicoFeeEstimator,
39
+ RelayKitBasePack: () => RelayKitBasePack,
40
+ Safe4337Pack: () => Safe4337Pack,
41
+ SafeOperationFactory: () => SafeOperationFactory_default,
42
+ SafeOperationV06: () => SafeOperationV06_default,
43
+ SafeOperationV07: () => SafeOperationV07_default,
44
+ createBundlerClient: () => createBundlerClient,
45
+ createUserOperation: () => createUserOperation,
46
+ encodeMultiSendCallData: () => encodeMultiSendCallData,
47
+ encodeNonce: () => encodeNonce,
48
+ entryPointToSafeModules: () => entryPointToSafeModules,
49
+ getDummySignature: () => getDummySignature,
50
+ getRelayKitVersion: () => getRelayKitVersion,
51
+ getSafeNonceFromEntrypoint: () => getSafeNonceFromEntrypoint,
52
+ getSignatureBytes: () => getSignatureBytes,
53
+ isEntryPointV6: () => isEntryPointV6,
54
+ isEntryPointV7: () => isEntryPointV7,
55
+ sameString: () => sameString,
56
+ userOperationToHexValues: () => userOperationToHexValues
57
+ });
58
+ module.exports = __toCommonJS(src_exports);
59
+
60
+ // src/packs/gelato/GelatoRelayPack.ts
61
+ var import_relay_sdk = require("@gelatonetwork/relay-sdk");
62
+ var import_protocol_kit = require("@safe-global/protocol-kit");
63
+
64
+ // src/RelayKitBasePack.ts
65
+ var RelayKitBasePack = class {
66
+ /**
67
+ * Creates a new RelayKitBasePack instance.
68
+ * The packs implemented using our SDK should extend this class and therefore provide a Safe SDK instance
69
+ * @param {Safe} protocolKit - The Safe SDK instance
70
+ */
71
+ constructor(protocolKit) {
72
+ this.protocolKit = protocolKit;
73
+ }
74
+ };
75
+
76
+ // src/constants.ts
77
+ var GELATO_NATIVE_TOKEN_ADDRESS = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
78
+ var GELATO_FEE_COLLECTOR = "0x3AC05161b76a35c1c28dC99Aa01BEd7B24cEA3bf";
79
+ var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
80
+ var GELATO_GAS_EXECUTION_OVERHEAD = 15e4;
81
+ var GELATO_TRANSFER_GAS_COST = 15e3;
82
+
83
+ // src/packs/gelato/GelatoRelayPack.ts
84
+ var GelatoRelayPack = class extends RelayKitBasePack {
85
+ #gelatoRelay;
86
+ #apiKey;
87
+ constructor({ apiKey, protocolKit }) {
88
+ super(protocolKit);
89
+ this.#gelatoRelay = new import_relay_sdk.GelatoRelay();
90
+ this.#apiKey = apiKey;
91
+ }
92
+ _getFeeToken(gasToken) {
93
+ return !gasToken || gasToken === ZERO_ADDRESS ? GELATO_NATIVE_TOKEN_ADDRESS : gasToken;
94
+ }
95
+ getFeeCollector() {
96
+ return GELATO_FEE_COLLECTOR;
97
+ }
98
+ async getEstimateFee(propsOrChainId, inputGasLimit, inputGasToken) {
99
+ let chainId;
100
+ let gasLimit;
101
+ let gasToken;
102
+ if (typeof propsOrChainId === "object") {
103
+ ;
104
+ ({ chainId, gasLimit, gasToken } = propsOrChainId);
105
+ } else {
106
+ chainId = propsOrChainId;
107
+ gasLimit = inputGasLimit;
108
+ gasToken = inputGasToken;
109
+ }
110
+ const feeToken = this._getFeeToken(gasToken);
111
+ const estimation = await this.#gelatoRelay.getEstimatedFee(
112
+ chainId,
113
+ feeToken,
114
+ BigInt(gasLimit),
115
+ false
116
+ );
117
+ return estimation.toString();
118
+ }
119
+ async getTaskStatus(taskId) {
120
+ return this.#gelatoRelay.getTaskStatus(taskId);
121
+ }
122
+ /**
123
+ * Creates a payment transaction to Gelato
124
+ *
125
+ * @private
126
+ * @async
127
+ * @function
128
+ * @param {string} gas - The gas amount for the payment.
129
+ * @param {MetaTransactionOptions} options - Options for the meta transaction.
130
+ * @returns {Promise<Transaction>} Promise object representing the created payment transaction.
131
+ *
132
+ */
133
+ async createPaymentToGelato(gas, options) {
134
+ const chainId = await this.protocolKit.getChainId();
135
+ const gelatoAddress = this.getFeeCollector();
136
+ const gasToken = options.gasToken ?? ZERO_ADDRESS;
137
+ const paymentToGelato = await this.getEstimateFee({ chainId, gasLimit: gas, gasToken });
138
+ const transferToGelato = (0, import_protocol_kit.createERC20TokenTransferTransaction)(
139
+ gasToken,
140
+ gelatoAddress,
141
+ paymentToGelato
142
+ );
143
+ return transferToGelato;
144
+ }
145
+ /**
146
+ * @deprecated Use createTransaction instead
147
+ */
148
+ async createRelayedTransaction({
149
+ transactions,
150
+ onlyCalls = false,
151
+ options = {}
152
+ }) {
153
+ return this.createTransaction({ transactions, onlyCalls, options });
154
+ }
155
+ /**
156
+ * Creates a Safe transaction designed to be executed using the Gelato Relayer.
157
+ *
158
+ * @param {GelatoCreateTransactionProps} options - Options for Gelato.
159
+ * @param {MetaTransactionData[]} [options.transactions] - The transactions batch.
160
+ * @param {boolean} [options.onlyCalls=false] - If true, MultiSendCallOnly contract should be used. Remember to not use delegate calls in the batch.
161
+ * @param {MetaTransactionOptions} [options.options={}] - Gas Options for the transaction batch.
162
+ * @returns {Promise<SafeTransaction>} Returns a Promise that resolves with a SafeTransaction object.
163
+ */
164
+ async createTransaction({
165
+ transactions,
166
+ onlyCalls = false,
167
+ options = {}
168
+ }) {
169
+ const { isSponsored = false } = options;
170
+ if (isSponsored) {
171
+ const nonce = await this.protocolKit.getNonce();
172
+ const sponsoredTransaction = await this.protocolKit.createTransaction({
173
+ transactions,
174
+ onlyCalls,
175
+ options: {
176
+ nonce
177
+ }
178
+ });
179
+ return sponsoredTransaction;
180
+ }
181
+ const gasToken = options.gasToken ?? ZERO_ADDRESS;
182
+ const isGasTokenCompatible = await (0, import_protocol_kit.isGasTokenCompatibleWithHandlePayment)(
183
+ gasToken,
184
+ this.protocolKit
185
+ );
186
+ if (!isGasTokenCompatible) {
187
+ return this.createTransactionWithTransfer({ transactions, onlyCalls, options });
188
+ }
189
+ return this.createTransactionWithHandlePayment({ transactions, onlyCalls, options });
190
+ }
191
+ /**
192
+ * Creates a Safe transaction designed to be executed using the Gelato Relayer and
193
+ * uses the handlePayment function defined in the Safe contract to pay the fees
194
+ * to the Gelato relayer.
195
+ *
196
+ * @async
197
+ * @function createTransactionWithHandlePayment
198
+ * @param {GelatoCreateTransactionProps} options - Options for Gelato.
199
+ * @param {MetaTransactionData[]} [options.transactions] - The transactions batch.
200
+ * @param {boolean} [options.onlyCalls=false] - If true, MultiSendCallOnly contract should be used. Remember to not use delegate calls in the batch.
201
+ * @param {MetaTransactionOptions} [options.options={}] - Gas Options for the transaction batch.
202
+ * @returns {Promise<SafeTransaction>} Returns a promise that resolves to the created SafeTransaction.
203
+ * @private
204
+ */
205
+ async createTransactionWithHandlePayment({
206
+ transactions,
207
+ onlyCalls = false,
208
+ options = {}
209
+ }) {
210
+ const { gasLimit } = options;
211
+ const nonce = await this.protocolKit.getNonce();
212
+ const transactionToEstimateGas = await this.protocolKit.createTransaction({
213
+ transactions,
214
+ onlyCalls,
215
+ options: {
216
+ nonce
217
+ }
218
+ });
219
+ const gasPrice = "1";
220
+ const safeTxGas = await (0, import_protocol_kit.estimateSafeTxGas)(this.protocolKit, transactionToEstimateGas);
221
+ const gasToken = options.gasToken ?? ZERO_ADDRESS;
222
+ const refundReceiver = this.getFeeCollector();
223
+ const chainId = await this.protocolKit.getChainId();
224
+ if (gasLimit) {
225
+ const paymentToGelato2 = await this.getEstimateFee({ chainId, gasLimit, gasToken });
226
+ const syncTransaction2 = await this.protocolKit.createTransaction({
227
+ transactions,
228
+ onlyCalls,
229
+ options: {
230
+ baseGas: paymentToGelato2,
231
+ gasPrice,
232
+ safeTxGas,
233
+ gasToken,
234
+ refundReceiver,
235
+ nonce
236
+ }
237
+ });
238
+ return syncTransaction2;
239
+ }
240
+ const baseGas = await (0, import_protocol_kit.estimateTxBaseGas)(this.protocolKit, transactionToEstimateGas);
241
+ const safeDeploymentGasCost = await (0, import_protocol_kit.estimateSafeDeploymentGas)(this.protocolKit);
242
+ const totalGas = Number(baseGas) + // baseGas
243
+ Number(safeTxGas) + // safeTxGas
244
+ Number(safeDeploymentGasCost) + // Safe deploymet gas cost if it is required
245
+ GELATO_GAS_EXECUTION_OVERHEAD;
246
+ const paymentToGelato = await this.getEstimateFee({
247
+ chainId,
248
+ gasLimit: String(totalGas),
249
+ gasToken
250
+ });
251
+ const syncTransaction = await this.protocolKit.createTransaction({
252
+ transactions,
253
+ onlyCalls,
254
+ options: {
255
+ baseGas: paymentToGelato,
256
+ // payment to Gelato
257
+ gasPrice,
258
+ safeTxGas,
259
+ gasToken,
260
+ refundReceiver,
261
+ nonce
262
+ }
263
+ });
264
+ return syncTransaction;
265
+ }
266
+ /**
267
+ * Creates a Safe transaction designed to be executed using the Gelato Relayer and
268
+ * uses a separate ERC20 transfer to pay the fees to the Gelato relayer.
269
+ *
270
+ * @async
271
+ * @function createTransactionWithTransfer
272
+ * @param {GelatoCreateTransactionProps} options - Options for Gelato.
273
+ * @param {MetaTransactionData[]} [options.transactions] - The transactions batch.
274
+ * @param {boolean} [options.onlyCalls=false] - If true, MultiSendCallOnly contract should be used. Remember to not use delegate calls in the batch.
275
+ * @param {MetaTransactionOptions} [options.options={}] - Gas Options for the transaction batch.
276
+ * @returns {Promise<SafeTransaction>} Returns a promise that resolves to the created SafeTransaction.
277
+ * @private
278
+ */
279
+ async createTransactionWithTransfer({
280
+ transactions,
281
+ onlyCalls = false,
282
+ options = {}
283
+ }) {
284
+ const { gasLimit } = options;
285
+ const nonce = await this.protocolKit.getNonce();
286
+ const gasToken = options.gasToken ?? ZERO_ADDRESS;
287
+ if (gasLimit) {
288
+ const transferToGelato2 = await this.createPaymentToGelato(gasLimit, options);
289
+ const syncTransaction2 = await this.protocolKit.createTransaction({
290
+ transactions: [...transactions, transferToGelato2],
291
+ onlyCalls,
292
+ options: {
293
+ nonce,
294
+ gasToken
295
+ }
296
+ });
297
+ return syncTransaction2;
298
+ }
299
+ const transactionToEstimateGas = await this.protocolKit.createTransaction({
300
+ transactions,
301
+ onlyCalls,
302
+ options: {
303
+ nonce
304
+ }
305
+ });
306
+ const safeTxGas = await (0, import_protocol_kit.estimateSafeTxGas)(this.protocolKit, transactionToEstimateGas);
307
+ const baseGas = await (0, import_protocol_kit.estimateTxBaseGas)(this.protocolKit, transactionToEstimateGas);
308
+ const safeDeploymentGasCost = await (0, import_protocol_kit.estimateSafeDeploymentGas)(this.protocolKit);
309
+ const totalGas = Number(baseGas) + // baseGas
310
+ Number(safeTxGas) + // safeTxGas without Gelato payment transfer
311
+ Number(safeDeploymentGasCost) + // Safe deploymet gas cost if it is required
312
+ GELATO_TRANSFER_GAS_COST + // Gelato payment transfer
313
+ GELATO_GAS_EXECUTION_OVERHEAD;
314
+ const transferToGelato = await this.createPaymentToGelato(String(totalGas), options);
315
+ const syncTransaction = await this.protocolKit.createTransaction({
316
+ transactions: [...transactions, transferToGelato],
317
+ onlyCalls,
318
+ options: {
319
+ nonce,
320
+ gasToken
321
+ }
322
+ });
323
+ return syncTransaction;
324
+ }
325
+ async sendSponsorTransaction(target, encodedTransaction, chainId) {
326
+ if (!this.#apiKey) {
327
+ throw new Error("API key not defined");
328
+ }
329
+ const request = {
330
+ chainId,
331
+ target,
332
+ data: encodedTransaction
333
+ };
334
+ const response = await this.#gelatoRelay.sponsoredCall(request, this.#apiKey);
335
+ return response;
336
+ }
337
+ async sendSyncTransaction(target, encodedTransaction, chainId, options) {
338
+ const { gasLimit, gasToken } = options;
339
+ const feeToken = this._getFeeToken(gasToken);
340
+ const request = {
341
+ chainId,
342
+ target,
343
+ data: encodedTransaction,
344
+ feeToken,
345
+ isRelayContext: false
346
+ };
347
+ const relayRequestOptions = {
348
+ gasLimit: gasLimit ? BigInt(gasLimit) : void 0
349
+ };
350
+ const response = await this.#gelatoRelay.callWithSyncFee(request, relayRequestOptions);
351
+ return response;
352
+ }
353
+ async relayTransaction({
354
+ target,
355
+ encodedTransaction,
356
+ chainId,
357
+ options = {}
358
+ }) {
359
+ const response = options.isSponsored ? this.sendSponsorTransaction(target, encodedTransaction, chainId) : this.sendSyncTransaction(target, encodedTransaction, chainId, options);
360
+ return response;
361
+ }
362
+ /**
363
+ * @deprecated Use executeTransaction instead
364
+ */
365
+ async executeRelayTransaction(safeTransaction, options) {
366
+ return this.executeTransaction({ executable: safeTransaction, options });
367
+ }
368
+ /**
369
+ * Sends the Safe transaction to the Gelato Relayer for execution.
370
+ * If the Safe is not deployed, it creates a batch of transactions including the Safe deployment transaction.
371
+ *
372
+ * @param {GelatoExecuteTransactionProps} props - Execution props
373
+ * @param {SafeTransaction} props.executable - The Safe transaction to be executed.
374
+ * @param {MetaTransactionOptions} props.options - Options for the transaction.
375
+ * @returns {Promise<RelayResponse>} Returns a Promise that resolves with a RelayResponse object.
376
+ */
377
+ async executeTransaction({
378
+ executable: safeTransaction,
379
+ options
380
+ }) {
381
+ const isSafeDeployed = await this.protocolKit.isSafeDeployed();
382
+ const chainId = await this.protocolKit.getChainId();
383
+ const safeAddress = await this.protocolKit.getAddress();
384
+ const safeTransactionEncodedData = await this.protocolKit.getEncodedTransaction(safeTransaction);
385
+ const gasToken = options?.gasToken || safeTransaction.data.gasToken;
386
+ if (isSafeDeployed) {
387
+ const relayTransaction2 = {
388
+ target: safeAddress,
389
+ encodedTransaction: safeTransactionEncodedData,
390
+ chainId,
391
+ options: {
392
+ ...options,
393
+ gasToken
394
+ }
395
+ };
396
+ return this.relayTransaction(relayTransaction2);
397
+ }
398
+ const safeDeploymentBatch = await this.protocolKit.wrapSafeTransactionIntoDeploymentBatch(safeTransaction);
399
+ const relayTransaction = {
400
+ target: safeDeploymentBatch.to,
401
+ // multiSend Contract address
402
+ encodedTransaction: safeDeploymentBatch.data,
403
+ chainId,
404
+ options: {
405
+ ...options,
406
+ gasToken
407
+ }
408
+ };
409
+ return this.relayTransaction(relayTransaction);
410
+ }
411
+ };
412
+
413
+ // src/packs/safe-4337/Safe4337Pack.ts
414
+ var import_viem8 = require("viem");
415
+ var import_satisfies = __toESM(require("semver/functions/satisfies.js"));
416
+ var import_protocol_kit5 = __toESM(require("@safe-global/protocol-kit"));
417
+ var import_types_kit3 = require("@safe-global/types-kit");
418
+ var import_safe_modules_deployments = require("@safe-global/safe-modules-deployments");
419
+ var import_viem9 = require("viem");
420
+
421
+ // src/packs/safe-4337/BaseSafeOperation.ts
422
+ var import_viem = require("viem");
423
+ var import_protocol_kit2 = require("@safe-global/protocol-kit");
424
+ var BaseSafeOperation = class {
425
+ constructor(userOperation, options) {
426
+ this.signatures = /* @__PURE__ */ new Map();
427
+ this.userOperation = userOperation;
428
+ this.options = options;
429
+ }
430
+ getSignature(signer) {
431
+ return this.signatures.get(signer.toLowerCase());
432
+ }
433
+ addSignature(signature) {
434
+ this.signatures.set(signature.signer.toLowerCase(), signature);
435
+ }
436
+ encodedSignatures() {
437
+ return (0, import_protocol_kit2.buildSignatureBytes)(Array.from(this.signatures.values()));
438
+ }
439
+ getUserOperation() {
440
+ return {
441
+ ...this.userOperation,
442
+ signature: (0, import_viem.encodePacked)(
443
+ ["uint48", "uint48", "bytes"],
444
+ [
445
+ this.options.validAfter || 0,
446
+ this.options.validUntil || 0,
447
+ this.encodedSignatures()
448
+ ]
449
+ )
450
+ };
451
+ }
452
+ getHash() {
453
+ return (0, import_viem.hashTypedData)({
454
+ domain: {
455
+ chainId: Number(this.options.chainId),
456
+ verifyingContract: this.options.moduleAddress
457
+ },
458
+ types: this.getEIP712Type(),
459
+ primaryType: "SafeOp",
460
+ message: this.getSafeOperation()
461
+ });
462
+ }
463
+ };
464
+ var BaseSafeOperation_default = BaseSafeOperation;
465
+
466
+ // src/packs/safe-4337/constants.ts
467
+ var import_viem2 = require("viem");
468
+ var DEFAULT_SAFE_VERSION = "1.4.1";
469
+ var DEFAULT_SAFE_MODULES_VERSION = "0.3.0";
470
+ var EIP712_SAFE_OPERATION_TYPE_V06 = {
471
+ SafeOp: [
472
+ { type: "address", name: "safe" },
473
+ { type: "uint256", name: "nonce" },
474
+ { type: "bytes", name: "initCode" },
475
+ { type: "bytes", name: "callData" },
476
+ { type: "uint256", name: "callGasLimit" },
477
+ { type: "uint256", name: "verificationGasLimit" },
478
+ { type: "uint256", name: "preVerificationGas" },
479
+ { type: "uint256", name: "maxFeePerGas" },
480
+ { type: "uint256", name: "maxPriorityFeePerGas" },
481
+ { type: "bytes", name: "paymasterAndData" },
482
+ { type: "uint48", name: "validAfter" },
483
+ { type: "uint48", name: "validUntil" },
484
+ { type: "address", name: "entryPoint" }
485
+ ]
486
+ };
487
+ var EIP712_SAFE_OPERATION_TYPE_V07 = {
488
+ SafeOp: [
489
+ { type: "address", name: "safe" },
490
+ { type: "uint256", name: "nonce" },
491
+ { type: "bytes", name: "initCode" },
492
+ { type: "bytes", name: "callData" },
493
+ { type: "uint128", name: "verificationGasLimit" },
494
+ { type: "uint128", name: "callGasLimit" },
495
+ { type: "uint256", name: "preVerificationGas" },
496
+ { type: "uint128", name: "maxPriorityFeePerGas" },
497
+ { type: "uint128", name: "maxFeePerGas" },
498
+ { type: "bytes", name: "paymasterAndData" },
499
+ { type: "uint48", name: "validAfter" },
500
+ { type: "uint48", name: "validUntil" },
501
+ { type: "address", name: "entryPoint" }
502
+ ]
503
+ };
504
+ var ABI = (0, import_viem2.parseAbi)([
505
+ "function enableModules(address[])",
506
+ "function multiSend(bytes memory transactions) public payable",
507
+ "function executeUserOp(address to, uint256 value, bytes data, uint8 operation)",
508
+ "function approve(address _spender, uint256 _value)",
509
+ "function configure((uint256 x, uint256 y, uint176 verifiers) signer)"
510
+ ]);
511
+ var ENTRYPOINT_ABI = [
512
+ {
513
+ inputs: [
514
+ { name: "sender", type: "address" },
515
+ { name: "key", type: "uint192" }
516
+ ],
517
+ name: "getNonce",
518
+ outputs: [{ name: "nonce", type: "uint256" }],
519
+ stateMutability: "view",
520
+ type: "function"
521
+ }
522
+ ];
523
+ var ENTRYPOINT_ADDRESS_V06 = "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789";
524
+ var ENTRYPOINT_ADDRESS_V07 = "0x0000000071727De22E5E9d8BAf0edAc6f37da032";
525
+
526
+ // src/packs/safe-4337/SafeOperationV06.ts
527
+ var SafeOperationV06 = class extends BaseSafeOperation_default {
528
+ constructor(userOperation, options) {
529
+ super(userOperation, options);
530
+ }
531
+ addEstimations(estimations) {
532
+ this.userOperation.maxFeePerGas = BigInt(
533
+ estimations.maxFeePerGas || this.userOperation.maxFeePerGas
534
+ );
535
+ this.userOperation.maxPriorityFeePerGas = BigInt(
536
+ estimations.maxPriorityFeePerGas || this.userOperation.maxPriorityFeePerGas
537
+ );
538
+ this.userOperation.verificationGasLimit = BigInt(
539
+ estimations.verificationGasLimit || this.userOperation.verificationGasLimit
540
+ );
541
+ this.userOperation.preVerificationGas = BigInt(
542
+ estimations.preVerificationGas || this.userOperation.preVerificationGas
543
+ );
544
+ this.userOperation.callGasLimit = BigInt(
545
+ estimations.callGasLimit || this.userOperation.callGasLimit
546
+ );
547
+ this.userOperation.paymasterAndData = estimations.paymasterAndData || this.userOperation.paymasterAndData;
548
+ }
549
+ getSafeOperation() {
550
+ return {
551
+ safe: this.userOperation.sender,
552
+ nonce: this.userOperation.nonce,
553
+ initCode: this.userOperation.initCode,
554
+ callData: this.userOperation.callData,
555
+ callGasLimit: this.userOperation.callGasLimit,
556
+ verificationGasLimit: this.userOperation.verificationGasLimit,
557
+ preVerificationGas: this.userOperation.preVerificationGas,
558
+ maxFeePerGas: this.userOperation.maxFeePerGas,
559
+ maxPriorityFeePerGas: this.userOperation.maxPriorityFeePerGas,
560
+ paymasterAndData: this.userOperation.paymasterAndData,
561
+ validAfter: this.options.validAfter || 0,
562
+ validUntil: this.options.validUntil || 0,
563
+ entryPoint: this.options.entryPoint
564
+ };
565
+ }
566
+ getEIP712Type() {
567
+ return EIP712_SAFE_OPERATION_TYPE_V06;
568
+ }
569
+ };
570
+ var SafeOperationV06_default = SafeOperationV06;
571
+
572
+ // src/packs/safe-4337/SafeOperationV07.ts
573
+ var import_viem3 = require("viem");
574
+ var SafeOperationV07 = class extends BaseSafeOperation_default {
575
+ constructor(userOperation, options) {
576
+ super(userOperation, options);
577
+ }
578
+ addEstimations(estimations) {
579
+ this.userOperation.maxFeePerGas = BigInt(
580
+ estimations.maxFeePerGas || this.userOperation.maxFeePerGas
581
+ );
582
+ this.userOperation.maxPriorityFeePerGas = BigInt(
583
+ estimations.maxPriorityFeePerGas || this.userOperation.maxPriorityFeePerGas
584
+ );
585
+ this.userOperation.verificationGasLimit = BigInt(
586
+ estimations.verificationGasLimit || this.userOperation.verificationGasLimit
587
+ );
588
+ this.userOperation.preVerificationGas = BigInt(
589
+ estimations.preVerificationGas || this.userOperation.preVerificationGas
590
+ );
591
+ this.userOperation.callGasLimit = BigInt(
592
+ estimations.callGasLimit || this.userOperation.callGasLimit
593
+ );
594
+ this.userOperation.paymasterPostOpGasLimit = estimations.paymasterPostOpGasLimit ? BigInt(estimations.paymasterPostOpGasLimit) : this.userOperation.paymasterPostOpGasLimit;
595
+ this.userOperation.paymasterVerificationGasLimit = estimations.paymasterVerificationGasLimit ? BigInt(estimations.paymasterVerificationGasLimit) : this.userOperation.paymasterVerificationGasLimit;
596
+ this.userOperation.paymaster = estimations.paymaster || this.userOperation.paymaster;
597
+ this.userOperation.paymasterData = estimations.paymasterData || this.userOperation.paymasterData;
598
+ }
599
+ getSafeOperation() {
600
+ const initCode = this.userOperation.factory ? (0, import_viem3.concat)([
601
+ this.userOperation.factory,
602
+ this.userOperation.factoryData || "0x"
603
+ ]) : "0x";
604
+ const paymasterAndData = (0, import_viem3.isAddress)(this.userOperation.paymaster || "") ? (0, import_viem3.concat)([
605
+ this.userOperation.paymaster,
606
+ (0, import_viem3.pad)((0, import_viem3.toHex)(this.userOperation.paymasterVerificationGasLimit || 0n), {
607
+ size: 16
608
+ }),
609
+ (0, import_viem3.pad)((0, import_viem3.toHex)(this.userOperation.paymasterPostOpGasLimit || 0n), {
610
+ size: 16
611
+ }),
612
+ this.userOperation.paymasterData || "0x"
613
+ ]) : "0x";
614
+ return {
615
+ safe: this.userOperation.sender,
616
+ nonce: this.userOperation.nonce,
617
+ initCode,
618
+ callData: this.userOperation.callData,
619
+ callGasLimit: this.userOperation.callGasLimit,
620
+ verificationGasLimit: this.userOperation.verificationGasLimit,
621
+ preVerificationGas: this.userOperation.preVerificationGas,
622
+ maxFeePerGas: this.userOperation.maxFeePerGas,
623
+ maxPriorityFeePerGas: this.userOperation.maxPriorityFeePerGas,
624
+ paymasterAndData,
625
+ validAfter: this.options.validAfter || 0,
626
+ validUntil: this.options.validUntil || 0,
627
+ entryPoint: this.options.entryPoint
628
+ };
629
+ }
630
+ getEIP712Type() {
631
+ return EIP712_SAFE_OPERATION_TYPE_V07;
632
+ }
633
+ };
634
+ var SafeOperationV07_default = SafeOperationV07;
635
+
636
+ // src/packs/safe-4337/utils/index.ts
637
+ var import_viem7 = require("viem");
638
+ var import_types_kit2 = require("@safe-global/types-kit");
639
+ var import_protocol_kit4 = require("@safe-global/protocol-kit");
640
+
641
+ // src/packs/safe-4337/utils/entrypoint.ts
642
+ var EQ_0_2_0 = "0.2.0";
643
+ var EQ_OR_GT_0_3_0 = ">=0.3.0";
644
+ function sameString(str1, str2) {
645
+ return str1.toLowerCase() === str2.toLowerCase();
646
+ }
647
+ function entryPointToSafeModules(entryPoint) {
648
+ const moduleVersionToEntryPoint = {
649
+ [ENTRYPOINT_ADDRESS_V06]: EQ_0_2_0,
650
+ [ENTRYPOINT_ADDRESS_V07]: EQ_OR_GT_0_3_0
651
+ };
652
+ return moduleVersionToEntryPoint[entryPoint];
653
+ }
654
+ function isEntryPointV6(address) {
655
+ return sameString(address, ENTRYPOINT_ADDRESS_V06);
656
+ }
657
+ function isEntryPointV7(address) {
658
+ return sameString(address, ENTRYPOINT_ADDRESS_V07);
659
+ }
660
+ async function getSafeNonceFromEntrypoint(protocolKit, safeAddress, entryPointAddress) {
661
+ const safeProvider = protocolKit.getSafeProvider();
662
+ const newNonce = await safeProvider.readContract({
663
+ address: entryPointAddress || "0x",
664
+ abi: ENTRYPOINT_ABI,
665
+ functionName: "getNonce",
666
+ args: [safeAddress, 0n]
667
+ });
668
+ return newNonce;
669
+ }
670
+
671
+ // src/packs/safe-4337/utils/signing.ts
672
+ var import_viem4 = require("viem");
673
+ var import_protocol_kit3 = require("@safe-global/protocol-kit");
674
+ var DUMMY_CLIENT_DATA_FIELDS = [
675
+ `"origin":"https://safe.global"`,
676
+ `"padding":"This pads the clientDataJSON so that we can leave room for additional implementation specific fields for a more accurate 'preVerificationGas' estimate."`
677
+ ].join(",");
678
+ var DUMMY_AUTHENTICATOR_DATA = new Uint8Array(37);
679
+ DUMMY_AUTHENTICATOR_DATA.fill(254);
680
+ DUMMY_AUTHENTICATOR_DATA[32] = 4;
681
+ function getDummySignature(signer, threshold) {
682
+ const signatures = [];
683
+ for (let i = 0; i < threshold; i++) {
684
+ const isContractSignature = true;
685
+ const passkeySignature = getSignatureBytes({
686
+ authenticatorData: DUMMY_AUTHENTICATOR_DATA,
687
+ clientDataFields: DUMMY_CLIENT_DATA_FIELDS,
688
+ r: BigInt(`0x${"ec".repeat(32)}`),
689
+ s: BigInt(`0x${"d5a".repeat(21)}f`)
690
+ });
691
+ signatures.push(new import_protocol_kit3.EthSafeSignature(signer, passkeySignature, isContractSignature));
692
+ }
693
+ return (0, import_viem4.encodePacked)(["uint48", "uint48", "bytes"], [0, 0, (0, import_protocol_kit3.buildSignatureBytes)(signatures)]);
694
+ }
695
+ function getSignatureBytes({
696
+ authenticatorData,
697
+ clientDataFields,
698
+ r,
699
+ s
700
+ }) {
701
+ const encodeUint256 = (x) => x.toString(16).padStart(64, "0");
702
+ const byteSize = (data) => 32 * (Math.ceil(data.length / 32) + 1);
703
+ const encodeBytes = (data) => `${encodeUint256(data.length)}${(0, import_viem4.toHex)(data).slice(2)}`.padEnd(byteSize(data) * 2, "0");
704
+ const authenticatorDataOffset = 32 * 4;
705
+ const clientDataFieldsOffset = authenticatorDataOffset + byteSize(authenticatorData);
706
+ return "0x" + encodeUint256(authenticatorDataOffset) + encodeUint256(clientDataFieldsOffset) + encodeUint256(r) + encodeUint256(s) + encodeBytes(authenticatorData) + encodeBytes(new TextEncoder().encode(clientDataFields));
707
+ }
708
+
709
+ // src/packs/safe-4337/utils/userOperations.ts
710
+ var import_viem5 = require("viem");
711
+ var import_types_kit = require("@safe-global/types-kit");
712
+ function encodeExecuteUserOpCallData(transaction) {
713
+ return (0, import_viem5.encodeFunctionData)({
714
+ abi: ABI,
715
+ functionName: "executeUserOp",
716
+ args: [
717
+ transaction.to,
718
+ BigInt(transaction.value),
719
+ transaction.data,
720
+ transaction.operation || import_types_kit.OperationType.Call
721
+ ]
722
+ });
723
+ }
724
+ async function getCallData(protocolKit, transactions, paymasterOptions, amountToApprove) {
725
+ if (amountToApprove) {
726
+ const approveToPaymasterTransaction = {
727
+ to: paymasterOptions.paymasterTokenAddress,
728
+ data: (0, import_viem5.encodeFunctionData)({
729
+ abi: ABI,
730
+ functionName: "approve",
731
+ args: [paymasterOptions.paymasterAddress, amountToApprove]
732
+ }),
733
+ value: "0",
734
+ operation: import_types_kit.OperationType.Call
735
+ // Call for approve
736
+ };
737
+ transactions.push(approveToPaymasterTransaction);
738
+ }
739
+ const isBatch = transactions.length > 1;
740
+ const multiSendAddress = protocolKit.getMultiSendAddress();
741
+ const callData = isBatch ? encodeExecuteUserOpCallData({
742
+ to: multiSendAddress,
743
+ value: "0",
744
+ data: encodeMultiSendCallData(transactions),
745
+ operation: import_types_kit.OperationType.DelegateCall
746
+ }) : encodeExecuteUserOpCallData(transactions[0]);
747
+ return callData;
748
+ }
749
+ function unpackInitCode(initCode) {
750
+ const initCodeBytes = (0, import_viem5.hexToBytes)(initCode);
751
+ return initCodeBytes.length > 0 ? {
752
+ factory: (0, import_viem5.getAddress)((0, import_viem5.sliceHex)(initCode, 0, 20)),
753
+ factoryData: (0, import_viem5.sliceHex)(initCode, 20)
754
+ } : {};
755
+ }
756
+ async function createUserOperation(protocolKit, transactions, {
757
+ amountToApprove,
758
+ entryPoint,
759
+ paymasterOptions,
760
+ customNonce
761
+ }) {
762
+ const safeAddress = await protocolKit.getAddress();
763
+ const nonce = customNonce || await getSafeNonceFromEntrypoint(protocolKit, safeAddress, entryPoint);
764
+ const isSafeDeployed = await protocolKit.isSafeDeployed();
765
+ const paymasterAndData = paymasterOptions && "paymasterAddress" in paymasterOptions ? paymasterOptions.paymasterAddress : "0x";
766
+ const callData = await getCallData(
767
+ protocolKit,
768
+ transactions,
769
+ paymasterOptions,
770
+ amountToApprove
771
+ );
772
+ const initCode = isSafeDeployed ? "0x" : await protocolKit.getInitCode();
773
+ if (isEntryPointV6(entryPoint)) {
774
+ return {
775
+ sender: safeAddress,
776
+ nonce: nonce.toString(),
777
+ initCode,
778
+ callData,
779
+ callGasLimit: 1n,
780
+ verificationGasLimit: 1n,
781
+ preVerificationGas: 1n,
782
+ maxFeePerGas: 1n,
783
+ maxPriorityFeePerGas: 1n,
784
+ paymasterAndData,
785
+ signature: "0x"
786
+ };
787
+ }
788
+ return {
789
+ sender: safeAddress,
790
+ nonce: nonce.toString(),
791
+ ...unpackInitCode(initCode),
792
+ callData,
793
+ callGasLimit: 1n,
794
+ verificationGasLimit: 1n,
795
+ preVerificationGas: 1n,
796
+ maxFeePerGas: 1n,
797
+ maxPriorityFeePerGas: 1n,
798
+ paymaster: paymasterAndData,
799
+ paymasterData: "0x",
800
+ paymasterVerificationGasLimit: void 0,
801
+ paymasterPostOpGasLimit: void 0,
802
+ signature: "0x"
803
+ };
804
+ }
805
+ function userOperationToHexValues(userOperation, entryPointAddress) {
806
+ const userOpV07 = userOperation;
807
+ const userOperationWithHexValues = {
808
+ ...userOperation,
809
+ nonce: (0, import_viem5.toHex)(BigInt(userOperation.nonce)),
810
+ callGasLimit: (0, import_viem5.toHex)(userOperation.callGasLimit),
811
+ verificationGasLimit: (0, import_viem5.toHex)(userOperation.verificationGasLimit),
812
+ preVerificationGas: (0, import_viem5.toHex)(userOperation.preVerificationGas),
813
+ maxFeePerGas: (0, import_viem5.toHex)(userOperation.maxFeePerGas),
814
+ maxPriorityFeePerGas: (0, import_viem5.toHex)(userOperation.maxPriorityFeePerGas),
815
+ ...isEntryPointV7(entryPointAddress) ? {
816
+ paymaster: userOpV07.paymaster !== "0x" ? userOpV07.paymaster : null,
817
+ paymasterData: userOpV07.paymasterData !== "0x" ? userOpV07.paymasterData : null,
818
+ paymasterVerificationGasLimit: userOpV07.paymasterVerificationGasLimit ? (0, import_viem5.toHex)(userOpV07.paymasterVerificationGasLimit) : null,
819
+ paymasterPostOpGasLimit: userOpV07.paymasterPostOpGasLimit ? (0, import_viem5.toHex)(userOpV07.paymasterPostOpGasLimit) : null
820
+ } : {}
821
+ };
822
+ return userOperationWithHexValues;
823
+ }
824
+
825
+ // src/packs/safe-4337/utils/getRelayKitVersion.ts
826
+ var getRelayKitVersion = () => "4.0.0";
827
+
828
+ // src/packs/safe-4337/utils/encodeNonce.ts
829
+ var import_viem6 = require("viem");
830
+ function encodeNonce(args) {
831
+ const key = BigInt((0, import_viem6.toHex)(args.key, { size: 24 }));
832
+ const sequence = BigInt((0, import_viem6.toHex)(args.sequence, { size: 8 }));
833
+ return (key << BigInt(64)) + sequence;
834
+ }
835
+
836
+ // src/packs/safe-4337/utils/index.ts
837
+ function createBundlerClient(bundlerUrl) {
838
+ const provider = (0, import_viem7.createPublicClient)({
839
+ transport: (0, import_viem7.http)(bundlerUrl),
840
+ rpcSchema: (0, import_viem7.rpcSchema)()
841
+ });
842
+ return provider;
843
+ }
844
+ function encodeMultiSendCallData(transactions) {
845
+ return (0, import_viem7.encodeFunctionData)({
846
+ abi: ABI,
847
+ functionName: "multiSend",
848
+ args: [
849
+ (0, import_protocol_kit4.encodeMultiSendData)(
850
+ transactions.map((tx) => ({ ...tx, operation: tx.operation ?? import_types_kit2.OperationType.Call }))
851
+ )
852
+ ]
853
+ });
854
+ }
855
+
856
+ // src/packs/safe-4337/SafeOperationFactory.ts
857
+ var SafeOperationFactory = class {
858
+ /**
859
+ * Creates a new SafeOperation with proper validation
860
+ * @param userOperation - The base user operation
861
+ * @param options - Configuration options
862
+ * @returns Validated SafeOperation instance
863
+ */
864
+ static createSafeOperation(userOperation, options) {
865
+ if (isEntryPointV6(options.entryPoint)) {
866
+ return new SafeOperationV06_default(userOperation, options);
867
+ }
868
+ return new SafeOperationV07_default(userOperation, options);
869
+ }
870
+ };
871
+ var SafeOperationFactory_default = SafeOperationFactory;
872
+
873
+ // src/packs/safe-4337/estimators/pimlico/PimlicoFeeEstimator.ts
874
+ var PimlicoFeeEstimator = class {
875
+ async preEstimateUserOperationGas({
876
+ bundlerUrl,
877
+ userOperation,
878
+ entryPoint,
879
+ paymasterOptions
880
+ }) {
881
+ const bundlerClient = createBundlerClient(bundlerUrl);
882
+ const feeData = await this.#getUserOperationGasPrices(bundlerClient);
883
+ const chainId = await this.#getChainId(bundlerClient);
884
+ let paymasterStubData = {};
885
+ if (paymasterOptions) {
886
+ const paymasterClient = createBundlerClient(
887
+ paymasterOptions.paymasterUrl
888
+ );
889
+ const context = "paymasterTokenAddress" in paymasterOptions ? {
890
+ token: paymasterOptions.paymasterTokenAddress
891
+ } : void 0;
892
+ paymasterStubData = await paymasterClient.request({
893
+ method: "pm_getPaymasterStubData" /* GET_PAYMASTER_STUB_DATA */,
894
+ params: [userOperationToHexValues(userOperation, entryPoint), entryPoint, chainId, context]
895
+ });
896
+ }
897
+ return {
898
+ ...feeData,
899
+ ...paymasterStubData
900
+ };
901
+ }
902
+ async postEstimateUserOperationGas({
903
+ userOperation,
904
+ entryPoint,
905
+ paymasterOptions
906
+ }) {
907
+ if (!paymasterOptions) return {};
908
+ const paymasterClient = createBundlerClient(
909
+ paymasterOptions.paymasterUrl
910
+ );
911
+ if (paymasterOptions.isSponsored) {
912
+ const params = [
913
+ userOperationToHexValues(userOperation, entryPoint),
914
+ entryPoint
915
+ ];
916
+ if (paymasterOptions.sponsorshipPolicyId) {
917
+ params.push({
918
+ sponsorshipPolicyId: paymasterOptions.sponsorshipPolicyId
919
+ });
920
+ }
921
+ const sponsoredData = await paymasterClient.request({
922
+ method: "pm_sponsorUserOperation" /* SPONSOR_USER_OPERATION */,
923
+ params
924
+ });
925
+ return sponsoredData;
926
+ }
927
+ const chainId = await this.#getChainId(paymasterClient);
928
+ const erc20PaymasterData = await paymasterClient.request({
929
+ method: "pm_getPaymasterData" /* GET_PAYMASTER_DATA */,
930
+ params: [
931
+ userOperationToHexValues(userOperation, entryPoint),
932
+ entryPoint,
933
+ chainId,
934
+ { token: paymasterOptions.paymasterTokenAddress }
935
+ ]
936
+ });
937
+ return erc20PaymasterData;
938
+ }
939
+ async #getUserOperationGasPrices(client) {
940
+ const feeData = await client.request({
941
+ method: "pimlico_getUserOperationGasPrice" /* GET_USER_OPERATION_GAS_PRICE */
942
+ });
943
+ const {
944
+ fast: { maxFeePerGas, maxPriorityFeePerGas }
945
+ } = feeData;
946
+ return {
947
+ maxFeePerGas,
948
+ maxPriorityFeePerGas
949
+ };
950
+ }
951
+ async #getChainId(client) {
952
+ const chainId = await client.request({ method: "eth_chainId" });
953
+ return chainId;
954
+ }
955
+ };
956
+
957
+ // src/packs/safe-4337/Safe4337Pack.ts
958
+ var MAX_ERC20_AMOUNT_TO_APPROVE = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn;
959
+ var EQ_OR_GT_1_4_1 = ">=1.4.1";
960
+ var Safe4337Pack = class _Safe4337Pack extends RelayKitBasePack {
961
+ #BUNDLER_URL;
962
+ #ENTRYPOINT_ADDRESS;
963
+ #SAFE_4337_MODULE_ADDRESS = "0x";
964
+ #SAFE_WEBAUTHN_SHARED_SIGNER_ADDRESS = "0x";
965
+ #bundlerClient;
966
+ #chainId;
967
+ #paymasterOptions;
968
+ #onchainIdentifier = "";
969
+ /**
970
+ * Creates an instance of the Safe4337Pack.
971
+ *
972
+ * @param {Safe4337Options} options - The initialization parameters.
973
+ */
974
+ constructor({
975
+ protocolKit,
976
+ bundlerClient,
977
+ bundlerUrl,
978
+ chainId,
979
+ paymasterOptions,
980
+ entryPointAddress,
981
+ safe4337ModuleAddress,
982
+ safeWebAuthnSharedSignerAddress,
983
+ onchainAnalytics
984
+ }) {
985
+ super(protocolKit);
986
+ this.#BUNDLER_URL = bundlerUrl;
987
+ this.#bundlerClient = bundlerClient;
988
+ this.#chainId = chainId;
989
+ this.#paymasterOptions = paymasterOptions;
990
+ this.#ENTRYPOINT_ADDRESS = entryPointAddress;
991
+ this.#SAFE_4337_MODULE_ADDRESS = safe4337ModuleAddress;
992
+ this.#SAFE_WEBAUTHN_SHARED_SIGNER_ADDRESS = safeWebAuthnSharedSignerAddress || "0x";
993
+ if (onchainAnalytics?.project) {
994
+ const { project, platform } = onchainAnalytics;
995
+ this.#onchainIdentifier = (0, import_protocol_kit5.generateOnChainIdentifier)({
996
+ project,
997
+ platform,
998
+ tool: "relay-kit",
999
+ toolVersion: getRelayKitVersion()
1000
+ });
1001
+ }
1002
+ }
1003
+ /**
1004
+ * Initializes a Safe4337Pack class.
1005
+ * This method creates the protocolKit instance based on the input parameters.
1006
+ * When the Safe address is provided, it will use the existing Safe.
1007
+ * When the Safe address is not provided, it will use the predictedSafe feature with the provided owners and threshold.
1008
+ * It will use the correct contract addresses for the fallbackHandler and the module and will add the data to enable the 4337 module.
1009
+ *
1010
+ * @param {Safe4337InitOptions} initOptions - The initialization parameters.
1011
+ * @return {Promise<Safe4337Pack>} The Promise object that will be resolved into an instance of Safe4337Pack.
1012
+ */
1013
+ static async init(initOptions) {
1014
+ const {
1015
+ provider,
1016
+ signer,
1017
+ options,
1018
+ bundlerUrl,
1019
+ customContracts,
1020
+ paymasterOptions,
1021
+ onchainAnalytics
1022
+ } = initOptions;
1023
+ let protocolKit;
1024
+ const bundlerClient = createBundlerClient(bundlerUrl);
1025
+ const chainId = await bundlerClient.request({ method: "eth_chainId" /* CHAIN_ID */ });
1026
+ let safeModulesSetupAddress = customContracts?.safeModulesSetupAddress;
1027
+ const network = parseInt(chainId, 16).toString();
1028
+ const safeModulesVersion = initOptions.safeModulesVersion || DEFAULT_SAFE_MODULES_VERSION;
1029
+ if (!safeModulesSetupAddress) {
1030
+ const safeModuleSetupDeployment = (0, import_safe_modules_deployments.getSafeModuleSetupDeployment)({
1031
+ released: true,
1032
+ version: safeModulesVersion,
1033
+ network
1034
+ });
1035
+ safeModulesSetupAddress = safeModuleSetupDeployment?.networkAddresses[network];
1036
+ }
1037
+ let safe4337ModuleAddress = customContracts?.safe4337ModuleAddress;
1038
+ if (!safe4337ModuleAddress) {
1039
+ const safe4337ModuleDeployment = (0, import_safe_modules_deployments.getSafe4337ModuleDeployment)({
1040
+ released: true,
1041
+ version: safeModulesVersion,
1042
+ network
1043
+ });
1044
+ safe4337ModuleAddress = safe4337ModuleDeployment?.networkAddresses[network];
1045
+ }
1046
+ if (!safeModulesSetupAddress || !safe4337ModuleAddress) {
1047
+ throw new Error(
1048
+ `Safe4337Module and/or SafeModuleSetup not available for chain ${network} and modules version ${safeModulesVersion}`
1049
+ );
1050
+ }
1051
+ let safeWebAuthnSharedSignerAddress = customContracts?.safeWebAuthnSharedSignerAddress;
1052
+ if ("safeAddress" in options) {
1053
+ protocolKit = await import_protocol_kit5.default.init({
1054
+ provider,
1055
+ signer,
1056
+ safeAddress: options.safeAddress
1057
+ });
1058
+ const safeVersion = protocolKit.getContractVersion();
1059
+ const isSafeVersion4337Compatible = (0, import_satisfies.default)(safeVersion, EQ_OR_GT_1_4_1);
1060
+ if (!isSafeVersion4337Compatible) {
1061
+ throw new Error(
1062
+ `Incompatibility detected: The current Safe Account version (${safeVersion}) is not supported. EIP-4337 requires the Safe to use at least v1.4.1.`
1063
+ );
1064
+ }
1065
+ const safeModules = await protocolKit.getModules();
1066
+ const is4337ModulePresent = safeModules.some((module2) => module2 === safe4337ModuleAddress);
1067
+ if (!is4337ModulePresent) {
1068
+ throw new Error(
1069
+ `Incompatibility detected: The EIP-4337 module is not enabled in the provided Safe Account. Enable this module (address: ${safe4337ModuleAddress}) to add compatibility.`
1070
+ );
1071
+ }
1072
+ const safeFallbackhandler = await protocolKit.getFallbackHandler();
1073
+ const is4337FallbackhandlerPresent = safeFallbackhandler === safe4337ModuleAddress;
1074
+ if (!is4337FallbackhandlerPresent) {
1075
+ throw new Error(
1076
+ `Incompatibility detected: The EIP-4337 fallbackhandler is not attached to the Safe Account. Attach this fallbackhandler (address: ${safe4337ModuleAddress}) to ensure compatibility.`
1077
+ );
1078
+ }
1079
+ } else {
1080
+ if (!options.owners || !options.threshold) {
1081
+ throw new Error("Owners and threshold are required to deploy a new Safe");
1082
+ }
1083
+ const safeVersion = options.safeVersion || DEFAULT_SAFE_VERSION;
1084
+ const enable4337ModuleTransaction = {
1085
+ to: safeModulesSetupAddress,
1086
+ value: "0",
1087
+ data: (0, import_viem9.encodeFunctionData)({
1088
+ abi: ABI,
1089
+ functionName: "enableModules",
1090
+ args: [[safe4337ModuleAddress]]
1091
+ }),
1092
+ operation: import_types_kit3.OperationType.DelegateCall
1093
+ // DelegateCall required for enabling the 4337 module
1094
+ };
1095
+ const setupTransactions = [enable4337ModuleTransaction];
1096
+ const isApproveTransactionRequired = !!paymasterOptions && !paymasterOptions.isSponsored && !!paymasterOptions.paymasterTokenAddress;
1097
+ if (isApproveTransactionRequired) {
1098
+ const { paymasterAddress, amountToApprove = MAX_ERC20_AMOUNT_TO_APPROVE } = paymasterOptions;
1099
+ const approveToPaymasterTransaction = {
1100
+ to: paymasterOptions.paymasterTokenAddress,
1101
+ data: (0, import_viem9.encodeFunctionData)({
1102
+ abi: ABI,
1103
+ functionName: "approve",
1104
+ args: [paymasterAddress, amountToApprove]
1105
+ }),
1106
+ value: "0",
1107
+ operation: import_types_kit3.OperationType.Call
1108
+ // Call for approve
1109
+ };
1110
+ setupTransactions.push(approveToPaymasterTransaction);
1111
+ }
1112
+ const safeProvider = await import_protocol_kit5.SafeProvider.init({ provider, signer, safeVersion });
1113
+ const isPasskeySigner = await safeProvider.isPasskeySigner();
1114
+ if (isPasskeySigner) {
1115
+ if (!safeWebAuthnSharedSignerAddress) {
1116
+ const safeWebAuthnSharedSignerDeployment = (0, import_safe_modules_deployments.getSafeWebAuthnShareSignerDeployment)({
1117
+ released: true,
1118
+ version: "0.2.1",
1119
+ network
1120
+ });
1121
+ safeWebAuthnSharedSignerAddress = safeWebAuthnSharedSignerDeployment?.networkAddresses[network];
1122
+ }
1123
+ if (!safeWebAuthnSharedSignerAddress) {
1124
+ throw new Error(`safeWebAuthnSharedSignerAddress not available for chain ${network}`);
1125
+ }
1126
+ const passkeySigner = await safeProvider.getExternalSigner();
1127
+ const checkSummedOwners = options.owners.map((owner) => (0, import_viem8.getAddress)(owner));
1128
+ const checkSummedSignerAddress = (0, import_viem8.getAddress)(safeWebAuthnSharedSignerAddress);
1129
+ if (!checkSummedOwners.includes(checkSummedSignerAddress)) {
1130
+ options.owners.push(checkSummedSignerAddress);
1131
+ }
1132
+ const sharedSignerTransaction = {
1133
+ to: safeWebAuthnSharedSignerAddress,
1134
+ value: "0",
1135
+ data: passkeySigner.encodeConfigure(),
1136
+ operation: import_types_kit3.OperationType.DelegateCall
1137
+ // DelegateCall required into the SafeWebAuthnSharedSigner instance in order for it to set its configuration.
1138
+ };
1139
+ setupTransactions.push(sharedSignerTransaction);
1140
+ }
1141
+ let deploymentTo;
1142
+ let deploymentData;
1143
+ const isBatch = setupTransactions.length > 1;
1144
+ if (isBatch) {
1145
+ const multiSendContract = await (0, import_protocol_kit5.getMultiSendContract)({
1146
+ safeProvider,
1147
+ safeVersion,
1148
+ deploymentType: options.deploymentType || void 0
1149
+ });
1150
+ const batchData = (0, import_viem9.encodeFunctionData)({
1151
+ abi: ABI,
1152
+ functionName: "multiSend",
1153
+ args: [(0, import_protocol_kit5.encodeMultiSendData)(setupTransactions)]
1154
+ });
1155
+ deploymentTo = multiSendContract.getAddress();
1156
+ deploymentData = batchData;
1157
+ } else {
1158
+ deploymentTo = enable4337ModuleTransaction.to;
1159
+ deploymentData = enable4337ModuleTransaction.data;
1160
+ }
1161
+ protocolKit = await import_protocol_kit5.default.init({
1162
+ provider,
1163
+ signer,
1164
+ predictedSafe: {
1165
+ safeDeploymentConfig: {
1166
+ safeVersion,
1167
+ saltNonce: options.saltNonce || void 0,
1168
+ deploymentType: options.deploymentType || void 0
1169
+ },
1170
+ safeAccountConfig: {
1171
+ owners: options.owners,
1172
+ threshold: options.threshold,
1173
+ to: deploymentTo,
1174
+ data: deploymentData,
1175
+ fallbackHandler: safe4337ModuleAddress,
1176
+ paymentToken: import_viem9.zeroAddress,
1177
+ payment: 0,
1178
+ paymentReceiver: import_viem9.zeroAddress
1179
+ }
1180
+ },
1181
+ onchainAnalytics
1182
+ });
1183
+ }
1184
+ let selectedEntryPoint;
1185
+ if (customContracts?.entryPointAddress) {
1186
+ const requiredSafeModulesVersion = entryPointToSafeModules(customContracts?.entryPointAddress);
1187
+ if (!(0, import_satisfies.default)(safeModulesVersion, requiredSafeModulesVersion))
1188
+ throw new Error(
1189
+ `The selected entrypoint ${customContracts?.entryPointAddress} is not compatible with version ${safeModulesVersion} of Safe modules`
1190
+ );
1191
+ selectedEntryPoint = customContracts?.entryPointAddress;
1192
+ } else {
1193
+ const supportedEntryPoints = await bundlerClient.request({
1194
+ method: "eth_supportedEntryPoints" /* SUPPORTED_ENTRY_POINTS */
1195
+ });
1196
+ if (!supportedEntryPoints.length) {
1197
+ throw new Error("No entrypoint provided or available through the bundler");
1198
+ }
1199
+ selectedEntryPoint = supportedEntryPoints.find((entryPoint) => {
1200
+ const requiredSafeModulesVersion = entryPointToSafeModules(entryPoint);
1201
+ return (0, import_satisfies.default)(safeModulesVersion, requiredSafeModulesVersion);
1202
+ });
1203
+ if (!selectedEntryPoint) {
1204
+ throw new Error(
1205
+ `Incompatibility detected: None of the entrypoints provided by the bundler is compatible with the Safe modules version ${safeModulesVersion}`
1206
+ );
1207
+ }
1208
+ }
1209
+ return new _Safe4337Pack({
1210
+ chainId: BigInt(chainId),
1211
+ protocolKit,
1212
+ bundlerClient,
1213
+ paymasterOptions,
1214
+ bundlerUrl,
1215
+ entryPointAddress: selectedEntryPoint,
1216
+ safe4337ModuleAddress,
1217
+ safeWebAuthnSharedSignerAddress,
1218
+ onchainAnalytics
1219
+ });
1220
+ }
1221
+ /**
1222
+ * Estimates gas for the SafeOperation.
1223
+ *
1224
+ * @param {EstimateFeeProps} props - The parameters for the gas estimation.
1225
+ * @param {BaseSafeOperation} props.safeOperation - The SafeOperation to estimate the gas.
1226
+ * @param {IFeeEstimator} props.feeEstimator - The function to estimate the gas.
1227
+ * @return {Promise<BaseSafeOperation>} The Promise object that will be resolved into the gas estimation.
1228
+ */
1229
+ async getEstimateFee({
1230
+ safeOperation,
1231
+ feeEstimator = new PimlicoFeeEstimator()
1232
+ }) {
1233
+ const threshold = await this.protocolKit.getThreshold();
1234
+ const preEstimationData = await feeEstimator?.preEstimateUserOperationGas?.({
1235
+ bundlerUrl: this.#BUNDLER_URL,
1236
+ entryPoint: this.#ENTRYPOINT_ADDRESS,
1237
+ userOperation: safeOperation.getUserOperation(),
1238
+ paymasterOptions: this.#paymasterOptions
1239
+ });
1240
+ if (preEstimationData) {
1241
+ safeOperation.addEstimations(preEstimationData);
1242
+ }
1243
+ const estimateUserOperationGas = await this.#bundlerClient.request({
1244
+ method: "eth_estimateUserOperationGas" /* ESTIMATE_USER_OPERATION_GAS */,
1245
+ params: [
1246
+ {
1247
+ ...userOperationToHexValues(safeOperation.getUserOperation(), this.#ENTRYPOINT_ADDRESS),
1248
+ signature: getDummySignature(this.#SAFE_WEBAUTHN_SHARED_SIGNER_ADDRESS, threshold)
1249
+ },
1250
+ this.#ENTRYPOINT_ADDRESS
1251
+ ]
1252
+ });
1253
+ if (estimateUserOperationGas) {
1254
+ safeOperation.addEstimations(estimateUserOperationGas);
1255
+ }
1256
+ const postEstimationData = await feeEstimator?.postEstimateUserOperationGas?.({
1257
+ bundlerUrl: this.#BUNDLER_URL,
1258
+ entryPoint: this.#ENTRYPOINT_ADDRESS,
1259
+ userOperation: {
1260
+ ...safeOperation.getUserOperation(),
1261
+ signature: getDummySignature(this.#SAFE_WEBAUTHN_SHARED_SIGNER_ADDRESS, threshold)
1262
+ },
1263
+ paymasterOptions: this.#paymasterOptions
1264
+ });
1265
+ if (postEstimationData) {
1266
+ safeOperation.addEstimations(postEstimationData);
1267
+ }
1268
+ return safeOperation;
1269
+ }
1270
+ /**
1271
+ * Creates a relayed transaction based on the provided parameters.
1272
+ *
1273
+ * @param {MetaTransactionData[]} transactions - The transactions to batch in a SafeOperation.
1274
+ * @param options - Optional configuration options for the transaction creation.
1275
+ * @return {Promise<BaseSafeOperation>} The Promise object will resolve a SafeOperation.
1276
+ */
1277
+ async createTransaction({
1278
+ transactions,
1279
+ options = {}
1280
+ }) {
1281
+ const { amountToApprove, validUntil, validAfter, feeEstimator, customNonce } = options;
1282
+ const userOperation = await createUserOperation(this.protocolKit, transactions, {
1283
+ entryPoint: this.#ENTRYPOINT_ADDRESS,
1284
+ paymasterOptions: this.#paymasterOptions,
1285
+ amountToApprove,
1286
+ customNonce
1287
+ });
1288
+ if (this.#onchainIdentifier) {
1289
+ userOperation.callData += this.#onchainIdentifier;
1290
+ }
1291
+ const safeOperation = SafeOperationFactory_default.createSafeOperation(userOperation, {
1292
+ chainId: this.#chainId,
1293
+ moduleAddress: this.#SAFE_4337_MODULE_ADDRESS,
1294
+ entryPoint: this.#ENTRYPOINT_ADDRESS,
1295
+ validUntil,
1296
+ validAfter
1297
+ });
1298
+ return await this.getEstimateFee({
1299
+ safeOperation,
1300
+ feeEstimator
1301
+ });
1302
+ }
1303
+ /**
1304
+ * Converts a SafeOperationResponse to an SafeOperation.
1305
+ *
1306
+ * @param {SafeOperationResponse} safeOperationResponse - The SafeOperationResponse to convert to SafeOperation
1307
+ * @returns {BaseSafeOperation} - The SafeOperation object
1308
+ */
1309
+ #toSafeOperation(safeOperationResponse) {
1310
+ const { validUntil, validAfter, userOperation } = safeOperationResponse;
1311
+ const paymaster = userOperation?.paymaster || "0x";
1312
+ const paymasterData = userOperation?.paymasterData || "0x";
1313
+ const safeOperation = SafeOperationFactory_default.createSafeOperation(
1314
+ {
1315
+ sender: userOperation?.sender || "0x",
1316
+ nonce: userOperation?.nonce || "0",
1317
+ initCode: userOperation?.initCode || "",
1318
+ callData: userOperation?.callData || "",
1319
+ callGasLimit: BigInt(userOperation?.callGasLimit || 0n),
1320
+ verificationGasLimit: BigInt(userOperation?.verificationGasLimit || 0),
1321
+ preVerificationGas: BigInt(userOperation?.preVerificationGas || 0),
1322
+ maxFeePerGas: BigInt(userOperation?.maxFeePerGas || 0),
1323
+ maxPriorityFeePerGas: BigInt(userOperation?.maxPriorityFeePerGas || 0),
1324
+ paymasterAndData: (0, import_viem9.concat)([paymaster, paymasterData]),
1325
+ signature: safeOperationResponse.preparedSignature || "0x"
1326
+ },
1327
+ {
1328
+ chainId: this.#chainId,
1329
+ moduleAddress: this.#SAFE_4337_MODULE_ADDRESS,
1330
+ entryPoint: userOperation?.entryPoint || this.#ENTRYPOINT_ADDRESS,
1331
+ validAfter: this.#timestamp(validAfter),
1332
+ validUntil: this.#timestamp(validUntil)
1333
+ }
1334
+ );
1335
+ if (safeOperationResponse.confirmations) {
1336
+ safeOperationResponse.confirmations.forEach((confirmation) => {
1337
+ safeOperation.addSignature(new import_protocol_kit5.EthSafeSignature(confirmation.owner, confirmation.signature));
1338
+ });
1339
+ }
1340
+ return safeOperation;
1341
+ }
1342
+ /**
1343
+ *
1344
+ * @param date An ISO string date
1345
+ * @returns The timestamp in seconds to send to the bundler
1346
+ */
1347
+ #timestamp(date) {
1348
+ return date ? new Date(date).getTime() / 1e3 : void 0;
1349
+ }
1350
+ /**
1351
+ * Signs a safe operation.
1352
+ *
1353
+ * @param {BaseSafeOperation | SafeOperationResponse} safeOperation - The SafeOperation to sign. It can be:
1354
+ * - A response from the API (Tx Service)
1355
+ * - An instance of SafeOperation
1356
+ * @param {SigningMethod} signingMethod - The signing method to use.
1357
+ * @return {Promise<BaseSafeOperation>} The Promise object will resolve to the signed SafeOperation.
1358
+ */
1359
+ async signSafeOperation(safeOperation, signingMethod = import_types_kit3.SigningMethod.ETH_SIGN_TYPED_DATA_V4) {
1360
+ let safeOp;
1361
+ if (safeOperation instanceof BaseSafeOperation_default) {
1362
+ safeOp = safeOperation;
1363
+ } else {
1364
+ safeOp = this.#toSafeOperation(safeOperation);
1365
+ }
1366
+ const safeProvider = this.protocolKit.getSafeProvider();
1367
+ const signerAddress = await safeProvider.getSignerAddress();
1368
+ const isPasskeySigner = await safeProvider.isPasskeySigner();
1369
+ if (!signerAddress) {
1370
+ throw new Error("There is no signer address available to sign the SafeOperation");
1371
+ }
1372
+ const isOwner = await this.protocolKit.isOwner(signerAddress);
1373
+ const isSafeDeployed = await this.protocolKit.isSafeDeployed();
1374
+ if (!isOwner && isSafeDeployed || !isSafeDeployed && !isPasskeySigner && !isOwner) {
1375
+ throw new Error("UserOperations can only be signed by Safe owners");
1376
+ }
1377
+ let safeSignature;
1378
+ if (isPasskeySigner) {
1379
+ const safeOpHash = safeOp.getHash();
1380
+ if (!isSafeDeployed) {
1381
+ const passkeySignature = await this.protocolKit.signHash(safeOpHash);
1382
+ safeSignature = new import_protocol_kit5.EthSafeSignature(
1383
+ this.#SAFE_WEBAUTHN_SHARED_SIGNER_ADDRESS,
1384
+ passkeySignature.data,
1385
+ true
1386
+ );
1387
+ } else {
1388
+ safeSignature = await this.protocolKit.signHash(safeOpHash);
1389
+ }
1390
+ } else {
1391
+ if ([
1392
+ import_types_kit3.SigningMethod.ETH_SIGN_TYPED_DATA_V4,
1393
+ import_types_kit3.SigningMethod.ETH_SIGN_TYPED_DATA_V3,
1394
+ import_types_kit3.SigningMethod.ETH_SIGN_TYPED_DATA
1395
+ ].includes(signingMethod)) {
1396
+ const signer = await safeProvider.getExternalSigner();
1397
+ if (!signer) {
1398
+ throw new Error("No signer found");
1399
+ }
1400
+ const signerAddress2 = signer.account.address;
1401
+ const safeOperation2 = safeOp.getSafeOperation();
1402
+ const signature = await signer.signTypedData({
1403
+ domain: {
1404
+ chainId: Number(this.#chainId),
1405
+ verifyingContract: this.#SAFE_4337_MODULE_ADDRESS
1406
+ },
1407
+ types: safeOp.getEIP712Type(),
1408
+ message: {
1409
+ ...safeOperation2,
1410
+ nonce: BigInt(safeOperation2.nonce),
1411
+ validAfter: (0, import_viem8.toHex)(safeOperation2.validAfter),
1412
+ validUntil: (0, import_viem8.toHex)(safeOperation2.validUntil),
1413
+ maxFeePerGas: (0, import_viem8.toHex)(safeOperation2.maxFeePerGas),
1414
+ maxPriorityFeePerGas: (0, import_viem8.toHex)(safeOperation2.maxPriorityFeePerGas)
1415
+ },
1416
+ primaryType: "SafeOp"
1417
+ });
1418
+ safeSignature = new import_protocol_kit5.EthSafeSignature(signerAddress2, signature);
1419
+ } else {
1420
+ const safeOpHash = safeOp.getHash();
1421
+ safeSignature = await this.protocolKit.signHash(safeOpHash);
1422
+ }
1423
+ }
1424
+ safeOp.addSignature(safeSignature);
1425
+ return safeOp;
1426
+ }
1427
+ /**
1428
+ * Executes the relay transaction.
1429
+ *
1430
+ * @param {Safe4337ExecutableProps} props - The parameters for the transaction execution.
1431
+ * @param {BaseSafeOperation | SafeOperationResponse} props.executable - The SafeOperation to execute. It can be:
1432
+ * - A response from the API (Tx Service)
1433
+ * - An instance of SafeOperation
1434
+ * @return {Promise<string>} The user operation hash.
1435
+ */
1436
+ async executeTransaction({ executable }) {
1437
+ let safeOperation;
1438
+ if (executable instanceof BaseSafeOperation_default) {
1439
+ safeOperation = executable;
1440
+ } else {
1441
+ safeOperation = this.#toSafeOperation(executable);
1442
+ }
1443
+ return this.#bundlerClient.request({
1444
+ method: "eth_sendUserOperation" /* SEND_USER_OPERATION */,
1445
+ params: [
1446
+ userOperationToHexValues(safeOperation.getUserOperation(), this.#ENTRYPOINT_ADDRESS),
1447
+ this.#ENTRYPOINT_ADDRESS
1448
+ ]
1449
+ });
1450
+ }
1451
+ /**
1452
+ * Return a UserOperation based on a hash (userOpHash) returned by eth_sendUserOperation
1453
+ *
1454
+ * @param {string} userOpHash - The hash of the user operation to fetch. Returned from the #sendUserOperation method
1455
+ * @returns {UserOperation} - null in case the UserOperation is not yet included in a block, or a full UserOperation, with the addition of entryPoint, blockNumber, blockHash and transactionHash
1456
+ */
1457
+ async getUserOperationByHash(userOpHash) {
1458
+ return this.#bundlerClient.request({
1459
+ method: "eth_getUserOperationByHash" /* GET_USER_OPERATION_BY_HASH */,
1460
+ params: [userOpHash]
1461
+ });
1462
+ }
1463
+ /**
1464
+ * Return a UserOperation receipt based on a hash (userOpHash) returned by eth_sendUserOperation
1465
+ *
1466
+ * @param {string} userOpHash - The hash of the user operation to fetch. Returned from the #sendUserOperation method
1467
+ * @returns {UserOperationReceipt} - null in case the UserOperation is not yet included in a block, or UserOperationReceipt object
1468
+ */
1469
+ async getUserOperationReceipt(userOpHash) {
1470
+ return this.#bundlerClient.request({
1471
+ method: "eth_getUserOperationReceipt" /* GET_USER_OPERATION_RECEIPT */,
1472
+ params: [userOpHash]
1473
+ });
1474
+ }
1475
+ /**
1476
+ * Returns an array of the entryPoint addresses supported by the client.
1477
+ * The first element of the array SHOULD be the entryPoint addressed preferred by the client.
1478
+ *
1479
+ * @returns {string[]} - The supported entry points.
1480
+ */
1481
+ async getSupportedEntryPoints() {
1482
+ return this.#bundlerClient.request({
1483
+ method: "eth_supportedEntryPoints" /* SUPPORTED_ENTRY_POINTS */
1484
+ });
1485
+ }
1486
+ /**
1487
+ * Returns EIP-155 Chain ID.
1488
+ *
1489
+ * @returns {string} - The chain id.
1490
+ */
1491
+ async getChainId() {
1492
+ return this.#bundlerClient.request({ method: "eth_chainId" /* CHAIN_ID */ });
1493
+ }
1494
+ getOnchainIdentifier() {
1495
+ return this.#onchainIdentifier;
1496
+ }
1497
+ };