@manifest-network/manifest-mcp-core 0.6.2 → 0.8.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.
- package/README.md +4 -1
- package/dist/__test-utils__/callTool.d.ts +1 -0
- package/dist/__test-utils__/callTool.d.ts.map +1 -1
- package/dist/__test-utils__/callTool.js.map +1 -1
- package/dist/client.d.ts +5 -2
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +16 -5
- package/dist/client.js.map +1 -1
- package/dist/cosmos.d.ts.map +1 -1
- package/dist/cosmos.js +64 -16
- package/dist/cosmos.js.map +1 -1
- package/dist/index.d.ts +6 -4
- package/dist/index.js +5 -3
- package/dist/lcd-adapter.d.ts.map +1 -1
- package/dist/lcd-adapter.js +22 -3
- package/dist/lcd-adapter.js.map +1 -1
- package/dist/logger.d.ts +8 -3
- package/dist/logger.d.ts.map +1 -1
- package/dist/logger.js +12 -7
- package/dist/logger.js.map +1 -1
- package/dist/modules.d.ts +28 -5
- package/dist/modules.d.ts.map +1 -1
- package/dist/modules.js +282 -4
- package/dist/modules.js.map +1 -1
- package/dist/queries/authz.d.ts +15 -0
- package/dist/queries/authz.d.ts.map +1 -0
- package/dist/queries/authz.js +62 -0
- package/dist/queries/authz.js.map +1 -0
- package/dist/queries/billing.d.ts +2 -2
- package/dist/queries/billing.d.ts.map +1 -1
- package/dist/queries/billing.js +12 -0
- package/dist/queries/billing.js.map +1 -1
- package/dist/queries/feegrant.d.ts +15 -0
- package/dist/queries/feegrant.d.ts.map +1 -0
- package/dist/queries/feegrant.js +52 -0
- package/dist/queries/feegrant.js.map +1 -0
- package/dist/queries/ibc-transfer.d.ts +13 -0
- package/dist/queries/ibc-transfer.d.ts.map +1 -0
- package/dist/queries/ibc-transfer.js +30 -0
- package/dist/queries/ibc-transfer.js.map +1 -0
- package/dist/queries/index.d.ts +7 -1
- package/dist/queries/index.js +7 -1
- package/dist/queries/mint.d.ts +13 -0
- package/dist/queries/mint.d.ts.map +1 -0
- package/dist/queries/mint.js +28 -0
- package/dist/queries/mint.js.map +1 -0
- package/dist/queries/poa.d.ts +13 -0
- package/dist/queries/poa.d.ts.map +1 -0
- package/dist/queries/poa.js +23 -0
- package/dist/queries/poa.js.map +1 -0
- package/dist/queries/tokenfactory.d.ts +13 -0
- package/dist/queries/tokenfactory.d.ts.map +1 -0
- package/dist/queries/tokenfactory.js +32 -0
- package/dist/queries/tokenfactory.js.map +1 -0
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +1 -4
- package/dist/retry.js.map +1 -1
- package/dist/server-utils.d.ts +15 -1
- package/dist/server-utils.d.ts.map +1 -1
- package/dist/server-utils.js +25 -1
- package/dist/server-utils.js.map +1 -1
- package/dist/tool-metadata.d.ts +93 -0
- package/dist/tool-metadata.d.ts.map +1 -0
- package/dist/tool-metadata.js +93 -0
- package/dist/tool-metadata.js.map +1 -0
- package/dist/tools/setItemCustomDomain.d.ts +51 -0
- package/dist/tools/setItemCustomDomain.d.ts.map +1 -0
- package/dist/tools/setItemCustomDomain.js +45 -0
- package/dist/tools/setItemCustomDomain.js.map +1 -0
- package/dist/transactions/authz.d.ts +15 -0
- package/dist/transactions/authz.d.ts.map +1 -0
- package/dist/transactions/authz.js +121 -0
- package/dist/transactions/authz.js.map +1 -0
- package/dist/transactions/billing.d.ts +26 -4
- package/dist/transactions/billing.d.ts.map +1 -1
- package/dist/transactions/billing.js +78 -9
- package/dist/transactions/billing.js.map +1 -1
- package/dist/transactions/feegrant.d.ts +15 -0
- package/dist/transactions/feegrant.d.ts.map +1 -0
- package/dist/transactions/feegrant.js +75 -0
- package/dist/transactions/feegrant.js.map +1 -0
- package/dist/transactions/ibc-transfer.d.ts +15 -0
- package/dist/transactions/ibc-transfer.d.ts.map +1 -0
- package/dist/transactions/ibc-transfer.js +94 -0
- package/dist/transactions/ibc-transfer.js.map +1 -0
- package/dist/transactions/index.d.ts +4 -1
- package/dist/transactions/index.js +4 -1
- package/dist/transactions/json-schemas.d.ts +78 -0
- package/dist/transactions/json-schemas.d.ts.map +1 -0
- package/dist/transactions/json-schemas.js +134 -0
- package/dist/transactions/json-schemas.js.map +1 -0
- package/dist/transactions/poa.d.ts +19 -0
- package/dist/transactions/poa.d.ts.map +1 -0
- package/dist/transactions/poa.js +130 -0
- package/dist/transactions/poa.js.map +1 -0
- package/dist/transactions/tokenfactory.d.ts +15 -0
- package/dist/transactions/tokenfactory.d.ts.map +1 -0
- package/dist/transactions/tokenfactory.js +138 -0
- package/dist/transactions/tokenfactory.js.map +1 -0
- package/dist/transactions/utils.d.ts +30 -1
- package/dist/transactions/utils.d.ts.map +1 -1
- package/dist/transactions/utils.js +44 -1
- package/dist/transactions/utils.js.map +1 -1
- package/dist/types.d.ts +85 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +0 -3
- package/dist/types.js.map +1 -1
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@ npm install @manifest-network/manifest-mcp-core
|
|
|
17
17
|
- **On-chain tool functions** (`tools/`) -- `getBalance`, `fundCredits`, `stopApp` (used by the lease package)
|
|
18
18
|
- **Server utilities** (`server-utils.ts`) -- `withErrorHandling`, `jsonResponse`, `bigIntReplacer`, `sanitizeForLogging`
|
|
19
19
|
- **Wallet providers** (`wallet/`) -- `MnemonicWalletProvider` (BIP-39), `signArbitraryWithAmino` (ADR-036)
|
|
20
|
-
- **Logger** (`logger.ts`) -- Leveled logger (stderr output
|
|
20
|
+
- **Logger** (`logger.ts`) -- Leveled logger (stderr output; defaults to `warn`, configurable via `logger.setLevel()`; the node package's bootstrap reads `LOG_LEVEL` and applies it)
|
|
21
21
|
- **Retry** (`retry.ts`) -- Exponential backoff with transient/permanent error classification
|
|
22
22
|
- **Validation** (`validation.ts`) -- Input validation helpers (`requireString`, `requireUuid`, `parseArgs`, etc.)
|
|
23
23
|
|
|
@@ -33,6 +33,9 @@ npm install @manifest-network/manifest-mcp-core
|
|
|
33
33
|
| sku | yes | yes |
|
|
34
34
|
| group | yes | yes |
|
|
35
35
|
| wasm | yes | yes |
|
|
36
|
+
| poa | yes | yes |
|
|
37
|
+
| tokenfactory | yes | yes |
|
|
38
|
+
| ibc-transfer | yes | yes |
|
|
36
39
|
| auth | yes | -- |
|
|
37
40
|
| manifest | -- | yes |
|
|
38
41
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"callTool.d.ts","names":[],"sources":["../../src/__test-utils__/callTool.ts"],"mappings":";;;;UAIiB,UAAA;EACf,OAAA,EAAS,KAAA;IAAQ,IAAA;IAAc,IAAA;EAAA;EAC/B,OAAA;AAAA;;;;;;;
|
|
1
|
+
{"version":3,"file":"callTool.d.ts","names":[],"sources":["../../src/__test-utils__/callTool.ts"],"mappings":";;;;UAIiB,UAAA;EACf,OAAA,EAAS,KAAA;IAAQ,IAAA;IAAc,IAAA;EAAA;EAC/B,OAAA;EACA,iBAAA,GAAoB,MAAA;AAAA;;;;;;;;AAiBtB;;;;;;;iBAAsB,QAAA,CACpB,MAAA,EAAQ,MAAA,EACR,QAAA,UACA,SAAA,GAAW,MAAA,mBACX,gBAAA,GAAkB,iBAAA,KACjB,OAAA,CAAQ,UAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"callTool.js","names":[],"sources":["../../src/__test-utils__/callTool.ts"],"sourcesContent":["import { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';\nimport type { Server } from '@modelcontextprotocol/sdk/server/index.js';\n\nexport interface ToolResult {\n content: Array<{ type: string; text: string }>;\n isError?: boolean;\n}\n\n/**\n * Shared test helper: connects an MCP client to a server via in-memory\n * transport, calls the given tool, then cleans up both transports.\n *\n * Cleanup always runs via the `finally` block: client and both transports\n * are closed, then removed from `activeTransports` to prevent double-close\n * in the caller's `afterEach`.\n *\n * @param server - The MCP `Server` instance (from `getServer()`)\n * @param toolName - Name of the tool to invoke\n * @param toolInput - Optional tool arguments\n * @param activeTransports - Optional mutable array; transports are added\n * before the call and removed after cleanup completes.\n */\nexport async function callTool(\n server: Server,\n toolName: string,\n toolInput: Record<string, unknown> = {},\n activeTransports: InMemoryTransport[] = [],\n): Promise<ToolResult> {\n const [clientTransport, serverTransport] =\n InMemoryTransport.createLinkedPair();\n activeTransports.push(clientTransport, serverTransport);\n\n const client = new Client({ name: 'test-client', version: '1.0.0' });\n\n try {\n await server.connect(serverTransport);\n await client.connect(clientTransport);\n\n return (await client.callTool({\n name: toolName,\n arguments: toolInput,\n })) as ToolResult;\n } finally {\n await client.close().catch(() => {});\n await clientTransport.close().catch(() => {});\n await serverTransport.close().catch(() => {});\n\n // Remove by identity so afterEach won't double-close\n for (const t of [clientTransport, serverTransport]) {\n const idx = activeTransports.indexOf(t);\n if (idx !== -1) activeTransports.splice(idx, 1);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"callTool.js","names":[],"sources":["../../src/__test-utils__/callTool.ts"],"sourcesContent":["import { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';\nimport type { Server } from '@modelcontextprotocol/sdk/server/index.js';\n\nexport interface ToolResult {\n content: Array<{ type: string; text: string }>;\n isError?: boolean;\n structuredContent?: Record<string, unknown>;\n}\n\n/**\n * Shared test helper: connects an MCP client to a server via in-memory\n * transport, calls the given tool, then cleans up both transports.\n *\n * Cleanup always runs via the `finally` block: client and both transports\n * are closed, then removed from `activeTransports` to prevent double-close\n * in the caller's `afterEach`.\n *\n * @param server - The MCP `Server` instance (from `getServer()`)\n * @param toolName - Name of the tool to invoke\n * @param toolInput - Optional tool arguments\n * @param activeTransports - Optional mutable array; transports are added\n * before the call and removed after cleanup completes.\n */\nexport async function callTool(\n server: Server,\n toolName: string,\n toolInput: Record<string, unknown> = {},\n activeTransports: InMemoryTransport[] = [],\n): Promise<ToolResult> {\n const [clientTransport, serverTransport] =\n InMemoryTransport.createLinkedPair();\n activeTransports.push(clientTransport, serverTransport);\n\n const client = new Client({ name: 'test-client', version: '1.0.0' });\n\n try {\n await server.connect(serverTransport);\n await client.connect(clientTransport);\n\n return (await client.callTool({\n name: toolName,\n arguments: toolInput,\n })) as ToolResult;\n } finally {\n await client.close().catch(() => {});\n await clientTransport.close().catch(() => {});\n await serverTransport.close().catch(() => {});\n\n // Remove by identity so afterEach won't double-close\n for (const t of [clientTransport, serverTransport]) {\n const idx = activeTransports.indexOf(t);\n if (idx !== -1) activeTransports.splice(idx, 1);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,eAAsB,SACpB,QACA,UACA,YAAqC,EAAE,EACvC,mBAAwC,EAAE,EACrB;CACrB,MAAM,CAAC,iBAAiB,mBACtB,kBAAkB,kBAAkB;AACtC,kBAAiB,KAAK,iBAAiB,gBAAgB;CAEvD,MAAM,SAAS,IAAI,OAAO;EAAE,MAAM;EAAe,SAAS;EAAS,CAAC;AAEpE,KAAI;AACF,QAAM,OAAO,QAAQ,gBAAgB;AACrC,QAAM,OAAO,QAAQ,gBAAgB;AAErC,SAAQ,MAAM,OAAO,SAAS;GAC5B,MAAM;GACN,WAAW;GACZ,CAAC;WACM;AACR,QAAM,OAAO,OAAO,CAAC,YAAY,GAAG;AACpC,QAAM,gBAAgB,OAAO,CAAC,YAAY,GAAG;AAC7C,QAAM,gBAAgB,OAAO,CAAC,YAAY,GAAG;AAG7C,OAAK,MAAM,KAAK,CAAC,iBAAiB,gBAAgB,EAAE;GAClD,MAAM,MAAM,iBAAiB,QAAQ,EAAE;AACvC,OAAI,QAAQ,GAAI,kBAAiB,OAAO,KAAK,EAAE"}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { ManifestMCPConfig, WalletProvider } from "./types.js";
|
|
2
2
|
import { SigningStargateClient } from "@cosmjs/stargate";
|
|
3
|
-
import { cosmwasm, liftedinit } from "@manifest-network/manifestjs";
|
|
3
|
+
import { cosmwasm, ibc, liftedinit, osmosis, strangelove_ventures } from "@manifest-network/manifestjs";
|
|
4
4
|
|
|
5
5
|
//#region src/client.d.ts
|
|
6
6
|
type LiftedinitQueryClient = Awaited<ReturnType<typeof liftedinit.ClientFactory.createRPCQueryClient>>;
|
|
7
7
|
type CosmwasmQueryClient = Awaited<ReturnType<typeof cosmwasm.ClientFactory.createRPCQueryClient>>;
|
|
8
|
-
type
|
|
8
|
+
type StrangeloveVenturesQueryClient = Awaited<ReturnType<typeof strangelove_ventures.ClientFactory.createRPCQueryClient>>;
|
|
9
|
+
type OsmosisQueryClient = Awaited<ReturnType<typeof osmosis.ClientFactory.createRPCQueryClient>>;
|
|
10
|
+
type IbcQueryClient = Awaited<ReturnType<typeof ibc.ClientFactory.createRPCQueryClient>>;
|
|
11
|
+
type ManifestQueryClient = LiftedinitQueryClient & Pick<CosmwasmQueryClient, 'cosmwasm'> & Pick<StrangeloveVenturesQueryClient, 'strangelove_ventures'> & Pick<OsmosisQueryClient, 'osmosis'> & Pick<IbcQueryClient, 'ibc'>;
|
|
9
12
|
/**
|
|
10
13
|
* Manages CosmJS client instances with lazy initialization and singleton pattern
|
|
11
14
|
*/
|
package/dist/client.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","names":[],"sources":["../src/client.ts"],"mappings":";;;;;
|
|
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,oBAAA;AAAA,KAEvC,cAAA,GAAiB,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,QAGA,kBAAA;EAAA,QACA,oBAAA;EAAA,QAED,WAAA,CAAA;;;;;;;;SAuBA,WAAA,CACL,MAAA,EAAQ,iBAAA,EACR,cAAA,EAAgB,cAAA,GACf,mBAAA;EAvGe;;;;EAAA,OA2JX,cAAA,CAAA;EAzJJ;;;;;EAqKG,cAAA,CAAA,GAAkB,OAAA,CAAQ,mBAAA;EArKW;;;;;EA4QrC,gBAAA,CAAA,GAAoB,OAAA,CAAQ,qBAAA;EA3QoB;;;EAkXhD,UAAA,CAAA,GAAc,OAAA;EAhXC;;;EAuXrB,SAAA,CAAA,GAAa,iBAAA;EAvXW;;;;EA+XlB,gBAAA,CAAA,GAAoB,OAAA;EA9XR;;;;;EAuYlB,UAAA,CAAA;AAAA"}
|
package/dist/client.js
CHANGED
|
@@ -5,7 +5,7 @@ import { logger } from "./logger.js";
|
|
|
5
5
|
import { createLCDQueryClient } from "./lcd-adapter.js";
|
|
6
6
|
import { Registry } from "@cosmjs/proto-signing";
|
|
7
7
|
import { AminoTypes, GasPrice, SigningStargateClient } from "@cosmjs/stargate";
|
|
8
|
-
import { cosmosAminoConverters, cosmosProtoRegistry, cosmwasm, cosmwasmAminoConverters, cosmwasmProtoRegistry, liftedinit, liftedinitAminoConverters, liftedinitProtoRegistry, osmosisAminoConverters, osmosisProtoRegistry, strangeloveVenturesAminoConverters, strangeloveVenturesProtoRegistry } from "@manifest-network/manifestjs";
|
|
8
|
+
import { cosmosAminoConverters, cosmosProtoRegistry, cosmwasm, cosmwasmAminoConverters, cosmwasmProtoRegistry, ibc, ibcAminoConverters, ibcProtoRegistry, liftedinit, liftedinitAminoConverters, liftedinitProtoRegistry, osmosis, osmosisAminoConverters, osmosisProtoRegistry, strangeloveVenturesAminoConverters, strangeloveVenturesProtoRegistry, strangelove_ventures } from "@manifest-network/manifestjs";
|
|
9
9
|
import { RateLimiter } from "limiter";
|
|
10
10
|
//#region src/client.ts
|
|
11
11
|
/** Default timeout for transaction broadcast (60 seconds) */
|
|
@@ -22,14 +22,16 @@ function getSigningManifestClientOptions() {
|
|
|
22
22
|
...liftedinitProtoRegistry,
|
|
23
23
|
...strangeloveVenturesProtoRegistry,
|
|
24
24
|
...osmosisProtoRegistry,
|
|
25
|
-
...cosmwasmProtoRegistry
|
|
25
|
+
...cosmwasmProtoRegistry,
|
|
26
|
+
...ibcProtoRegistry
|
|
26
27
|
]),
|
|
27
28
|
aminoTypes: new AminoTypes({
|
|
28
29
|
...cosmosAminoConverters,
|
|
29
30
|
...liftedinitAminoConverters,
|
|
30
31
|
...strangeloveVenturesAminoConverters,
|
|
31
32
|
...osmosisAminoConverters,
|
|
32
|
-
...cosmwasmAminoConverters
|
|
33
|
+
...cosmwasmAminoConverters,
|
|
34
|
+
...ibcAminoConverters
|
|
33
35
|
})
|
|
34
36
|
};
|
|
35
37
|
}
|
|
@@ -111,10 +113,19 @@ var CosmosClientManager = class CosmosClientManager {
|
|
|
111
113
|
operationName: "connect LCD query client"
|
|
112
114
|
});
|
|
113
115
|
else if (this.config.rpcUrl) client = await withRetry(async () => {
|
|
114
|
-
const [liftedinitClient, cosmwasmClient] = await Promise.all([
|
|
116
|
+
const [liftedinitClient, cosmwasmClient, strangeloveClient, osmosisClient, ibcClient] = await Promise.all([
|
|
117
|
+
liftedinit.ClientFactory.createRPCQueryClient({ rpcEndpoint: this.config.rpcUrl }),
|
|
118
|
+
cosmwasm.ClientFactory.createRPCQueryClient({ rpcEndpoint: this.config.rpcUrl }),
|
|
119
|
+
strangelove_ventures.ClientFactory.createRPCQueryClient({ rpcEndpoint: this.config.rpcUrl }),
|
|
120
|
+
osmosis.ClientFactory.createRPCQueryClient({ rpcEndpoint: this.config.rpcUrl }),
|
|
121
|
+
ibc.ClientFactory.createRPCQueryClient({ rpcEndpoint: this.config.rpcUrl })
|
|
122
|
+
]);
|
|
115
123
|
return {
|
|
116
124
|
...liftedinitClient,
|
|
117
|
-
cosmwasm: cosmwasmClient.cosmwasm
|
|
125
|
+
cosmwasm: cosmwasmClient.cosmwasm,
|
|
126
|
+
strangelove_ventures: strangeloveClient.strangelove_ventures,
|
|
127
|
+
osmosis: osmosisClient.osmosis,
|
|
128
|
+
ibc: ibcClient.ibc
|
|
118
129
|
};
|
|
119
130
|
}, {
|
|
120
131
|
config: this.config.retry,
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":["cosmwasmNs"],"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 liftedinit,\n liftedinitAminoConverters,\n liftedinitProtoRegistry,\n osmosisAminoConverters,\n osmosisProtoRegistry,\n strangeloveVenturesAminoConverters,\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// Uses Pick to extract only the cosmwasm 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>;\nexport type ManifestQueryClient = LiftedinitQueryClient &\n Pick<CosmwasmQueryClient, 'cosmwasm'>;\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 ]);\n\n const aminoTypes = new AminoTypes({\n ...cosmosAminoConverters,\n ...liftedinitAminoConverters,\n ...strangeloveVenturesAminoConverters,\n ...osmosisAminoConverters,\n ...cosmwasmAminoConverters,\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 namespaces into a single client\n client = await withRetry(\n async () => {\n const [liftedinitClient, cosmwasmClient] = await Promise.all([\n liftedinit.ClientFactory.createRPCQueryClient({\n rpcEndpoint: this.config.rpcUrl!,\n }),\n cosmwasmNs.ClientFactory.createRPCQueryClient({\n rpcEndpoint: this.config.rpcUrl!,\n }),\n ]);\n return {\n ...liftedinitClient,\n cosmwasm: cosmwasmClient.cosmwasm,\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":";;;;;;;;;;;AA6DA,MAAM,+BAA+B;;AAGrC,MAAM,qCAAqC;;;;AAK3C,SAAS,kCAAkC;AAiBzC,QAAO;EAAE,UAhBQ,IAAI,SAAS;GAC5B,GAAG;GACH,GAAG;GACH,GAAG;GACH,GAAG;GACH,GAAG;GACJ,CAAC;EAUiB,YARA,IAAI,WAAW;GAChC,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,iBAAiB;AAG1B,OAAI,uBAAuB;AACzB,QAAI,SAAS,eAAe;AAC1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AAiB,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;;;AAjU5B,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 // 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,sBA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AAO,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"}
|
package/dist/cosmos.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cosmos.d.ts","names":[],"sources":["../src/cosmos.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"cosmos.d.ts","names":[],"sources":["../src/cosmos.ts"],"mappings":";;;;;;AAqGA;;;;iBAAsB,WAAA,CACpB,aAAA,EAAe,mBAAA,EACf,MAAA,UACA,UAAA,UACA,IAAA,cACC,OAAA,CAAQ,iBAAA;;;;;;;;;;iBA+DW,QAAA,CACpB,aAAA,EAAe,mBAAA,EACf,MAAA,UACA,UAAA,UACA,IAAA,aACA,mBAAA,YACA,SAAA,GAAY,WAAA,GACX,OAAA,CAAQ,cAAA;;;AAPX;;;;;;;;;iBA4GsB,iBAAA,CACpB,aAAA,EAAe,mBAAA,EACf,MAAA,UACA,UAAA,UACA,IAAA,aACA,SAAA,GAAY,WAAA,GACX,OAAA,CAAQ,iBAAA"}
|
package/dist/cosmos.js
CHANGED
|
@@ -1,11 +1,44 @@
|
|
|
1
1
|
import { ManifestMCPError, ManifestMCPErrorCode } from "./types.js";
|
|
2
2
|
import { withRetry } from "./retry.js";
|
|
3
3
|
import "./config.js";
|
|
4
|
-
import { getQueryHandler, getTxHandler, getTxMsgBuilder } from "./modules.js";
|
|
4
|
+
import { getQueryHandler, getTxContextLoader, getTxHandler, getTxMsgBuilder } from "./modules.js";
|
|
5
5
|
import { calculateFee } from "@cosmjs/stargate";
|
|
6
6
|
//#region src/cosmos.ts
|
|
7
7
|
const VALID_NAME_PATTERN = /^[a-zA-Z0-9_][a-zA-Z0-9_-]*$/;
|
|
8
8
|
/**
|
|
9
|
+
* Resolve and run the `TxBuildContext` loader registered for `(module,
|
|
10
|
+
* subcommand)` in `TX_MODULES`. Returns `undefined` when no loader is
|
|
11
|
+
* registered (the common case) so the caller can short-circuit and skip the
|
|
12
|
+
* chain read.
|
|
13
|
+
*
|
|
14
|
+
* Acquires a rate-limit token before the loader runs so each extra RPC is
|
|
15
|
+
* counted against the same budget every other RPC respects, and wraps any
|
|
16
|
+
* non-`ManifestMCPError` failure as `QUERY_FAILED` with `{module, subcommand}`
|
|
17
|
+
* details for symmetric error classification on both broadcast and estimate
|
|
18
|
+
* paths.
|
|
19
|
+
*/
|
|
20
|
+
async function loadBuildContext(clientManager, module, subcommand) {
|
|
21
|
+
const loader = getTxContextLoader(module, subcommand);
|
|
22
|
+
if (!loader) return void 0;
|
|
23
|
+
try {
|
|
24
|
+
await clientManager.acquireRateLimit();
|
|
25
|
+
return await loader(await clientManager.getQueryClient());
|
|
26
|
+
} catch (error) {
|
|
27
|
+
if (error instanceof ManifestMCPError) {
|
|
28
|
+
if (!error.details?.module) throw new ManifestMCPError(error.code, error.message, {
|
|
29
|
+
...error.details,
|
|
30
|
+
module,
|
|
31
|
+
subcommand
|
|
32
|
+
});
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
throw new ManifestMCPError(ManifestMCPErrorCode.QUERY_FAILED, `Failed to load build context for ${module} ${subcommand}: ${error instanceof Error ? error.message : String(error)}`, {
|
|
36
|
+
module,
|
|
37
|
+
subcommand
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
9
42
|
* Validate that a string is safe for use as a module or subcommand name.
|
|
10
43
|
* Uses the appropriate UNSUPPORTED_QUERY or UNSUPPORTED_TX code so that
|
|
11
44
|
* the error is immediately classified as non-retryable.
|
|
@@ -24,17 +57,26 @@ async function cosmosQuery(clientManager, module, subcommand, args = []) {
|
|
|
24
57
|
validateName(subcommand, "subcommand", ManifestMCPErrorCode.UNSUPPORTED_QUERY);
|
|
25
58
|
const handler = getQueryHandler(module);
|
|
26
59
|
return withRetry(async () => {
|
|
27
|
-
await clientManager.acquireRateLimit();
|
|
28
|
-
const queryClient = await clientManager.getQueryClient();
|
|
29
60
|
try {
|
|
61
|
+
await clientManager.acquireRateLimit();
|
|
30
62
|
return {
|
|
31
63
|
module,
|
|
32
64
|
subcommand,
|
|
33
|
-
result: await handler(
|
|
65
|
+
result: await handler(await clientManager.getQueryClient(), subcommand, args)
|
|
34
66
|
};
|
|
35
67
|
} catch (error) {
|
|
36
|
-
if (error instanceof ManifestMCPError)
|
|
37
|
-
|
|
68
|
+
if (error instanceof ManifestMCPError) {
|
|
69
|
+
if (!error.details?.module) throw new ManifestMCPError(error.code, error.message, {
|
|
70
|
+
...error.details,
|
|
71
|
+
module,
|
|
72
|
+
subcommand
|
|
73
|
+
});
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
throw new ManifestMCPError(ManifestMCPErrorCode.QUERY_FAILED, `Query ${module} ${subcommand} failed: ${error instanceof Error ? error.message : String(error)}`, {
|
|
77
|
+
module,
|
|
78
|
+
subcommand
|
|
79
|
+
});
|
|
38
80
|
}
|
|
39
81
|
}, {
|
|
40
82
|
config: clientManager.getConfig().retry,
|
|
@@ -64,12 +106,14 @@ async function cosmosTx(clientManager, module, subcommand, args = [], waitForCon
|
|
|
64
106
|
};
|
|
65
107
|
}
|
|
66
108
|
const handler = getTxHandler(module);
|
|
109
|
+
const buildContext = await withRetry(() => loadBuildContext(clientManager, module, subcommand), {
|
|
110
|
+
config: clientManager.getConfig().retry,
|
|
111
|
+
operationName: `load-context ${module} ${subcommand}`
|
|
112
|
+
});
|
|
67
113
|
return withRetry(async () => {
|
|
68
|
-
await clientManager.acquireRateLimit();
|
|
69
|
-
const signingClient = await clientManager.getSigningClient();
|
|
70
|
-
const senderAddress = await clientManager.getAddress();
|
|
71
114
|
try {
|
|
72
|
-
|
|
115
|
+
await clientManager.acquireRateLimit();
|
|
116
|
+
return await handler(await clientManager.getSigningClient(), await clientManager.getAddress(), subcommand, args, waitForConfirmation, txOptions, buildContext);
|
|
73
117
|
} catch (error) {
|
|
74
118
|
if (error instanceof ManifestMCPError) {
|
|
75
119
|
if (!error.details?.module) throw new ManifestMCPError(error.code, error.message, {
|
|
@@ -112,14 +156,18 @@ async function cosmosEstimateFee(clientManager, module, subcommand, args = [], o
|
|
|
112
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}`);
|
|
113
157
|
}
|
|
114
158
|
const builder = getTxMsgBuilder(module);
|
|
159
|
+
const buildContext = await withRetry(() => loadBuildContext(clientManager, module, subcommand), {
|
|
160
|
+
config: config.retry,
|
|
161
|
+
operationName: `load-context ${module} ${subcommand}`
|
|
162
|
+
});
|
|
115
163
|
return withRetry(async () => {
|
|
116
|
-
await clientManager.acquireRateLimit();
|
|
117
|
-
const signingClient = await clientManager.getSigningClient();
|
|
118
|
-
const senderAddress = await clientManager.getAddress();
|
|
119
|
-
const clientMultiplier = signingClient.defaultGasMultiplier;
|
|
120
|
-
const gasMultiplier = overrides?.gasMultiplier ?? (typeof clientMultiplier === "number" ? clientMultiplier : 1.5);
|
|
121
164
|
try {
|
|
122
|
-
|
|
165
|
+
await clientManager.acquireRateLimit();
|
|
166
|
+
const signingClient = await clientManager.getSigningClient();
|
|
167
|
+
const senderAddress = await clientManager.getAddress();
|
|
168
|
+
const clientMultiplier = signingClient.defaultGasMultiplier;
|
|
169
|
+
const gasMultiplier = overrides?.gasMultiplier ?? (typeof clientMultiplier === "number" ? clientMultiplier : 1.5);
|
|
170
|
+
const built = builder(senderAddress, subcommand, args, buildContext);
|
|
123
171
|
const gasEstimate = await signingClient.simulate(senderAddress, built.messages, built.memo);
|
|
124
172
|
const fee = calculateFee(Math.ceil(gasEstimate * gasMultiplier), gasPrice);
|
|
125
173
|
return {
|
package/dist/cosmos.js.map
CHANGED
|
@@ -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 { getQueryHandler, getTxHandler, getTxMsgBuilder } from './modules.js';\nimport { withRetry } from './retry.js';\nimport {\n type CosmosQueryResult,\n type CosmosTxResult,\n type FeeEstimateResult,\n ManifestMCPError,\n ManifestMCPErrorCode,\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 * 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 // Apply rate limiting before making RPC request\n await clientManager.acquireRateLimit();\n\n const queryClient = await clientManager.getQueryClient();\n\n try {\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 throw error;\n }\n throw new ManifestMCPError(\n ManifestMCPErrorCode.QUERY_FAILED,\n `Query ${module} ${subcommand} failed: ${error instanceof Error ? error.message : String(error)}`,\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\n return withRetry(\n async () => {\n // Apply rate limiting before making RPC request\n await clientManager.acquireRateLimit();\n\n const signingClient = await clientManager.getSigningClient();\n const senderAddress = await clientManager.getAddress();\n\n try {\n return await handler(\n signingClient,\n senderAddress,\n subcommand,\n args,\n waitForConfirmation,\n txOptions,\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\n return withRetry(\n async () => {\n // Apply rate limiting before making RPC request\n await clientManager.acquireRateLimit();\n\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 try {\n const built = builder(senderAddress, subcommand, args);\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":";;;;;;AAiBA,MAAM,qBAAqB;;;;;;AAO3B,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,UAAU,gBAAgB,OAAO;AAEvC,QAAO,UACL,YAAY;AAEV,QAAM,cAAc,kBAAkB;EAEtC,MAAM,cAAc,MAAM,cAAc,gBAAgB;AAExD,MAAI;AAGF,UAAO;IACL;IACA;IACA,QALa,MAAM,QAAQ,aAAa,YAAY,KAAK;IAM1D;WACM,OAAO;AACd,OAAI,iBAAiB,iBACnB,OAAM;AAER,SAAM,IAAI,iBACR,qBAAqB,cACrB,SAAS,OAAO,GAAG,WAAW,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,GAChG;;IAGL;EACE,QAAQ,cAAc,WAAW,CAAC;EAClC,eAAe,SAAS,OAAO,GAAG;EACnC,CACF;;;;;;;;;;;AAYH,eAAsB,SACpB,eACA,QACA,YACA,OAAiB,EAAE,EACnB,sBAA+B,OAC/B,WACyB;AACzB,cAAa,QAAQ,UAAU,qBAAqB,eAAe;AACnE,cAAa,YAAY,cAAc,qBAAqB,eAAe;CAG3E,IAAI;AACJ,KAAI,WAAW,kBAAkB,KAAA,GAAW;AAC1C,MACE,CAAC,OAAO,SAAS,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,EAE1B,OAAM,IAAI,iBACR,qBAAqB,gBACrB,mDAAmD,UAAU,gBAC9D;;CAKL,MAAM,UAAU,gBAAgB,OAAO;AAEvC,QAAO,UACL,YAAY;AAEV,QAAM,cAAc,kBAAkB;EAEtC,MAAM,gBAAgB,MAAM,cAAc,kBAAkB;EAC5D,MAAM,gBAAgB,MAAM,cAAc,YAAY;EAQtD,MAAM,mBACJ,cACA;EACF,MAAM,gBACJ,WAAW,kBACV,OAAO,qBAAqB,WACzB,mBAAA;AAGN,MAAI;GACF,MAAM,QAAQ,QAAQ,eAAe,YAAY,KAAK;GACtD,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,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,Y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AG;EAC1C,CACF;AAED,QAAO,UACL,YAAY;AAOV,MAAI;AACF,SAAM,cAAc,kBAAkB;GACtC,MAAM,gBAAgB,MAAM,cAAc,kBAAkB;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"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,20 +1,22 @@
|
|
|
1
|
-
import { AccountInfo, AccountInfoResult, AddressBytesToStringResult, AddressStringToBytesResult, Any, AuthAccountResult, AuthAccountsResult, AuthParams, AuthParamsResult, AvailableModules, BalanceResult, BalancesResult, BankMetadata, BankParams, BankParamsResult, BaseAccount, Bech32PrefixResult, BillingParams, BillingParamsResult, BuiltMessages, CodeInfoResponse, Coin, CommissionResult, CommunityPoolResult, ContractCodeHistoryEntry, ContractInfo, CosmosQueryResult, CosmosTxResult, CreditAccount, CreditAccountResult, CreditAccountsResult, CreditAddressResult, CreditEstimateResult, DecCoin, DelegationDelegatorReward, DelegationResponse, DelegationResult, DelegationsResult, DelegatorValidatorsResult, DelegatorWithdrawAddressResult, DenomMetadataResult, DenomsMetadataResult, DepositParams, DepositResult, DepositsResult, DistributionParams, DistributionParamsResult, FeeEstimateResult, GovDeposit, GovParams, GovParamsResult, GovProposal, GovTallyResult, GovVote, GroupInfo, GroupInfoResult, GroupMember, GroupMembersResult, GroupPoliciesResult, GroupPolicyInfo, GroupPolicyInfoResult, GroupProposal, GroupProposalResult, GroupProposalsResult, GroupTallyQueryResult, GroupTallyResult, GroupVote, GroupVoteResult, GroupVotesResult, GroupsResult, HistoricalInfo, HistoricalInfoResult, Lease, LeaseItemInput, LeaseResult, LeasesResult, ManifestMCPConfig, ManifestMCPError, ManifestMCPErrorCode, Model, ModuleAccount, ModuleAccountsResult, ModuleInfo, PaginatedResult, PaginationResponse, ProposalResult, ProposalsResult, Provider, ProviderResult, ProviderWithdrawableResult, ProvidersResult, QueryCreditEstimateResponse, QueryResult, RateLimitConfig, RedelegationResponse, RedelegationsResult, RetryConfig, RewardsResult, SKU, SendEnabled, SendEnabledResult, SignArbitraryResult, SkuParams, SkuParamsResult, SkuResult, SkusResult, SlashesResult, StakingParams, StakingParamsResult, StakingPool, StakingPoolResult, SupplyOfResult, TallyParams, TallyResult, TotalSupplyResult, TxOptions, TxOverrides, UnbondingDelegation, UnbondingDelegationResult, UnbondingDelegationsResult, Validator, ValidatorAccumulatedCommission, ValidatorOutstandingRewards, ValidatorOutstandingRewardsResult, ValidatorResult, ValidatorSlashEvent, ValidatorsResult, VoteResult, VotesResult, VotingParams, WalletProvider, WasmAllContractStateResult, WasmBuildAddressResult, WasmCodeInfo, WasmCodeInfoResult, WasmCodeResult, WasmCodesResult, WasmContractHistoryResult, WasmContractInfoResult, WasmContractsByCodeResult, WasmContractsByCreatorResult, WasmLimitsConfigResult, WasmParams, WasmParamsResult, WasmPinnedCodesResult, WasmRawContractStateResult, WasmSmartContractStateResult, WithdrawableAmountResult } from "./types.js";
|
|
1
|
+
import { AccountInfo, AccountInfoResult, AddressBytesToStringResult, AddressStringToBytesResult, Any, AuthAccountResult, AuthAccountsResult, AuthParams, AuthParamsResult, AuthzGrant, AuthzGrantAuthorization, AuthzGranteeGrantsResult, AuthzGranterGrantsResult, AuthzGrantsResult, AvailableModules, BalanceResult, BalancesResult, BankMetadata, BankParams, BankParamsResult, BaseAccount, Bech32PrefixResult, BillingParams, BillingParamsResult, BuiltMessages, CodeInfoResponse, Coin, CommissionResult, CommunityPoolResult, ContractCodeHistoryEntry, ContractInfo, CosmosQueryResult, CosmosTxResult, CreditAccount, CreditAccountResult, CreditAccountsResult, CreditAddressResult, CreditEstimateResult, DecCoin, DelegationDelegatorReward, DelegationResponse, DelegationResult, DelegationsResult, DelegatorValidatorsResult, DelegatorWithdrawAddressResult, DenomAuthorityMetadata, DenomAuthorityMetadataResult, DenomMetadataResult, DenomTrace, DenomsFromAdminResult, DenomsFromCreatorResult, DenomsMetadataResult, DepositParams, DepositResult, DepositsResult, DistributionParams, DistributionParamsResult, FeeEstimateResult, FeegrantAllowanceResult, FeegrantAllowancesResult, FeegrantGrant, GovDeposit, GovParams, GovParamsResult, GovProposal, GovTallyResult, GovVote, GroupInfo, GroupInfoResult, GroupMember, GroupMembersResult, GroupPoliciesResult, GroupPolicyInfo, GroupPolicyInfoResult, GroupProposal, GroupProposalResult, GroupProposalsResult, GroupTallyQueryResult, GroupTallyResult, GroupVote, GroupVoteResult, GroupVotesResult, GroupsResult, HistoricalInfo, HistoricalInfoResult, IbcDenomTraceResult, IbcDenomTracesResult, IbcTransferParams, IbcTransferParamsResult, Lease, LeaseByCustomDomainResult, LeaseItemInput, LeaseResult, LeasesResult, ManifestMCPConfig, ManifestMCPError, ManifestMCPErrorCode, MintAnnualProvisionsResult, MintInflationResult, MintParams, MintParamsResult, Model, ModuleAccount, ModuleAccountsResult, ModuleInfo, PaginatedResult, PaginationResponse, PoAAuthorityResult, PoAConsensusPowerResult, PoAPendingValidatorsResult, PoAStakingParams, PoAValidator, ProposalResult, ProposalsResult, Provider, ProviderResult, ProviderWithdrawableResult, ProvidersResult, QueryCreditEstimateResponse, QueryResult, RateLimitConfig, RedelegationResponse, RedelegationsResult, RetryConfig, RewardsResult, SKU, SendEnabled, SendEnabledResult, SignArbitraryResult, SkuParams, SkuParamsResult, SkuResult, SkusResult, SlashesResult, StakingParams, StakingParamsResult, StakingPool, StakingPoolResult, SupplyOfResult, TallyParams, TallyResult, TokenfactoryParams, TokenfactoryParamsResult, TotalSupplyResult, TxBuildContext, TxOptions, TxOverrides, UnbondingDelegation, UnbondingDelegationResult, UnbondingDelegationsResult, Validator, ValidatorAccumulatedCommission, ValidatorOutstandingRewards, ValidatorOutstandingRewardsResult, ValidatorResult, ValidatorSlashEvent, ValidatorsResult, VoteResult, VotesResult, VotingParams, WalletProvider, WasmAllContractStateResult, WasmBuildAddressResult, WasmCodeInfo, WasmCodeInfoResult, WasmCodeResult, WasmCodesResult, WasmContractHistoryResult, WasmContractInfoResult, WasmContractsByCodeResult, WasmContractsByCreatorResult, WasmLimitsConfigResult, WasmParams, WasmParamsResult, WasmPinnedCodesResult, WasmRawContractStateResult, WasmSmartContractStateResult, WithdrawableAmountResult } from "./types.js";
|
|
2
2
|
import { CosmosClientManager, ManifestQueryClient } from "./client.js";
|
|
3
3
|
import { DEFAULT_RETRY_CONFIG, RetryOptions, calculateBackoff, isRetryableError, withRetry } from "./retry.js";
|
|
4
4
|
import { ValidationResult, createConfig, createValidatedConfig, validateConfig } from "./config.js";
|
|
5
5
|
import { cosmosEstimateFee, cosmosQuery, cosmosTx } from "./cosmos.js";
|
|
6
6
|
import { createLCDQueryClient } from "./lcd-adapter.js";
|
|
7
|
-
import { LogLevel, logger } from "./logger.js";
|
|
7
|
+
import { LogLevel, logger, parseLogLevel } from "./logger.js";
|
|
8
8
|
import { getAvailableModules, getModuleSubcommands, getSubcommandUsage, getSupportedModules, isSubcommandSupported } from "./modules.js";
|
|
9
9
|
import { validateAddress } from "./transactions/utils.js";
|
|
10
10
|
import { MAX_PAGE_LIMIT, createPagination } from "./queries/utils.js";
|
|
11
|
-
import { INFRASTRUCTURE_ERROR_CODES, ManifestMCPServerOptions, MnemonicServerConfig, SENSITIVE_FIELDS, bigIntReplacer, createMnemonicServer, jsonResponse, sanitizeForLogging, withErrorHandling } from "./server-utils.js";
|
|
11
|
+
import { INFRASTRUCTURE_ERROR_CODES, ManifestMCPServerOptions, MnemonicServerConfig, SENSITIVE_FIELDS, bigIntReplacer, createMnemonicServer, jsonResponse, sanitizeForLogging, structuredResponse, withErrorHandling } from "./server-utils.js";
|
|
12
|
+
import { MANIFEST_TOOL_META_VERSION, ManifestToolMeta, ManifestToolMetaContainer, ManifestToolMetaVersion, manifestMeta, mutatingAnnotations, readOnlyAnnotations } from "./tool-metadata.js";
|
|
12
13
|
import { FundCreditsResult, fundCredits } from "./tools/fundCredits.js";
|
|
13
14
|
import { getBalance } from "./tools/getBalance.js";
|
|
15
|
+
import { SetItemCustomDomainOptions, SetItemCustomDomainResult, setItemCustomDomain } from "./tools/setItemCustomDomain.js";
|
|
14
16
|
import { StopAppResult, stopApp } from "./tools/stopApp.js";
|
|
15
17
|
import { DNS_LABEL_RE, optionalBoolean, parseArgs, requireString, requireStringEnum, requireUuid } from "./validation.js";
|
|
16
18
|
import { VERSION } from "./version.js";
|
|
17
19
|
import { MnemonicWalletProvider } from "./wallet/mnemonic.js";
|
|
18
20
|
import { signArbitraryWithAmino } from "./wallet/sign-arbitrary.js";
|
|
19
21
|
import { LeaseState, leaseStateFromJSON, leaseStateToJSON } from "@manifest-network/manifestjs/dist/codegen/liftedinit/billing/v1/types.js";
|
|
20
|
-
export { AccountInfo, AccountInfoResult, AddressBytesToStringResult, AddressStringToBytesResult, Any, AuthAccountResult, AuthAccountsResult, AuthParams, AuthParamsResult, AvailableModules, BalanceResult, BalancesResult, BankMetadata, BankParams, BankParamsResult, BaseAccount, Bech32PrefixResult, BillingParams, BillingParamsResult, BuiltMessages, CodeInfoResponse, Coin, CommissionResult, CommunityPoolResult, ContractCodeHistoryEntry, ContractInfo, CosmosClientManager, CosmosQueryResult, CosmosTxResult, CreditAccount, CreditAccountResult, CreditAccountsResult, CreditAddressResult, CreditEstimateResult, DEFAULT_RETRY_CONFIG, DNS_LABEL_RE, DecCoin, DelegationDelegatorReward, DelegationResponse, DelegationResult, DelegationsResult, DelegatorValidatorsResult, DelegatorWithdrawAddressResult, DenomMetadataResult, DenomsMetadataResult, DepositParams, DepositResult, DepositsResult, DistributionParams, DistributionParamsResult, FeeEstimateResult, type FundCreditsResult, GovDeposit, GovParams, GovParamsResult, GovProposal, GovTallyResult, GovVote, GroupInfo, GroupInfoResult, GroupMember, GroupMembersResult, GroupPoliciesResult, GroupPolicyInfo, GroupPolicyInfoResult, GroupProposal, GroupProposalResult, GroupProposalsResult, GroupTallyQueryResult, GroupTallyResult, GroupVote, GroupVoteResult, GroupVotesResult, GroupsResult, HistoricalInfo, HistoricalInfoResult, INFRASTRUCTURE_ERROR_CODES, Lease, LeaseItemInput, LeaseResult, LeaseState, LeasesResult, type LogLevel, MAX_PAGE_LIMIT, ManifestMCPConfig, ManifestMCPError, ManifestMCPErrorCode, type ManifestMCPServerOptions, type ManifestQueryClient, type MnemonicServerConfig, MnemonicWalletProvider, Model, ModuleAccount, ModuleAccountsResult, ModuleInfo, PaginatedResult, PaginationResponse, ProposalResult, ProposalsResult, Provider, ProviderResult, ProviderWithdrawableResult, ProvidersResult, QueryCreditEstimateResponse, QueryResult, RateLimitConfig, RedelegationResponse, RedelegationsResult, RetryConfig, type RetryOptions, RewardsResult, SENSITIVE_FIELDS, SKU, SendEnabled, SendEnabledResult, SignArbitraryResult, SkuParams, SkuParamsResult, SkuResult, SkusResult, SlashesResult, StakingParams, StakingParamsResult, StakingPool, StakingPoolResult, type StopAppResult, SupplyOfResult, TallyParams, TallyResult, TotalSupplyResult, TxOptions, TxOverrides, UnbondingDelegation, UnbondingDelegationResult, UnbondingDelegationsResult, VERSION, type ValidationResult, Validator, ValidatorAccumulatedCommission, ValidatorOutstandingRewards, ValidatorOutstandingRewardsResult, ValidatorResult, ValidatorSlashEvent, ValidatorsResult, VoteResult, VotesResult, VotingParams, WalletProvider, WasmAllContractStateResult, WasmBuildAddressResult, WasmCodeInfo, WasmCodeInfoResult, WasmCodeResult, WasmCodesResult, WasmContractHistoryResult, WasmContractInfoResult, WasmContractsByCodeResult, WasmContractsByCreatorResult, WasmLimitsConfigResult, WasmParams, WasmParamsResult, WasmPinnedCodesResult, WasmRawContractStateResult, WasmSmartContractStateResult, WithdrawableAmountResult, bigIntReplacer, calculateBackoff, cosmosEstimateFee, cosmosQuery, cosmosTx, createConfig, createLCDQueryClient, createMnemonicServer, createPagination, createValidatedConfig, fundCredits, getAvailableModules, getBalance, getModuleSubcommands, getSubcommandUsage, getSupportedModules, isRetryableError, isSubcommandSupported, jsonResponse, leaseStateFromJSON, leaseStateToJSON, logger, optionalBoolean, parseArgs, requireString, requireStringEnum, requireUuid, sanitizeForLogging, signArbitraryWithAmino, stopApp, validateAddress, validateConfig, withErrorHandling, withRetry };
|
|
22
|
+
export { AccountInfo, AccountInfoResult, AddressBytesToStringResult, AddressStringToBytesResult, Any, AuthAccountResult, AuthAccountsResult, AuthParams, AuthParamsResult, AuthzGrant, AuthzGrantAuthorization, AuthzGranteeGrantsResult, AuthzGranterGrantsResult, AuthzGrantsResult, AvailableModules, BalanceResult, BalancesResult, BankMetadata, BankParams, BankParamsResult, BaseAccount, Bech32PrefixResult, BillingParams, BillingParamsResult, BuiltMessages, CodeInfoResponse, Coin, CommissionResult, CommunityPoolResult, ContractCodeHistoryEntry, ContractInfo, CosmosClientManager, CosmosQueryResult, CosmosTxResult, CreditAccount, CreditAccountResult, CreditAccountsResult, CreditAddressResult, CreditEstimateResult, DEFAULT_RETRY_CONFIG, DNS_LABEL_RE, DecCoin, DelegationDelegatorReward, DelegationResponse, DelegationResult, DelegationsResult, DelegatorValidatorsResult, DelegatorWithdrawAddressResult, DenomAuthorityMetadata, DenomAuthorityMetadataResult, DenomMetadataResult, DenomTrace, DenomsFromAdminResult, DenomsFromCreatorResult, DenomsMetadataResult, DepositParams, DepositResult, DepositsResult, DistributionParams, DistributionParamsResult, FeeEstimateResult, FeegrantAllowanceResult, FeegrantAllowancesResult, FeegrantGrant, type FundCreditsResult, GovDeposit, GovParams, GovParamsResult, GovProposal, GovTallyResult, GovVote, GroupInfo, GroupInfoResult, GroupMember, GroupMembersResult, GroupPoliciesResult, GroupPolicyInfo, GroupPolicyInfoResult, GroupProposal, GroupProposalResult, GroupProposalsResult, GroupTallyQueryResult, GroupTallyResult, GroupVote, GroupVoteResult, GroupVotesResult, GroupsResult, HistoricalInfo, HistoricalInfoResult, INFRASTRUCTURE_ERROR_CODES, IbcDenomTraceResult, IbcDenomTracesResult, IbcTransferParams, IbcTransferParamsResult, Lease, LeaseByCustomDomainResult, LeaseItemInput, LeaseResult, LeaseState, LeasesResult, type LogLevel, MANIFEST_TOOL_META_VERSION, MAX_PAGE_LIMIT, ManifestMCPConfig, ManifestMCPError, ManifestMCPErrorCode, type ManifestMCPServerOptions, type ManifestQueryClient, type ManifestToolMeta, type ManifestToolMetaContainer, type ManifestToolMetaVersion, MintAnnualProvisionsResult, MintInflationResult, MintParams, MintParamsResult, type MnemonicServerConfig, MnemonicWalletProvider, Model, ModuleAccount, ModuleAccountsResult, ModuleInfo, PaginatedResult, PaginationResponse, PoAAuthorityResult, PoAConsensusPowerResult, PoAPendingValidatorsResult, PoAStakingParams, PoAValidator, ProposalResult, ProposalsResult, Provider, ProviderResult, ProviderWithdrawableResult, ProvidersResult, QueryCreditEstimateResponse, QueryResult, RateLimitConfig, RedelegationResponse, RedelegationsResult, RetryConfig, type RetryOptions, RewardsResult, SENSITIVE_FIELDS, SKU, SendEnabled, SendEnabledResult, type SetItemCustomDomainOptions, type SetItemCustomDomainResult, SignArbitraryResult, SkuParams, SkuParamsResult, SkuResult, SkusResult, SlashesResult, StakingParams, StakingParamsResult, StakingPool, StakingPoolResult, type StopAppResult, SupplyOfResult, TallyParams, TallyResult, TokenfactoryParams, TokenfactoryParamsResult, TotalSupplyResult, TxBuildContext, TxOptions, TxOverrides, UnbondingDelegation, UnbondingDelegationResult, UnbondingDelegationsResult, VERSION, type ValidationResult, Validator, ValidatorAccumulatedCommission, ValidatorOutstandingRewards, ValidatorOutstandingRewardsResult, ValidatorResult, ValidatorSlashEvent, ValidatorsResult, VoteResult, VotesResult, VotingParams, WalletProvider, WasmAllContractStateResult, WasmBuildAddressResult, WasmCodeInfo, WasmCodeInfoResult, WasmCodeResult, WasmCodesResult, WasmContractHistoryResult, WasmContractInfoResult, WasmContractsByCodeResult, WasmContractsByCreatorResult, WasmLimitsConfigResult, WasmParams, WasmParamsResult, WasmPinnedCodesResult, WasmRawContractStateResult, WasmSmartContractStateResult, WithdrawableAmountResult, bigIntReplacer, calculateBackoff, cosmosEstimateFee, cosmosQuery, cosmosTx, createConfig, createLCDQueryClient, createMnemonicServer, createPagination, createValidatedConfig, fundCredits, getAvailableModules, getBalance, getModuleSubcommands, getSubcommandUsage, getSupportedModules, isRetryableError, isSubcommandSupported, jsonResponse, leaseStateFromJSON, leaseStateToJSON, logger, manifestMeta, mutatingAnnotations, optionalBoolean, parseArgs, parseLogLevel, readOnlyAnnotations, requireString, requireStringEnum, requireUuid, sanitizeForLogging, setItemCustomDomain, signArbitraryWithAmino, stopApp, structuredResponse, validateAddress, validateConfig, withErrorHandling, withRetry };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ManifestMCPError, ManifestMCPErrorCode } from "./types.js";
|
|
2
2
|
import { DEFAULT_RETRY_CONFIG, calculateBackoff, isRetryableError, withRetry } from "./retry.js";
|
|
3
3
|
import { createConfig, createValidatedConfig, validateConfig } from "./config.js";
|
|
4
|
-
import { logger } from "./logger.js";
|
|
4
|
+
import { logger, parseLogLevel } from "./logger.js";
|
|
5
5
|
import { createLCDQueryClient } from "./lcd-adapter.js";
|
|
6
6
|
import { CosmosClientManager } from "./client.js";
|
|
7
7
|
import { DNS_LABEL_RE, optionalBoolean, parseArgs, requireString, requireStringEnum, requireUuid } from "./validation.js";
|
|
@@ -12,10 +12,12 @@ import { cosmosEstimateFee, cosmosQuery, cosmosTx } from "./cosmos.js";
|
|
|
12
12
|
import { signArbitraryWithAmino } from "./wallet/sign-arbitrary.js";
|
|
13
13
|
import { MnemonicWalletProvider } from "./wallet/mnemonic.js";
|
|
14
14
|
import "./wallet/index.js";
|
|
15
|
-
import { INFRASTRUCTURE_ERROR_CODES, SENSITIVE_FIELDS, bigIntReplacer, createMnemonicServer, jsonResponse, sanitizeForLogging, withErrorHandling } from "./server-utils.js";
|
|
15
|
+
import { INFRASTRUCTURE_ERROR_CODES, SENSITIVE_FIELDS, bigIntReplacer, createMnemonicServer, jsonResponse, sanitizeForLogging, structuredResponse, withErrorHandling } from "./server-utils.js";
|
|
16
|
+
import { MANIFEST_TOOL_META_VERSION, manifestMeta, mutatingAnnotations, readOnlyAnnotations } from "./tool-metadata.js";
|
|
16
17
|
import { fundCredits } from "./tools/fundCredits.js";
|
|
17
18
|
import { getBalance } from "./tools/getBalance.js";
|
|
19
|
+
import { setItemCustomDomain } from "./tools/setItemCustomDomain.js";
|
|
18
20
|
import { stopApp } from "./tools/stopApp.js";
|
|
19
21
|
import { VERSION } from "./version.js";
|
|
20
22
|
import { LeaseState, leaseStateFromJSON, leaseStateToJSON } from "@manifest-network/manifestjs/dist/codegen/liftedinit/billing/v1/types.js";
|
|
21
|
-
export { CosmosClientManager, DEFAULT_RETRY_CONFIG, DNS_LABEL_RE, INFRASTRUCTURE_ERROR_CODES, LeaseState, MAX_PAGE_LIMIT, ManifestMCPError, ManifestMCPErrorCode, MnemonicWalletProvider, SENSITIVE_FIELDS, VERSION, bigIntReplacer, calculateBackoff, cosmosEstimateFee, cosmosQuery, cosmosTx, createConfig, createLCDQueryClient, createMnemonicServer, createPagination, createValidatedConfig, fundCredits, getAvailableModules, getBalance, getModuleSubcommands, getSubcommandUsage, getSupportedModules, isRetryableError, isSubcommandSupported, jsonResponse, leaseStateFromJSON, leaseStateToJSON, logger, optionalBoolean, parseArgs, requireString, requireStringEnum, requireUuid, sanitizeForLogging, signArbitraryWithAmino, stopApp, validateAddress, validateConfig, withErrorHandling, withRetry };
|
|
23
|
+
export { CosmosClientManager, DEFAULT_RETRY_CONFIG, DNS_LABEL_RE, INFRASTRUCTURE_ERROR_CODES, LeaseState, MANIFEST_TOOL_META_VERSION, MAX_PAGE_LIMIT, ManifestMCPError, ManifestMCPErrorCode, MnemonicWalletProvider, SENSITIVE_FIELDS, VERSION, bigIntReplacer, calculateBackoff, cosmosEstimateFee, cosmosQuery, cosmosTx, createConfig, createLCDQueryClient, createMnemonicServer, createPagination, createValidatedConfig, fundCredits, getAvailableModules, getBalance, getModuleSubcommands, getSubcommandUsage, getSupportedModules, isRetryableError, isSubcommandSupported, jsonResponse, leaseStateFromJSON, leaseStateToJSON, logger, manifestMeta, mutatingAnnotations, optionalBoolean, parseArgs, parseLogLevel, readOnlyAnnotations, requireString, requireStringEnum, requireUuid, sanitizeForLogging, setItemCustomDomain, signArbitraryWithAmino, stopApp, structuredResponse, validateAddress, validateConfig, withErrorHandling, withRetry };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lcd-adapter.d.ts","names":[],"sources":["../src/lcd-adapter.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"lcd-adapter.d.ts","names":[],"sources":["../src/lcd-adapter.ts"],"mappings":";;;iBAiBS,gBAAA,CAAiB,GAAA;AAAA,UAwBhB,SAAA;EACR,QAAA,CAAS,MAAA;AAAA;AAAA,iBAGF,aAAA,CACP,SAAA,EAAW,MAAA,mBACX,UAAA,WACC,SAAA;AAAA,KAiBE,OAAA,OAAc,IAAA,gBAAoB,OAAA;AAAA,iBAE9B,WAAA,CACP,MAAA,WACA,WAAA,YACC,MAAA,SAAe,OAAA;AAAA,iBAqCT,iBAAA,CAAkB,UAAA;;;;;AAjED;;iBAwFjB,kBAAA,CAAmB,OAAA,YAAmB,MAAA;AAAA,iBAqCzB,oBAAA,CACpB,YAAA,WACC,OAAA,CAAQ,mBAAA"}
|
package/dist/lcd-adapter.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ManifestMCPError, ManifestMCPErrorCode } from "./types.js";
|
|
2
2
|
import { logger } from "./logger.js";
|
|
3
|
-
import { cosmos, cosmwasm, liftedinit } from "@manifest-network/manifestjs";
|
|
3
|
+
import { cosmos, cosmwasm, ibc, liftedinit, osmosis, strangelove_ventures } from "@manifest-network/manifestjs";
|
|
4
4
|
import { toBase64, toUtf8 } from "@cosmjs/encoding";
|
|
5
5
|
//#region src/lcd-adapter.ts
|
|
6
6
|
function snakeToCamel(s) {
|
|
@@ -86,8 +86,17 @@ function patchWasmQueryData(wasmLcd) {
|
|
|
86
86
|
async function createLCDQueryClient(restEndpoint) {
|
|
87
87
|
let lcd;
|
|
88
88
|
let cosmwasmLcd;
|
|
89
|
+
let strangeloveLcd;
|
|
90
|
+
let osmosisLcd;
|
|
91
|
+
let ibcLcd;
|
|
89
92
|
try {
|
|
90
|
-
[lcd, cosmwasmLcd] = await Promise.all([
|
|
93
|
+
[lcd, cosmwasmLcd, strangeloveLcd, osmosisLcd, ibcLcd] = await Promise.all([
|
|
94
|
+
liftedinit.ClientFactory.createLCDClient({ restEndpoint }),
|
|
95
|
+
cosmwasm.ClientFactory.createLCDClient({ restEndpoint }),
|
|
96
|
+
strangelove_ventures.ClientFactory.createLCDClient({ restEndpoint }),
|
|
97
|
+
osmosis.ClientFactory.createLCDClient({ restEndpoint }),
|
|
98
|
+
ibc.ClientFactory.createLCDClient({ restEndpoint })
|
|
99
|
+
]);
|
|
91
100
|
} catch (error) {
|
|
92
101
|
throw new ManifestMCPError(ManifestMCPErrorCode.RPC_CONNECTION_FAILED, `Failed to create LCD client for ${restEndpoint}: ${error instanceof Error ? error.message : String(error)}`);
|
|
93
102
|
}
|
|
@@ -119,7 +128,17 @@ async function createLCDQueryClient(restEndpoint) {
|
|
|
119
128
|
manifest: { v1: unsupportedModule("liftedinit.manifest.v1") },
|
|
120
129
|
sku: { v1: adaptModule(lcd.liftedinit.sku.v1, liftedinit.sku.v1) }
|
|
121
130
|
},
|
|
122
|
-
cosmwasm: { wasm: { v1: adaptModule(patchWasmQueryData(cosmwasmLcd.cosmwasm.wasm.v1), cosmwasm.wasm.v1) } }
|
|
131
|
+
cosmwasm: { wasm: { v1: adaptModule(patchWasmQueryData(cosmwasmLcd.cosmwasm.wasm.v1), cosmwasm.wasm.v1) } },
|
|
132
|
+
strangelove_ventures: { poa: { v1: adaptModule(strangeloveLcd.strangelove_ventures.poa.v1, strangelove_ventures.poa.v1) } },
|
|
133
|
+
osmosis: { tokenfactory: { v1beta1: adaptModule(osmosisLcd.osmosis.tokenfactory.v1beta1, osmosis.tokenfactory.v1beta1) } },
|
|
134
|
+
ibc: {
|
|
135
|
+
applications: { transfer: { v1: adaptModule(ibcLcd.ibc.applications.transfer.v1, ibc.applications.transfer.v1) } },
|
|
136
|
+
core: {
|
|
137
|
+
channel: { v1: adaptModule(ibcLcd.ibc.core.channel.v1, ibc.core.channel.v1) },
|
|
138
|
+
client: { v1: adaptModule(ibcLcd.ibc.core.client.v1, ibc.core.client.v1) },
|
|
139
|
+
connection: { v1: adaptModule(ibcLcd.ibc.core.connection.v1, ibc.core.connection.v1) }
|
|
140
|
+
}
|
|
141
|
+
}
|
|
123
142
|
};
|
|
124
143
|
} catch (error) {
|
|
125
144
|
if (error instanceof ManifestMCPError) throw error;
|