@manifest-network/manifest-mcp-core 0.10.0 → 0.11.0

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 (94) hide show
  1. package/dist/__test-utils__/mocks.d.ts +8 -8
  2. package/dist/__test-utils__/mocks.d.ts.map +1 -1
  3. package/dist/client.d.ts +29 -3
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/client.js +44 -10
  6. package/dist/client.js.map +1 -1
  7. package/dist/config.js +2 -2
  8. package/dist/config.js.map +1 -1
  9. package/dist/cosmos.js +15 -15
  10. package/dist/cosmos.js.map +1 -1
  11. package/dist/env-utils.d.ts +31 -0
  12. package/dist/env-utils.d.ts.map +1 -0
  13. package/dist/env-utils.js +53 -0
  14. package/dist/env-utils.js.map +1 -0
  15. package/dist/index.d.ts +3 -1
  16. package/dist/index.js +3 -1
  17. package/dist/internals/guarded-fetch.d.ts +138 -0
  18. package/dist/internals/guarded-fetch.d.ts.map +1 -0
  19. package/dist/internals/guarded-fetch.js +242 -0
  20. package/dist/internals/guarded-fetch.js.map +1 -0
  21. package/dist/lcd-adapter.js +7 -7
  22. package/dist/lcd-adapter.js.map +1 -1
  23. package/dist/modules.js +6 -6
  24. package/dist/modules.js.map +1 -1
  25. package/dist/queries/auth.js +2 -2
  26. package/dist/queries/auth.js.map +1 -1
  27. package/dist/queries/authz.js +2 -2
  28. package/dist/queries/authz.js.map +1 -1
  29. package/dist/queries/bank.js.map +1 -1
  30. package/dist/queries/billing.js +2 -2
  31. package/dist/queries/billing.js.map +1 -1
  32. package/dist/queries/distribution.js.map +1 -1
  33. package/dist/queries/feegrant.js.map +1 -1
  34. package/dist/queries/gov.js.map +1 -1
  35. package/dist/queries/group.js.map +1 -1
  36. package/dist/queries/ibc-transfer.js.map +1 -1
  37. package/dist/queries/mint.js.map +1 -1
  38. package/dist/queries/poa.js.map +1 -1
  39. package/dist/queries/sku.js.map +1 -1
  40. package/dist/queries/staking.js.map +1 -1
  41. package/dist/queries/tokenfactory.js.map +1 -1
  42. package/dist/queries/utils.js +6 -6
  43. package/dist/queries/utils.js.map +1 -1
  44. package/dist/queries/wasm.js +4 -4
  45. package/dist/queries/wasm.js.map +1 -1
  46. package/dist/retry.d.ts.map +1 -1
  47. package/dist/retry.js +11 -10
  48. package/dist/retry.js.map +1 -1
  49. package/dist/server-utils.js +6 -6
  50. package/dist/server-utils.js.map +1 -1
  51. package/dist/tool-metadata.js.map +1 -1
  52. package/dist/tools/fundCredits.js.map +1 -1
  53. package/dist/tools/setItemCustomDomain.js +3 -3
  54. package/dist/tools/setItemCustomDomain.js.map +1 -1
  55. package/dist/transactions/authz.js +6 -6
  56. package/dist/transactions/authz.js.map +1 -1
  57. package/dist/transactions/bank.js.map +1 -1
  58. package/dist/transactions/billing.js +12 -12
  59. package/dist/transactions/billing.js.map +1 -1
  60. package/dist/transactions/distribution.js.map +1 -1
  61. package/dist/transactions/feegrant.js.map +1 -1
  62. package/dist/transactions/gov.js +4 -4
  63. package/dist/transactions/gov.js.map +1 -1
  64. package/dist/transactions/group.js +8 -8
  65. package/dist/transactions/group.js.map +1 -1
  66. package/dist/transactions/ibc-transfer.js +6 -6
  67. package/dist/transactions/ibc-transfer.js.map +1 -1
  68. package/dist/transactions/json-schemas.js +5 -8
  69. package/dist/transactions/json-schemas.js.map +1 -1
  70. package/dist/transactions/manifest.js.map +1 -1
  71. package/dist/transactions/poa.js +2 -2
  72. package/dist/transactions/poa.js.map +1 -1
  73. package/dist/transactions/sku.js +3 -3
  74. package/dist/transactions/sku.js.map +1 -1
  75. package/dist/transactions/staking.js.map +1 -1
  76. package/dist/transactions/tokenfactory.js.map +1 -1
  77. package/dist/transactions/utils.js +24 -24
  78. package/dist/transactions/utils.js.map +1 -1
  79. package/dist/transactions/wasm.js +4 -4
  80. package/dist/transactions/wasm.js.map +1 -1
  81. package/dist/types.d.ts +2 -1
  82. package/dist/types.d.ts.map +1 -1
  83. package/dist/types.js +1 -0
  84. package/dist/types.js.map +1 -1
  85. package/dist/validation.js +6 -6
  86. package/dist/validation.js.map +1 -1
  87. package/dist/version.d.ts +1 -1
  88. package/dist/version.js +1 -1
  89. package/dist/version.js.map +1 -1
  90. package/dist/wallet/mnemonic.js +9 -9
  91. package/dist/wallet/mnemonic.js.map +1 -1
  92. package/dist/wallet/sign-arbitrary.js +2 -2
  93. package/dist/wallet/sign-arbitrary.js.map +1 -1
  94. package/package.json +5 -5
@@ -1,8 +1,8 @@
1
1
  import { ManifestMCPConfig, WalletProvider } from "../types.js";
2
2
  import { ManifestQueryClient } from "../client.js";
3
3
  import { LeaseState } from "@manifest-network/manifestjs/dist/codegen/liftedinit/billing/v1/types.js";
4
- import * as vitest from "vitest";
5
- import * as _vitest_spy0 from "@vitest/spy";
4
+ import * as _$vitest from "vitest";
5
+ import * as _$_vitest_spy0 from "@vitest/spy";
6
6
 
7
7
  //#region src/__test-utils__/mocks.d.ts
8
8
  /**
@@ -122,12 +122,12 @@ declare function makeMockClientManager(overrides?: {
122
122
  address?: string;
123
123
  config?: ManifestMCPConfig;
124
124
  }): {
125
- getQueryClient: vitest.Mock<_vitest_spy0.Procedure>;
126
- getSigningClient: vitest.Mock<_vitest_spy0.Procedure>;
127
- getAddress: vitest.Mock<_vitest_spy0.Procedure>;
128
- getConfig: vitest.Mock<_vitest_spy0.Procedure>;
129
- acquireRateLimit: vitest.Mock<_vitest_spy0.Procedure>;
130
- disconnect: vitest.Mock<_vitest_spy0.Procedure>;
125
+ getQueryClient: _$vitest.Mock<_$_vitest_spy0.Procedure>;
126
+ getSigningClient: _$vitest.Mock<_$_vitest_spy0.Procedure>;
127
+ getAddress: _$vitest.Mock<_$_vitest_spy0.Procedure>;
128
+ getConfig: _$vitest.Mock<_$_vitest_spy0.Procedure>;
129
+ acquireRateLimit: _$vitest.Mock<_$_vitest_spy0.Procedure>;
130
+ disconnect: _$vitest.Mock<_$_vitest_spy0.Procedure>;
131
131
  };
132
132
  //#endregion
133
133
  export { makeMockClientManager, makeMockConfig, makeMockQueryClient, makeMockWallet };
@@ -1 +1 @@
1
- {"version":3,"file":"mocks.d.ts","names":[],"sources":["../../src/__test-utils__/mocks.ts"],"mappings":";;;;;;;;;;iBAYgB,cAAA,CACd,SAAA,GAAY,OAAA,CAAQ,iBAAA,IACnB,iBAAA;AAFH;;;;AAAA,iBAgBgB,cAAA,CAAe,IAAA;EAC7B,aAAA;AAAA,IACE,cAAA;;;;UAiBM,gBAAA;EACR,QAAA;IAAa,KAAA;IAAe,MAAA;EAAA;EAC5B,aAAA;IACE,gBAAA;IACA,iBAAA;IACA,eAAA;MAAmB,KAAA;MAAe,MAAA;IAAA;EAAA;EAEpC,qBAAA;IAA0B,KAAA;IAAe,MAAA;EAAA;EACzC,8BAAA;IAAmC,KAAA;IAAe,MAAA;EAAA;EAClD,cAAA;IACE,cAAA;MAAkB,KAAA;MAAe,MAAA;IAAA;IACjC,kBAAA;MAAsB,KAAA;MAAe,MAAA;IAAA;IACrC,wBAAA;IACA,gBAAA;EAAA;EAEF,KAAA;IACE,IAAA;IACA,KAAA,EAAO,UAAA;IACP,YAAA;IACA,SAAA,GAAY,IAAA;IACZ,QAAA,GAAW,IAAA;EAAA;EAEb,YAAA;IAAiB,IAAA;IAAc,YAAA;IAAsB,SAAA,GAAY,IAAA;EAAA;EACjE,aAAA;IAAkB,IAAA;IAAc,YAAA;IAAsB,SAAA,GAAY,IAAA;EAAA;EAClE,YAAA;IAAiB,IAAA;IAAc,YAAA;IAAsB,SAAA,GAAY,IAAA;EAAA;EACjE,cAAA;IAAmB,IAAA;IAAc,YAAA;IAAsB,SAAA,GAAY,IAAA;EAAA;EACnE,aAAA;IAAkB,IAAA;IAAc,YAAA;IAAsB,SAAA,GAAY,IAAA;EAAA;AAAA;AAAA,UAG1D,YAAA;EACR,SAAA;IACE,IAAA;IACA,OAAA;IACA,MAAA;IACA,MAAA;EAAA;EAEF,IAAA;IACE,IAAA;IACA,IAAA;IACA,YAAA;IACA,SAAA;MAAc,MAAA;M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AAmB,IAAA;IAAc,YAAA;IAAsB,SAAA,GAAY,IAAA;EAAA;EACnE,aAAA;IAAkB,IAAA;IAAc,YAAA;IAAsB,SAAA,GAAY,IAAA;EAAA;AAAA;AAAA,UAG1D,YAAA;EACR,SAAA;IACE,IAAA;IACA,OAAA;IACA,MAAA;IACA,MAAA;EAAA;EAEF,IAAA;IACE,IAAA;IACA,IAAA;IACA,YAAA;IACA,SAAA;MAAc,MAAA;MAAgB,KAAA;IAAA;EAAA;EAEhC,cAAA,GAAiB,MAAA;IAAiB,QAAA;MAAY,MAAA;IAAA;EAAA;AAAA;;;;iBAMhC,mBAAA,CAAoB,SAAA;EAClC,OAAA,GAAU,gBAAA;EACV,GAAA,GAAM,YAAA;AAAA,IA4KU,mBAAA;;;;iBAMF,qBAAA,CAAsB,SAAA;EACpC,WAAA,GAAc,mBAAA;EACd,OAAA;EACA,MAAA,GAAS,iBAAA;AAAA;gCAAiB,cAAA,CAAA,SAAA"}
package/dist/client.d.ts CHANGED
@@ -19,6 +19,7 @@ declare class CosmosClientManager {
19
19
  private queryClient;
20
20
  private signingClient;
21
21
  private rateLimiter;
22
+ private refCount;
22
23
  private queryClientPromise;
23
24
  private signingClientPromise;
24
25
  private constructor();
@@ -28,11 +29,27 @@ declare class CosmosClientManager {
28
29
  * - Config and walletProvider references are always updated
29
30
  * - Signing client is disconnected/recreated if gasPrice, gasMultiplier, or walletProvider changed
30
31
  * - Rate limiter is updated if requestsPerSecond changed (without affecting signing client)
32
+ *
33
+ * Every call acquires a reference (increments refCount). Each caller must
34
+ * balance it with exactly one disconnect() so the shared clients are torn
35
+ * down only once the last holder releases (see disconnect()).
36
+ *
37
+ * Reference accounting counts calls, not distinct callers: a call that only
38
+ * updates config on an existing key (changed gasPrice/gasMultiplier/
39
+ * walletProvider/rate limit) still acquires a reference. A holder that
40
+ * re-invokes getInstance to reconfigure a key it already holds therefore
41
+ * takes an ADDITIONAL reference and must balance it with an additional
42
+ * disconnect(), or refCount never reaches zero and the clients leak. Today
43
+ * every server acquires once at construction and releases once at shutdown,
44
+ * so this caveat only applies to callers that reconfigure a live key in place.
31
45
  */
32
46
  static getInstance(config: ManifestMCPConfig, walletProvider: WalletProvider): CosmosClientManager;
33
47
  /**
34
48
  * Clear all cached instances (useful for testing or reconnection).
35
- * Disconnects signing clients and releases query client references before clearing.
49
+ * Force-tears-down each instance regardless of its refCount clearing the
50
+ * registry is an unconditional reset, so it ignores outstanding holders,
51
+ * disconnects signing clients, releases query client references, and resets
52
+ * refCount to zero before clearing.
36
53
  */
37
54
  static clearInstances(): void;
38
55
  /**
@@ -61,11 +78,20 @@ declare class CosmosClientManager {
61
78
  */
62
79
  acquireRateLimit(): Promise<void>;
63
80
  /**
64
- * Disconnect the signing client and release query client references.
81
+ * Release this holder's reference to the shared instance. The underlying
82
+ * clients are only torn down once the last holder disconnects (refCount
83
+ * reaches zero), so one server's shutdown cannot sever a client still in
84
+ * use by another server sharing the same config key. Calling disconnect()
85
+ * more times than getInstance() was called is safe and never drives the
86
+ * count negative.
87
+ */
88
+ disconnect(): void;
89
+ /**
90
+ * Tear down the signing client and release query client references.
65
91
  * The query client's underlying HTTP transport is stateless and does not
66
92
  * require an explicit disconnect.
67
93
  */
68
- disconnect(): void;
94
+ private teardown;
69
95
  }
70
96
  //#endregion
71
97
  export { CosmosClientManager, ManifestQueryClient };
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","names":[],"sources":["../src/client.ts"],"mappings":";;;;;KA4CK,qBAAA,GAAwB,OAAA,CAC3B,UAAA,QAAkB,UAAA,CAAW,aAAA,CAAc,oBAAA;AAAA,KAExC,mBAAA,GAAsB,OAAA,CACzB,UAAA,QAAkB,QAAA,CAAW,aAAA,CAAc,oBAAA;AAAA,KAExC,8BAAA,GAAiC,OAAA,CACpC,UAAA,QAAkB,oBAAA,CAAsB,aAAA,CAAc,oBAAA;AAAA,KAEnD,kBAAA,GAAqB,OAAA,CACxB,UAAA,QAAkB,OAAA,CAAU,aAAA,CAAc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iB,OAAA,CACpB,UAAA,QAAkB,GAAA,CAAM,aAAA,CAAc,oBAAA;AAAA,KAE5B,mBAAA,GAAsB,qBAAA,GAChC,IAAA,CAAK,mBAAA,gBACL,IAAA,CAAK,8BAAA,4BACL,IAAA,CAAK,kBAAA,eACL,IAAA,CAAK,cAAA;;;;cAiDM,mBAAA;EAAA,eACI,SAAA;EAAA,QAEP,MAAA;EAAA,QACA,cAAA;EAAA,QACA,WAAA;EAAA,QACA,aAAA;EAAA,QACA,WAAA;EAAA,QAMA,QAAA;EAAA,QAGA,kBAAA;EAAA,QACA,oBAAA;EAAA,QAED,WAAA,CAAA;EAnFW;;;;;;;;;;;;AAA6C;;;;;;;;EAA7C,OAuHX,WAAA,CACL,MAAA,EAAQ,iBAAA,EACR,cAAA,EAAgB,cAAA,GACf,mBAAA;EAvHH;;;;;;AAA0E;EAA1E,OA+KO,cAAA,CAAA;;;;;;EAeD,cAAA,CAAA,GAAkB,OAAA,CAAQ,mBAAA;EA5LR;;;;;EAmSlB,gBAAA,CAAA,GAAoB,OAAA,CAAQ,qBAAA;EAlS4B;AAAA;;EAyYxD,UAAA,CAAA,GAAc,OAAA;EAtYF;;;EA6YlB,SAAA,CAAA,GAAa,iBAAA;EA9Yc;;;;EAsZrB,gBAAA,CAAA,GAAoB,OAAA;EArZY;;;AAExC;;;;;EA+ZE,UAAA,CAAA;EA7ZK;;;;;EAAA,QAuaG,QAAA;AAAA"}
package/dist/client.js CHANGED
@@ -1,4 +1,4 @@
1
- import { ManifestMCPError, ManifestMCPErrorCode } from "./types.js";
1
+ import { ManifestMCPError } from "./types.js";
2
2
  import { withRetry } from "./retry.js";
