keyring-agent-core 0.3.5 → 0.3.7

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.d.ts CHANGED
@@ -35,6 +35,20 @@ declare function clampTick(tick: number): number;
35
35
  * Shared types for swap/bridge service providers.
36
36
  */
37
37
  type ProviderName = 'debridge' | 'relay';
38
+ /**
39
+ * Why a swap is happening — this, not the chain alone, decides which config
40
+ * API picks the provider. See {@link file://./routing.ts}.
41
+ *
42
+ * 'pool' — internal native→token legs for add-liquidity (coinpool config).
43
+ * 'userSwap' — user-facing swap / buy (keyringV2 setting, like the app).
44
+ */
45
+ type SwapRoute = 'pool' | 'userSwap';
46
+ /** Input to provider resolution. `dstChainId` defaults to `srcChainId`. */
47
+ interface SwapRouteRequest {
48
+ route: SwapRoute;
49
+ srcChainId?: number | string | null;
50
+ dstChainId?: number | string | null;
51
+ }
38
52
  interface SwapQuoteParams {
39
53
  srcChainId: number | string;
40
54
  srcTokenAddress: string;
@@ -50,7 +64,12 @@ interface SwapQuoteParams {
50
64
  */
51
65
  slippage?: number | 'auto';
52
66
  isCrossChain?: boolean;
53
- isHasAffiliate?: boolean;
67
+ /**
68
+ * Which route this quote serves. Decides WHICH affiliate config the adapter
69
+ * reads — the two are not interchangeable, see
70
+ * {@link file://./KeyringSettingApi.ts}. Defaults to `'userSwap'`.
71
+ */
72
+ route?: SwapRoute;
54
73
  }
55
74
  interface SwapTxData {
56
75
  from?: string;
@@ -61,6 +80,17 @@ interface SwapTxData {
61
80
  };
62
81
  value?: string;
63
82
  chainId?: number | string;
83
+ /**
84
+ * Gas the provider estimated for THIS transaction, when it reports one.
85
+ *
86
+ * Carried because the fee that sizes a spend is `gasPrice × gasLimit`, and the
87
+ * app prefers the quote's own gas over a fixed default (its `gasLimitRawTx`) —
88
+ * a multi-hop route costs more than the 1M fallback, and reserving the
89
+ * fallback for it leaves a "Max" the swap cannot pay for. Dropping it here is
90
+ * why the agent could only ever price the default; the app's own adapter has
91
+ * always kept it (`RelayAdapter.js`).
92
+ */
93
+ gas?: string | number;
64
94
  maxFeePerGas?: string;
65
95
  maxPriorityFeePerGas?: string;
66
96
  }
@@ -85,25 +115,49 @@ interface CheckApprovalParams {
85
115
  tokenDecimals: number;
86
116
  quoteData: SwapQuoteResult;
87
117
  }
118
+ /**
119
+ * One unsigned ERC-20 approval transaction, ready to sign and broadcast as-is.
120
+ *
121
+ * A swap can need MORE THAN ONE of these, in order. The case that forces it is
122
+ * a token whose `approve` refuses to overwrite a non-zero allowance — USDT on
123
+ * Ethereum being the canonical one, which reverts on
124
+ * `require(!((_value != 0) && (allowed[owner][spender] != 0)))`. Raising such an
125
+ * allowance takes two transactions: `approve(spender, 0)`, then
126
+ * `approve(spender, amount)`. Relay already returns both as two separate
127
+ * `approve` steps in a single quote; the deBridge path builds the same pair
128
+ * itself. See `CheckApprovalResult.approvals`.
129
+ */
130
+ interface ApprovalTx {
131
+ to?: string;
132
+ from?: string;
133
+ data?: string;
134
+ value?: string;
135
+ chainId?: number | string;
136
+ gas?: string | number;
137
+ maxFeePerGas?: string;
138
+ maxPriorityFeePerGas?: string;
139
+ }
88
140
  interface CheckApprovalResult {
89
141
  isNeeded: boolean;
90
142
  integrated?: boolean;
91
143
  contractAddress?: string;
144
+ /**
145
+ * EVERY approval transaction this swap needs, in the order they must be sent.
146
+ * Usually one; two when a standing allowance has to be zeroed first (see
147
+ * `ApprovalTx`). Empty/absent when `isNeeded` is false.
148
+ *
149
+ * Callers MUST run all of them — taking only the first sends the zeroing
150
+ * approve and then a swap with no allowance, which reverts.
151
+ */
152
+ approvals?: ApprovalTx[];
153
+ /**
154
+ * @deprecated The FIRST entry of `approvals`, kept so existing callers keep
155
+ * compiling. It is NOT sufficient on its own — read `approvals` instead.
156
+ */
92
157
  approvalData?: unknown;
93
158
  message?: string;
94
159
  error?: string;
95
160
  }
96
- interface ExecuteSwapParams {
97
- quoteData: SwapQuoteResult;
98
- }
99
- interface ExecuteSwapResult {
100
- success: boolean;
101
- provider?: ProviderName;
102
- txData?: SwapTxData;
103
- steps?: unknown[];
104
- estimation?: Record<string, unknown>;
105
- error?: string;
106
- }
107
161
  interface TrackTransactionParams {
108
162
  requestIdOrTxHash: string;
109
163
  }
@@ -113,26 +167,37 @@ interface TrackTransactionResult {
113
167
  status: TrackStatus;
114
168
  error?: string;
115
169
  }
116
- interface SwapServiceConfig {
170
+ interface SwapProviderConfig {
117
171
  apiBaseUrl?: string;
118
172
  apiKey?: string;
119
173
  accessToken?: string;
120
174
  }
121
- type ExchangeProviderConfig = Record<ProviderName, SwapServiceConfig>;
175
+ type SwapProviderConfigMap = Record<ProviderName, SwapProviderConfig>;
122
176
 
123
177
  /**
124
178
  * Abstract base for swap/bridge providers. Each adapter must implement the five
125
179
  * methods below; the factory wires the active provider based on chain config.
126
180
  */
127
- declare abstract class BaseSwapService {
128
- protected readonly config: SwapServiceConfig;
129
- protected constructor(config: SwapServiceConfig);
181
+ declare abstract class BaseSwapProvider {
182
+ protected readonly config: SwapProviderConfig;
183
+ protected constructor(config: SwapProviderConfig);
130
184
  abstract getProviderName(): ProviderName;
185
+ /**
186
+ * A view of this adapter that serves `route` — every quote it produces
187
+ * defaults to that route, so callers need not repeat it on each `getQuote`.
188
+ *
189
+ * Returns a lightweight delegating wrapper rather than mutating `this`:
190
+ * adapters are cached and shared per provider by the factory, so the SAME
191
+ * instance serves both routes concurrently. Storing the route as state would
192
+ * let one route's quote read the other route's affiliate config.
193
+ *
194
+ * An explicit `route` on the quote params still wins.
195
+ */
196
+ withRoute(route: SwapRoute): BaseSwapProvider;
131
197
  /** True when approval is delivered as part of the quote (e.g. Relay). */
132
- hasIntegratedApproval(): boolean;
198
+ abstract hasIntegratedApproval(): boolean;
133
199
  abstract getQuote(params: SwapQuoteParams): Promise<SwapQuoteResult>;
134
200
  abstract checkApproval(params: CheckApprovalParams): Promise<CheckApprovalResult>;
135
- abstract executeSwap(params: ExecuteSwapParams): Promise<ExecuteSwapResult>;
136
201
  abstract trackTransaction(params: TrackTransactionParams): Promise<TrackTransactionResult>;
137
202
  }
138
203
 
@@ -141,10 +206,10 @@ declare abstract class BaseSwapService {
141
206
  * uses /dln/order/create-tx. Approval is NOT integrated — caller must check
142
207
  * on-chain allowance against `tx.to` separately.
143
208
  */
144
- declare class DebridgeAdapter extends BaseSwapService {
209
+ declare class DebridgeProvider extends BaseSwapProvider {
145
210
  private readonly apiBaseUrl;
146
211
  private readonly accessToken;
147
- constructor(config?: SwapServiceConfig);
212
+ constructor(config?: SwapProviderConfig);
148
213
  getProviderName(): ProviderName;
149
214
  hasIntegratedApproval(): boolean;
150
215
  getQuote(params: SwapQuoteParams): Promise<SwapQuoteResult>;
@@ -155,6 +220,11 @@ declare class DebridgeAdapter extends BaseSwapService {
155
220
  * on-chain `allowance(userAddress, spender)` and only flag `isNeeded` when the
156
221
  * current allowance is below `amount` (no redundant approve when already set).
157
222
  *
223
+ * `approvals` carries the transactions to send, in order. It is usually one
224
+ * `approve(spender, amount)`, but a token that refuses to overwrite a non-zero
225
+ * allowance (USDT on Ethereum) needs its allowance zeroed first, so it is two.
226
+ * See `buildApprovals` for how that is detected without a token list.
227
+ *
158
228
  * `amount` is the spend in the token's smallest units (wei-equivalent), the
159
229
  * same value passed as `srcTokenAmount` to the quote.
160
230
  */
@@ -166,79 +236,467 @@ declare class DebridgeAdapter extends BaseSwapService {
166
236
  * (`0xdd62ed3e`) + two 32-byte-padded addresses.
167
237
  */
168
238
  private readAllowance;
169
- executeSwap(params: ExecuteSwapParams): Promise<ExecuteSwapResult>;
170
239
  trackTransaction(params: TrackTransactionParams): Promise<TrackTransactionResult>;
171
240
  private get;
172
241
  }
173
242
 
174
243
  /**
175
- * Relay.link adapter. Relay bundles approval + swap into a single quote (one
176
- * "approve" step + one "swap"/"deposit" step), so `hasIntegratedApproval` is true.
244
+ * Relay.link adapter. Relay bundles approval + swap into a single quote, so
245
+ * `hasIntegratedApproval` is true.
246
+ *
247
+ * The approval part is a LIST, not a single step: `steps` carries one `approve`
248
+ * entry per approval transaction the swap needs, followed by the
249
+ * `swap`/`deposit` step. Most tokens produce one; a token that refuses to
250
+ * overwrite a non-zero allowance (USDT on Ethereum) produces two — an
251
+ * `approve(spender, 0)` and then the real `approve(spender, amount)` — and both
252
+ * must be sent, in order. Picking only the first sends the zeroing approve and
253
+ * then swaps against an allowance of 0, which reverts.
177
254
  */
178
- declare class RelayAdapter extends BaseSwapService {
255
+ declare class RelayProvider extends BaseSwapProvider {
179
256
  private readonly apiBaseUrl;
180
257
  private readonly apiKey?;
181
- constructor(config?: SwapServiceConfig);
258
+ constructor(config?: SwapProviderConfig);
182
259
  getProviderName(): ProviderName;
183
260
  hasIntegratedApproval(): boolean;
184
261
  getQuote(params: SwapQuoteParams): Promise<SwapQuoteResult>;
262
+ /**
263
+ * Relay decides the approvals itself and ships them in the quote, so this
264
+ * reads them back rather than probing the chain. Every `approve` step becomes
265
+ * one entry of `approvals`, in quote order — two of them when the pay token
266
+ * needs its allowance zeroed first.
267
+ */
185
268
  checkApproval(params: CheckApprovalParams): Promise<CheckApprovalResult>;
186
- executeSwap(params: ExecuteSwapParams): Promise<ExecuteSwapResult>;
187
269
  trackTransaction(params: TrackTransactionParams): Promise<TrackTransactionResult>;
188
270
  private request;
189
271
  }
190
272
 
191
273
  /**
192
- * Picks the right swap adapter based on the source chain.
274
+ * The coinpool platform config: deployed contract addresses, and the
275
+ * chain→provider map that routes add-liquidity swap legs.
276
+ *
277
+ * This is coinpool's OWN source of truth, separate from the keyringV2
278
+ * setting ({@link file://./KeyringV2SettingService.ts}) that user-facing swaps
279
+ * read. The two must not be merged — see {@link file://./SwapRouter.ts}.
280
+ *
281
+ * Both payloads are effectively static (contract deployments and their routing),
282
+ * so they are cached for the lifetime of the process.
283
+ */
284
+ declare class CoinpoolConfigApi {
285
+ private readonly addresses;
286
+ private readonly providerMap;
287
+ constructor(addressesUrl?: string, providerMapUrl?: string);
288
+ /**
289
+ * The provider coinpool assigns to `chainId`, or null when the API is
290
+ * unreachable or the chain has no mapping (caller falls back to a default).
291
+ */
292
+ getProviderByChain(chainId: number | string): Promise<ProviderName | null>;
293
+ /** The add-liquidity gateway (`createPoolProxyV3`) for `chainId`. */
294
+ getGatewayAddress(chainId: string): Promise<string | undefined>;
295
+ /** The Uniswap NFT position manager for `chainId`. */
296
+ getPositionManagerAddress(chainId: string): Promise<string | undefined>;
297
+ /**
298
+ * Decimal chain ids that have an add-liquidity gateway configured. Empty when
299
+ * the config isn't loaded yet — callers treat that as "nothing supported".
300
+ */
301
+ getGatewayChains(): Promise<string[]>;
302
+ private getAddress;
303
+ private listChainsWithAddress;
304
+ /** Entries are either a bare address or a list; the first is canonical. */
305
+ private firstAddress;
306
+ /** Accepts a hex ("0x2105") or decimal chain id; returns its decimal key. */
307
+ private toDecimalChainKey;
308
+ private isProviderName;
309
+ }
310
+ /** Shared instance — the config is global and immutable. */
311
+ declare const coinpoolConfigApi: CoinpoolConfigApi;
312
+
313
+ interface AffiliateFee {
314
+ affiliateFeeRecipient: string;
315
+ affiliateFeePercent: number;
316
+ }
317
+ /**
318
+ * The Keyring exchange admin setting — the source of truth the APP uses for
319
+ * user-facing swaps.
320
+ *
321
+ * It answers two independent questions, both served from one cached fetch:
322
+ *
323
+ * 1. Routing — {@link getBridgeProvider}, a port of the app's
324
+ * `useGetSettingExchange` + the `bridgeProvider` memo in
325
+ * `useGetRawTxExchange`.
326
+ * 2. Affiliate fees — {@link getAffiliateFee}, applied by adapters on EVERY
327
+ * route, including coinpool-routed pool legs.
328
+ *
329
+ * Distinct from {@link file://./CoinpoolConfigApi.ts}, which is coinpool's
330
+ * own config. Keeping them apart is deliberate.
331
+ */
332
+ declare class KeyringSettingApi {
333
+ private readonly setting;
334
+ private readonly chainSupport;
335
+ constructor(settingUrl?: string);
336
+ /**
337
+ * The provider for a swap, exactly like the app resolves it:
338
+ *
339
+ * 1. `keyringV2.bridgeProvider` is the default route for every pair.
340
+ * 2. A pair overrides to deBridge when either side is in deBridge's
341
+ * `requireChain` AND both sides are supported by deBridge.
342
+ * 3. Anything unreachable falls back to {@link DEFAULT_PROVIDER}.
343
+ *
344
+ * `dstChainId` defaults to `srcChainId` (same-chain swap). Chain ids may be
345
+ * hex (`0x2105`) or decimal.
346
+ */
347
+ getBridgeProvider(srcChainId: number | string | null | undefined, dstChainId?: number | string | null): Promise<ProviderName>;
348
+ /**
349
+ * The affiliate fee to attach to a quote, or null when none should be (missing
350
+ * recipient or a non-positive percent).
351
+ *
352
+ * The two routes read DIFFERENT parts of this payload, and must keep doing so:
353
+ *
354
+ * `'userSwap'` — the `keyringV2` block, exactly like the app's
355
+ * `getMoreDataSwap` ({@link resolveKeyringV2Fee}).
356
+ * `'pool'` — the legacy top-level keys, which is what the pool gateway
357
+ * has always been paid through ({@link resolveLegacyFee}).
358
+ *
359
+ * Defaults to `'userSwap'`, matching {@link SwapQuoteParams.route}.
360
+ */
361
+ getAffiliateFee(provider: ProviderName, chainId: number | string, route?: SwapRoute): Promise<AffiliateFee | null>;
362
+ /**
363
+ * Route `'pool'` — the legacy top-level keys.
364
+ *
365
+ * deBridge keys its recipient per chain inside the `affiliateRecipient` JSON
366
+ * string; Relay uses one flat recipient + percent pair.
367
+ */
368
+ private resolveLegacyFee;
369
+ /**
370
+ * Route `'userSwap'` — the `keyringV2` block, a direct port of the app's
371
+ * `getSettingAffiliate` (`SwapServices/{Debridge,Relay}Adapter.js`).
372
+ *
373
+ * Both fields are keyed on the provider ACTUALLY serving the quote, matching
374
+ * the app's adapters — each reads its own `PLATFORM_EXCHANGE` key rather than
375
+ * the setting's default `bridgeProvider`. That distinction is load-bearing:
376
+ * `requireChain` can route a pair to deBridge while `bridgeProvider` still
377
+ * says relay, and the fee must follow the provider that gets paid.
378
+ *
379
+ * percent = provider.affiliateFeePercentCustom[chainId]
380
+ * || provider.affiliateFeePercent
381
+ * || 0
382
+ *
383
+ * recipient = provider.affiliateRecipientCustom[chainId]
384
+ * || keyringV2.affiliateRecipientDefault
385
+ *
386
+ * The app treats 0 / '' as "not set" at every level (`||`), so this does too.
387
+ * Note the app has a final `|| AFFILIATE_FEE_RECIPIENT` env fallback that the
388
+ * core has no equivalent for; with no recipient configured we attach no fee.
389
+ */
390
+ private resolveKeyringV2Fee;
391
+ /** Legacy `affiliateRecipient` is a JSON *string* keyed by chain id. */
392
+ private parseRecipientMap;
393
+ /** Fetches both providers' supported chains; one failing must not sink the other. */
394
+ private fetchChainSupport;
395
+ private requireChainKeys;
396
+ private normalizeProvider;
397
+ /** Accepts a hex (`0x2105`) or decimal chain id and returns its decimal string. */
398
+ private toChainKey;
399
+ private toPercent;
400
+ }
401
+ /** Shared instance — the setting is global. */
402
+ declare const keyringSettingApi: KeyringSettingApi;
403
+
404
+ /**
405
+ * Abstract base for swap routers.
406
+ *
407
+ * A router answers ONE question: which provider (deBridge / Relay) should serve
408
+ * this swap? Each concrete router owns a different source of truth, and they are
409
+ * deliberately kept apart — see {@link PoolSwapRouter} and
410
+ * {@link UserSwapRouter}.
411
+ *
412
+ * Subclasses implement {@link resolveProvider}; the base wraps it in
413
+ * {@link resolve}, which guarantees a usable provider even when the underlying
414
+ * config API fails. Routing sits on the critical path of a swap the user is
415
+ * waiting on, so a config outage must degrade to {@link DEFAULT_PROVIDER}
416
+ * rather than surface as an error.
417
+ *
418
+ * Affiliate fees are NOT a routing concern: they come from the Keyring setting
419
+ * on EVERY route, including coinpool-routed pool legs. Adapters read them
420
+ * directly ({@link file://./KeyringSettingApi.ts}).
421
+ */
422
+ declare abstract class SwapRouter {
423
+ /** The route this router serves. Used as its key in the registry. */
424
+ abstract readonly route: SwapRoute;
425
+ /**
426
+ * Resolves the provider for `request`. May throw or return null — the caller
427
+ * is {@link resolve}, which supplies the fallback.
428
+ */
429
+ protected abstract resolveProvider(request: SwapRouteRequest): Promise<ProviderName | null>;
430
+ /**
431
+ * The provider for `request`. Never throws: any failure inside
432
+ * {@link resolveProvider} degrades to {@link DEFAULT_PROVIDER}.
433
+ */
434
+ resolve(request: SwapRouteRequest): Promise<ProviderName>;
435
+ /**
436
+ * Normalizes a chain id to a finite number, or null when absent/unparseable.
437
+ * Shared by subclasses so every router treats chain ids alike.
438
+ */
439
+ protected toNumericChainId(chainId: number | string | null | undefined): number | null;
440
+ }
441
+ /**
442
+ * Route `'pool'` — the native→token legs add-liquidity mixes before minting.
443
+ *
444
+ * Reads the coinpool config (`bridgeProviderByChain`), keyed on the source chain
445
+ * ALONE: these legs are always same-chain, so there is no pair to consider. This
446
+ * is the historical behaviour and the pool gateway is deployed against it, so it
447
+ * stays as-is.
448
+ */
449
+ declare class PoolSwapRouter extends SwapRouter {
450
+ private readonly config;
451
+ readonly route: "pool";
452
+ constructor(config?: CoinpoolConfigApi);
453
+ protected resolveProvider({ srcChainId }: SwapRouteRequest): Promise<ProviderName | null>;
454
+ }
455
+ /**
456
+ * Route `'userSwap'` — a user-facing swap or buy.
457
+ *
458
+ * Routed exactly like the Keyring app: the `keyringV2` admin setting's
459
+ * `bridgeProvider` is the default, overridden to deBridge when either side of
460
+ * the pair is in deBridge's `requireChain` and both sides support it. Uses BOTH
461
+ * chain ids because it is cross-chain aware.
462
+ */
463
+ declare class UserSwapRouter extends SwapRouter {
464
+ private readonly setting;
465
+ readonly route: "userSwap";
466
+ constructor(setting?: KeyringSettingApi);
467
+ protected resolveProvider({ srcChainId, dstChainId }: SwapRouteRequest): Promise<ProviderName | null>;
468
+ }
469
+
470
+ /**
471
+ * Holds one {@link SwapRouter} per route and dispatches a request to the right
472
+ * one.
473
+ *
474
+ * Routers self-declare the route they serve, so adding a route never touches
475
+ * the dispatch logic below.
476
+ */
477
+ declare class SwapRouterRegistry {
478
+ private readonly routers;
479
+ constructor(routers?: readonly SwapRouter[]);
480
+ /**
481
+ * Resolves the provider for `request` via its route's router.
482
+ *
483
+ * Never throws. Routers already degrade to {@link DEFAULT_PROVIDER} on config
484
+ * failure; the guard here covers an unknown `route` arriving from untyped JS,
485
+ * so a bad route picks the default provider instead of crashing a swap the
486
+ * user is waiting on.
487
+ */
488
+ resolveProvider(request: SwapRouteRequest): Promise<ProviderName>;
489
+ }
490
+ /** Shared registry backing the default {@link file://./SwapProviderFactory.ts} singleton. */
491
+ declare const swapRouterRegistry: SwapRouterRegistry;
492
+
493
+ /**
494
+ * Builds (and caches) the adapter for a swap.
495
+ *
496
+ * Callers state WHY they are swapping — the `route` — and the factory delegates
497
+ * to the matching {@link file://./SwapRouter.ts}. Two routes exist and they read
498
+ * different config sources on purpose:
193
499
  *
194
- * Resolution: query the exchange settings API's `bridgeProviderByChain` map.
195
- * Falls back to `DEFAULT_PROVIDER` when the API is unreachable or the chain
196
- * has no mapping. Adapter instances are cached per provider name.
500
+ * `{ route: 'pool' }` → coinpool `bridgeProviderByChain` (add-liquidity legs)
501
+ * `{ route: 'userSwap' }` → keyringV2 `bridgeProvider` (user swap / buy, like the app)
502
+ *
503
+ * Adapters are stateless, so one instance per provider is shared process-wide.
197
504
  */
198
- declare class SwapServiceFactory {
199
- private readonly providerConfig;
200
- private readonly isProduction;
505
+ declare class SwapProviderFactory {
506
+ /**
507
+ * An EXPLICIT config override, or undefined to read the module default.
508
+ *
509
+ * Deliberately not defaulted in the constructor: `config.ts` imports this
510
+ * module for `swapProviderFactory` while this module imports
511
+ * `SWAP_PROVIDER_CONFIG` from it, and in the bundled build the singleton below
512
+ * is constructed BEFORE that const is assigned. A default parameter would
513
+ * therefore capture `undefined` for the life of the process, and every
514
+ * `createService` would fault on it. Reading the binding lazily in
515
+ * {@link providers} sidesteps the cycle: by the time a quote is taken, the
516
+ * module has finished evaluating.
517
+ */
518
+ private readonly configOverride?;
519
+ private readonly routersOverride?;
201
520
  private readonly cache;
202
- constructor(providerConfig?: ExchangeProviderConfig, isProduction?: boolean);
203
- getService(srcChainId?: number | string | null): Promise<BaseSwapService>;
204
- getServiceByProvider(provider: ProviderName): Promise<BaseSwapService>;
205
- getActiveProvider(srcChainId?: number | string | null): Promise<ProviderName>;
206
- isProviderActive(name: ProviderName, srcChainId?: number | string | null): Promise<boolean>;
207
- getAvailableProviders(): ProviderName[];
208
- clearCache(): void;
521
+ constructor(providerConfig?: SwapProviderConfigMap, routers?: SwapRouterRegistry);
522
+ /** Connection config in force — an injected map, else the module default. */
523
+ private get providers();
524
+ /** Router registry in force — same lazy read, same cycle. */
525
+ private get routers();
526
+ /**
527
+ * The adapter for a swap, chosen by its route, with that route already bound
528
+ * to it. Never throws on config failure — routing degrades to the default
529
+ * provider.
530
+ *
531
+ * The returned service applies `request.route` to every quote, so callers
532
+ * state the route ONCE here rather than repeating it on each `getQuote`.
533
+ */
534
+ getService(request: SwapRouteRequest): Promise<BaseSwapProvider>;
535
+ /**
536
+ * The adapter for an ALREADY-resolved provider. Use this to stay on the
537
+ * provider that produced a quote (approval and execution must not re-route
538
+ * mid-flight); use {@link getService} to start a new swap.
539
+ */
540
+ getServiceByProvider(provider: ProviderName): BaseSwapProvider;
541
+ /**
542
+ * Discards the cached adapters so the next call rebuilds them from the
543
+ * CURRENT provider config. Needed when connection config (an API key) is
544
+ * installed after an adapter has already been handed out.
545
+ */
546
+ resetCache(): void;
547
+ /** The provider a route resolves to, without building the adapter. */
548
+ resolveProvider(request: SwapRouteRequest): Promise<ProviderName>;
209
549
  private createService;
210
550
  }
211
- /** Default singleton. */
212
- declare const swapServiceFactory: SwapServiceFactory;
551
+ /** Default singleton (production endpoints). */
552
+ declare const swapProviderFactory: SwapProviderFactory;
213
553
 
214
554
  /**
215
- * Per-provider client config. The active provider for a given chain is decided
216
- * at runtime by the exchange settings API (`bridgeProviderByChain`); this map
217
- * only holds connection-level config (base URLs, tokens) for each provider.
555
+ * Connection-level config (base URLs, tokens) for each swap provider.
556
+ *
557
+ * WHICH provider serves a given swap is decided at runtime by the routers
558
+ * ({@link file://./SwapRouter.ts}); this map only says how to reach each one.
218
559
  */
219
- declare const SWAP_PROVIDER_CONFIG: ExchangeProviderConfig;
560
+ declare const SWAP_PROVIDER_CONFIG: SwapProviderConfigMap;
220
561
  declare const DEFAULT_PROVIDER: ProviderName;
562
+ /**
563
+ * Installs connection-level overrides for a provider — the host app's API key
564
+ * for Relay, say — before the first quote is taken.
565
+ *
566
+ * Adapters are built once and cached per provider, so this ALSO drops the
567
+ * factory's cache: an adapter constructed before the key arrived would keep
568
+ * sending unauthenticated requests for the life of the process.
569
+ */
570
+ declare function configureSwapProvider(name: ProviderName, cfg: Partial<SwapProviderConfig>): void;
221
571
 
222
- interface AffiliateFee {
223
- affiliateFeeRecipient: string;
224
- affiliateFeePercent: number;
572
+ /**
573
+ * A single remote value, fetched at most once per TTL and shared by every
574
+ * concurrent caller.
575
+ *
576
+ * Three config sources in this module needed the same thing — a lazy load, a
577
+ * single-flight guard so parallel tool calls don't stampede the API, and a
578
+ * failure mode that never rejects. Each had grown its own copy of that logic;
579
+ * this is the one implementation they all use.
580
+ *
581
+ * On failure {@link get} resolves to the last known value, or null if it never
582
+ * loaded. Callers therefore always receive a value or null and never an
583
+ * exception — routing and address lookups sit on the critical path of a user's
584
+ * swap, so a config outage must degrade rather than throw.
585
+ */
586
+ declare class CachedResource<T> {
587
+ private readonly loader;
588
+ private readonly ttlMs;
589
+ private value;
590
+ private loadedAt;
591
+ private inFlight;
592
+ /**
593
+ * @param loader Fetches a fresh value. May throw; failures are absorbed.
594
+ * @param ttlMs How long a loaded value stays fresh. Omit (or `Infinity`) to
595
+ * cache for the lifetime of the process — right for values that are
596
+ * effectively static, like deployed contract addresses.
597
+ */
598
+ constructor(loader: () => Promise<T | null>, ttlMs?: number);
599
+ /** The cached value, loading it first if missing or stale. Never throws. */
600
+ get(): Promise<T | null>;
225
601
  }
602
+
603
+ /**
604
+ * Reading a quote's provider-specific shape.
605
+ *
606
+ * Every adapter answers with its own JSON under `raw`, so the two facts callers
607
+ * actually want — how much comes out, and why it failed — sit at a different
608
+ * path per provider. These helpers own that mapping.
609
+ *
610
+ * They live in the swap module rather than in a tool because BOTH the agent's
611
+ * tools and the app's in-chat amount form quote through `swapProviderFactory`
612
+ * and must read the result identically: an estimate the form derived one way and
613
+ * the confirm card derived another would show the user two different numbers for
614
+ * one trade.
615
+ */
616
+ /**
617
+ * Estimated receive amount in the destination token's smallest units, or
618
+ * `undefined` when the quote reports none.
619
+ *
620
+ * Shape differs per provider — deBridge same-chain: `raw.tokenOut.minAmount`;
621
+ * deBridge cross-chain: `raw.estimation.dstChainTokenOut.amount`; Relay:
622
+ * `raw.details.currencyOut.{amount|minimumAmount}`. Anything that isn't a run of
623
+ * digits is rejected rather than passed on: these are smallest-unit integers, and
624
+ * a decimal or an e-notation string here would be scaled by the token's decimals
625
+ * a second time downstream.
626
+ */
627
+ declare function extractOutRaw(quote: SwapQuoteResult): string | undefined;
226
628
  /**
227
- * Returns the active provider for `chainId` from the coinpool config API, or
228
- * `null` when the API is unreachable or the chain has no mapping (caller should
229
- * fall back to a default).
629
+ * A human-readable failure reason from a failed quote. Adapters set
630
+ * `errorMessage` (string) and `error` (string or a provider object); deBridge
631
+ * also nests a reason in `raw.errorMessage` / `raw.error`. Always returns
632
+ * something, so the caller has a line to show.
230
633
  */
231
- declare function getProviderByChain(chainId: number | string, isProduction: boolean): Promise<ProviderName | null>;
634
+ declare function extractQuoteError(quote: SwapQuoteResult): string;
635
+
232
636
  /**
233
- * Returns the affiliate fee tuple for the given provider+chain, or `null` when
234
- * no fee should be attached (missing recipient or percent <= 0).
637
+ * The fixed native protocol fee (in WEI) a swap on `srcChainId` will be charged,
638
+ * or `0n` when none applies.
639
+ *
640
+ * Mirrors `useProtocolFee` exactly, including its failure mode: the hook wraps
641
+ * the whole read in a try/catch returning '0', so an unreachable RPC or a chain
642
+ * without the contract degrades to "no fee" rather than blocking the user. Never
643
+ * throws.
644
+ *
645
+ * `dstChainId` defaults to `srcChainId`, i.e. a same-chain swap, which is the
646
+ * case that returns `0n`.
235
647
  */
236
- declare function getAffiliateFee(provider: ProviderName, chainId: number | string): Promise<AffiliateFee | null>;
648
+ declare function readProtocolFeeWei(input: {
649
+ provider: ProviderName;
650
+ srcChainId: number | string | null | undefined;
651
+ dstChainId?: number | string | null | undefined;
652
+ }): Promise<bigint>;
237
653
 
238
- declare function getGatewayAddress(chainId: string, isProduction: boolean): Promise<string | undefined>;
239
- /** Decimal chain ids that have an add-liquidity gateway (`createPoolProxyV3`) configured. */
240
- declare function getGatewayChains(isProduction: boolean): Promise<string[]>;
241
- declare function getPositionManagerAddress(chainId: string, isProduction: boolean): Promise<string | undefined>;
654
+ /**
655
+ * Building the ERC-20 approval leg of a swap, for providers that do NOT bundle
656
+ * it themselves (deBridge). Relay ships its own approve steps in the quote and
657
+ * does not come through here — see `RelayProvider.checkApproval`.
658
+ *
659
+ * The reason this is more than one `encodeFunctionData` call: some ERC-20s
660
+ * refuse to overwrite a NON-ZERO allowance. USDT on Ethereum is the canonical
661
+ * one — its `approve` carries
662
+ *
663
+ * require(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
664
+ *
665
+ * so raising a standing allowance reverts, and the allowance has to be zeroed
666
+ * first. Others of the same 2017-2018 vintage (KNC, OMG, the old ERC-20 BNB)
667
+ * do the same. Which is why this is decided by BEHAVIOUR, not by a hard-coded
668
+ * token list: the chain is asked whether `approve(spender, amount)` would
669
+ * succeed as things stand, and only when it would not is the zeroing approve
670
+ * prepended. A list would miss every token nobody has reported yet.
671
+ */
672
+ /** `approve(spender, value)` calldata for an ERC-20. */
673
+ declare function encodeApprove(spender: string, value: bigint): string;
674
+ interface BuildApprovalsParams {
675
+ /** Undefined when the caller has no chain to probe on — see below. */
676
+ chain?: string;
677
+ token: string;
678
+ owner: string;
679
+ spender: string;
680
+ /** The spend, in the token's smallest units. */
681
+ amount: bigint;
682
+ /** Current allowance, when the caller has already read it. */
683
+ allowance?: bigint | null;
684
+ }
685
+ /**
686
+ * Every approval transaction needed to let `spender` pull `amount`, in order.
687
+ *
688
+ * - `[]` when the standing allowance already covers the spend.
689
+ * - `[approve(amount)]` in the ordinary case.
690
+ * - `[approve(0), approve(amount)]` when a non-zero allowance is in the way and
691
+ * the token will not let it be overwritten.
692
+ *
693
+ * The zeroing leg is only added when there IS something to zero, so a first-time
694
+ * approval is never charged for two transactions. When the probe cannot reach a
695
+ * verdict the single approve is returned unchanged: that is what every earlier
696
+ * build did, and guessing "reset" on an unreadable RPC would spend the user's
697
+ * gas on a transaction that is very probably unnecessary.
698
+ */
699
+ declare function buildApprovals({ chain, token, owner, spender, amount, allowance, }: BuildApprovalsParams): Promise<ApprovalTx[]>;
242
700
 
243
701
  declare const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
244
702
  interface NativeTokenInfo {
@@ -260,18 +718,10 @@ interface ChainMeta {
260
718
  declare function getChainMeta(chainId: string): ChainMeta | undefined;
261
719
  declare function getNativeTokenInfo(chainId: string): NativeTokenInfo | undefined;
262
720
  interface PoolServiceConfig {
263
- /**
264
- * Optional swap factory override. When omitted, a factory is built using the
265
- * `isProduction` flag (defaults to the prod singleton when true).
266
- */
267
- swapFactory?: SwapServiceFactory;
721
+ /** Optional swap factory override. Defaults to the shared singleton. */
722
+ swapFactory?: SwapProviderFactory;
268
723
  /** Pantograph URL for native price lookups. Default: https://pantograph.keyring.app */
269
724
  pantographUrl?: string;
270
- /**
271
- * Whether to hit production endpoints for addresses + bridge-provider config.
272
- * Default true.
273
- */
274
- isProduction?: boolean;
275
725
  }
276
726
  interface TransactionReceiptLog {
277
727
  address?: string;
@@ -333,7 +783,6 @@ interface PoolOnchainInfo {
333
783
  }
334
784
  declare class PoolService {
335
785
  private swapFactory;
336
- private isProduction;
337
786
  constructor(config?: PoolServiceConfig);
338
787
  /**
339
788
  * True when this service has on-chain pool support (RPC + gateway config) for
@@ -462,9 +911,10 @@ declare class PoolService {
462
911
  * Fetches a single-leg same-chain swap quote (native → token) used to mix
463
912
  * the user's native input into pool token0 / token1 before minting.
464
913
  *
465
- * Provider is picked by `SwapServiceFactory` from the (numeric) chain id —
466
- * deBridge for chains it supports, Relay otherwise. The return shape is
467
- * normalised: `{ to, data, value, minAmountOut }`, regardless of provider.
914
+ * Provider is picked by `SwapProviderFactory` on the `'pool'` route: the
915
+ * coinpool `bridgeProviderByChain` config, keyed on the chain id. The return
916
+ * shape is normalised: `{ to, data, value, minAmountOut }`, regardless of
917
+ * provider.
468
918
  *
469
919
  * Throws on failure; caller decides whether to surface or skip.
470
920
  */
@@ -1091,71 +1541,64 @@ interface BuyTokenSide {
1091
1541
  amount?: string;
1092
1542
  /** Amount in the token's smallest unit (wei-equivalent), as a decimal string. */
1093
1543
  rawAmount?: string;
1544
+ /**
1545
+ * Token logo URL, when the balance/metadata source reported one. Display only
1546
+ * — the FE falls back to a generic token icon when it is absent, so nothing
1547
+ * depends on it being set.
1548
+ */
1549
+ logo?: string;
1094
1550
  }
1095
1551
  /**
1096
- * Props for the FE `BuyTokenConfirmTx` component — the single data cube the
1097
- * BuyTokenTool ships once the user has supplied pay token + dest token + a
1098
- * spend amount.
1552
+ * Props for the FE `SwapTokenForm` component — the ONE payload SwapTokenTool and
1553
+ * BuyTokenTool ship, and the only UI either of them emits.
1554
+ *
1555
+ * Sent as soon as both sides of the trade are resolved, whether or not the user
1556
+ * named an amount: named, it arrives as `initialAmount` and the form opens
1557
+ * pre-filled; unnamed, the form opens empty. Either way the amount stays
1558
+ * editable and the FE quotes it.
1099
1559
  *
1100
- * The tool has already: fetched a swap quote (so `estimatedOut` is the expected
1101
- * receive amount), built the raw swap transaction (`swapTx`), and checked
1102
- * allowance (`approveTx` is set only when an approval must run first). The FE
1103
- * renders a confirmation panel and executes approve (if any) then swap itself —
1104
- * no further BE round-trip is needed. This is NOT a wallet-action form payload:
1105
- * BuyTokenTool emits its own UI component, so `buy_token` is intentionally NOT
1106
- * a member of WalletActionType.
1560
+ * This replaced two things at once: percentage action-buttons that spent a full
1561
+ * agent turn per tap, and a separately-quoted confirm card. Both were the same
1562
+ * trade at different stages, and neither let the user change the amount without
1563
+ * another round-trip through the model.
1564
+ *
1565
+ * The FE quotes by calling `swapProviderFactory` directly: the core is imported
1566
+ * IN-PROCESS by the app, so the adapters the tools once used are already
1567
+ * reachable. It must quote with `route: 'userSwap'` and `isCrossChain: false` —
1568
+ * the route decides which affiliate config applies, so another route would price
1569
+ * a different trade.
1570
+ *
1571
+ * `fromToken.rawAmount` carries the SPENDABLE balance in smallest units — for a
1572
+ * native source that is already NET of the gas reserve, so "100%" can never
1573
+ * leave the user unable to pay for the swap. The FE derives every percentage
1574
+ * from it with `mulDivFloor` (exported from the core alongside these types):
1575
+ * float math on a balance rounds UP and trips a false "insufficient balance".
1107
1576
  */
1108
- interface BuyTokenConfirmTxProps {
1577
+ interface SwapTokenFormProps {
1109
1578
  chain: ChainRef;
1110
- /** Token the user spends. */
1111
- payToken: BuyTokenSide;
1112
- /** Token the user receives. */
1113
- buyToken: BuyTokenSide;
1114
- /** Estimated receive amount of buyToken (human-readable), when the provider reported one. */
1115
- estimatedOut?: string;
1116
- /** Estimated receive amount of buyToken in smallest units, when available. */
1117
- estimatedOutRaw?: string;
1118
- /** Swap provider that produced the quote (e.g. "debridge", "relay"). */
1119
- provider?: string;
1120
- /** Raw swap transaction the FE signs + broadcasts. */
1121
- swapTx: UnsignedTx;
1122
- /**
1123
- * Raw ERC-20 approve transaction to run BEFORE the swap. Present only when an
1124
- * allowance is required (native pay token or sufficient allowance ⇒ omitted).
1125
- */
1126
- approveTx?: UnsignedTx;
1127
- }
1128
- /**
1129
- * Props for the FE `SwapTokenConfirmTx` component — the single data cube the
1130
- * SwapTokenTool ships once the user has supplied a SOURCE token they hold,
1131
- * a destination token, and a source amount.
1132
- *
1133
- * Mechanically identical to {@link BuyTokenConfirmTxProps} (deBridge EXACT_INPUT
1134
- * quote → raw swap tx → optional approve), but the framing is "swap FROM a token
1135
- * I already hold TO another token": `fromToken` is the user's held source token
1136
- * (always balance-checked) and `toToken` is what they receive. Like buy, this is
1137
- * NOT a wallet-action form payload — SwapTokenTool emits its own UI component, so
1138
- * `swap_token` is intentionally NOT a member of WalletActionType.
1139
- */
1140
- interface SwapTokenConfirmTxProps {
1141
- chain: ChainRef;
1142
- /** Token the user spends (the source they already hold). */
1579
+ /**
1580
+ * The token being spent. `rawAmount` is the spendable balance (smallest
1581
+ * units, gas reserve already deducted for native); `amount` is the same
1582
+ * figure human-readable. Carries no chosen amount — that is what the form asks for.
1583
+ */
1143
1584
  fromToken: BuyTokenSide;
1144
- /** Token the user receives. */
1585
+ /** The token being received. Has no amount until the form quotes one. */
1145
1586
  toToken: BuyTokenSide;
1146
- /** Estimated receive amount of toToken (human-readable), when the provider reported one. */
1147
- estimatedOut?: string;
1148
- /** Estimated receive amount of toToken in smallest units, when available. */
1149
- estimatedOutRaw?: string;
1150
- /** Swap provider that produced the quote (e.g. "debridge", "relay"). */
1151
- provider?: string;
1152
- /** Raw swap transaction the FE signs + broadcasts. */
1153
- swapTx: UnsignedTx;
1587
+ /** Wallet the swap is quoted and signed for (sender and recipient). */
1588
+ walletAddress: string;
1589
+ /** 'swap' when the user started from a token they hold, 'buy' when from the destination. */
1590
+ intent: 'swap' | 'buy';
1154
1591
  /**
1155
- * Raw ERC-20 approve transaction to run BEFORE the swap. Present only when an
1156
- * allowance is required (native source token or sufficient allowance ⇒ omitted).
1592
+ * Amount the user already named ("swap 10 USDC to USDT"), pre-filled into the
1593
+ * field and quoted on sight. Absent when they named no amount, leaving the
1594
+ * field empty for them to size.
1595
+ *
1596
+ * This is what lets ONE form serve both cases. The amount is still fully
1597
+ * editable — a named amount is a starting point, not a commitment — and it is
1598
+ * already validated against the spendable balance by the tool, so the form
1599
+ * never opens pre-filled with more than the user can spend.
1157
1600
  */
1158
- approveTx?: UnsignedTx;
1601
+ initialAmount?: string;
1159
1602
  }
1160
1603
  /** Human-readable summary of an add-liquidity tx, shown above the Confirm button. */
1161
1604
  interface AddLiquiditySummary {
@@ -1458,6 +1901,19 @@ interface AgentConfig {
1458
1901
  * is not listed simply uses those built-in and catalogue endpoints.
1459
1902
  */
1460
1903
  rpcUrls?: Record<string, string>;
1904
+ /**
1905
+ * Connection-level config for the swap providers, keyed by provider name —
1906
+ * currently the host app's Relay API key. Installed before any swap tool
1907
+ * runs, so quotes taken through the agent carry the same key (rate limits,
1908
+ * attribution) as the ones the app takes directly.
1909
+ *
1910
+ * Omit it and the providers fall back to their built-in public endpoints.
1911
+ */
1912
+ swapProviders?: Partial<Record<'debridge' | 'relay', {
1913
+ apiKey?: string;
1914
+ apiBaseUrl?: string;
1915
+ accessToken?: string;
1916
+ }>>;
1461
1917
  /**
1462
1918
  * Restrict which of the built-in supported chains are active by REMOVING the
1463
1919
  * listed ones. Each entry is a {@link ChainSelector} — the chain's canonical
@@ -1572,13 +2028,35 @@ interface AgentConfig {
1572
2028
  * for buying one. Opt-in — defaults to false.
1573
2029
  */
1574
2030
  nfc?: boolean;
1575
- pool?: boolean;
2031
+ /**
2032
+ * Uniswap Explore-backed pool agent (V2/V3/V4 + add-liquidity). Default on.
2033
+ * Mutually exclusive with `pool-subgraph` and `pool-defillama`.
2034
+ */
2035
+ 'pool-uniswap'?: boolean;
1576
2036
  /**
1577
2037
  * Subgraph-backed pool agent (Uniswap V3 via The Graph + DefiLlama APR + CoinPool ranges).
1578
- * Mutually exclusive with `pool`. Enabling this (true) automatically disables `pool`
1579
- * unless `pool` is also explicitly set to true. Defaults to false.
2038
+ * Mutually exclusive with `pool-uniswap` and `pool-defillama`. Enabling this
2039
+ * (true) automatically disables `pool-uniswap` unless that key is also
2040
+ * explicitly set to true. Defaults to false.
1580
2041
  */
1581
2042
  'pool-subgraph'?: boolean;
2043
+ /**
2044
+ * DefiLlama-backed pool agent (Uniswap V2/V3/V4 market data from DefiLlama
2045
+ * Yields + CoinPool ranges + on-chain add-liquidity).
2046
+ *
2047
+ * Serves the SAME capabilities as `pool-uniswap` — same questions, same
2048
+ * add-liquidity flow — through a different upstream API, so a deployment can
2049
+ * switch data sources without any user-visible behaviour change. Its data
2050
+ * tools are named `defillama-*` where the Uniswap stack's are `uniswap-*`;
2051
+ * the add-liquidity / price-range / manage tools are literally shared
2052
+ * (`pool-*`). Covers 7 chains rather than 8: DefiLlama tracks no Uniswap
2053
+ * pools on Linea.
2054
+ *
2055
+ * Mutually exclusive with `pool-uniswap` and `pool-subgraph`. Enabling this
2056
+ * (true) automatically disables `pool-uniswap` unless that key is also
2057
+ * explicitly set to true. Defaults to false. Configure via `defiLlama`.
2058
+ */
2059
+ 'pool-defillama'?: boolean;
1582
2060
  ai?: boolean;
1583
2061
  };
1584
2062
  /**
@@ -1620,11 +2098,28 @@ interface AgentConfig {
1620
2098
  searchBaseUrl?: string;
1621
2099
  /** Minimum USD value the user must supply to add liquidity. Default 10. */
1622
2100
  minProvideUsd?: number;
2101
+ } | false;
2102
+ /**
2103
+ * DefiLlama Yields config for the `pool-defillama` subagent. Set to `false` to
2104
+ * skip registering those tools.
2105
+ *
2106
+ * Independent of `uniswap` — the DefiLlama stack needs no Uniswap gateway. It
2107
+ * DOES still use the shared RPC endpoints (for the on-chain add-liquidity
2108
+ * flow) and the CoinPool API (for price-range suggestions), exactly as the
2109
+ * Uniswap stack does. To actually route queries here, also set
2110
+ * `subagents['pool-defillama']: true`.
2111
+ */
2112
+ defiLlama?: {
2113
+ /** Base URL of the DefiLlama Yields API (default: https://yields.llama.fi). */
2114
+ baseUrl?: string;
1623
2115
  /**
1624
- * Hit production endpoints (coinpool.app) for addresses + bridge-provider
1625
- * mapping. Set false for staging. Default true.
2116
+ * How long the pool snapshot is cached, in ms. Default 5 minutes.
2117
+ * DefiLlama serves one un-filterable ~12MB payload, so this is fetched
2118
+ * whole and cached; upstream itself only refreshes hourly.
1626
2119
  */
1627
- isProduction?: boolean;
2120
+ cacheTtlMs?: number;
2121
+ /** Minimum USD value the user must supply to add liquidity. Default 10. */
2122
+ minProvideUsd?: number;
1628
2123
  } | false;
1629
2124
  /**
1630
2125
  * Tools that must NOT open a form in this deployment, mapped to the message
@@ -2679,33 +3174,38 @@ declare function createNfcAgent(llm: LLMProvider, registry: ToolRegistry, option
2679
3174
  declare const AI_AGENT_TOOL_NAMES: readonly ["gemini-search-ai"];
2680
3175
  declare function createAiAgent(llm: LLMProvider, registry: ToolRegistry, options?: SubagentOptions): Subagent;
2681
3176
 
2682
- declare const POOL_AGENT_TOOL_NAMES: readonly ["get-top-pools", "get-pool-detail", "search-pools", "lookup-pool-by-address", "open-add-liquidity-form", "preview-add-liquidity", "estimate-pool-yield", "get-pool-price-ranges", "manage-liquidity-redirect", "pool-fallback-ai"];
2683
- declare function createPoolAgent(llm: LLMProvider, registry: ToolRegistry, options?: SubagentOptions): Subagent;
3177
+ declare const POOL_UNISWAP_AGENT_TOOL_NAMES: readonly ["uniswap-top-pools", "uniswap-pool-detail", "uniswap-search-pools", "uniswap-pool-by-address", "pool-open-add-liquidity-form", "pool-preview-add-liquidity", "uniswap-estimate-pool-yield", "pool-price-ranges", "pool-manage-liquidity-redirect", "pool-fallback-ai"];
3178
+ declare function createPoolUniswapAgent(llm: LLMProvider, registry: ToolRegistry, options?: SubagentOptions): Subagent;
2684
3179
 
2685
3180
  declare const WALLET_ACTION_AGENT_TOOL_NAMES: readonly ["open-send-native-form", "open-send-token-form", "open-send-nft-form", "open-buy-token-form", "open-swap-token-form", "open-approve-token-form"];
2686
3181
  declare function createWalletActionAgent(llm: LLMProvider, registry: ToolRegistry, options?: SubagentOptions): Subagent;
2687
3182
 
2688
3183
  /** Built-in subagent ids. */
2689
- type DefaultSubagentName = 'wallet' | 'wallet-action' | 'lending' | 'token' | 'nft' | 'nfc' | 'pool' | 'pool-subgraph' | 'ai';
3184
+ type DefaultSubagentName = 'wallet' | 'wallet-action' | 'lending' | 'token' | 'nft' | 'nfc' | 'pool-uniswap' | 'pool-subgraph' | 'pool-defillama' | 'ai';
2690
3185
  /**
2691
3186
  * Per-subagent enable flags. Default for every key is `true` EXCEPT
2692
- * `pool-subgraph`, which defaults to `false` because it is mutually exclusive
2693
- * with `pool`. Enable exactly one of `pool` / `pool-subgraph` per deployment:
3187
+ * `pool-subgraph` and `pool-defillama`, which default to `false` because all
3188
+ * three pool agents are mutually exclusive. Enable exactly ONE per deployment:
2694
3189
  *
2695
- * - `pool` (default on) → Uniswap interface gateway (V2/V3/V4) + add-liquidity flows
2696
- * - `pool-subgraph` → The Graph subgraphs (V3 only) + DefiLlama APR + CoinPool ranges
3190
+ * - `pool-uniswap` (default on) → Uniswap Explore gateway (V2/V3/V4) + add-liquidity
3191
+ * - `pool-subgraph` → The Graph subgraphs (V3) + DefiLlama APR + CoinPool ranges
3192
+ * - `pool-defillama` → DefiLlama Yields (V2/V3/V4 data, V3 add-liquidity) + CoinPool ranges
2697
3193
  *
2698
- * Turning `pool-subgraph` on automatically turns `pool` off unless the caller
2699
- * has explicitly enabled `pool: true`. This prevents two pool agents from
2700
- * competing for the same user query.
3194
+ * Turning `pool-subgraph` OR `pool-defillama` on automatically turns
3195
+ * `pool-uniswap` off unless the caller has explicitly enabled it. This prevents
3196
+ * two pool agents from competing for the same user query.
3197
+ *
3198
+ * `pool-defillama` serves the same capabilities as `pool-uniswap` through a
3199
+ * different API: same flows, source-prefixed tool names, 7 chains instead of 8
3200
+ * (no Linea).
2701
3201
  */
2702
3202
  type SubagentToggles = Partial<Record<DefaultSubagentName, boolean>>;
2703
3203
  /**
2704
3204
  * Create the default set of domain subagents. Returned in routing-priority order.
2705
3205
  *
2706
- * `toggles` lets callers disable individual subagents. `pool-subgraph` is
2707
- * opt-in (default false); enabling it disables `pool` unless the caller has
2708
- * explicitly set `pool: true`.
3206
+ * `toggles` lets callers disable individual subagents. `pool-subgraph` and
3207
+ * `pool-defillama` are opt-in (default false); enabling either disables
3208
+ * `pool-uniswap` unless the caller has explicitly set it back on.
2709
3209
  */
2710
3210
  declare function createDefaultSubagents(llm: LLMProvider, registry: ToolRegistry, options?: SubagentOptions, toggles?: SubagentToggles): Subagent[];
2711
3211
 
@@ -2832,6 +3332,24 @@ interface TokenMetadata {
2832
3332
  usd_price?: number;
2833
3333
  usd_price_24hr_percent_change?: number;
2834
3334
  usd_price_24hr_usd_change?: number;
3335
+ /**
3336
+ * The token's `symbol()` as READ FROM THE CONTRACT, when the upstream index
3337
+ * has it. Distinct from `symbol`, which is the index's own editorial label and
3338
+ * is frequently lower-cased ("usdc") or otherwise diverges from the chain.
3339
+ *
3340
+ * `null` when the index never resolved it — a token whose symbol therefore
3341
+ * still has to be read on-chain by the caller. Absent on endpoints that don't
3342
+ * report it at all (e.g. top-gainers), which is the same situation.
3343
+ *
3344
+ * Consumers should not have to reach for this: `normalizePantographToken`
3345
+ * already promotes it over `symbol`, so the canonical field is on-chain-true
3346
+ * wherever Pantograph knew the answer. It stays exposed for callers that need
3347
+ * to know WHICH source a symbol came from — see `confirmTokenIdentities`,
3348
+ * which skips its RPC round-trip when the symbol is already on-chain-sourced.
3349
+ */
3350
+ symbolOnchain?: string | null;
3351
+ /** The token's on-chain `name()`, same contract as {@link symbolOnchain}. */
3352
+ nameOnchain?: string | null;
2835
3353
  auditGoplus?: Record<string, unknown>;
2836
3354
  holder_count?: string;
2837
3355
  holders?: unknown[];
@@ -7473,10 +7991,7 @@ interface CoinPoolPairSummary {
7473
7991
  }
7474
7992
  type SubgraphSort = 'tvl' | 'volume' | 'apr' | 'fee' | 'liquidity';
7475
7993
 
7476
- type TopPoolsToolConfig = UniswapServiceConfig & {
7477
- /** Hit production addresses endpoints (for add-liquidity gateway lookup). Default true. */
7478
- isProduction?: boolean;
7479
- };
7994
+ type TopPoolsToolConfig = UniswapServiceConfig;
7480
7995
  /**
7481
7996
  * Tool: get-top-pools
7482
7997
  *
@@ -7544,10 +8059,7 @@ interface CoinPoolServiceConfig {
7544
8059
  coinPoolBaseUrl?: string;
7545
8060
  }
7546
8061
 
7547
- type PoolDetailToolConfig = UniswapServiceConfig & {
7548
- /** Hit production addresses endpoints (for add-liquidity gateway lookup). Default true. */
7549
- isProduction?: boolean;
7550
- };
8062
+ type PoolDetailToolConfig = UniswapServiceConfig;
7551
8063
  /**
7552
8064
  * Tool: get-pool-detail
7553
8065
  *
@@ -7604,10 +8116,7 @@ declare class PoolDetailTool extends BaseTool {
7604
8116
  private fetchPriceRanges;
7605
8117
  }
7606
8118
 
7607
- type PoolSearchToolConfig = UniswapServiceConfig & {
7608
- /** Hit production addresses endpoints (for add-liquidity gateway lookup). Default true. */
7609
- isProduction?: boolean;
7610
- };
8119
+ type PoolSearchToolConfig = UniswapServiceConfig;
7611
8120
  /**
7612
8121
  * Tool: search-pools
7613
8122
  *
@@ -7636,10 +8145,7 @@ interface PoolHistoricalVolumePoint {
7636
8145
  volumeUsd?: number;
7637
8146
  }
7638
8147
 
7639
- type PoolByAddressToolConfig = UniswapServiceConfig & {
7640
- /** Hit production addresses endpoints (for add-liquidity gateway lookup). Default true. */
7641
- isProduction?: boolean;
7642
- };
8148
+ type PoolByAddressToolConfig = UniswapServiceConfig;
7643
8149
  /**
7644
8150
  * Tool: lookup-pool-by-address
7645
8151
  *
@@ -7763,12 +8269,89 @@ declare class PoolByAddressTool extends BaseTool {
7763
8269
  private formatPoolCandidate;
7764
8270
  }
7765
8271
 
8272
+ /**
8273
+ * Pluggable pool LOOKUP for the add-liquidity flow.
8274
+ *
8275
+ * `OpenAddLiquidityFormTool` needs exactly one thing from a pool data source:
8276
+ * turn a token pair (plus an optional fee tier, plus an optionally pinned pool
8277
+ * address) into candidate pools it can pick from. Everything the tool does after
8278
+ * that — reading `slot0` / `tickSpacing` on-chain, the balance and gas-reserve
8279
+ * maths, tick alignment, building the gateway call — is chain state, identical
8280
+ * no matter which API named the pool.
8281
+ *
8282
+ * Isolating just the lookup behind this interface is what lets the Uniswap
8283
+ * Explore stack and the DefiLlama stack share ONE add-liquidity implementation
8284
+ * instead of maintaining two ~1000-line copies that would inevitably drift.
8285
+ *
8286
+ * {@link PoolCandidate} is structurally a subset of `SearchPoolResult`, so the
8287
+ * Uniswap resolver is a pass-through and the tool's existing matching helpers
8288
+ * work unchanged against either source.
8289
+ */
8290
+
8291
+ /**
8292
+ * A token as a candidate reports it. `name` and `logo` are display-only — they
8293
+ * flow straight into the add-liquidity form's props — and are optional because
8294
+ * not every source carries them (DefiLlama reports symbols and addresses only,
8295
+ * so the form simply renders without them).
8296
+ */
8297
+ interface PoolCandidateToken {
8298
+ symbol?: string;
8299
+ address?: string;
8300
+ name?: string;
8301
+ logo?: string;
8302
+ }
8303
+ /**
8304
+ * One candidate pool. `id` is the pool address (V2/V3) or pool id (V4) — the
8305
+ * identifier the add-liquidity flow reads on-chain.
8306
+ */
8307
+ interface PoolCandidate {
8308
+ id?: string;
8309
+ protocolVersion?: 'V2' | 'V3' | 'V4';
8310
+ feeTier?: number;
8311
+ token0?: PoolCandidateToken;
8312
+ token1?: PoolCandidateToken;
8313
+ tvlUsd?: number;
8314
+ volume1DayUsd?: number;
8315
+ volumeUsd24hr?: number;
8316
+ apr?: number;
8317
+ isDynamicFee?: boolean;
8318
+ }
8319
+ interface ResolvePoolCandidatesParams {
8320
+ chain: string;
8321
+ token0Symbol: string;
8322
+ token1Symbol: string;
8323
+ /** Narrow to one fee tier (bps). Ignored when a pool address is pinned. */
8324
+ feeTier?: number;
8325
+ /**
8326
+ * `'V3'` for the mintable set (the default the flow works with), `'ALL'` when
8327
+ * the caller is diagnosing whether the pool exists as V2/V4 instead.
8328
+ */
8329
+ protocolVersion: 'V3' | 'ALL';
8330
+ }
8331
+ /** A pool data source the add-liquidity flow can resolve candidates from. */
8332
+ interface PoolCandidateResolver {
8333
+ /**
8334
+ * Return every pool matching the pair on the chain. Returns `null` — distinct
8335
+ * from `[]` — when the LOOKUP ITSELF failed, so the caller reports an error
8336
+ * rather than the misleading "no pool found".
8337
+ */
8338
+ resolveCandidates(params: ResolvePoolCandidatesParams): Promise<PoolCandidate[] | null>;
8339
+ }
8340
+
7766
8341
  interface OpenAddLiquidityFormToolConfig extends UniswapServiceConfig {
7767
8342
  pool?: PoolServiceConfig;
7768
8343
  /** Min USD value the user must supply. Default 10. */
7769
8344
  minProvideUsd?: number;
7770
8345
  /** CoinPool API config for the reference price-range suggestions. */
7771
8346
  coinPool?: CoinPoolServiceConfig;
8347
+ /**
8348
+ * Where candidate pools are looked up from. Defaults to Uniswap's own pool
8349
+ * search; the DefiLlama-backed pool agent injects its own resolver so both
8350
+ * agents share this single add-liquidity implementation. See
8351
+ * {@link PoolCandidateResolver} — only the LOOKUP varies, never the on-chain
8352
+ * work that follows it.
8353
+ */
8354
+ resolver?: PoolCandidateResolver;
7772
8355
  }
7773
8356
  /**
7774
8357
  * Tool: open-add-liquidity-form
@@ -7791,7 +8374,7 @@ declare class OpenAddLiquidityFormTool extends BaseTool {
7791
8374
  category: string;
7792
8375
  description: string;
7793
8376
  parameters: ToolParameter[];
7794
- private uniswap;
8377
+ private resolver;
7795
8378
  private pool;
7796
8379
  private coinPool;
7797
8380
  private minProvideUsd;
@@ -7921,7 +8504,39 @@ declare class EstimatePoolYieldTool extends BaseTool {
7921
8504
  private describeQuery;
7922
8505
  }
7923
8506
 
7924
- type PoolPriceRangesToolConfig = CoinPoolServiceConfig;
8507
+ /**
8508
+ * A pool operation's supported-chain tier. Pools cover fewer chains than the
8509
+ * 12-chain global catalog, and ADD-LIQUIDITY covers fewer still:
8510
+ * - `info` → the 8 Uniswap-Explore chains ({@link POOL_INFO_CHAIN_HEXES}).
8511
+ * - `add-liquidity` → only chains with a gateway contract configured (a smaller,
8512
+ * dynamic subset resolved from the addresses API at call time).
8513
+ *
8514
+ * Tools never reason about these sets directly — they hand a scope to
8515
+ * {@link gatePoolChain}, which resolves + validates the chain and, when it isn't
8516
+ * served, returns the right "not available on this chain, available on: …" result.
8517
+ */
8518
+ interface PoolChainScope {
8519
+ /** Selects the not-supported wording ({@link poolChainNotSupportedResult}). */
8520
+ readonly kind: 'info' | 'add-liquidity';
8521
+ /** Canonical hex ids this scope serves, intersected with the active set. */
8522
+ listSupported(): Promise<string[]>;
8523
+ /** True when this scope's data/flow is available for `chain`. */
8524
+ isSupported(chain: string): Promise<boolean>;
8525
+ }
8526
+
8527
+ interface PoolPriceRangesToolConfig extends CoinPoolServiceConfig {
8528
+ /**
8529
+ * Chain scope to gate on. Defaults to the Uniswap pool-INFO set; the
8530
+ * DefiLlama-backed pool agent passes its own (narrower) scope so the tool
8531
+ * advertises and gates the same chains as the rest of that agent's tools.
8532
+ * CoinPool itself is shared — only the SUPPORTED-CHAIN set differs.
8533
+ */
8534
+ scope?: PoolChainScope;
8535
+ /** Human-readable supported-chain list for the tool description. */
8536
+ supportsLabel?: string;
8537
+ /** `chain` parameter description matching {@link scope}. */
8538
+ chainParamDescription?: string;
8539
+ }
7925
8540
  /**
7926
8541
  * Tool: get-pool-price-ranges
7927
8542
  *
@@ -7940,6 +8555,7 @@ declare class PoolPriceRangesTool extends BaseTool {
7940
8555
  category: string;
7941
8556
  parameters: ToolParameter[];
7942
8557
  private service;
8558
+ private scope;
7943
8559
  constructor(config?: PoolPriceRangesToolConfig);
7944
8560
  protected run(args: Record<string, unknown>, userContext?: UserContext): Promise<Record<string, unknown>>;
7945
8561
  }
@@ -8550,43 +9166,655 @@ declare class SubgraphAddPoolTool extends BaseTool {
8550
9166
  }
8551
9167
 
8552
9168
  /**
8553
- * Native gas-reserve estimation for wallet-action tools.
9169
+ * DefiLlamaPoolService — pool data from the DefiLlama Yields API.
8554
9170
  *
8555
- * When the SPENT token is the chain's native coin, the user can't spend their
8556
- * full balance — some must be left to pay the transaction's gas. So "spendable"
8557
- * is `balance − gasReserve`, where `gasReserve = gasLimit × gasPrice`:
9171
+ * The data source behind the `pool-defillama` subagent, mirroring what
9172
+ * {@link UniswapService} (Uniswap Explore) does for the `pool-uniswap`
9173
+ * subagent: same questions, different upstream. A deployment enables exactly
9174
+ * one of them.
8558
9175
  *
8559
- * - send native: gasLimit 30_000 (a plain value transfer).
8560
- * - buy / swap: gasLimit 1_000_000 (a router call + possible approval).
9176
+ * Three properties of the upstream shape everything here:
8561
9177
  *
8562
- * The gas price is read live via `eth_gasPrice` against the chain's RPC (a
8563
- * caller-supplied override when configured, else the chain's default).
8564
- * This is best-effort and SILENT: the reserve is only ever used internally to
8565
- * size "spendable" — it is never surfaced to the user. When the price can't be
8566
- * read (RPC error, unknown chain) the reserve is `0n`, i.e. we fall back to the
8567
- * full balance rather than blocking the user.
9178
+ * 1. ONE endpoint, NO filters. `https://yields.llama.fi/pools` ignores every
9179
+ * query parameter and always returns the full ~12MB / 17k-pool snapshot, so
9180
+ * the service fetches once, caches, and does all filtering/sorting locally.
9181
+ * The in-flight promise is shared so a burst of tool calls triggers a single
9182
+ * download.
9183
+ * 2. NO pool addresses. A pool is identified by an opaque UUID plus
9184
+ * `underlyingTokens` + `poolMeta` (the fee tier). The address every on-chain
9185
+ * flow needs is recomputed with {@link deriveV3PoolAddress} — see
9186
+ * `uniswapV3PoolAddress.ts`. V2/V4 have no such derivation here, so only V3
9187
+ * pools carry an address.
9188
+ * 3. NO address index. Nothing maps an address back to a pool, so a pasted 0x
9189
+ * address is resolved by deriving candidate addresses for the pools we
9190
+ * already hold and matching (see {@link findByPoolAddress}); the caller falls
9191
+ * back to an on-chain read when that misses.
8568
9192
  */
8569
- /** Gas limits per native action kind (matches the FE's tx builders). */
8570
- declare const NATIVE_GAS_LIMIT: {
8571
- readonly send: 30000n;
8572
- /** buy and swap both go through a router call (+ possible approval). */
8573
- readonly swap: 1000000n;
8574
- };
8575
- type NativeActionKind = keyof typeof NATIVE_GAS_LIMIT;
8576
-
8577
- /** Resolved token identity used to pre-fill a wallet-action form. */
8578
- interface ResolvedToken {
8579
- address: string;
8580
- symbol?: string;
8581
- name?: string;
8582
- decimals?: number;
8583
- }
8584
- /**
8585
- * Shared base for wallet-action tools.
8586
- *
8587
- * Each concrete tool resolves identifiers + validates inputs, then returns the
8588
- * `WalletActionProps` payload below. The FE owns the form and the on-chain tx;
8589
- * the agent only forwards a structured intent.
9193
+ interface DefiLlamaPoolServiceConfig {
9194
+ /** Base URL of the DefiLlama Yields API. Defaults to `https://yields.llama.fi`. */
9195
+ baseUrl?: string;
9196
+ /** Snapshot cache TTL in ms. Defaults to 5 minutes (upstream refreshes hourly). */
9197
+ cacheTtlMs?: number;
9198
+ }
9199
+ /** Uniswap protocol versions DefiLlama exposes as separate `project` values. */
9200
+ type DefiLlamaProtocolVersion = 'V2' | 'V3' | 'V4';
9201
+ /** A pool, normalized to the shape the pool tools render. */
9202
+ interface DefiLlamaPool {
9203
+ /** DefiLlama's opaque pool UUID — stable, and the key for the history chart. */
9204
+ id: string;
9205
+ /** `"USDC/WETH"`. Derived from the upstream `symbol` (`"USDC-WETH"`). */
9206
+ pair: string;
9207
+ chain: string;
9208
+ protocolVersion: DefiLlamaProtocolVersion;
9209
+ /**
9210
+ * The pool's on-chain address, recomputed via CREATE2. Present only for V3
9211
+ * pools on a chain with a known factory AND a parseable fee tier; `undefined`
9212
+ * otherwise, which callers must treat as "cannot act on-chain".
9213
+ */
9214
+ address?: string;
9215
+ /** Fee tier in hundredths of a bip (500 = 0.05%), parsed from `poolMeta`. */
9216
+ feeTierBps?: number;
9217
+ /** Fee tier as a percentage (0.05 = 0.05%). */
9218
+ feeTierPercent?: number;
9219
+ tvlUsd: number;
9220
+ /** Fee APR as a PERCENT (5 = 5%) — same unit as the Uniswap/subgraph paths. */
9221
+ apr?: number;
9222
+ /** {@link apr} plus any reward/incentive APR upstream attributes to the pool. */
9223
+ totalApr?: number;
9224
+ volume1DayUsd?: number;
9225
+ volume7DayUsd?: number;
9226
+ /** 24h volume ÷ TVL — the capital-efficiency signal the shared rubric reads. */
9227
+ volumeToTvlRatio?: number;
9228
+ /** LP fee revenue over 24h, in USD: volume × fee tier. */
9229
+ fee24hUsd?: number;
9230
+ token0?: {
9231
+ symbol?: string;
9232
+ address?: string;
9233
+ };
9234
+ token1?: {
9235
+ symbol?: string;
9236
+ address?: string;
9237
+ };
9238
+ /** True when DefiLlama classifies the pool as a stablecoin pair. */
9239
+ isStablecoin?: boolean;
9240
+ /** Upstream impermanent-loss risk label ("no" / "yes"). */
9241
+ ilRisk?: string;
9242
+ /** APR change over 1d / 7d / 30d, in percentage points. */
9243
+ aprChange1D?: number;
9244
+ aprChange7D?: number;
9245
+ aprChange30D?: number;
9246
+ /** 30-day mean APR — a steadiness signal against the spot `apr`. */
9247
+ aprMean30d?: number;
9248
+ }
9249
+ interface DefiLlamaServiceResponse<T> {
9250
+ success: boolean;
9251
+ data?: T;
9252
+ error?: string;
9253
+ }
9254
+ type DefiLlamaSortBy = 'tvl' | 'volume1Day' | 'volume7Day' | 'apr';
9255
+ /** Hex chain ids this service serves, in the order tools should advertise them. */
9256
+ declare const DEFILLAMA_POOL_CHAIN_HEXES: string[];
9257
+ declare class DefiLlamaPoolService {
9258
+ private readonly baseUrl;
9259
+ private readonly cacheTtlMs;
9260
+ constructor(config?: DefiLlamaPoolServiceConfig);
9261
+ /** The cache entry for this instance's endpoint, created on first use. */
9262
+ private get store();
9263
+ isSupported(chain?: string | null): boolean;
9264
+ listSupportedChains(): string[];
9265
+ /**
9266
+ * The full normalized pool snapshot, cached for {@link cacheTtlMs}.
9267
+ *
9268
+ * On a refresh failure a STALE cache is returned rather than throwing: pool
9269
+ * data minutes out of date is far better than an error, and DefiLlama's own
9270
+ * numbers only refresh hourly.
9271
+ */
9272
+ private snapshot;
9273
+ /**
9274
+ * Force the next read to re-download. Exposed for tests/diagnostics.
9275
+ *
9276
+ * Clears the cache for THIS instance's endpoint, which every service on that
9277
+ * endpoint shares — that is the point of the shared cache, and what makes a
9278
+ * test's reset actually take effect on the tools under test.
9279
+ */
9280
+ clearCache(): void;
9281
+ /**
9282
+ * Parse `poolMeta` into a fee tier in hundredths of a bip.
9283
+ *
9284
+ * Upstream writes the tier as a percentage string ("0.05%", "0.3%"). Values
9285
+ * that do not correspond to a real Uniswap tier are rejected rather than
9286
+ * rounded: a wrong tier would derive a wrong pool address, and a wrong address
9287
+ * is far more damaging than a missing one.
9288
+ */
9289
+ private parseFeeTierBps;
9290
+ private normalize;
9291
+ private sortValue;
9292
+ private sorted;
9293
+ /**
9294
+ * The chain-wide leaderboard — the `get-top-pools` counterpart.
9295
+ *
9296
+ * `forAddLiquidity` keeps only pools that can actually be minted into: V3
9297
+ * pools whose address was derivable. Without it a user could pick a V2/V4 pool
9298
+ * from the list and hit a dead end at the add-liquidity step.
9299
+ */
9300
+ getTopPools(params: {
9301
+ chain: string;
9302
+ limit?: number;
9303
+ sortBy?: DefiLlamaSortBy;
9304
+ protocolVersion?: DefiLlamaProtocolVersion | 'ALL';
9305
+ forAddLiquidity?: boolean;
9306
+ }): Promise<DefiLlamaServiceResponse<DefiLlamaPool[]>>;
9307
+ /**
9308
+ * Free-text pool search — the `search-pools` counterpart.
9309
+ *
9310
+ * Matches on token SYMBOLS (and token addresses when the query looks like
9311
+ * one). Every named symbol must appear in the pair, so "ETH USDC" returns only
9312
+ * ETH/USDC pools rather than the union of both tokens' pools.
9313
+ */
9314
+ searchPools(params: {
9315
+ chain: string;
9316
+ query: string;
9317
+ limit?: number;
9318
+ sortBy?: DefiLlamaSortBy;
9319
+ protocolVersion?: DefiLlamaProtocolVersion | 'ALL';
9320
+ forAddLiquidity?: boolean;
9321
+ }): Promise<DefiLlamaServiceResponse<DefiLlamaPool[]>>;
9322
+ /**
9323
+ * Symbol comparison that tolerates the wrapped/native spelling difference:
9324
+ * a user asking for "ETH" means the WETH pools, and "BTC" means WBTC. Exact
9325
+ * match first so "ETH" never matches an unrelated token that merely contains
9326
+ * those letters.
9327
+ */
9328
+ private symbolMatches;
9329
+ /**
9330
+ * Resolve the pools for a token pair (and optional fee tier) — the
9331
+ * `get-pool-detail` counterpart. Returns EVERY matching pool, sorted, so the
9332
+ * caller can render fee-tier candidates when more than one comes back.
9333
+ */
9334
+ getPoolsByPair(params: {
9335
+ chain: string;
9336
+ token0Symbol: string;
9337
+ token1Symbol?: string;
9338
+ feeTierBps?: number;
9339
+ protocolVersion?: DefiLlamaProtocolVersion | 'ALL';
9340
+ }): Promise<DefiLlamaServiceResponse<DefiLlamaPool[]>>;
9341
+ /**
9342
+ * Reverse-resolve a pool ADDRESS to its DefiLlama entry.
9343
+ *
9344
+ * DefiLlama has no address index, so this matches against the addresses the
9345
+ * snapshot already derived. A hit therefore means "a V3 pool DefiLlama tracks
9346
+ * on this chain"; a miss means only that DefiLlama does not track it — the
9347
+ * pool may still exist, which is why callers fall back to an on-chain read
9348
+ * rather than reporting "not found".
9349
+ */
9350
+ findByPoolAddress(params: {
9351
+ chain: string;
9352
+ address: string;
9353
+ }): Promise<DefiLlamaServiceResponse<DefiLlamaPool | null>>;
9354
+ /**
9355
+ * Find the pools that contain a given TOKEN address — what a pasted address
9356
+ * resolves to when it turns out to be a token rather than a pool.
9357
+ */
9358
+ findPoolsByTokenAddress(params: {
9359
+ chain: string;
9360
+ address: string;
9361
+ limit?: number;
9362
+ }): Promise<DefiLlamaServiceResponse<DefiLlamaPool[]>>;
9363
+ }
9364
+
9365
+ type DefiLlamaTopPoolsToolConfig = DefiLlamaPoolServiceConfig;
9366
+ /**
9367
+ * Tool: get-top-pools (DefiLlama-backed)
9368
+ *
9369
+ * The chain-wide pool leaderboard — the DefiLlama counterpart of the Uniswap
9370
+ * stack's `uniswap-top-pools`. The `llama-` prefix names the data source, so a
9371
+ * log line or trace says unambiguously which stack answered.
9372
+ *
9373
+ * Note the sort keys differ slightly from the Uniswap stack: DefiLlama reports a
9374
+ * 7-day volume bucket where Uniswap reports a 30-day one, so `volume7Day`
9375
+ * replaces `volume30Day` rather than being faked from data we do not have.
9376
+ */
9377
+ declare class DefiLlamaTopPoolsTool extends BaseTool {
9378
+ name: string;
9379
+ description: string;
9380
+ category: string;
9381
+ parameters: ToolParameter[];
9382
+ private service;
9383
+ private pool;
9384
+ constructor(config?: DefiLlamaTopPoolsToolConfig);
9385
+ protected run(args: Record<string, unknown>, userContext?: UserContext): Promise<Record<string, unknown>>;
9386
+ }
9387
+
9388
+ type DefiLlamaPoolSearchToolConfig = DefiLlamaPoolServiceConfig;
9389
+ /**
9390
+ * Tool: search-pools (DefiLlama-backed)
9391
+ *
9392
+ * Finds pools related to a token the user named — the DefiLlama counterpart of
9393
+ * the Uniswap stack's `uniswap-search-pools`.
9394
+ *
9395
+ * The match is AND-across-terms (see `DefiLlamaPoolService.searchPools`), so a
9396
+ * two-symbol query returns that pair's pools rather than the union of each
9397
+ * token's pools, and "ETH" resolves to the WETH pools a user actually means.
9398
+ */
9399
+ declare class DefiLlamaPoolSearchTool extends BaseTool {
9400
+ name: string;
9401
+ description: string;
9402
+ category: string;
9403
+ parameters: ToolParameter[];
9404
+ private service;
9405
+ private pool;
9406
+ constructor(config?: DefiLlamaPoolSearchToolConfig);
9407
+ protected run(args: Record<string, unknown>, userContext?: UserContext): Promise<Record<string, unknown>>;
9408
+ }
9409
+
9410
+ type DefiLlamaPoolDetailToolConfig = DefiLlamaPoolServiceConfig;
9411
+ /**
9412
+ * Tool: get-pool-detail (DefiLlama-backed)
9413
+ *
9414
+ * Full stats for ONE pool identified BY TOKEN PAIR (never by address — that is
9415
+ * `lookup-pool-by-address`). Mirrors the Uniswap stack's two-outcome contract
9416
+ * exactly, because the subagent prompt is shared:
9417
+ *
9418
+ * - the filter resolves to one pool → `{ pool: … }`
9419
+ * - it resolves to several → `{ candidates: [ … ] }` and NO `pool`
9420
+ * key, so the model asks which fee tier rather than inventing one.
9421
+ */
9422
+ declare class DefiLlamaPoolDetailTool extends BaseTool {
9423
+ name: string;
9424
+ description: string;
9425
+ category: string;
9426
+ parameters: ToolParameter[];
9427
+ private service;
9428
+ private pool;
9429
+ constructor(config?: DefiLlamaPoolDetailToolConfig);
9430
+ protected run(args: Record<string, unknown>, userContext?: UserContext): Promise<Record<string, unknown>>;
9431
+ }
9432
+
9433
+ type DefiLlamaPoolByAddressToolConfig = DefiLlamaPoolServiceConfig;
9434
+ /**
9435
+ * Tool: lookup-pool-by-address (DefiLlama-backed)
9436
+ *
9437
+ * Resolves a bare 0x address the user pasted without saying what it is.
9438
+ *
9439
+ * This is the one capability DefiLlama cannot serve on its own: its Yields feed
9440
+ * has no address index at all — a pool is an opaque UUID — so an address can
9441
+ * never be looked up directly. The tool therefore resolves in three stages,
9442
+ * cheapest first, and only reports "not found" when all three miss:
9443
+ *
9444
+ * 1. POOL, from the snapshot. `DefiLlamaPoolService` recomputes each V3 pool's
9445
+ * CREATE2 address, so a pasted address can be matched against those. A hit
9446
+ * carries the full market stats (TVL / volume / APR).
9447
+ * 2. TOKEN, from the snapshot — the address is one of a tracked pool's tokens,
9448
+ * so we can list the pools containing it.
9449
+ * 3. POOL, ON-CHAIN. A miss above means only that DefiLlama does not TRACK the
9450
+ * pool, not that it does not exist (new pools, thin pools, and every pool on
9451
+ * a chain DefiLlama covers sparsely). Reading `slot0`/`token0`/`token1`
9452
+ * settles it definitively. Such a pool has no market stats — it is reported
9453
+ * as a real pool with its on-chain facts and an explicit note that TVL /
9454
+ * volume / APR are unavailable, never with invented numbers.
9455
+ *
9456
+ * The `resolvedAs` contract ("pool" | "token") matches the Uniswap stack's tool
9457
+ * exactly, so the shared subagent prompt drives either implementation.
9458
+ */
9459
+ declare class DefiLlamaPoolByAddressTool extends BaseTool {
9460
+ name: string;
9461
+ description: string;
9462
+ category: string;
9463
+ parameters: ToolParameter[];
9464
+ private service;
9465
+ private pool;
9466
+ constructor(config?: DefiLlamaPoolByAddressToolConfig);
9467
+ protected run(args: Record<string, unknown>, userContext?: UserContext): Promise<Record<string, unknown>>;
9468
+ /**
9469
+ * Read the address as a Uniswap V3 pool directly from the chain.
9470
+ *
9471
+ * Returns `null` when the address is not a V3 pool — `readPoolOnchain`
9472
+ * multicalls `slot0`/`tickSpacing`/`token0`/`token1`, all of which revert on a
9473
+ * non-pool contract, so a throw here IS the "not a pool" signal. Token symbols
9474
+ * are then filled in with one batched metadata read so the pair can be named.
9475
+ */
9476
+ private readPoolOnchain;
9477
+ }
9478
+
9479
+ type DefiLlamaEstimatePoolYieldToolConfig = DefiLlamaPoolServiceConfig;
9480
+ /**
9481
+ * Tool: estimate-pool-yield (DefiLlama-backed)
9482
+ *
9483
+ * Projects fee income for a USD deposit. Mirrors the Uniswap stack's tool
9484
+ * contract field-for-field — `candidates` / `depositMode` / `autoPickedReason` —
9485
+ * so the shared subagent prompt's YIELD ESTIMATION FLOW drives either one.
9486
+ *
9487
+ * The tool resolves missing inputs itself rather than bouncing questions back:
9488
+ * one token auto-picks that token's highest-volume pool, a missing deposit falls
9489
+ * back to a clearly-labelled $1000 example, and only a genuinely ambiguous fee
9490
+ * tier produces a candidates list.
9491
+ */
9492
+ declare class DefiLlamaEstimatePoolYieldTool extends BaseTool {
9493
+ name: string;
9494
+ description: string;
9495
+ category: string;
9496
+ parameters: ToolParameter[];
9497
+ private service;
9498
+ constructor(config?: DefiLlamaEstimatePoolYieldToolConfig);
9499
+ protected run(args: Record<string, unknown>, userContext?: UserContext): Promise<Record<string, unknown>>;
9500
+ /** One representative pool (the deepest) per fee tier, ordered by TVL. */
9501
+ private dedupeByFeeTier;
9502
+ }
9503
+
9504
+ /**
9505
+ * The DefiLlama implementation of {@link PoolCandidateResolver}.
9506
+ *
9507
+ * Lets the DefiLlama-backed pool agent reuse the SHARED add-liquidity flow
9508
+ * (`OpenAddLiquidityFormTool` / `PreviewAddLiquidityTool`) rather than forking
9509
+ * it: only the pool LOOKUP changes, and everything downstream — the on-chain
9510
+ * reads, balance and gas maths, tick alignment, the gateway call — is identical
9511
+ * because it operates on a pool address, not on an API response.
9512
+ *
9513
+ * The addresses come from `DefiLlamaPoolService`, which recomputes each V3
9514
+ * pool's CREATE2 address (DefiLlama itself never reports one). Pools whose
9515
+ * address could not be derived are dropped: the flow's very next step reads the
9516
+ * pool on-chain by address, so an entry without one could only fail there, with
9517
+ * a far less clear error than "no pool found".
9518
+ */
9519
+
9520
+ declare class DefiLlamaPoolCandidateResolver implements PoolCandidateResolver {
9521
+ private service;
9522
+ constructor(config?: DefiLlamaPoolServiceConfig);
9523
+ resolveCandidates(params: ResolvePoolCandidatesParams): Promise<PoolCandidate[] | null>;
9524
+ }
9525
+
9526
+ /**
9527
+ * Chain scope + shared parameter text for the DefiLlama-backed pool tools.
9528
+ *
9529
+ * The `pool` (Uniswap Explore) agent serves 8 chains; this stack serves 7 —
9530
+ * Linea is deliberately absent because DefiLlama tracks zero Uniswap pools
9531
+ * there, and a chain that always answers with an empty list is worse than one
9532
+ * that says plainly it is not supported. Everything here derives from
9533
+ * {@link DEFILLAMA_POOL_CHAIN_HEXES}, so the advertised set, the gate, and the
9534
+ * "not available on this chain" list can never drift apart.
9535
+ *
9536
+ * Only the SCOPE differs from the Uniswap stack — the gating machinery itself
9537
+ * ({@link gatePoolChain}, {@link poolChainNotSupportedResult}) is shared, so both
9538
+ * pool agents phrase an unsupported chain identically.
9539
+ */
9540
+
9541
+ /**
9542
+ * The pool-INFO scope for the DefiLlama stack — the 7 chains with real pool
9543
+ * data. Constant-backed (no network call), like `poolInfoScope()`.
9544
+ */
9545
+ declare function defiLlamaPoolInfoScope(): PoolChainScope;
9546
+ /**
9547
+ * Human-readable, comma-joined list of the DefiLlama pool chains — names ONLY,
9548
+ * never hex. Used in each tool's `description` "Supports:" line so the
9549
+ * advertised set always matches the gated one.
9550
+ */
9551
+ declare function defiLlamaPoolSupportsLabel(): string;
9552
+ /**
9553
+ * Canonical `chain` PARAMETER description for the DefiLlama pool tools.
9554
+ *
9555
+ * Spells out an EXHAUSTIVE name→hex map rather than an "e.g." list, for the same
9556
+ * reason the Uniswap stack does: given a partial list the model would sometimes
9557
+ * emit the wrong hex, or none, for a chain the list did not name. Linea is
9558
+ * absent on purpose — passing it is still safe (the gate answers "not available
9559
+ * on Linea, available on: …"), it is simply never advertised.
9560
+ */
9561
+ declare const DEFILLAMA_POOL_CHAIN_PARAM_DESCRIPTION: string;
9562
+
9563
+ /**
9564
+ * Shared rendering shape for the DefiLlama pool tools.
9565
+ *
9566
+ * Every tool in this folder returns pools through {@link formatDefiLlamaPool} so a
9567
+ * pool reads identically whether it arrived from a ranking, a search, a pair
9568
+ * lookup, or a pasted address — the same guarantee `poolDetailShape.ts` gives
9569
+ * the Uniswap stack. The field NAMES deliberately match the Uniswap stack's
9570
+ * (`tvlUsd`, `volume1DayUsd`, `apr`, `feeTierPercent`, `volumeToTvlRatio`) so
9571
+ * the shared analyst rubric in `poolAnalysis.ts` reads the same keys from both
9572
+ * sources and neither agent needs its own divergent prompt.
9573
+ */
9574
+
9575
+ /** A pool as the LLM sees it. Nulls are omitted rather than sent as `null`. */
9576
+ interface FormattedDefiLlamaPool {
9577
+ pair: string;
9578
+ address?: string;
9579
+ chain: string;
9580
+ protocolVersion: string;
9581
+ feeTierBps?: number;
9582
+ feeTierPercent?: number;
9583
+ tvlUsd: number;
9584
+ volume1DayUsd?: number;
9585
+ volume7DayUsd?: number;
9586
+ fee24hUsd?: number;
9587
+ apr?: number;
9588
+ totalApr?: number;
9589
+ volumeToTvlRatio?: number;
9590
+ aprChange1D?: number;
9591
+ aprChange7D?: number;
9592
+ aprMean30d?: number;
9593
+ isStablecoin?: boolean;
9594
+ ilRisk?: string;
9595
+ token0?: {
9596
+ symbol?: string;
9597
+ address?: string;
9598
+ };
9599
+ token1?: {
9600
+ symbol?: string;
9601
+ address?: string;
9602
+ };
9603
+ uniswapUrl?: string;
9604
+ /**
9605
+ * True when this pool cannot be added to through the in-app flow — a V2/V4
9606
+ * pool, or a V3 pool whose address could not be derived. Surfaced so the
9607
+ * analyst never promises an add-liquidity step that would dead-end.
9608
+ */
9609
+ addLiquidityUnavailable?: boolean;
9610
+ }
9611
+ /**
9612
+ * Shape one {@link DefiLlamaPool} for a tool response.
9613
+ *
9614
+ * The Uniswap explore URL is attached whenever the address was derivable, giving
9615
+ * the user the same clickable pool page the Uniswap-backed agent links to — the
9616
+ * pool is the same on-chain contract regardless of which API described it.
9617
+ */
9618
+ declare function formatDefiLlamaPool(p: DefiLlamaPool): FormattedDefiLlamaPool;
9619
+ /**
9620
+ * Extra grounding signals the DefiLlama feed carries that the Uniswap Explore
9621
+ * feed does not. Appended to the shared rubric so the analyst actually uses the
9622
+ * APR-trend and IL-risk fields instead of ignoring unfamiliar keys.
9623
+ */
9624
+ declare const DEFILLAMA_EXTRA_SIGNALS: string;
9625
+
9626
+ /**
9627
+ * The transaction-fee model for wallet-action tools — the exchange screen's
9628
+ * `feeGas`, ported so the agent sizes a spend exactly like the app does.
9629
+ *
9630
+ * The app computes one figure and uses it for three decisions
9631
+ * (`Exchange/index.js`):
9632
+ *
9633
+ * feeGas = gasPrice × gasLimit + protocolFee
9634
+ *
9635
+ * 1. "Max" on a NATIVE spend is `balance − feeGas`.
9636
+ * 2. A spend is rejected when `amountIn > balance − feeGas`.
9637
+ * 3. Any spend is rejected when the wallet's NATIVE balance is `≤ feeGas` —
9638
+ * including an ERC-20 spend, which still needs native to pay its own gas.
9639
+ *
9640
+ * Each term matches the app:
9641
+ *
9642
+ * - `gasPrice` is read live via `eth_gasPrice` against the chain's RPC (a
9643
+ * caller-supplied override when configured, else the chain's default).
9644
+ * - `gasLimit` prefers the QUOTE's own gas (`tx.gas`, or deBridge's
9645
+ * `estimatedTransactionFee.details.gasLimit`) and floors it at the default —
9646
+ * the app's `gasLimitRawTx` memo. Without a quote the default stands:
9647
+ * - send native: 30_000 (a plain value transfer)
9648
+ * - buy / swap: 1_000_000 (a router call + possible approval), the same
9649
+ * number as the app's `DEFAULT_GAS_LIMIT`.
9650
+ * - `protocolFee` is deBridge's fixed native order fee, non-zero only on a
9651
+ * CROSS-CHAIN deBridge route — see {@link readProtocolFeeWei}.
9652
+ *
9653
+ * Best-effort and SILENT throughout: when a term can't be read (RPC error,
9654
+ * unknown chain) it contributes `0n`, so the user degrades to a larger spendable
9655
+ * rather than being blocked by an outage. The one thing never guessed upward is
9656
+ * the reserve itself — an overstated reserve would falsely reject a legitimate
9657
+ * "100%".
9658
+ */
9659
+
9660
+ /** Gas limits per native action kind (matches the FE's tx builders). */
9661
+ declare const NATIVE_GAS_LIMIT: {
9662
+ readonly send: 30000n;
9663
+ /** buy and swap both go through a router call (+ possible approval). */
9664
+ readonly swap: 1000000n;
9665
+ };
9666
+ type NativeActionKind = keyof typeof NATIVE_GAS_LIMIT;
9667
+ /**
9668
+ * The gas limit to price the reserve at: the QUOTE's own gas when it reports
9669
+ * one, floored at the kind's default — the app's `gasLimitRawTx`.
9670
+ *
9671
+ * The floor is what makes this safe in both directions. A quote reporting MORE
9672
+ * than the default (a multi-hop route) raises the reserve, which the fixed
9673
+ * default used to understate; a quote reporting less — or none — cannot lower it
9674
+ * below the default and shrink the reserve on a route that may still need an
9675
+ * approval on top.
9676
+ */
9677
+ declare function resolveGasLimit(kind: NativeActionKind, quoteGas?: QuoteGas): bigint;
9678
+ /**
9679
+ * The gas figures a provider quote may carry. Structural rather than tied to
9680
+ * `SwapQuoteResult`, so a caller can pass the raw quote, its `raw` payload, or
9681
+ * a hand-built object without a cast.
9682
+ */
9683
+ interface QuoteGas {
9684
+ tx?: {
9685
+ gas?: string | number | bigint | null;
9686
+ } | null;
9687
+ estimatedTransactionFee?: {
9688
+ details?: {
9689
+ gasLimit?: string | number | bigint | null;
9690
+ } | null;
9691
+ } | null;
9692
+ }
9693
+ /** Everything the fee model needs beyond the chain and the action kind. */
9694
+ interface FeeContext {
9695
+ /** The quote being sized, when one has been taken — supplies the real gas limit. */
9696
+ quoteGas?: QuoteGas;
9697
+ /** Provider serving the swap; only deBridge charges a fixed protocol fee. */
9698
+ provider?: ProviderName;
9699
+ /** Destination chain. Defaults to the source chain (same-chain swap → no protocol fee). */
9700
+ dstChainId?: number | string | null;
9701
+ }
9702
+ /**
9703
+ * The full transaction fee (in wei) for an action of `kind` on `chainId` —
9704
+ * `gasPrice × gasLimit + protocolFee`, the app's `feeGas`.
9705
+ *
9706
+ * This is the ONE figure to reserve, to compare a spend against, and to check
9707
+ * the native balance against. Returns `0n` only when the gas price is unreadable
9708
+ * AND no protocol fee applies. Never throws.
9709
+ */
9710
+ declare function estimateTransactionFeeWei(chainId: string, kind: NativeActionKind, context?: FeeContext): Promise<bigint>;
9711
+ /**
9712
+ * Estimate the native gas reserve (in wei) to set aside for a transaction of
9713
+ * the given kind on `chainId`. Returns `0n` when the gas price can't be read
9714
+ * from any endpoint — the caller then treats the full balance as spendable.
9715
+ * Never throws.
9716
+ *
9717
+ * Thin alias for {@link estimateTransactionFeeWei}, kept because "the reserve
9718
+ * withheld from a native balance" and "the fee the transaction costs" are the
9719
+ * same number and must never drift apart.
9720
+ */
9721
+ declare function estimateNativeGasReserveWei(chainId: string, kind: NativeActionKind, context?: FeeContext): Promise<bigint>;
9722
+ /**
9723
+ * Given a native balance (human token units) and a gas reserve (wei), return the
9724
+ * spendable balance in the SAME human units: `balance − gasReserve`, floored at
9725
+ * 0. Uses the chain's native decimals to convert the wei reserve. When decimals
9726
+ * are unknown the reserve is ignored (returns the full balance).
9727
+ */
9728
+ declare function spendableNative(balanceNum: number, gasReserveWei: bigint, chainId: string): number;
9729
+ /**
9730
+ * Convert a wei fee to the chain's native units, or `null` when the chain's
9731
+ * decimals are unknown (the caller then has no figure to compare and skips the
9732
+ * check rather than inventing one).
9733
+ */
9734
+ declare function feeWeiToNative(feeWei: bigint, chainId: string): number | null;
9735
+ /**
9736
+ * How much MORE native coin the wallet needs before the transaction can pay its
9737
+ * own fee, or `null` when it already has enough.
9738
+ *
9739
+ * This is the app's `minBalanceAddToSwap` — `feeGas − balanceNative`, floored at
9740
+ * 0 — and it exists for the case a native-only reserve cannot express: spending
9741
+ * an ERC-20 still burns NATIVE gas, so a wallet holding plenty of USDC and no ETH
9742
+ * passes every balance check on the token being spent and then fails on chain.
9743
+ * The exchange screen blocks that case up front ("You need {amount} {item} to
9744
+ * swap"); before this, the agent opened the form and let the user find out at
9745
+ * signing time.
9746
+ *
9747
+ * Mirrors the app's `>=` comparison, so a balance exactly equal to the fee counts
9748
+ * as insufficient: spending it all would leave nothing for the next block's price
9749
+ * movement. Returns `null` when the fee is 0 or unresolvable, which keeps an RPC
9750
+ * outage from blocking a user who may well have enough.
9751
+ */
9752
+ declare function nativeGasShortfall(input: {
9753
+ /** The wallet's NATIVE balance, in native units. */
9754
+ nativeBalance: number;
9755
+ /** The fee the transaction will cost, from {@link estimateTransactionFeeWei}. */
9756
+ feeWei: bigint;
9757
+ chainId: string;
9758
+ }): number | null;
9759
+ /** What a failed affordability check reports, all in native units. */
9760
+ interface NativeGasGap {
9761
+ /** How much more native coin the wallet needs. */
9762
+ shortfall: number;
9763
+ /** Native coin symbol, for the message ("you need 0.0012 ETH"). */
9764
+ nativeSymbol: string;
9765
+ /** The fee the transaction is expected to cost. */
9766
+ fee: number;
9767
+ }
9768
+ /**
9769
+ * Whether the wallet can pay this action's transaction fee at all, and if not,
9770
+ * how much native coin it is short.
9771
+ *
9772
+ * The gas reserve alone does not cover this. It is subtracted from a NATIVE
9773
+ * spend, so it protects "swap all my ETH" — but an ERC-20 spend burns native gas
9774
+ * the reserve never touches, and a wallet holding USDC with an empty ETH balance
9775
+ * passes every check on the token being spent and only fails at signing. The
9776
+ * exchange screen checks the native balance against `feeGas` on BOTH paths and
9777
+ * blocks with "You need {amount} {item} to swap"; this is that check.
9778
+ *
9779
+ * Returns `null` — "let it through" — whenever the answer isn't clearly no: the
9780
+ * wallet has enough, or the fee/balance can't be read. An RPC outage must never
9781
+ * block a user who can perfectly well pay.
9782
+ *
9783
+ * `readNativeBalance` is injected rather than imported so this stays independent
9784
+ * of any one tool's balance source; a wallet with no native entry reads as 0,
9785
+ * which IS the shortfall this exists to catch.
9786
+ */
9787
+ declare function checkNativeGasAffordable(input: {
9788
+ chainId: string | undefined;
9789
+ gasKind: NativeActionKind;
9790
+ /** Resolves the wallet's native balance + symbol, or undefined when unreadable. */
9791
+ readNativeBalance: () => Promise<{
9792
+ balance?: number;
9793
+ symbol?: string;
9794
+ } | undefined>;
9795
+ /** Quote/provider context, so the fee matches the one the tx will actually pay. */
9796
+ feeContext?: FeeContext;
9797
+ }): Promise<NativeGasGap | null>;
9798
+
9799
+ /** Resolved token identity used to pre-fill a wallet-action form. */
9800
+ interface ResolvedToken {
9801
+ address: string;
9802
+ symbol?: string;
9803
+ name?: string;
9804
+ decimals?: number;
9805
+ /**
9806
+ * True when `symbol` is the token's own `symbol()`, promoted from Pantograph's
9807
+ * `symbolOnchain`. It marks the symbol as safe to display as-is, in preference
9808
+ * to whatever the user or the model called the token.
9809
+ */
9810
+ symbolIsOnchain?: boolean;
9811
+ }
9812
+ /**
9813
+ * Shared base for wallet-action tools.
9814
+ *
9815
+ * Each concrete tool resolves identifiers + validates inputs, then returns the
9816
+ * `WalletActionProps` payload below. The FE owns the form and the on-chain tx;
9817
+ * the agent only forwards a structured intent.
8590
9818
  *
8591
9819
  * Subclasses implement `buildAction()` returning the fully-shaped payload (or
8592
9820
  * an `{ error, _instructions }` object that aborts before emitting UI).
@@ -8944,9 +10172,19 @@ declare class ApproveTokenTool extends BaseWalletActionTool {
8944
10172
  * Tool: open-buy-token-form
8945
10173
  *
8946
10174
  * A STANDALONE wallet-action tool (NOT a `BaseWalletActionTool`): instead of
8947
- * emitting the shared form payload, it does the quote + approval work itself and
8948
- * ships a custom `BuyTokenConfirmTx` UI payload the FE executes directly. That's
8949
- * why `buy_token` is intentionally NOT a member of `WalletActionType`.
10175
+ * emitting the shared form payload, it resolves the two tokens and ships a custom
10176
+ * `SwapTokenForm` payload the FE sizes, quotes and executes itself. That's why
10177
+ * `buy_token` is intentionally NOT a member of `WalletActionType`.
10178
+ *
10179
+ * The tool deliberately does NOT quote. It once did — building a priced confirm
10180
+ * card whenever the user named an amount — but a quote built here goes stale
10181
+ * while the message sits in the chat, and the amount it was built for could not
10182
+ * be changed without another agent turn. The form quotes on the FE for the amount
10183
+ * currently on screen, so what executes is always what was just priced.
10184
+ *
10185
+ * It emits the SAME `SwapTokenForm` payload as {@link SwapTokenTool}: a buy and a
10186
+ * swap are one transaction under two framings, so they are one form. Only
10187
+ * `intent` differs, and it decides wording and which x402 route is charged.
8950
10188
  *
8951
10189
  * Branches, picked deterministically from the args:
8952
10190
  *
@@ -8967,19 +10205,16 @@ declare class ApproveTokenTool extends BaseWalletActionTool {
8967
10205
  * 25/50/75/100% buttons sized off the real balance. Skipped for the native
8968
10206
  * pay token and when balances can't be read.
8969
10207
  *
8970
- * 1.5 **Amount picker** — dest + pay token are known but no amount was given.
8971
- * The tool reads the pay-token balance and emits 25/50/75/100% buttons so
8972
- * the user sizes the spend in one tap (or types a custom amount).
8973
- *
8974
- * 1.75 **Confirm tx** — dest + pay token + a PAY-TOKEN amount are all known.
8975
- * The tool fetches a swap quote (estimated receive amount + the raw swap
8976
- * tx), checks allowance, and emits a `BuyTokenConfirmTx` payload bundling
8977
- * the estimate, the raw swap transaction, and the approve transaction (when
8978
- * one is needed). The FE executes approve (if any) then swap itself.
10208
+ * 1.5 **Amount form** — dest + pay token are known. The tool reads the pay-token
10209
+ * balance (for the percentage shortcuts) and emits ONE `SwapTokenForm`
10210
+ * payload, whether or not the user named an amount: named, it arrives as
10211
+ * `initialAmount` and the form opens pre-filled; unnamed, the form opens
10212
+ * empty. Either way the amount stays editable and the FE quotes it. This is
10213
+ * the tool's only UI outcome.
8979
10214
  *
8980
10215
  * When none of the above produces a result (couldn't resolve the dest token,
8981
- * quote failed, amount given only on the buy side, …) the tool returns an
8982
- * error/_instructions object — it never opens a generic form.
10216
+ * amount given only on the buy side, …) the tool returns an error/_instructions
10217
+ * object — it never opens a generic form.
8983
10218
  *
8984
10219
  * Amount disambiguation mirrors the chatbot SDK:
8985
10220
  * - "buy PEPE with 10 USDC" → pay_with_amount = "10"
@@ -9087,13 +10322,6 @@ declare class BuyTokenTool extends BaseTool {
9087
10322
  * just comes back with `address: null`.
9088
10323
  */
9089
10324
  private resolveSide;
9090
- /**
9091
- * Pay token + dest token + a pay-token amount are known. Fetch a swap quote
9092
- * (estimated receive amount + raw swap tx), check approval, and return a
9093
- * `BuyTokenConfirmTx` UI payload the FE executes itself. Returns `null` when
9094
- * anything we need can't be produced (bad chain, quote failed, non-EVM tx).
9095
- */
9096
- private buildConfirmTx;
9097
10325
  /**
9098
10326
  * deBridge only quotes EXACT_INPUT, so a "buy X of the dest token" request has
9099
10327
  * no input amount to seed the quote. Convert the desired output into a pay-token
@@ -9133,29 +10361,6 @@ declare class BuyTokenTool extends BaseTool {
9133
10361
  * string or `null`.
9134
10362
  */
9135
10363
  private resolveBuyAmountSpec;
9136
- /**
9137
- * Check whether the pay token needs an allowance for this swap and, if so,
9138
- * return a ready-to-sign ERC-20 approve tx. Relay bundles the approve step in
9139
- * the quote (`approvalData` is the tx); deBridge only reports the spender
9140
- * (`tx.to`), so we encode the approve calldata ourselves.
9141
- */
9142
- private buildApproveTx;
9143
- /** Human amount → smallest-unit decimal string (no float drift via BigInt). */
9144
- private toRawAmount;
9145
- /**
9146
- * Pull a human-readable failure reason out of a failed quote. Adapters set
9147
- * `errorMessage` (string) and `error` (string or a provider object). deBridge
9148
- * also nests a reason in `raw.errorMessage` / `raw.error`. Falls back to a
9149
- * generic line so the caller always has something to show.
9150
- */
9151
- private extractQuoteError;
9152
- /**
9153
- * Estimated receive amount in the dest token's smallest units. Shape differs
9154
- * per provider — deBridge same-chain: `raw.tokenOut.minAmount`; deBridge
9155
- * cross-chain: `raw.estimation.dstChainTokenOut.amount`; Relay:
9156
- * `raw.details.currencyOut.{amount|minimumAmount}`.
9157
- */
9158
- private extractOutRaw;
9159
10364
  private buildPayWithPicker;
9160
10365
  /**
9161
10366
  * Guard the buy flow against a pay token the user can't fund. Returns:
@@ -9166,19 +10371,27 @@ declare class BuyTokenTool extends BaseTool {
9166
10371
  */
9167
10372
  private checkPayBalance;
9168
10373
  /**
9169
- * Read the connected wallet's balance of the pay token. Returns the held
9170
- * amount + on-chain symbol, or `null` when balances can't be fetched / the
9171
- * token isn't held (zero balance or not held at all).
9172
- *
9173
- * For the NATIVE pay coin the returned balance is the SPENDABLE figure — the
9174
- * held balance minus a silently-estimated swap gas reserve (gasLimit
9175
- * 1_000_000 × gasPrice) — so the percent buttons, amount picker, and balance
9176
- * check stay within what the user can actually spend while still covering gas.
9177
- * The reserve is never surfaced; callers only ever expose the spendable
9178
- * number. ERC-20 pay tokens are returned at their raw held balance (gas is
9179
- * paid in the native coin, not the pay token).
10374
+ * The connected wallet's SPENDABLE balance of the PAY token — the shared
10375
+ * {@link readSpendableBalance}, which is also what the in-chat form calls when
10376
+ * the user refreshes. A native pay coin comes back net of the swap gas reserve
10377
+ * so a sized buy always leaves gas to execute it; an ERC-20 comes back at its
10378
+ * held balance. `null` when the balance can't be read or the token isn't held.
9180
10379
  */
9181
10380
  private readPayBalance;
10381
+ /**
10382
+ * The wallet's RAW held native balance — no gas reserve deducted.
10383
+ *
10384
+ * Distinct from {@link readPayBalance} on purpose. That one answers "how much of
10385
+ * this can be spent", which for the native coin is already `held − fee`. The
10386
+ * fee affordability check needs the other question — "does the wallet hold
10387
+ * enough to pay the fee at all" — and must compare against the raw balance, or
10388
+ * it subtracts the fee twice and rejects wallets that can pay. The exchange
10389
+ * screen reads a raw `balanceNative` for the same comparison.
10390
+ *
10391
+ * Returns `{ balance: 0 }` when the native coin can't be read or isn't held:
10392
+ * both mean the fee cannot be paid, which is the finding, not a reason to skip.
10393
+ */
10394
+ private readNativeHeldBalance;
9182
10395
  /**
9183
10396
  * 25/50/75/100% quick-spend buttons sized off a held balance. Every amount is
9184
10397
  * an EXACT fraction of the exact balance STRING, floored — so a clicked button
@@ -9187,7 +10400,25 @@ declare class BuyTokenTool extends BaseTool {
9187
10400
  * percent.
9188
10401
  */
9189
10402
  private percentSpendButtons;
9190
- private buildAmountPicker;
10403
+ /**
10404
+ * Both sides are resolved but no amount was given. Ship the INTERACTIVE amount
10405
+ * form: the user sizes the spend on a slider, the FE quotes it live, and one
10406
+ * tap executes it — no further agent turn.
10407
+ *
10408
+ * This used to emit four percent BUTTONS, each of which re-submitted a prompt
10409
+ * and re-ran this whole tool just to change one number. The form collapses that
10410
+ * to a single payload, so changing your mind costs nothing.
10411
+ *
10412
+ * The spendable balance rides down as `rawAmount` (smallest units) so the FE
10413
+ * can take exact BigInt fractions of it; for a native pay token it is already
10414
+ * net of the gas reserve (see {@link readPayBalance}). Returns `null` when the
10415
+ * balance can't be read — the caller then falls through to asking for an
10416
+ * amount in words, exactly as before.
10417
+ *
10418
+ * The mirror of SwapTokenTool's own `buildAmountForm`: same payload shape, same
10419
+ * FE component, distinguished only by `intent`.
10420
+ */
10421
+ private buildAmountForm;
9191
10422
  /**
9192
10423
  * Trim IEEE-754 noise from a computed amount (≤8 significant digits) and
9193
10424
  * ALWAYS return plain decimal notation — never exponential ("1.5e-7"). Use
@@ -9237,10 +10468,16 @@ declare class BuyTokenTool extends BaseTool {
9237
10468
  * Tool: open-swap-token-form
9238
10469
  *
9239
10470
  * A STANDALONE wallet-action tool (NOT a `BaseWalletActionTool`), built as the
9240
- * mirror of {@link BuyTokenTool}: it does the quote + approval work itself and
9241
- * ships a custom `SwapTokenConfirmTx` UI payload the FE executes directly. That's
10471
+ * mirror of {@link BuyTokenTool}: it resolves the two tokens and ships a custom
10472
+ * `SwapTokenAmountForm` payload the FE sizes, quotes and executes itself. That's
9242
10473
  * why `swap_token` is intentionally NOT a member of `WalletActionType`.
9243
10474
  *
10475
+ * The tool deliberately does NOT quote. It once did — building a priced confirm
10476
+ * card whenever the user named an amount — but a quote built here goes stale
10477
+ * while the message sits in the chat, and any amount it was built for could not
10478
+ * then be changed without another agent turn. The form quotes on the FE for the
10479
+ * amount currently on screen, so what executes is always what was just priced.
10480
+ *
9244
10481
  * The defining difference from BUY: the SOURCE is a token the user ALREADY HOLDS.
9245
10482
  * Buy starts from a destination ("buy PEPE") and asks which wallet token to pay
9246
10483
  * with; swap starts from the user's own token ("swap USDC") and asks what to
@@ -9258,7 +10495,10 @@ declare class BuyTokenTool extends BaseTool {
9258
10495
  * 0. **Source picker** — the user named NO source (`from_symbol`/`from_address`
9259
10496
  * empty). The tool fetches the wallet's native + ERC-20 holdings and emits
9260
10497
  * `actionButtons` so the user picks which token to swap FROM. A click
9261
- * re-submits a prompt like `"swap USDC"` which routes back here.
10498
+ * re-submits a prompt like `"swap USDC"` which routes back here. When a
10499
+ * destination WAS named ("swap to PEPE"), it rides along in every click-
10500
+ * prompt — `"swap USDC to PEPE"` — so choosing a source doesn't discard the
10501
+ * half of the request the user already made.
9262
10502
  *
9263
10503
  * 1. **Destination picker (trending)** — the user named the source only. The
9264
10504
  * tool fetches the chain's live trending list (minus the source token) and
@@ -9272,19 +10512,15 @@ declare class BuyTokenTool extends BaseTool {
9272
10512
  * amount, it reports the shortfall and emits 25/50/75/100% buttons sized off
9273
10513
  * the real balance. Skipped for the native source token.
9274
10514
  *
9275
- * 1.5 **Amount picker** — source + dest known but no amount given. The tool
9276
- * reads the source balance and emits 25/50/75/100% buttons so the user sizes
9277
- * the swap in one tap (or types a custom amount).
10515
+ * 1.5 **Amount form** — source + dest known. The tool reads the source balance
10516
+ * (for the percentage shortcuts) and emits ONE `SwapTokenAmountForm` payload,
10517
+ * whether or not the user named an amount: named, it arrives as
10518
+ * `initialAmount` and the form opens pre-filled; unnamed, the form opens
10519
+ * empty. Either way the amount stays editable and the FE quotes it. This is
10520
+ * the tool's only UI outcome.
9278
10521
  *
9279
- * 1.75 **Confirm tx** — source + dest + a SOURCE amount are all known. The tool
9280
- * fetches a swap quote (estimated receive amount + the raw swap tx), checks
9281
- * allowance, and emits a `SwapTokenConfirmTx` payload bundling the estimate,
9282
- * the raw swap transaction, and the approve transaction (when one is needed).
9283
- * The FE executes approve (if any) then swap itself.
9284
- *
9285
- * When none of the above produces a result (couldn't resolve a token, quote
9286
- * failed, …) the tool returns an error/_instructions object — it never opens a
9287
- * generic form.
10522
+ * When none of the above produces a result (couldn't resolve a token, …) the
10523
+ * tool returns an error/_instructions object — it never opens a generic form.
9288
10524
  *
9289
10525
  * Amount disambiguation mirrors BuyTokenTool. The swap is EXACT_INPUT (deBridge),
9290
10526
  * so the amount that seeds the quote is the SOURCE amount:
@@ -9341,13 +10577,6 @@ declare class SwapTokenTool extends BaseTool {
9341
10577
  * just comes back with `address: null`.
9342
10578
  */
9343
10579
  private resolveSide;
9344
- /**
9345
- * Source token + dest token + a source-token amount are known. Fetch a swap
9346
- * quote (estimated receive amount + raw swap tx), check approval, and return a
9347
- * `SwapTokenConfirmTx` UI payload the FE executes itself. Returns `null` when
9348
- * anything we need can't be produced (bad chain, quote failed, non-EVM tx).
9349
- */
9350
- private buildConfirmTx;
9351
10580
  /**
9352
10581
  * deBridge only quotes EXACT_INPUT, so a "swap to X of the dest token" request
9353
10582
  * has no input amount to seed the quote. Convert the desired output into a
@@ -9384,29 +10613,6 @@ declare class SwapTokenTool extends BaseTool {
9384
10613
  * null). Returns a plain token amount string or `null`.
9385
10614
  */
9386
10615
  private resolveToAmountSpec;
9387
- /**
9388
- * Check whether the source token needs an allowance for this swap and, if so,
9389
- * return a ready-to-sign ERC-20 approve tx. deBridge only reports the spender
9390
- * (`tx.to`), so we encode the approve calldata ourselves; integrated providers
9391
- * (Relay) hand back the approve tx directly.
9392
- */
9393
- private buildApproveTx;
9394
- /** Human amount → smallest-unit decimal string (no float drift via BigInt). */
9395
- private toRawAmount;
9396
- /**
9397
- * Pull a human-readable failure reason out of a failed quote. Adapters set
9398
- * `errorMessage` (string) and `error` (string or a provider object). deBridge
9399
- * also nests a reason in `raw.errorMessage` / `raw.error`. Falls back to a
9400
- * generic line so the caller always has something to show.
9401
- */
9402
- private extractQuoteError;
9403
- /**
9404
- * Estimated receive amount in the dest token's smallest units. Shape differs
9405
- * per provider — deBridge same-chain: `raw.tokenOut.minAmount`; deBridge
9406
- * cross-chain: `raw.estimation.dstChainTokenOut.amount`; Relay:
9407
- * `raw.details.currencyOut.{amount|minimumAmount}`.
9408
- */
9409
- private extractOutRaw;
9410
10616
  private buildSourcePicker;
9411
10617
  private buildToTrendingPicker;
9412
10618
  /**
@@ -9418,19 +10624,28 @@ declare class SwapTokenTool extends BaseTool {
9418
10624
  */
9419
10625
  private checkFromBalance;
9420
10626
  /**
9421
- * Read the connected wallet's balance of the source token. Returns the held
9422
- * amount + on-chain symbol, or `null` when balances can't be fetched / the
9423
- * token isn't held (zero balance or not held at all).
9424
- *
9425
- * For the NATIVE source coin the returned balance is the SPENDABLE figure —
9426
- * the held balance minus a silently-estimated swap gas reserve (gasLimit
9427
- * 1_000_000 × gasPrice) — so the percent buttons, amount picker, and balance
9428
- * check all stay within what the user can actually swap while still covering
9429
- * gas. The reserve is never surfaced; callers only ever expose the spendable
9430
- * number. ERC-20 sources are returned at their raw held balance (gas is paid
9431
- * in the native coin, not the source token).
10627
+ * The connected wallet's SPENDABLE balance of the source token — the shared
10628
+ * {@link readSpendableBalance}, which is also what the in-chat form calls when
10629
+ * the user refreshes. Native sources come back net of the swap gas reserve, so
10630
+ * the percent buttons and the balance check stay within what can actually be
10631
+ * swapped; ERC-20 sources come back at their held balance. `null` when the
10632
+ * balance can't be read or the token isn't held.
9432
10633
  */
9433
10634
  private readFromBalance;
10635
+ /**
10636
+ * The wallet's RAW held native balance — no gas reserve deducted.
10637
+ *
10638
+ * Distinct from {@link readFromBalance} on purpose. That one answers "how much of
10639
+ * this can be spent", which for the native coin is already `held − fee`. The
10640
+ * fee affordability check needs the other question — "does the wallet hold
10641
+ * enough to pay the fee at all" — and must compare against the raw balance, or
10642
+ * it subtracts the fee twice and rejects wallets that can pay. The exchange
10643
+ * screen reads a raw `balanceNative` for the same comparison.
10644
+ *
10645
+ * Returns `{ balance: 0 }` when the native coin can't be read or isn't held:
10646
+ * both mean the fee cannot be paid, which is the finding, not a reason to skip.
10647
+ */
10648
+ private readNativeHeldBalance;
9434
10649
  /**
9435
10650
  * 25/50/75/100% quick-spend buttons sized off a held balance. Every amount is
9436
10651
  * an EXACT fraction of the exact balance STRING, floored — so a clicked button
@@ -9439,7 +10654,27 @@ declare class SwapTokenTool extends BaseTool {
9439
10654
  * percent.
9440
10655
  */
9441
10656
  private percentSpendButtons;
9442
- private buildAmountPicker;
10657
+ /**
10658
+ * Both sides are resolved: ship the interactive form. The user sizes the spend
10659
+ * (pre-filled when they already named an amount), the FE quotes it live, and
10660
+ * one tap executes it — no further agent turn, and no quote that can go stale
10661
+ * sitting on screen.
10662
+ *
10663
+ * This is the tool's ONLY UI outcome. It used to emit four percent BUTTONS
10664
+ * when no amount was given and a separately-quoted confirm card when one was;
10665
+ * both are now this single form, which is why the tool no longer quotes at all.
10666
+ *
10667
+ * The spendable balance rides down as `rawAmount` (smallest units) so the FE
10668
+ * can take exact BigInt fractions of it; for a native source it is already net
10669
+ * of the gas reserve (see {@link readFromBalance}).
10670
+ *
10671
+ * A balance that can't be read is NOT fatal — the FE quotes for itself, so it
10672
+ * only needs the two tokens. The form simply opens without percentage
10673
+ * shortcuts and without a "spendable" line, rather than the user losing the
10674
+ * form entirely over a balance lookup. Returns `null` only when something the
10675
+ * form genuinely cannot work without is missing (chain, symbol, decimals).
10676
+ */
10677
+ private buildAmountForm;
9443
10678
  /**
9444
10679
  * Trim IEEE-754 noise from a computed amount (≤8 significant digits) and
9445
10680
  * ALWAYS return plain decimal notation — never exponential ("1.5e-7").
@@ -9581,6 +10816,152 @@ declare class SendNftTool extends BaseWalletActionTool {
9581
10816
  private paramsFromNft;
9582
10817
  }
9583
10818
 
10819
+ /**
10820
+ * Exact decimal-string math for wallet balances, quantised to a token's own
10821
+ * decimals.
10822
+ *
10823
+ * Amounts compared against — or derived from — a wallet balance MUST stay exact
10824
+ * AND must never carry more fractional digits than the token supports (USDT on
10825
+ * Optimism is 6 dp; ETH is 18). Float math / significant-figure rounding can
10826
+ * round UP (false "insufficient balance"), and a fraction like 25% of a 6-dp
10827
+ * balance can spill to 8 dp — an amount the token can't represent, which
10828
+ * `toRawAmount` then silently truncates (possibly to 0).
10829
+ *
10830
+ * Everything here works on decimal STRINGS / BigInt (arbitrary precision, so
10831
+ * very large and very small balances are exact), tolerates scientific notation
10832
+ * on input, and FLOORS — a fraction of a balance can never exceed it.
10833
+ *
10834
+ * Use these for any balance-sourced amount. Plain float rounding (`trimAmount`)
10835
+ * stays fine for price-derived ESTIMATES (usd→token, buy/swap→pay).
10836
+ */
10837
+ /** Expand any exponential notation ("1.5e-7") in a JS number to plain decimal. */
10838
+ declare function toPlainDecimal(n: number): string;
10839
+ /**
10840
+ * Normalise a numeric string to a plain decimal — expands scientific notation
10841
+ * ("1.5e-7" → "0.00000015", "1.2e21" → "1200000000000000000000") with arbitrary
10842
+ * precision (pure string math, never via the lossy `Number`). Returns null when
10843
+ * the string isn't a number.
10844
+ */
10845
+ declare function normalizeDecimal(input: string): string | null;
10846
+ /** Render a non-negative integer scaled by 10^decimals back to a decimal string. */
10847
+ declare function weiToHuman(wei: bigint, decimals: number): string;
10848
+ /**
10849
+ * Convert a human decimal string to the token's smallest unit (wei), truncating
10850
+ * any fractional digits beyond `decimals`. Tolerates scientific notation.
10851
+ * Returns null when not a positive number.
10852
+ */
10853
+ declare function humanToWei(value: string, decimals: number): bigint | null;
10854
+ /**
10855
+ * Exact numeric string from a raw amount input, with NO rounding — so a
10856
+ * high-decimal amount a user typed/clicked is preserved verbatim. Strips a
10857
+ * trailing token symbol ("0.0000011 WBTC" → "0.0000011"), tolerates scientific
10858
+ * notation, normalises a leading ".". Returns null when no positive number.
10859
+ */
10860
+ declare function exactAmountString(raw: unknown): string | null;
10861
+ /**
10862
+ * Floor a decimal string to at most `decimals` fractional digits — drops digits
10863
+ * the token can't represent (USDT-OP keeps 6). Exact, never rounds up.
10864
+ */
10865
+ declare function floorToDecimals(value: string, decimals: number): string;
10866
+ /**
10867
+ * Exact `value × num / den`, FLOORED and quantised to `decimals` fractional
10868
+ * digits — never rounds up, so a fraction of a balance ("50% / 25% / all") can
10869
+ * never exceed the real balance nor carry more precision than the token has.
10870
+ */
10871
+ declare function mulDivFloor(value: string, num: bigint, den: bigint, decimals: number): string;
10872
+ /** Exact decimal-string comparison (no float, e-notation aware). -1 / 0 / 1. */
10873
+ declare function compareDecimal(a: string, b: string): number;
10874
+
10875
+ /**
10876
+ * The SPENDABLE balance of a wallet-action's source token — one implementation.
10877
+ *
10878
+ * "Spendable" is not "held". For an ERC-20 the two are the same, but for the
10879
+ * chain's NATIVE coin some of the balance has to be left behind to pay the
10880
+ * transaction's own gas, so spendable is `balance − gasReserve` (see
10881
+ * {@link estimateNativeGasReserveWei}). Sizing a swap off the raw native balance
10882
+ * produces a "Max" the user cannot actually execute: the router call reverts for
10883
+ * want of gas.
10884
+ *
10885
+ * This lived twice — `SwapTokenTool.readFromBalance` and
10886
+ * `BuyTokenTool.readPayBalance` were the same function under two variable names
10887
+ * — and now lives once, for the same reason `decimalAmount` is shared: the tool
10888
+ * that SEEDS a form and the form that later RE-READS the balance must agree to
10889
+ * the last digit, and two copies of a gas reserve are two chances to drift.
10890
+ *
10891
+ * Exported from the package because the in-chat swap/buy form re-reads the
10892
+ * balance itself when the user taps Refresh. The alternative — the form doing
10893
+ * its own `getBalance` — is precisely the copy this module exists to prevent: it
10894
+ * would read the RAW native balance and quietly lose the gas reserve.
10895
+ */
10896
+
10897
+ /**
10898
+ * A token's logo, whichever name the source used for it.
10899
+ *
10900
+ * The wallet-balance API says `logo`, while the Pantograph token search spreads
10901
+ * the same URL across `logo` / `icon_image` / `logoURI` / `thumbnail` depending
10902
+ * on the list a token came from — so reading only one of them leaves tokens that
10903
+ * do have an icon rendering as the blank placeholder.
10904
+ */
10905
+ declare const pickLogo: (t: {
10906
+ logo?: string;
10907
+ icon_image?: string;
10908
+ logoURI?: string;
10909
+ thumbnail?: string;
10910
+ }) => string | undefined;
10911
+ /** What a spendable read yields. `null` from the reader means "no usable balance". */
10912
+ interface SpendableBalance {
10913
+ /**
10914
+ * Human-readable spendable amount — already net of the gas reserve for a
10915
+ * native source. This is the exact string every fraction is taken FROM; never
10916
+ * re-round it, since rounding up produces an amount the user does not have.
10917
+ */
10918
+ balanceFormatted: string;
10919
+ /** The same figure as a number, for comparisons. */
10920
+ balanceNum: number;
10921
+ /**
10922
+ * The same figure in the token's SMALLEST units. What the form's percentage
10923
+ * pills divide, so the number shown and the number divided are provably one.
10924
+ * `undefined` when decimals aren't known and the conversion can't be made.
10925
+ */
10926
+ rawAmount?: string;
10927
+ symbol?: string;
10928
+ decimals?: number;
10929
+ logo?: string;
10930
+ }
10931
+ /**
10932
+ * Read the spendable balance of `tokenAddress` for `walletAddress` on `chain`.
10933
+ *
10934
+ * Returns `null` — never a zero — when the token isn't held, the balance is
10935
+ * unreadable, or a native balance is entirely consumed by its own gas reserve.
10936
+ * "Holds nothing" and "we couldn't ask" both mean the caller has no percentages
10937
+ * to offer, and both must leave whatever figure is already on screen alone
10938
+ * rather than overwrite it with a zero the wallet does not report.
10939
+ *
10940
+ * @param moralis The balance source. Callers that have no Moralis
10941
+ * configured get `null`, as before.
10942
+ * @param walletAddress The holder.
10943
+ * @param tokenAddress `'native'` for the chain's coin, else the contract.
10944
+ * @param chain Hex chain id. Required for the native gas reserve; a
10945
+ * native read without one returns the full balance.
10946
+ * @param kind Which gas limit the reserve is sized against —
10947
+ * `'swap'` (a router call, the default) or `'send'`.
10948
+ * @param feeContext Quote/provider context for the reserve: the quote's own
10949
+ * gas limit and, on a cross-chain deBridge route, its fixed
10950
+ * protocol fee. Omitted, the reserve falls back to the
10951
+ * default gas limit and no protocol fee — which is what
10952
+ * every pre-quote caller wants.
10953
+ * @param dbg Optional trace sink, so the tools keep the logging they had.
10954
+ */
10955
+ declare function readSpendableBalance(input: {
10956
+ moralis?: MoralisService;
10957
+ walletAddress: string;
10958
+ tokenAddress: string;
10959
+ chain?: string;
10960
+ kind?: NativeActionKind;
10961
+ feeContext?: FeeContext;
10962
+ dbg?: (msg: string, data?: unknown) => void;
10963
+ }): Promise<SpendableBalance | null>;
10964
+
9584
10965
  /**
9585
10966
  * JSON-RPC wire types + the EIP-1193 request function every transport exposes.
9586
10967
  */
@@ -11591,6 +12972,11 @@ interface PantographRawToken {
11591
12972
  decimals?: number;
11592
12973
  fixedPrice?: number | string | null;
11593
12974
  } | null;
12975
+ /**
12976
+ * The contract's own `symbol()`, as the index read it. `null` (or absent) when
12977
+ * the index never resolved one — see {@link TokenMetadata.symbolOnchain}.
12978
+ */
12979
+ symbolOnchain?: string | null;
11594
12980
  }
11595
12981
  /**
11596
12982
  * The yield half of a token API row — what decides whether a quoted price
@@ -11618,6 +13004,20 @@ declare class PantographService {
11618
13004
  * slug — so token lookups work the same on Ethereum, Gnosis, or any other EVM.
11619
13005
  */
11620
13006
  private tokensUrl;
13007
+ /**
13008
+ * Fetch token metadata + price rows for any number of contracts on one chain,
13009
+ * split across as many `/keyrings/tokens/all/{chainId}` requests as needed.
13010
+ *
13011
+ * Batches run in parallel and their rows are concatenated, so the caller sees
13012
+ * one flat list and cannot tell how many requests produced it. A batch that
13013
+ * fails contributes nothing rather than failing the whole call: every caller
13014
+ * here degrades per token (a missing row means no price, not an error), so
13015
+ * losing one chunk of a large wallet is strictly better than losing all of it.
13016
+ *
13017
+ * `chainId` is the DECIMAL id this route is keyed by; callers holding a hex
13018
+ * chain convert before calling.
13019
+ */
13020
+ private fetchTokensAll;
11621
13021
  /**
11622
13022
  * Enrich token balances with price and logo data from Pantograph.
11623
13023
  * Mutates the array in-place. Non-fatal: silently skips on failure.
@@ -11723,6 +13123,46 @@ declare class PantographService {
11723
13123
  }): Promise<MoralisApiResponse<TrendingToken[]>>;
11724
13124
  }
11725
13125
 
13126
+ /**
13127
+ * Deterministic Uniswap V3 pool-address derivation (CREATE2).
13128
+ *
13129
+ * DefiLlama Yields identifies a pool by an opaque UUID and never reports the
13130
+ * pool's contract address — it only gives `underlyingTokens` (the two token
13131
+ * addresses) and `poolMeta` (the fee tier). That is a problem for every flow
13132
+ * that must touch the chain: `PoolService.readPoolOnchain` needs a real address
13133
+ * to read `slot0` / `tickSpacing`, and the add-liquidity mint is built from it.
13134
+ *
13135
+ * Uniswap V3 deploys every pool through the factory with CREATE2, so the address
13136
+ * is a pure function of (factory, token0, token1, fee) and can be recomputed
13137
+ * locally — no RPC call, no extra API. This module is that function, and it is
13138
+ * what lets the DefiLlama-backed pool agent reach full parity with the Uniswap
13139
+ * Explore agent on the add-liquidity flow.
13140
+ *
13141
+ * The derived address is a CLAIM, not a fact: it is where the pool WOULD live if
13142
+ * it exists with that exact fee tier. Callers that go on to build a transaction
13143
+ * must confirm it on-chain (`readPoolOnchain` reverts on a non-pool), which the
13144
+ * add-liquidity flow already does as its first step.
13145
+ */
13146
+ /** True when Uniswap V3 pool addresses can be derived on this chain. */
13147
+ declare function canDeriveV3PoolAddress(chain: string): boolean;
13148
+ /**
13149
+ * Derive the Uniswap V3 pool address for a token pair + fee tier on `chain`.
13150
+ *
13151
+ * Token order does NOT matter: the pair is sorted the way the factory sorts it
13152
+ * (ascending by address), so passing (WETH, USDC) and (USDC, WETH) yield the
13153
+ * same pool — which matters because DefiLlama's `underlyingTokens` order does
13154
+ * not follow the pool's own token0/token1 order.
13155
+ *
13156
+ * @param chain Hex chain id.
13157
+ * @param tokenA Either token's address (order irrelevant).
13158
+ * @param tokenB The other token's address.
13159
+ * @param feeTierBps Fee tier in hundredths of a bip, as the factory stores it
13160
+ * (100 = 0.01%, 500 = 0.05%, 3000 = 0.3%, 10000 = 1%).
13161
+ * @returns The lowercase pool address, or `null` when the chain has no known
13162
+ * factory or either input is not a valid address.
13163
+ */
13164
+ declare function deriveV3PoolAddress(chain: string, tokenA: string, tokenB: string, feeTierBps: number): string | null;
13165
+
11726
13166
  /**
11727
13167
  * Manages conversation history for a single session.
11728
13168
  *
@@ -12017,4 +13457,4 @@ declare class AbortError extends Error {
12017
13457
  */
12018
13458
  declare function isAbortError(err: unknown): boolean;
12019
13459
 
12020
- export { AI_AGENT_TOOL_NAMES, type Abi, type AbiItem, type AbiParameter, AbortError, type AddLiquidityFormProps, type AddLiquiditySummary, type Address, type AffiliateFee, type AgentConfig, AgentCore, type AgentResponse, ApproveTokenTool, type ApyPoint, BaseNftAiTool, BaseSwapService, BaseTool, BaseWalletActionTool, type BlockParameters, type BlockTag, type BuyTokenConfirmTxProps, type BuyTokenSide, BuyTokenTool, type CallParameters, type Chain, type ChainMeta, type ChainRef, type ChainSelector, ChatHistory, type ChatMessage, type ChatOptions, type ChatRole, type CheckApprovalParams, type CheckApprovalResult, type Client, type ClientBatchConfig, type ConfirmAddLiquidityTxProps, type ContractFunctionParameters, type CortexResponse, DEFAULT_CHAIN, DEFAULT_PROVIDER, DEFAULT_RPC_BY_CHAIN, DebridgeAdapter, type DecodedCall, type DecodedEvent, type DecodedParam, type DefaultSubagentName, type DefiPosition, type DefiPositionDetails, type DefiPositionToken, type DefiProtocolSummary, type EIP1193RequestFn, EstimatePoolYieldTool, type EstimatePoolYieldToolConfig, type ExchangeProviderConfig, type ExecuteSwapParams, type ExecuteSwapResult, GeminiProvider, GeminiSearchAiTool, type GeminiSearchAiToolConfig, HEX_TO_PANTOGRAPH, type Hex, type HolderChangePeriod, type HolderSupplyTier, type HttpMethod, type IngestKnowledgeBaseInput, type IngestKnowledgeBaseResult, type InputTokenInfo, type KBSearchResult, KnowledgeBase, type KnowledgeBaseEntry, type KnowledgeBaseProvider, type LLMProvider, type LLMProviderConfig, type LLMResponse, type LLMToolCall, type LendingMarket, type LendingMarketCardProps, LendingMarketDetailTool, type LendingMarketDetailToolConfig, type LendingMarketListProps, type LendingMarketOverview, LendingMarketsTool, type LendingMarketsToolConfig, type LendingProtocolType, LendingReadService, LendingService, type LendingServiceConfig, type LendingSupplyPosition, LendingSupplyService, MULTICALL3_ADDRESS, ManageLiquidityRedirectTool, type MarketplaceLink, type MoralisApiResponse, MoralisService, type MoralisServiceConfig, type MulticallParameters, type MulticallRawParameters, type MulticallResult, NFC_AGENT_TOOL_NAMES, NFC_AMAZON_DEFAULT_DOMAIN, NFC_AMAZON_DOMAINS, type NFTCollectionItem, NFTContractInfoTool, type NFTContractMetadata, type NFTItem, type NFTLastSale, type NFTMetadata, NFTMetadataTool, NFT_AGENT_TOOL_NAMES, type NativeTokenInfo, NfcBuyTool, NfcInfoTool, type NftTransferLastSale, NoFormTool, type NoFormToolMessages, OpenAddLiquidityFormTool, type OpenAddLiquidityFormToolConfig, OpenSupplyFormTool, type OpenSupplyFormToolConfig, POOL_AGENT_TOOL_NAMES, PantographService, type PantographServiceConfig, type PantographYieldIdentity, type PaymentToken, PoolByAddressTool, type PoolByAddressToolConfig, PoolDetailTool, type PoolDetailToolConfig, type PoolDisplayInfo, PoolFallbackAiTool, type PoolFallbackAiToolConfig, type PoolOnchainInfo, PoolPriceRangesTool, type PoolPriceRangesToolConfig, PoolSearchTool, type PoolSearchToolConfig, PoolService, type PoolServiceConfig, type PresetInputs, PreviewAddLiquidityTool, type PreviewAddLiquidityToolConfig, type PriceBounds, type PriceRangePrefill, type ProviderName, PublicClient, type PublicClientConfig, type QuickRate, type RangePreset, type ReActPhase, type ReActStep, type ReActTrace, type ReadContractParameters, RelayAdapter, type ResolvedRange, Router, type RouterAssignment, type RouterDecision, SUPPLIABLE_TYPES, SUPPORTED_CHAINS, SUPPORTED_CHAINS_LABEL, SWAP_PROVIDER_CONFIG, SendNativeTool, SendNftTool, SendTokenTool, type StateOverride, type StorageProvider, Subagent, type SubagentCard, type SubagentOptions, type SubagentParams, type SubagentResult, type SubagentTask, type SubagentToggles, SubgraphAddPoolTool, type SubgraphAddPoolToolConfig, SubgraphCoinPoolPairsTool, type SubgraphCoinPoolPairsToolConfig, SubgraphPoolByAddressTool, type SubgraphPoolByAddressToolConfig, SubgraphPoolByPositionIdTool, type SubgraphPoolByPositionIdToolConfig, SubgraphPoolSearchTool, type SubgraphPoolSearchToolConfig, SubgraphPositionDetailTool, type SubgraphPositionDetailToolConfig, SubgraphTrendingPoolsTool, type SubgraphTrendingPoolsToolConfig, type SuggestedAction, Summarizer, type SuppliableMarket, type SupplyProtocolType, type SupplyUsdcProps, type SupportedChainId, type SupportedChainName, type SwapQuoteParams, type SwapQuoteResult, type SwapServiceConfig, SwapServiceFactory, type SwapTokenConfirmTxProps, SwapTokenTool, type SwapTxData, Synthesizer, TOKEN_AGENT_TOOL_NAMES, TRANSFER_TOPIC, TRENDING_DEFAULT_BY_HEX_CHAIN, type TokenAnalyticsResponse, type TokenAnalyticsTimeframeBuckets, TokenAnalyticsTool, type TokenAnalyticsToolConfig, type TokenApproval, type TokenApprovalSpender, type TokenApprovalToken, type TokenBalance, type TokenDisplay, type TokenHoldersResponse, TokenHoldersTool, type TokenHoldersToolConfig, TokenInfoTool, type TokenInfoToolConfig, type TokenMetadata, type TokenScoreMetrics, type TokenScoreResponse, type TokenScoreSupply, type TokenScoreTimeframeBuckets, TokenScoreTool, type TokenScoreToolConfig, type Tool, type ToolDefinition, type ToolKind, type ToolParameter, ToolRegistry, type ToolResult, type TopGainerTimeFrames, type TopGainerToken, type TopGainersTimeFrame, TopGainersTool, type TopGainersToolConfig, TopPoolsTool, type TopPoolsToolConfig, type TrackStatus, type TrackTransactionParams, type TrackTransactionResult, type TransactionByHashResponse, TransactionByHashTool, type TransactionByHashToolConfig, type TransactionLog, type TransactionReceipt, type TransactionReceiptLog, type Transport, type TransportConfig, type TrendingToken, type TrendingTokenTimeframeBuckets, TrendingTokensTool, type TrendingTokensToolConfig, type UIPayload, UNISWAP_CHAIN_SLUG, UNRESOLVED_ASSET, type UnsignedTx, type UpstashEmbedStrategy, type UpstashFusionAlgorithm, type UpstashKBUpsertEntry, UpstashKnowledgeBase, type UpstashKnowledgeBaseConfig, type UserContext, type VectorKBConfig, WALLET_ACTION_AGENT_TOOL_NAMES, WALLET_AGENT_TOOL_NAMES, type WalletActionProps, type WalletActionType, type WalletApprovalsResponse, WalletApprovalsTool, type WalletApprovalsToolConfig, type WalletDefiPositionSummary, WalletDefiPositionsTool, type WalletDefiPositionsToolConfig, type WalletDefiPositionsV1Response, type WalletDefiProtocolPositionsResponse, WalletDefiProtocolPositionsTool, type WalletDefiProtocolPositionsToolConfig, type WalletDefiProtocolPositionsV1Response, type WalletDefiSummaryResponse, type WalletDefiSummaryV1Response, type WalletHistoryCategory, type WalletHistoryContractInteraction, type WalletHistoryErc20Transfer, type WalletHistoryItem, type WalletHistoryNativeTransfer, type WalletHistoryNftTransfer, type WalletHistoryResponse, WalletHistoryTool, type WalletHistoryToolConfig, WalletLendingPositionsTool, type WalletLendingPositionsToolConfig, WalletNFTsTool, type WalletNFTsToolConfig, type WalletNftCardProps, type WalletNftListProps, type WalletNftTransferItem, type WalletNftTransfersResponse, WalletNftTransfersTool, type WalletNftTransfersToolConfig, type WalletPnlDaysWindow, type WalletPnlResponse, type WalletPnlSummaryResponse, WalletPnlSummaryTool, type WalletPnlSummaryToolConfig, type WalletPnlTokenItem, WalletPnlTool, type WalletPnlToolConfig, WalletTokenBalancesTool, type WalletTokenBalancesToolConfig, type WalletTokenTransferItem, type WalletTokenTransfersResponse, WalletTokenTransfersTool, type WalletTokenTransfersToolConfig, type WebsiteTrustExtraData, type WebsiteTrustInput, WebsiteTrustKeyringAgent, type WebsiteTrustKeyringAgentConfig, type WebsiteTrustResult, type X402Authorization, type X402Challenge, type X402Display, type X402Outcome, type X402PaymentRequiredProps, type X402Receipt, type X402RequestSpec, type X402Requirements, type X402SignRequest, type X402Signer, type X402TypedData, type X402Version, type YieldConversionCall, type YieldConversionPlan, type YieldPricingOptions, type YieldPricingToken, type YieldTokenInput, type YieldTokenValue, ZERO_ADDRESS, amazonDomainForLanguage, apiClient, applyYieldConversions, buildChallenge, buildRangePresets, buildUniswapPoolUrl, call, chains, checksumAddress, clampTick, clearPublicClientCache, completeX402, configureSupportedChains, convertSusdsShares, createAiAgent, createDefaultSubagents, createNfcAgent, createNftAgent, createPoolAgent, createPublicClient, createTokenAgent, createTransport, createWalletActionAgent, createWalletAgent, createX402SignatureProvider, decodeAbiParameters, decodeErrorResult, decodeFunctionData, decodeFunctionResult, displayFromChallenge, effectivePriceUSD, encodeAbiParameters, encodeErrorResult, encodeFunctionData, encodeSignedHeader, erc1155Abi, erc20Abi, erc20Abi_bytes32, erc721Abi, estimateGas, ethCallAt, ethCallByChain, fallback, fetchTopMarketplaces, getAbiItem, getAddress, getAffiliateFee, getBalance, getBlock, getBlockNumber, getChain, getChainContractAddress, getChainId, getChainMeta, getCode, getDefaultRpcUrl, getGasPrice, getGatewayAddress, getGatewayChains, getNativeTokenInfo, getPositionManagerAddress, getProviderByChain, getPublicClient, getRevertReason, getRpcOverrides, getStorageAt, getTokenPriceUSD, getTransactionCount, http, ingestKnowledgeBase, isAbortError, isAddress, isAddressEqual, isPaymentRequired, isShareBasedProtocol, isShareBasedYieldToken, isSupplyChain, listCandidateChains, listSupplyChains, multicall, multicall3Abi, multicallRaw, nfcAmazonSearchUrl, normaliseCountry, normalizePriceRangeToPool, parseAbi, parseAbiItem, parseAbiParameters, planYieldTokenConversions, priceToTick, protocolLabelFor, psm3For, readContract, readPaymentError, readPaymentRequired, readReceipt, registerMaybeNoForm, requestWithX402, resolveNfcShopLinks, resolveRpcUrl, resolveRpcUrls, resolveTokenPriceUSD, roundTickToSpacing, rpcCall, setRpcOverrides, swapServiceFactory, tickToPrice, toEventSelector, toFunctionSelector, toPantographChain, valueYieldTokens };
13460
+ export { AI_AGENT_TOOL_NAMES, type Abi, type AbiItem, type AbiParameter, AbortError, type AddLiquidityFormProps, type AddLiquiditySummary, type Address, type AffiliateFee, type AgentConfig, AgentCore, type AgentResponse, type ApprovalTx, ApproveTokenTool, type ApyPoint, BaseNftAiTool, BaseSwapProvider, BaseTool, BaseWalletActionTool, type BlockParameters, type BlockTag, type BuildApprovalsParams, type BuyTokenSide, BuyTokenTool, CachedResource, type CallParameters, type Chain, type ChainMeta, type ChainRef, type ChainSelector, ChatHistory, type ChatMessage, type ChatOptions, type ChatRole, type CheckApprovalParams, type CheckApprovalResult, type Client, type ClientBatchConfig, CoinpoolConfigApi, type ConfirmAddLiquidityTxProps, type ContractFunctionParameters, type CortexResponse, DEFAULT_CHAIN, DEFAULT_PROVIDER, DEFAULT_RPC_BY_CHAIN, DEFILLAMA_EXTRA_SIGNALS, DEFILLAMA_POOL_CHAIN_HEXES, DEFILLAMA_POOL_CHAIN_PARAM_DESCRIPTION, DebridgeProvider, type DecodedCall, type DecodedEvent, type DecodedParam, type DefaultSubagentName, DefiLlamaEstimatePoolYieldTool, type DefiLlamaEstimatePoolYieldToolConfig, type DefiLlamaPool, DefiLlamaPoolByAddressTool, type DefiLlamaPoolByAddressToolConfig, DefiLlamaPoolCandidateResolver, DefiLlamaPoolDetailTool, type DefiLlamaPoolDetailToolConfig, DefiLlamaPoolSearchTool, type DefiLlamaPoolSearchToolConfig, DefiLlamaPoolService, type DefiLlamaPoolServiceConfig, type DefiLlamaProtocolVersion, type DefiLlamaServiceResponse, type DefiLlamaSortBy, DefiLlamaTopPoolsTool, type DefiLlamaTopPoolsToolConfig, type DefiPosition, type DefiPositionDetails, type DefiPositionToken, type DefiProtocolSummary, type EIP1193RequestFn, EstimatePoolYieldTool, type EstimatePoolYieldToolConfig, type FeeContext, type FormattedDefiLlamaPool, GeminiProvider, GeminiSearchAiTool, type GeminiSearchAiToolConfig, HEX_TO_PANTOGRAPH, type Hex, type HolderChangePeriod, type HolderSupplyTier, type HttpMethod, type IngestKnowledgeBaseInput, type IngestKnowledgeBaseResult, type InputTokenInfo, type KBSearchResult, KeyringSettingApi, KnowledgeBase, type KnowledgeBaseEntry, type KnowledgeBaseProvider, type LLMProvider, type LLMProviderConfig, type LLMResponse, type LLMToolCall, type LendingMarket, type LendingMarketCardProps, LendingMarketDetailTool, type LendingMarketDetailToolConfig, type LendingMarketListProps, type LendingMarketOverview, LendingMarketsTool, type LendingMarketsToolConfig, type LendingProtocolType, LendingReadService, LendingService, type LendingServiceConfig, type LendingSupplyPosition, LendingSupplyService, MULTICALL3_ADDRESS, ManageLiquidityRedirectTool, type MarketplaceLink, type MoralisApiResponse, MoralisService, type MoralisServiceConfig, type MulticallParameters, type MulticallRawParameters, type MulticallResult, NATIVE_GAS_LIMIT, NFC_AGENT_TOOL_NAMES, NFC_AMAZON_DEFAULT_DOMAIN, NFC_AMAZON_DOMAINS, type NFTCollectionItem, NFTContractInfoTool, type NFTContractMetadata, type NFTItem, type NFTLastSale, type NFTMetadata, NFTMetadataTool, NFT_AGENT_TOOL_NAMES, type NativeActionKind, type NativeGasGap, type NativeTokenInfo, NfcBuyTool, NfcInfoTool, type NftTransferLastSale, NoFormTool, type NoFormToolMessages, OpenAddLiquidityFormTool, type OpenAddLiquidityFormToolConfig, OpenSupplyFormTool, type OpenSupplyFormToolConfig, POOL_UNISWAP_AGENT_TOOL_NAMES, PantographService, type PantographServiceConfig, type PantographYieldIdentity, type PaymentToken, PoolByAddressTool, type PoolByAddressToolConfig, PoolDetailTool, type PoolDetailToolConfig, type PoolDisplayInfo, PoolFallbackAiTool, type PoolFallbackAiToolConfig, type PoolOnchainInfo, PoolPriceRangesTool, type PoolPriceRangesToolConfig, PoolSearchTool, type PoolSearchToolConfig, PoolService, type PoolServiceConfig, PoolSwapRouter, type PresetInputs, PreviewAddLiquidityTool, type PreviewAddLiquidityToolConfig, type PriceBounds, type PriceRangePrefill, type ProviderName, PublicClient, type PublicClientConfig, type QuickRate, type QuoteGas, type RangePreset, type ReActPhase, type ReActStep, type ReActTrace, type ReadContractParameters, RelayProvider, type ResolvedRange, Router, type RouterAssignment, type RouterDecision, SUPPLIABLE_TYPES, SUPPORTED_CHAINS, SUPPORTED_CHAINS_LABEL, SWAP_PROVIDER_CONFIG, SendNativeTool, SendNftTool, SendTokenTool, type SpendableBalance, type StateOverride, type StorageProvider, Subagent, type SubagentCard, type SubagentOptions, type SubagentParams, type SubagentResult, type SubagentTask, type SubagentToggles, SubgraphAddPoolTool, type SubgraphAddPoolToolConfig, SubgraphCoinPoolPairsTool, type SubgraphCoinPoolPairsToolConfig, SubgraphPoolByAddressTool, type SubgraphPoolByAddressToolConfig, SubgraphPoolByPositionIdTool, type SubgraphPoolByPositionIdToolConfig, SubgraphPoolSearchTool, type SubgraphPoolSearchToolConfig, SubgraphPositionDetailTool, type SubgraphPositionDetailToolConfig, SubgraphTrendingPoolsTool, type SubgraphTrendingPoolsToolConfig, type SuggestedAction, Summarizer, type SuppliableMarket, type SupplyProtocolType, type SupplyUsdcProps, type SupportedChainId, type SupportedChainName, type SwapProviderConfig, type SwapProviderConfigMap, SwapProviderFactory, type SwapQuoteParams, type SwapQuoteResult, type SwapRoute, type SwapRouteRequest, SwapRouter, SwapRouterRegistry, type SwapTokenFormProps, SwapTokenTool, type SwapTxData, Synthesizer, TOKEN_AGENT_TOOL_NAMES, TRANSFER_TOPIC, TRENDING_DEFAULT_BY_HEX_CHAIN, type TokenAnalyticsResponse, type TokenAnalyticsTimeframeBuckets, TokenAnalyticsTool, type TokenAnalyticsToolConfig, type TokenApproval, type TokenApprovalSpender, type TokenApprovalToken, type TokenBalance, type TokenDisplay, type TokenHoldersResponse, TokenHoldersTool, type TokenHoldersToolConfig, TokenInfoTool, type TokenInfoToolConfig, type TokenMetadata, type TokenScoreMetrics, type TokenScoreResponse, type TokenScoreSupply, type TokenScoreTimeframeBuckets, TokenScoreTool, type TokenScoreToolConfig, type Tool, type ToolDefinition, type ToolKind, type ToolParameter, ToolRegistry, type ToolResult, type TopGainerTimeFrames, type TopGainerToken, type TopGainersTimeFrame, TopGainersTool, type TopGainersToolConfig, TopPoolsTool, type TopPoolsToolConfig, type TrackStatus, type TrackTransactionParams, type TrackTransactionResult, type TransactionByHashResponse, TransactionByHashTool, type TransactionByHashToolConfig, type TransactionLog, type TransactionReceipt, type TransactionReceiptLog, type Transport, type TransportConfig, type TrendingToken, type TrendingTokenTimeframeBuckets, TrendingTokensTool, type TrendingTokensToolConfig, type UIPayload, UNISWAP_CHAIN_SLUG, UNRESOLVED_ASSET, type UnsignedTx, type UpstashEmbedStrategy, type UpstashFusionAlgorithm, type UpstashKBUpsertEntry, UpstashKnowledgeBase, type UpstashKnowledgeBaseConfig, type UserContext, UserSwapRouter, type VectorKBConfig, WALLET_ACTION_AGENT_TOOL_NAMES, WALLET_AGENT_TOOL_NAMES, type WalletActionProps, type WalletActionType, type WalletApprovalsResponse, WalletApprovalsTool, type WalletApprovalsToolConfig, type WalletDefiPositionSummary, WalletDefiPositionsTool, type WalletDefiPositionsToolConfig, type WalletDefiPositionsV1Response, type WalletDefiProtocolPositionsResponse, WalletDefiProtocolPositionsTool, type WalletDefiProtocolPositionsToolConfig, type WalletDefiProtocolPositionsV1Response, type WalletDefiSummaryResponse, type WalletDefiSummaryV1Response, type WalletHistoryCategory, type WalletHistoryContractInteraction, type WalletHistoryErc20Transfer, type WalletHistoryItem, type WalletHistoryNativeTransfer, type WalletHistoryNftTransfer, type WalletHistoryResponse, WalletHistoryTool, type WalletHistoryToolConfig, WalletLendingPositionsTool, type WalletLendingPositionsToolConfig, WalletNFTsTool, type WalletNFTsToolConfig, type WalletNftCardProps, type WalletNftListProps, type WalletNftTransferItem, type WalletNftTransfersResponse, WalletNftTransfersTool, type WalletNftTransfersToolConfig, type WalletPnlDaysWindow, type WalletPnlResponse, type WalletPnlSummaryResponse, WalletPnlSummaryTool, type WalletPnlSummaryToolConfig, type WalletPnlTokenItem, WalletPnlTool, type WalletPnlToolConfig, WalletTokenBalancesTool, type WalletTokenBalancesToolConfig, type WalletTokenTransferItem, type WalletTokenTransfersResponse, WalletTokenTransfersTool, type WalletTokenTransfersToolConfig, type WebsiteTrustExtraData, type WebsiteTrustInput, WebsiteTrustKeyringAgent, type WebsiteTrustKeyringAgentConfig, type WebsiteTrustResult, type X402Authorization, type X402Challenge, type X402Display, type X402Outcome, type X402PaymentRequiredProps, type X402Receipt, type X402RequestSpec, type X402Requirements, type X402SignRequest, type X402Signer, type X402TypedData, type X402Version, type YieldConversionCall, type YieldConversionPlan, type YieldPricingOptions, type YieldPricingToken, type YieldTokenInput, type YieldTokenValue, ZERO_ADDRESS, amazonDomainForLanguage, apiClient, applyYieldConversions, buildApprovals, buildChallenge, buildRangePresets, buildUniswapPoolUrl, call, canDeriveV3PoolAddress, chains, checkNativeGasAffordable, checksumAddress, clampTick, clearPublicClientCache, coinpoolConfigApi, compareDecimal, completeX402, configureSupportedChains, configureSwapProvider, convertSusdsShares, createAiAgent, createDefaultSubagents, createNfcAgent, createNftAgent, createPoolUniswapAgent, createPublicClient, createTokenAgent, createTransport, createWalletActionAgent, createWalletAgent, createX402SignatureProvider, decodeAbiParameters, decodeErrorResult, decodeFunctionData, decodeFunctionResult, defiLlamaPoolInfoScope, defiLlamaPoolSupportsLabel, deriveV3PoolAddress, displayFromChallenge, effectivePriceUSD, encodeAbiParameters, encodeApprove, encodeErrorResult, encodeFunctionData, encodeSignedHeader, erc1155Abi, erc20Abi, erc20Abi_bytes32, erc721Abi, estimateGas, estimateNativeGasReserveWei, estimateTransactionFeeWei, ethCallAt, ethCallByChain, exactAmountString, extractOutRaw, extractQuoteError, fallback, feeWeiToNative, fetchTopMarketplaces, floorToDecimals, formatDefiLlamaPool, getAbiItem, getAddress, getBalance, getBlock, getBlockNumber, getChain, getChainContractAddress, getChainId, getChainMeta, getCode, getDefaultRpcUrl, getGasPrice, getNativeTokenInfo, getPublicClient, getRevertReason, getRpcOverrides, getStorageAt, getTokenPriceUSD, getTransactionCount, http, humanToWei, ingestKnowledgeBase, isAbortError, isAddress, isAddressEqual, isPaymentRequired, isShareBasedProtocol, isShareBasedYieldToken, isSupplyChain, keyringSettingApi, listCandidateChains, listSupplyChains, mulDivFloor, multicall, multicall3Abi, multicallRaw, nativeGasShortfall, nfcAmazonSearchUrl, normaliseCountry, normalizeDecimal, normalizePriceRangeToPool, parseAbi, parseAbiItem, parseAbiParameters, pickLogo, planYieldTokenConversions, priceToTick, protocolLabelFor, psm3For, readContract, readPaymentError, readPaymentRequired, readProtocolFeeWei, readReceipt, readSpendableBalance, registerMaybeNoForm, requestWithX402, resolveGasLimit, resolveNfcShopLinks, resolveRpcUrl, resolveRpcUrls, resolveTokenPriceUSD, roundTickToSpacing, rpcCall, setRpcOverrides, spendableNative, swapProviderFactory, swapRouterRegistry, tickToPrice, toEventSelector, toFunctionSelector, toPantographChain, toPlainDecimal, valueYieldTokens, weiToHuman };