@injectivelabs/wallet-core 1.16.24 → 1.16.25-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 (41) hide show
  1. package/dist/cjs/index.cjs +1007 -0
  2. package/dist/cjs/index.d.cts +281 -0
  3. package/dist/cjs/package.json +2 -2
  4. package/dist/esm/index.d.ts +281 -3
  5. package/dist/esm/index.js +1003 -3
  6. package/dist/esm/package.json +2 -2
  7. package/package.json +19 -19
  8. package/dist/cjs/broadcaster/MsgBroadcaster.d.ts +0 -137
  9. package/dist/cjs/broadcaster/MsgBroadcaster.js +0 -918
  10. package/dist/cjs/broadcaster/Web3Broadcaster.d.ts +0 -30
  11. package/dist/cjs/broadcaster/Web3Broadcaster.js +0 -32
  12. package/dist/cjs/broadcaster/index.d.ts +0 -3
  13. package/dist/cjs/broadcaster/index.js +0 -19
  14. package/dist/cjs/broadcaster/types.d.ts +0 -56
  15. package/dist/cjs/broadcaster/types.js +0 -13
  16. package/dist/cjs/index.d.ts +0 -3
  17. package/dist/cjs/index.js +0 -19
  18. package/dist/cjs/strategy/BaseWalletStrategy.d.ts +0 -58
  19. package/dist/cjs/strategy/BaseWalletStrategy.js +0 -176
  20. package/dist/cjs/strategy/index.d.ts +0 -2
  21. package/dist/cjs/strategy/index.js +0 -8
  22. package/dist/cjs/utils/index.d.ts +0 -1
  23. package/dist/cjs/utils/index.js +0 -17
  24. package/dist/cjs/utils/tx.d.ts +0 -1
  25. package/dist/cjs/utils/tx.js +0 -11
  26. package/dist/esm/broadcaster/MsgBroadcaster.d.ts +0 -137
  27. package/dist/esm/broadcaster/MsgBroadcaster.js +0 -914
  28. package/dist/esm/broadcaster/Web3Broadcaster.d.ts +0 -30
  29. package/dist/esm/broadcaster/Web3Broadcaster.js +0 -28
  30. package/dist/esm/broadcaster/index.d.ts +0 -3
  31. package/dist/esm/broadcaster/index.js +0 -3
  32. package/dist/esm/broadcaster/types.d.ts +0 -56
  33. package/dist/esm/broadcaster/types.js +0 -10
  34. package/dist/esm/strategy/BaseWalletStrategy.d.ts +0 -58
  35. package/dist/esm/strategy/BaseWalletStrategy.js +0 -173
  36. package/dist/esm/strategy/index.d.ts +0 -2
  37. package/dist/esm/strategy/index.js +0 -2
  38. package/dist/esm/utils/index.d.ts +0 -1
  39. package/dist/esm/utils/index.js +0 -1
  40. package/dist/esm/utils/tx.d.ts +0 -1
  41. package/dist/esm/utils/tx.js +0 -7