3
3
  import "./config.js";
4
4
  import { logger } from "./logger.js";
@@ -42,12 +42,14 @@ var CosmosClientManager = class CosmosClientManager {
42
42
  constructor(config, walletProvider) {
43
43
  this.queryClient = null;
44
44
  this.signingClient = null;
45
+ this.refCount = 0;
45
46
  this.queryClientPromise = null;
46
47
  this.signingClientPromise = null;
47
48
  this.config = config;
48
49
  this.walletProvider = walletProvider;
50
+ const requestsPerSecond = config.rateLimit?.requestsPerSecond ?? 10;
49
51
  this.rateLimiter = new RateLimiter({
50
- tokensPerInterval: config.rateLimit?.requestsPerSecond ?? 10,
52
+ tokensPerInterval: requestsPerSecond,
51
53
  interval: "second"
52
54
  });
53
55
  }
@@ -57,6 +59,19 @@ var CosmosClientManager = class CosmosClientManager {
57
59
  * - Config and walletProvider references are always updated
58
60
  * - Signing client is disconnected/recreated if gasPrice, gasMultiplier, or walletProvider changed
59
61
  * - Rate limiter is updated if requestsPerSecond changed (without affecting signing client)
62
+ *
63
+ * Every call acquires a reference (increments refCount). Each caller must
64
+ * balance it with exactly one disconnect() so the shared clients are torn
65
+ * down only once the last holder releases (see disconnect()).
66
+ *
67
+ * Reference accounting counts calls, not distinct callers: a call that only
68
+ * updates config on an existing key (changed gasPrice/gasMultiplier/
69
+ * walletProvider/rate limit) still acquires a reference. A holder that
70
+ * re-invokes getInstance to reconfigure a key it already holds therefore
71
+ * takes an ADDITIONAL reference and must balance it with an additional
72
+ * disconnect(), or refCount never reaches zero and the clients leak. Today
73
+ * every server acquires once at construction and releases once at shutdown,
74
+ * so this caveat only applies to callers that reconfigure a live key in place.
60
75
  */
61
76
  static getInstance(config, walletProvider) {
62
77
  const parts = [config.chainId, config.rpcUrl ?? ""];
@@ -86,14 +101,21 @@ var CosmosClientManager = class CosmosClientManager {
86
101
  });
87
102
  }
88
103
  }
104
+ instance.refCount += 1;
89
105
  return instance;
90
106
  }
91
107
  /**
92
108
  * Clear all cached instances (useful for testing or reconnection).
93
- * Disconnects signing clients and releases query client references before clearing.
109
+ * Force-tears-down each instance regardless of its refCount clearing the
110
+ * registry is an unconditional reset, so it ignores outstanding holders,
111
+ * disconnects signing clients, releases query client references, and resets
112
+ * refCount to zero before clearing.
94
113
  */
95
114
  static clearInstances() {
96
- for (const instance of CosmosClientManager.instances.values()) instance.disconnect();
115
+ for (const instance of CosmosClientManager.instances.values()) {
116
+ instance.teardown();
117
+ instance.refCount = 0;
118
+ }
97
119
  CosmosClientManager.instances.clear();
98
120
  }
99
121
  /**
@@ -131,7 +153,7 @@ var CosmosClientManager = class CosmosClientManager {
131
153
  config: this.config.retry,
132
154
  operationName: "connect query client"
133
155
  });
134
- else throw new ManifestMCPError(ManifestMCPErrorCode.INVALID_CONFIG, "Cannot create query client: neither restUrl nor rpcUrl is configured.");
156
+ else throw new ManifestMCPError("INVALID_CONFIG", "Cannot create query client: neither restUrl nor rpcUrl is configured.");
135
157
  if (this.queryClientPromise === thisInitPromise) {
136
158
  this.queryClient = client;
137
159
  this.queryClientPromise = null;
@@ -141,7 +163,7 @@ var CosmosClientManager = class CosmosClientManager {
141
163
  if (this.queryClientPromise === thisInitPromise) this.queryClientPromise = null;
142
164
  if (error instanceof ManifestMCPError) throw error;
143
165
  const endpoint = this.config.restUrl ?? this.config.rpcUrl;
144
- throw new ManifestMCPError(ManifestMCPErrorCode.RPC_CONNECTION_FAILED, `Failed to connect to ${this.config.restUrl ? "REST" : "RPC"} endpoint: ${error instanceof Error ? error.message : String(error)}`, { url: endpoint });
166
+ throw new ManifestMCPError("RPC_CONNECTION_FAILED", `Failed to connect to ${this.config.restUrl ? "REST" : "RPC"} endpoint: ${error instanceof Error ? error.message : String(error)}`, { url: endpoint });
145
167
  }
146
168
  })();
147
169
  return this.queryClientPromise;
@@ -152,7 +174,7 @@ var CosmosClientManager = class CosmosClientManager {
152
174
  * Automatically retries on transient connection failures with exponential backoff.
153
175
  */
