@injectivelabs/wallet-core 1.20.7 → 1.20.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -1,1245 +1,5 @@
1
- import { ChainCosmosErrorCode, GeneralException, TransactionChainErrorModule, TransactionException, UnspecifiedErrorCode, WalletException, Web3Exception, isThrownException } from "@injectivelabs/exceptions";
2
- import { EventEmitter } from "eventemitter3";
3
- import { Wallet, WalletDeviceType, WalletStrategyEmitterEventType, createEip712StdSignDoc, getEthereumSignerAddress, getInjectiveSignerAddress, isCosmosAminoOnlyWallet, isCosmosWallet, isEip712V2OnlyWallet, isEvmBrowserWallet, isEvmWallet } from "@injectivelabs/wallet-base";
4
- import { EvmChainId } from "@injectivelabs/ts-types";
5
- import { PrivateKey, PublicKey } from "@injectivelabs/sdk-ts/core/accounts";
6
- import { base64ToUint8Array, getGasPriceBasedOnMessage, hexToBase64, hexToBuff, hexToUint8Array, ofacList, recoverTypedSignaturePubKey, safeBigIntStringify, uint8ArrayToBase64 } from "@injectivelabs/sdk-ts/utils";
7
- import { IndexerGrpcWeb3GwApi } from "@injectivelabs/sdk-ts/client/indexer";
8
- import { getNetworkEndpoints, getNetworkInfo, isMainnet, isTestnet } from "@injectivelabs/networks";
9
- import { ChainGrpcAuthApi, ChainGrpcTendermintApi, ChainGrpcTxFeesApi } from "@injectivelabs/sdk-ts/client/chain";
10
- import { DEFAULT_BLOCK_TIMEOUT_HEIGHT, DEFAULT_BLOCK_TIME_IN_SECONDS, DEFAULT_GAS_PRICE, getStdFee, sleep, toBigNumber } from "@injectivelabs/utils";
11
- import { CosmosTxV1Beta1TxPb, SIGN_DIRECT, SIGN_EIP712, SIGN_EIP712_V2, TxClient, TxGrpcApi, createTransaction, createTransactionWithSigners, createTxRawEIP712, createTxRawFromSigResponse, createWeb3Extension, getAminoStdSignDoc, getEip712TypedData, getEip712TypedDataV2 } from "@injectivelabs/sdk-ts/core/tx";
1
+ import { n as MsgBroadcaster, r as checkIfTxRunOutOfGas, t as Web3Broadcaster } from "./broadcaster-CA8Ix8IA.js";
2
+ import "./defineProperty-D4YE9KXX.js";
3
+ import { t as BaseWalletStrategy } from "./strategy-DU-V-GfI.js";
12
4
 
