@mangrove-ai/sdk 0.3.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/dist/index.cjs DELETED
@@ -1,903 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- DexService: () => DexService,
24
- EthersSigner: () => EthersSigner,
25
- MangroveClient: () => MangroveClient,
26
- MarketplaceService: () => MarketplaceService,
27
- McpTransport: () => McpTransport,
28
- OneInchService: () => OneInchService,
29
- RestTransport: () => RestTransport,
30
- WalletService: () => WalletService
31
- });
32
- module.exports = __toCommonJS(index_exports);
33
-
34
- // src/transport/mcp.ts
35
- var import_client = require("@modelcontextprotocol/sdk/client/index.js");
36
- var import_streamableHttp = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
37
- var McpTransport = class {
38
- /**
39
- * Create an MCP transport targeting the given server URL.
40
- * @param url - MCP server endpoint URL.
41
- * @param apiKey - Optional Bearer token for authenticated requests.
42
- */
43
- constructor(url, apiKey) {
44
- this.client = null;
45
- this.url = url;
46
- this.apiKey = apiKey;
47
- }
48
- async connect() {
49
- const headers = {};
50
- if (this.apiKey) {
51
- headers["Authorization"] = `Bearer ${this.apiKey}`;
52
- }
53
- const mcpTransport = new import_streamableHttp.StreamableHTTPClientTransport(
54
- new URL(this.url),
55
- { requestInit: { headers } }
56
- );
57
- this.client = new import_client.Client({ name: "mangrove-sdk", version: "0.1.0" });
58
- await this.client.connect(mcpTransport);
59
- }
60
- async callTool(name, params) {
61
- if (!this.client) {
62
- throw new Error("Not connected. Call connect() first.");
63
- }
64
- const result = await this.client.callTool({ name, arguments: params });
65
- const textContent = result.content?.find((c) => c.type === "text");
66
- if (!textContent) {
67
- throw new Error(`No text content in response for tool: ${name}`);
68
- }
69
- try {
70
- return JSON.parse(textContent.text);
71
- } catch {
72
- throw new Error(`Invalid JSON in MCP response for tool '${name}'`);
73
- }
74
- }
75
- async disconnect() {
76
- if (this.client) {
77
- await this.client.close();
78
- this.client = null;
79
- }
80
- }
81
- };
82
-
83
- // src/transport/rest.ts
84
- var TOOL_NAME_PATTERN = /^[a-z][a-z0-9_]*$/;
85
- var RestTransport = class {
86
- /**
87
- * Create a REST transport targeting the given base URL with optional API key.
88
- * @param baseUrl - Base URL of the FastAPI server (trailing slash is stripped). Must use HTTPS unless localhost.
89
- * @param apiKey - Optional Bearer token for authenticated requests.
90
- */
91
- constructor(baseUrl, apiKey) {
92
- const url = baseUrl.replace(/\/$/, "");
93
- if (!url.startsWith("https://") && !url.startsWith("http://localhost") && !url.startsWith("http://127.0.0.1")) {
94
- throw new Error(`RestTransport requires HTTPS for non-local URLs (got: ${url})`);
95
- }
96
- this.baseUrl = url;
97
- this.apiKey = apiKey;
98
- }
99
- async callTool(name, params) {
100
- if (!TOOL_NAME_PATTERN.test(name)) {
101
- throw new Error(`Invalid tool name: ${name}`);
102
- }
103
- const headers = {
104
- "Content-Type": "application/json"
105
- };
106
- if (this.apiKey) {
107
- headers["Authorization"] = `Bearer ${this.apiKey}`;
108
- }
109
- const response = await fetch(`${this.baseUrl}/api/v1/tools/${name}`, {
110
- method: "POST",
111
- headers,
112
- body: JSON.stringify(params)
113
- });
114
- if (!response.ok) {
115
- const body2 = await response.json().catch(() => ({}));
116
- throw new Error(
117
- `REST call to ${name} failed (${response.status}): ${body2.message || response.statusText}`
118
- );
119
- }
120
- const body = await response.json();
121
- if (body && body.error === true) {
122
- const msg = body.message || body.code || "unknown error";
123
- throw new Error(`Tool ${name} failed: ${msg}`);
124
- }
125
- return body;
126
- }
127
- async connect() {
128
- }
129
- async disconnect() {
130
- }
131
- };
132
-
133
- // src/utils/normalize.ts
134
- function normalizeQuote(raw) {
135
- return {
136
- quoteId: raw.quote_id ?? raw.quoteId,
137
- venueId: raw.venue_id ?? raw.venueId,
138
- inputToken: raw.input_token ?? raw.inputToken ?? raw.src_token_address,
139
- outputToken: raw.output_token ?? raw.outputToken ?? raw.dst_token_address,
140
- inputAmount: String(raw.input_amount ?? raw.inputAmount ?? "0"),
141
- outputAmount: String(raw.output_amount ?? raw.outputAmount ?? "0"),
142
- mangroveFee: String(raw.mangrove_fee ?? raw.mangroveFee ?? "0"),
143
- chainId: raw.chain_id ?? raw.chainId,
144
- billingMode: raw.billing_mode ?? raw.billingMode ?? "standard",
145
- routes: raw.routes ?? [],
146
- expiresAt: raw.expires_at ?? raw.expiresAt ?? ""
147
- };
148
- }
149
- function normalizeUnsignedTx(raw) {
150
- const payload = raw.payload ?? {};
151
- const chainId = payload.chainId ?? raw.chain_id ?? raw.chainId;
152
- const nonce = payload.nonce ?? raw.nonce;
153
- return {
154
- chainId,
155
- to: payload.to ?? raw.to,
156
- data: payload.data ?? raw.data,
157
- value: String(payload.value ?? raw.value ?? "0"),
158
- gas: String(payload.gas ?? raw.gas ?? "0"),
159
- ...nonce != null ? { nonce: Number(nonce) } : {},
160
- ...payload.gasPrice ? { gasPrice: String(payload.gasPrice) } : {},
161
- ...payload.maxFeePerGas ? { maxFeePerGas: String(payload.maxFeePerGas) } : {},
162
- ...payload.maxPriorityFeePerGas ? { maxPriorityFeePerGas: String(payload.maxPriorityFeePerGas) } : {}
163
- };
164
- }
165
- function normalizeBroadcastResult(raw) {
166
- return {
167
- txHash: raw.tx_hash ?? raw.txHash,
168
- chainId: raw.chain_id ?? raw.chainId,
169
- broadcastMethod: raw.broadcast_method ?? raw.broadcastMethod ?? "public"
170
- };
171
- }
172
- function normalizeTransactionStatus(raw) {
173
- return {
174
- txHash: raw.tx_hash ?? raw.txHash,
175
- chainId: raw.chain_id ?? raw.chainId,
176
- status: raw.status,
177
- ...raw.block_number != null || raw.blockNumber != null ? { blockNumber: raw.block_number ?? raw.blockNumber } : {},
178
- ...raw.gas_used != null || raw.gasUsed != null ? { gasUsed: String(raw.gas_used ?? raw.gasUsed) } : {}
179
- };
180
- }
181
- function normalizeTokenBalance(raw) {
182
- return {
183
- address: raw.address ?? "",
184
- balance: String(raw.balance ?? "0"),
185
- decimals: raw.decimals ?? 0,
186
- symbol: raw.symbol ?? "",
187
- name: raw.name ?? ""
188
- };
189
- }
190
- function normalizeGasPrice(raw) {
191
- return {
192
- baseFee: String(raw.baseFee ?? raw.base_fee ?? "0"),
193
- maxPriorityFeePerGas: String(raw.maxPriorityFeePerGas ?? raw.max_priority_fee_per_gas ?? "0"),
194
- maxFeePerGas: String(raw.maxFeePerGas ?? raw.max_fee_per_gas ?? "0")
195
- };
196
- }
197
- function normalizeTokenInfo(raw) {
198
- return {
199
- address: raw.address ?? "",
200
- symbol: raw.symbol ?? "",
201
- name: raw.name ?? "",
202
- decimals: raw.decimals ?? 0,
203
- logoURI: raw.logoURI ?? raw.logo_uri ?? raw.logoUrl ?? raw.logo_url ?? ""
204
- };
205
- }
206
- function normalizeCreateListingResult(raw) {
207
- return {
208
- listingId: raw.listing_id ?? raw.listingId,
209
- status: raw.status ?? "active",
210
- createdAt: raw.created_at ?? raw.createdAt ?? ""
211
- };
212
- }
213
- function normalizeListing(raw) {
214
- return {
215
- listingId: raw.listing_id ?? raw.listingId,
216
- sellerAddress: raw.seller_address ?? raw.sellerAddress,
217
- title: raw.title ?? "",
218
- description: raw.description ?? "",
219
- category: raw.category ?? "other",
220
- subcategory: raw.subcategory ?? null,
221
- priceXrp: raw.price_xrp ?? raw.priceXrp ?? 0,
222
- listingType: raw.listing_type ?? raw.listingType ?? "static",
223
- status: raw.status ?? "active",
224
- tags: raw.tags ?? [],
225
- storageUri: raw.storage_uri ?? raw.storageUri ?? null,
226
- contentHash: raw.content_hash ?? raw.contentHash ?? null,
227
- createdAt: raw.created_at ?? raw.createdAt ?? "",
228
- updatedAt: raw.updated_at ?? raw.updatedAt ?? "",
229
- expiresAt: raw.expires_at ?? raw.expiresAt ?? null
230
- };
231
- }
232
- function normalizeSearchResult(raw) {
233
- const rawListings = raw.listings ?? [];
234
- return {
235
- listings: rawListings.map(normalizeListing),
236
- totalCount: raw.total_count ?? raw.totalCount ?? 0,
237
- nextCursor: raw.next_cursor ?? raw.nextCursor ?? null
238
- };
239
- }
240
-
241
- // src/dex/service.ts
242
- var DexService = class {
243
- constructor(transport) {
244
- this.transport = transport;
245
- }
246
- /**
247
- * Request a swap quote from the DEX aggregator.
248
- * @param params - Quote parameters (src, dst, amount, chainId, mode).
249
- * @returns A server-issued Quote with pricing and expiry.
250
- */
251
- async getQuote(params) {
252
- const result = await this.transport.callTool("dex_get_quote", {
253
- input_token: params.src,
254
- output_token: params.dst,
255
- amount: params.amount,
256
- chain_id: params.chainId,
257
- mode: params.mode || "standard"
258
- });
259
- return normalizeQuote(result);
260
- }
261
- /**
262
- * Convert a quote into unsigned swap calldata ready for signing.
263
- * @param quoteId - ID from a previously obtained Quote.
264
- * @param slippage - Maximum slippage percentage (default 0.5%).
265
- * @returns Unsigned transaction calldata for the swap.
266
- */
267
- async prepareSwap(params) {
268
- const result = await this.transport.callTool("dex_prepare_swap", {
269
- quote_id: params.quoteId,
270
- wallet_address: params.walletAddress,
271
- slippage: params.slippage ?? 0.5
272
- });
273
- return normalizeUnsignedTx(result);
274
- }
275
- /**
276
- * Generate an unsigned ERC-20 approval transaction for the DEX router.
277
- * @param params - Token address, chain ID, and optional specific amount.
278
- * @returns Unsigned approval transaction calldata.
279
- */
280
- async approveToken(params) {
281
- const result = await this.transport.callTool("dex_approve_token", {
282
- token_address: params.tokenAddress,
283
- chain_id: params.chainId,
284
- wallet_address: params.walletAddress,
285
- ...params.amount ? { amount: params.amount } : {}
286
- });
287
- return normalizeUnsignedTx(result);
288
- }
289
- /**
290
- * Broadcast a signed transaction to the network.
291
- * @param params - Chain ID, signed transaction hex, and MEV protection flag.
292
- * @returns Broadcast result with transaction hash.
293
- */
294
- async broadcast(params) {
295
- const result = await this.transport.callTool("dex_broadcast", {
296
- chain_id: params.chainId,
297
- signed_tx: params.signedTx,
298
- mev_protection: params.mevProtection || false
299
- });
300
- return normalizeBroadcastResult(result);
301
- }
302
- /**
303
- * Check the on-chain status of a transaction.
304
- * @param params - Transaction hash and chain ID.
305
- * @returns Current transaction status (pending, confirmed, or failed).
306
- */
307
- async txStatus(params) {
308
- const result = await this.transport.callTool("dex_tx_status", {
309
- tx_hash: params.txHash,
310
- chain_id: params.chainId
311
- });
312
- return normalizeTransactionStatus(result);
313
- }
314
- /**
315
- * List all venues supported by the DEX aggregator.
316
- * @returns Supported venue metadata.
317
- */
318
- async supportedVenues() {
319
- return this.transport.callTool("dex_supported_venues", {});
320
- }
321
- /**
322
- * List supported trading pairs, optionally filtered by chain or venue.
323
- * @param chainId - Optional chain ID filter.
324
- * @param venue - Optional venue name filter (e.g. '1inch').
325
- * @returns Supported trading pair metadata.
326
- */
327
- async supportedPairs(venueId) {
328
- return this.transport.callTool("dex_supported_pairs", {
329
- venue_id: venueId
330
- });
331
- }
332
- };
333
-
334
- // src/dex/swap.ts
335
- var NATIVE_TOKEN = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
336
- var POLL_INTERVAL_MS = 2e3;
337
- var MAX_POLLS = 60;
338
- var SwapOrchestrator = class {
339
- constructor(dex, signer, transport) {
340
- this.dex = dex;
341
- this.signer = signer;
342
- this.transport = transport;
343
- }
344
- /**
345
- * Execute a full swap from quote through on-chain confirmation.
346
- *
347
- * Flow: get quote -> check ERC-20 allowance (skip for native tokens) ->
348
- * approve if needed -> prepare unsigned swap tx -> sign locally ->
349
- * broadcast -> poll until confirmed or failed.
350
- *
351
- * @param params - Swap parameters (src, dst, amount, chainId, slippage, mevProtection, mode).
352
- * @returns Final swap result including tx hash, status, and amounts.
353
- * @throws If the transaction does not confirm within the polling timeout.
354
- */
355
- async swap(params) {
356
- const slippage = params.slippage ?? 0.5;
357
- const mevProtection = params.mevProtection ?? false;
358
- const mode = params.mode ?? "standard";
359
- const quote = await this.dex.getQuote({
360
- src: params.src,
361
- dst: params.dst,
362
- amount: params.amount,
363
- chainId: params.chainId,
364
- mode
365
- });
366
- if (quote.expiresAt) {
367
- const expiry = new Date(quote.expiresAt);
368
- if (!isNaN(expiry.getTime()) && expiry < /* @__PURE__ */ new Date()) {
369
- throw new Error(`Quote ${quote.quoteId} expired at ${quote.expiresAt}. Re-fetch a fresh quote.`);
370
- }
371
- }
372
- const isNativeToken = params.src.toLowerCase() === NATIVE_TOKEN.toLowerCase();
373
- if (!isNativeToken) {
374
- const needsApproval = await this.checkNeedsApproval(params.src, params.chainId);
375
- if (needsApproval) {
376
- await this.approveAndWait(params.src, params.chainId);
377
- }
378
- }
379
- const walletAddress = await this.signer.getAddress();
380
- const unsignedTx = await this.dex.prepareSwap({ quoteId: quote.quoteId, walletAddress, slippage });
381
- const signedTx = await this.signer.signTransaction(unsignedTx);
382
- const broadcastResult = await this.dex.broadcast({
383
- chainId: params.chainId,
384
- signedTx,
385
- mevProtection
386
- });
387
- const status = await this.pollStatus(broadcastResult.txHash, params.chainId);
388
- return {
389
- txHash: broadcastResult.txHash,
390
- chainId: params.chainId,
391
- status: status.status,
392
- gasUsed: status.gasUsed || "0",
393
- inputToken: quote.inputToken,
394
- outputToken: quote.outputToken,
395
- inputAmount: quote.inputAmount,
396
- outputAmount: quote.outputAmount
397
- };
398
- }
399
- async checkNeedsApproval(tokenAddress, chainId) {
400
- const walletAddress = await this.signer.getAddress();
401
- const result = await this.transport.callTool("oneinch_allowances", {
402
- chain_id: chainId,
403
- wallet_address: walletAddress,
404
- spender: "router"
405
- });
406
- const raw = result;
407
- const allowanceMap = typeof raw.allowances === "object" && raw.allowances !== null ? raw.allowances : raw;
408
- const value = allowanceMap[tokenAddress];
409
- if (value === void 0 || value === null || value === "0") {
410
- return true;
411
- }
412
- try {
413
- return BigInt(value) === 0n;
414
- } catch {
415
- return true;
416
- }
417
- }
418
- async approveAndWait(tokenAddress, chainId) {
419
- const walletAddress = await this.signer.getAddress();
420
- const approveTx = await this.dex.approveToken({ tokenAddress, chainId, walletAddress });
421
- const signedApproval = await this.signer.signTransaction(approveTx);
422
- const approvalBroadcast = await this.dex.broadcast({
423
- chainId,
424
- signedTx: signedApproval
425
- });
426
- const status = await this.pollStatus(approvalBroadcast.txHash, chainId);
427
- if (status.status === "failed") {
428
- throw new Error(`Approval transaction failed on-chain: ${approvalBroadcast.txHash}`);
429
- }
430
- }
431
- async pollStatus(txHash, chainId) {
432
- for (let i = 0; i < MAX_POLLS; i++) {
433
- const status = await this.dex.txStatus({ txHash, chainId });
434
- if (status.status === "confirmed" || status.status === "failed") {
435
- return status;
436
- }
437
- await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
438
- }
439
- throw new Error(`Transaction ${txHash} did not confirm within ${MAX_POLLS * POLL_INTERVAL_MS / 1e3}s`);
440
- }
441
- };
442
-
443
- // src/oneinch/service.ts
444
- var OneInchService = class {
445
- constructor(transport) {
446
- this.transport = transport;
447
- }
448
- /**
449
- * Get ERC-20 token balances for a wallet.
450
- * @param params - Chain ID and wallet address.
451
- * @returns Array of token balances with symbol, decimals, and name.
452
- */
453
- async getBalances(params) {
454
- const result = await this.transport.callTool("oneinch_balances", {
455
- chain_id: params.chainId,
456
- wallet: params.wallet
457
- });
458
- const raw = result;
459
- const balances = raw.balances;
460
- if (Array.isArray(balances)) {
461
- return balances.map((b) => normalizeTokenBalance(b));
462
- }
463
- if (balances && typeof balances === "object") {
464
- return Object.entries(balances).map(
465
- ([address, balance]) => normalizeTokenBalance({ address, balance: String(balance) })
466
- );
467
- }
468
- return [];
469
- }
470
- /**
471
- * Get ERC-20 token allowances for a wallet and spender.
472
- * @param params - Chain ID, wallet address, and spender identifier.
473
- * @returns Token address to allowance mapping.
474
- */
475
- async getAllowances(params) {
476
- return this.transport.callTool("oneinch_allowances", {
477
- chain_id: params.chainId,
478
- wallet: params.wallet,
479
- spender: params.spender
480
- });
481
- }
482
- /**
483
- * Get current spot prices for one or more tokens.
484
- * @param params - Chain ID and comma-separated token addresses.
485
- * @returns Token address to USD price mapping.
486
- */
487
- async getSpotPrice(params) {
488
- return this.transport.callTool("oneinch_spot_price", {
489
- chain_id: params.chainId,
490
- tokens: params.tokens
491
- });
492
- }
493
- /**
494
- * Get current gas price estimates for a chain.
495
- * @param params - Chain ID.
496
- * @returns Typed gas price data (baseFee, maxPriorityFeePerGas, maxFeePerGas).
497
- */
498
- async getGasPrice(params) {
499
- const result = await this.transport.callTool("oneinch_gas_price", {
500
- chain_id: params.chainId
501
- });
502
- return normalizeGasPrice(result);
503
- }
504
- /**
505
- * Search for tokens by name or symbol on a given chain.
506
- * @param params - Chain ID and search query string.
507
- * @returns Matching token metadata.
508
- */
509
- async searchTokens(params) {
510
- return this.transport.callTool("oneinch_token_search", {
511
- chain_id: params.chainId,
512
- query: params.query
513
- });
514
- }
515
- /**
516
- * Get detailed metadata for a specific token.
517
- * @param params - Chain ID and token contract address.
518
- * @returns Typed token info (address, symbol, name, decimals, logoURI).
519
- */
520
- async getTokenInfo(params) {
521
- const result = await this.transport.callTool("oneinch_token_info", {
522
- chain_id: params.chainId,
523
- address: params.address
524
- });
525
- return normalizeTokenInfo(result);
526
- }
527
- /**
528
- * Get total portfolio value in USD for one or more wallet addresses.
529
- * @param params - Comma-separated wallet addresses and optional chain ID filter.
530
- * @returns Aggregated portfolio value.
531
- */
532
- async getPortfolioValue(params) {
533
- return this.transport.callTool("oneinch_portfolio_value", {
534
- addresses: params.addresses,
535
- ...params.chainId ? { chain_id: params.chainId } : {}
536
- });
537
- }
538
- /**
539
- * Get profit and loss data for a portfolio.
540
- * @param params - Comma-separated wallet addresses and optional chain ID filter.
541
- * @returns PnL breakdown by token and chain.
542
- */
543
- async getPortfolioPnl(params) {
544
- return this.transport.callTool("oneinch_portfolio_pnl", {
545
- addresses: params.addresses,
546
- ...params.chainId ? { chain_id: params.chainId } : {}
547
- });
548
- }
549
- /**
550
- * Get token holdings breakdown for a portfolio.
551
- * @param params - Comma-separated wallet addresses and optional chain ID filter.
552
- * @returns Per-token balances and values.
553
- */
554
- async getPortfolioTokens(params) {
555
- return this.transport.callTool("oneinch_portfolio_tokens", {
556
- addresses: params.addresses,
557
- ...params.chainId ? { chain_id: params.chainId } : {}
558
- });
559
- }
560
- /**
561
- * Get DeFi protocol positions for a portfolio.
562
- * @param params - Comma-separated wallet addresses and optional chain ID filter.
563
- * @returns DeFi positions by protocol.
564
- */
565
- async getPortfolioDefi(params) {
566
- return this.transport.callTool("oneinch_portfolio_defi", {
567
- addresses: params.addresses,
568
- ...params.chainId ? { chain_id: params.chainId } : {}
569
- });
570
- }
571
- /**
572
- * Get portfolio value chart data over time.
573
- * @param params - Chain ID, wallet address, and optional time range (default '1month').
574
- * @returns Time-series chart data points.
575
- */
576
- async getChart(params) {
577
- return this.transport.callTool("oneinch_chart", {
578
- chain_id: params.chainId,
579
- address: params.address,
580
- timerange: params.timerange || "1month"
581
- });
582
- }
583
- /**
584
- * Get transaction history for a wallet address.
585
- * @param params - Wallet address and optional result limit (default 50).
586
- * @returns Recent transaction records.
587
- */
588
- async getHistory(params) {
589
- return this.transport.callTool("oneinch_history", {
590
- address: params.address,
591
- limit: params.limit || 50
592
- });
593
- }
594
- };
595
-
596
- // src/wallet/service.ts
597
- var WalletService = class {
598
- constructor(transport) {
599
- this.transport = transport;
600
- }
601
- /**
602
- * Get chain configuration: supported networks, RPC URLs, native token info.
603
- * Call this before creating a wallet to understand chain requirements.
604
- * @param params - Optional chain family filter (defaults to 'xrpl').
605
- */
606
- async chainInfo(params = {}) {
607
- const result = await this.transport.callTool("wallet_chain_info", {
608
- chain: params.chain ?? "xrpl"
609
- });
610
- return normalizeChainInfo(result);
611
- }
612
- /**
613
- * Create a new wallet. XRPL wallets are funded via testnet/devnet faucet.
614
- * EVM wallets generate a random keypair. Solana is Phase 3.
615
- * @param params - Chain, network, and optional chain ID.
616
- */
617
- async create(params = {}) {
618
- const toolParams = {
619
- chain: params.chain ?? "xrpl",
620
- network: params.network ?? "testnet"
621
- };
622
- if (params.chainId !== void 0) {
623
- toolParams.chain_id = params.chainId;
624
- }
625
- const result = await this.transport.callTool("wallet_create", toolParams);
626
- return normalizeCreateResult(result);
627
- }
628
- /**
629
- * Check wallet balance. Currently returns NOT_IMPLEMENTED from the server.
630
- * @param params - Address, chain, and optional chain ID.
631
- */
632
- async balance(params) {
633
- const toolParams = {
634
- address: params.address,
635
- chain: params.chain ?? "xrpl"
636
- };
637
- if (params.chainId !== void 0) {
638
- toolParams.chain_id = params.chainId;
639
- }
640
- return this.transport.callTool("wallet_balance", toolParams);
641
- }
642
- /**
643
- * List recent transactions for an address. Currently returns NOT_IMPLEMENTED from the server.
644
- * @param params - Address, chain, optional chain ID and limit.
645
- */
646
- async transactions(params) {
647
- const toolParams = {
648
- address: params.address,
649
- chain: params.chain ?? "xrpl",
650
- limit: params.limit ?? 20
651
- };
652
- if (params.chainId !== void 0) {
653
- toolParams.chain_id = params.chainId;
654
- }
655
- return this.transport.callTool("wallet_transactions", toolParams);
656
- }
657
- };
658
- function normalizeChainInfo(raw) {
659
- return {
660
- chain: raw.chain,
661
- chainFamily: raw.chain_family ?? raw.chainFamily,
662
- nativeToken: raw.native_token ?? raw.nativeToken,
663
- walletCreation: raw.wallet_creation ?? raw.walletCreation,
664
- networks: raw.networks,
665
- supportedChainIds: raw.supported_chain_ids ?? raw.supportedChainIds,
666
- sdkMethod: raw.sdk_method ?? raw.sdkMethod
667
- };
668
- }
669
- function normalizeCreateResult(raw) {
670
- return {
671
- address: raw.address,
672
- chain: raw.chain,
673
- network: raw.network,
674
- isFunded: raw.is_funded ?? raw.isFunded ?? false,
675
- warnings: raw.warnings ?? [],
676
- secret: raw.secret,
677
- seedPhrase: raw.seed_phrase ?? raw.seedPhrase,
678
- privateKey: raw.private_key ?? raw.privateKey,
679
- chainId: raw.chain_id ?? raw.chainId
680
- };
681
- }
682
-
683
- // src/marketplace/service.ts
684
- var MarketplaceService = class {
685
- constructor(transport) {
686
- this.transport = transport;
687
- }
688
- /**
689
- * Create a new listing on the Mangrove Marketplace.
690
- * @param params - Listing details (seller address, title, category, price, etc.).
691
- * @returns Compact result with listing ID, status, and creation timestamp.
692
- */
693
- async createListing(params) {
694
- const result = await this.transport.callTool("marketplace_create_listing", {
695
- seller_address: params.sellerAddress,
696
- title: params.title,
697
- description: params.description,
698
- category: params.category,
699
- price_xrp: params.priceXrp,
700
- ...params.listingType ? { listing_type: params.listingType } : {},
701
- ...params.storageUri ? { storage_uri: params.storageUri } : {},
702
- ...params.contentHash ? { content_hash: params.contentHash } : {},
703
- ...params.subcategory ? { subcategory: params.subcategory } : {},
704
- ...params.tags ? { tags: params.tags } : {}
705
- });
706
- return normalizeCreateListingResult(result);
707
- }
708
- /**
709
- * Search the Mangrove Marketplace for listings.
710
- * @param params - Optional filters (query, category, price range, type, limit).
711
- * @returns Paginated search results with listings and total count.
712
- */
713
- async search(params = {}) {
714
- const result = await this.transport.callTool("marketplace_search", {
715
- ...params.query != null ? { query: params.query } : {},
716
- ...params.category != null ? { category: params.category } : {},
717
- ...params.minPrice != null ? { min_price: params.minPrice } : {},
718
- ...params.maxPrice != null ? { max_price: params.maxPrice } : {},
719
- ...params.listingType != null ? { listing_type: params.listingType } : {},
720
- ...params.limit != null ? { limit: params.limit } : {}
721
- });
722
- return normalizeSearchResult(result);
723
- }
724
- /**
725
- * Get full details of a specific listing by ID.
726
- * @param listingId - The listing's unique identifier.
727
- * @returns Full listing details.
728
- */
729
- async getListing(listingId) {
730
- const result = await this.transport.callTool("marketplace_get_listing", {
731
- listing_id: listingId
732
- });
733
- return normalizeListing(result);
734
- }
735
- /**
736
- * Make an offer on a marketplace listing.
737
- * Note: This tool is a stub on the server (returns NOT_IMPLEMENTED).
738
- * @param params - Listing ID and buyer address.
739
- * @returns Raw server response.
740
- */
741
- async makeOffer(params) {
742
- return this.transport.callTool("marketplace_make_offer", {
743
- listing_id: params.listingId,
744
- buyer_address: params.buyerAddress
745
- });
746
- }
747
- /**
748
- * Accept an offer, creating XRPL escrow.
749
- * Note: This tool is a stub on the server (returns NOT_IMPLEMENTED).
750
- * @param params - Offer ID and seller address.
751
- * @returns Raw server response.
752
- */
753
- async acceptOffer(params) {
754
- return this.transport.callTool("marketplace_accept_offer", {
755
- offer_id: params.offerId,
756
- seller_address: params.sellerAddress
757
- });
758
- }
759
- /**
760
- * Confirm delivery and release escrow to seller.
761
- * Note: This tool is a stub on the server (returns NOT_IMPLEMENTED).
762
- * @param params - Offer ID and buyer address.
763
- * @returns Raw server response.
764
- */
765
- async confirmDelivery(params) {
766
- return this.transport.callTool("marketplace_confirm_delivery", {
767
- offer_id: params.offerId,
768
- buyer_address: params.buyerAddress
769
- });
770
- }
771
- /**
772
- * Rate a completed marketplace transaction.
773
- * Note: This tool is a stub on the server (returns NOT_IMPLEMENTED).
774
- * @param params - Offer ID, rater address, score (1-5), optional comment.
775
- * @returns Raw server response.
776
- */
777
- async rate(params) {
778
- return this.transport.callTool("marketplace_rate", {
779
- offer_id: params.offerId,
780
- rater_address: params.raterAddress,
781
- score: params.score,
782
- ...params.comment != null ? { comment: params.comment } : {}
783
- });
784
- }
785
- };
786
-
787
- // src/client.ts
788
- var MangroveClient = class {
789
- /**
790
- * Create a MangroveClient. Uses MCP transport by default; pass transport: 'rest' for REST fallback.
791
- * @param config - Client configuration (url, signer, transport, apiKey).
792
- */
793
- constructor(config) {
794
- this.config = config;
795
- if (config.transport === "rest") {
796
- this.transport = new RestTransport(config.url, config.apiKey);
797
- } else {
798
- this.transport = new McpTransport(config.url, config.apiKey);
799
- }
800
- this._dex = new DexService(this.transport);
801
- this._oneinch = new OneInchService(this.transport);
802
- this._wallet = new WalletService(this.transport);
803
- this._marketplace = new MarketplaceService(this.transport);
804
- if (config.signer) {
805
- this._swapOrchestrator = new SwapOrchestrator(this._dex, config.signer, this.transport);
806
- }
807
- }
808
- /**
809
- * Access DEX operations. Includes low-level methods (getQuote, prepareSwap, approveToken,
810
- * broadcast, txStatus) and high-level swap() orchestration.
811
- * Calling swap() requires a Signer in the config.
812
- */
813
- get dex() {
814
- const service = this._dex;
815
- const orchestrator = this._swapOrchestrator;
816
- return new Proxy(service, {
817
- get(target, prop) {
818
- if (prop === "swap") {
819
- if (!orchestrator) {
820
- throw new Error("Signer required for swap(). Pass a signer in MangroveConfig.");
821
- }
822
- return orchestrator.swap.bind(orchestrator);
823
- }
824
- const value = target[prop];
825
- return typeof value === "function" ? value.bind(target) : value;
826
- }
827
- });
828
- }
829
- /**
830
- * Access 1inch ancillary operations: balances, gas prices, token info,
831
- * portfolio data, charts, and history.
832
- */
833
- get oneinch() {
834
- return this._oneinch;
835
- }
836
- /**
837
- * Access wallet operations: chain info, wallet creation, balance, and transaction history.
838
- */
839
- get wallet() {
840
- return this._wallet;
841
- }
842
- /**
843
- * Access marketplace operations: create listings, search, get details,
844
- * make offers, accept offers, confirm delivery, and rate transactions.
845
- */
846
- get marketplace() {
847
- return this._marketplace;
848
- }
849
- /** Open the transport connection. Must be called before making any tool calls. */
850
- async connect() {
851
- await this.transport.connect();
852
- }
853
- /** Close the transport connection and release resources. */
854
- async disconnect() {
855
- await this.transport.disconnect();
856
- }
857
- };
858
-
859
- // src/signer/ethers.ts
860
- var EthersSigner = class {
861
- /**
862
- * Create an EthersSigner from an ethers.js Wallet and list of supported chain IDs.
863
- * @param wallet - An ethers.js Wallet instance (or any object matching EthersWallet).
864
- * @param supportedChainIds - Chain IDs this wallet can sign transactions for.
865
- */
866
- constructor(wallet, supportedChainIds) {
867
- this.wallet = wallet;
868
- this.chainIds = supportedChainIds;
869
- }
870
- /** {@inheritDoc Signer.getAddress} */
871
- async getAddress() {
872
- return this.wallet.address;
873
- }
874
- /** {@inheritDoc Signer.signTransaction} */
875
- async signTransaction(tx) {
876
- return this.wallet.signTransaction({
877
- chainId: tx.chainId,
878
- to: tx.to,
879
- data: tx.data,
880
- value: tx.value,
881
- gasLimit: tx.gas,
882
- ...tx.nonce != null ? { nonce: tx.nonce } : {},
883
- ...tx.gasPrice ? { gasPrice: tx.gasPrice } : {},
884
- ...tx.maxFeePerGas ? { maxFeePerGas: tx.maxFeePerGas } : {},
885
- ...tx.maxPriorityFeePerGas ? { maxPriorityFeePerGas: tx.maxPriorityFeePerGas } : {}
886
- });
887
- }
888
- /** {@inheritDoc Signer.getSupportedChainIds} */
889
- async getSupportedChainIds() {
890
- return this.chainIds;
891
- }
892
- };
893
- // Annotate the CommonJS export names for ESM import in node:
894
- 0 && (module.exports = {
895
- DexService,
896
- EthersSigner,
897
- MangroveClient,
898
- MarketplaceService,
899
- McpTransport,
900
- OneInchService,
901
- RestTransport,
902
- WalletService
903
- });