154
176
  async getSigningClient() {
155
- if (!this.config.rpcUrl || !this.config.gasPrice) throw new ManifestMCPError(ManifestMCPErrorCode.INVALID_CONFIG, "Signing client requires rpcUrl and gasPrice configuration. Current config is query-only (REST).");
177
+ if (!this.config.rpcUrl || !this.config.gasPrice) throw new ManifestMCPError("INVALID_CONFIG", "Signing client requires rpcUrl and gasPrice configuration. Current config is query-only (REST).");
156
178
  if (this.signingClient) return this.signingClient;
157
179
  if (this.signingClientPromise) return this.signingClientPromise;
158
180
  this.signingClientPromise = (async () => {
@@ -192,7 +214,7 @@ var CosmosClientManager = class CosmosClientManager {
192
214
  } catch (error) {
193
215
  if (this.signingClientPromise === thisInitPromise) this.signingClientPromise = null;
194
216
  if (error instanceof ManifestMCPError) throw error;
195
- throw new ManifestMCPError(ManifestMCPErrorCode.RPC_CONNECTION_FAILED, `Failed to connect signing client: ${error instanceof Error ? error.message : String(error)}`, { rpcUrl: this.config.rpcUrl });
217
+ throw new ManifestMCPError("RPC_CONNECTION_FAILED", `Failed to connect signing client: ${error instanceof Error ? error.message : String(error)}`, { rpcUrl: this.config.rpcUrl });
196
218
  }
197
219
  })();
198
220
  return this.signingClientPromise;
@@ -217,11 +239,23 @@ var CosmosClientManager = class CosmosClientManager {
217
239
  await this.rateLimiter.removeTokens(1);
218
240
  }
219
241
  /**
220
- * Disconnect the signing client and release query client references.
242
+ * Release this holder's reference to the shared instance. The underlying
243
+ * clients are only torn down once the last holder disconnects (refCount
244
+ * reaches zero), so one server's shutdown cannot sever a client still in
245
+ * use by another server sharing the same config key. Calling disconnect()
246
+ * more times than getInstance() was called is safe and never drives the
247
+ * count negative.
248
+ */
249
+ disconnect() {
250
+ if (this.refCount > 0) this.refCount -= 1;
251
+ if (this.refCount === 0) this.teardown();
252
+ }
253
+ /**
254
+ * Tear down the signing client and release query client references.
221
255
  * The query client's underlying HTTP transport is stateless and does not
222
256
  * require an explicit disconnect.
223
257
  */
224
- disconnect() {
258
+ teardown() {
225
259
  if (this.signingClient) {
226
260
  this.signingClient.disconnect();
227
261
  this.signingClient = null;
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":["cosmwasmNs","strangeloveVenturesNs","osmosisNs","ibcNs"],"sources":["../src/client.ts"],"sourcesContent":["import { Registry } from '@cosmjs/proto-signing';\nimport {\n AminoTypes,\n GasPrice,\n type HttpEndpoint,\n SigningStargateClient,\n} from '@cosmjs/stargate';\nimport {\n cosmosAminoConverters,\n cosmosProtoRegistry,\n cosmwasmAminoConverters,\n cosmwasm as cosmwasmNs,\n cosmwasmProtoRegistry,\n ibcAminoConverters,\n ibc as ibcNs,\n ibcProtoRegistry,\n liftedinit,\n liftedinitAminoConverters,\n liftedinitProtoRegistry,\n osmosisAminoConverters,\n osmosis as osmosisNs,\n osmosisProtoRegistry,\n strangeloveVenturesAminoConverters,\n strangelove_ventures as strangeloveVenturesNs,\n strangeloveVenturesProtoRegistry,\n} from '@manifest-network/manifestjs';\nimport { RateLimiter } from 'limiter';\nimport {\n DEFAULT_GAS_MULTIPLIER,\n DEFAULT_REQUESTS_PER_SECOND,\n} from './config.js';\nimport { createLCDQueryClient } from './lcd-adapter.js';\nimport { logger } from './logger.js';\nimport { withRetry } from './retry.js';\nimport {\n type ManifestMCPConfig,\n ManifestMCPError,\n ManifestMCPErrorCode,\n type WalletProvider,\n} from './types.js';\n\n// Combined query client type: liftedinit modules (cosmos + billing/manifest/sku) + cosmwasm\n// + strangelove_ventures (poa) + osmosis (tokenfactory) + ibc (transfer, channel, client, connection).\n// Uses Pick to extract only each factory's unique namespace, avoiding conflicts with overlapping cosmos types.\ntype LiftedinitQueryClient = Awaited<\n ReturnType<typeof liftedinit.ClientFactory.createRPCQueryClient>\n>;\ntype CosmwasmQueryClient = Awaited<\n ReturnType<typeof cosmwasmNs.ClientFactory.createRPCQueryClient>\n>;\ntype StrangeloveVenturesQueryClient = Awaited<\n ReturnType<typeof strangeloveVenturesNs.ClientFactory.createRPCQueryClient>\n>;\ntype OsmosisQueryClient = Awaited<\n ReturnType<typeof osmosisNs.ClientFactory.createRPCQueryClient>\n>;\ntype IbcQueryClient = Awaited<\n ReturnType<typeof ibcNs.ClientFactory.createRPCQueryClient>\n>;\nexport type ManifestQueryClient = LiftedinitQueryClient &\n Pick<CosmwasmQueryClient, 'cosmwasm'> &\n Pick<StrangeloveVenturesQueryClient, 'strangelove_ventures'> &\n Pick<OsmosisQueryClient, 'osmosis'> &\n Pick<IbcQueryClient, 'ibc'>;\n\n/**\n * Extract the registry type expected by SigningStargateClient.connectWithSigner.\n *\n * The Registry type from @cosmjs/proto-signing doesn't perfectly match the registry type\n * in SigningStargateClientOptions due to telescope-generated proto types. This type alias\n * extracts the expected registry type from the function signature to enable type-safe casting.\n */\ntype SigningClientRegistry = Parameters<\n typeof SigningStargateClient.connectWithSigner\n>[2] extends { registry?: infer R }\n ? R\n : never;\n\n/** Default timeout for transaction broadcast (60 seconds) */\nconst DEFAULT_BROADCAST_TIMEOUT_MS = 60_000;\n\n/** Default polling interval for transaction confirmation (3 seconds) */\nconst DEFAULT_BROADCAST_POLL_INTERVAL_MS = 3_000;\n\n/**\n * Get combined signing client options with all Manifest registries\n */\nfunction getSigningManifestClientOptions() {\n const registry = new Registry([\n ...cosmosProtoRegistry,\n ...liftedinitProtoRegistry,\n ...strangeloveVenturesProtoRegistry,\n ...osmosisProtoRegistry,\n ...cosmwasmProtoRegistry,\n ...ibcProtoRegistry,\n ]);\n\n const aminoTypes = new AminoTypes({\n ...cosmosAminoConverters,\n ...liftedinitAminoConverters,\n ...strangeloveVenturesAminoConverters,\n ...osmosisAminoConverters,\n ...cosmwasmAminoConverters,\n ...ibcAminoConverters,\n });\n\n return { registry, aminoTypes };\n}\n\n/**\n * Manages CosmJS client instances with lazy initialization and singleton pattern\n */\nexport class CosmosClientManager {\n private static instances: Map<string, CosmosClientManager> = new Map();\n\n private config: ManifestMCPConfig;\n private walletProvider: WalletProvider;\n private queryClient: ManifestQueryClient | null = null;\n private signingClient: SigningStargateClient | null = null;\n private rateLimiter: RateLimiter;\n\n // Promises to prevent concurrent client initialization (lazy init race condition)\n private queryClientPromise: Promise<ManifestQueryClient> | null = null;\n private signingClientPromise: Promise<SigningStargateClient> | null = null;\n\n private constructor(\n config: ManifestMCPConfig,\n walletProvider: WalletProvider,\n ) {\n this.config = config;\n this.walletProvider = walletProvider;\n\n // Initialize rate limiter with configured or default requests per second\n const requestsPerSecond =\n config.rateLimit?.requestsPerSecond ?? DEFAULT_REQUESTS_PER_SECOND;\n this.rateLimiter = new RateLimiter({\n tokensPerInterval: requestsPerSecond,\n interval: 'second',\n });\n }\n\n /**\n * Get or create a singleton instance for the given config.\n * Instances are keyed by chainId:rpcUrl:restUrl. For existing instances:\n * - Config and walletProvider references are always updated\n * - Signing client is disconnected/recreated if gasPrice, gasMultiplier, or walletProvider changed\n * - Rate limiter is updated if requestsPerSecond changed (without affecting signing client)\n */\n static getInstance(\n config: ManifestMCPConfig,\n walletProvider: WalletProvider,\n ): CosmosClientManager {\n const parts = [config.chainId, config.rpcUrl ?? ''];\n if (config.restUrl) parts.push(config.restUrl);\n const key = parts.join(':');\n let instance = CosmosClientManager.instances.get(key);\n\n if (!instance) {\n instance = new CosmosClientManager(config, walletProvider);\n CosmosClientManager.instances.set(key, instance);\n } else {\n // Check what changed to determine what needs updating\n const signingClientAffected =\n instance.config.gasPrice !== config.gasPrice ||\n instance.config.gasMultiplier !== config.gasMultiplier ||\n instance.walletProvider !== walletProvider;\n\n const rateLimitChanged =\n instance.config.rateLimit?.requestsPerSecond !==\n config.rateLimit?.requestsPerSecond;\n\n // Always update config reference\n instance.config = config;\n instance.walletProvider = walletProvider;\n\n // Only invalidate signing client if fields it depends on changed\n if (signingClientAffected) {\n if (instance.signingClient) {\n instance.signingClient.disconnect();\n instance.signingClient = null;\n }\n // Also clear the promise to allow re-initialization with new config\n instance.signingClientPromise = null;\n }\n\n // Update rate limiter independently (doesn't affect signing client)\n if (rateLimitChanged) {\n const newRps =\n config.rateLimit?.requestsPerSecond ?? DEFAULT_REQUESTS_PER_SECOND;\n instance.rateLimiter = new RateLimiter({\n tokensPerInterval: newRps,\n interval: 'second',\n });\n }\n }\n\n return instance;\n }\n\n /**\n * Clear all cached instances (useful for testing or reconnection).\n * Disconnects signing clients and releases query client references before clearing.\n */\n static clearInstances(): void {\n for (const instance of CosmosClientManager.instances.values()) {\n instance.disconnect();\n }\n CosmosClientManager.instances.clear();\n }\n\n /**\n * Get the manifestjs RPC query client with all module extensions\n *\n * Automatically retries on transient connection failures with exponential backoff.\n */\n async getQueryClient(): Promise<ManifestQueryClient> {\n // Return cached client if available\n if (this.queryClient) {\n return this.queryClient;\n }\n\n // If initialization is already in progress, wait for it\n if (this.queryClientPromise) {\n return this.queryClientPromise;\n }\n\n // Start initialization and cache the promise to prevent concurrent init\n this.queryClientPromise = (async () => {\n // Capture reference to detect if superseded by disconnect/config change\n const thisInitPromise = this.queryClientPromise;\n try {\n let client: ManifestQueryClient;\n if (this.config.restUrl) {\n // Use LCD/REST for queries when restUrl is configured\n client = await withRetry(\n () => createLCDQueryClient(this.config.restUrl!),\n {\n config: this.config.retry,\n operationName: 'connect LCD query client',\n },\n );\n } else if (this.config.rpcUrl) {\n // Use RPC: merge liftedinit + cosmwasm + strangelove_ventures + osmosis + ibc namespaces\n client = await withRetry(\n async () => {\n const [\n liftedinitClient,\n cosmwasmClient,\n strangeloveClient,\n osmosisClient,\n ibcClient,\n ] = await Promise.all([\n liftedinit.ClientFactory.createRPCQueryClient({\n rpcEndpoint: this.config.rpcUrl!,\n }),\n cosmwasmNs.ClientFactory.createRPCQueryClient({\n rpcEndpoint: this.config.rpcUrl!,\n }),\n strangeloveVenturesNs.ClientFactory.createRPCQueryClient({\n rpcEndpoint: this.config.rpcUrl!,\n }),\n osmosisNs.ClientFactory.createRPCQueryClient({\n rpcEndpoint: this.config.rpcUrl!,\n }),\n ibcNs.ClientFactory.createRPCQueryClient({\n rpcEndpoint: this.config.rpcUrl!,\n }),\n ]);\n return {\n ...liftedinitClient,\n cosmwasm: cosmwasmClient.cosmwasm,\n strangelove_ventures: strangeloveClient.strangelove_ventures,\n osmosis: osmosisClient.osmosis,\n ibc: ibcClient.ibc,\n } as ManifestQueryClient;\n },\n {\n config: this.config.retry,\n operationName: 'connect query client',\n },\n );\n } else {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'Cannot create query client: neither restUrl nor rpcUrl is configured.',\n );\n }\n // Only store if this is still the active promise\n if (this.queryClientPromise === thisInitPromise) {\n this.queryClient = client;\n this.queryClientPromise = null;\n }\n return client;\n } catch (error) {\n // Clear promise on failure so retry is possible (only if still active)\n if (this.queryClientPromise === thisInitPromise) {\n this.queryClientPromise = null;\n }\n if (error instanceof ManifestMCPError) {\n throw error;\n }\n const endpoint = this.config.restUrl ?? this.config.rpcUrl;\n throw new ManifestMCPError(\n ManifestMCPErrorCode.RPC_CONNECTION_FAILED,\n `Failed to connect to ${this.config.restUrl ? 'REST' : 'RPC'} endpoint: ${error instanceof Error ? error.message : String(error)}`,\n { url: endpoint },\n );\n }\n })();\n\n return this.queryClientPromise;\n }\n\n /**\n * Get a signing client with all Manifest registries (for transactions)\n *\n * Automatically retries on transient connection failures with exponential backoff.\n */\n async getSigningClient(): Promise<SigningStargateClient> {\n if (!this.config.rpcUrl || !this.config.gasPrice) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'Signing client requires rpcUrl and gasPrice configuration. Current config is query-only (REST).',\n );\n }\n\n // Return cached client if available\n if (this.signingClient) {\n return this.signingClient;\n }\n\n // If initialization is already in progress, wait for it\n if (this.signingClientPromise) {\n return this.signingClientPromise;\n }\n\n // Start initialization and cache the promise to prevent concurrent init\n this.signingClientPromise = (async () => {\n // Capture reference to detect if superseded by disconnect/config change\n const thisInitPromise = this.signingClientPromise;\n try {\n const signer = await this.walletProvider.getSigner();\n const gasPrice = GasPrice.fromString(this.config.gasPrice!);\n const { registry, aminoTypes } = getSigningManifestClientOptions();\n\n // Configure endpoint as HttpEndpoint object (required for custom options)\n const endpoint: HttpEndpoint = {\n url: this.config.rpcUrl!,\n headers: {},\n };\n\n // Note: Registry type from @cosmjs/proto-signing doesn't perfectly match\n // SigningStargateClientOptions due to telescope-generated proto types.\n // This is a known limitation with custom cosmos-sdk module registries.\n // Wrap with retry for transient connection failures\n const client = await withRetry(\n async () => {\n const c = await SigningStargateClient.connectWithSigner(\n endpoint,\n signer,\n {\n registry: registry as SigningClientRegistry,\n aminoTypes,\n gasPrice,\n broadcastTimeoutMs: DEFAULT_BROADCAST_TIMEOUT_MS,\n broadcastPollIntervalMs: DEFAULT_BROADCAST_POLL_INTERVAL_MS,\n },\n );\n // The property is private readonly with no constructor option,\n // so we must bypass TypeScript's access control to override it.\n const record = c as unknown as Record<string, unknown>;\n if (typeof record.defaultGasMultiplier === 'number') {\n record.defaultGasMultiplier =\n this.config.gasMultiplier ?? DEFAULT_GAS_MULTIPLIER;\n } else {\n const effective =\n this.config.gasMultiplier ?? DEFAULT_GAS_MULTIPLIER;\n logger.warn(\n `gasMultiplier ${effective} could not be applied: ` +\n `signing client defaultGasMultiplier is ${typeof record.defaultGasMultiplier}, expected number. ` +\n `Transactions will use the CosmJS built-in gas multiplier instead.`,\n );\n }\n return c;\n },\n {\n config: this.config.retry,\n operationName: 'connect signing client',\n },\n );\n // Only store if this is still the active promise\n if (this.signingClientPromise === thisInitPromise) {\n this.signingClient = client;\n this.signingClientPromise = null;\n } else {\n // Promise was superseded, clean up the client we just created\n client.disconnect();\n }\n return client;\n } catch (error) {\n // Clear promise on failure so retry is possible (only if still active)\n if (this.signingClientPromise === thisInitPromise) {\n this.signingClientPromise = null;\n }\n if (error instanceof ManifestMCPError) {\n throw error;\n }\n throw new ManifestMCPError(\n ManifestMCPErrorCode.RPC_CONNECTION_FAILED,\n `Failed to connect signing client: ${error instanceof Error ? error.message : String(error)}`,\n { rpcUrl: this.config.rpcUrl },\n );\n }\n })();\n\n return this.signingClientPromise;\n }\n\n /**\n * Get the wallet address\n */\n async getAddress(): Promise<string> {\n return this.walletProvider.getAddress();\n }\n\n /**\n * Get the configuration\n */\n getConfig(): ManifestMCPConfig {\n return this.config;\n }\n\n /**\n * Acquire a rate limit token before making an RPC request.\n * This will wait if the rate limit has been exceeded.\n */\n async acquireRateLimit(): Promise<void> {\n await this.rateLimiter.removeTokens(1);\n }\n\n /**\n * Disconnect the signing client and release query client references.\n * The query client's underlying HTTP transport is stateless and does not\n * require an explicit disconnect.\n */\n disconnect(): void {\n if (this.signingClient) {\n this.signingClient.disconnect();\n this.signingClient = null;\n }\n this.signingClientPromise = null;\n this.queryClient = null;\n this.queryClientPromise = null;\n }\n}\n"],"mappings":";;;;;;;;;;;AA+EA,MAAM,+BAA+B;;AAGrC,MAAM,qCAAqC;;;;AAK3C,SAAS,kCAAkC;AAmBzC,QAAO;EAAE,UAlBQ,IAAI,SAAS;GAC5B,GAAG;GACH,GAAG;GACH,GAAG;GACH,GAAG;GACH,GAAG;GACH,GAAG;GACJ,CAAC;EAWiB,YATA,IAAI,WAAW;GAChC,GAAG;GACH,GAAG;GACH,GAAG;GACH,GAAG;GACH,GAAG;GACH,GAAG;GACJ,CAAC;EAE6B;;;;;AAMjC,IAAa,sBAAb,MAAa,oBAAoB;CAa/B,YACE,QACA,gBACA;AAXF,OAAQ,cAA0C;AAClD,OAAQ,gBAA8C;AAItD,OAAQ,qBAA0D;AAClE,OAAQ,uBAA8D;AAMpE,OAAK,SAAS;AACd,OAAK,iBAAiB;AAKtB,OAAK,cAAc,IAAI,YAAY;GACjC,mBAFA,OAAO,WAAW,qBAAA;GAGlB,UAAU;GACX,CAAC;;;;;;;;;CAUJ,OAAO,YACL,QACA,gBACqB;EACrB,MAAM,QAAQ,CAAC,OAAO,SAAS,OAAO,UAAU,GAAG;AACnD,MAAI,OAAO,QAAS,OAAM,KAAK,OAAO,QAAQ;EAC9C,MAAM,MAAM,MAAM,KAAK,IAAI;EAC3B,IAAI,WAAW,oBAAoB,UAAU,IAAI,IAAI;AAErD,MAAI,CAAC,UAAU;AACb,cAAW,IAAI,oBAAoB,QAAQ,eAAe;AAC1D,uBAAoB,UAAU,IAAI,KAAK,SAAS;SAC3C;GAEL,MAAM,wBACJ,SAAS,OAAO,aAAa,OAAO,YACpC,SAAS,OAAO,kBAAkB,OAAO,iBACzC,SAAS,mBAAmB;GAE9B,MAAM,mBACJ,SAAS,OAAO,WAAW,sBAC3B,OAAO,WAAW;AAGpB,YAAS,SAAS;AAClB,YAAS,iBAAi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AA;AACd,aAAO,KACL,iBAAiB,UAAU,gEACiB,OAAO,OAAO,qBAAqB,sFAEhF;;AAEH,YAAO;OAET;KACE,QAAQ,KAAK,OAAO;KACpB,eAAe;KAChB,CACF;AAED,QAAI,KAAK,yBAAyB,iBAAiB;AACjD,UAAK,gBAAgB;AACrB,UAAK,uBAAuB;UAG5B,QAAO,YAAY;AAErB,WAAO;YACA,OAAO;AAEd,QAAI,KAAK,yBAAyB,gBAChC,MAAK,uBAAuB;AAE9B,QAAI,iBAAiB,iBACnB,OAAM;AAER,UAAM,IAAI,iBACR,qBAAqB,uBACrB,qCAAqC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,IAC3F,EAAE,QAAQ,KAAK,OAAO,QAAQ,CAC/B;;MAED;AAEJ,SAAO,KAAK;;;;;CAMd,MAAM,aAA8B;AAClC,SAAO,KAAK,eAAe,YAAY;;;;;CAMzC,YAA+B;AAC7B,SAAO,KAAK;;;;;;CAOd,MAAM,mBAAkC;AACtC,QAAM,KAAK,YAAY,aAAa,EAAE;;;;;;;CAQxC,aAAmB;AACjB,MAAI,KAAK,eAAe;AACtB,QAAK,cAAc,YAAY;AAC/B,QAAK,gBAAgB;;AAEvB,OAAK,uBAAuB;AAC5B,OAAK,cAAc;AACnB,OAAK,qBAAqB;;;AAnV5B,oBAAe,4BAA8C,IAAI,KAAK"}
1
+ {"version":3,"file":"client.js","names":["cosmwasmNs","strangeloveVenturesNs","osmosisNs","ibcNs"],"sources":["../src/client.ts"],"sourcesContent":["import { Registry } from '@cosmjs/proto-signing';\nimport {\n AminoTypes,\n GasPrice,\n type HttpEndpoint,\n SigningStargateClient,\n} from '@cosmjs/stargate';\nimport {\n cosmosAminoConverters,\n cosmosProtoRegistry,\n cosmwasmAminoConverters,\n cosmwasm as cosmwasmNs,\n cosmwasmProtoRegistry,\n ibcAminoConverters,\n ibc as ibcNs,\n ibcProtoRegistry,\n liftedinit,\n liftedinitAminoConverters,\n liftedinitProtoRegistry,\n osmosisAminoConverters,\n osmosis as osmosisNs,\n osmosisProtoRegistry,\n strangeloveVenturesAminoConverters,\n strangelove_ventures as strangeloveVenturesNs,\n strangeloveVenturesProtoRegistry,\n} from '@manifest-network/manifestjs';\nimport { RateLimiter } from 'limiter';\nimport {\n DEFAULT_GAS_MULTIPLIER,\n DEFAULT_REQUESTS_PER_SECOND,\n} from './config.js';\nimport { createLCDQueryClient } from './lcd-adapter.js';\nimport { logger } from './logger.js';\nimport { withRetry } from './retry.js';\nimport {\n type ManifestMCPConfig,\n ManifestMCPError,\n ManifestMCPErrorCode,\n type WalletProvider,\n} from './types.js';\n\n// Combined query client type: liftedinit modules (cosmos + billing/manifest/sku) + cosmwasm\n// + strangelove_ventures (poa) + osmosis (tokenfactory) + ibc (transfer, channel, client, connection).\n// Uses Pick to extract only each factory's unique namespace, avoiding conflicts with overlapping cosmos types.\ntype LiftedinitQueryClient = Awaited<\n ReturnType<typeof liftedinit.ClientFactory.createRPCQueryClient>\n>;\ntype CosmwasmQueryClient = Awaited<\n ReturnType<typeof cosmwasmNs.ClientFactory.createRPCQueryClient>\n>;\ntype StrangeloveVenturesQueryClient = Awaited<\n ReturnType<typeof strangeloveVenturesNs.ClientFactory.createRPCQueryClient>\n>;\ntype OsmosisQueryClient = Awaited<\n ReturnType<typeof osmosisNs.ClientFactory.createRPCQueryClient>\n>;\ntype IbcQueryClient = Awaited<\n ReturnType<typeof ibcNs.ClientFactory.createRPCQueryClient>\n>;\nexport type ManifestQueryClient = LiftedinitQueryClient &\n Pick<CosmwasmQueryClient, 'cosmwasm'> &\n Pick<StrangeloveVenturesQueryClient, 'strangelove_ventures'> &\n Pick<OsmosisQueryClient, 'osmosis'> &\n Pick<IbcQueryClient, 'ibc'>;\n\n/**\n * Extract the registry type expected by SigningStargateClient.connectWithSigner.\n *\n * The Registry type from @cosmjs/proto-signing doesn't perfectly match the registry type\n * in SigningStargateClientOptions due to telescope-generated proto types. This type alias\n * extracts the expected registry type from the function signature to enable type-safe casting.\n */\ntype SigningClientRegistry = Parameters<\n typeof SigningStargateClient.connectWithSigner\n>[2] extends { registry?: infer R }\n ? R\n : never;\n\n/** Default timeout for transaction broadcast (60 seconds) */\nconst DEFAULT_BROADCAST_TIMEOUT_MS = 60_000;\n\n/** Default polling interval for transaction confirmation (3 seconds) */\nconst DEFAULT_BROADCAST_POLL_INTERVAL_MS = 3_000;\n\n/**\n * Get combined signing client options with all Manifest registries\n */\nfunction getSigningManifestClientOptions() {\n const registry = new Registry([\n ...cosmosProtoRegistry,\n ...liftedinitProtoRegistry,\n ...strangeloveVenturesProtoRegistry,\n ...osmosisProtoRegistry,\n ...cosmwasmProtoRegistry,\n ...ibcProtoRegistry,\n ]);\n\n const aminoTypes = new AminoTypes({\n ...cosmosAminoConverters,\n ...liftedinitAminoConverters,\n ...strangeloveVenturesAminoConverters,\n ...osmosisAminoConverters,\n ...cosmwasmAminoConverters,\n ...ibcAminoConverters,\n });\n\n return { registry, aminoTypes };\n}\n\n/**\n * Manages CosmJS client instances with lazy initialization and singleton pattern\n */\nexport class CosmosClientManager {\n private static instances: Map<string, CosmosClientManager> = new Map();\n\n private config: ManifestMCPConfig;\n private walletProvider: WalletProvider;\n private queryClient: ManifestQueryClient | null = null;\n private signingClient: SigningStargateClient | null = null;\n private rateLimiter: RateLimiter;\n\n // Number of live holders (servers) sharing this instance. Each getInstance\n // acquisition increments it; each disconnect() decrements it. The underlying\n // clients are only torn down once the count reaches zero (the last holder\n // disconnects), so one server's shutdown can't sever another's shared client.\n private refCount = 0;\n\n // Promises to prevent concurrent client initialization (lazy init race condition)\n private queryClientPromise: Promise<ManifestQueryClient> | null = null;\n private signingClientPromise: Promise<SigningStargateClient> | null = null;\n\n private constructor(\n config: ManifestMCPConfig,\n walletProvider: WalletProvider,\n ) {\n this.config = config;\n this.walletProvider = walletProvider;\n\n // Initialize rate limiter with configured or default requests per second\n const requestsPerSecond =\n config.rateLimit?.requestsPerSecond ?? DEFAULT_REQUESTS_PER_SECOND;\n this.rateLimiter = new RateLimiter({\n tokensPerInterval: requestsPerSecond,\n interval: 'second',\n });\n }\n\n /**\n * Get or create a singleton instance for the given config.\n * Instances are keyed by chainId:rpcUrl:restUrl. For existing instances:\n * - Config and walletProvider references are always updated\n * - Signing client is disconnected/recreated if gasPrice, gasMultiplier, or walletProvider changed\n * - Rate limiter is updated if requestsPerSecond changed (without affecting signing client)\n *\n * Every call acquires a reference (increments refCount). Each caller must\n * balance it with exactly one disconnect() so the shared clients are torn\n * down only once the last holder releases (see disconnect()).\n *\n * Reference accounting counts calls, not distinct callers: a call that only\n * updates config on an existing key (changed gasPrice/gasMultiplier/\n * walletProvider/rate limit) still acquires a reference. A holder that\n * re-invokes getInstance to reconfigure a key it already holds therefore\n * takes an ADDITIONAL reference and must balance it with an additional\n * disconnect(), or refCount never reaches zero and the clients leak. Today\n * every server acquires once at construction and releases once at shutdown,\n * so this caveat only applies to callers that reconfigure a live key in place.\n */\n static getInstance(\n config: ManifestMCPConfig,\n walletProvider: WalletProvider,\n ): CosmosClientManager {\n const parts = [config.chainId, config.rpcUrl ?? ''];\n if (config.restUrl) parts.push(config.restUrl);\n const key = parts.join(':');\n let instance = CosmosClientManager.instances.get(key);\n\n if (!instance) {\n instance = new CosmosClientManager(config, walletProvider);\n CosmosClientManager.instances.set(key, instance);\n } else {\n // Check what changed to determine what needs updating\n const signingClientAffected =\n instance.config.gasPrice !== config.gasPrice ||\n instance.config.gasMultiplier !== config.gasMultiplier ||\n instance.walletProvider !== walletProvider;\n\n const rateLimitChanged =\n instance.config.rateLimit?.requestsPerSecond !==\n config.rateLimit?.requestsPerSecond;\n\n // Always update config reference\n instance.config = config;\n instance.walletProvider = walletProvider;\n\n // Only invalidate signing client if fields it depends on changed\n if (signingClientAffected) {\n if (instance.signingClient) {\n instance.signingClient.disconnect();\n instance.signingClient = null;\n }\n // Also clear the promise to allow re-initialization with new config\n instance.signingClientPromise = null;\n }\n\n // Update rate limiter independently (doesn't affect signing client)\n if (rateLimitChanged) {\n const newRps =\n config.rateLimit?.requestsPerSecond ?? DEFAULT_REQUESTS_PER_SECOND;\n instance.rateLimiter = new RateLimiter({\n tokensPerInterval: newRps,\n interval: 'second',\n });\n }\n }\n\n instance.refCount += 1;\n return instance;\n }\n\n /**\n * Clear all cached instances (useful for testing or reconnection).\n * Force-tears-down each instance regardless of its refCount — clearing the\n * registry is an unconditional reset, so it ignores outstanding holders,\n * disconnects signing clients, releases query client references, and resets\n * refCount to zero before clearing.\n */\n static clearInstances(): void {\n for (const instance of CosmosClientManager.instances.values()) {\n // Force teardown regardless of refCount — clearing the registry is an\n // unconditional reset (used by tests/reconnection), so drop all holders.\n instance.teardown();\n instance.refCount = 0;\n }\n CosmosClientManager.instances.clear();\n }\n\n /**\n * Get the manifestjs RPC query client with all module extensions\n *\n * Automatically retries on transient connection failures with exponential backoff.\n */\n async getQueryClient(): Promise<ManifestQueryClient> {\n // Return cached client if available\n if (this.queryClient) {\n return this.queryClient;\n }\n\n // If initialization is already in progress, wait for it\n if (this.queryClientPromise) {\n return this.queryClientPromise;\n }\n\n // Start initialization and cache the promise to prevent concurrent init\n this.queryClientPromise = (async () => {\n // Capture reference to detect if superseded by disconnect/config change\n const thisInitPromise = this.queryClientPromise;\n try {\n let client: ManifestQueryClient;\n if (this.config.restUrl) {\n // Use LCD/REST for queries when restUrl is configured\n client = await withRetry(\n () => createLCDQueryClient(this.config.restUrl!),\n {\n config: this.config.retry,\n operationName: 'connect LCD query client',\n },\n );\n } else if (this.config.rpcUrl) {\n // Use RPC: merge liftedinit + cosmwasm + strangelove_ventures + osmosis + ibc namespaces\n client = await withRetry(\n async () => {\n const [\n liftedinitClient,\n cosmwasmClient,\n strangeloveClient,\n osmosisClient,\n ibcClient,\n ] = await Promise.all([\n liftedinit.ClientFactory.createRPCQueryClient({\n rpcEndpoint: this.config.rpcUrl!,\n }),\n cosmwasmNs.ClientFactory.createRPCQueryClient({\n rpcEndpoint: this.config.rpcUrl!,\n }),\n strangeloveVenturesNs.ClientFactory.createRPCQueryClient({\n rpcEndpoint: this.config.rpcUrl!,\n }),\n osmosisNs.ClientFactory.createRPCQueryClient({\n rpcEndpoint: this.config.rpcUrl!,\n }),\n ibcNs.ClientFactory.createRPCQueryClient({\n rpcEndpoint: this.config.rpcUrl!,\n }),\n ]);\n return {\n ...liftedinitClient,\n cosmwasm: cosmwasmClient.cosmwasm,\n strangelove_ventures: strangeloveClient.strangelove_ventures,\n osmosis: osmosisClient.osmosis,\n ibc: ibcClient.ibc,\n } as ManifestQueryClient;\n },\n {\n config: this.config.retry,\n operationName: 'connect query client',\n },\n );\n } else {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'Cannot create query client: neither restUrl nor rpcUrl is configured.',\n );\n }\n // Only store if this is still the active promise\n if (this.queryClientPromise === thisInitPromise) {\n this.queryClient = client;\n this.queryClientPromise = null;\n }\n return client;\n } catch (error) {\n // Clear promise on failure so retry is possible (only if still active)\n if (this.queryClientPromise === thisInitPromise) {\n this.queryClientPromise = null;\n }\n if (error instanceof ManifestMCPError) {\n throw error;\n }\n const endpoint = this.config.restUrl ?? this.config.rpcUrl;\n throw new ManifestMCPError(\n ManifestMCPErrorCode.RPC_CONNECTION_FAILED,\n `Failed to connect to ${this.config.restUrl ? 'REST' : 'RPC'} endpoint: ${error instanceof Error ? error.message : String(error)}`,\n { url: endpoint },\n );\n }\n })();\n\n return this.queryClientPromise;\n }\n\n /**\n * Get a signing client with all Manifest registries (for transactions)\n *\n * Automatically retries on transient connection failures with exponential backoff.\n */\n async getSigningClient(): Promise<SigningStargateClient> {\n if (!this.config.rpcUrl || !this.config.gasPrice) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'Signing client requires rpcUrl and gasPrice configuration. Current config is query-only (REST).',\n );\n }\n\n // Return cached client if available\n if (this.signingClient) {\n return this.signingClient;\n }\n\n // If initialization is already in progress, wait for it\n if (this.signingClientPromise) {\n return this.signingClientPromise;\n }\n\n // Start initialization and cache the promise to prevent concurrent init\n this.signingClientPromise = (async () => {\n // Capture reference to detect if superseded by disconnect/config change\n const thisInitPromise = this.signingClientPromise;\n try {\n const signer = await this.walletProvider.getSigner();\n const gasPrice = GasPrice.fromString(this.config.gasPrice!);\n const { registry, aminoTypes } = getSigningManifestClientOptions();\n\n // Configure endpoint as HttpEndpoint object (required for custom options)\n const endpoint: HttpEndpoint = {\n url: this.config.rpcUrl!,\n headers: {},\n };\n\n // Note: Registry type from @cosmjs/proto-signing doesn't perfectly match\n // SigningStargateClientOptions due to telescope-generated proto types.\n // This is a known limitation with custom cosmos-sdk module registries.\n // Wrap with retry for transient connection failures\n const client = await withRetry(\n async () => {\n const c = await SigningStargateClient.connectWithSigner(\n endpoint,\n signer,\n {\n registry: registry as SigningClientRegistry,\n aminoTypes,\n gasPrice,\n broadcastTimeoutMs: DEFAULT_BROADCAST_TIMEOUT_MS,\n broadcastPollIntervalMs: DEFAULT_BROADCAST_POLL_INTERVAL_MS,\n },\n );\n // The property is private readonly with no constructor option,\n // so we must bypass TypeScript's access control to override it.\n const record = c as unknown as Record<string, unknown>;\n if (typeof record.defaultGasMultiplier === 'number') {\n record.defaultGasMultiplier =\n this.config.gasMultiplier ?? DEFAULT_GAS_MULTIPLIER;\n } else {\n const effective =\n this.config.gasMultiplier ?? DEFAULT_GAS_MULTIPLIER;\n logger.warn(\n `gasMultiplier ${effective} could not be applied: ` +\n `signing client defaultGasMultiplier is ${typeof record.defaultGasMultiplier}, expected number. ` +\n `Transactions will use the CosmJS built-in gas multiplier instead.`,\n );\n }\n return c;\n },\n {\n config: this.config.retry,\n operationName: 'connect signing client',\n },\n );\n // Only store if this is still the active promise\n if (this.signingClientPromise === thisInitPromise) {\n this.signingClient = client;\n this.signingClientPromise = null;\n } else {\n // Promise was superseded, clean up the client we just created\n client.disconnect();\n }\n return client;\n } catch (error) {\n // Clear promise on failure so retry is possible (only if still active)\n if (this.signingClientPromise === thisInitPromise) {\n this.signingClientPromise = null;\n }\n if (error instanceof ManifestMCPError) {\n throw error;\n }\n throw new ManifestMCPError(\n ManifestMCPErrorCode.RPC_CONNECTION_FAILED,\n `Failed to connect signing client: ${error instanceof Error ? error.message : String(error)}`,\n { rpcUrl: this.config.rpcUrl },\n );\n }\n })();\n\n return this.signingClientPromise;\n }\n\n /**\n * Get the wallet address\n */\n async getAddress(): Promise<string> {\n return this.walletProvider.getAddress();\n }\n\n /**\n * Get the configuration\n */\n getConfig(): ManifestMCPConfig {\n return this.config;\n }\n\n /**\n * Acquire a rate limit token before making an RPC request.\n * This will wait if the rate limit has been exceeded.\n */\n async acquireRateLimit(): Promise<void> {\n await this.rateLimiter.removeTokens(1);\n }\n\n /**\n * Release this holder's reference to the shared instance. The underlying\n * clients are only torn down once the last holder disconnects (refCount\n * reaches zero), so one server's shutdown cannot sever a client still in\n * use by another server sharing the same config key. Calling disconnect()\n * more times than getInstance() was called is safe and never drives the\n * count negative.\n */\n disconnect(): void {\n if (this.refCount > 0) this.refCount -= 1;\n if (this.refCount === 0) this.teardown();\n }\n\n /**\n * Tear down the signing client and release query client references.\n * The query client's underlying HTTP transport is stateless and does not\n * require an explicit disconnect.\n */\n private teardown(): void {\n if (this.signingClient) {\n this.signingClient.disconnect();\n this.signingClient = null;\n }\n this.signingClientPromise = null;\n this.queryClient = null;\n this.queryClientPromise = null;\n }\n}\n"],"mappings":";;;;;;;;;;;AA+EA,MAAM,+BAA+B;;AAGrC,MAAM,qCAAqC;;;;AAK3C,SAAS,kCAAkC;AAmBzC,QAAO;EAAE,UAAA,IAlBY,SAAS;GAC5B,GAAG;GACH,GAAG;GACH,GAAG;GACH,GAAG;GACH,GAAG;GACH,GAAG;GACJ,CAWgB;EAAE,YAAA,IATI,WAAW;GAChC,GAAG;GACH,GAAG;GACH,GAAG;GACH,GAAG;GACH,GAAG;GACH,GAAG;GACJ,CAE4B;EAAE;;;;;AAMjC,IAAa,sBAAb,MAAa,oBAAoB;CAmB/B,YACE,QACA,gBACA;AAjBF,OAAQ,cAA0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AQ,KAAK,OAAO,QAAQ,CAC/B;;MAED;AAEJ,SAAO,KAAK;;;;;CAMd,MAAM,aAA8B;AAClC,SAAO,KAAK,eAAe,YAAY;;;;;CAMzC,YAA+B;AAC7B,SAAO,KAAK;;;;;;CAOd,MAAM,mBAAkC;AACtC,QAAM,KAAK,YAAY,aAAa,EAAE;;;;;;;;;;CAWxC,aAAmB;AACjB,MAAI,KAAK,WAAW,EAAG,MAAK,YAAY;AACxC,MAAI,KAAK,aAAa,EAAG,MAAK,UAAU;;;;;;;CAQ1C,WAAyB;AACvB,MAAI,KAAK,eAAe;AACtB,QAAK,cAAc,YAAY;AAC/B,QAAK,gBAAgB;;AAEvB,OAAK,uBAAuB;AAC5B,OAAK,cAAc;AACnB,OAAK,qBAAqB;;;AA1X5B,oBAAe,4BAA8C,IAAI,KAAK"}
package/dist/config.js CHANGED
@@ -1,4 +1,4 @@
1
- import { ManifestMCPError, ManifestMCPErrorCode } from "./types.js";
1
+ import { ManifestMCPError } from "./types.js";
2
2
  import { DEFAULT_RETRY_CONFIG } from "./retry.js";
3
3
  //#region src/config.ts
4
4
  /**
@@ -131,7 +131,7 @@ function validateConfig(config) {
131
131
  */
132
132
  function createValidatedConfig(input) {
133
133
  const validation = validateConfig(input);
134
- if (!validation.valid) throw new ManifestMCPError(ManifestMCPErrorCode.INVALID_CONFIG, `Invalid configuration: ${validation.errors.join(", ")}`, { errors: validation.errors });
134
+ if (!validation.valid) throw new ManifestMCPError("INVALID_CONFIG", `Invalid configuration: ${validation.errors.join(", ")}`, { errors: validation.errors });
135
135
  return createConfig(input);
136
136
  }
137
137
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { DEFAULT_RETRY_CONFIG } from './retry.js';\nimport {\n type ManifestMCPConfig,\n ManifestMCPError,\n ManifestMCPErrorCode,\n} from './types.js';\n\n/**\n * Default address prefix for Manifest Network\n */\nconst DEFAULT_ADDRESS_PREFIX = 'manifest';\n\n/**\n * Default requests per second for rate limiting\n */\nexport const DEFAULT_REQUESTS_PER_SECOND = 10;\n\n/**\n * Default gas simulation multiplier. CosmJS defaults to 1.4 but billing module\n * transactions (close-lease in particular) can exceed that. 1.5 matches\n * the --gas-adjustment value used in this project's E2E scripts (e2e/scripts/init_billing.sh).\n */\nexport const DEFAULT_GAS_MULTIPLIER = 1.5;\n\n// Re-export for consumers\nexport { DEFAULT_RETRY_CONFIG };\n\n/**\n * Check if a hostname is localhost (IPv4, IPv6, or hostname)\n * Handles both bracketed and unbracketed IPv6 formats\n */\nfunction isLocalhostHostname(hostname: string): boolean {\n if (hostname === 'localhost' || hostname === '127.0.0.1') {\n return true;\n }\n // Handle IPv6 localhost - hostname may be '::1' or '[::1]' depending on environment\n const normalizedHostname = hostname.replace(/^\\[|\\]$/g, '');\n return normalizedHostname === '::1';\n}\n\n/**\n * Validate URL format and check if it uses HTTPS or is localhost (HTTP allowed for local dev)\n * Returns validation result with error reason if invalid\n */\nexport function validateEndpointUrl(\n url: string,\n label: string,\n): { valid: true } | { valid: false; reason: string } {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return { valid: false, reason: `${label} must be a valid URL` };\n }\n\n if (parsed.protocol === 'https:') {\n return { valid: true };\n }\n\n if (parsed.protocol === 'http:' && isLocalhostHostname(parsed.hostname)) {\n return { valid: true }; // HTTP allowed for localhost\n }\n\n return {\n valid: false,\n reason: `${label} must use HTTPS (got ${parsed.protocol}//). HTTP is only allowed for local development (localhost, 127.0.0.1, ::1).`,\n };\n}\n\n/**\n * Validate gas price format (e.g., \"1.0umfx\")\n */\nfunction isValidGasPrice(gasPrice: string): boolean {\n // Gas price should be a number followed by a denomination.\n // Denoms can be simple (umfx), IBC (ibc/ABC123...), or factory\n // (factory/manifest1.../utoken). Denoms are made of non-empty segments\n // separated by '/', with the first segment starting with a letter.\n // Each segment may contain letters, digits, dots, colons, underscores,\n // and hyphens. Denom length must be 3-128 chars per the Cosmos SDK spec.\n const match = gasPrice.match(\n /^(\\d+(?:\\.\\d+)?)([a-zA-Z][a-zA-Z0-9.:_-]*(?:\\/[a-zA-Z0-9.:_-]+)*)$/,\n );\n if (!match) {\n return false;\n }\n const denom = match[2];\n return denom.length >= 3 && denom.length <= 128;\n}\n\n/**\n * Validate chain ID format\n */\nfunction isValidChainId(chainId: string): boolean {\n // Chain ID should be alphanumeric with hyphens\n return /^[a-zA-Z0-9][\\w-]*$/.test(chainId);\n}\n\n/**\n * Create a configuration object with defaults applied\n */\nexport function createConfig(input: ManifestMCPConfig): ManifestMCPConfig {\n return {\n chainId: input.chainId,\n rpcUrl: input.rpcUrl,\n gasPrice: input.gasPrice,\n restUrl: input.restUrl,\n addressPrefix: input.addressPrefix ?? DEFAULT_ADDRESS_PREFIX,\n rateLimit: {\n requestsPerSecond:\n input.rateLimit?.requestsPerSecond ?? DEFAULT_REQUESTS_PER_SECOND,\n },\n retry: {\n maxRetries: input.retry?.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries,\n baseDelayMs: input.retry?.baseDelayMs ?? DEFAULT_RETRY_CONFIG.baseDelayMs,\n maxDelayMs: input.retry?.maxDelayMs ?? DEFAULT_RETRY_CONFIG.maxDelayMs,\n },\n gasMultiplier: input.gasMultiplier ?? DEFAULT_GAS_MULTIPLIER,\n };\n}\n\n/**\n * Validation result\n */\nexport interface ValidationResult {\n valid: boolean;\n errors: string[];\n}\n\n/**\n * Validate a configuration object\n */\nexport function validateConfig(\n config: Partial<ManifestMCPConfig>,\n): ValidationResult {\n const errors: string[] = [];\n\n // Required fields\n if (!config.chainId) {\n errors.push('chainId is required');\n } else if (!isValidChainId(config.chainId)) {\n errors.push(\n 'chainId must be alphanumeric with hyphens (e.g., \"manifest-ledger-testnet\")',\n );\n }\n\n // At least one of rpcUrl or restUrl must be provided\n if (!config.rpcUrl && !config.restUrl) {\n errors.push('At least one of rpcUrl or restUrl is required');\n }\n\n if (config.rpcUrl) {\n const urlCheck = validateEndpointUrl(config.rpcUrl, 'rpcUrl');\n if (!urlCheck.valid) {\n errors.push(urlCheck.reason);\n }\n }\n\n if (config.restUrl) {\n const urlCheck = validateEndpointUrl(config.restUrl, 'restUrl');\n if (!urlCheck.valid) {\n errors.push(urlCheck.reason);\n }\n }\n\n // gasPrice required when rpcUrl is provided (needed for signing)\n if (config.rpcUrl && !config.gasPrice) {\n errors.push('gasPrice is required when rpcUrl is provided');\n } else if (config.gasPrice && !isValidGasPrice(config.gasPrice)) {\n errors.push(\n 'gasPrice must be a number followed by denomination (e.g., \"1.0umfx\", \"0.5factory/addr/udenom\", or \"0.25ibc/ABC123\")',\n );\n }\n\n // Optional fields\n if (config.addressPrefix !== undefined) {\n if (!/^[a-z]+$/.test(config.addressPrefix)) {\n errors.push('addressPrefix must be lowercase letters only');\n }\n }\n\n if (config.rateLimit !== undefined) {\n if (\n typeof config.rateLimit !== 'object' ||\n config.rateLimit === null ||\n Array.isArray(config.rateLimit)\n ) {\n errors.push('rateLimit must be a plain object');\n } else if (config.rateLimit.requestsPerSecond !== undefined) {\n if (\n typeof config.rateLimit.requestsPerSecond !== 'number' ||\n config.rateLimit.requestsPerSecond <= 0 ||\n !Number.isInteger(config.rateLimit.requestsPerSecond)\n ) {\n errors.push('rateLimit.requestsPerSecond must be a positive integer');\n }\n }\n }\n\n if (config.retry !== undefined) {\n if (\n typeof config.retry !== 'object' ||\n config.retry === null ||\n Array.isArray(config.retry)\n ) {\n errors.push('retry must be a plain object');\n } else {\n if (config.retry.maxRetries !== undefined) {\n if (\n typeof config.retry.maxRetries !== 'number' ||\n config.retry.maxRetries < 0 ||\n !Number.isInteger(config.retry.maxRetries)\n ) {\n errors.push('retry.maxRetries must be a non-negative integer');\n }\n }\n if (config.retry.baseDelayMs !== undefined) {\n if (\n typeof config.retry.baseDelayMs !== 'number' ||\n config.retry.baseDelayMs <= 0 ||\n !Number.isInteger(config.retry.baseDelayMs)\n ) {\n errors.push('retry.baseDelayMs must be a positive integer');\n }\n }\n if (config.retry.maxDelayMs !== undefined) {\n if (\n typeof config.retry.maxDelayMs !== 'number' ||\n config.retry.maxDelayMs <= 0 ||\n !Number.isInteger(config.retry.maxDelayMs)\n ) {\n errors.push('retry.maxDelayMs must be a positive integer');\n }\n }\n // Validate maxDelayMs >= baseDelayMs if both are provided\n if (\n config.retry.baseDelayMs !== undefined &&\n config.retry.maxDelayMs !== undefined &&\n config.retry.maxDelayMs < config.retry.baseDelayMs\n ) {\n errors.push(\n 'retry.maxDelayMs must be greater than or equal to retry.baseDelayMs',\n );\n }\n }\n }\n\n if (config.gasMultiplier !== undefined) {\n if (\n typeof config.gasMultiplier !== 'number' ||\n !Number.isFinite(config.gasMultiplier) ||\n config.gasMultiplier < 1\n ) {\n errors.push('gasMultiplier must be a finite number >= 1');\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n };\n}\n\n/**\n * Create and validate a configuration, throwing on invalid config\n */\nexport function createValidatedConfig(\n input: ManifestMCPConfig,\n): ManifestMCPConfig {\n const validation = validateConfig(input);\n\n if (!validation.valid) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `Invalid configuration: ${validation.errors.join(', ')}`,\n { errors: validation.errors },\n );\n }\n\n return createConfig(input);\n}\n"],"mappings":";;;;;;AAUA,MAAM,yBAAyB;;;;AAK/B,MAAa,8BAA8B;;;;;;AAO3C,MAAa,yBAAyB;;;;;AAStC,SAAS,oBAAoB,UAA2B;AACtD,KAAI,aAAa,eAAe,aAAa,YAC3C,QAAO;AAIT,QAD2B,SAAS,QAAQ,YAAY,GAAG,KAC7B;;;;;;AAOhC,SAAgB,oBACd,KACA,OACoD;CACpD,IAAI;AACJ,KAAI;AACF,WAAS,IAAI,IAAI,IAAI;SACf;AACN,SAAO;GAAE,OAAO;GAAO,QAAQ,GAAG,MAAM;GAAuB;;AAGjE,KAAI,OAAO,aAAa,SACtB,QAAO,EAAE,OAAO,MAAM;AAGxB,KAAI,OAAO,aAAa,WAAW,oBAAoB,OAAO,SAAS,CACrE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EACD;;AAKP,KAAI,OAAO,kBAAkB,KAAA;MAEzB,OAAO,OAAO,kBAAkB,YAChC,CAAC,OAAO,SAAS,OAAO,cAAc,IACtC,OAAO,gBAAgB,EAEvB,QAAO,KAAK,6CAA6C;;AAI7D,QAAO;EACL,OAAO,OAAO,WAAW;EACzB;EACD;;;;;AAMH,SAAgB,sBACd,OACmB;CACnB,MAAM,aAAa,eAAe,MAAM;AAExC,KAAI,CAAC,WAAW,MACd,OAAM,IAAI,iBACR,qBAAqB,gBACrB,0BAA0B,WAAW,OAAO,KAAK,KAAK,IACtD,EAAE,QAAQ,WAAW,QAAQ,CAC9B;AAGH,QAAO,aAAa,MAAM"}
1
+ {"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { DEFAULT_RETRY_CONFIG } from './retry.js';\nimport {\n type ManifestMCPConfig,\n ManifestMCPError,\n ManifestMCPErrorCode,\n} from './types.js';\n\n/**\n * Default address prefix for Manifest Network\n */\nconst DEFAULT_ADDRESS_PREFIX = 'manifest';\n\n/**\n * Default requests per second for rate limiting\n */\nexport const DEFAULT_REQUESTS_PER_SECOND = 10;\n\n/**\n * Default gas simulation multiplier. CosmJS defaults to 1.4 but billing module\n * transactions (close-lease in particular) can exceed that. 1.5 matches\n * the --gas-adjustment value used in this project's E2E scripts (e2e/scripts/init_billing.sh).\n */\nexport const DEFAULT_GAS_MULTIPLIER = 1.5;\n\n// Re-export for consumers\nexport { DEFAULT_RETRY_CONFIG };\n\n/**\n * Check if a hostname is localhost (IPv4, IPv6, or hostname)\n * Handles both bracketed and unbracketed IPv6 formats\n */\nfunction isLocalhostHostname(hostname: string): boolean {\n if (hostname === 'localhost' || hostname === '127.0.0.1') {\n return true;\n }\n // Handle IPv6 localhost - hostname may be '::1' or '[::1]' depending on environment\n const normalizedHostname = hostname.replace(/^\\[|\\]$/g, '');\n return normalizedHostname === '::1';\n}\n\n/**\n * Validate URL format and check if it uses HTTPS or is localhost (HTTP allowed for local dev)\n * Returns validation result with error reason if invalid\n */\nexport function validateEndpointUrl(\n url: string,\n label: string,\n): { valid: true } | { valid: false; reason: string } {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return { valid: false, reason: `${label} must be a valid URL` };\n }\n\n if (parsed.protocol === 'https:') {\n return { valid: true };\n }\n\n if (parsed.protocol === 'http:' && isLocalhostHostname(parsed.hostname)) {\n return { valid: true }; // HTTP allowed for localhost\n }\n\n return {\n valid: false,\n reason: `${label} must use HTTPS (got ${parsed.protocol}//). HTTP is only allowed for local development (localhost, 127.0.0.1, ::1).`,\n };\n}\n\n/**\n * Validate gas price format (e.g., \"1.0umfx\")\n */\nfunction isValidGasPrice(gasPrice: string): boolean {\n // Gas price should be a number followed by a denomination.\n // Denoms can be simple (umfx), IBC (ibc/ABC123...), or factory\n // (factory/manifest1.../utoken). Denoms are made of non-empty segments\n // separated by '/', with the first segment starting with a letter.\n // Each segment may contain letters, digits, dots, colons, underscores,\n // and hyphens. Denom length must be 3-128 chars per the Cosmos SDK spec.\n const match = gasPrice.match(\n /^(\\d+(?:\\.\\d+)?)([a-zA-Z][a-zA-Z0-9.:_-]*(?:\\/[a-zA-Z0-9.:_-]+)*)$/,\n );\n if (!match) {\n return false;\n }\n const denom = match[2];\n return denom.length >= 3 && denom.length <= 128;\n}\n\n/**\n * Validate chain ID format\n */\nfunction isValidChainId(chainId: string): boolean {\n // Chain ID should be alphanumeric with hyphens\n return /^[a-zA-Z0-9][\\w-]*$/.test(chainId);\n}\n\n/**\n * Create a configuration object with defaults applied\n */\nexport function createConfig(input: ManifestMCPConfig): ManifestMCPConfig {\n return {\n chainId: input.chainId,\n rpcUrl: input.rpcUrl,\n gasPrice: input.gasPrice,\n restUrl: input.restUrl,\n addressPrefix: input.addressPrefix ?? DEFAULT_ADDRESS_PREFIX,\n rateLimit: {\n requestsPerSecond:\n input.rateLimit?.requestsPerSecond ?? DEFAULT_REQUESTS_PER_SECOND,\n },\n retry: {\n maxRetries: input.retry?.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries,\n baseDelayMs: input.retry?.baseDelayMs ?? DEFAULT_RETRY_CONFIG.baseDelayMs,\n maxDelayMs: input.retry?.maxDelayMs ?? DEFAULT_RETRY_CONFIG.maxDelayMs,\n },\n gasMultiplier: input.gasMultiplier ?? DEFAULT_GAS_MULTIPLIER,\n };\n}\n\n/**\n * Validation result\n */\nexport interface ValidationResult {\n valid: boolean;\n errors: string[];\n}\n\n/**\n * Validate a configuration object\n */\nexport function validateConfig(\n config: Partial<ManifestMCPConfig>,\n): ValidationResult {\n const errors: string[] = [];\n\n // Required fields\n if (!config.chainId) {\n errors.push('chainId is required');\n } else if (!isValidChainId(config.chainId)) {\n errors.push(\n 'chainId must be alphanumeric with hyphens (e.g., \"manifest-ledger-testnet\")',\n );\n }\n\n // At least one of rpcUrl or restUrl must be provided\n if (!config.rpcUrl && !config.restUrl) {\n errors.push('At least one of rpcUrl or restUrl is required');\n }\n\n if (config.rpcUrl) {\n const urlCheck = validateEndpointUrl(config.rpcUrl, 'rpcUrl');\n if (!urlCheck.valid) {\n errors.push(urlCheck.reason);\n }\n }\n\n if (config.restUrl) {\n const urlCheck = validateEndpointUrl(config.restUrl, 'restUrl');\n if (!urlCheck.valid) {\n errors.push(urlCheck.reason);\n }\n }\n\n // gasPrice required when rpcUrl is provided (needed for signing)\n if (config.rpcUrl && !config.gasPrice) {\n errors.push('gasPrice is required when rpcUrl is provided');\n } else if (config.gasPrice && !isValidGasPrice(config.gasPrice)) {\n errors.push(\n 'gasPrice must be a number followed by denomination (e.g., \"1.0umfx\", \"0.5factory/addr/udenom\", or \"0.25ibc/ABC123\")',\n );\n }\n\n // Optional fields\n if (config.addressPrefix !== undefined) {\n if (!/^[a-z]+$/.test(config.addressPrefix)) {\n errors.push('addressPrefix must be lowercase letters only');\n }\n }\n\n if (config.rateLimit !== undefined) {\n if (\n typeof config.rateLimit !== 'object' ||\n config.rateLimit === null ||\n Array.isArray(config.rateLimit)\n ) {\n errors.push('rateLimit must be a plain object');\n } else if (config.rateLimit.requestsPerSecond !== undefined) {\n if (\n typeof config.rateLimit.requestsPerSecond !== 'number' ||\n config.rateLimit.requestsPerSecond <= 0 ||\n !Number.isInteger(config.rateLimit.requestsPerSecond)\n ) {\n errors.push('rateLimit.requestsPerSecond must be a positive integer');\n }\n }\n }\n\n if (config.retry !== undefined) {\n if (\n typeof config.retry !== 'object' ||\n config.retry === null ||\n Array.isArray(config.retry)\n ) {\n errors.push('retry must be a plain object');\n } else {\n if (config.retry.maxRetries !== undefined) {\n if (\n typeof config.retry.maxRetries !== 'number' ||\n config.retry.maxRetries < 0 ||\n !Number.isInteger(config.retry.maxRetries)\n ) {\n errors.push('retry.maxRetries must be a non-negative integer');\n }\n }\n if (config.retry.baseDelayMs !== undefined) {\n if (\n typeof config.retry.baseDelayMs !== 'number' ||\n config.retry.baseDelayMs <= 0 ||\n !Number.isInteger(config.retry.baseDelayMs)\n ) {\n errors.push('retry.baseDelayMs must be a positive integer');\n }\n }\n if (config.retry.maxDelayMs !== undefined) {\n if (\n typeof config.retry.maxDelayMs !== 'number' ||\n config.retry.maxDelayMs <= 0 ||\n !Number.isInteger(config.retry.maxDelayMs)\n ) {\n errors.push('retry.maxDelayMs must be a positive integer');\n }\n }\n // Validate maxDelayMs >= baseDelayMs if both are provided\n if (\n config.retry.baseDelayMs !== undefined &&\n config.retry.maxDelayMs !== undefined &&\n config.retry.maxDelayMs < config.retry.baseDelayMs\n ) {\n errors.push(\n 'retry.maxDelayMs must be greater than or equal to retry.baseDelayMs',\n );\n }\n }\n }\n\n if (config.gasMultiplier !== undefined) {\n if (\n typeof config.gasMultiplier !== 'number' ||\n !Number.isFinite(config.gasMultiplier) ||\n config.gasMultiplier < 1\n ) {\n errors.push('gasMultiplier must be a finite number >= 1');\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n };\n}\n\n/**\n * Create and validate a configuration, throwing on invalid config\n */\nexport function createValidatedConfig(\n input: ManifestMCPConfig,\n): ManifestMCPConfig {\n const validation = validateConfig(input);\n\n if (!validation.valid) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `Invalid configuration: ${validation.errors.join(', ')}`,\n { errors: validation.errors },\n );\n }\n\n return createConfig(input);\n}\n"],"mappings":";;;;;;AAUA,MAAM,yBAAyB;;;;AAK/B,MAAa,8BAA8B;;;;;;AAO3C,MAAa,yBAAyB;;;;;AAStC,SAAS,oBAAoB,UAA2B;AACtD,KAAI,aAAa,eAAe,aAAa,YAC3C,QAAO;AAIT,QAD2B,SAAS,QAAQ,YAAY,GAC/B,KAAK;;;;;;AAOhC,SAAgB,oBACd,KACA,OACoD;CACpD,IAAI;AACJ,KAAI;AACF,WAAS,IAAI,IAAI,IAAI;SACf;AACN,SAAO;GAAE,OAAO;GAAO,QAAQ,GAAG,MAAM;GAAuB;;AAGjE,KAAI,OAAO,aAAa,SACtB,QAAO,EAAE,OAAO,MAAM;AAGxB,KAAI,OAAO,aAAa,WAAW,oBAAoB,OAAO,SAAS,CACrE,QAAO,EAAE,OAAO,MAAM;AAGxB,QAAO;EACL,OAAO;EACP,QAAQ,GAAG,MAAM,uBAAuB,OAAO,SAAS;EACzD;;;;;AAMH,SAAS,gBAAgB,UAA2B;CAOlD,MAAM,QAAQ,SAAS,MACrB,qEACD;AACD,KAAI,CAAC,MACH,QAAO;CAET,MAAM,QAAQ,MAAM;AACpB,QAAO,MAAM,UAAU,KAAK,MAAM,UAAU;;;;;AAM9C,SAAS,eAAe,SAA0B;AAEhD,QAAO,sBAAsB,KAAK,QAAQ;;;;;AAM5C,SAAgB,aAAa,OAA6C;AACxE,QAAO;EACL,SAAS,MAAM;EACf,QAAQ,MAAM;EACd,UAAU,MAAM;EAChB,SAAS,MAAM;EACf,eAAe,MAAM,iBAAiB;EACtC,WAAW,EACT,mBACE,MAAM,WAAW,qBAAA,IACpB;EACD,OAAO;GACL,YAAY,MAAM,OAAO,cAAc,qBAAqB;GAC5D,aAAa,MAAM,OAAO,eAAe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AA+B;MACtC;AACL,MAAI,OAAO,MAAM,eAAe,KAAA;OAE5B,OAAO,OAAO,MAAM,eAAe,YACnC,OAAO,MAAM,aAAa,KAC1B,CAAC,OAAO,UAAU,OAAO,MAAM,WAAW,CAE1C,QAAO,KAAK,kDAAkD;;AAGlE,MAAI,OAAO,MAAM,gBAAgB,KAAA;OAE7B,OAAO,OAAO,MAAM,gBAAgB,YACpC,OAAO,MAAM,eAAe,KAC5B,CAAC,OAAO,UAAU,OAAO,MAAM,YAAY,CAE3C,QAAO,KAAK,+CAA+C;;AAG/D,MAAI,OAAO,MAAM,eAAe,KAAA;OAE5B,OAAO,OAAO,MAAM,eAAe,YACnC,OAAO,MAAM,cAAc,KAC3B,CAAC,OAAO,UAAU,OAAO,MAAM,WAAW,CAE1C,QAAO,KAAK,8CAA8C;;AAI9D,MACE,OAAO,MAAM,gBAAgB,KAAA,KAC7B,OAAO,MAAM,eAAe,KAAA,KAC5B,OAAO,MAAM,aAAa,OAAO,MAAM,YAEvC,QAAO,KACL,sEACD;;AAKP,KAAI,OAAO,kBAAkB,KAAA;MAEzB,OAAO,OAAO,kBAAkB,YAChC,CAAC,OAAO,SAAS,OAAO,cAAc,IACtC,OAAO,gBAAgB,EAEvB,QAAO,KAAK,6CAA6C;;AAI7D,QAAO;EACL,OAAO,OAAO,WAAW;EACzB;EACD;;;;;AAMH,SAAgB,sBACd,OACmB;CACnB,MAAM,aAAa,eAAe,MAAM;AAExC,KAAI,CAAC,WAAW,MACd,OAAM,IAAI,iBAAA,kBAER,0BAA0B,WAAW,OAAO,KAAK,KAAK,IACtD,EAAE,QAAQ,WAAW,QAAQ,CAC9B;AAGH,QAAO,aAAa,MAAM"}
package/dist/cosmos.js CHANGED
@@ -1,4 +1,4 @@
1
- import { ManifestMCPError, ManifestMCPErrorCode } from "./types.js";
1
+ import { ManifestMCPError } from "./types.js";
2
2
  import { withRetry } from "./retry.js";
3
3
  import "./config.js";
4
4
  import { getQueryHandler, getTxContextLoader, getTxHandler, getTxMsgBuilder } from "./modules.js";
@@ -32,7 +32,7 @@ async function loadBuildContext(clientManager, module, subcommand) {
32
32
  });
33
33
  throw error;
34
34
  }
35
- throw new ManifestMCPError(ManifestMCPErrorCode.QUERY_FAILED, `Failed to load build context for ${module} ${subcommand}: ${error instanceof Error ? error.message : String(error)}`, {
35
+ throw new ManifestMCPError("QUERY_FAILED", `Failed to load build context for ${module} ${subcommand}: ${error instanceof Error ? error.message : String(error)}`, {
36
36
  module,
37
37
  subcommand
38
38
  });
@@ -53,8 +53,8 @@ function validateName(name, field, errorCode) {
53
53
  * with exponential backoff. Configure retry behavior via `config.retry`.
54
54
  */
55
55
  async function cosmosQuery(clientManager, module, subcommand, args = []) {
56
- validateName(module, "module", ManifestMCPErrorCode.UNSUPPORTED_QUERY);
57
- validateName(subcommand, "subcommand", ManifestMCPErrorCode.UNSUPPORTED_QUERY);
56
+ validateName(module, "module", "UNSUPPORTED_QUERY");
57
+ validateName(subcommand, "subcommand", "UNSUPPORTED_QUERY");
58
58
  const handler = getQueryHandler(module);
59
59
  return withRetry(async () => {
60
60
  try {
@@ -73,7 +73,7 @@ async function cosmosQuery(clientManager, module, subcommand, args = []) {
73
73
  });
74
74
  throw error;
75
75
  }
76
- throw new ManifestMCPError(ManifestMCPErrorCode.QUERY_FAILED, `Query ${module} ${subcommand} failed: ${error instanceof Error ? error.message : String(error)}`, {
76
+ throw new ManifestMCPError("QUERY_FAILED", `Query ${module} ${subcommand} failed: ${error instanceof Error ? error.message : String(error)}`, {
77
77
  module,
78
78
  subcommand
79
79
  });
@@ -93,13 +93,13 @@ async function cosmosQuery(clientManager, module, subcommand, args = []) {
93
93
  * (insufficient funds, invalid args, etc.) are not retried as they won't succeed.
94
94
  */
95
95
  async function cosmosTx(clientManager, module, subcommand, args = [], waitForConfirmation = false, overrides) {
96
- validateName(module, "module", ManifestMCPErrorCode.UNSUPPORTED_TX);
97
- validateName(subcommand, "subcommand", ManifestMCPErrorCode.UNSUPPORTED_TX);
96
+ validateName(module, "module", "UNSUPPORTED_TX");
97
+ validateName(subcommand, "subcommand", "UNSUPPORTED_TX");
98
98
  let txOptions;
99
99
  if (overrides?.gasMultiplier !== void 0) {
100
- if (!Number.isFinite(overrides.gasMultiplier) || overrides.gasMultiplier < 1) throw new ManifestMCPError(ManifestMCPErrorCode.INVALID_CONFIG, `gasMultiplier must be a finite number >= 1, got ${overrides.gasMultiplier}`);
100
+ if (!Number.isFinite(overrides.gasMultiplier) || overrides.gasMultiplier < 1) throw new ManifestMCPError("INVALID_CONFIG", `gasMultiplier must be a finite number >= 1, got ${overrides.gasMultiplier}`);
101
101
  const gasPrice = clientManager.getConfig().gasPrice;
102
- if (!gasPrice) throw new ManifestMCPError(ManifestMCPErrorCode.INVALID_CONFIG, "gasMultiplier override requires gasPrice configuration");
102
+ if (!gasPrice) throw new ManifestMCPError("INVALID_CONFIG", "gasMultiplier override requires gasPrice configuration");
103
103
  txOptions = {
104
104
  gasMultiplier: overrides.gasMultiplier,
105
105
  gasPrice
@@ -124,7 +124,7 @@ async function cosmosTx(clientManager, module, subcommand, args = [], waitForCon
124
124
  });
125
125
  throw error;
126
126
  }
127
- throw new ManifestMCPError(ManifestMCPErrorCode.TX_FAILED, `Tx ${module} ${subcommand} failed: ${error instanceof Error ? error.message : String(error)}`, {
127
+ throw new ManifestMCPError("TX_FAILED", `Tx ${module} ${subcommand} failed: ${error instanceof Error ? error.message : String(error)}`, {
128
128
  module,
129
129
  subcommand,
130
130
  args
@@ -147,13 +147,13 @@ async function cosmosTx(clientManager, module, subcommand, args = [], waitForCon
147
147
  * @returns FeeEstimateResult with raw gas estimate and computed fee
148
148
  */
149
149
  async function cosmosEstimateFee(clientManager, module, subcommand, args = [], overrides) {
150
- validateName(module, "module", ManifestMCPErrorCode.UNSUPPORTED_TX);
151
- validateName(subcommand, "subcommand", ManifestMCPErrorCode.UNSUPPORTED_TX);
150
+ validateName(module, "module", "UNSUPPORTED_TX");
151
+ validateName(subcommand, "subcommand", "UNSUPPORTED_TX");
152
152
  const config = clientManager.getConfig();
153
153
  const gasPrice = config.gasPrice;
154
- if (!gasPrice) throw new ManifestMCPError(ManifestMCPErrorCode.INVALID_CONFIG, "Fee estimation requires gasPrice configuration");
154
+ if (!gasPrice) throw new ManifestMCPError("INVALID_CONFIG", "Fee estimation requires gasPrice configuration");
155
155
  if (overrides?.gasMultiplier !== void 0) {
156
- if (!Number.isFinite(overrides.gasMultiplier) || overrides.gasMultiplier < 1) throw new ManifestMCPError(ManifestMCPErrorCode.INVALID_CONFIG, `gasMultiplier must be a finite number >= 1, got ${overrides.gasMultiplier}`);
156
+ if (!Number.isFinite(overrides.gasMultiplier) || overrides.gasMultiplier < 1) throw new ManifestMCPError("INVALID_CONFIG", `gasMultiplier must be a finite number >= 1, got ${overrides.gasMultiplier}`);
157
157
  }
158
158
  const builder = getTxMsgBuilder(module);
159
159
  const buildContext = await withRetry(() => loadBuildContext(clientManager, module, subcommand), {
@@ -189,7 +189,7 @@ async function cosmosEstimateFee(clientManager, module, subcommand, args = [], o
189
189
  });
190
190
  throw error;
191
191
  }
192
- throw new ManifestMCPError(ManifestMCPErrorCode.SIMULATION_FAILED, `Fee estimation for ${module} ${subcommand} failed: ${error instanceof Error ? error.message : String(error)}`, {
192
+ throw new ManifestMCPError("SIMULATION_FAILED", `Fee estimation for ${module} ${subcommand} failed: ${error instanceof Error ? error.message : String(error)}`, {
193
193
  module,
194
194
  subcommand,
195
195
  args
@@ -1 +1 @@
1
- {"version":3,"file":"cosmos.js","names":[],"sources":["../src/cosmos.ts"],"sourcesContent":["import { calculateFee } from '@cosmjs/stargate';\nimport type { CosmosClientManager } from './client.js';\nimport { DEFAULT_GAS_MULTIPLIER } from './config.js';\nimport {\n getQueryHandler,\n getTxContextLoader,\n getTxHandler,\n getTxMsgBuilder,\n} from './modules.js';\nimport { withRetry } from './retry.js';\nimport {\n type CosmosQueryResult,\n type CosmosTxResult,\n type FeeEstimateResult,\n ManifestMCPError,\n ManifestMCPErrorCode,\n type TxBuildContext,\n type TxOptions,\n type TxOverrides,\n} from './types.js';\n\n// Validation pattern for module/subcommand names (alphanumeric, hyphens, underscores)\n// First character must not be a hyphen to prevent potential issues\nconst VALID_NAME_PATTERN = /^[a-zA-Z0-9_][a-zA-Z0-9_-]*$/;\n\n/**\n * Resolve and run the `TxBuildContext` loader registered for `(module,\n * subcommand)` in `TX_MODULES`. Returns `undefined` when no loader is\n * registered (the common case) so the caller can short-circuit and skip the\n * chain read.\n *\n * Acquires a rate-limit token before the loader runs so each extra RPC is\n * counted against the same budget every other RPC respects, and wraps any\n * non-`ManifestMCPError` failure as `QUERY_FAILED` with `{module, subcommand}`\n * details for symmetric error classification on both broadcast and estimate\n * paths.\n */\nasync function loadBuildContext(\n clientManager: CosmosClientManager,\n module: string,\n subcommand: string,\n): Promise<TxBuildContext | undefined> {\n const loader = getTxContextLoader(module, subcommand);\n if (!loader) return undefined;\n\n // The full loader call sequence — rate-limit acquire, query-client\n // construction, loader invocation — runs inside the try/catch so every\n // failure mode gets the {module, subcommand} attribution callers expect\n // from a structured error. Without the wrap, an INVALID_CONFIG from\n // `getQueryClient` (or a connection failure that escapes the inner\n // withRetry) would propagate without telling the caller which tx was\n // being prepared.\n try {\n await clientManager.acquireRateLimit();\n const queryClient = await clientManager.getQueryClient();\n return await loader(queryClient);\n } catch (error) {\n if (error instanceof ManifestMCPError) {\n if (!error.details?.module) {\n throw new ManifestMCPError(error.code, error.message, {\n ...error.details,\n module,\n subcommand,\n });\n }\n throw error;\n }\n throw new ManifestMCPError(\n ManifestMCPErrorCode.QUERY_FAILED,\n `Failed to load build context for ${module} ${subcommand}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { module, subcommand },\n );\n }\n}\n\n/**\n * Validate that a string is safe for use as a module or subcommand name.\n * Uses the appropriate UNSUPPORTED_QUERY or UNSUPPORTED_TX code so that\n * the error is immediately classified as non-retryable.\n */\nfunction validateName(\n name: string,\n field: string,\n errorCode: ManifestMCPErrorCode,\n): void {\n if (!name || !VALID_NAME_PATTERN.test(name)) {\n throw new ManifestMCPError(\n errorCode,\n `Invalid ${field}: \"${name}\". Only alphanumeric characters, hyphens, and underscores are allowed.`,\n );\n }\n}\n\n/**\n * Execute a Cosmos query via manifestjs RPC client\n *\n * Automatically retries on transient failures (network errors, timeouts, 5xx)\n * with exponential backoff. Configure retry behavior via `config.retry`.\n */\nexport async function cosmosQuery(\n clientManager: CosmosClientManager,\n module: string,\n subcommand: string,\n args: string[] = [],\n): Promise<CosmosQueryResult> {\n validateName(module, 'module', ManifestMCPErrorCode.UNSUPPORTED_QUERY);\n validateName(\n subcommand,\n 'subcommand',\n ManifestMCPErrorCode.UNSUPPORTED_QUERY,\n );\n\n // Get handler from registry (throws if module not found) - do this before retry loop\n const handler = getQueryHandler(module);\n\n return withRetry(\n async () => {\n // The rate-limit + query-client acquisition runs inside the try/catch\n // so a failure during either step is wrapped with {module, subcommand}\n // attribution, matching the handler-leg semantics. Otherwise an\n // INVALID_CONFIG from `getQueryClient` (or a connection failure that\n // escapes the inner withRetry) would propagate without telling the\n // caller which query was being routed.\n try {\n await clientManager.acquireRateLimit();\n const queryClient = await clientManager.getQueryClient();\n const result = await handler(queryClient, subcommand, args);\n\n return {\n module,\n subcommand,\n result,\n };\n } catch (error) {\n if (error instanceof ManifestMCPError) {\n if (!error.details?.module) {\n throw new ManifestMCPError(error.code, error.message, {\n ...error.details,\n module,\n subcommand,\n });\n }\n throw error;\n }\n throw new ManifestMCPError(\n ManifestMCPErrorCode.QUERY_FAILED,\n `Query ${module} ${subcommand} failed: ${error instanceof Error ? error.message : String(error)}`,\n { module, subcommand },\n );\n }\n },\n {\n config: clientManager.getConfig().retry,\n operationName: `query ${module} ${subcommand}`,\n },\n );\n}\n\n/**\n * Execute a Cosmos transaction via manifestjs signing client\n *\n * Automatically retries on transient failures (network errors, timeouts, 5xx)\n * with exponential backoff. Configure retry behavior via `config.retry`.\n *\n * Note: Only network-level failures are retried. Transaction validation errors\n * (insufficient funds, invalid args, etc.) are not retried as they won't succeed.\n */\nexport async function cosmosTx(\n clientManager: CosmosClientManager,\n module: string,\n subcommand: string,\n args: string[] = [],\n waitForConfirmation: boolean = false,\n overrides?: TxOverrides,\n): Promise<CosmosTxResult> {\n validateName(module, 'module', ManifestMCPErrorCode.UNSUPPORTED_TX);\n validateName(subcommand, 'subcommand', ManifestMCPErrorCode.UNSUPPORTED_TX);\n\n // Build fully-resolved gas options from caller overrides + server config\n let txOptions: TxOptions | undefined;\n if (overrides?.gasMultiplier !== undefined) {\n if (\n !Number.isFinite(overrides.gasMultiplier) ||\n overrides.gasMultiplier < 1\n ) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `gasMultiplier must be a finite number >= 1, got ${overrides.gasMultiplier}`,\n );\n }\n const gasPrice = clientManager.getConfig().gasPrice;\n if (!gasPrice) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'gasMultiplier override requires gasPrice configuration',\n );\n }\n txOptions = { gasMultiplier: overrides.gasMultiplier, gasPrice };\n }\n\n // Get handler from registry (throws if module not found) - do this before retry loop\n const handler = getTxHandler(module);\n // Fetch chain context once before the broadcast retry loop: every broadcast\n // attempt uses the same snapshot and we don't consume extra rate-limit\n // tokens per broadcast retry. The loader is independently wrapped in its\n // own withRetry so transient LCD failures during the chain read still get\n // retried (parity with cosmosQuery's params reads).\n const buildContext = await withRetry(\n () => loadBuildContext(clientManager, module, subcommand),\n {\n config: clientManager.getConfig().retry,\n operationName: `load-context ${module} ${subcommand}`,\n },\n );\n\n return withRetry(\n async () => {\n // The rate-limit + signing-client + address acquisition runs inside\n // the try/catch so a failure during any of those steps is wrapped\n // with {module, subcommand, args} attribution, matching the\n // handler-leg semantics. Otherwise an INVALID_CONFIG / wallet error\n // from these calls would propagate without telling the caller which\n // tx was being prepared.\n try {\n await clientManager.acquireRateLimit();\n const signingClient = await clientManager.getSigningClient();\n const senderAddress = await clientManager.getAddress();\n\n return await handler(\n signingClient,\n senderAddress,\n subcommand,\n args,\n waitForConfirmation,\n txOptions,\n buildContext,\n );\n } catch (error) {\n if (error instanceof ManifestMCPError) {\n // Re-throw with enriched context if not already present\n if (!error.details?.module) {\n throw new ManifestMCPError(error.code, error.message, {\n ...error.details,\n module,\n subcommand,\n args,\n });\n }\n throw error;\n }\n throw new ManifestMCPError(\n ManifestMCPErrorCode.TX_FAILED,\n `Tx ${module} ${subcommand} failed: ${error instanceof Error ? error.message : String(error)}`,\n { module, subcommand, args },\n );\n }\n },\n {\n config: clientManager.getConfig().retry,\n operationName: `tx ${module} ${subcommand}`,\n },\n );\n}\n\n/**\n * Estimate the fee for a Cosmos transaction without broadcasting it.\n *\n * Looks up the message builder for the given module, builds the messages,\n * and calls `client.simulate()` to get a gas estimate. Multiplies by the\n * configured (or overridden) gas multiplier and computes the fee.\n *\n * Automatically retries on transient failures via `withRetry`.\n *\n * @returns FeeEstimateResult with raw gas estimate and computed fee\n */\nexport async function cosmosEstimateFee(\n clientManager: CosmosClientManager,\n module: string,\n subcommand: string,\n args: string[] = [],\n overrides?: TxOverrides,\n): Promise<FeeEstimateResult> {\n validateName(module, 'module', ManifestMCPErrorCode.UNSUPPORTED_TX);\n validateName(subcommand, 'subcommand', ManifestMCPErrorCode.UNSUPPORTED_TX);\n\n // Always need gasPrice for fee calculation (unlike cosmosTx which can use 'auto')\n const config = clientManager.getConfig();\n const gasPrice = config.gasPrice;\n if (!gasPrice) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'Fee estimation requires gasPrice configuration',\n );\n }\n\n // Validate the override eagerly (the resolved fallback values are always valid).\n if (overrides?.gasMultiplier !== undefined) {\n if (\n !Number.isFinite(overrides.gasMultiplier) ||\n overrides.gasMultiplier < 1\n ) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `gasMultiplier must be a finite number >= 1, got ${overrides.gasMultiplier}`,\n );\n }\n }\n\n // Get builder from registry (throws if module not found) - do this before retry loop\n const builder = getTxMsgBuilder(module);\n // Fetch chain context once before the simulate retry loop: every simulate\n // attempt uses the same snapshot and we don't consume extra rate-limit\n // tokens per simulate retry. The loader is independently wrapped in its\n // own withRetry so transient LCD failures during the chain read still get\n // retried (parity with cosmosQuery's params reads).\n const buildContext = await withRetry(\n () => loadBuildContext(clientManager, module, subcommand),\n {\n config: config.retry,\n operationName: `load-context ${module} ${subcommand}`,\n },\n );\n\n return withRetry(\n async () => {\n // The rate-limit + signing-client + address acquisition runs inside\n // the try/catch so a failure during any of those steps is wrapped\n // with {module, subcommand, args} attribution, matching the\n // handler-leg semantics. Otherwise an INVALID_CONFIG / wallet error\n // from these calls would propagate without telling the caller which\n // estimate was being computed.\n try {\n await clientManager.acquireRateLimit();\n const signingClient = await clientManager.getSigningClient();\n const senderAddress = await clientManager.getAddress();\n\n // Resolve gasMultiplier from the signing client when no override is provided.\n // This guarantees parity with cosmosTx's 'auto' path: client.ts patches the\n // signing client's defaultGasMultiplier to config.gasMultiplier; if that\n // patch fails (rare — only when CosmJS internals change), the client\n // falls back to CosmJS's built-in default. Reading from the client uses\n // the same value cosmosTx would.\n const clientMultiplier = (\n signingClient as unknown as { defaultGasMultiplier?: unknown }\n ).defaultGasMultiplier;\n const gasMultiplier =\n overrides?.gasMultiplier ??\n (typeof clientMultiplier === 'number'\n ? clientMultiplier\n : DEFAULT_GAS_MULTIPLIER);\n\n const built = builder(senderAddress, subcommand, args, buildContext);\n const gasEstimate = await signingClient.simulate(\n senderAddress,\n built.messages,\n built.memo,\n );\n const gasLimit = Math.ceil(gasEstimate * gasMultiplier);\n const fee = calculateFee(gasLimit, gasPrice);\n\n return {\n module,\n subcommand: built.canonicalSubcommand ?? subcommand,\n gasEstimate: String(gasEstimate),\n fee: { amount: fee.amount, gas: fee.gas },\n };\n } catch (error) {\n if (error instanceof ManifestMCPError) {\n // Re-throw with enriched context if not already present (mirrors cosmosTx)\n if (!error.details?.module) {\n throw new ManifestMCPError(error.code, error.message, {\n ...error.details,\n module,\n subcommand,\n args,\n });\n }\n throw error;\n }\n // SIMULATION_FAILED is NOT in NON_RETRYABLE_ERROR_CODES, so withRetry\n // will fall through to isTransientErrorMessage for message-based\n // classification. Transient errors (network/5xx) get retried; real\n // simulation failures (insufficient funds, etc) fail fast.\n throw new ManifestMCPError(\n ManifestMCPErrorCode.SIMULATION_FAILED,\n `Fee estimation for ${module} ${subcommand} failed: ${error instanceof Error ? error.message : String(error)}`,\n { module, subcommand, args },\n );\n }\n },\n {\n config: config.retry,\n operationName: `estimate ${module} ${subcommand}`,\n },\n );\n}\n"],"mappings":";;;;;;AAuBA,MAAM,qBAAqB;;;;;;;;;;;;;AAc3B,eAAe,iBACb,eACA,QACA,YACqC;CACrC,MAAM,SAAS,mBAAmB,QAAQ,WAAW;AACrD,KAAI,CAAC,OAAQ,QAAO,KAAA;AASpB,KAAI;AACF,QAAM,cAAc,kBAAkB;AAEtC,SAAO,MAAM,OADO,MAAM,cAAc,gBAAgB,CACxB;UACzB,OAAO;AACd,MAAI,iBAAiB,kBAAkB;AACrC,OAAI,CAAC,MAAM,SAAS,OAClB,OAAM,IAAI,iBAAiB,MAAM,MAAM,MAAM,SAAS;IACpD,GAAG,MAAM;IACT;IACA;IACD,CAAC;AAEJ,SAAM;;AAER,QAAM,IAAI,iBACR,qBAAqB,cACrB,oCAAoC,OAAO,GAAG,WAAW,IACvD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,IAExD;GAAE;GAAQ;GAAY,CACvB;;;;;;;;AASL,SAAS,aACP,MACA,OACA,WACM;AACN,KAAI,CAAC,QAAQ,CAAC,mBAAmB,KAAK,KAAK,CACzC,OAAM,IAAI,iBACR,WACA,WAAW,MAAM,KAAK,KAAK,wEAC5B;;;;;;;;AAUL,eAAsB,YACpB,eACA,QACA,YACA,OAAiB,EAAE,EACS;AAC5B,cAAa,QAAQ,UAAU,qBAAqB,kBAAkB;AACtE,cACE,YACA,cACA,qBAAqB,kBACtB;CAGD,MAAM,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B;GAC5D,MAAM,gBAAgB,MAAM,cAAc,YAAY;GAQtD,MAAM,mBACJ,cACA;GACF,MAAM,gBACJ,WAAW,kBACV,OAAO,qBAAqB,WACzB,mBAAA;GAGN,MAAM,QAAQ,QAAQ,eAAe,YAAY,MAAM,aAAa;GACpE,MAAM,cAAc,MAAM,cAAc,SACtC,eACA,MAAM,UACN,MAAM,KACP;GAED,MAAM,MAAM,aADK,KAAK,KAAK,cAAc,cAAc,EACpB,SAAS;AAE5C,UAAO;IACL;IACA,YAAY,MAAM,uBAAuB;IACzC,aAAa,OAAO,YAAY;IAChC,KAAK;KAAE,QAAQ,IAAI;KAAQ,KAAK,IAAI;KAAK;IAC1C;WACM,OAAO;AACd,OAAI,iBAAiB,kBAAkB;AAErC,QAAI,CAAC,MAAM,SAAS,OAClB,OAAM,IAAI,iBAAiB,MAAM,MAAM,MAAM,SAAS;KACpD,GAAG,MAAM;KACT;KACA;KACA;KACD,CAAC;AAEJ,UAAM;;AAMR,SAAM,IAAI,iBACR,qBAAqB,mBACrB,sBAAsB,OAAO,GAAG,WAAW,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,IAC5G;IAAE;IAAQ;IAAY;IAAM,CAC7B;;IAGL;EACE,QAAQ,OAAO;EACf,eAAe,YAAY,OAAO,GAAG;EACtC,CACF"}
1
+ {"version":3,"file":"cosmos.js","names":[],"sources":["../src/cosmos.ts"],"sourcesContent":["import { calculateFee } from '@cosmjs/stargate';\nimport type { CosmosClientManager } from './client.js';\nimport { DEFAULT_GAS_MULTIPLIER } from './config.js';\nimport {\n getQueryHandler,\n getTxContextLoader,\n getTxHandler,\n getTxMsgBuilder,\n} from './modules.js';\nimport { withRetry } from './retry.js';\nimport {\n type CosmosQueryResult,\n type CosmosTxResult,\n type FeeEstimateResult,\n ManifestMCPError,\n ManifestMCPErrorCode,\n type TxBuildContext,\n type TxOptions,\n type TxOverrides,\n} from './types.js';\n\n// Validation pattern for module/subcommand names (alphanumeric, hyphens, underscores)\n// First character must not be a hyphen to prevent potential issues\nconst VALID_NAME_PATTERN = /^[a-zA-Z0-9_][a-zA-Z0-9_-]*$/;\n\n/**\n * Resolve and run the `TxBuildContext` loader registered for `(module,\n * subcommand)` in `TX_MODULES`. Returns `undefined` when no loader is\n * registered (the common case) so the caller can short-circuit and skip the\n * chain read.\n *\n * Acquires a rate-limit token before the loader runs so each extra RPC is\n * counted against the same budget every other RPC respects, and wraps any\n * non-`ManifestMCPError` failure as `QUERY_FAILED` with `{module, subcommand}`\n * details for symmetric error classification on both broadcast and estimate\n * paths.\n */\nasync function loadBuildContext(\n clientManager: CosmosClientManager,\n module: string,\n subcommand: string,\n): Promise<TxBuildContext | undefined> {\n const loader = getTxContextLoader(module, subcommand);\n if (!loader) return undefined;\n\n // The full loader call sequence — rate-limit acquire, query-client\n // construction, loader invocation — runs inside the try/catch so every\n // failure mode gets the {module, subcommand} attribution callers expect\n // from a structured error. Without the wrap, an INVALID_CONFIG from\n // `getQueryClient` (or a connection failure that escapes the inner\n // withRetry) would propagate without telling the caller which tx was\n // being prepared.\n try {\n await clientManager.acquireRateLimit();\n const queryClient = await clientManager.getQueryClient();\n return await loader(queryClient);\n } catch (error) {\n if (error instanceof ManifestMCPError) {\n if (!error.details?.module) {\n throw new ManifestMCPError(error.code, error.message, {\n ...error.details,\n module,\n subcommand,\n });\n }\n throw error;\n }\n throw new ManifestMCPError(\n ManifestMCPErrorCode.QUERY_FAILED,\n `Failed to load build context for ${module} ${subcommand}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { module, subcommand },\n );\n }\n}\n\n/**\n * Validate that a string is safe for use as a module or subcommand name.\n * Uses the appropriate UNSUPPORTED_QUERY or UNSUPPORTED_TX code so that\n * the error is immediately classified as non-retryable.\n */\nfunction validateName(\n name: string,\n field: string,\n errorCode: ManifestMCPErrorCode,\n): void {\n if (!name || !VALID_NAME_PATTERN.test(name)) {\n throw new ManifestMCPError(\n errorCode,\n `Invalid ${field}: \"${name}\". Only alphanumeric characters, hyphens, and underscores are allowed.`,\n );\n }\n}\n\n/**\n * Execute a Cosmos query via manifestjs RPC client\n *\n * Automatically retries on transient failures (network errors, timeouts, 5xx)\n * with exponential backoff. Configure retry behavior via `config.retry`.\n */\nexport async function cosmosQuery(\n clientManager: CosmosClientManager,\n module: string,\n subcommand: string,\n args: string[] = [],\n): Promise<CosmosQueryResult> {\n validateName(module, 'module', ManifestMCPErrorCode.UNSUPPORTED_QUERY);\n validateName(\n subcommand,\n 'subcommand',\n ManifestMCPErrorCode.UNSUPPORTED_QUERY,\n );\n\n // Get handler from registry (throws if module not found) - do this before retry loop\n const handler = getQueryHandler(module);\n\n return withRetry(\n async () => {\n // The rate-limit + query-client acquisition runs inside the try/catch\n // so a failure during either step is wrapped with {module, subcommand}\n // attribution, matching the handler-leg semantics. Otherwise an\n // INVALID_CONFIG from `getQueryClient` (or a connection failure that\n // escapes the inner withRetry) would propagate without telling the\n // caller which query was being routed.\n try {\n await clientManager.acquireRateLimit();\n const queryClient = await clientManager.getQueryClient();\n const result = await handler(queryClient, subcommand, args);\n\n return {\n module,\n subcommand,\n result,\n };\n } catch (error) {\n if (error instanceof ManifestMCPError) {\n if (!error.details?.module) {\n throw new ManifestMCPError(error.code, error.message, {\n ...error.details,\n module,\n subcommand,\n });\n }\n throw error;\n }\n throw new ManifestMCPError(\n ManifestMCPErrorCode.QUERY_FAILED,\n `Query ${module} ${subcommand} failed: ${error instanceof Error ? error.message : String(error)}`,\n { module, subcommand },\n );\n }\n },\n {\n config: clientManager.getConfig().retry,\n operationName: `query ${module} ${subcommand}`,\n },\n );\n}\n\n/**\n * Execute a Cosmos transaction via manifestjs signing client\n *\n * Automatically retries on transient failures (network errors, timeouts, 5xx)\n * with exponential backoff. Configure retry behavior via `config.retry`.\n *\n * Note: Only network-level failures are retried. Transaction validation errors\n * (insufficient funds, invalid args, etc.) are not retried as they won't succeed.\n */\nexport async function cosmosTx(\n clientManager: CosmosClientManager,\n module: string,\n subcommand: string,\n args: string[] = [],\n waitForConfirmation: boolean = false,\n overrides?: TxOverrides,\n): Promise<CosmosTxResult> {\n validateName(module, 'module', ManifestMCPErrorCode.UNSUPPORTED_TX);\n validateName(subcommand, 'subcommand', ManifestMCPErrorCode.UNSUPPORTED_TX);\n\n // Build fully-resolved gas options from caller overrides + server config\n let txOptions: TxOptions | undefined;\n if (overrides?.gasMultiplier !== undefined) {\n if (\n !Number.isFinite(overrides.gasMultiplier) ||\n overrides.gasMultiplier < 1\n ) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `gasMultiplier must be a finite number >= 1, got ${overrides.gasMultiplier}`,\n );\n }\n const gasPrice = clientManager.getConfig().gasPrice;\n if (!gasPrice) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'gasMultiplier override requires gasPrice configuration',\n );\n }\n txOptions = { gasMultiplier: overrides.gasMultiplier, gasPrice };\n }\n\n // Get handler from registry (throws if module not found) - do this before retry loop\n const handler = getTxHandler(module);\n // Fetch chain context once before the broadcast retry loop: every broadcast\n // attempt uses the same snapshot and we don't consume extra rate-limit\n // tokens per broadcast retry. The loader is independently wrapped in its\n // own withRetry so transient LCD failures during the chain read still get\n // retried (parity with cosmosQuery's params reads).\n const buildContext = await withRetry(\n () => loadBuildContext(clientManager, module, subcommand),\n {\n config: clientManager.getConfig().retry,\n operationName: `load-context ${module} ${subcommand}`,\n },\n );\n\n return withRetry(\n async () => {\n // The rate-limit + signing-client + address acquisition runs inside\n // the try/catch so a failure during any of those steps is wrapped\n // with {module, subcommand, args} attribution, matching the\n // handler-leg semantics. Otherwise an INVALID_CONFIG / wallet error\n // from these calls would propagate without telling the caller which\n // tx was being prepared.\n try {\n await clientManager.acquireRateLimit();\n const signingClient = await clientManager.getSigningClient();\n const senderAddress = await clientManager.getAddress();\n\n return await handler(\n signingClient,\n senderAddress,\n subcommand,\n args,\n waitForConfirmation,\n txOptions,\n buildContext,\n );\n } catch (error) {\n if (error instanceof ManifestMCPError) {\n // Re-throw with enriched context if not already present\n if (!error.details?.module) {\n throw new ManifestMCPError(error.code, error.message, {\n ...error.details,\n module,\n subcommand,\n args,\n });\n }\n throw error;\n }\n throw new ManifestMCPError(\n ManifestMCPErrorCode.TX_FAILED,\n `Tx ${module} ${subcommand} failed: ${error instanceof Error ? error.message : String(error)}`,\n { module, subcommand, args },\n );\n }\n },\n {\n config: clientManager.getConfig().retry,\n operationName: `tx ${module} ${subcommand}`,\n },\n );\n}\n\n/**\n * Estimate the fee for a Cosmos transaction without broadcasting it.\n *\n * Looks up the message builder for the given module, builds the messages,\n * and calls `client.simulate()` to get a gas estimate. Multiplies by the\n * configured (or overridden) gas multiplier and computes the fee.\n *\n * Automatically retries on transient failures via `withRetry`.\n *\n * @returns FeeEstimateResult with raw gas estimate and computed fee\n */\nexport async function cosmosEstimateFee(\n clientManager: CosmosClientManager,\n module: string,\n subcommand: string,\n args: string[] = [],\n overrides?: TxOverrides,\n): Promise<FeeEstimateResult> {\n validateName(module, 'module', ManifestMCPErrorCode.UNSUPPORTED_TX);\n validateName(subcommand, 'subcommand', ManifestMCPErrorCode.UNSUPPORTED_TX);\n\n // Always need gasPrice for fee calculation (unlike cosmosTx which can use 'auto')\n const config = clientManager.getConfig();\n const gasPrice = config.gasPrice;\n if (!gasPrice) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'Fee estimation requires gasPrice configuration',\n );\n }\n\n // Validate the override eagerly (the resolved fallback values are always valid).\n if (overrides?.gasMultiplier !== undefined) {\n if (\n !Number.isFinite(overrides.gasMultiplier) ||\n overrides.gasMultiplier < 1\n ) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `gasMultiplier must be a finite number >= 1, got ${overrides.gasMultiplier}`,\n );\n }\n }\n\n // Get builder from registry (throws if module not found) - do this before retry loop\n const builder = getTxMsgBuilder(module);\n // Fetch chain context once before the simulate retry loop: every simulate\n // attempt uses the same snapshot and we don't consume extra rate-limit\n // tokens per simulate retry. The loader is independently wrapped in its\n // own withRetry so transient LCD failures during the chain read still get\n // retried (parity with cosmosQuery's params reads).\n const buildContext = await withRetry(\n () => loadBuildContext(clientManager, module, subcommand),\n {\n config: config.retry,\n operationName: `load-context ${module} ${subcommand}`,\n },\n );\n\n return withRetry(\n async () => {\n // The rate-limit + signing-client + address acquisition runs inside\n // the try/catch so a failure during any of those steps is wrapped\n // with {module, subcommand, args} attribution, matching the\n // handler-leg semantics. Otherwise an INVALID_CONFIG / wallet error\n // from these calls would propagate without telling the caller which\n // estimate was being computed.\n try {\n await clientManager.acquireRateLimit();\n const signingClient = await clientManager.getSigningClient();\n const senderAddress = await clientManager.getAddress();\n\n // Resolve gasMultiplier from the signing client when no override is provided.\n // This guarantees parity with cosmosTx's 'auto' path: client.ts patches the\n // signing client's defaultGasMultiplier to config.gasMultiplier; if that\n // patch fails (rare — only when CosmJS internals change), the client\n // falls back to CosmJS's built-in default. Reading from the client uses\n // the same value cosmosTx would.\n const clientMultiplier = (\n signingClient as unknown as { defaultGasMultiplier?: unknown }\n ).defaultGasMultiplier;\n const gasMultiplier =\n overrides?.gasMultiplier ??\n (typeof clientMultiplier === 'number'\n ? clientMultiplier\n : DEFAULT_GAS_MULTIPLIER);\n\n const built = builder(senderAddress, subcommand, args, buildContext);\n const gasEstimate = await signingClient.simulate(\n senderAddress,\n built.messages,\n built.memo,\n );\n const gasLimit = Math.ceil(gasEstimate * gasMultiplier);\n const fee = calculateFee(gasLimit, gasPrice);\n\n return {\n module,\n subcommand: built.canonicalSubcommand ?? subcommand,\n gasEstimate: String(gasEstimate),\n fee: { amount: fee.amount, gas: fee.gas },\n };\n } catch (error) {\n if (error instanceof ManifestMCPError) {\n // Re-throw with enriched context if not already present (mirrors cosmosTx)\n if (!error.details?.module) {\n throw new ManifestMCPError(error.code, error.message, {\n ...error.details,\n module,\n subcommand,\n args,\n });\n }\n throw error;\n }\n // SIMULATION_FAILED is NOT in NON_RETRYABLE_ERROR_CODES, so withRetry\n // will fall through to isTransientErrorMessage for message-based\n // classification. Transient errors (network/5xx) get retried; real\n // simulation failures (insufficient funds, etc) fail fast.\n throw new ManifestMCPError(\n ManifestMCPErrorCode.SIMULATION_FAILED,\n `Fee estimation for ${module} ${subcommand} failed: ${error instanceof Error ? error.message : String(error)}`,\n { module, subcommand, args },\n );\n }\n },\n {\n config: config.retry,\n operationName: `estimate ${module} ${subcommand}`,\n },\n );\n}\n"],"mappings":";;;;;;AAuBA,MAAM,qBAAqB;;;;;;;;;;;;;AAc3B,eAAe,iBACb,eACA,QACA,YACqC;CACrC,MAAM,SAAS,mBAAmB,QAAQ,WAAW;AACrD,KAAI,CAAC,OAAQ,QAAO,KAAA;AASpB,KAAI;AACF,QAAM,cAAc,kBAAkB;AAEtC,SAAO,MAAM,OAAO,MADM,cAAc,gBAAgB,CACxB;UACzB,OAAO;AACd,MAAI,iBAAiB,kBAAkB;AACrC,OAAI,CAAC,MAAM,SAAS,OAClB,OAAM,IAAI,iBAAiB,MAAM,MAAM,MAAM,SAAS;IACpD,GAAG,MAAM;IACT;IACA;IACD,CAAC;AAEJ,SAAM;;AAER,QAAM,IAAI,iBAAA,gBAER,oCAAoC,OAAO,GAAG,WAAW,IACvD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,IAExD;GAAE;GAAQ;GAAY,CACvB;;;;;;;;AASL,SAAS,aACP,MACA,OACA,WACM;AACN,KAAI,CAAC,QAAQ,CAAC,mBAAmB,KAAK,KAAK,CACzC,OAAM,IAAI,iBACR,WACA,WAAW,MAAM,KAAK,KAAK,wEAC5B;;;;;;;;AAUL,eAAsB,YACpB,eACA,QACA,YACA,OAAiB,EAAE,EACS;AAC5B,cAAa,QAAQ,UAAA,oBAAiD;AACtE,cACE,YACA,cAAA,oBAED;CAGD,MAAM,UAAU,gBAAgB,OAAO;AAEvC,QAAO,UACL,YAAY;AAOV,MAAI;AACF,SAAM,cAAc,kBAAkB;AAItC,UAAO;IACL;IACA;IACA,QAA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