13
- //#region src/utils/tx.ts
14
- const checkIfTxRunOutOfGas = (e) => {
15
- return e instanceof TransactionException && e.contextCode === ChainCosmosErrorCode.ErrOutOfGas && e.contextModule === TransactionChainErrorModule.CosmosSdk && e.originalMessage.includes("out of gas");
16
- };
17
-
18
- //#endregion
19
- //#region \0@oxc-project+runtime@0.99.0/helpers/typeof.js
20
- function _typeof(o) {
21
- "@babel/helpers - typeof";
22
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
23
- return typeof o$1;
24
- } : function(o$1) {
25
- return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
26
- }, _typeof(o);
27
- }
28
-
29
- //#endregion
30
- //#region \0@oxc-project+runtime@0.99.0/helpers/toPrimitive.js
31
- function toPrimitive(t, r) {
32
- if ("object" != _typeof(t) || !t) return t;
33
- var e = t[Symbol.toPrimitive];
34
- if (void 0 !== e) {
35
- var i = e.call(t, r || "default");
36
- if ("object" != _typeof(i)) return i;
37
- throw new TypeError("@@toPrimitive must return a primitive value.");
38
- }
39
- return ("string" === r ? String : Number)(t);
40
- }
41
-
42
- //#endregion
43
- //#region \0@oxc-project+runtime@0.99.0/helpers/toPropertyKey.js
44
- function toPropertyKey(t) {
45
- var i = toPrimitive(t, "string");
46
- return "symbol" == _typeof(i) ? i : i + "";
47
- }
48
-
49
- //#endregion
50
- //#region \0@oxc-project+runtime@0.99.0/helpers/defineProperty.js
51
- function _defineProperty(e, r, t) {
52
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
53
- value: t,
54
- enumerable: !0,
55
- configurable: !0,
56
- writable: !0
57
- }) : e[r] = t, e;
58
- }
59
-
60
- //#endregion
61
- //#region src/strategy/BaseWalletStrategy.ts
62
- const getInitialWallet = (args) => {
63
- if (args.wallet) return args.wallet;
64
- const keys = Object.keys(args.strategies || {});
65
- if (keys.length === 0) return Wallet.Metamask;
66
- if (keys.includes(Wallet.Metamask) && args.evmOptions) return Wallet.Metamask;
67
- if (keys.includes(Wallet.Keplr) && !args.evmOptions) return Wallet.Keplr;
68
- return keys[0];
69
- };
70
- var BaseWalletStrategy = class {
71
- constructor(args) {
72
- _defineProperty(this, "strategies", void 0);
73
- _defineProperty(this, "wallet", void 0);
74
- _defineProperty(this, "args", void 0);
75
- _defineProperty(this, "metadata", void 0);
76
- _defineProperty(this, "wallets", void 0);
77
- _defineProperty(this, "emitter", void 0);
78
- _defineProperty(this, "on", void 0);
79
- _defineProperty(this, "off", void 0);
80
- _defineProperty(this, "emit", void 0);
81
- this.args = args;
82
- this.strategies = args.strategies;
83
- this.wallet = getInitialWallet(args);
84
- this.metadata = args.metadata;
85
- this.emitter = new EventEmitter();
86
- this.on = this.emitter.on.bind(this.emitter);
87
- this.off = this.emitter.off.bind(this.emitter);
88
- this.emit = this.emitter.emit.bind(this.emitter);
89
- }
90
- /**
91
- * Get the emitter instance.
92
- * Used to pass to strategies so they can emit events directly.
93
- */
94
- getEmitter() {
95
- return this.emitter;
96
- }
97
- getWallet() {
98
- return this.wallet;
99
- }
100
- async setWallet(wallet) {
101
- var _strategy$initStrateg;
102
- this.wallet = wallet;
103
- const strategy = this.getStrategy();
104
- await (strategy === null || strategy === void 0 || (_strategy$initStrateg = strategy.initStrategy) === null || _strategy$initStrateg === void 0 ? void 0 : _strategy$initStrateg.call(strategy));
105
- }
106
- setMetadata(metadata) {
107
- var _this$getStrategy$set, _this$getStrategy;
108
- this.metadata = metadata;
109
- (_this$getStrategy$set = (_this$getStrategy = this.getStrategy()).setMetadata) === null || _this$getStrategy$set === void 0 || _this$getStrategy$set.call(_this$getStrategy, metadata);
110
- }
111
- getStrategy() {
112
- if (!this.strategies[this.wallet]) throw new GeneralException(/* @__PURE__ */ new Error(`Wallet ${this.wallet} is not enabled/available!`));
113
- return this.strategies[this.wallet];
114
- }
115
- getAddresses(args) {
116
- return this.getStrategy().getAddresses(args);
117
- }
118
- getAddressesInfo(args) {
119
- return this.getStrategy().getAddressesInfo(args);
120
- }
121
- getWalletDeviceType() {
122
- return this.getStrategy().getWalletDeviceType();
123
- }
124
- getPubKey(address) {
125
- return this.getStrategy().getPubKey(address);
126
- }
127
- enable(args) {
128
- return this.getStrategy().enable(args);
129
- }
130
- async enableAndGetAddresses(args) {
131
- await this.getStrategy().enable(args);
132
- return this.getStrategy().getAddresses(args);
133
- }
134
- getEthereumChainId() {
135
- return this.getStrategy().getEthereumChainId();
136
- }
137
- async getEvmTransactionReceipt(txHash, evmChainId) {
138
- return this.getStrategy().getEvmTransactionReceipt(txHash, evmChainId);
139
- }
140
- async getSessionOrConfirm(address) {
141
- return this.getStrategy().getSessionOrConfirm(address);
142
- }
143
- async getWalletClient() {
144
- var _this$getStrategy2;
145
- if ((_this$getStrategy2 = this.getStrategy()) === null || _this$getStrategy2 === void 0 ? void 0 : _this$getStrategy2.getWalletClient) {
146
- var _this$getStrategy3, _this$getStrategy3$ge;
147
- 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);
148
- if (result) return result;
149
- }
150
- throw new WalletException(/* @__PURE__ */ new Error("Wallet client not found. Please check your wallet strategy."));
151
- }
152
- async sendTransaction(tx, options) {
153
- return this.getStrategy().sendTransaction(tx, options);
154
- }
155
- async sendEvmTransaction(tx, options) {
156
- return this.getStrategy().sendEvmTransaction(tx, options);
157
- }
158
- async signEip712TypedData(eip712TypedData, address, options = {}) {
159
- if (isCosmosWallet(this.wallet)) throw new WalletException(/* @__PURE__ */ new Error(`You can't sign Ethereum Transaction using ${this.wallet}`));
160
- /** Phantom wallet needs enabling before signing */
161
- if (this.wallet === Wallet.Phantom) await this.enable();
162
- this.emit(WalletStrategyEmitterEventType.TransactionSignStart);
163
- const response = await this.getStrategy().signEip712TypedData(eip712TypedData, address, options);
164
- this.emit(WalletStrategyEmitterEventType.TransactionSigned);
165
- return response;
166
- }
167
- async signAminoCosmosTransaction(transaction) {
168
- if (isEvmWallet(this.wallet)) throw new WalletException(/* @__PURE__ */ new Error(`You can't sign Cosmos Transaction using ${this.wallet}`));
169
- this.emit(WalletStrategyEmitterEventType.TransactionSignStart);
170
- const response = await this.getStrategy().signAminoCosmosTransaction(transaction);
171
- this.emit(WalletStrategyEmitterEventType.TransactionSigned);
172
- return response;
173
- }
174
- async signCosmosTransaction(transaction) {
175
- if (isEvmWallet(this.wallet)) throw new WalletException(/* @__PURE__ */ new Error(`You can't sign Cosmos Transaction using ${this.wallet}`));
176
- this.emit(WalletStrategyEmitterEventType.TransactionSignStart);
177
- const response = await this.getStrategy().signCosmosTransaction(transaction);
178
- this.emit(WalletStrategyEmitterEventType.TransactionSigned);
179
- return response;
180
- }
181
- async signArbitrary(signer, data) {
182
- if (this.getStrategy().signArbitrary) {
183
- this.emit(WalletStrategyEmitterEventType.TransactionSignStart);
184
- const response = await this.getStrategy().signArbitrary(signer, data);
185
- this.emit(WalletStrategyEmitterEventType.TransactionSigned);
186
- return response;
187
- }
188
- }
189
- async onAccountChange(callback) {
190
- if (this.getStrategy().onAccountChange) return this.getStrategy().onAccountChange(callback);
191
- }
192
- async onChainIdChange(callback) {
193
- if (this.getStrategy().onChainIdChange) return this.getStrategy().onChainIdChange(callback);
194
- }
195
- async disconnect() {
196
- if (this.getStrategy().disconnect) {
197
- await this.getStrategy().disconnect();
198
- this.emit(WalletStrategyEmitterEventType.WalletStrategyDisconnect);
199
- }
200
- }
201
- getCosmosWallet(chainId) {
202
- const strategy = this.getStrategy();
203
- if (strategy.getCosmosWallet == void 0) throw new WalletException(/* @__PURE__ */ new Error(`This method is not available for ${this.getWallet()} wallet`));
204
- return strategy.getCosmosWallet(chainId);
205
- }
206
- async getEip1193Provider() {
207
- if (this.getStrategy().getEip1193Provider) return this.getStrategy().getEip1193Provider();
208
- throw new WalletException(/* @__PURE__ */ new Error("EIP1193 provider not found. Please check your wallet strategy."));
209
- }
210
- async getOfflineSigner(chainId) {
211
- if (this.getStrategy().getOfflineSigner) return this.getStrategy().getOfflineSigner(chainId);
212
- throw new WalletException(/* @__PURE__ */ new Error("Offline signer not found. Please check your wallet strategy."));
213
- }
214
- };
215
-
216
- //#endregion
217
- //#region src/broadcaster/MsgBroadcaster.ts
218
- const getEthereumWalletPubKey = async ({ pubKey, eip712TypedData, signature }) => {
219
- if (pubKey) return pubKey;
220
- return hexToBase64(await recoverTypedSignaturePubKey(eip712TypedData, signature));
221
- };
222
- const defaultRetriesConfig = () => ({ [`${TransactionChainErrorModule.CosmosSdk}-${ChainCosmosErrorCode.ErrMempoolIsFull}`]: {
223
- retries: 0,
224
- maxRetries: 10,
225
- timeout: 1e3
226
- } });
227
- /**
228
- * This class is used to broadcast transactions
229
- * using the WalletStrategy as a handler
230
- * for the sign/broadcast flow of the transactions
231
- *
232
- * Mainly used for building UI products
233
- */
234
- var MsgBroadcaster = class {
235
- constructor(options) {
236
- _defineProperty(this, "options", void 0);
237
- _defineProperty(this, "walletStrategy", void 0);
238
- _defineProperty(this, "endpoints", void 0);
239
- _defineProperty(this, "chainId", void 0);
240
- _defineProperty(this, "txTimeout", DEFAULT_BLOCK_TIMEOUT_HEIGHT);
241
- _defineProperty(this, "simulateTx", true);
242
- _defineProperty(this, "txTimeoutOnFeeDelegation", false);
243
- _defineProperty(this, "evmChainId", void 0);
244
- _defineProperty(this, "gasBufferCoefficient", 1.2);
245
- _defineProperty(this, "retriesOnError", defaultRetriesConfig());
246
- _defineProperty(this, "httpHeaders", void 0);
247
- _defineProperty(this, "txInclusion", void 0);
248
- const networkInfo = getNetworkInfo(options.network);
249
- this.options = options;
250
- this.simulateTx = options.simulateTx !== void 0 ? options.simulateTx : true;
251
- this.txTimeout = options.txTimeout || DEFAULT_BLOCK_TIMEOUT_HEIGHT;
252
- this.txTimeoutOnFeeDelegation = options.txTimeoutOnFeeDelegation !== void 0 ? options.txTimeoutOnFeeDelegation : true;
253
- this.gasBufferCoefficient = options.gasBufferCoefficient || 1.2;
254
- this.chainId = options.chainId || networkInfo.chainId;
255
- this.evmChainId = options.evmChainId || networkInfo.evmChainId;
256
- this.endpoints = options.endpoints || getNetworkEndpoints(options.network);
257
- this.walletStrategy = options.walletStrategy;
258
- this.httpHeaders = options.httpHeaders;
259
- this.txInclusion = options.txInclusion;
260
- }
261
- setOptions(options) {
262
- this.simulateTx = options.simulateTx || this.simulateTx;
263
- this.txTimeout = options.txTimeout || this.txTimeout;
264
- this.txTimeoutOnFeeDelegation = options.txTimeoutOnFeeDelegation || this.txTimeoutOnFeeDelegation;
265
- this.txInclusion = options.txInclusion || this.txInclusion;
266
- }
267
- async getEvmChainId() {
268
- const { walletStrategy } = this;
269
- if (!isEvmBrowserWallet(walletStrategy.wallet)) return this.evmChainId;
270
- const mainnetEvmIds = [EvmChainId.Mainnet, EvmChainId.MainnetEvm];
271
- const testnetEvmIds = [EvmChainId.Sepolia, EvmChainId.TestnetEvm];
272
- const devnetEvmIds = [
273
- EvmChainId.Sepolia,
274
- EvmChainId.DevnetEvm,
275
- EvmChainId.MainnetEvm,
276
- EvmChainId.TestnetEvm
277
- ];
278
- try {
279
- const chainId = await walletStrategy.getEthereumChainId();
280
- if (!chainId) return this.evmChainId;
281
- const evmChainId = parseInt(chainId, 16);
282
- if (isNaN(evmChainId)) return this.evmChainId;
283
- if (isMainnet(this.options.network) && !mainnetEvmIds.includes(evmChainId) || isTestnet(this.options.network) && !testnetEvmIds.includes(evmChainId) || !isMainnet(this.options.network) && !isTestnet(this.options.network) && !devnetEvmIds.includes(evmChainId)) throw new WalletException(/* @__PURE__ */ new Error("Your selected network is incorrect"));
284
- return evmChainId;
285
- } catch (e) {
286
- throw new WalletException(e);
287
- }
288
- }
289
- /**
290
- * Broadcasting the transaction using the client
291
- * side approach for both cosmos and ethereum native wallets
292
- *
293
- * @param tx
294
- * @returns {string} transaction hash
295
- */
296
- async broadcast(tx) {
297
- const { walletStrategy } = this;
298
- const txWithAddresses = {
299
- ...tx,
300
- ethereumAddress: getEthereumSignerAddress(tx.injectiveAddress),
301
- injectiveAddress: getInjectiveSignerAddress(tx.injectiveAddress)
302
- };
303
- if (ofacList.includes(txWithAddresses.ethereumAddress)) throw new GeneralException(/* @__PURE__ */ new Error("You cannot execute this transaction"));
304
- try {
305
- return isCosmosWallet(walletStrategy.wallet) ? await this.broadcastDirectSign(txWithAddresses) : isEip712V2OnlyWallet(walletStrategy.wallet) ? await this.broadcastEip712V2(txWithAddresses) : await this.broadcastEip712(txWithAddresses);
306
- } catch (e) {
307
- const error = e;
308
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionFail);
309
- if (isThrownException(error)) throw error;
310
- throw new TransactionException(new Error(error));
311
- }
312
- }
313
- /**
314
- * Broadcasting the transaction using the client
315
- * side approach for both cosmos and ethereum native wallets
316
- * Note: using EIP712_V2 for Ethereum wallets
317
- *
318
- * @param tx
319
- * @returns {string} transaction hash
320
- */
321
- async broadcastV2(tx) {
322
- const { walletStrategy } = this;
323
- const txWithAddresses = {
324
- ...tx,
325
- ethereumAddress: getEthereumSignerAddress(tx.injectiveAddress),
326
- injectiveAddress: getInjectiveSignerAddress(tx.injectiveAddress)
327
- };
328
- if (ofacList.includes(txWithAddresses.ethereumAddress)) throw new GeneralException(/* @__PURE__ */ new Error("You cannot execute this transaction"));
329
- try {
330
- return isCosmosWallet(walletStrategy.wallet) ? await this.broadcastDirectSign(txWithAddresses) : await this.broadcastEip712V2(txWithAddresses);
331
- } catch (e) {
332
- const error = e;
333
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionFail);
334
- if (isThrownException(error)) throw error;
335
- throw new TransactionException(new Error(error));
336
- }
337
- }
338
- /**
339
- * Broadcasting the transaction using the feeDelegation
340
- * support approach for both cosmos and ethereum native wallets
341
- *
342
- * @param tx
343
- * @returns {string} transaction hash
344
- */
345
- async broadcastWithFeeDelegation(tx) {
346
- const { walletStrategy } = this;
347
- const txWithAddresses = {
348
- ...tx,
349
- ethereumAddress: getEthereumSignerAddress(tx.injectiveAddress),
350
- injectiveAddress: getInjectiveSignerAddress(tx.injectiveAddress)
351
- };
352
- if (ofacList.includes(txWithAddresses.ethereumAddress)) throw new GeneralException(/* @__PURE__ */ new Error("You cannot execute this transaction"));
353
- try {
354
- return isCosmosWallet(walletStrategy.wallet) ? await this.broadcastDirectSignWithFeeDelegation(txWithAddresses) : await this.broadcastEip712WithFeeDelegation(txWithAddresses);
355
- } catch (e) {
356
- const error = e;
357
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionFail);
358
- if (isThrownException(error)) throw error;
359
- throw new TransactionException(new Error(error));
360
- }
361
- }
362
- /**
363
- * Sign and broadcast a pre-built transaction whose fee payer signature
364
- * is already provided (e.g. from the RFQ executor / web3-gw `prepare`
365
- * endpoint). The taker is signed locally with the supplied private key.
366
- *
367
- * Autosign-only: the caller passes the autosign private key directly
368
- * (e.g. `sharedWalletStore.autoSign.privateKey`). We don't go through
369
- * `walletStrategy.signCosmosTransaction` because the PK strategy stubs
370
- * that out — and going through the wallet strategy would defeat the
371
- * point of autosign (no popups).
372
- *
373
- * @param tx Base64-encoded or raw `TxRaw` bytes returned by the prepare endpoint
374
- * @param feePayerSig Hex (`0x...`) or base64 fee payer signature
375
- * @param accountNumber Account number of the taker
376
- * @param privateKey Taker (autosign) private key — hex, with or without `0x`
377
- * @returns transaction response with txHash
378
- */
379
- async broadcastWithFeePayerSig({ tx, privateKey, feePayerSig, accountNumber, txInclusion, txTimeoutInBlocks: txTimeoutInBlocksParam }) {
380
- const { chainId, endpoints, walletStrategy } = this;
381
- const txTimeoutInBlocks = this.resolveTimeoutInBlocks(txTimeoutInBlocksParam);
382
- const pk = PrivateKey.fromHex(privateKey);
383
- if (ofacList.includes(pk.toHex().toLowerCase())) throw new GeneralException(/* @__PURE__ */ new Error("You cannot execute this transaction"));
384
- const txBytes = typeof tx === "string" ? base64ToUint8Array(tx) : tx;
385
- const txRaw = CosmosTxV1Beta1TxPb.TxRaw.fromBinary(txBytes);
386
- try {
387
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationStart);
388
- const signDoc = CosmosTxV1Beta1TxPb.SignDoc.create({
389
- chainId,
390
- bodyBytes: txRaw.bodyBytes,
391
- authInfoBytes: txRaw.authInfoBytes,
392
- accountNumber: BigInt(accountNumber)
393
- });
394
- const signDocBytes = CosmosTxV1Beta1TxPb.SignDoc.toBinary(signDoc);
395
- const takerSig = await pk.sign(signDocBytes);
396
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationEnd);
397
- txRaw.signatures = [takerSig, feePayerSig.startsWith("0x") ? hexToUint8Array(feePayerSig.slice(2)) : base64ToUint8Array(feePayerSig)];
398
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastStart);
399
- const txInclusionOptions = this.resolveTxInclusionOptions({ txInclusion });
400
- const txResponse = await new TxGrpcApi(endpoints.grpc).broadcast(txRaw, {
401
- txTimeout: txTimeoutInBlocks,
402
- ...txInclusionOptions,
403
- onBroadcast: () => {
404
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastSynced);
405
- }
406
- });
407
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastEnd);
408
- if (txResponse.code !== 0) throw new TransactionException(/* @__PURE__ */ new Error(`Transaction failed - ${txResponse.rawLog} - ${txResponse.txHash}`), {
409
- code: UnspecifiedErrorCode,
410
- contextCode: txResponse.code,
411
- contextModule: txResponse.codespace
412
- });
413
- return txResponse;
414
- } catch (e) {
415
- const error = e;
416
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionFail);
417
- if (isThrownException(error)) throw error;
418
- throw new TransactionException(new Error(error));
419
- }
420
- }
421
- /**
422
- * Prepare/sign/broadcast transaction using
423
- * Ethereum native wallets on the client side.
424
- *
425
- * Note: Gas estimation not available
426
- *
427
- * @param tx The transaction that needs to be broadcasted
428
- * @returns transaction hash
429
- */
430
- async broadcastEip712(tx) {
431
- var _tx$gas, _baseAccount$pubKey;
432
- const { chainId, endpoints, walletStrategy } = this;
433
- const txTimeoutInBlocks = this.resolveTimeoutInBlocks(tx.txTimeoutInBlocks);
434
- const msgs = Array.isArray(tx.msgs) ? tx.msgs : [tx.msgs];
435
- const [evmChainId, { baseAccount, latestHeight }] = await Promise.all([this.getEvmChainId(), this.fetchAccountAndBlockDetails(tx.injectiveAddress, tx.accountDetails)]);
436
- if (!evmChainId) throw new GeneralException(/* @__PURE__ */ new Error("Please provide evmChainId"));
437
- const timeoutHeight = toBigNumber(latestHeight.toString()).plus(txTimeoutInBlocks);
438
- const txTimeoutTimeInSeconds = txTimeoutInBlocks * DEFAULT_BLOCK_TIME_IN_SECONDS;
439
- const txTimeoutTimeInMilliSeconds = txTimeoutTimeInSeconds * 1e3;
440
- const gas = (((_tx$gas = tx.gas) === null || _tx$gas === void 0 ? void 0 : _tx$gas.gas) || getGasPriceBasedOnMessage(msgs)).toString();
441
- let stdFee = getStdFee({
442
- ...tx.gas,
443
- gas
444
- });
445
- /**
446
- * Account has not been created on chain
447
- * and we cannot simulate the transaction
448
- * to estimate the gas
449
- **/
450
- if (!baseAccount.pubKey) stdFee = await this.getStdFeeWithDynamicBaseFee(stdFee);
451
- else {
452
- const { stdFee: simulatedStdFee } = await this.getTxWithSignersAndStdFee({
453
- chainId,
454
- signMode: SIGN_EIP712,
455
- memo: tx.memo,
456
- message: msgs,
457
- timeoutHeight: timeoutHeight.toNumber(),
458
- signers: {
459
- pubKey: baseAccount.pubKey.key,
460
- accountNumber: baseAccount.accountNumber,
461
- sequence: baseAccount.sequence
462
- },
463
- fee: stdFee
464
- });
465
- stdFee = simulatedStdFee;
466
- }
467
- /** EIP712 for signing on Ethereum wallets */
468
- const eip712TypedData = getEip712TypedData({
469
- msgs,
470
- fee: stdFee,
471
- tx: {
472
- memo: tx.memo,
473
- accountNumber: baseAccount.accountNumber.toString(),
474
- sequence: baseAccount.sequence.toString(),
475
- timeoutHeight: timeoutHeight.toFixed(),
476
- chainId
477
- },
478
- evmChainId
479
- });
480
- /** Signing on Ethereum */
481
- const signature = await walletStrategy.signEip712TypedData(safeBigIntStringify(eip712TypedData), tx.ethereumAddress, { txTimeout: txTimeoutTimeInSeconds });
482
- const pubKeyOrSignatureDerivedPubKey = await getEthereumWalletPubKey({
483
- pubKey: (_baseAccount$pubKey = baseAccount.pubKey) === null || _baseAccount$pubKey === void 0 ? void 0 : _baseAccount$pubKey.key,
484
- eip712TypedData,
485
- signature
486
- });
487
- /** Preparing the transaction for client broadcasting */
488
- const { txRaw } = createTransaction({
489
- message: msgs,
490
- memo: tx.memo,
491
- signMode: SIGN_EIP712,
492
- fee: stdFee,
493
- pubKey: pubKeyOrSignatureDerivedPubKey,
494
- sequence: baseAccount.sequence,
495
- timeoutHeight: timeoutHeight.toNumber(),
496
- accountNumber: baseAccount.accountNumber,
497
- chainId
498
- });
499
- const txRawEip712 = createTxRawEIP712(txRaw, createWeb3Extension({ evmChainId }));
500
- /** Append Signatures */
501
- txRawEip712.signatures = [hexToBuff(signature)];
502
- const inclusionWaiter = await this.prepareTxInclusionWaiter({
503
- tx,
504
- txRawOrSignResponse: txRawEip712,
505
- timeout: txTimeoutTimeInMilliSeconds
506
- });
507
- let response;
508
- try {
509
- response = await walletStrategy.sendTransaction(txRawEip712, {
510
- chainId,
511
- endpoints,
512
- txTimeout: txTimeoutInBlocks,
513
- address: tx.injectiveAddress
514
- });
515
- } catch (e) {
516
- inclusionWaiter.close();
517
- throw e;
518
- }
519
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastSynced);
520
- const confirmedTx = await this.waitForPreparedTxInclusion({
521
- tx,
522
- inclusionWaiter,
523
- responseTxHash: response.txHash,
524
- timeout: txTimeoutTimeInMilliSeconds
525
- });
526
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastEnd);
527
- return confirmedTx;
528
- }
529
- /**
530
- * Prepare/sign/broadcast transaction using
531
- * Ethereum native wallets on the client side.
532
- *
533
- * Note: Gas estimation not available
534
- *
535
- * @param tx The transaction that needs to be broadcasted
536
- * @returns transaction hash
537
- */
538
- async broadcastEip712V2(tx) {
539
- var _tx$gas2, _baseAccount$pubKey2;
540
- const { chainId, endpoints, walletStrategy } = this;
541
- const txTimeoutInBlocks = this.resolveTimeoutInBlocks(tx.txTimeoutInBlocks);
542
- const msgs = Array.isArray(tx.msgs) ? tx.msgs : [tx.msgs];
543
- const [evmChainId, { baseAccount, latestHeight }] = await Promise.all([this.getEvmChainId(), this.fetchAccountAndBlockDetails(tx.injectiveAddress, tx.accountDetails)]);
544
- if (!evmChainId) throw new GeneralException(/* @__PURE__ */ new Error("Please provide evmChainId"));
545
- const timeoutHeight = toBigNumber(latestHeight).plus(txTimeoutInBlocks);
546
- const txTimeoutTimeInSeconds = txTimeoutInBlocks * DEFAULT_BLOCK_TIME_IN_SECONDS;
547
- const txTimeoutTimeInMilliSeconds = txTimeoutTimeInSeconds * 1e3;
548
- const gas = (((_tx$gas2 = tx.gas) === null || _tx$gas2 === void 0 ? void 0 : _tx$gas2.gas) || getGasPriceBasedOnMessage(msgs)).toString();
549
- let stdFee = getStdFee({
550
- ...tx.gas,
551
- gas
552
- });
553
- /**
554
- * Account has not been created on chain
555
- * and we cannot simulate the transaction
556
- * to estimate the gas
557
- **/
558
- if (!baseAccount.pubKey) stdFee = await this.getStdFeeWithDynamicBaseFee(stdFee);
559
- else {
560
- const { stdFee: simulatedStdFee } = await this.getTxWithSignersAndStdFee({
561
- chainId,
562
- signMode: SIGN_EIP712_V2,
563
- memo: tx.memo,
564
- message: msgs,
565
- timeoutHeight: timeoutHeight.toNumber(),
566
- signers: {
567
- pubKey: baseAccount.pubKey.key,
568
- sequence: baseAccount.sequence,
569
- accountNumber: baseAccount.accountNumber
570
- },
571
- fee: stdFee
572
- });
573
- stdFee = simulatedStdFee;
574
- }
575
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationStart);
576
- /** EIP712 for signing on Ethereum wallets */
577
- const eip712TypedData = getEip712TypedDataV2({
578
- msgs,
579
- fee: stdFee,
580
- tx: {
581
- memo: tx.memo,
582
- accountNumber: baseAccount.accountNumber.toString(),
583
- sequence: baseAccount.sequence.toString(),
584
- timeoutHeight: timeoutHeight.toFixed(),
585
- chainId
586
- },
587
- evmChainId
588
- });
589
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationEnd);
590
- /** Signing on Ethereum */
591
- const signature = await walletStrategy.signEip712TypedData(safeBigIntStringify(eip712TypedData), tx.ethereumAddress, { txTimeout: txTimeoutTimeInSeconds });
592
- const pubKeyOrSignatureDerivedPubKey = await getEthereumWalletPubKey({
593
- pubKey: (_baseAccount$pubKey2 = baseAccount.pubKey) === null || _baseAccount$pubKey2 === void 0 ? void 0 : _baseAccount$pubKey2.key,
594
- eip712TypedData,
595
- signature
596
- });
597
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastStart);
598
- const { txRaw } = createTransaction({
599
- message: msgs,
600
- memo: tx.memo,
601
- signMode: SIGN_EIP712_V2,
602
- fee: stdFee,
603
- pubKey: pubKeyOrSignatureDerivedPubKey,
604
- sequence: baseAccount.sequence,
605
- timeoutHeight: timeoutHeight.toNumber(),
606
- accountNumber: baseAccount.accountNumber,
607
- chainId
608
- });
609
- const txRawEip712 = createTxRawEIP712(txRaw, createWeb3Extension({ evmChainId }));
610
- /** Append Signatures */
611
- txRawEip712.signatures = [hexToBuff(signature)];
612
- const inclusionWaiter = await this.prepareTxInclusionWaiter({
613
- tx,
614
- timeout: txTimeoutTimeInMilliSeconds,
615
- txRawOrSignResponse: txRawEip712
616
- });
617
- let response;
618
- try {
619
- response = await walletStrategy.sendTransaction(txRawEip712, {
620
- chainId,
621
- endpoints,
622
- txTimeout: txTimeoutInBlocks,
623
- address: tx.injectiveAddress
624
- });
625
- } catch (e) {
626
- inclusionWaiter.close();
627
- throw e;
628
- }
629
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastSynced);
630
- const confirmedTx = await this.waitForPreparedTxInclusion({
631
- tx,
632
- inclusionWaiter,
633
- responseTxHash: response.txHash,
634
- timeout: txTimeoutTimeInMilliSeconds
635
- });
636
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastEnd);
637
- return confirmedTx;
638
- }
639
- /**
640
- * Prepare/sign/broadcast transaction using
641
- * Ethereum native wallets using the Web3Gateway.
642
- *
643
- * @param tx The transaction that needs to be broadcasted
644
- * @returns transaction hash
645
- */
646
- async broadcastEip712WithFeeDelegation(tx) {
647
- const { endpoints, simulateTx, httpHeaders, walletStrategy, txTimeoutOnFeeDelegation } = this;
648
- const txTimeoutInBlocks = this.resolveTimeoutInBlocks(tx.txTimeoutInBlocks);
649
- const msgs = Array.isArray(tx.msgs) ? tx.msgs : [tx.msgs];
650
- const web3Msgs = msgs.map((msg) => msg.toWeb3());
651
- const evmChainId = await this.getEvmChainId();
652
- if (!evmChainId) throw new GeneralException(/* @__PURE__ */ new Error("Please provide evmChainId"));
653
- const transactionApi = new IndexerGrpcWeb3GwApi(endpoints.web3gw || endpoints.indexer);
654
- if (httpHeaders) transactionApi.setMetadata(httpHeaders);
655
- const txTimeoutTimeInSeconds = txTimeoutInBlocks * DEFAULT_BLOCK_TIME_IN_SECONDS;
656
- const txTimeoutTimeInMilliSeconds = txTimeoutTimeInSeconds * 1e3;
657
- let timeoutHeight = void 0;
658
- if (txTimeoutOnFeeDelegation) timeoutHeight = toBigNumber((await new ChainGrpcTendermintApi(endpoints.grpc).fetchLatestBlock()).header.height.toString()).plus(txTimeoutInBlocks).toNumber();
659
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationStart);
660
- const prepareTxResponse = await transactionApi.prepareTxRequest({
661
- timeoutHeight,
662
- memo: tx.memo,
663
- message: web3Msgs,
664
- address: tx.ethereumAddress,
665
- chainId: evmChainId,
666
- gasLimit: getGasPriceBasedOnMessage(msgs),
667
- estimateGas: simulateTx
668
- });
669
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationEnd);
670
- const signature = await walletStrategy.signEip712TypedData(prepareTxResponse.data, tx.ethereumAddress, { txTimeout: txTimeoutTimeInSeconds });
671
- const broadcast = async () => await transactionApi.broadcastTxRequest({
672
- signature,
673
- message: web3Msgs,
674
- txResponse: prepareTxResponse,
675
- chainId: evmChainId
676
- });
677
- try {
678
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastStart);
679
- const response = await broadcast();
680
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastSynced);
681
- const confirmedTx = await this.waitForTxInclusion({
682
- tx,
683
- txHash: response.txHash,
684
- timeout: txTimeoutTimeInMilliSeconds
685
- });
686
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastEnd);
687
- return confirmedTx;
688
- } catch (e) {
689
- const error = e;
690
- if (isThrownException(error)) {
691
- const exception = error;
692
- /**
693
- * First MsgExec transaction with a PrivateKey wallet
694
- * always runs out of gas for some reason, temporary solution
695
- * to just broadcast the transaction twice
696
- **/
697
- if (walletStrategy.wallet === Wallet.PrivateKey && checkIfTxRunOutOfGas(exception)) {
698
- const { baseAccount } = await new ChainGrpcAuthApi(endpoints.grpc).fetchAccount(tx.injectiveAddress);
699
- /** We only do it on the first account tx fail */
700
- if (baseAccount.sequence > 1) throw e;
701
- return await this.broadcastEip712WithFeeDelegation(tx);
702
- }
703
- return await this.retryOnException(exception, broadcast);
704
- }
705
- throw e;
706
- }
707
- }
708
- /**
709
- * Prepare/sign/broadcast transaction using
710
- * Cosmos native wallets on the client side.
711
- *
712
- * @param tx The transaction that needs to be broadcasted
713
- * @returns transaction hash
714
- */
715
- async broadcastDirectSign(tx) {
716
- var _tx$gas3;
717
- const { chainId, endpoints, walletStrategy } = this;
718
- const txTimeoutInBlocks = this.resolveTimeoutInBlocks(tx.txTimeoutInBlocks);
719
- const msgs = Array.isArray(tx.msgs) ? tx.msgs : [tx.msgs];
720
- /**
721
- * When using Ledger with Keplr/Leap we have
722
- * to send EIP712 to sign on Keplr/Leap
723
- */
724
- if ([Wallet.Keplr, Wallet.Leap].includes(walletStrategy.getWallet())) {
725
- if (await walletStrategy.getWalletDeviceType() === WalletDeviceType.Hardware) return this.experimentalBroadcastWalletThroughLedger(tx);
726
- }
727
- const [{ baseAccount, latestHeight }, pubKey] = await Promise.all([this.fetchAccountAndBlockDetails(tx.injectiveAddress, tx.accountDetails), walletStrategy.getPubKey(tx.injectiveAddress)]);
728
- const timeoutHeight = toBigNumber(latestHeight).plus(txTimeoutInBlocks);
729
- const txTimeoutTimeInMilliSeconds = txTimeoutInBlocks * DEFAULT_BLOCK_TIME_IN_SECONDS * 1e3;
730
- const signMode = isCosmosAminoOnlyWallet(walletStrategy.wallet) ? SIGN_EIP712 : SIGN_DIRECT;
731
- const gas = (((_tx$gas3 = tx.gas) === null || _tx$gas3 === void 0 ? void 0 : _tx$gas3.gas) || getGasPriceBasedOnMessage(msgs)).toString();
732
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationStart);
733
- /** Prepare the Transaction * */
734
- const { txRaw } = await this.getTxWithSignersAndStdFee({
735
- chainId,
736
- signMode,
737
- memo: tx.memo,
738
- message: msgs,
739
- timeoutHeight: timeoutHeight.toNumber(),
740
- signers: {
741
- pubKey,
742
- accountNumber: baseAccount.accountNumber,
743
- sequence: baseAccount.sequence
744
- },
745
- fee: getStdFee({
746
- ...tx.gas,
747
- gas
748
- })
749
- });
750
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationEnd);
751
- /** Ledger using Cosmos app only allows signing amino docs */
752
- if (isCosmosAminoOnlyWallet(walletStrategy.wallet)) {
753
- var _tx$gas4;
754
- const aminoSignDoc = getAminoStdSignDoc({
755
- ...tx,
756
- ...baseAccount,
757
- msgs,
758
- chainId,
759
- 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()),
760
- timeoutHeight: timeoutHeight.toFixed()
761
- });
762
- txRaw.signatures = [base64ToUint8Array((await walletStrategy.signAminoCosmosTransaction({
763
- signDoc: aminoSignDoc,
764
- address: tx.injectiveAddress
765
- })).signature.signature)];
766
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastStart);
767
- const inclusionWaiter$1 = await this.prepareTxInclusionWaiter({
768
- tx,
769
- txRawOrSignResponse: txRaw,
770
- timeout: txTimeoutTimeInMilliSeconds
771
- });
772
- let response$1;
773
- try {
774
- response$1 = await walletStrategy.sendTransaction(txRaw, {
775
- chainId,
776
- endpoints,
777
- address: tx.injectiveAddress,
778
- txTimeout: txTimeoutInBlocks
779
- });
780
- } catch (e) {
781
- inclusionWaiter$1.close();
782
- throw e;
783
- }
784
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastSynced);
785
- const confirmedTx$1 = await this.waitForPreparedTxInclusion({
786
- tx,
787
- inclusionWaiter: inclusionWaiter$1,
788
- timeout: txTimeoutTimeInMilliSeconds,
789
- responseTxHash: response$1.txHash
790
- });
791
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastEnd);
792
- return confirmedTx$1;
793
- }
794
- const directSignResponse = await walletStrategy.signCosmosTransaction({
795
- txRaw,
796
- chainId,
797
- address: tx.injectiveAddress,
798
- accountNumber: baseAccount.accountNumber
799
- });
800
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastStart);
801
- const inclusionWaiter = await this.prepareTxInclusionWaiter({
802
- tx,
803
- timeout: txTimeoutTimeInMilliSeconds,
804
- txRawOrSignResponse: directSignResponse
805
- });
806
- let response;
807
- try {
808
- response = await walletStrategy.sendTransaction(directSignResponse, {
809
- chainId,
810
- endpoints,
811
- txTimeout: txTimeoutInBlocks,
812
- address: tx.injectiveAddress
813
- });
814
- } catch (e) {
815
- inclusionWaiter.close();
816
- throw e;
817
- }
818
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastSynced);
819
- const confirmedTx = await this.waitForPreparedTxInclusion({
820
- tx,
821
- inclusionWaiter,
822
- responseTxHash: response.txHash,
823
- timeout: txTimeoutTimeInMilliSeconds
824
- });
825
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastEnd);
826
- return confirmedTx;
827
- }
828
- /**
829
- * We use this method only when we want to broadcast a transaction using Ledger on Keplr/Leap for Injective
830
- *
831
- * Note: Gas estimation not available
832
- * @param tx the transaction that needs to be broadcasted
833
- */
834
- async experimentalBroadcastWalletThroughLedger(tx) {
835
- var _tx$gas5, _tx$gas6;
836
- const { chainId, endpoints, evmChainId, simulateTx, walletStrategy } = this;
837
- const txTimeoutInBlocks = this.resolveTimeoutInBlocks(tx.txTimeoutInBlocks);
838
- const msgs = Array.isArray(tx.msgs) ? tx.msgs : [tx.msgs];
839
- /**
840
- * We can only use this method
841
- * when Ledger is connected through Keplr
842
- */
843
- if ([Wallet.Keplr, Wallet.Leap].includes(walletStrategy.getWallet())) {
844
- if (!(await walletStrategy.getWalletDeviceType() === WalletDeviceType.Hardware)) throw new GeneralException(/* @__PURE__ */ new Error(`This method can only be used when Ledger is connected through ${walletStrategy.getWallet()}`));
845
- }
846
- if (!evmChainId) throw new GeneralException(/* @__PURE__ */ new Error("Please provide evmChainId"));
847
- const cosmosWallet = walletStrategy.getCosmosWallet(chainId);
848
- const [{ baseAccount, latestHeight }, pubKey] = await Promise.all([this.fetchAccountAndBlockDetails(tx.injectiveAddress, tx.accountDetails), walletStrategy.getPubKey()]);
849
- const timeoutHeight = toBigNumber(latestHeight).plus(txTimeoutInBlocks);
850
- const gas = (((_tx$gas5 = tx.gas) === null || _tx$gas5 === void 0 ? void 0 : _tx$gas5.gas) || getGasPriceBasedOnMessage(msgs)).toString();
851
- /** EIP712 for signing on Ethereum wallets */
852
- const eip712TypedData = getEip712TypedData({
853
- msgs,
854
- fee: await this.getStdFeeWithDynamicBaseFee({
855
- ...tx.gas,
856
- gas
857
- }),
858
- tx: {
859
- chainId,
860
- memo: tx.memo,
861
- timeoutHeight: timeoutHeight.toFixed(),
862
- sequence: baseAccount.sequence.toString(),
863
- accountNumber: baseAccount.accountNumber.toString()
864
- },
865
- evmChainId
866
- });
867
- const aminoSignResponse = await cosmosWallet.signEIP712CosmosTx({
868
- eip712: eip712TypedData,
869
- signDoc: createEip712StdSignDoc({
870
- ...tx,
871
- ...baseAccount,
872
- msgs,
873
- chainId,
874
- 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()),
875
- timeoutHeight: timeoutHeight.toFixed()
876
- })
877
- });
878
- /**
879
- * Create TxRaw from the signed tx that we
880
- * get as a response in case the user changed the fee/memo
881
- * on the Keplr popup
882
- */
883
- const { txRaw } = createTransaction({
884
- pubKey,
885
- chainId,
886
- message: msgs,
887
- signMode: SIGN_EIP712,
888
- memo: aminoSignResponse.signed.memo,
889
- fee: aminoSignResponse.signed.fee,
890
- sequence: parseInt(aminoSignResponse.signed.sequence, 10),
891
- accountNumber: parseInt(aminoSignResponse.signed.account_number, 10),
892
- timeoutHeight: parseInt(aminoSignResponse.signed.timeout_height, 10)
893
- });
894
- const txRawEip712 = createTxRawEIP712(txRaw, createWeb3Extension({ evmChainId }));
895
- if (simulateTx) await this.simulateTxRaw(txRawEip712);
896
- txRawEip712.signatures = [base64ToUint8Array(aminoSignResponse.signature.signature)];
897
- /** Broadcast the transaction */
898
- const response = await new TxGrpcApi(endpoints.grpc).broadcast(txRawEip712, {
899
- txTimeout: txTimeoutInBlocks,
900
- ...this.resolveTxInclusionOptions(tx),
901
- onBroadcast: () => {
902
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastSynced);
903
- }
904
- });
905
- if (response.code !== 0) throw new TransactionException(new Error(response.rawLog), {
906
- code: UnspecifiedErrorCode,
907
- contextCode: response.code,
908
- contextModule: response.codespace
909
- });
910
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastEnd);
911
- return response;
912
- }
913
- /**
914
- * Prepare/sign/broadcast transaction using
915
- * Cosmos native wallets using the Web3Gateway.
916
- *
917
- * @param tx The transaction that needs to be broadcasted
918
- * @returns transaction hash
919
- */
920
- async broadcastDirectSignWithFeeDelegation(tx) {
921
- var _tx$gas7;
922
- const { options, chainId, endpoints, simulateTx, httpHeaders, walletStrategy, txTimeoutOnFeeDelegation } = this;
923
- const txTimeoutInBlocks = this.resolveTimeoutInBlocks(tx.txTimeoutInBlocks);
924
- const msgs = Array.isArray(tx.msgs) ? tx.msgs : [tx.msgs];
925
- /**
926
- * We can only use this method when Keplr is connected
927
- * with ledger
928
- */
929
- if (walletStrategy.getWallet() === Wallet.Keplr) {
930
- if (await walletStrategy.getWalletDeviceType() === WalletDeviceType.Hardware) throw new GeneralException(/* @__PURE__ */ new Error("Keplr + Ledger is not available with fee delegation. Connect with Ledger directly."));
931
- }
932
- const cosmosWallet = walletStrategy.getCosmosWallet(chainId);
933
- const canDisableCosmosGasCheck = [Wallet.Keplr, Wallet.OWallet].includes(walletStrategy.wallet);
934
- const feePayerPubKey = await this.fetchFeePayerPubKey(options.feePayerPubKey);
935
- const feePayerPublicKey = PublicKey.fromBase64(feePayerPubKey);
936
- const feePayer = feePayerPublicKey.toAddress().address;
937
- const transactionApi = new IndexerGrpcWeb3GwApi(endpoints.web3gw || endpoints.indexer);
938
- if (httpHeaders) transactionApi.setMetadata(httpHeaders);
939
- const fetchAccountBlockDetails = async () => {
940
- try {
941
- const { baseAccount: baseAccount$1, latestHeight: latestHeight$1 } = await this.fetchAccountAndBlockDetails(tx.injectiveAddress, tx.accountDetails);
942
- return {
943
- baseAccount: baseAccount$1,
944
- latestHeight: latestHeight$1
945
- };
946
- } catch (e) {
947
- const error = e;
948
- if (isThrownException(error) && error.message.toLowerCase().includes(`account ${tx.injectiveAddress} not found`)) {
949
- await transactionApi.prepareCosmosTxRequest({
950
- address: tx.injectiveAddress,
951
- message: msgs.map((msg) => msg.toWeb3Gw()),
952
- memo: tx.memo,
953
- estimateGas: simulateTx
954
- });
955
- const { baseAccount: baseAccount$1, latestHeight: latestHeight$1 } = await this.fetchAccountAndBlockDetails(tx.injectiveAddress);
956
- return {
957
- baseAccount: baseAccount$1,
958
- latestHeight: latestHeight$1
959
- };
960
- }
961
- throw e;
962
- }
963
- };
964
- /** Account Details * */
965
- const { baseAccount, latestHeight } = await fetchAccountBlockDetails();
966
- const chainGrpcAuthApi = new ChainGrpcAuthApi(endpoints.grpc);
967
- if (httpHeaders) chainGrpcAuthApi.setMetadata(httpHeaders);
968
- const { baseAccount: feePayerBaseAccount } = await chainGrpcAuthApi.fetchAccount(feePayer);
969
- const timeoutHeight = toBigNumber(latestHeight).plus(txTimeoutOnFeeDelegation ? txTimeoutInBlocks : DEFAULT_BLOCK_TIMEOUT_HEIGHT);
970
- const txTimeoutTimeInMilliSeconds = txTimeoutInBlocks * DEFAULT_BLOCK_TIME_IN_SECONDS * 1e3;
971
- const pubKey = await walletStrategy.getPubKey();
972
- const gas = (((_tx$gas7 = tx.gas) === null || _tx$gas7 === void 0 ? void 0 : _tx$gas7.gas) || getGasPriceBasedOnMessage(msgs)).toString();
973
- /** Prepare the Transaction * */
974
- const { txRaw } = await this.getTxWithSignersAndStdFee({
975
- chainId,
976
- memo: tx.memo,
977
- message: msgs,
978
- timeoutHeight: timeoutHeight.toNumber(),
979
- signers: [{
980
- pubKey,
981
- accountNumber: baseAccount.accountNumber,
982
- sequence: baseAccount.sequence
983
- }, {
984
- pubKey: feePayerPublicKey.toBase64(),
985
- accountNumber: feePayerBaseAccount.accountNumber,
986
- sequence: feePayerBaseAccount.sequence
987
- }],
988
- fee: getStdFee({
989
- ...tx.gas,
990
- gas,
991
- payer: feePayer
992
- })
993
- });
994
- if (canDisableCosmosGasCheck && cosmosWallet.disableGasCheck) cosmosWallet.disableGasCheck(chainId);
995
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationStart);
996
- const directSignResponse = await walletStrategy.signCosmosTransaction({
997
- txRaw,
998
- chainId,
999
- address: tx.injectiveAddress,
1000
- accountNumber: baseAccount.accountNumber
1001
- });
1002
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionPreparationEnd);
1003
- const signedTxRaw = createTxRawFromSigResponse(directSignResponse);
1004
- const broadcast = async () => await transactionApi.broadcastCosmosTxRequest({
1005
- txRaw: signedTxRaw,
1006
- address: tx.injectiveAddress,
1007
- signature: directSignResponse.signature.signature,
1008
- pubKey: directSignResponse.signature.pub_key || {
1009
- value: pubKey,
1010
- type: "/injective.crypto.v1beta1.ethsecp256k1.PubKey"
1011
- }
1012
- });
1013
- try {
1014
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastStart);
1015
- const inclusionWaiter = await this.prepareTxInclusionWaiter({
1016
- tx,
1017
- txRawOrSignResponse: signedTxRaw,
1018
- timeout: txTimeoutTimeInMilliSeconds
1019
- });
1020
- let response;
1021
- try {
1022
- response = await broadcast();
1023
- } catch (e) {
1024
- inclusionWaiter.close();
1025
- throw e;
1026
- }
1027
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastSynced);
1028
- if (canDisableCosmosGasCheck && cosmosWallet.enableGasCheck) cosmosWallet.enableGasCheck(chainId);
1029
- const confirmedTx = await this.waitForPreparedTxInclusion({
1030
- tx,
1031
- inclusionWaiter,
1032
- responseTxHash: response.txHash,
1033
- timeout: txTimeoutTimeInMilliSeconds
1034
- });
1035
- walletStrategy.emit(WalletStrategyEmitterEventType.TransactionBroadcastEnd);
1036
- return confirmedTx;
1037
- } catch (e) {
1038
- const error = e;
1039
- if (isThrownException(error)) {
1040
- const exception = error;
1041
- return await this.retryOnException(exception, broadcast);
1042
- }
1043
- throw e;
1044
- }
1045
- }
1046
- /**
1047
- * Fetch the fee payer's pub key from the web3 gateway
1048
- *
1049
- * Returns a base64 version of it
1050
- */
1051
- async fetchFeePayerPubKey(existingFeePayerPubKey) {
1052
- if (existingFeePayerPubKey) return existingFeePayerPubKey;
1053
- const { endpoints, httpHeaders } = this;
1054
- const transactionApi = new IndexerGrpcWeb3GwApi(endpoints.web3gw || endpoints.indexer);
1055
- if (httpHeaders) transactionApi.setMetadata(httpHeaders);
1056
- const response = await transactionApi.fetchFeePayer();
1057
- if (!response.feePayerPubKey) throw new GeneralException(/* @__PURE__ */ new Error("Please provide a feePayerPubKey"));
1058
- if (response.feePayerPubKey.key.startsWith("0x") || response.feePayerPubKey.key.length === 66) return uint8ArrayToBase64(hexToUint8Array(response.feePayerPubKey.key));
1059
- return response.feePayerPubKey.key;
1060
- }
1061
- async getStdFeeWithDynamicBaseFee(args) {
1062
- const client = new ChainGrpcTxFeesApi(this.endpoints.grpc);
1063
- let baseFee = DEFAULT_GAS_PRICE;
1064
- try {
1065
- const response = await client.fetchEipBaseFee();
1066
- baseFee = Number((response === null || response === void 0 ? void 0 : response.baseFee) || DEFAULT_GAS_PRICE);
1067
- } catch (_unused) {}
1068
- if (!args) return getStdFee(baseFee ? { gasPrice: baseFee } : {});
1069
- if (typeof args === "string") return getStdFee({
1070
- ...baseFee && { gasPrice: toBigNumber(baseFee).toFixed() },
1071
- gas: args
1072
- });
1073
- return getStdFee({
1074
- ...args,
1075
- ...baseFee && { gasPrice: toBigNumber(baseFee).toFixed() }
1076
- });
1077
- }
1078
- /**
1079
- * In case we don't want to simulate the transaction
1080
- * we get the gas limit based on the message type.
1081
- *
1082
- * If we want to simulate the transaction we set the
1083
- * gas limit based on the simulation and add a small multiplier
1084
- * to be safe (factor of 1.2 as default)
1085
- */
1086
- async getTxWithSignersAndStdFee(args) {
1087
- var _result$gasInfo;
1088
- const { simulateTx } = this;
1089
- if (!simulateTx) return {
1090
- ...createTransactionWithSigners(args),
1091
- stdFee: await this.getStdFeeWithDynamicBaseFee(args.fee)
1092
- };
1093
- const result = await this.simulateTxWithSigners(args);
1094
- if (!((_result$gasInfo = result.gasInfo) === null || _result$gasInfo === void 0 ? void 0 : _result$gasInfo.gasUsed)) return {
1095
- ...createTransactionWithSigners(args),
1096
- stdFee: await this.getStdFeeWithDynamicBaseFee(args.fee)
1097
- };
1098
- const stdGasFee = { ...await this.getStdFeeWithDynamicBaseFee({
1099
- ...getStdFee(args.fee),
1100
- gas: toBigNumber(result.gasInfo.gasUsed).times(this.gasBufferCoefficient).toFixed()
1101
- }) };
1102
- return {
1103
- ...createTransactionWithSigners({
1104
- ...args,
1105
- fee: stdGasFee
1106
- }),
1107
- stdFee: stdGasFee
1108
- };
1109
- }
1110
- /**
1111
- * Create TxRaw and simulate it
1112
- */
1113
- async simulateTxRaw(txRaw) {
1114
- const { endpoints, httpHeaders } = this;
1115
- txRaw.signatures = [new Uint8Array(0)];
1116
- const client = new TxGrpcApi(endpoints.grpc);
1117
- if (httpHeaders) client.setMetadata(httpHeaders);
1118
- return await client.simulate(txRaw);
1119
- }
1120
- /**
1121
- * Create TxRaw and simulate it
1122
- */
1123
- async simulateTxWithSigners(args) {
1124
- const { endpoints, httpHeaders } = this;
1125
- const { txRaw } = createTransactionWithSigners(args);
1126
- txRaw.signatures = Array(Array.isArray(args.signers) ? args.signers.length : 1).fill(new Uint8Array(0));
1127
- const client = new TxGrpcApi(endpoints.grpc);
1128
- if (httpHeaders) client.setMetadata(httpHeaders);
1129
- return await client.simulate(txRaw);
1130
- }
1131
- async retryOnException(exception, retryLogic) {
1132
- const errorsToRetry = Object.keys(this.retriesOnError);
1133
- const errorKey = `${exception.contextModule}-${exception.contextCode}`;
1134
- if (!errorsToRetry.includes(errorKey)) throw exception;
1135
- const retryConfig = this.retriesOnError[errorKey];
1136
- if (retryConfig.retries >= retryConfig.maxRetries) {
1137
- this.retriesOnError = defaultRetriesConfig();
1138
- throw exception;
1139
- }
1140
- await sleep(retryConfig.timeout);
1141
- try {
1142
- retryConfig.retries += 1;
1143
- return await retryLogic();
1144
- } catch (e) {
1145
- const error = e;
1146
- if (isThrownException(error)) return this.retryOnException(error, retryLogic);
1147
- throw e;
1148
- }
1149
- }
1150
- async fetchAccountAndBlockDetails(address, existingAccountDetails) {
1151
- const { endpoints, httpHeaders } = this;
1152
- const tendermintClient = new ChainGrpcTendermintApi(endpoints.grpc);
1153
- if (httpHeaders) tendermintClient.setMetadata(httpHeaders);
1154
- if (existingAccountDetails) return {
1155
- baseAccount: existingAccountDetails,
1156
- latestHeight: (await tendermintClient.fetchLatestBlock()).header.height.toString()
1157
- };
1158
- const chainClient = new ChainGrpcAuthApi(endpoints.grpc);
1159
- if (httpHeaders) chainClient.setMetadata(httpHeaders);
1160
- const [accountDetails, latestBlock] = await Promise.all([chainClient.fetchAccount(address), tendermintClient.fetchLatestBlock()]);
1161
- const { baseAccount } = accountDetails;
1162
- return {
1163
- baseAccount,
1164
- latestHeight: latestBlock.header.height.toString()
1165
- };
1166
- }
1167
- resolveTimeoutInBlocks(override) {
1168
- return typeof override === "number" && Number.isInteger(override) && override > 0 ? override : this.txTimeout;
1169
- }
1170
- resolveTxInclusionOptions(tx) {
1171
- var _txInclusion$eventInc;
1172
- const txInclusion = (tx === null || tx === void 0 ? void 0 : tx.txInclusion) || this.txInclusion;
1173
- if (!txInclusion) return;
1174
- return {
1175
- ...txInclusion,
1176
- eventInclusion: {
1177
- ...txInclusion.eventInclusion,
1178
- rpcEndpoint: ((_txInclusion$eventInc = txInclusion.eventInclusion) === null || _txInclusion$eventInc === void 0 ? void 0 : _txInclusion$eventInc.rpcEndpoint) || this.endpoints.rpc
1179
- }
1180
- };
1181
- }
1182
- createTxGrpcApi() {
1183
- const client = new TxGrpcApi(this.endpoints.grpc);
1184
- if (this.httpHeaders) client.setMetadata(this.httpHeaders);
1185
- return client;
1186
- }
1187
- async waitForTxInclusion({ tx, txHash, timeout }) {
1188
- return this.createTxGrpcApi().waitForTxInclusion({
1189
- txHash,
1190
- timeout,
1191
- options: this.resolveTxInclusionOptions(tx)
1192
- });
1193
- }
1194
- async prepareTxInclusionWaiter({ tx, timeout, txRawOrSignResponse }) {
1195
- const txRaw = createTxRawFromSigResponse(txRawOrSignResponse);
1196
- const txHash = TxClient.hash(txRaw);
1197
- return this.createTxGrpcApi().prepareTxInclusionWait({
1198
- txHash,
1199
- timeout,
1200
- options: this.resolveTxInclusionOptions(tx)
1201
- });
1202
- }
1203
- async waitForPreparedTxInclusion({ tx, timeout, responseTxHash, inclusionWaiter }) {
1204
- if (!inclusionWaiter) return this.waitForTxInclusion({
1205
- tx,
1206
- timeout,
1207
- txHash: responseTxHash
1208
- });
1209
- const confirmedTx = await inclusionWaiter.wait(responseTxHash);
1210
- if (!confirmedTx) throw new TransactionException(/* @__PURE__ */ new Error(`The transaction with ${responseTxHash} is not found`));
1211
- return confirmedTx;
1212
- }
1213
- };
1214
-
1215
- //#endregion
1216
- //#region src/broadcaster/Web3Broadcaster.ts
1217
- /**
1218
- * Preparing and broadcasting
1219
- * Ethereum transactions
1220
- */
1221
- var Web3Broadcaster = class {
1222
- constructor({ walletStrategy, evmChainId }) {
1223
- _defineProperty(this, "walletStrategy", void 0);
1224
- _defineProperty(this, "evmChainId", void 0);
1225
- this.evmChainId = evmChainId;
1226
- this.walletStrategy = walletStrategy;
1227
- }
1228
- async sendTransaction(args) {
1229
- const { evmChainId, walletStrategy } = this;
1230
- try {
1231
- const chainId = args.evmChainId || evmChainId;
1232
- const txHash = await walletStrategy.sendEvmTransaction(args.tx, {
1233
- evmChainId: chainId,
1234
- address: args.address
1235
- });
1236
- await walletStrategy.getEvmTransactionReceipt(txHash, chainId);
1237
- return txHash;
1238
- } catch (e) {
1239
- throw new Web3Exception(new Error(e.message));
1240
- }
1241
- }
1242
- };
1243
-
1244
- //#endregion
1245
5
  export { BaseWalletStrategy, MsgBroadcaster, Web3Broadcaster, checkIfTxRunOutOfGas };