@@ -0,0 +1,1007 @@
1
+ let __injectivelabs_exceptions = require("@injectivelabs/exceptions");
2
+ let eventemitter3 = require("eventemitter3");
3
+ let __injectivelabs_wallet_base = require("@injectivelabs/wallet-base");
4
+ let __injectivelabs_ts_types = require("@injectivelabs/ts-types");
5
+ let __injectivelabs_networks = require("@injectivelabs/networks");
6
+ let __injectivelabs_utils = require("@injectivelabs/utils");
7
+ let __injectivelabs_sdk_ts = require("@injectivelabs/sdk-ts");
8
+
9
+ //#region src/utils/tx.ts
10
+ const checkIfTxRunOutOfGas = (e) => {
11
+ return e instanceof __injectivelabs_exceptions.TransactionException && e.contextCode === __injectivelabs_exceptions.ChainCosmosErrorCode.ErrOutOfGas && e.contextModule === __injectivelabs_exceptions.TransactionChainErrorModule.CosmosSdk && e.originalMessage.includes("out of gas");
12
+ };
13
+
14
+ //#endregion
15
+ //#region src/broadcaster/types.ts
16
+ const WalletStrategyEmitterEventType = {
17
+ TransactionFail: "transaction-fail",
18
+ TransactionSigned: "transaction-signed",
19
+ TransactionSignStart: "transaction-sign-start",
20
+ TransactionBroadcastEnd: "transaction-broadcast-end",
21
+ WalletStrategyDisconnect: "wallet-strategy-disconnect",
22
+ TransactionBroadcastStart: "transaction-broadcast-start",
23
+ TransactionPreparationEnd: "transaction-preparation-end",
24
+ TransactionPreparationStart: "transaction-preparation-start"
25
+ };
26
+
27
+ //#endregion
28
+ //#region \0@oxc-project+runtime@0.96.0/helpers/typeof.js
29
+ function _typeof(o) {
30
+ "@babel/helpers - typeof";
31
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
32
+ return typeof o$1;
33
+ } : function(o$1) {
34
+ return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
35
+ }, _typeof(o);
36
+ }
37
+
38
+ //#endregion
39
+ //#region \0@oxc-project+runtime@0.96.0/helpers/toPrimitive.js
40
+ function toPrimitive(t, r) {
41
+ if ("object" != _typeof(t) || !t) return t;
42
+ var e = t[Symbol.toPrimitive];
43
+ if (void 0 !== e) {
44
+ var i = e.call(t, r || "default");
45
+ if ("object" != _typeof(i)) return i;
46
+ throw new TypeError("@@toPrimitive must return a primitive value.");
47
+ }
48
+ return ("string" === r ? String : Number)(t);
49
+ }
50
+
51
+ //#endregion
52
+ //#region \0@oxc-project+runtime@0.96.0/helpers/toPropertyKey.js
53
+ function toPropertyKey(t) {
54
+ var i = toPrimitive(t, "string");
55
+ return "symbol" == _typeof(i) ? i : i + "";
56
+ }
57
+
58
+ //#endregion
59
+ //#region \0@oxc-project+runtime@0.96.0/helpers/defineProperty.js
60
+ function _defineProperty(e, r, t) {
61
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
62
+ value: t,
63
+ enumerable: !0,
64
+ configurable: !0,
65
+ writable: !0
66
+ }) : e[r] = t, e;
67
+ }
68
+
69
+ //#endregion
70
+ //#region src/strategy/BaseWalletStrategy.ts
71
+ const getInitialWallet = (args) => {
72
+ if (args.wallet) return args.wallet;
73
+ const keys = Object.keys(args.strategies || {});
74
+ if (keys.length === 0) return __injectivelabs_wallet_base.Wallet.Metamask;
75
+ if (keys.includes(__injectivelabs_wallet_base.Wallet.Metamask) && args.evmOptions) return __injectivelabs_wallet_base.Wallet.Metamask;
76
+ if (keys.includes(__injectivelabs_wallet_base.Wallet.Keplr) && !args.evmOptions) return __injectivelabs_wallet_base.Wallet.Keplr;
77
+ return keys[0];
78
+ };
79
+ var BaseWalletStrategy = class {
80
+ constructor(args) {
81
+ _defineProperty(this, "strategies", void 0);
82
+ _defineProperty(this, "wallet", void 0);
83
+ _defineProperty(this, "args", void 0);
84
+ _defineProperty(this, "metadata", void 0);
85
+ _defineProperty(this, "wallets", void 0);
86
+ _defineProperty(this, "emitter", void 0);
87
+ _defineProperty(this, "on", void 0);
88
+ _defineProperty(this, "off", void 0);
89
+ _defineProperty(this, "emit", void 0);
90
+ this.args = args;
91
+ this.strategies = args.strategies;
92
+ this.wallet = getInitialWallet(args);
93
+ this.metadata = args.metadata;
94
+ this.emitter = new eventemitter3.EventEmitter();
95
+ this.on = this.emitter.on.bind(this.emitter);
96
+ this.off = this.emitter.off.bind(this.emitter);
97
+ this.emit = this.emitter.emit.bind(this.emitter);
98
+ }
99
+ getWallet() {
100
+ return this.wallet;
101
+ }
102
+ setWallet(wallet) {
103
+ this.wallet = wallet;
104
+ this.getStrategy();
105
+ }
106
+ setMetadata(metadata) {
107
+ var _this$getStrategy$set, _this$getStrategy;
108
+ console.log("Setting metadata", metadata);
109
+ this.metadata = metadata;
110
+ (_this$getStrategy$set = (_this$getStrategy = this.getStrategy()).setMetadata) === null || _this$getStrategy$set === void 0 || _this$getStrategy$set.call(_this$getStrategy, metadata);
111
+ }
112
+ getStrategy() {
113
+ if (!this.strategies[this.wallet]) throw new __injectivelabs_exceptions.GeneralException(/* @__PURE__ */ new Error(`Wallet ${this.wallet} is not enabled/available!`));
114
+ return this.strategies[this.wallet];
115
+ }
116
+ getAddresses(args) {
117
+ return this.getStrategy().getAddresses(args);
118
+ }
119
+ getWalletDeviceType() {
120
+ return this.getStrategy().getWalletDeviceType();
121
+ }
122
+ getPubKey(address) {
123
+ return this.getStrategy().getPubKey(address);
124
+ }
125
+ enable(args) {
126
+ return this.getStrategy().enable(args);
127
+ }
128
+ async enableAndGetAddresses(args) {
129
+ await this.getStrategy().enable(args);
130
+ return this.getStrategy().getAddresses(args);
131
+ }
132
+ getEthereumChainId() {
133
+ return this.getStrategy().getEthereumChainId();
134
+ }
135
+ async getEvmTransactionReceipt(txHash, evmChainId) {
136
+ return this.getStrategy().getEvmTransactionReceipt(txHash, evmChainId);
137
+ }
138
+ async getSessionOrConfirm(address) {
139
+ return this.getStrategy().getSessionOrConfirm(address);
140
+ }
141
+ async getWalletClient() {
142
+ var _this$getStrategy2;
143
+ if ((_this$getStrategy2 = this.getStrategy()) === null || _this$getStrategy2 === void 0 ? void 0 : _this$getStrategy2.getWalletClient) {
144
+ var _this$getStrategy3, _this$getStrategy3$ge;
145
+ const result = (_this$getStrategy3 = this.getStrategy()) === null || _this$getStrategy3 === void 0 || (_this$getStrategy3$ge = _this$getStrategy3.getWalletClient) === null || _this$getStrategy3$ge === void 0 ? void 0 : _this$getStrategy3$ge.call(_this$getStrategy3);
146
+ if (result) return result;
147
+ }
148
+ throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Wallet client not found. Please check your wallet strategy."));
149
+ }
150
+ async sendTransaction(tx, options) {
151
+ return this.getStrategy().sendTransaction(tx, options);
152
+ }
153
+ async sendEvmTransaction(tx, options) {
154
+ return this.getStrategy().sendEvmTransaction(tx, options);
155
+ }
156
+ async signEip712TypedData(eip712TypedData, address, options = {}) {
157
+ if ((0, __injectivelabs_wallet_base.isCosmosWallet)(this.wallet)) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`You can't sign Ethereum Transaction using ${this.wallet}`));
158
+ /** Phantom wallet needs enabling before signing */
159
+ if (this.wallet === __injectivelabs_wallet_base.Wallet.Phantom) await this.enable();
160
+ this.emit(WalletStrategyEmitterEventType.TransactionSignStart);
161
+ const response = await this.getStrategy().signEip712TypedData(eip712TypedData, address, options);
162
+ this.emit(WalletStrategyEmitterEventType.TransactionSigned);
163
+ return response;
164
+ }
165
+ async signAminoCosmosTransaction(transaction) {
166
+ if ((0, __injectivelabs_wallet_base.isEvmWallet)(this.wallet)) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`You can't sign Cosmos Transaction using ${this.wallet}`));
167
+ this.emit(WalletStrategyEmitterEventType.TransactionSignStart);
168
+ const response = await this.getStrategy().signAminoCosmosTransaction(transaction);
169
+ this.emit(WalletStrategyEmitterEventType.TransactionSigned);
170
+ return response;
171
+ }
172
+ async signCosmosTransaction(transaction) {
173
+ if ((0, __injectivelabs_wallet_base.isEvmWallet)(this.wallet)) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`You can't sign Cosmos Transaction using ${this.wallet}`));
174
+ this.emit(WalletStrategyEmitterEventType.TransactionSignStart);
175
+ const response = await this.getStrategy().signCosmosTransaction(transaction);
176
+ this.emit(WalletStrategyEmitterEventType.TransactionSigned);
177
+ return response;
178
+ }
179
+ async signArbitrary(signer, data) {
180
+ if (this.getStrategy().signArbitrary) {
181
+ this.emit(WalletStrategyEmitterEventType.TransactionSignStart);
182
+ const response = await this.getStrategy().signArbitrary(signer, data);
183
+ this.emit(WalletStrategyEmitterEventType.TransactionSigned);
184
+ return response;
185
+ }
186
+ }
187
+ async onAccountChange(callback) {
188
+ if (this.getStrategy().onAccountChange) return this.getStrategy().onAccountChange(callback);
189
+ }
190
+ async onChainIdChange(callback) {
191
+ if (this.getStrategy().onChainIdChange) return this.getStrategy().onChainIdChange(callback);
192
+ }
193
+ async disconnect() {
194
+ if (this.getStrategy().disconnect) {
195
+ await this.getStrategy().disconnect();
196
+ this.emit(WalletStrategyEmitterEventType.WalletStrategyDisconnect);
197
+ }
198
+ }
199
+ getCosmosWallet(chainId) {
200
+ const strategy = this.getStrategy();
201
+ if (strategy.getCosmosWallet == void 0) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error(`This method is not available for ${this.getWallet()} wallet`));
202
+ return strategy.getCosmosWallet(chainId);
203
+ }
204
+ async getEip1193Provider() {
205
+ if (this.getStrategy().getEip1193Provider) return this.getStrategy().getEip1193Provider();
206
+ throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("EIP1193 provider not found. Please check your wallet strategy."));
207
+ }
208
+ async getOfflineSigner(chainId) {
209
+ if (this.getStrategy().getOfflineSigner) return this.getStrategy().getOfflineSigner(chainId);
210
+ throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Offline signer not found. Please check your wallet strategy."));
211
+ }
212
+ };
213
+
214
+ //#endregion
215
+ //#region src/broadcaster/MsgBroadcaster.ts
216
+ const getEthereumWalletPubKey = async ({ pubKey, eip712TypedData, signature }) => {
217
+ if (pubKey) return pubKey;
218
+ return (0, __injectivelabs_sdk_ts.hexToBase64)(await (0, __injectivelabs_sdk_ts.recoverTypedSignaturePubKey)(eip712TypedData, signature));
219
+ };
220
+ const defaultRetriesConfig = () => ({ [`${__injectivelabs_exceptions.TransactionChainErrorModule.CosmosSdk}-${__injectivelabs_exceptions.ChainCosmosErrorCode.ErrMempoolIsFull}`]: {
221
+ retries: 0,
222
+ maxRetries: 10,
223
+ timeout: 1e3
224
+ } });
225
+ /**
226
+ * This class is used to broadcast transactions
227
+ * using the WalletStrategy as a handler
228
+ * for the sign/broadcast flow of the transactions
229
+ *
230
+ * Mainly used for building UI products
231
+ */
232
+ var MsgBroadcaster = class {
233
+ constructor(options) {
234
+ _defineProperty(this, "options", void 0);
235
+ _defineProperty(this, "walletStrategy", void 0);
236
+ _defineProperty(this, "endpoints", void 0);
237
+ _defineProperty(this, "chainId", void 0);
238
+ _defineProperty(this, "txTimeout", __injectivelabs_utils.DEFAULT_BLOCK_TIMEOUT_HEIGHT);
239
+ _defineProperty(this, "simulateTx", true);
240
+ _defineProperty(this, "txTimeoutOnFeeDelegation", false);
241
+ _defineProperty(this, "evmChainId", void 0);
242
+ _defineProperty(this, "gasBufferCoefficient", 1.2);
243
+ _defineProperty(this, "retriesOnError", defaultRetriesConfig());
244
+ _defineProperty(this, "httpHeaders", void 0);
245
+ const networkInfo = (0, __injectivelabs_networks.getNetworkInfo)(options.network);
246
+ this.options = options;
247
+ this.simulateTx = options.simulateTx !== void 0 ? options.simulateTx : true;
248
+ this.txTimeout = options.txTimeout || __injectivelabs_utils.DEFAULT_BLOCK_TIMEOUT_HEIGHT;
249
+ this.txTimeoutOnFeeDelegation = options.txTimeoutOnFeeDelegation !== void 0 ? options.txTimeoutOnFeeDelegation : true;
250
+ this.gasBufferCoefficient = options.gasBufferCoefficient || 1.2;
251
+ this.chainId = options.chainId || networkInfo.chainId;
252
+ this.evmChainId = options.evmChainId || networkInfo.evmChainId;
253
+ this.endpoints = options.endpoints || (0, __injectivelabs_networks.getNetworkEndpoints)(options.network);
254
+ this.walletStrategy = options.walletStrategy;
255
+ this.httpHeaders = options.httpHeaders;
256
+ }
257
+ setOptions(options) {
258
+ this.simulateTx = options.simulateTx || this.simulateTx;
259
+ this.txTimeout = options.txTimeout || this.txTimeout;
260
+ this.txTimeoutOnFeeDelegation = options.txTimeoutOnFeeDelegation || this.txTimeoutOnFeeDelegation;
261
+ }
262
+ async getEvmChainId() {
263
+ const { walletStrategy } = this;
264
+ if (!(0, __injectivelabs_wallet_base.isEvmBrowserWallet)(walletStrategy.wallet)) return this.evmChainId;
265
+ const mainnetEvmIds = [__injectivelabs_ts_types.EvmChainId.Mainnet, __injectivelabs_ts_types.EvmChainId.MainnetEvm];
266
+ const testnetEvmIds = [__injectivelabs_ts_types.EvmChainId.Sepolia, __injectivelabs_ts_types.EvmChainId.TestnetEvm];
267
+ const devnetEvmIds = [__injectivelabs_ts_types.EvmChainId.Sepolia, __injectivelabs_ts_types.EvmChainId.DevnetEvm];
268
+ try {
269
+ const chainId = await walletStrategy.getEthereumChainId();
270
+ if (!chainId) return this.evmChainId;
271
+ const evmChainId = parseInt(chainId, 16);
272
+ if (isNaN(evmChainId)) return this.evmChainId;
273
+ if ((0, __injectivelabs_networks.isMainnet)(this.options.network) && !mainnetEvmIds.includes(evmChainId) || (0, __injectivelabs_networks.isTestnet)(this.options.network) && !testnetEvmIds.includes(evmChainId) || !(0, __injectivelabs_networks.isMainnet)(this.options.network) && !(0, __injectivelabs_networks.isTestnet)(this.options.network) && !devnetEvmIds.includes(evmChainId)) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Your selected network is incorrect"));
274
+ return evmChainId;
275
+ } catch (e) {
276
+ throw new __injectivelabs_exceptions.WalletException(e);
277
+ }
278
+ }
279
+ /**
280
+ * Broadcasting the transaction using the client
281
+ * side approach for both cosmos and ethereum native wallets
282
+ *
283
+ * @param tx
284
+ * @returns {string} transaction hash
285
+ */
286
+ async broadcast(tx) {
287
+ const { walletStrategy } = this;
288
+ const txWithAddresses = {
289
+ ...tx,
290
+ ethereumAddress: (0, __injectivelabs_wallet_base.getEthereumSignerAddress)(tx.injectiveAddress),
291
+ injectiveAddress: (0, __injectivelabs_wallet_base.getInjectiveSignerAddress)(tx.injectiveAddress)
292
+ };
293
+ if (__injectivelabs_sdk_ts.ofacWallets.includes(txWithAddresses.ethereumAddress)) throw new __injectivelabs_exceptions.GeneralException(/* @__PURE__ */ new Error("You cannot execute this transaction"));
294
+ try {
295
+ return (0, __injectivelabs_wallet_base.isCosmosWallet)(walletStrategy.wallet) ? await this.broadcastDirectSign(txWithAddresses) : (0, __injectivelabs_wallet_base.isEip712V2OnlyWallet)(walletStrategy.wallet) ? await this.broadcastEip712V2(txWithAddresses) : await this.broadcastEip712(txWithAddresses);
296
+ } catch (e) {
297
+ const error = e;
298
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionFail);
299
+ if ((0, __injectivelabs_exceptions.isThrownException)(error)) throw error;
300
+ throw new __injectivelabs_exceptions.TransactionException(new Error(error));
301
+ }
302
+ }
303
+ /**
304
+ * Broadcasting the transaction using the client
305
+ * side approach for both cosmos and ethereum native wallets
306
+ * Note: using EIP712_V2 for Ethereum wallets
307
+ *
308
+ * @param tx
309
+ * @returns {string} transaction hash
310
+ */
311
+ async broadcastV2(tx) {
312
+ const { walletStrategy } = this;
313
+ const txWithAddresses = {
314
+ ...tx,
315
+ ethereumAddress: (0, __injectivelabs_wallet_base.getEthereumSignerAddress)(tx.injectiveAddress),
316
+ injectiveAddress: (0, __injectivelabs_wallet_base.getInjectiveSignerAddress)(tx.injectiveAddress)
317
+ };
318
+ if (__injectivelabs_sdk_ts.ofacWallets.includes(txWithAddresses.ethereumAddress)) throw new __injectivelabs_exceptions.GeneralException(/* @__PURE__ */ new Error("You cannot execute this transaction"));
319
+ try {
320
+ return (0, __injectivelabs_wallet_base.isCosmosWallet)(walletStrategy.wallet) ? await this.broadcastDirectSign(txWithAddresses) : await this.broadcastEip712V2(txWithAddresses);
321
+ } catch (e) {
322
+ const error = e;
323
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionFail);
324
+ if ((0, __injectivelabs_exceptions.isThrownException)(error)) throw error;
325
+ throw new __injectivelabs_exceptions.TransactionException(new Error(error));
326
+ }
327
+ }
328
+ /**
329
+ * Broadcasting the transaction using the feeDelegation
330
+ * support approach for both cosmos and ethereum native wallets
331
+ *
332
+ * @param tx
333
+ * @returns {string} transaction hash
334
+ */
335
+ async broadcastWithFeeDelegation(tx) {
336
+ const { walletStrategy } = this;
337
+ const txWithAddresses = {
338
+ ...tx,
339
+ ethereumAddress: (0, __injectivelabs_wallet_base.getEthereumSignerAddress)(tx.injectiveAddress),
340
+ injectiveAddress: (0, __injectivelabs_wallet_base.getInjectiveSignerAddress)(tx.injectiveAddress)
341
+ };
342
+ if (__injectivelabs_sdk_ts.ofacWallets.includes(txWithAddresses.ethereumAddress)) throw new __injectivelabs_exceptions.GeneralException(/* @__PURE__ */ new Error("You cannot execute this transaction"));
343
+ try {
344
+ return (0, __injectivelabs_wallet_base.isCosmosWallet)(walletStrategy.wallet) ? await this.broadcastDirectSignWithFeeDelegation(txWithAddresses) : await this.broadcastEip712WithFeeDelegation(txWithAddresses);
345
+ } catch (e) {
346
+ const error = e;
347
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionFail);
348
+ if ((0, __injectivelabs_exceptions.isThrownException)(error)) throw error;
349
+ throw new __injectivelabs_exceptions.TransactionException(new Error(error));
350
+ }
351
+ }
352
+ /**
353
+ * Prepare/sign/broadcast transaction using
354
+ * Ethereum native wallets on the client side.
355
+ *
356
+ * Note: Gas estimation not available
357
+ *
358
+ * @param tx The transaction that needs to be broadcasted
359
+ * @returns transaction hash
360
+ */
361
+ async broadcastEip712(tx) {
362
+ var _tx$gas, _baseAccount$pubKey;
363
+ const { chainId, endpoints, walletStrategy, txTimeout: txTimeoutInBlocks } = this;
364
+ const msgs = Array.isArray(tx.msgs) ? tx.msgs : [tx.msgs];
365
+ const evmChainId = await this.getEvmChainId();
366
+ if (!evmChainId) throw new __injectivelabs_exceptions.GeneralException(/* @__PURE__ */ new Error("Please provide evmChainId"));
367
+ /** Account Details * */
368
+ const { baseAccount, latestHeight } = await this.fetchAccountAndBlockDetails(tx.injectiveAddress);
369
+ const timeoutHeight = (0, __injectivelabs_utils.toBigNumber)(latestHeight).plus(txTimeoutInBlocks);
370
+ const txTimeoutTimeInSeconds = txTimeoutInBlocks * __injectivelabs_utils.DEFAULT_BLOCK_TIME_IN_SECONDS;
371
+ const txTimeoutTimeInMilliSeconds = txTimeoutTimeInSeconds * 1e3;
372
+ const gas = (((_tx$gas = tx.gas) === null || _tx$gas === void 0 ? void 0 : _tx$gas.gas) || (0, __injectivelabs_sdk_ts.getGasPriceBasedOnMessage)(msgs)).toString();
373
+ let stdFee = (0, __injectivelabs_utils.getStdFee)({
374
+ ...tx.gas,
375
+ gas
376
+ });
377
+ /**
378
+ * Account has not been created on chain
379
+ * and we cannot simulate the transaction
380
+ * to estimate the gas
381
+ **/
382
+ if (!baseAccount.pubKey) stdFee = await this.getStdFeeWithDynamicBaseFee(stdFee);
383
+ else {
384
+ const { stdFee: simulatedStdFee } = await this.getTxWithSignersAndStdFee({
385
+ chainId,
386
+ signMode: __injectivelabs_sdk_ts.SIGN_EIP712,
387
+ memo: tx.memo,
388
+ message: msgs,
389
+ timeoutHeight: timeoutHeight.toNumber(),
390
+ signers: {
391
+ pubKey: baseAccount.pubKey.key,
392
+ accountNumber: baseAccount.accountNumber,
393
+ sequence: baseAccount.sequence
394
+ },
395
+ fee: stdFee
396
+ });
397
+ stdFee = simulatedStdFee;
398
+ }
399
+ /** EIP712 for signing on Ethereum wallets */
400
+ const eip712TypedData = (0, __injectivelabs_sdk_ts.getEip712TypedData)({
401
+ msgs,
402
+ fee: stdFee,
403
+ tx: {
404
+ memo: tx.memo,
405
+ accountNumber: baseAccount.accountNumber.toString(),
406
+ sequence: baseAccount.sequence.toString(),
407
+ timeoutHeight: timeoutHeight.toFixed(),
408
+ chainId
409
+ },
410
+ evmChainId
411
+ });
412
+ /** Signing on Ethereum */
413
+ const signature = await walletStrategy.signEip712TypedData(JSON.stringify(eip712TypedData), tx.ethereumAddress, { txTimeout: txTimeoutTimeInSeconds });
414
+ const pubKeyOrSignatureDerivedPubKey = await getEthereumWalletPubKey({
415
+ pubKey: (_baseAccount$pubKey = baseAccount.pubKey) === null || _baseAccount$pubKey === void 0 ? void 0 : _baseAccount$pubKey.key,
416
+ eip712TypedData,
417
+ signature
418
+ });
419
+ /** Preparing the transaction for client broadcasting */
420
+ const { txRaw } = (0, __injectivelabs_sdk_ts.createTransaction)({
421
+ message: msgs,
422
+ memo: tx.memo,
423
+ signMode: __injectivelabs_sdk_ts.SIGN_EIP712,
424
+ fee: stdFee,
425
+ pubKey: pubKeyOrSignatureDerivedPubKey,
426
+ sequence: baseAccount.sequence,
427
+ timeoutHeight: timeoutHeight.toNumber(),
428
+ accountNumber: baseAccount.accountNumber,
429
+ chainId
430
+ });
431
+ const txRawEip712 = (0, __injectivelabs_sdk_ts.createTxRawEIP712)(txRaw, (0, __injectivelabs_sdk_ts.createWeb3Extension)({ evmChainId }));
432
+ /** Append Signatures */
433
+ txRawEip712.signatures = [(0, __injectivelabs_sdk_ts.hexToBuff)(signature)];
434
+ const response = await walletStrategy.sendTransaction(txRawEip712, {
435
+ chainId,
436
+ endpoints,
437
+ txTimeout: txTimeoutInBlocks,
438
+ address: tx.injectiveAddress
439
+ });
440
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastEnd);
441
+ return await new __injectivelabs_sdk_ts.TxGrpcApi(endpoints.grpc).fetchTxPoll(response.txHash, txTimeoutTimeInMilliSeconds);
442
+ }
443
+ /**
444
+ * Prepare/sign/broadcast transaction using
445
+ * Ethereum native wallets on the client side.
446
+ *
447
+ * Note: Gas estimation not available
448
+ *
449
+ * @param tx The transaction that needs to be broadcasted
450
+ * @returns transaction hash
451
+ */
452
+ async broadcastEip712V2(tx) {
453
+ var _tx$gas2, _baseAccount$pubKey2;
454
+ const { chainId, endpoints, walletStrategy, txTimeout: txTimeoutInBlocks } = this;
455
+ const msgs = Array.isArray(tx.msgs) ? tx.msgs : [tx.msgs];
456
+ const evmChainId = await this.getEvmChainId();
457
+ if (!evmChainId) throw new __injectivelabs_exceptions.GeneralException(/* @__PURE__ */ new Error("Please provide evmChainId"));
458
+ /** Account Details * */
459
+ const { baseAccount, latestHeight } = await this.fetchAccountAndBlockDetails(tx.injectiveAddress);
460
+ const timeoutHeight = (0, __injectivelabs_utils.toBigNumber)(latestHeight).plus(txTimeoutInBlocks);
461
+ const txTimeoutTimeInSeconds = txTimeoutInBlocks * __injectivelabs_utils.DEFAULT_BLOCK_TIME_IN_SECONDS;
462
+ const txTimeoutTimeInMilliSeconds = txTimeoutTimeInSeconds * 1e3;
463
+ const gas = (((_tx$gas2 = tx.gas) === null || _tx$gas2 === void 0 ? void 0 : _tx$gas2.gas) || (0, __injectivelabs_sdk_ts.getGasPriceBasedOnMessage)(msgs)).toString();
464
+ let stdFee = (0, __injectivelabs_utils.getStdFee)({
465
+ ...tx.gas,
466
+ gas
467
+ });
468
+ /**
469
+ * Account has not been created on chain
470
+ * and we cannot simulate the transaction
471
+ * to estimate the gas
472
+ **/
473
+ if (!baseAccount.pubKey) stdFee = await this.getStdFeeWithDynamicBaseFee(stdFee);
474
+ else {
475
+ const { stdFee: simulatedStdFee } = await this.getTxWithSignersAndStdFee({
476
+ chainId,
477
+ signMode: __injectivelabs_sdk_ts.SIGN_EIP712_V2,
478
+ memo: tx.memo,
479
+ message: msgs,
480
+ timeoutHeight: timeoutHeight.toNumber(),
481
+ signers: {
482
+ pubKey: baseAccount.pubKey.key,
483
+ sequence: baseAccount.sequence,
484
+ accountNumber: baseAccount.accountNumber
485
+ },
486
+ fee: stdFee
487
+ });
488
+ stdFee = simulatedStdFee;
489
+ }
490
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationStart);
491
+ /** EIP712 for signing on Ethereum wallets */
492
+ const eip712TypedData = (0, __injectivelabs_sdk_ts.getEip712TypedDataV2)({
493
+ msgs,
494
+ fee: stdFee,
495
+ tx: {
496
+ memo: tx.memo,
497
+ accountNumber: baseAccount.accountNumber.toString(),
498
+ sequence: baseAccount.sequence.toString(),
499
+ timeoutHeight: timeoutHeight.toFixed(),
500
+ chainId
501
+ },
502
+ evmChainId
503
+ });
504
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationEnd);
505
+ /** Signing on Ethereum */
506
+ const signature = await walletStrategy.signEip712TypedData(JSON.stringify(eip712TypedData), tx.ethereumAddress, { txTimeout: txTimeoutTimeInSeconds });
507
+ const pubKeyOrSignatureDerivedPubKey = await getEthereumWalletPubKey({
508
+ pubKey: (_baseAccount$pubKey2 = baseAccount.pubKey) === null || _baseAccount$pubKey2 === void 0 ? void 0 : _baseAccount$pubKey2.key,
509
+ eip712TypedData,
510
+ signature
511
+ });
512
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastStart);
513
+ const { txRaw } = (0, __injectivelabs_sdk_ts.createTransaction)({
514
+ message: msgs,
515
+ memo: tx.memo,
516
+ signMode: __injectivelabs_sdk_ts.SIGN_EIP712_V2,
517
+ fee: stdFee,
518
+ pubKey: pubKeyOrSignatureDerivedPubKey,
519
+ sequence: baseAccount.sequence,
520
+ timeoutHeight: timeoutHeight.toNumber(),
521
+ accountNumber: baseAccount.accountNumber,
522
+ chainId
523
+ });
524
+ const txRawEip712 = (0, __injectivelabs_sdk_ts.createTxRawEIP712)(txRaw, (0, __injectivelabs_sdk_ts.createWeb3Extension)({ evmChainId }));
525
+ /** Append Signatures */
526
+ txRawEip712.signatures = [(0, __injectivelabs_sdk_ts.hexToBuff)(signature)];
527
+ const response = await walletStrategy.sendTransaction(txRawEip712, {
528
+ chainId,
529
+ endpoints,
530
+ txTimeout: txTimeoutInBlocks,
531
+ address: tx.injectiveAddress
532
+ });
533
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastEnd);
534
+ return await new __injectivelabs_sdk_ts.TxGrpcApi(endpoints.grpc).fetchTxPoll(response.txHash, txTimeoutTimeInMilliSeconds);
535
+ }
536
+ /**
537
+ * Prepare/sign/broadcast transaction using
538
+ * Ethereum native wallets using the Web3Gateway.
539
+ *
540
+ * @param tx The transaction that needs to be broadcasted
541
+ * @returns transaction hash
542
+ */
543
+ async broadcastEip712WithFeeDelegation(tx) {
544
+ const { endpoints, simulateTx, httpHeaders, walletStrategy, txTimeoutOnFeeDelegation, txTimeout: txTimeoutInBlocks } = this;
545
+ const msgs = Array.isArray(tx.msgs) ? tx.msgs : [tx.msgs];
546
+ const web3Msgs = msgs.map((msg) => msg.toWeb3());
547
+ const evmChainId = await this.getEvmChainId();
548
+ if (!evmChainId) throw new __injectivelabs_exceptions.GeneralException(/* @__PURE__ */ new Error("Please provide evmChainId"));
549
+ const transactionApi = new __injectivelabs_sdk_ts.IndexerGrpcWeb3GwApi(endpoints.web3gw || endpoints.indexer);
550
+ if (httpHeaders) transactionApi.setMetadata(httpHeaders);
551
+ const txTimeoutTimeInSeconds = txTimeoutInBlocks * __injectivelabs_utils.DEFAULT_BLOCK_TIME_IN_SECONDS;
552
+ const txTimeoutTimeInMilliSeconds = txTimeoutTimeInSeconds * 1e3;
553
+ let timeoutHeight = void 0;
554
+ if (txTimeoutOnFeeDelegation) {
555
+ const latestHeight = (await new __injectivelabs_sdk_ts.ChainGrpcTendermintApi(endpoints.grpc).fetchLatestBlock()).header.height;
556
+ timeoutHeight = (0, __injectivelabs_utils.toBigNumber)(latestHeight).plus(txTimeoutInBlocks).toNumber();
557
+ }
558
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationStart);
559
+ const prepareTxResponse = await transactionApi.prepareTxRequest({
560
+ timeoutHeight,
561
+ memo: tx.memo,
562
+ message: web3Msgs,
563
+ address: tx.ethereumAddress,
564
+ chainId: evmChainId,
565
+ gasLimit: (0, __injectivelabs_sdk_ts.getGasPriceBasedOnMessage)(msgs),
566
+ estimateGas: simulateTx
567
+ });
568
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationEnd);
569
+ const signature = await walletStrategy.signEip712TypedData(prepareTxResponse.data, tx.ethereumAddress, { txTimeout: txTimeoutTimeInSeconds });
570
+ const broadcast = async () => await transactionApi.broadcastTxRequest({
571
+ signature,
572
+ message: web3Msgs,
573
+ txResponse: prepareTxResponse,
574
+ chainId: evmChainId
575
+ });
576
+ try {
577
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastStart);
578
+ const response = await broadcast();
579
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastEnd);
580
+ return await new __injectivelabs_sdk_ts.TxGrpcApi(endpoints.grpc).fetchTxPoll(response.txHash, txTimeoutTimeInMilliSeconds);
581
+ } catch (e) {
582
+ const error = e;
583
+ if ((0, __injectivelabs_exceptions.isThrownException)(error)) {
584
+ const exception = error;
585
+ /**
586
+ * First MsgExec transaction with a PrivateKey wallet
587
+ * always runs out of gas for some reason, temporary solution
588
+ * to just broadcast the transaction twice
589
+ **/
590
+ if (walletStrategy.wallet === __injectivelabs_wallet_base.Wallet.PrivateKey && checkIfTxRunOutOfGas(exception)) {
591
+ const { baseAccount } = await new __injectivelabs_sdk_ts.ChainGrpcAuthApi(endpoints.grpc).fetchAccount(tx.injectiveAddress);
592
+ /** We only do it on the first account tx fail */
593
+ if (baseAccount.sequence > 1) throw e;
594
+ return await this.broadcastEip712WithFeeDelegation(tx);
595
+ }
596
+ return await this.retryOnException(exception, broadcast);
597
+ }
598
+ throw e;
599
+ }
600
+ }
601
+ /**
602
+ * Prepare/sign/broadcast transaction using
603
+ * Cosmos native wallets on the client side.
604
+ *
605
+ * @param tx The transaction that needs to be broadcasted
606
+ * @returns transaction hash
607
+ */
608
+ async broadcastDirectSign(tx) {
609
+ var _tx$gas3;
610
+ const { chainId, endpoints, walletStrategy, txTimeout: txTimeoutInBlocks } = this;
611
+ const msgs = Array.isArray(tx.msgs) ? tx.msgs : [tx.msgs];
612
+ /**
613
+ * When using Ledger with Keplr/Leap we have
614
+ * to send EIP712 to sign on Keplr/Leap
615
+ */
616
+ if ([__injectivelabs_wallet_base.Wallet.Keplr, __injectivelabs_wallet_base.Wallet.Leap].includes(walletStrategy.getWallet())) {
617
+ if (await walletStrategy.getWalletDeviceType() === __injectivelabs_wallet_base.WalletDeviceType.Hardware) return this.experimentalBroadcastWalletThroughLedger(tx);
618
+ }
619
+ const { baseAccount, latestHeight } = await this.fetchAccountAndBlockDetails(tx.injectiveAddress);
620
+ const timeoutHeight = (0, __injectivelabs_utils.toBigNumber)(latestHeight).plus(txTimeoutInBlocks);
621
+ const txTimeoutTimeInMilliSeconds = txTimeoutInBlocks * __injectivelabs_utils.DEFAULT_BLOCK_TIME_IN_SECONDS * 1e3;
622
+ const signMode = (0, __injectivelabs_wallet_base.isCosmosAminoOnlyWallet)(walletStrategy.wallet) ? __injectivelabs_sdk_ts.SIGN_EIP712 : __injectivelabs_sdk_ts.SIGN_DIRECT;
623
+ const pubKey = await walletStrategy.getPubKey(tx.injectiveAddress);
624
+ const gas = (((_tx$gas3 = tx.gas) === null || _tx$gas3 === void 0 ? void 0 : _tx$gas3.gas) || (0, __injectivelabs_sdk_ts.getGasPriceBasedOnMessage)(msgs)).toString();
625
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationStart);
626
+ /** Prepare the Transaction * */
627
+ const { txRaw } = await this.getTxWithSignersAndStdFee({
628
+ chainId,
629
+ signMode,
630
+ memo: tx.memo,
631
+ message: msgs,
632
+ timeoutHeight: timeoutHeight.toNumber(),
633
+ signers: {
634
+ pubKey,
635
+ accountNumber: baseAccount.accountNumber,
636
+ sequence: baseAccount.sequence
637
+ },
638
+ fee: (0, __injectivelabs_utils.getStdFee)({
639
+ ...tx.gas,
640
+ gas
641
+ })
642
+ });
643
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationEnd);
644
+ /** Ledger using Cosmos app only allows signing amino docs */
645
+ if ((0, __injectivelabs_wallet_base.isCosmosAminoOnlyWallet)(walletStrategy.wallet)) {
646
+ var _tx$gas4;
647
+ const aminoSignDoc = (0, __injectivelabs_sdk_ts.getAminoStdSignDoc)({
648
+ ...tx,
649
+ ...baseAccount,
650
+ msgs,
651
+ chainId,
652
+ gas: gas || ((_tx$gas4 = tx.gas) === null || _tx$gas4 === void 0 || (_tx$gas4 = _tx$gas4.gas) === null || _tx$gas4 === void 0 ? void 0 : _tx$gas4.toString()),
653
+ timeoutHeight: timeoutHeight.toFixed()
654
+ });
655
+ txRaw.signatures = [(0, __injectivelabs_sdk_ts.base64ToUint8Array)((await walletStrategy.signAminoCosmosTransaction({
656
+ signDoc: aminoSignDoc,
657
+ address: tx.injectiveAddress
658
+ })).signature.signature)];
659
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastStart);
660
+ const response$1 = await walletStrategy.sendTransaction(txRaw, {
661
+ chainId,
662
+ endpoints,
663
+ address: tx.injectiveAddress,
664
+ txTimeout: txTimeoutInBlocks
665
+ });
666
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastEnd);
667
+ return await new __injectivelabs_sdk_ts.TxGrpcApi(endpoints.grpc).fetchTxPoll(response$1.txHash, txTimeoutTimeInMilliSeconds);
668
+ }
669
+ const directSignResponse = await walletStrategy.signCosmosTransaction({
670
+ txRaw,
671
+ chainId,
672
+ address: tx.injectiveAddress,
673
+ accountNumber: baseAccount.accountNumber
674
+ });
675
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastStart);
676
+ const response = await walletStrategy.sendTransaction(directSignResponse, {
677
+ chainId,
678
+ endpoints,
679
+ txTimeout: txTimeoutInBlocks,
680
+ address: tx.injectiveAddress
681
+ });
682
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastEnd);
683
+ return await new __injectivelabs_sdk_ts.TxGrpcApi(endpoints.grpc).fetchTxPoll(response.txHash, txTimeoutTimeInMilliSeconds);
684
+ }
685
+ /**
686
+ * We use this method only when we want to broadcast a transaction using Ledger on Keplr/Leap for Injective
687
+ *
688
+ * Note: Gas estimation not available
689
+ * @param tx the transaction that needs to be broadcasted
690
+ */
691
+ async experimentalBroadcastWalletThroughLedger(tx) {
692
+ var _tx$gas5, _tx$gas6;
693
+ const { chainId, endpoints, evmChainId, simulateTx, walletStrategy, txTimeout: txTimeoutInBlocks } = this;
694
+ const msgs = Array.isArray(tx.msgs) ? tx.msgs : [tx.msgs];
695
+ /**
696
+ * We can only use this method
697
+ * when Ledger is connected through Keplr
698
+ */
699
+ if ([__injectivelabs_wallet_base.Wallet.Keplr, __injectivelabs_wallet_base.Wallet.Leap].includes(walletStrategy.getWallet())) {
700
+ if (!(await walletStrategy.getWalletDeviceType() === __injectivelabs_wallet_base.WalletDeviceType.Hardware)) throw new __injectivelabs_exceptions.GeneralException(/* @__PURE__ */ new Error(`This method can only be used when Ledger is connected through ${walletStrategy.getWallet()}`));
701
+ }
702
+ if (!evmChainId) throw new __injectivelabs_exceptions.GeneralException(/* @__PURE__ */ new Error("Please provide evmChainId"));
703
+ const cosmosWallet = walletStrategy.getCosmosWallet(chainId);
704
+ const { baseAccount, latestHeight } = await this.fetchAccountAndBlockDetails(tx.injectiveAddress);
705
+ const timeoutHeight = (0, __injectivelabs_utils.toBigNumber)(latestHeight).plus(txTimeoutInBlocks);
706
+ const pubKey = await walletStrategy.getPubKey();
707
+ const gas = (((_tx$gas5 = tx.gas) === null || _tx$gas5 === void 0 ? void 0 : _tx$gas5.gas) || (0, __injectivelabs_sdk_ts.getGasPriceBasedOnMessage)(msgs)).toString();
708
+ /** EIP712 for signing on Ethereum wallets */
709
+ const eip712TypedData = (0, __injectivelabs_sdk_ts.getEip712TypedData)({
710
+ msgs,
711
+ fee: await this.getStdFeeWithDynamicBaseFee({
712
+ ...tx.gas,
713
+ gas
714
+ }),
715
+ tx: {
716
+ chainId,
717
+ memo: tx.memo,
718
+ timeoutHeight: timeoutHeight.toFixed(),
719
+ sequence: baseAccount.sequence.toString(),
720
+ accountNumber: baseAccount.accountNumber.toString()
721
+ },
722
+ evmChainId
723
+ });
724
+ const aminoSignResponse = await cosmosWallet.signEIP712CosmosTx({
725
+ eip712: eip712TypedData,
726
+ signDoc: (0, __injectivelabs_wallet_base.createEip712StdSignDoc)({
727
+ ...tx,
728
+ ...baseAccount,
729
+ msgs,
730
+ chainId,
731
+ gas: gas || ((_tx$gas6 = tx.gas) === null || _tx$gas6 === void 0 || (_tx$gas6 = _tx$gas6.gas) === null || _tx$gas6 === void 0 ? void 0 : _tx$gas6.toString()),
732
+ timeoutHeight: timeoutHeight.toFixed()
733
+ })
734
+ });
735
+ /**
736
+ * Create TxRaw from the signed tx that we
737
+ * get as a response in case the user changed the fee/memo
738
+ * on the Keplr popup
739
+ */
740
+ const { txRaw } = (0, __injectivelabs_sdk_ts.createTransaction)({
741
+ pubKey,
742
+ message: msgs,
743
+ memo: aminoSignResponse.signed.memo,
744
+ signMode: __injectivelabs_sdk_ts.SIGN_EIP712,
745
+ fee: aminoSignResponse.signed.fee,
746
+ sequence: parseInt(aminoSignResponse.signed.sequence, 10),
747
+ timeoutHeight: parseInt(aminoSignResponse.signed.timeout_height, 10),
748
+ accountNumber: parseInt(aminoSignResponse.signed.account_number, 10),
749
+ chainId
750
+ });
751
+ const txRawEip712 = (0, __injectivelabs_sdk_ts.createTxRawEIP712)(txRaw, (0, __injectivelabs_sdk_ts.createWeb3Extension)({ evmChainId }));
752
+ if (simulateTx) await this.simulateTxRaw(txRawEip712);
753
+ txRawEip712.signatures = [(0, __injectivelabs_sdk_ts.base64ToUint8Array)(aminoSignResponse.signature.signature)];
754
+ /** Broadcast the transaction */
755
+ const response = await new __injectivelabs_sdk_ts.TxGrpcApi(endpoints.grpc).broadcast(txRawEip712, { txTimeout: txTimeoutInBlocks });
756
+ if (response.code !== 0) throw new __injectivelabs_exceptions.TransactionException(new Error(response.rawLog), {
757
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
758
+ contextCode: response.code,
759
+ contextModule: response.codespace
760
+ });
761
+ return response;
762
+ }
763
+ /**
764
+ * Prepare/sign/broadcast transaction using
765
+ * Cosmos native wallets using the Web3Gateway.
766
+ *
767
+ * @param tx The transaction that needs to be broadcasted
768
+ * @returns transaction hash
769
+ */
770
+ async broadcastDirectSignWithFeeDelegation(tx) {
771
+ var _tx$gas7;
772
+ const { options, chainId, endpoints, httpHeaders, walletStrategy, txTimeoutOnFeeDelegation, txTimeout: txTimeoutInBlocks } = this;
773
+ const msgs = Array.isArray(tx.msgs) ? tx.msgs : [tx.msgs];
774
+ /**
775
+ * We can only use this method when Keplr is connected
776
+ * with ledger
777
+ */
778
+ if (walletStrategy.getWallet() === __injectivelabs_wallet_base.Wallet.Keplr) {
779
+ if (await walletStrategy.getWalletDeviceType() === __injectivelabs_wallet_base.WalletDeviceType.Hardware) throw new __injectivelabs_exceptions.GeneralException(/* @__PURE__ */ new Error("Keplr + Ledger is not available with fee delegation. Connect with Ledger directly."));
780
+ }
781
+ const cosmosWallet = walletStrategy.getCosmosWallet(chainId);
782
+ const canDisableCosmosGasCheck = [__injectivelabs_wallet_base.Wallet.Keplr, __injectivelabs_wallet_base.Wallet.OWallet].includes(walletStrategy.wallet);
783
+ const feePayerPubKey = await this.fetchFeePayerPubKey(options.feePayerPubKey);
784
+ const feePayerPublicKey = __injectivelabs_sdk_ts.PublicKey.fromBase64(feePayerPubKey);
785
+ const feePayer = feePayerPublicKey.toAddress().address;
786
+ /** Account Details * */
787
+ const { baseAccount, latestHeight } = await this.fetchAccountAndBlockDetails(tx.injectiveAddress);
788
+ const chainGrpcAuthApi = new __injectivelabs_sdk_ts.ChainGrpcAuthApi(endpoints.grpc);
789
+ if (httpHeaders) chainGrpcAuthApi.setMetadata(httpHeaders);
790
+ const { baseAccount: feePayerBaseAccount } = await chainGrpcAuthApi.fetchAccount(feePayer);
791
+ const timeoutHeight = (0, __injectivelabs_utils.toBigNumber)(latestHeight).plus(txTimeoutOnFeeDelegation ? txTimeoutInBlocks : __injectivelabs_utils.DEFAULT_BLOCK_TIMEOUT_HEIGHT);
792
+ const txTimeoutTimeInMilliSeconds = txTimeoutInBlocks * __injectivelabs_utils.DEFAULT_BLOCK_TIME_IN_SECONDS * 1e3;
793
+ const pubKey = await walletStrategy.getPubKey();
794
+ const gas = (((_tx$gas7 = tx.gas) === null || _tx$gas7 === void 0 ? void 0 : _tx$gas7.gas) || (0, __injectivelabs_sdk_ts.getGasPriceBasedOnMessage)(msgs)).toString();
795
+ /** Prepare the Transaction * */
796
+ const { txRaw } = await this.getTxWithSignersAndStdFee({
797
+ chainId,
798
+ memo: tx.memo,
799
+ message: msgs,
800
+ timeoutHeight: timeoutHeight.toNumber(),
801
+ signers: [{
802
+ pubKey,
803
+ accountNumber: baseAccount.accountNumber,
804
+ sequence: baseAccount.sequence
805
+ }, {
806
+ pubKey: feePayerPublicKey.toBase64(),
807
+ accountNumber: feePayerBaseAccount.accountNumber,
808
+ sequence: feePayerBaseAccount.sequence
809
+ }],
810
+ fee: (0, __injectivelabs_utils.getStdFee)({
811
+ ...tx.gas,
812
+ gas,
813
+ payer: feePayer
814
+ })
815
+ });
816
+ if (canDisableCosmosGasCheck && cosmosWallet.disableGasCheck) cosmosWallet.disableGasCheck(chainId);
817
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationStart);
818
+ const directSignResponse = await walletStrategy.signCosmosTransaction({
819
+ txRaw,
820
+ chainId,
821
+ address: tx.injectiveAddress,
822
+ accountNumber: baseAccount.accountNumber
823
+ });
824
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationEnd);
825
+ const transactionApi = new __injectivelabs_sdk_ts.IndexerGrpcWeb3GwApi(endpoints.web3gw || endpoints.indexer);
826
+ if (httpHeaders) transactionApi.setMetadata(httpHeaders);
827
+ const broadcast = async () => await transactionApi.broadcastCosmosTxRequest({
828
+ address: tx.injectiveAddress,
829
+ txRaw: (0, __injectivelabs_sdk_ts.createTxRawFromSigResponse)(directSignResponse),
830
+ signature: directSignResponse.signature.signature,
831
+ pubKey: directSignResponse.signature.pub_key || {
832
+ value: pubKey,
833
+ type: "/injective.crypto.v1beta1.ethsecp256k1.PubKey"
834
+ }
835
+ });
836
+ try {
837
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastStart);
838
+ const response = await broadcast();
839
+ walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastEnd);
840
+ if (canDisableCosmosGasCheck && cosmosWallet.enableGasCheck) cosmosWallet.enableGasCheck(chainId);
841
+ return await new __injectivelabs_sdk_ts.TxGrpcApi(endpoints.grpc).fetchTxPoll(response.txHash, txTimeoutTimeInMilliSeconds);
842
+ } catch (e) {
843
+ const error = e;
844
+ if ((0, __injectivelabs_exceptions.isThrownException)(error)) {
845
+ const exception = error;
846
+ return await this.retryOnException(exception, broadcast);
847
+ }
848
+ throw e;
849
+ }
850
+ }
851
+ /**
852
+ * Fetch the fee payer's pub key from the web3 gateway
853
+ *
854
+ * Returns a base64 version of it
855
+ */
856
+ async fetchFeePayerPubKey(existingFeePayerPubKey) {
857
+ if (existingFeePayerPubKey) return existingFeePayerPubKey;
858
+ const { endpoints, httpHeaders } = this;
859
+ const transactionApi = new __injectivelabs_sdk_ts.IndexerGrpcWeb3GwApi(endpoints.web3gw || endpoints.indexer);
860
+ if (httpHeaders) transactionApi.setMetadata(httpHeaders);
861
+ const response = await transactionApi.fetchFeePayer();
862
+ if (!response.feePayerPubKey) throw new __injectivelabs_exceptions.GeneralException(/* @__PURE__ */ new Error("Please provide a feePayerPubKey"));
863
+ if (response.feePayerPubKey.key.startsWith("0x") || response.feePayerPubKey.key.length === 66) return (0, __injectivelabs_sdk_ts.uint8ArrayToBase64)((0, __injectivelabs_sdk_ts.hexToUint8Array)(response.feePayerPubKey.key));
864
+ return response.feePayerPubKey.key;
865
+ }
866
+ async getStdFeeWithDynamicBaseFee(args) {
867
+ const client = new __injectivelabs_sdk_ts.ChainGrpcTxFeesApi(this.endpoints.grpc);
868
+ let baseFee = __injectivelabs_utils.DEFAULT_GAS_PRICE;
869
+ try {
870
+ const response = await client.fetchEipBaseFee();
871
+ baseFee = Number((response === null || response === void 0 ? void 0 : response.baseFee) || __injectivelabs_utils.DEFAULT_GAS_PRICE);
872
+ } catch (_unused) {}
873
+ if (!args) return (0, __injectivelabs_utils.getStdFee)(baseFee ? { gasPrice: baseFee } : {});
874
+ if (typeof args === "string") return (0, __injectivelabs_utils.getStdFee)({
875
+ ...baseFee && { gasPrice: (0, __injectivelabs_utils.toBigNumber)(baseFee).toFixed() },
876
+ gas: args
877
+ });
878
+ return (0, __injectivelabs_utils.getStdFee)({
879
+ ...args,
880
+ ...baseFee && { gasPrice: (0, __injectivelabs_utils.toBigNumber)(baseFee).toFixed() }
881
+ });
882
+ }
883
+ /**
884
+ * In case we don't want to simulate the transaction
885
+ * we get the gas limit based on the message type.
886
+ *
887
+ * If we want to simulate the transaction we set the
888
+ * gas limit based on the simulation and add a small multiplier
889
+ * to be safe (factor of 1.2 as default)
890
+ */
891
+ async getTxWithSignersAndStdFee(args) {
892
+ var _result$gasInfo;
893
+ const { simulateTx } = this;
894
+ if (!simulateTx) return {
895
+ ...(0, __injectivelabs_sdk_ts.createTransactionWithSigners)(args),
896
+ stdFee: await this.getStdFeeWithDynamicBaseFee(args.fee)
897
+ };
898
+ const result = await this.simulateTxWithSigners(args);
899
+ if (!((_result$gasInfo = result.gasInfo) === null || _result$gasInfo === void 0 ? void 0 : _result$gasInfo.gasUsed)) return {
900
+ ...(0, __injectivelabs_sdk_ts.createTransactionWithSigners)(args),
901
+ stdFee: await this.getStdFeeWithDynamicBaseFee(args.fee)
902
+ };
903
+ const stdGasFee = { ...await this.getStdFeeWithDynamicBaseFee({
904
+ ...(0, __injectivelabs_utils.getStdFee)(args.fee),
905
+ gas: (0, __injectivelabs_utils.toBigNumber)(result.gasInfo.gasUsed).times(this.gasBufferCoefficient).toFixed()
906
+ }) };
907
+ return {
908
+ ...(0, __injectivelabs_sdk_ts.createTransactionWithSigners)({
909
+ ...args,
910
+ fee: stdGasFee
911
+ }),
912
+ stdFee: stdGasFee
913
+ };
914
+ }
915
+ /**
916
+ * Create TxRaw and simulate it
917
+ */
918
+ async simulateTxRaw(txRaw) {
919
+ const { endpoints, httpHeaders } = this;
920
+ txRaw.signatures = [new Uint8Array(0)];
921
+ const client = new __injectivelabs_sdk_ts.TxGrpcApi(endpoints.grpc);
922
+ if (httpHeaders) client.setMetadata(httpHeaders);
923
+ return await client.simulate(txRaw);
924
+ }
925
+ /**
926
+ * Create TxRaw and simulate it
927
+ */
928
+ async simulateTxWithSigners(args) {
929
+ const { endpoints, httpHeaders } = this;
930
+ const { txRaw } = (0, __injectivelabs_sdk_ts.createTransactionWithSigners)(args);
931
+ txRaw.signatures = Array(Array.isArray(args.signers) ? args.signers.length : 1).fill(new Uint8Array(0));
932
+ const client = new __injectivelabs_sdk_ts.TxGrpcApi(endpoints.grpc);
933
+ if (httpHeaders) client.setMetadata(httpHeaders);
934
+ return await client.simulate(txRaw);
935
+ }
936
+ async retryOnException(exception, retryLogic) {
937
+ const errorsToRetry = Object.keys(this.retriesOnError);
938
+ const errorKey = `${exception.contextModule}-${exception.contextCode}`;
939
+ if (!errorsToRetry.includes(errorKey)) throw exception;
940
+ const retryConfig = this.retriesOnError[errorKey];
941
+ if (retryConfig.retries >= retryConfig.maxRetries) {
942
+ this.retriesOnError = defaultRetriesConfig();
943
+ throw exception;
944
+ }
945
+ await (0, __injectivelabs_utils.sleep)(retryConfig.timeout);
946
+ try {
947
+ retryConfig.retries += 1;
948
+ return await retryLogic();
949
+ } catch (e) {
950
+ const error = e;
951
+ if ((0, __injectivelabs_exceptions.isThrownException)(error)) return this.retryOnException(error, retryLogic);
952
+ throw e;
953
+ }
954
+ }
955
+ async fetchAccountAndBlockDetails(address) {
956
+ const { endpoints, httpHeaders } = this;
957
+ const chainClient = new __injectivelabs_sdk_ts.ChainGrpcAuthApi(endpoints.grpc);
958
+ const tendermintClient = new __injectivelabs_sdk_ts.ChainGrpcTendermintApi(endpoints.grpc);
959
+ if (httpHeaders) {
960
+ chainClient.setMetadata(httpHeaders);
961
+ tendermintClient.setMetadata(httpHeaders);
962
+ }
963
+ const accountDetails = await chainClient.fetchAccount(address);
964
+ const { baseAccount } = accountDetails;
965
+ return {
966
+ baseAccount,
967
+ latestHeight: (await tendermintClient.fetchLatestBlock()).header.height,
968
+ accountDetails
969
+ };
970
+ }
971
+ };
972
+
973
+ //#endregion
974
+ //#region src/broadcaster/Web3Broadcaster.ts
975
+ /**
976
+ * Preparing and broadcasting
977
+ * Ethereum transactions
978
+ */
979
+ var Web3Broadcaster = class {
980
+ constructor({ walletStrategy, evmChainId }) {
981
+ _defineProperty(this, "walletStrategy", void 0);
982
+ _defineProperty(this, "evmChainId", void 0);
983
+ this.evmChainId = evmChainId;
984
+ this.walletStrategy = walletStrategy;
985
+ }
986
+ async sendTransaction(args) {
987
+ const { evmChainId, walletStrategy } = this;
988
+ try {
989
+ const chainId = args.evmChainId || evmChainId;
990
+ const txHash = await walletStrategy.sendEvmTransaction(args.tx, {
991
+ evmChainId: chainId,
992
+ address: args.address
993
+ });
994
+ await walletStrategy.getEvmTransactionReceipt(txHash, chainId);
995
+ return txHash;
996
+ } catch (e) {
997
+ throw new __injectivelabs_exceptions.Web3Exception(new Error(e.message));
998
+ }
999
+ }
1000
+ };
1001
+
1002
+ //#endregion
1003
+ exports.BaseWalletStrategy = BaseWalletStrategy;
1004
+ exports.MsgBroadcaster = MsgBroadcaster;
1005
+ exports.WalletStrategyEmitterEventType = WalletStrategyEmitterEventType;
1006
+ exports.Web3Broadcaster = Web3Broadcaster;
1007
+ exports.checkIfTxRunOutOfGas = checkIfTxRunOutOfGas;