@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 +21 -0
- package/README.md +198 -194
- package/dist/contract.generated.d.ts +7140 -0
- package/dist/contract.generated.js +2595 -0
- package/dist/contract.generated.js.map +1 -0
- package/dist/index.d.ts +101 -367
- package/dist/index.js +459 -426
- package/dist/index.js.map +1 -0
- package/package.json +16 -53
- package/dist/index.cjs +0 -471
- package/dist/index.d.cts +0 -371
package/dist/index.js
CHANGED
|
@@ -1,440 +1,473 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
var McpTransport = class {
|
|
5
|
-
/**
|
|
6
|
-
* Create an MCP transport targeting the given server URL.
|
|
7
|
-
* @param url - MCP server endpoint URL.
|
|
8
|
-
* @param apiKey - Optional Bearer token for authenticated requests.
|
|
9
|
-
*/
|
|
10
|
-
constructor(url, apiKey) {
|
|
11
|
-
this.client = null;
|
|
12
|
-
this.url = url;
|
|
13
|
-
this.apiKey = apiKey;
|
|
14
|
-
}
|
|
15
|
-
async connect() {
|
|
16
|
-
const headers = {};
|
|
17
|
-
if (this.apiKey) {
|
|
18
|
-
headers["Authorization"] = `Bearer ${this.apiKey}`;
|
|
19
|
-
}
|
|
20
|
-
const mcpTransport = new StreamableHTTPClientTransport(
|
|
21
|
-
new URL(this.url),
|
|
22
|
-
{ requestInit: { headers } }
|
|
23
|
-
);
|
|
24
|
-
this.client = new Client({ name: "mangrove-sdk", version: "0.1.0" });
|
|
25
|
-
await this.client.connect(mcpTransport);
|
|
26
|
-
}
|
|
27
|
-
async callTool(name, params) {
|
|
28
|
-
if (!this.client) {
|
|
29
|
-
throw new Error("Not connected. Call connect() first.");
|
|
30
|
-
}
|
|
31
|
-
const result = await this.client.callTool({ name, arguments: params });
|
|
32
|
-
const textContent = result.content?.find((c) => c.type === "text");
|
|
33
|
-
if (!textContent) {
|
|
34
|
-
throw new Error(`No text content in response for tool: ${name}`);
|
|
35
|
-
}
|
|
36
|
-
try {
|
|
37
|
-
return JSON.parse(textContent.text);
|
|
38
|
-
} catch {
|
|
39
|
-
throw new Error(`Invalid JSON in MCP response for tool '${name}'`);
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
async disconnect() {
|
|
43
|
-
if (this.client) {
|
|
44
|
-
await this.client.close();
|
|
45
|
-
this.client = null;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
};
|
|
49
|
-
|
|
50
|
-
// src/transport/rest.ts
|
|
51
|
-
var TOOL_NAME_PATTERN = /^[a-z][a-z0-9_]*$/;
|
|
52
|
-
var RestTransport = class {
|
|
53
|
-
/**
|
|
54
|
-
* Create a REST transport targeting the given base URL with optional API key.
|
|
55
|
-
* @param baseUrl - Base URL of the FastAPI server (trailing slash is stripped). Must use HTTPS unless localhost.
|
|
56
|
-
* @param apiKey - Optional Bearer token for authenticated requests.
|
|
57
|
-
*/
|
|
58
|
-
constructor(baseUrl, apiKey) {
|
|
59
|
-
const url = baseUrl.replace(/\/$/, "");
|
|
60
|
-
if (!url.startsWith("https://") && !url.startsWith("http://localhost") && !url.startsWith("http://127.0.0.1")) {
|
|
61
|
-
throw new Error(`RestTransport requires HTTPS for non-local URLs (got: ${url})`);
|
|
62
|
-
}
|
|
63
|
-
this.baseUrl = url;
|
|
64
|
-
this.apiKey = apiKey;
|
|
65
|
-
}
|
|
66
|
-
async callTool(name, params) {
|
|
67
|
-
if (!TOOL_NAME_PATTERN.test(name)) {
|
|
68
|
-
throw new Error(`Invalid tool name: ${name}`);
|
|
69
|
-
}
|
|
70
|
-
const headers = {
|
|
71
|
-
"Content-Type": "application/json"
|
|
72
|
-
};
|
|
73
|
-
if (this.apiKey) {
|
|
74
|
-
headers["Authorization"] = `Bearer ${this.apiKey}`;
|
|
75
|
-
}
|
|
76
|
-
const response = await fetch(`${this.baseUrl}/api/v1/tools/${name}`, {
|
|
77
|
-
method: "POST",
|
|
78
|
-
headers,
|
|
79
|
-
body: JSON.stringify(params)
|
|
80
|
-
});
|
|
81
|
-
if (!response.ok) {
|
|
82
|
-
const body2 = await response.json().catch(() => ({}));
|
|
83
|
-
throw new Error(
|
|
84
|
-
`REST call to ${name} failed (${response.status}): ${body2.message || response.statusText}`
|
|
85
|
-
);
|
|
86
|
-
}
|
|
87
|
-
const body = await response.json();
|
|
88
|
-
if (body && body.error === true) {
|
|
89
|
-
const msg = body.message || body.code || "unknown error";
|
|
90
|
-
throw new Error(`Tool ${name} failed: ${msg}`);
|
|
91
|
-
}
|
|
92
|
-
return body;
|
|
93
|
-
}
|
|
94
|
-
async connect() {
|
|
95
|
-
}
|
|
96
|
-
async disconnect() {
|
|
97
|
-
}
|
|
98
|
-
};
|
|
99
|
-
|
|
100
|
-
// src/utils/normalize.ts
|
|
101
|
-
function normalizeQuote(raw) {
|
|
102
|
-
return {
|
|
103
|
-
quoteId: raw.quote_id ?? raw.quoteId,
|
|
104
|
-
venueId: raw.venue_id ?? raw.venueId,
|
|
105
|
-
inputToken: raw.input_token ?? raw.inputToken ?? raw.src_token_address,
|
|
106
|
-
outputToken: raw.output_token ?? raw.outputToken ?? raw.dst_token_address,
|
|
107
|
-
inputAmount: String(raw.input_amount ?? raw.inputAmount ?? "0"),
|
|
108
|
-
outputAmount: String(raw.output_amount ?? raw.outputAmount ?? "0"),
|
|
109
|
-
mangroveFee: String(raw.mangrove_fee ?? raw.mangroveFee ?? "0"),
|
|
110
|
-
chainId: raw.chain_id ?? raw.chainId,
|
|
111
|
-
billingMode: raw.billing_mode ?? raw.billingMode ?? "standard",
|
|
112
|
-
routes: raw.routes ?? [],
|
|
113
|
-
expiresAt: raw.expires_at ?? raw.expiresAt ?? ""
|
|
114
|
-
};
|
|
1
|
+
import { operationMetadata } from './contract.generated.js';
|
|
2
|
+
export class ConfigurationError extends Error {
|
|
3
|
+
name = 'ConfigurationError';
|
|
115
4
|
}
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const chainId = payload.chainId ?? raw.chain_id ?? raw.chainId;
|
|
119
|
-
const nonce = payload.nonce ?? raw.nonce;
|
|
120
|
-
return {
|
|
121
|
-
chainId,
|
|
122
|
-
to: payload.to ?? raw.to,
|
|
123
|
-
data: payload.data ?? raw.data,
|
|
124
|
-
value: String(payload.value ?? raw.value ?? "0"),
|
|
125
|
-
gas: String(payload.gas ?? raw.gas ?? "0"),
|
|
126
|
-
...nonce != null ? { nonce: Number(nonce) } : {},
|
|
127
|
-
...payload.gasPrice ? { gasPrice: String(payload.gasPrice) } : {},
|
|
128
|
-
...payload.maxFeePerGas ? { maxFeePerGas: String(payload.maxFeePerGas) } : {},
|
|
129
|
-
...payload.maxPriorityFeePerGas ? { maxPriorityFeePerGas: String(payload.maxPriorityFeePerGas) } : {}
|
|
130
|
-
};
|
|
5
|
+
export class MalformedResponseError extends Error {
|
|
6
|
+
name = 'MalformedResponseError';
|
|
131
7
|
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
txHash: raw.tx_hash ?? raw.txHash,
|
|
135
|
-
chainId: raw.chain_id ?? raw.chainId,
|
|
136
|
-
broadcastMethod: raw.broadcast_method ?? raw.broadcastMethod ?? "public"
|
|
137
|
-
};
|
|
8
|
+
export class RequestTimeoutError extends Error {
|
|
9
|
+
name = 'RequestTimeoutError';
|
|
138
10
|
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
txHash: raw.tx_hash ?? raw.txHash,
|
|
142
|
-
chainId: raw.chain_id ?? raw.chainId,
|
|
143
|
-
status: raw.status,
|
|
144
|
-
...raw.block_number != null || raw.blockNumber != null ? { blockNumber: raw.block_number ?? raw.blockNumber } : {},
|
|
145
|
-
...raw.gas_used != null || raw.gasUsed != null ? { gasUsed: String(raw.gas_used ?? raw.gasUsed) } : {}
|
|
146
|
-
};
|
|
11
|
+
export class RequestAbortedError extends Error {
|
|
12
|
+
name = 'RequestAbortedError';
|
|
147
13
|
}
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
chain_id: params.chainId,
|
|
165
|
-
mode: params.mode || "standard"
|
|
166
|
-
});
|
|
167
|
-
return normalizeQuote(result);
|
|
168
|
-
}
|
|
169
|
-
/**
|
|
170
|
-
* Convert a quote into unsigned swap calldata ready for signing.
|
|
171
|
-
* @param quoteId - ID from a previously obtained Quote.
|
|
172
|
-
* @param slippage - Maximum slippage percentage (default 0.5%).
|
|
173
|
-
* @returns Unsigned transaction calldata for the swap.
|
|
174
|
-
*/
|
|
175
|
-
async prepareSwap(params) {
|
|
176
|
-
const result = await this.transport.callTool("dex_prepare_swap", {
|
|
177
|
-
quote_id: params.quoteId,
|
|
178
|
-
wallet_address: params.walletAddress,
|
|
179
|
-
slippage: params.slippage ?? 0.5
|
|
180
|
-
});
|
|
181
|
-
return normalizeUnsignedTx(result);
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* Generate an unsigned ERC-20 approval transaction for the DEX router.
|
|
185
|
-
* @param params - Token address, chain ID, and optional specific amount.
|
|
186
|
-
* @returns Unsigned approval transaction calldata.
|
|
187
|
-
*/
|
|
188
|
-
async approveToken(params) {
|
|
189
|
-
const result = await this.transport.callTool("dex_approve_token", {
|
|
190
|
-
token_address: params.tokenAddress,
|
|
191
|
-
chain_id: params.chainId,
|
|
192
|
-
wallet_address: params.walletAddress,
|
|
193
|
-
...params.amount ? { amount: params.amount } : {}
|
|
194
|
-
});
|
|
195
|
-
return normalizeUnsignedTx(result);
|
|
196
|
-
}
|
|
197
|
-
/**
|
|
198
|
-
* Broadcast a signed transaction to the network.
|
|
199
|
-
* @param params - Chain ID, signed transaction hex, and MEV protection flag.
|
|
200
|
-
* @returns Broadcast result with transaction hash.
|
|
201
|
-
*/
|
|
202
|
-
async broadcast(params) {
|
|
203
|
-
const result = await this.transport.callTool("dex_broadcast", {
|
|
204
|
-
chain_id: params.chainId,
|
|
205
|
-
signed_tx: params.signedTx,
|
|
206
|
-
mev_protection: params.mevProtection || false
|
|
207
|
-
});
|
|
208
|
-
return normalizeBroadcastResult(result);
|
|
209
|
-
}
|
|
210
|
-
/**
|
|
211
|
-
* Check the on-chain status of a transaction.
|
|
212
|
-
* @param params - Transaction hash and chain ID.
|
|
213
|
-
* @returns Current transaction status (pending, confirmed, or failed).
|
|
214
|
-
*/
|
|
215
|
-
async txStatus(params) {
|
|
216
|
-
const result = await this.transport.callTool("dex_tx_status", {
|
|
217
|
-
tx_hash: params.txHash,
|
|
218
|
-
chain_id: params.chainId
|
|
219
|
-
});
|
|
220
|
-
return normalizeTransactionStatus(result);
|
|
221
|
-
}
|
|
222
|
-
/**
|
|
223
|
-
* List all venues supported by the DEX aggregator.
|
|
224
|
-
* @returns Supported venue metadata.
|
|
225
|
-
*/
|
|
226
|
-
async supportedVenues() {
|
|
227
|
-
return this.transport.callTool("dex_supported_venues", {});
|
|
228
|
-
}
|
|
229
|
-
/**
|
|
230
|
-
* List supported trading pairs, optionally filtered by chain or venue.
|
|
231
|
-
* @param chainId - Optional chain ID filter.
|
|
232
|
-
* @param venue - Optional venue name filter (e.g. '1inch').
|
|
233
|
-
* @returns Supported trading pair metadata.
|
|
234
|
-
*/
|
|
235
|
-
async supportedPairs(venueId) {
|
|
236
|
-
return this.transport.callTool("dex_supported_pairs", {
|
|
237
|
-
venue_id: venueId
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
};
|
|
241
|
-
|
|
242
|
-
// src/dex/swap.ts
|
|
243
|
-
var NATIVE_TOKEN = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
|
|
244
|
-
var POLL_INTERVAL_MS = 2e3;
|
|
245
|
-
var MAX_POLLS = 60;
|
|
246
|
-
var SwapOrchestrator = class {
|
|
247
|
-
constructor(dex, signer, transport) {
|
|
248
|
-
this.dex = dex;
|
|
249
|
-
this.signer = signer;
|
|
250
|
-
this.transport = transport;
|
|
251
|
-
}
|
|
252
|
-
/**
|
|
253
|
-
* Execute a full swap from quote through on-chain confirmation.
|
|
254
|
-
*
|
|
255
|
-
* Flow: get quote -> check ERC-20 allowance (skip for native tokens) ->
|
|
256
|
-
* approve if needed -> prepare unsigned swap tx -> sign locally ->
|
|
257
|
-
* broadcast -> poll until confirmed or failed.
|
|
258
|
-
*
|
|
259
|
-
* @param params - Swap parameters (src, dst, amount, chainId, slippage, mevProtection, mode).
|
|
260
|
-
* @returns Final swap result including tx hash, status, and amounts.
|
|
261
|
-
* @throws If the transaction does not confirm within the polling timeout.
|
|
262
|
-
*/
|
|
263
|
-
async swap(params) {
|
|
264
|
-
const slippage = params.slippage ?? 0.5;
|
|
265
|
-
const mevProtection = params.mevProtection ?? false;
|
|
266
|
-
const mode = params.mode ?? "standard";
|
|
267
|
-
const quote = await this.dex.getQuote({
|
|
268
|
-
src: params.src,
|
|
269
|
-
dst: params.dst,
|
|
270
|
-
amount: params.amount,
|
|
271
|
-
chainId: params.chainId,
|
|
272
|
-
mode
|
|
273
|
-
});
|
|
274
|
-
if (quote.expiresAt) {
|
|
275
|
-
const expiry = new Date(quote.expiresAt);
|
|
276
|
-
if (!isNaN(expiry.getTime()) && expiry < /* @__PURE__ */ new Date()) {
|
|
277
|
-
throw new Error(`Quote ${quote.quoteId} expired at ${quote.expiresAt}. Re-fetch a fresh quote.`);
|
|
278
|
-
}
|
|
14
|
+
export class NetworkError extends Error {
|
|
15
|
+
name = 'NetworkError';
|
|
16
|
+
}
|
|
17
|
+
export class APIError extends Error {
|
|
18
|
+
status;
|
|
19
|
+
code;
|
|
20
|
+
correlationId;
|
|
21
|
+
retryAfter;
|
|
22
|
+
name = 'APIError';
|
|
23
|
+
constructor(status, code, message, correlationId, retryAfter, response, headers = {}) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.status = status;
|
|
26
|
+
this.code = code;
|
|
27
|
+
this.correlationId = correlationId;
|
|
28
|
+
this.retryAfter = retryAfter;
|
|
29
|
+
Object.defineProperties(this, { response: { value: response }, headers: { value: headers } });
|
|
279
30
|
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
if (needsApproval) {
|
|
284
|
-
await this.approveAndWait(params.src, params.chainId);
|
|
285
|
-
}
|
|
31
|
+
toJSON() {
|
|
32
|
+
return { name: this.name, status: this.status, code: this.code, message: this.message,
|
|
33
|
+
correlationId: this.correlationId, retryAfter: this.retryAfter };
|
|
286
34
|
}
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
txHash: broadcastResult.txHash,
|
|
298
|
-
chainId: params.chainId,
|
|
299
|
-
status: status.status,
|
|
300
|
-
gasUsed: status.gasUsed || "0",
|
|
301
|
-
inputToken: quote.inputToken,
|
|
302
|
-
outputToken: quote.outputToken,
|
|
303
|
-
inputAmount: quote.inputAmount,
|
|
304
|
-
outputAmount: quote.outputAmount
|
|
305
|
-
};
|
|
306
|
-
}
|
|
307
|
-
async checkNeedsApproval(tokenAddress, chainId) {
|
|
308
|
-
const walletAddress = await this.signer.getAddress();
|
|
309
|
-
const result = await this.transport.callTool("oneinch_allowances", {
|
|
310
|
-
chain_id: chainId,
|
|
311
|
-
wallet_address: walletAddress,
|
|
312
|
-
spender: "router"
|
|
35
|
+
}
|
|
36
|
+
function pause(ms, signal) {
|
|
37
|
+
return new Promise((resolve, reject) => {
|
|
38
|
+
if (signal?.aborted) {
|
|
39
|
+
reject(new RequestAbortedError('Request was cancelled'));
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const onAbort = () => { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); reject(new RequestAbortedError('Request was cancelled')); };
|
|
43
|
+
const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, ms);
|
|
44
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
313
45
|
});
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
46
|
+
}
|
|
47
|
+
function object(value) {
|
|
48
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
49
|
+
}
|
|
50
|
+
function positive(value, name) {
|
|
51
|
+
if (!Number.isSafeInteger(value) || value <= 0)
|
|
52
|
+
throw new ConfigurationError(`${name} must be a positive integer`);
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
function environmentVariables() {
|
|
56
|
+
return globalThis.process?.env ?? {};
|
|
57
|
+
}
|
|
58
|
+
function credentialField(name) {
|
|
59
|
+
return /authorization|cookie|password|(?:api|private)[_-]?key|(?:access|refresh|firebase|csrf|session|oauth|bearer)[_-]?token|secret|seed[_-]?phrase|wallet[_-]?seed|signature/i.test(name);
|
|
60
|
+
}
|
|
61
|
+
function safeString(value, secrets, fallback, maxLength = 512) {
|
|
62
|
+
if (typeof value !== 'string')
|
|
63
|
+
return fallback;
|
|
64
|
+
let result = value;
|
|
65
|
+
for (const secret of typeof secrets === 'string' ? [secrets] : secrets ?? []) {
|
|
66
|
+
if (secret)
|
|
67
|
+
result = result.split(secret).join('[redacted]');
|
|
319
68
|
}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
69
|
+
return result.replace(/Bearer\s+\S+/gi, 'Bearer [redacted]')
|
|
70
|
+
.replace(/((?:api[_-]?key|authorization|refresh[_-]?token|cookie)\s*[:=]\s*)[^\s,;]+/gi, '$1[redacted]')
|
|
71
|
+
.replace(/[\u0000-\u001f\u007f]/g, ' ').slice(0, maxLength);
|
|
72
|
+
}
|
|
73
|
+
function errorEnvelope(value, secrets) {
|
|
74
|
+
// Preserve machine-readable decisions without making credentials part of errors.
|
|
75
|
+
if (typeof value === 'string')
|
|
76
|
+
return safeString(value, secrets, '', Infinity);
|
|
77
|
+
if (Array.isArray(value))
|
|
78
|
+
return value.map(item => errorEnvelope(item, secrets));
|
|
79
|
+
if (object(value))
|
|
80
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [
|
|
81
|
+
safeString(key, secrets, '', Infinity),
|
|
82
|
+
credentialField(key) ? '[redacted]' : errorEnvelope(item, secrets),
|
|
83
|
+
]));
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
function requestSecrets(apiKey, headers, body) {
|
|
87
|
+
const secrets = apiKey ? [apiKey] : [];
|
|
88
|
+
for (const [key, value] of headers) {
|
|
89
|
+
if (credentialField(key)) {
|
|
90
|
+
secrets.push(value);
|
|
91
|
+
if (key === 'cookie')
|
|
92
|
+
for (const cookie of value.split(';')) {
|
|
93
|
+
const separator = cookie.indexOf('=');
|
|
94
|
+
if (separator !== -1)
|
|
95
|
+
secrets.push(cookie.slice(separator + 1).trim());
|
|
96
|
+
}
|
|
97
|
+
}
|
|
324
98
|
}
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
throw new Error(`Approval transaction failed on-chain: ${approvalBroadcast.txHash}`);
|
|
99
|
+
const pending = body === undefined ? [] : [JSON.parse(body)];
|
|
100
|
+
while (pending.length) {
|
|
101
|
+
const current = pending.pop();
|
|
102
|
+
if (current === null || typeof current !== 'object')
|
|
103
|
+
continue;
|
|
104
|
+
for (const [key, value] of Object.entries(current)) {
|
|
105
|
+
if (typeof value === 'string' && credentialField(key))
|
|
106
|
+
secrets.push(value);
|
|
107
|
+
else if (value !== null && typeof value === 'object')
|
|
108
|
+
pending.push(value);
|
|
109
|
+
}
|
|
337
110
|
}
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
111
|
+
return secrets.filter(Boolean).sort((a, b) => b.length - a.length);
|
|
112
|
+
}
|
|
113
|
+
function page(value, itemKey, offset, requestedLimit) {
|
|
114
|
+
if (!object(value) || !Array.isArray(value[itemKey]))
|
|
115
|
+
throw new MalformedResponseError('Expected a paginated result');
|
|
116
|
+
const items = value[itemKey];
|
|
117
|
+
const number = (name, fallback) => {
|
|
118
|
+
const result = value[name] ?? fallback;
|
|
119
|
+
if (typeof result !== 'number' || !Number.isSafeInteger(result) || result < 0) {
|
|
120
|
+
throw new MalformedResponseError(`Invalid page ${name}`);
|
|
121
|
+
}
|
|
122
|
+
return result;
|
|
123
|
+
};
|
|
124
|
+
const actualOffset = number('offset', offset);
|
|
125
|
+
const limit = number('limit', requestedLimit);
|
|
126
|
+
const total = number('total', actualOffset + items.length);
|
|
127
|
+
if (actualOffset !== offset || total < actualOffset + items.length)
|
|
128
|
+
throw new MalformedResponseError('Page bounds contradict the requested offset or total');
|
|
129
|
+
const explicitMore = value['has_more'];
|
|
130
|
+
if (explicitMore !== undefined && typeof explicitMore !== 'boolean')
|
|
131
|
+
throw new MalformedResponseError('Invalid has_more');
|
|
132
|
+
const hasMore = explicitMore ?? actualOffset + items.length < total;
|
|
133
|
+
if (!hasMore && actualOffset + items.length < total)
|
|
134
|
+
throw new MalformedResponseError('Page ended before its reported total');
|
|
135
|
+
const next = Object.hasOwn(value, 'next_offset') ? value['next_offset'] : (hasMore ? actualOffset + items.length : null);
|
|
136
|
+
if (hasMore && (typeof next !== 'number' || !Number.isSafeInteger(next) || next <= actualOffset || items.length === 0)) {
|
|
137
|
+
throw new MalformedResponseError('Page continuation did not advance');
|
|
346
138
|
}
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
139
|
+
return { items, total, offset: actualOffset, limit, hasMore, nextOffset: hasMore ? next : null };
|
|
140
|
+
}
|
|
141
|
+
export class MangroveAI {
|
|
142
|
+
baseUrl;
|
|
143
|
+
timeoutMs;
|
|
144
|
+
#apiKey;
|
|
145
|
+
fetcher;
|
|
146
|
+
maxResponseBytes;
|
|
147
|
+
constructor(options = {}) {
|
|
148
|
+
if (typeof window !== 'undefined')
|
|
149
|
+
throw new ConfigurationError('Use the API-key client in server-side code');
|
|
150
|
+
const env = environmentVariables();
|
|
151
|
+
this.#apiKey = options.apiKey ?? env['MANGROVE_API_KEY'];
|
|
152
|
+
if (this.#apiKey !== undefined && (typeof this.#apiKey !== 'string' || !this.#apiKey || /[^\x21-\x7e]/.test(this.#apiKey))) {
|
|
153
|
+
throw new ConfigurationError('apiKey must be a nonempty ASCII token without whitespace');
|
|
154
|
+
}
|
|
155
|
+
const environment = options.environment ?? env['MANGROVE_ENVIRONMENT'] ?? (this.#apiKey?.startsWith('dev_') ? 'dev' : this.#apiKey?.startsWith('local_') ? 'local' : 'prod');
|
|
156
|
+
if (!['prod', 'dev', 'local'].includes(environment))
|
|
157
|
+
throw new ConfigurationError('environment must be prod, dev or local');
|
|
158
|
+
const configured = options.baseUrl ?? env['MANGROVE_BASE_URL'];
|
|
159
|
+
if ((environment === 'dev' || this.#apiKey?.startsWith('dev_')) && !configured)
|
|
160
|
+
throw new ConfigurationError('Development requires an explicit baseUrl or MANGROVE_BASE_URL');
|
|
161
|
+
if (environment === 'prod' && this.#apiKey?.startsWith('test_') && !configured)
|
|
162
|
+
throw new ConfigurationError('test_ keys require an explicit baseUrl or local environment; no production fallback');
|
|
163
|
+
const raw = configured ?? (environment === 'local' ? 'http://localhost:5001' : 'https://api.mangrovedeveloper.ai');
|
|
164
|
+
let origin;
|
|
165
|
+
try {
|
|
166
|
+
origin = new URL(raw);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
throw new ConfigurationError('baseUrl must be an absolute HTTP(S) API origin');
|
|
170
|
+
}
|
|
171
|
+
if (origin.username || origin.password || origin.search || origin.hash)
|
|
172
|
+
throw new ConfigurationError('baseUrl cannot contain credentials, query or fragment');
|
|
173
|
+
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(origin.hostname);
|
|
174
|
+
if (origin.protocol !== 'https:' && !(origin.protocol === 'http:' && loopback))
|
|
175
|
+
throw new ConfigurationError('baseUrl requires HTTPS except for loopback testing');
|
|
176
|
+
if (!['', '/', '/api/v1', '/api/v1/', '/api/v2', '/api/v2/'].includes(origin.pathname)) {
|
|
177
|
+
throw new ConfigurationError('baseUrl must be an API origin or a v1/v2 base URL');
|
|
178
|
+
}
|
|
179
|
+
this.baseUrl = origin.origin;
|
|
180
|
+
this.timeoutMs = positive(options.timeoutMs ?? 30_000, 'timeoutMs');
|
|
181
|
+
this.maxResponseBytes = positive(options.maxResponseBytes ?? 8 * 1024 * 1024, 'maxResponseBytes');
|
|
182
|
+
this.fetcher = options.fetch ?? globalThis.fetch;
|
|
183
|
+
if (!this.fetcher)
|
|
184
|
+
throw new ConfigurationError('This runtime needs fetch support');
|
|
363
185
|
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
186
|
+
async request(operation, options) {
|
|
187
|
+
if (typeof operation !== 'string' || !Object.hasOwn(operationMetadata, operation))
|
|
188
|
+
throw new ConfigurationError('Operation is absent from the reviewed contract');
|
|
189
|
+
if (!object(options))
|
|
190
|
+
throw new ConfigurationError('Request options must be an object');
|
|
191
|
+
const metadata = operationMetadata[operation];
|
|
192
|
+
if (!metadata)
|
|
193
|
+
throw new ConfigurationError('Operation is absent from the reviewed contract');
|
|
194
|
+
const input = options;
|
|
195
|
+
if (metadata.authenticated && !this.#apiKey)
|
|
196
|
+
throw new ConfigurationError('This operation requires an API credential');
|
|
197
|
+
if (input.signal?.aborted)
|
|
198
|
+
throw new RequestAbortedError('Request was cancelled');
|
|
199
|
+
if (metadata.bodyRequired && input.body === undefined)
|
|
200
|
+
throw new ConfigurationError('This operation requires a request body');
|
|
201
|
+
const headers = new Headers({ Accept: 'application/json' });
|
|
202
|
+
for (const [key, value] of Object.entries(input.headers ?? {})) {
|
|
203
|
+
if (['authorization', 'host', 'content-length'].includes(key.toLowerCase()))
|
|
204
|
+
throw new ConfigurationError('A protected header cannot be overridden');
|
|
205
|
+
try {
|
|
206
|
+
headers.set(key, value);
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
throw new ConfigurationError('A request header is invalid');
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if (this.#apiKey)
|
|
213
|
+
headers.set('Authorization', `Bearer ${this.#apiKey}`);
|
|
214
|
+
for (const [group, keys] of Object.entries(metadata.required)) {
|
|
215
|
+
for (const key of keys) {
|
|
216
|
+
const value = group === 'headers' ? headers.get(key) : input[group]?.[key];
|
|
217
|
+
if (value === undefined || value === null || value === '')
|
|
218
|
+
throw new ConfigurationError(`Missing required ${group} parameter: ${key}`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const path = metadata.path.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
222
|
+
const value = input.path?.[name];
|
|
223
|
+
if ((typeof value !== 'string' && typeof value !== 'number') || value === '.' || value === '..')
|
|
224
|
+
throw new ConfigurationError('Invalid path parameter');
|
|
225
|
+
return encodeURIComponent(String(value));
|
|
226
|
+
});
|
|
227
|
+
const url = new URL(this.baseUrl + path);
|
|
228
|
+
for (const [key, value] of Object.entries(input.query ?? {})) {
|
|
229
|
+
if (value === undefined)
|
|
230
|
+
continue;
|
|
231
|
+
if (Array.isArray(value)) {
|
|
232
|
+
const format = metadata.queryFormats[key];
|
|
233
|
+
if (!format || value.some(item => !['string', 'number', 'boolean'].includes(typeof item)
|
|
234
|
+
|| typeof item === 'number' && !Number.isFinite(item)))
|
|
235
|
+
throw new ConfigurationError('A query parameter has an invalid array value');
|
|
236
|
+
if (format === 'multi')
|
|
237
|
+
for (const item of value)
|
|
238
|
+
url.searchParams.append(key, String(item));
|
|
239
|
+
else {
|
|
240
|
+
const separator = { csv: ',', ssv: ' ', tsv: '\t', pipes: '|' }[format];
|
|
241
|
+
if (separator === undefined)
|
|
242
|
+
throw new ConfigurationError('Unsupported query array encoding');
|
|
243
|
+
url.searchParams.set(key, value.join(separator));
|
|
244
|
+
}
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
if (value === null || (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') || (typeof value === 'number' && !Number.isFinite(value))) {
|
|
248
|
+
throw new ConfigurationError('Query parameters must be scalar values');
|
|
249
|
+
}
|
|
250
|
+
url.searchParams.set(key, String(value));
|
|
251
|
+
}
|
|
252
|
+
let body;
|
|
253
|
+
if (input.body !== undefined) {
|
|
254
|
+
try {
|
|
255
|
+
body = JSON.stringify(input.body, (_, value) => {
|
|
256
|
+
if (typeof value === 'number' && !Number.isFinite(value) || ['bigint', 'function', 'symbol'].includes(typeof value))
|
|
257
|
+
throw new Error();
|
|
258
|
+
return value;
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
throw new ConfigurationError('Request body must be JSON serializable');
|
|
263
|
+
}
|
|
264
|
+
if (body === undefined)
|
|
265
|
+
throw new ConfigurationError('Request body must be JSON serializable');
|
|
266
|
+
headers.set('Content-Type', 'application/json');
|
|
267
|
+
}
|
|
268
|
+
const secrets = requestSecrets(this.#apiKey, headers, body);
|
|
269
|
+
const controller = new AbortController();
|
|
270
|
+
const timeout = positive(input.timeoutMs ?? this.timeoutMs, 'timeoutMs');
|
|
271
|
+
let timer;
|
|
272
|
+
let onAbort;
|
|
273
|
+
const interrupted = new Promise((_, reject) => {
|
|
274
|
+
timer = setTimeout(() => { controller.abort(); reject(new RequestTimeoutError('Request deadline exceeded')); }, timeout);
|
|
275
|
+
onAbort = () => { controller.abort(); reject(new RequestAbortedError('Request was cancelled')); };
|
|
276
|
+
input.signal?.addEventListener('abort', onAbort, { once: true });
|
|
277
|
+
});
|
|
278
|
+
const perform = async () => {
|
|
279
|
+
let response;
|
|
280
|
+
try {
|
|
281
|
+
response = await this.fetcher(url, { method: metadata.method, headers,
|
|
282
|
+
...(body !== undefined ? { body } : {}), signal: controller.signal, redirect: 'error' });
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
if (input.signal?.aborted)
|
|
286
|
+
throw new RequestAbortedError('Request was cancelled');
|
|
287
|
+
if (controller.signal.aborted)
|
|
288
|
+
throw new RequestTimeoutError('Request deadline exceeded');
|
|
289
|
+
throw new NetworkError('The API request failed; no automatic retry was sent');
|
|
290
|
+
}
|
|
291
|
+
if (response.status >= 300 && response.status < 400)
|
|
292
|
+
throw new MalformedResponseError('API redirects are refused');
|
|
293
|
+
const contentType = response.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase();
|
|
294
|
+
if (response.ok && response.status !== 204 && response.status !== 205
|
|
295
|
+
&& contentType !== 'application/json' && !contentType?.endsWith('+json')) {
|
|
296
|
+
await response.body?.cancel();
|
|
297
|
+
throw new MalformedResponseError('Expected application/json from the API');
|
|
298
|
+
}
|
|
299
|
+
const declaredLength = response.headers.get('content-length');
|
|
300
|
+
if (declaredLength !== null && Number(declaredLength) > this.maxResponseBytes) {
|
|
301
|
+
await response.body?.cancel();
|
|
302
|
+
throw new MalformedResponseError('API response exceeds the configured size limit');
|
|
303
|
+
}
|
|
304
|
+
const reader = response.body?.getReader();
|
|
305
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
306
|
+
let text = '';
|
|
307
|
+
let bytes = 0;
|
|
308
|
+
try {
|
|
309
|
+
if (reader) {
|
|
310
|
+
for (;;) {
|
|
311
|
+
const chunk = await reader.read();
|
|
312
|
+
if (chunk.done)
|
|
313
|
+
break;
|
|
314
|
+
bytes += chunk.value.byteLength;
|
|
315
|
+
if (bytes > this.maxResponseBytes)
|
|
316
|
+
throw new MalformedResponseError('API response exceeds the configured size limit');
|
|
317
|
+
text += decoder.decode(chunk.value, { stream: true });
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
text += decoder.decode();
|
|
321
|
+
}
|
|
322
|
+
catch (error) {
|
|
323
|
+
await reader?.cancel().catch(() => undefined);
|
|
324
|
+
if (error instanceof MalformedResponseError)
|
|
325
|
+
throw error;
|
|
326
|
+
throw new MalformedResponseError('API response body could not be read');
|
|
327
|
+
}
|
|
328
|
+
finally {
|
|
329
|
+
reader?.releaseLock();
|
|
330
|
+
}
|
|
331
|
+
let data;
|
|
332
|
+
if (response.ok && response.status !== 204 && response.status !== 205 && text.length === 0) {
|
|
333
|
+
throw new MalformedResponseError('Expected a nonempty JSON API response');
|
|
334
|
+
}
|
|
335
|
+
try {
|
|
336
|
+
data = text ? JSON.parse(text) : undefined;
|
|
337
|
+
}
|
|
338
|
+
catch {
|
|
339
|
+
if (response.ok)
|
|
340
|
+
throw new MalformedResponseError('Expected a JSON API response');
|
|
341
|
+
}
|
|
342
|
+
if (!response.ok) {
|
|
343
|
+
const envelope = object(data) ? data : {};
|
|
344
|
+
const nested = object(envelope['error']) ? envelope['error'] : envelope;
|
|
345
|
+
const code = safeString(nested['code'] ?? envelope['code'], secrets, 'HTTP_ERROR');
|
|
346
|
+
const message = safeString(nested['message'] ?? envelope['message'] ?? envelope['error'], secrets, `API request failed (${response.status})`);
|
|
347
|
+
const correlation = safeString(envelope['correlation_id'] ?? response.headers.get('x-correlation-id'), secrets, '');
|
|
348
|
+
const retry = safeString(response.headers.get('retry-after'), secrets, '');
|
|
349
|
+
const retainedHeaders = {};
|
|
350
|
+
for (const name of ['payment-required', 'payment-response', 'www-authenticate', 'retry-after', 'x-correlation-id']) {
|
|
351
|
+
const value = response.headers.get(name);
|
|
352
|
+
if (value !== null) {
|
|
353
|
+
if (value.length > this.maxResponseBytes)
|
|
354
|
+
throw new MalformedResponseError('API error header exceeds the configured size limit');
|
|
355
|
+
retainedHeaders[name] = safeString(value, secrets, '', value.length);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
throw new APIError(response.status, code, message, correlation || undefined, retry || undefined, errorEnvelope(data, secrets), retainedHeaders);
|
|
359
|
+
}
|
|
360
|
+
if (response.status === 204 || response.status === 205)
|
|
361
|
+
return undefined;
|
|
362
|
+
return data;
|
|
363
|
+
};
|
|
364
|
+
try {
|
|
365
|
+
return await Promise.race([perform(), interrupted]);
|
|
366
|
+
}
|
|
367
|
+
finally {
|
|
368
|
+
if (timer)
|
|
369
|
+
clearTimeout(timer);
|
|
370
|
+
if (onAbort)
|
|
371
|
+
input.signal?.removeEventListener('abort', onAbort);
|
|
372
|
+
controller.abort();
|
|
373
|
+
}
|
|
367
374
|
}
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
375
|
+
users = {
|
|
376
|
+
getMyMetrics: async (controls = {}) => {
|
|
377
|
+
const value = await this.request('GET /api/v1/users/me/metrics', controls);
|
|
378
|
+
if (!object(value) || value['success'] !== true || !object(value['metrics']))
|
|
379
|
+
throw new MalformedResponseError('Expected a successful usage metrics response');
|
|
380
|
+
const metrics = value['metrics'];
|
|
381
|
+
for (const key of ['conversations_count', 'messages_count', 'estimated_tokens', 'strategies_count', 'backtests_count']) {
|
|
382
|
+
const count = metrics[key];
|
|
383
|
+
if (count !== undefined && count !== null && (typeof count !== 'number' || !Number.isSafeInteger(count) || count < 0)) {
|
|
384
|
+
throw new MalformedResponseError('Usage metrics contain an invalid count');
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
for (const key of ['token_breakdown', 'tool_calls']) {
|
|
388
|
+
if (metrics[key] !== undefined && metrics[key] !== null && !object(metrics[key])) {
|
|
389
|
+
throw new MalformedResponseError('Usage metrics contain an invalid object');
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
return metrics;
|
|
393
|
+
},
|
|
394
|
+
};
|
|
395
|
+
signals = {
|
|
396
|
+
list: async (options = {}) => {
|
|
397
|
+
const { signal, timeoutMs, ...query } = options;
|
|
398
|
+
const result = await this.request('GET /api/v1/signals/', { query,
|
|
399
|
+
...(signal ? { signal } : {}), ...(timeoutMs !== undefined ? { timeoutMs } : {}) });
|
|
400
|
+
const parsed = page(result, 'signals', query.offset ?? 0, query.limit ?? 50);
|
|
401
|
+
if (parsed.items.some(value => !object(value) || typeof value['name'] !== 'string' || typeof value['category'] !== 'string')) {
|
|
402
|
+
throw new MalformedResponseError('Signal page contains invalid entries');
|
|
403
|
+
}
|
|
404
|
+
return parsed;
|
|
405
|
+
},
|
|
406
|
+
listIter: (options = {}) => {
|
|
407
|
+
const self = this;
|
|
408
|
+
return { async *[Symbol.asyncIterator]() {
|
|
409
|
+
let offset = 0;
|
|
410
|
+
const seenNames = new Set();
|
|
411
|
+
for (;;) {
|
|
412
|
+
const result = await self.signals.list({ ...options, offset });
|
|
413
|
+
const names = new Set(result.items.map(item => item.name));
|
|
414
|
+
if (names.size !== result.items.length || result.items.some(item => seenNames.has(item.name))) {
|
|
415
|
+
throw new MalformedResponseError('Signal pagination repeated a signal identity');
|
|
416
|
+
}
|
|
417
|
+
for (const name of names)
|
|
418
|
+
seenNames.add(name);
|
|
419
|
+
for (const item of result.items)
|
|
420
|
+
yield item;
|
|
421
|
+
if (!result.hasMore || result.nextOffset === null)
|
|
422
|
+
return;
|
|
423
|
+
if (result.nextOffset <= offset)
|
|
424
|
+
throw new MalformedResponseError('Signal pagination did not advance');
|
|
425
|
+
offset = result.nextOffset;
|
|
426
|
+
}
|
|
427
|
+
} };
|
|
428
|
+
},
|
|
429
|
+
};
|
|
430
|
+
strategyWorkflow = Object.fromEntries(Object.keys(operationMetadata).filter(key => key.startsWith('POST /api/v1/strategy-workflow/')).map(key => {
|
|
431
|
+
const name = key.split('/').at(-1).replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
|
|
432
|
+
return [name, (options) => this.request(key, options)];
|
|
433
|
+
}));
|
|
434
|
+
backtesting = {
|
|
435
|
+
submit: async (body, controls = {}) => {
|
|
436
|
+
const result = await this.request('POST /api/v2/backtests/', { body, ...controls });
|
|
437
|
+
return this.backtestStatus(result);
|
|
438
|
+
},
|
|
439
|
+
getStatus: async (backtestId, controls = {}) => {
|
|
440
|
+
const result = await this.request('GET /api/v2/backtests/{backtest_id}/status', { path: { backtest_id: backtestId }, ...controls });
|
|
441
|
+
const status = this.backtestStatus(result);
|
|
442
|
+
if (status.backtest_id !== backtestId)
|
|
443
|
+
throw new MalformedResponseError('Backtest status identity does not match');
|
|
444
|
+
return status;
|
|
445
|
+
},
|
|
446
|
+
wait: async (backtestId, options = {}) => {
|
|
447
|
+
const deadline = performance.now() + positive(options.timeoutMs ?? this.timeoutMs, 'timeoutMs');
|
|
448
|
+
const interval = positive(options.pollIntervalMs ?? 1_000, 'pollIntervalMs');
|
|
449
|
+
for (;;) {
|
|
450
|
+
const remaining = Math.floor(deadline - performance.now());
|
|
451
|
+
if (remaining <= 0)
|
|
452
|
+
throw new RequestTimeoutError('Backtest polling deadline exceeded');
|
|
453
|
+
const result = await this.backtesting.getStatus(backtestId, {
|
|
454
|
+
timeoutMs: remaining, ...(options.signal ? { signal: options.signal } : {}),
|
|
455
|
+
});
|
|
456
|
+
if (result.status === 'completed' || result.status === 'failed' || result.status === 'cancelled')
|
|
457
|
+
return result;
|
|
458
|
+
const delay = Math.min(interval, Math.floor(deadline - performance.now()));
|
|
459
|
+
if (delay <= 0)
|
|
460
|
+
throw new RequestTimeoutError('Backtest polling deadline exceeded');
|
|
461
|
+
await pause(delay, options.signal);
|
|
462
|
+
}
|
|
463
|
+
},
|
|
464
|
+
};
|
|
465
|
+
backtestStatus(value) {
|
|
466
|
+
if (!object(value) || typeof value['backtest_id'] !== 'string' || !value['backtest_id']
|
|
467
|
+
|| typeof value['status'] !== 'string' || !['pending', 'running', 'completed', 'failed', 'cancelled'].includes(value['status'])) {
|
|
468
|
+
throw new MalformedResponseError('Expected a backtest identity and recognized status');
|
|
384
469
|
}
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
}
|
|
390
|
-
/** Open the transport connection. Must be called before making any tool calls. */
|
|
391
|
-
async connect() {
|
|
392
|
-
await this.transport.connect();
|
|
393
|
-
}
|
|
394
|
-
/** Close the transport connection and release resources. */
|
|
395
|
-
async disconnect() {
|
|
396
|
-
await this.transport.disconnect();
|
|
397
|
-
}
|
|
398
|
-
};
|
|
399
|
-
|
|
400
|
-
// src/signer/ethers.ts
|
|
401
|
-
var EthersSigner = class {
|
|
402
|
-
/**
|
|
403
|
-
* Create an EthersSigner from an ethers.js Wallet and list of supported chain IDs.
|
|
404
|
-
* @param wallet - An ethers.js Wallet instance (or any object matching EthersWallet).
|
|
405
|
-
* @param supportedChainIds - Chain IDs this wallet can sign transactions for.
|
|
406
|
-
*/
|
|
407
|
-
constructor(wallet, supportedChainIds) {
|
|
408
|
-
this.wallet = wallet;
|
|
409
|
-
this.chainIds = supportedChainIds;
|
|
410
|
-
}
|
|
411
|
-
/** {@inheritDoc Signer.getAddress} */
|
|
412
|
-
async getAddress() {
|
|
413
|
-
return this.wallet.address;
|
|
414
|
-
}
|
|
415
|
-
/** {@inheritDoc Signer.signTransaction} */
|
|
416
|
-
async signTransaction(tx) {
|
|
417
|
-
return this.wallet.signTransaction({
|
|
418
|
-
chainId: tx.chainId,
|
|
419
|
-
to: tx.to,
|
|
420
|
-
data: tx.data,
|
|
421
|
-
value: tx.value,
|
|
422
|
-
gasLimit: tx.gas,
|
|
423
|
-
...tx.nonce != null ? { nonce: tx.nonce } : {},
|
|
424
|
-
...tx.gasPrice ? { gasPrice: tx.gasPrice } : {},
|
|
425
|
-
...tx.maxFeePerGas ? { maxFeePerGas: tx.maxFeePerGas } : {},
|
|
426
|
-
...tx.maxPriorityFeePerGas ? { maxPriorityFeePerGas: tx.maxPriorityFeePerGas } : {}
|
|
427
|
-
});
|
|
428
|
-
}
|
|
429
|
-
/** {@inheritDoc Signer.getSupportedChainIds} */
|
|
430
|
-
async getSupportedChainIds() {
|
|
431
|
-
return this.chainIds;
|
|
432
|
-
}
|
|
433
|
-
};
|
|
434
|
-
export {
|
|
435
|
-
DexService,
|
|
436
|
-
EthersSigner,
|
|
437
|
-
MangroveClient,
|
|
438
|
-
McpTransport,
|
|
439
|
-
RestTransport
|
|
440
|
-
};
|
|
470
|
+
return value;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
//# sourceMappingURL=index.js.map
|