@mangrove-ai/sdk 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +159 -48
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,104 +1,215 @@
1
1
  # @mangrove-ai/sdk
2
2
 
3
- TypeScript SDK for MangroveMarkets -- DEX aggregation and agent marketplace with pluggable signing.
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)).
4
6
 
5
7
  ## Installation
6
8
 
7
9
  ```bash
8
- pnpm add @mangrove-ai/sdk
9
- # or
10
- npm install @mangrove-ai/sdk
10
+ npm install @mangrove-ai/sdk ethers
11
11
  ```
12
12
 
13
+ `ethers` is an optional peer dependency -- only needed if you use the built-in `EthersSigner`.
14
+
13
15
  ## Quick Start
14
16
 
15
17
  ```typescript
16
18
  import { MangroveClient, EthersSigner } from '@mangrove-ai/sdk';
17
19
  import { Wallet } from 'ethers';
18
20
 
21
+ // 1. Create a signer (private key stays local, never sent to server)
19
22
  const wallet = new Wallet(process.env.PRIVATE_KEY!);
20
- const signer = new EthersSigner(wallet, [8453]); // Base chain
23
+ const signer = new EthersSigner(wallet, [8453]); // Base chain ID
21
24
 
25
+ // 2. Connect to MangroveMarkets
22
26
  const client = new MangroveClient({
23
27
  url: 'https://mangrovemarkets.com',
28
+ transport: 'rest', // or 'mcp' for MCP protocol
24
29
  signer,
25
- transport: 'mcp', // or 'rest'
26
30
  });
27
-
28
31
  await client.connect();
29
32
 
30
- // High-level: one-call swap
33
+ // 3. Swap tokens (one call handles everything)
31
34
  const result = await client.dex.swap({
32
- src: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC
33
- dst: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', // ETH
34
- amount: '1000000', // 1 USDC
35
- chainId: 8453,
36
- slippage: 0.5,
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
37
40
  });
38
41
 
39
- console.log('Swap confirmed:', result.txHash);
42
+ console.log(`Swap confirmed: ${result.txHash}`);
43
+ console.log(`Status: ${result.status}`);
44
+ console.log(`Gas used: ${result.gasUsed}`);
45
+
40
46
  await client.disconnect();
41
47
  ```
42
48
 
43
- ## Architecture
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.
44
52
 
45
53
  ```
46
- MangroveClient
47
- |-- transport (MCP or REST)
48
- |-- dex (DexService + SwapOrchestrator)
49
- |-- oneinch (OneInchService)
50
- |-- signer (pluggable, never sees private keys)
54
+ Your App --> SDK --> MangroveMarkets Server --> 1inch API
55
+ |
56
+ +--> Local Signing (ethers.js or custom)
51
57
  ```
52
58
 
53
- ### Two API Levels
59
+ ### Swap Flow
60
+
61
+ When you call `client.dex.swap()`, the SDK handles the full flow:
62
+
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
70
+
71
+ ## API Reference
72
+
73
+ ### MangroveClient
54
74
 
55
- **High-level** -- one call does everything:
56
75
  ```typescript
57
- const result = await client.dex.swap({ src, dst, amount, chainId });
58
- // Handles: quote -> approve -> sign -> broadcast -> poll
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
81
+ });
82
+
83
+ await client.connect(); // Open connection
84
+ await client.disconnect(); // Close connection
85
+ ```
86
+
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 }
59
103
  ```
60
104
 
61
- **Low-level** -- step-by-step control:
105
+ #### Low-Level (Step-by-Step Control)
106
+
62
107
  ```typescript
63
- const quote = await client.dex.getQuote({ src, dst, amount, chainId });
64
- const approveTx = await client.dex.approveToken({ tokenAddress, chainId });
65
- const signed = await signer.signTransaction(approveTx);
66
- await client.dex.broadcast({ chainId, signedTx: signed });
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, ... }
116
+
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, ... }
124
+
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 }
67
150
  ```
68
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
+
69
167
  ### Transport Options
70
168
 
71
- | Transport | Protocol | Use Case |
169
+ | Transport | Protocol | Best For |
72
170
  |-----------|----------|----------|
73
- | `mcp` (default) | MCP over Streamable HTTP | AI agents via MCP |
74
- | `rest` | REST API (FastAPI) | Direct HTTP integration |
171
+ | `'mcp'` (default) | MCP over Streamable HTTP | AI agents using MCP protocol |
172
+ | `'rest'` | REST API over HTTPS | Direct HTTP integration, scripts |
75
173
 
76
- ### Signer Interface
174
+ ### Custom Signers
77
175
 
78
- The SDK never sees private keys. Implement the `Signer` interface:
176
+ The SDK never touches private keys. Implement `Signer` for any signing backend:
79
177
 
80
178
  ```typescript
81
- interface Signer {
82
- getAddress(): Promise<string>;
83
- signTransaction(tx: UnsignedTransaction): Promise<string>;
84
- getSupportedChainIds(): Promise<number[]>;
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[]> { /* ... */ }
85
185
  }
86
186
  ```
87
187
 
88
- Built-in: `EthersSigner` wraps an ethers.js Wallet. Bring your own for MPC wallets, hardware wallets, or custom signing.
188
+ Use cases: MPC wallets, hardware wallets (Ledger/Trezor), cloud KMS, custodial signing.
89
189
 
90
- ## Services
190
+ ## Security
91
191
 
92
- | Service | Methods |
93
- |---------|---------|
94
- | `client.dex` | getQuote, prepareSwap, approveToken, broadcast, txStatus, swap |
95
- | `client.oneinch` | getBalances, getAllowances, getSpotPrice, getGasPrice, searchTokens, getTokenInfo, getPortfolioValue, getPortfolioPnl, getPortfolioTokens, getPortfolioDefi, getChart, getHistory |
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)
96
198
 
97
- ## Security
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
98
208
 
99
- - No tool accepts private keys -- the server returns unsigned calldata
100
- - Signing happens locally via the Signer interface
101
- - The SDK itself never stores or transmits secrets
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
102
213
 
103
214
  ## License
104
215
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mangrove-ai/sdk",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "TypeScript SDK for MangroveMarkets -- DEX aggregation and agent marketplace with pluggable signing",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",