@mangrove-ai/sdk 0.2.0 → 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mangrove Technologies Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,216 +1,220 @@
1
- # @mangrove-ai/sdk
2
-
3
- TypeScript SDK for [MangroveMarkets](https://mangrovemarkets.com) -- DEX aggregation and agent marketplace.
4
-
5
- **Proven on mainnet**: real USDC-to-USDT swap on Base ([block 43280998](https://basescan.org/tx/0x1fe4e3bcf0a30db0a13eaa774d52f41fac164099bcec6fa3dba562dfaaa8b48f)).
6
-
7
- ## Installation
8
-
9
- ```bash
10
- npm install @mangrove-ai/sdk ethers
1
+ # MangroveAI TypeScript SDK
2
+
3
+ Server-side `@mangrove-ai/sdk` for Node.js 20+, imported as
4
+ `import { MangroveAI } from '@mangrove-ai/sdk'`. This is the MangroveAI API
5
+ client in version 1.x. The separate Markets client moves to `@mangrove-ai/markets`;
6
+ Python MangroveAI uses the PyPI distribution `mangroveai` and import `mangrove_ai`.
7
+
8
+ **Major product migration:** `@mangrove-ai/sdk` 0.1.2, 0.2.0 and 0.3.0 are
9
+ historical Markets packages. Version 1.0.0 is the MangroveAI SDK and does not
10
+ provide their `MangroveClient` API. Markets applications must install
11
+ `@mangrove-ai/markets` 0.4.0 after that release is verified, or use its reviewed
12
+ archive. Read the [migration notice](https://github.com/MangroveTechnologies/MangroveAI-SDK/blob/main/docs/typescript-package-migration.md)
13
+ before changing a pin. The old `@mangrove-ai/client` candidate was never published
14
+ and will not become a registry alias.
15
+
16
+ Check the [dated repository release status](https://github.com/MangroveTechnologies/MangroveAI-SDK/blob/main/docs/issue-66-release-handoff.md)
17
+ for registry availability and verified versions. Source, a local package and a
18
+ published npm release are separate states. For evaluation before a registry
19
+ release, build and install a reviewed local tarball:
20
+
21
+ ```sh
22
+ npm ci --ignore-scripts --prefix packages/typescript
23
+ npm pack ./packages/typescript
11
24
  ```
12
25
 
13
- `ethers` is an optional peer dependency -- only needed if you use the built-in `EthersSigner`.
14
-
15
- ## Quick Start
16
-
17
- ```typescript
18
- import { MangroveClient, EthersSigner } from '@mangrove-ai/sdk';
19
- import { Wallet } from 'ethers';
26
+ Run these commands from the source repository root with Node.js 20+. The archive
27
+ is written there, with a name based on that revision's `package.json` version.
28
+ Then install that reviewed archive in the consuming project, using its actual path:
20
29
 
21
- // 1. Create a signer (private key stays local, never sent to server)
22
- const wallet = new Wallet(process.env.PRIVATE_KEY!);
23
- const signer = new EthersSigner(wallet, [8453]); // Base chain ID
24
-
25
- // 2. Connect to MangroveMarkets
26
- const client = new MangroveClient({
27
- url: 'https://mangrovemarkets.com',
28
- transport: 'rest', // or 'mcp' for MCP protocol
29
- signer,
30
- });
31
- await client.connect();
32
-
33
- // 3. Swap tokens (one call handles everything)
34
- const result = await client.dex.swap({
35
- src: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC on Base
36
- dst: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2', // USDT on Base
37
- amount: '4000000', // 4 USDC (6 decimals)
38
- chainId: 8453, // Base
39
- slippage: 1.0, // 1% max slippage
40
- });
41
-
42
- console.log(`Swap confirmed: ${result.txHash}`);
43
- console.log(`Status: ${result.status}`);
44
- console.log(`Gas used: ${result.gasUsed}`);
45
-
46
- await client.disconnect();
30
+ ```sh
31
+ npm install /path/to/reviewed/mangrove-ai-sdk-1.0.0.tgz
47
32
  ```
48
33
 
49
- ## How It Works
50
-
51
- The SDK connects to the MangroveMarkets server, which aggregates DEX liquidity via 1inch across 12 EVM chains. The server returns unsigned transaction calldata -- your private key never leaves the client.
52
-
53
- ```
54
- Your App --> SDK --> MangroveMarkets Server --> 1inch API
55
- |
56
- +--> Local Signing (ethers.js or custom)
34
+ When installing a registry release, verify its exact version and package identity
35
+ first.
36
+
37
+ ## First request
38
+
39
+ Keep the API key in server-side configuration, outside browser bundles, prompts
40
+ and logs. The constructor can read `MANGROVE_API_KEY` or accept the key directly.
41
+ Development requires an explicit `baseUrl` or `MANGROVE_BASE_URL`. Keys beginning
42
+ with `test_` also require an explicit origin or `environment: 'local'`; they never
43
+ default to production. This selects routing, not server permission enforcement.
44
+
45
+ ```js
46
+ import { MangroveAI, APIError } from '@mangrove-ai/sdk';
47
+
48
+ const client = new MangroveAI({ apiKey: process.env.MANGROVE_API_KEY, timeoutMs: 30_000 });
49
+ try {
50
+ const metrics = await client.users.getMyMetrics();
51
+ console.log({ messages: metrics.messages_count });
52
+ } catch (error) {
53
+ if (error instanceof APIError) {
54
+ console.error({ status: error.status, code: error.code, correlationId: error.correlationId });
55
+ } else {
56
+ throw error;
57
+ }
58
+ }
57
59
  ```
58
60
 
59
- ### Swap Flow
61
+ This sends one Bearer-authenticated usage read. It does not create a wallet,
62
+ launch compute, connect a broker, invoke an MCP tool or send a payment.
60
63
 
61
- When you call `client.dex.swap()`, the SDK handles the full flow:
64
+ ## Supported surface
62
65
 
63
- 1. **Get quote** from the DEX aggregator
64
- 2. **Check allowance** -- does the router have permission to spend your tokens?
65
- 3. **Approve** (if needed) -- sign and broadcast an ERC-20 approval tx
66
- 4. **Prepare swap** -- get unsigned swap calldata from 1inch
67
- 5. **Sign locally** -- your private key signs the tx on your machine
68
- 6. **Broadcast** -- send the signed tx to the network
69
- 7. **Poll** until confirmed or failed
66
+ The named helpers are `users`, `signals`, `strategyWorkflow` and `backtesting`.
67
+ Other declared REST operations use `client.request(operation, options)`, with
68
+ generated path, parameter, body and response types. This is not Python helper
69
+ parity. The current classification has 264 core/Oracle proxy method/path keys,
70
+ including 10 v2 operations: 261 JSON/no-content, one separate redirect flow and
71
+ two streaming/non-JSON operations. Counts describe pinned declarations, not live
72
+ endpoint acceptance. The JSON transport does not perform the redirect or consume
73
+ those streams. Operation keys include the HTTP method and exact versioned path:
70
74
 
71
- ## API Reference
72
-
73
- ### MangroveClient
74
-
75
- ```typescript
76
- const client = new MangroveClient({
77
- url: string; // Server URL (e.g., 'https://mangrovemarkets.com')
78
- transport?: string; // 'mcp' (default) or 'rest'
79
- signer?: Signer; // Required for swap operations
80
- apiKey?: string; // Optional API key for authenticated endpoints
75
+ ```ts
76
+ const result = await client.request('GET /api/v1/strategies/{strategy_id}', {
77
+ path: { strategy_id: 'the-strategy-id' },
81
78
  });
82
-
83
- await client.connect(); // Open connection
84
- await client.disconnect(); // Close connection
85
79
  ```
86
80
 
87
- ### DexService (`client.dex`)
88
-
89
- #### High-Level
90
-
91
- ```typescript
92
- // Full swap -- handles quote, approve, sign, broadcast, poll
93
- const result = await client.dex.swap({
94
- src: string; // Source token address
95
- dst: string; // Destination token address
96
- amount: string; // Amount in smallest unit (wei)
97
- chainId: number; // EVM chain ID
98
- slippage?: number; // Max slippage % (default: 0.5)
99
- mevProtection?: boolean; // Flashbots MEV protection (default: false)
100
- mode?: 'standard' | 'x402'; // Billing mode (default: 'standard')
101
- });
102
- // Returns: { txHash, chainId, status, gasUsed, inputToken, outputToken, inputAmount, outputAmount }
81
+ The contracts and complete operation classification live in
82
+ `contracts/mangroveai/` in the source repository. Types describe server schema
83
+ declarations. They are not proof that every deployed response matches its model.
84
+ Unmodelled responses and legacy Raw JSON fields remain `unknown`. The transport
85
+ checks status, JSON, size and deadline; the metrics and pagination helpers also
86
+ validate their envelopes. Application code must narrow an opaque result.
87
+
88
+ The server's canonical strategy workflow schemas generate method names such as
89
+ `client.strategyWorkflow.getStrategy({ body: { strategy_id } })` and
90
+ `client.strategyWorkflow.saveStrategy({ body: ... })`. These helpers pass requests
91
+ to the same server operations; they do not copy composition, ranking or risk rules.
92
+
93
+ Mangrove owns deterministic risk management based on live market and account
94
+ conditions. The SDK carries requests and preserves the server's decisions and
95
+ results. It does not implement trading policy or establish that every execution
96
+ path enforces that product contract.
97
+
98
+ The Oracle projection uses the API proxy origin, not a private Oracle service
99
+ host. Its allowlist and HTTP methods come from the proxy. Some retail adapters
100
+ transform upstream backtest, simulation, experiment and condition envelopes;
101
+ their types remain opaque, with upstream declarations identified separately.
102
+ Server scopes, tenant access, entitlements and billing still apply.
103
+
104
+ The generated `ExecutionConfiguration` type describes normalized authoring
105
+ values from the backend's canonical configuration schema, including cooldown
106
+ fields and their required declarations. Transport inputs also accept a legacy
107
+ object escape hatch, preserving server compatibility with numeric strings and
108
+ other existing shapes. To read the server's schema and glossary explicitly:
109
+
110
+ ```ts
111
+ const config = await client.request('GET /api/v1/config/execution-config-schema', {});
112
+ console.log(config.json_schema);
103
113
  ```
104
114
 
105
- #### Low-Level (Step-by-Step Control)
115
+ This is one server request and may be billable. The client does not fetch it
116
+ automatically, prevalidate execution configuration or implement risk policy.
117
+ Normalized authoring guidance is separate from the server's accepted transport
118
+ input; nested guidance is not a claim that the HTTP boundary enforces all fields.
106
119
 
107
- ```typescript
108
- // Get a quote
109
- const quote = await client.dex.getQuote({
110
- src: '0xUSDC...',
111
- dst: '0xETH...',
112
- amount: '1000000',
113
- chainId: 8453,
114
- });
115
- // Returns: { quoteId, venueId, inputToken, outputToken, inputAmount, outputAmount, ... }
120
+ The generic JSON transport does not consume SSE, binary or HTML responses. It
121
+ rejects those formats instead of misrepresenting them as JSON. MCP discovery,
122
+ MCP OAuth, x402 signing and the separate legacy KB host are separate interfaces.
123
+ There is no automatic payment or automatic retry. A failed non-idempotent request
124
+ may need a server status read before the caller decides whether to repeat it.
116
125
 
117
- // Get unsigned approval tx (ERC-20 tokens only)
118
- const approveTx = await client.dex.approveToken({
119
- tokenAddress: '0xUSDC...',
120
- chainId: 8453,
121
- walletAddress: '0xYourWallet...',
122
- });
123
- // Returns: { chainId, to, data, value, gas, nonce, maxFeePerGas, ... }
126
+ ## Pagination and asynchronous jobs
124
127
 
125
- // Get unsigned swap tx
126
- const swapTx = await client.dex.prepareSwap({
127
- quoteId: quote.quoteId,
128
- walletAddress: '0xYourWallet...',
129
- slippage: 1.0,
130
- });
131
- // Returns: { chainId, to, data, value, gas, nonce, maxFeePerGas, ... }
132
-
133
- // Sign locally
134
- const signedTx = await signer.signTransaction(swapTx);
135
-
136
- // Broadcast
137
- const broadcast = await client.dex.broadcast({
138
- chainId: 8453,
139
- signedTx: signedTx,
140
- mevProtection: false,
141
- });
142
- // Returns: { txHash, chainId, broadcastMethod }
143
-
144
- // Poll status
145
- const status = await client.dex.txStatus({
146
- txHash: broadcast.txHash,
147
- chainId: 8453,
148
- });
149
- // Returns: { txHash, chainId, status, blockNumber, gasUsed }
150
- ```
151
-
152
- ### Supported Chains
153
-
154
- | Chain | ID | Status |
155
- |-------|----|--------|
156
- | Ethereum | 1 | Supported |
157
- | Base | 8453 | Supported (primary, proven) |
158
- | Arbitrum | 42161 | Supported |
159
- | Polygon | 137 | Supported |
160
- | Optimism | 10 | Supported |
161
- | BNB Chain | 56 | Supported |
162
- | Avalanche | 43114 | Supported |
163
- | Gnosis | 100 | Supported |
164
- | zkSync Era | 324 | Supported |
165
- | Linea | 59144 | Supported |
166
-
167
- ### Transport Options
168
-
169
- | Transport | Protocol | Best For |
170
- |-----------|----------|----------|
171
- | `'mcp'` (default) | MCP over Streamable HTTP | AI agents using MCP protocol |
172
- | `'rest'` | REST API over HTTPS | Direct HTTP integration, scripts |
173
-
174
- ### Custom Signers
175
-
176
- The SDK never touches private keys. Implement `Signer` for any signing backend:
177
-
178
- ```typescript
179
- import type { Signer, UnsignedTransaction } from '@mangrove-ai/sdk';
180
-
181
- class MyCustomSigner implements Signer {
182
- async getAddress(): Promise<string> { /* ... */ }
183
- async signTransaction(tx: UnsignedTransaction): Promise<string> { /* ... */ }
184
- async getSupportedChainIds(): Promise<number[]> { /* ... */ }
128
+ ```js
129
+ for await (const signal of client.signals.listIter({ limit: 100, category: 'momentum' })) {
130
+ console.log(signal.name);
185
131
  }
186
132
  ```
187
133
 
188
- Use cases: MPC wallets, hardware wallets (Ledger/Trezor), cloud KMS, custodial signing.
189
-
190
- ## Security
191
-
192
- - Private keys never leave the client -- server returns unsigned calldata only
193
- - HTTPS enforced for non-localhost connections
194
- - Tool names validated to prevent URL injection
195
- - Server error responses detected and thrown (not silently ignored)
196
- - Quote expiry checked before submitting stale quotes
197
- - Failed approvals detected and thrown (not silently continued)
198
-
199
- ## Examples
200
-
201
- See the [examples directory](https://github.com/MangroveTechnologies/MangroveMarkets/tree/main/packages/sdk/examples) for:
202
-
203
- - `basic.ts` -- Read-only operations (no signer needed)
204
- - `high-level-swap.ts` -- One-call swap via SwapOrchestrator
205
- - `low-level-swap.ts` -- Step-by-step control over the full flow
206
-
207
- ## Links
208
-
209
- - Server: https://mangrovemarkets.com
210
- - API Docs: https://mangrovemarkets.com/docs (Swagger) / https://mangrovemarkets.com/redoc (ReDoc)
211
- - GitHub: https://github.com/MangroveTechnologies/MangroveMarkets
212
- - Issues: https://github.com/MangroveTechnologies/MangroveMarkets/issues
213
-
214
- ## License
134
+ Pagination follows the server's `next_offset` rather than the requested page size.
135
+ Malformed, contradictory or repeated pages raise. Each page is a separate request
136
+ and may be billable. Stop iteration when the application has what it needs.
137
+
138
+ `client.backtesting.submit(body)` makes an explicit submission;
139
+ `getStatus(backtestId)` reads one status. `wait(backtestId, { timeoutMs,
140
+ pollIntervalMs, signal })` only polls that existing job. It returns completed,
141
+ failed and cancelled results without replacing them with a success. It enforces
142
+ one total polling deadline and never resubmits the job. Obtain the appropriate
143
+ approval before submitting compute; the SDK does not infer approval.
144
+
145
+ ## Configuration and errors
146
+
147
+ `baseUrl` or `MANGROVE_BASE_URL` accepts an API origin or its `/api/v1` or
148
+ `/api/v2` base. Both API versions stay on that origin. Production defaults to
149
+ `https://api.mangrovedeveloper.ai`. Development keys require an explicit origin;
150
+ the client does not fall back to production. HTTPS is required except for
151
+ loopback tests. API redirects are refused.
152
+
153
+ `timeoutMs` is a positive integer, default 30000. One deadline covers response
154
+ headers and the entire JSON body. `maxResponseBytes` defaults to 8 MiB and is
155
+ enforced against both the declared size and actual chunks. Request controls
156
+ accept an AbortSignal and a per-request timeout. An injected `fetch` can supply
157
+ test transport or a caller-managed cookie jar. Native Node fetch does not retain
158
+ session cookies; the recommended authentication path is an API key. A manual
159
+ session refresh requires the same session's Cookie and X-CSRF-Token headers and
160
+ has no JSON token body.
161
+
162
+ Errors include `APIError`, `ConfigurationError`, `MalformedResponseError`,
163
+ `RequestTimeoutError`, `RequestAbortedError` and `NetworkError`. `APIError`
164
+ exposes HTTP status, safe code/message, correlation ID and Retry-After. Its
165
+ non-enumerable `response` retains the redacted error envelope; `headers` retains
166
+ payment challenge/recovery and authentication headers. Inspect these explicitly
167
+ when handling a server decision. Default JSON serialization excludes them and
168
+ never includes request credentials. No payer or automatic recovery is invoked.
169
+
170
+ ## Build and release checks
171
+
172
+ From the repository root:
173
+
174
+ ```sh
175
+ python3 scripts/generate_typescript_contract.py --check
176
+ npm ci --ignore-scripts --prefix packages/typescript
177
+ npm run typecheck --prefix packages/typescript
178
+ npm test --prefix packages/typescript
179
+ node packages/typescript/test/packed-artifact.mjs
180
+ ```
215
181
 
216
- MIT
182
+ Updating contracts is a reviewed change. Export all three documents from the backend's
183
+ `scripts/export_developer_contracts.py` with network blocked, then regenerate the
184
+ TypeScript declarations and inspect the capability diff. Preserve the recorded
185
+ source revisions and hashes. Changes to the pinned inputs without regeneration
186
+ fail CI. A source-only check cannot detect an unobserved deployment change.
187
+
188
+ Package versioning is independent of Python. Verify the candidate name, exact
189
+ source commit, compatibility, installed tarball examples and required server
190
+ deployment before a maintainer publishes. Then read back the registry artifact
191
+ and update the consumer pins and public guide. Do not advertise a source candidate as
192
+ available from npm until those steps succeed.
193
+
194
+ The separate `Release MangroveAI TypeScript SDK` workflow is manual, runs from
195
+ reviewed `main` and defaults to `dry_run=true`. Its selected version must match
196
+ the manifest and lock, identify this repository's `@mangrove-ai/sdk` with major
197
+ version at least 1, and pass installed-package checks. Publishing first requires
198
+ verified `@mangrove-ai/markets` 0.4.0. It uses directory publication after official
199
+ npm preparation proves the selected source `gitHead`; it does not guess that
200
+ publishing a tarball adds source metadata.
201
+
202
+ After publishing, actual npm archive bytes must match the local SHA512 and
203
+ SHA-256. The native workflow then creates/verifies annotated
204
+ `typescript-v1.0.0`, a source/checksum-bound GitHub Release and immutable tarball,
205
+ checksum and provenance assets. Exact old Markets versions 0.1.2, 0.2.0 and 0.3.0
206
+ receive migration notices only after those checks. No package version, tag or
207
+ asset is overwritten, and the whole package name is never deprecated.
208
+
209
+ An optional full main-ancestor `release_commit` supports an interrupted release.
210
+ An already published artifact can resume only when its name, repository,
211
+ `gitHead`, integrity and downloaded bytes match the rebuilt original source.
212
+ Existing tags are dereferenced to their annotated commit; matching release
213
+ bodies/assets are retained and missing assets can be completed. Conflicts stop.
214
+ Dry runs never publish, tag, create releases or deprecate versions. Package
215
+ publication remains separate from deployed API and live acceptance.
216
+
217
+ For a new unpublished version, the selected source must still be fresh `main`
218
+ immediately before publishing. An older main ancestor is accepted only to finish
219
+ an already published artifact whose exact source and bytes were verified. It
220
+ cannot start a new publication or move npm `latest` back to stale source.