keyring-agent-core 0.2.53 → 0.2.55

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
@@ -368,6 +368,18 @@ declare class PoolService {
368
368
  */
369
369
  listAddLiquiditySupportedChains(): Promise<string[]>;
370
370
  getPositionManagerAddress(chainId: string): Promise<string | undefined>;
371
+ /**
372
+ * The shared read client for a chain — see {@link file://../chain/index.ts}.
373
+ *
374
+ * Endpoint rules are the core-wide ones, which `getPublicClient` already
375
+ * applies: the shared override first, then the chain's backups behind it. This
376
+ * used to pass {@link getRpcUrl} explicitly, which resolved to the SAME
377
+ * preferred endpoint but pinned it — dropping the backups, so a flaky RPC
378
+ * failed the read instead of falling through. Cached per chain by the client
379
+ * factory, and multicall-batching, so the several reads a pool description
380
+ * needs collapse into one round-trip.
381
+ */
382
+ private client;
371
383
  /** Generic eth_call helper. `data` is the encoded calldata (with selector). */
372
384
  ethCall(chainId: string, to: string, data: string): Promise<string>;
373
385
  /** Read native balance (wei) */
@@ -391,7 +403,16 @@ declare class PoolService {
391
403
  * before quoting "spendable". Mirrors coinpool-v2: gasLimit × gasPrice × 1.8.
392
404
  */
393
405
  estimateGasReserveWei(chainId: string): Promise<bigint>;
394
- /** Read full pool state in one batch of eth_calls */
406
+ /**
407
+ * Read full pool state in ONE round-trip.
408
+ *
409
+ * The six reads go through Multicall3 (`aggregate3`) with `allowFailure: false`,
410
+ * so a pool address that isn't a V3 pool fails loudly here — as it did when
411
+ * these were six separate `eth_call`s — rather than yielding a half-filled
412
+ * description. Addresses are lower-cased on the way out: the decoder returns
413
+ * EIP-55 checksummed hex, while callers key maps and compare against
414
+ * {@link ZERO_ADDRESS} in lowercase.
415
+ */
395
416
  readPoolOnchain(chainId: string, poolAddress: string): Promise<PoolOnchainInfo>;
396
417
  readErc20Decimals(chainId: string, tokenAddress: string): Promise<number>;
397
418
  /**
@@ -468,41 +489,6 @@ declare class PoolService {
468
489
  value: string;
469
490
  minAmountOut: string;
470
491
  }>;
471
- /**
472
- * Encode a call to the CoinPool gateway's `mint(paymentInfo, exchanges, params)`
473
- * function. Layout matches coinpool-v2's GatewayAbi.
474
- *
475
- * Function signature:
476
- * mint(
477
- * PaymentInfo[2] paymentInfo,
478
- * Exchange[2] exchanges,
479
- * MintParams params
480
- * )
481
- *
482
- * Where:
483
- * PaymentInfo = (address tokenIn, uint256 tokenInAmount, address tokenOut, uint256 tokenOutAmount)
484
- * Exchange = (address to, bytes data, uint256 value)
485
- * MintParams = (uint24 fee, uint256 amount0Min, uint256 amount1Min, int24 tickLower, int24 tickUpper)
486
- */
487
- encodeMintCalldata(args: {
488
- paymentInfo: Array<{
489
- tokenIn: string;
490
- tokenInAmount: bigint;
491
- tokenOut: string;
492
- tokenOutAmount: bigint;
493
- }>;
494
- exchanges: Array<{
495
- to: string;
496
- data: string;
497
- value: bigint;
498
- }>;
499
- fee: number;
500
- amount0Min: bigint;
501
- amount1Min: bigint;
502
- tickLower: number;
503
- tickUpper: number;
504
- }): string;
505
- _keccak(hex: string): string;
506
492
  }
507
493
 
508
494
  /**
@@ -1398,10 +1384,14 @@ interface AgentConfig {
1398
1384
  llm: LLMProviderConfig;
1399
1385
  /**
1400
1386
  * Core-wide RPC overrides, keyed by hex chain id (e.g. `{ '0x1': 'https://…' }`).
1401
- * The single place to configure RPC endpoints — shared by every on-chain read
1402
- * in the core: gas-reserve estimation for wallet actions, the swap allowance
1403
- * check, and the pool tools. A chain that is not listed falls back to the
1404
- * built-in public default for that chain.
1387
+ * Shared by every on-chain read in the core: gas-reserve estimation for wallet
1388
+ * actions, the swap allowance check, and the pool tools.
1389
+ *
1390
+ * An entry PREFERS an endpoint rather than replacing the list — a chain's
1391
+ * built-in defaults, plus the endpoints loaded from the Pantograph chains
1392
+ * catalogue on startup, stay behind it as backups, so a configured node going
1393
+ * down degrades to the public ones instead of losing the chain. A chain that
1394
+ * is not listed simply uses those built-in and catalogue endpoints.
1405
1395
  */
1406
1396
  rpcUrls?: Record<string, string>;
1407
1397
  /**
@@ -1476,7 +1466,7 @@ interface AgentConfig {
1476
1466
  pantographUrl?: string;
1477
1467
  } | false;
1478
1468
  /**
1479
- * USDC lending / supply tool config (`get-lending-markets` and
1469
+ * Lending / supply tool config (`get-lending-markets` and
1480
1470
  * `get-wallet-lending-positions`). Set to `false` to skip registering them —
1481
1471
  * to keep the tools but stop routing to them, use `subagents.lending: false`.
1482
1472
  * Independent of `moralis`: the curated market list comes from the CoinPool
@@ -1501,7 +1491,7 @@ interface AgentConfig {
1501
1491
  wallet?: boolean;
1502
1492
  'wallet-action'?: boolean;
1503
1493
  /**
1504
- * USDC lending expert: which markets to supply to and what the wallet
1494
+ * Lending expert: which markets to supply to and what the wallet
1505
1495
  * already supplies. Needs `lending` (its tools) to be enabled.
1506
1496
  */
1507
1497
  lending?: boolean;
@@ -5231,6 +5221,133 @@ declare class TransactionByHashTool extends BaseTool {
5231
5221
  }>;
5232
5222
  }
5233
5223
 
5224
+ /**
5225
+ * Shared ABI / hex types for the codec layer.
5226
+ *
5227
+ * Deliberately STRUCTURAL and loose (every field but `type` optional) rather
5228
+ * than viem's fully-inferred `Abi` generics: this core hand-writes its ABIs as
5229
+ * plain object literals — some without `as const` — and a strict type would
5230
+ * reject them at every call site for no runtime benefit. Validation happens
5231
+ * where it matters, at runtime, in {@link file://./signature.ts}.
5232
+ */
5233
+ /** A 0x-prefixed hex string. */
5234
+ type Hex = `0x${string}`;
5235
+ /** A 0x-prefixed 20-byte address. */
5236
+ type Address = `0x${string}`;
5237
+ /** One ABI input/output parameter; `components` is present for tuples. */
5238
+ interface AbiParameter {
5239
+ readonly name?: string;
5240
+ readonly type: string;
5241
+ readonly internalType?: string;
5242
+ readonly components?: readonly AbiParameter[];
5243
+ /** Events only — whether the parameter is a topic. */
5244
+ readonly indexed?: boolean;
5245
+ }
5246
+ /** One ABI entry: function, event, error, constructor, fallback or receive. */
5247
+ interface AbiItem {
5248
+ readonly type?: string;
5249
+ readonly name?: string;
5250
+ readonly inputs?: readonly AbiParameter[];
5251
+ readonly outputs?: readonly AbiParameter[];
5252
+ readonly stateMutability?: string;
5253
+ readonly anonymous?: boolean;
5254
+ }
5255
+ /** A contract ABI. */
5256
+ type Abi = readonly AbiItem[];
5257
+
5258
+ /**
5259
+ * Chain shape — viem's `Chain`, plus a `hexId` because this core identifies
5260
+ * chains by hex id (`0x2105`) everywhere: in tool arguments, in `UserContext`,
5261
+ * and in the wallet payloads it hands the app.
5262
+ */
5263
+
5264
+ /** A contract deployed at a known address on a chain. */
5265
+ interface ChainContract {
5266
+ address: Address;
5267
+ /** Block the contract was deployed at, when known — reads before it can't work. */
5268
+ blockCreated?: number;
5269
+ }
5270
+ /** The chain's one native coin (everything else on it is a token). */
5271
+ interface ChainNativeCurrency {
5272
+ name: string;
5273
+ symbol: string;
5274
+ decimals: number;
5275
+ }
5276
+ interface Chain {
5277
+ /** Decimal chain id (`8453`). */
5278
+ id: number;
5279
+ /** Canonical hex chain id (`0x2105`) — this core's primary key for a chain. */
5280
+ hexId: Hex;
5281
+ /** Display name, as shown to users. */
5282
+ name: string;
5283
+ nativeCurrency: ChainNativeCurrency;
5284
+ rpcUrls: {
5285
+ default: {
5286
+ http: readonly string[];
5287
+ };
5288
+ };
5289
+ blockExplorers?: {
5290
+ default: {
5291
+ name: string;
5292
+ url: string;
5293
+ };
5294
+ };
5295
+ /** Well-known contracts; `multicall3` is what the batching layer needs. */
5296
+ contracts?: {
5297
+ multicall3?: ChainContract;
5298
+ };
5299
+ testnet?: boolean;
5300
+ }
5301
+
5302
+ /**
5303
+ * The 12 EVM chains this core supports, as viem-shaped {@link Chain} objects.
5304
+ *
5305
+ * One definition per chain carries everything the stack needs — decimal id, hex
5306
+ * id, display name, native coin, default public RPC and the Multicall3
5307
+ * deployment — so nothing has to be threaded through call sites or duplicated in
5308
+ * a second table.
5309
+ *
5310
+ * Multicall3 sits at the SAME deterministic address on every one of them
5311
+ * (verified on-chain via `eth_getCode`), but each chain still spells it out: a
5312
+ * chain that ever ships it elsewhere is then a one-line change here.
5313
+ *
5314
+ * `blockCreated` is advisory metadata — it only gates reads pinned to a
5315
+ * HISTORICAL block (a read at `latest`, the default, never consults it) — and is
5316
+ * left out where the deployment block isn't confirmed.
5317
+ *
5318
+ * `rpcUrls.default.http` is an ORDERED PREFERENCE LIST, not a single endpoint:
5319
+ * the first entry is the one normally used, and the rest are fixed backups the
5320
+ * {@link file://../transports/fallback.ts} transport walks down when a request
5321
+ * fails transiently (rate limit, 5xx, timeout). A public endpoint rejecting the
5322
+ * odd method — eth.llamarpc.com answering `eth_gasPrice` with HTTP 525, say —
5323
+ * therefore degrades to a slower answer rather than no answer.
5324
+ */
5325
+
5326
+ /** Canonical Multicall3 address, identical on every supported chain. */
5327
+ declare const MULTICALL3_ADDRESS: "0xcA11bde05977b3631167028862bE2a173976CA11";
5328
+ /** Every supported chain, in the core's canonical order. */
5329
+ declare const chains: readonly Chain[];
5330
+
5331
+ /**
5332
+ * Domain-level batched reads, on top of the chain stack
5333
+ * ({@link file://../chain/index.ts}).
5334
+ *
5335
+ * The Multicall3 plumbing this file used to carry — the hand-written
5336
+ * `aggregate3` encoder, the `(bool,bytes)[]` reader, the chunking loop — now
5337
+ * lives in `chain/actions/multicall.ts` and `chain/actions/multicallRaw.ts`,
5338
+ * where it is ABI-driven and reusable. What remains here are the three helpers
5339
+ * the core's services actually ask for, with their signatures and their
5340
+ * never-throws, positionally-aligned contracts unchanged:
5341
+ *
5342
+ * - {@link multicallRead} raw calldata in, raw return data out
5343
+ * - {@link multicallErc20Metadata} symbol + decimals, incl. legacy bytes32 tokens
5344
+ * - {@link multicallTokenUris} ERC-721 `tokenURI` for many NFTs
5345
+ *
5346
+ * For anything new, prefer the client directly — `getPublicClient(chainId)` then
5347
+ * `.multicall({ contracts })` — which decodes results and reports typed
5348
+ * per-entry errors instead of `null`.
5349
+ */
5350
+
5234
5351
  /** One read in a {@link multicallRead} batch: a target contract + full calldata. */
5235
5352
  interface MulticallRequest {
5236
5353
  /** Contract to call. A malformed address yields a `null` result. */
@@ -5264,92 +5381,135 @@ interface MulticallRequest {
5264
5381
  * step 2. The protocols stay ignorant of batching; the batching stays ignorant
5265
5382
  * of protocols.
5266
5383
  *
5384
+ * ## Rates that take two calls
5385
+ *
5386
+ * Compound and Spark cannot quote a rate in one read: Compound's `getSupplyRate`
5387
+ * is a function OF `getUtilization()`, and a Spark L2 vault's `getAPR()` lives on
5388
+ * whatever address its `rateProvider()` returns. Both are therefore a CHAIN of
5389
+ * two calls, the second built from the first's answer.
5390
+ *
5391
+ * {@link LendingProtocol.followUpRateCall} expresses that: given phase one's
5392
+ * return data, it declares the follow-up (or null when there is none), and
5393
+ * {@link LendingProtocol.decodeLiveRate} decodes whichever call came last. The
5394
+ * service runs at most two multicall rounds — every market that needs a follow-up
5395
+ * still shares one — so the cost is two round-trips per chain, not two per market.
5396
+ *
5397
+ * These reads exist because the numbers must match the CoinPool app, which reads
5398
+ * the same rates on-chain at render time. An earlier version leaned on the newest
5399
+ * row of CoinPool's history endpoint instead; that row is a snapshot taken hours
5400
+ * earlier, and on a chain whose utilization moves — Compound on Base was 5.33% by
5401
+ * the stored row against 5.21% on chain — it visibly disagrees with the app.
5402
+ *
5267
5403
  * The APY half ({@link LendingProtocol.fetchApy}) is a per-market HTTP call to a
5268
5404
  * different upstream per protocol, so there is nothing to batch and each class
5269
5405
  * simply does the fetch.
5270
5406
  */
5271
5407
  /** Market kinds `/supply/v2` returns; see {@link PROTOCOLS}. */
5272
- type LendingProtocolType = 'aave-v3' | 'compound-v3' | 'spark' | 'spark-ethereum' | 'morpho-v2';
5273
-
5408
+ type LendingProtocolType = 'aave-v3' | 'compound-v3' | 'spark' | 'spark-ethereum' | 'spark-l2-susds' | 'morpho-v2';
5274
5409
  /**
5275
- * Client for the CoinPool USDC **lending / supply** markets — the data behind
5276
- * the app's "Supply" product (Aave v3, Compound v3, Spark, Morpho v2 vaults).
5277
- *
5278
- * A wallet's supplied balance is NOT read from an indexer: the receipt token
5279
- * (aToken / Comet / ERC-4626 vault share) is read straight from chain through
5280
- * Multicall3, so the number always matches what the app shows. Everything else
5281
- * comes from the same sources the CoinPool web app itself uses — its
5282
- * `useUsdcLendingData` hook, in the SEPARATE `coinpool-v2` repository
5283
- * (`src/hooks/useUsdcLendingData.ts`), is the reference this service was checked
5284
- * against protocol by protocol:
5285
- *
5286
- * - market list ................. CoinPool `GET /supply/v2?chainId=…`
5287
- * - supply-APY history ......... Aave v3 GraphQL (`aave-v3`),
5288
- * Morpho GraphQL (`morpho-v2`),
5289
- * CoinPool `GET /supply/rates/history` (rest)
5290
- * - supplied amount / market size on-chain via Multicall3
5291
- *
5292
- * Reported APY is the AVERAGE of the daily supply-APY samples of the last
5293
- * {@link APY_HISTORY_DAYS} days plus the live rate — a spot rate swings with
5294
- * borrow demand, so an average is what a supplier actually earns.
5410
+ * The per-chain facts a protocol needs — the numeric chain id, and nothing else.
5295
5411
  *
5296
- * ## Protocols differ; the pipeline does not
5297
- *
5298
- * The market kinds disagree on every input: where the market size lives, whether
5299
- * the receipt token is 1:1 with USDC or an ERC-4626 share, which API knows the
5300
- * rate history, and whether a live rate has to come off-chain. Each kind is a
5301
- * class in {@link file://./lending/protocols.ts}; this file is the pipeline that
5302
- * drives them and knows about no protocol by name.
5303
- *
5304
- * | | market size | balance | APY history | live APY |
5305
- * |--------------|----------------|-------------|-------------|------------|
5306
- * | aave-v3 | aToken supply | underlying | Aave API | on-chain |
5307
- * | compound-v3 | Comet supply | underlying | CoinPool | newest row |
5308
- * | spark* | totalAssets() | ERC-4626 | CoinPool | newest row |
5309
- * | morpho-v2 | totalAssets() | ERC-4626 | Morpho API | from API |
5310
- *
5311
- * Two entries in that last column are worth stating outright, because the app
5312
- * looks like it disagrees. The app derives EVERY protocol's live rate on-chain,
5313
- * each with its own formula; here only Aave does. That is not a shortcut taken
5314
- * blindly — CoinPool's history endpoint refreshes intraday and its newest row
5315
- * was checked against chain to six decimals for all three protocols that use it
5316
- * (see `fetchCoinPoolApy`). Aave is the one case where the API and the on-chain
5317
- * figure genuinely differ, so it is the one case that pays for the extra call.
5412
+ * This used to also carry the chain's USDC address and decimals, as the DEFAULT
5413
+ * underlying for a market whose own underlying could not be read. That default
5414
+ * is gone: every market's asset now comes from the market itself ({@link
5415
+ * MarketAsset}), and a market that cannot name its asset is reported unresolved
5416
+ * rather than assumed to be USDC. Keeping the fields around would invite exactly
5417
+ * the assumption they were removed for.
5418
+ */
5419
+ interface LendingChainInfo {
5420
+ chainId: number;
5421
+ }
5422
+ /** Endpoints {@link LendingProtocol.fetchApy} may call, injected so they stay configurable. */
5423
+ interface ApyEndpoints {
5424
+ coinPoolBaseUrl: string;
5425
+ aaveApiUrl: string;
5426
+ morphoApiUrl: string;
5427
+ }
5428
+ /**
5429
+ * Display name of a market's protocol family, derived from its `type`.
5318
5430
  *
5319
- * Protocols DECLARE their on-chain calls rather than making them, so every
5320
- * market on a chain still resolves in ONE Multicall3 round-trip regardless of
5321
- * how many protocols are involved — see the protocols module for why.
5431
+ * `type` is the one identifier that is always exact — it is what selects the
5432
+ * on-chain calls — whereas the market's `name` and `protocol` are display
5433
+ * strings whose form depends on where the market came from: discovery writes
5434
+ * "Aave v3" with a lowercase v, the catalogue passes through whatever
5435
+ * `/supply/v2` supplies, and a Morpho market's `name` is the VAULT's name
5436
+ * ("Gauntlet USDC Core"), not the protocol's.
5322
5437
  *
5323
- * Independent of {@link file://./MoralisService.ts}: these markets are curated by the
5324
- * CoinPool platform and an indexer neither knows the curated set nor the vault
5325
- * share → USDC conversion.
5438
+ * Returns null for a market kind with no label — an unknown `type` from the
5439
+ * catalogue, or a family added upstream after this table. Callers fall back to
5440
+ * the market's own strings rather than showing a guess.
5326
5441
  */
5327
- interface LendingServiceConfig {
5328
- /** Base URL of the CoinPool API. Defaults to `https://api.coinpool.app`. */
5329
- coinPoolBaseUrl?: string;
5330
- /** Aave v3 GraphQL endpoint (supply-APY history). */
5331
- aaveApiUrl?: string;
5332
- /** Morpho GraphQL endpoint (vault APY history + live net APY). */
5333
- morphoApiUrl?: string;
5334
- }
5335
- /** One curated USDC lending market. */
5442
+ declare function protocolLabelFor(type: string): string | null;
5443
+
5444
+ /**
5445
+ * The shapes every lending module agrees on, kept apart from the services that
5446
+ * produce them so `catalog`, `discovery` and `describe` can share them without
5447
+ * importing each other or the facade.
5448
+ */
5449
+
5450
+ /** One lending market — curated by CoinPool or discovered from its receipt token. */
5336
5451
  interface LendingMarket {
5337
5452
  /** Hex chain id the market lives on. */
5338
5453
  chain: string;
5339
- /** Display name, e.g. "Aave v3 USDC" / "Spark USDC Savings Vault". */
5454
+ /**
5455
+ * Display name of THIS MARKET, e.g. "Aave v3 USDC" / "Spark USDC Savings
5456
+ * Vault". For a Morpho market it is the vault's own name from Morpho's API
5457
+ * ("Gauntlet USDC Core") — the vault, not the protocol, which is why the app
5458
+ * link's slug is built from it.
5459
+ *
5460
+ * Not the protocol's name: use {@link protocolLabel} to title a market by the
5461
+ * protocol it belongs to.
5462
+ */
5340
5463
  name: string;
5341
- /** Protocol family, e.g. "AAVE" / "MORPHO". */
5464
+ /**
5465
+ * Protocol family as its SOURCE spells it — "AAVE" / "MORPHO" from discovery,
5466
+ * or whatever `/supply/v2` supplies for a curated market. Neither casing nor
5467
+ * wording is guaranteed, so prefer {@link protocolLabel} for display.
5468
+ */
5342
5469
  protocol: string;
5470
+ /**
5471
+ * Protocol family in the form a reader should see: "Aave V3", "Compound V3",
5472
+ * "Spark", "Morpho V2". Derived from {@link type}, the one identifier that is
5473
+ * always exact, so it is stable no matter whether the market was discovered
5474
+ * on chain or came from the catalogue.
5475
+ *
5476
+ * Null for a market kind with no known label — an unrecognised `type` from the
5477
+ * catalogue, or a family added upstream. Fall back to {@link name} /
5478
+ * {@link protocol} then, rather than showing nothing.
5479
+ */
5480
+ protocolLabel: string | null;
5343
5481
  /** Protocol app URL, when known. */
5344
5482
  protocolUrl: string | null;
5345
5483
  type: LendingProtocolType | string;
5346
- /** Pool / vault contract — where a supply goes. */
5484
+ /**
5485
+ * Pool / vault contract — where a supply goes.
5486
+ *
5487
+ * One exception: `spark-l2-susds` markets are read-only and have no vault on
5488
+ * their chain, so this holds the SSR oracle they are read through.
5489
+ */
5347
5490
  contract: string;
5348
5491
  /** Receipt token holding the user's balance (aToken, Comet, vault share). */
5349
5492
  token: string;
5493
+ /**
5494
+ * Underlying asset ADDRESS, supplied when the market cannot name it on chain.
5495
+ *
5496
+ * Normally absent: a market's asset is read from its own contract at describe
5497
+ * time ({@link LendingProtocol.underlyingCall}), which is the only source that
5498
+ * cannot go stale. This exists for the one family with no such accessor —
5499
+ * cross-chain sUSDS, whose asset comes from PSM3 during discovery — so the
5500
+ * answer is carried forward rather than re-derived or guessed.
5501
+ *
5502
+ * Deliberately NOT named `asset`: {@link LendingMarketOverview.asset} is the
5503
+ * resolved object (address + decimals + symbol + logo), and this is only the
5504
+ * raw input to it. Decimals and symbol are still read on chain from this
5505
+ * address, so nothing here bypasses the checks that suppress a mis-scaled
5506
+ * amount.
5507
+ */
5508
+ assetAddress?: string;
5350
5509
  /**
5351
5510
  * CoinPool's balanced score for the market, 0–10 (higher is better) — weighs
5352
- * protocol safety, market size and yield. Null when the market is unscored.
5511
+ * protocol safety, market size and yield. Null when the market is unscored,
5512
+ * which every DISCOVERED market is: the score exists only in the catalogue.
5353
5513
  */
5354
5514
  platformScore: number | null;
5355
5515
  }
@@ -5361,7 +5521,36 @@ interface ApyPoint {
5361
5521
  }
5362
5522
  /** A lending market plus its live rate and size — what you'd compare before supplying. */
5363
5523
  interface LendingMarketOverview extends LendingMarket {
5364
- /** Total USDC supplied to this market by everyone (market size). */
5524
+ /**
5525
+ * The asset this market lends, read on chain. Most curated markets are USDC;
5526
+ * those on WETH / wstETH / other assets report their own here.
5527
+ *
5528
+ * Always consult this before rendering an amount: {@link totalSuppliedUsdc} and
5529
+ * {@link LendingSupplyPosition.suppliedUsdc} are denominated in THIS asset, not
5530
+ * necessarily in USDC, and labelling a WETH figure "USDC" is worse than showing
5531
+ * no label at all.
5532
+ */
5533
+ asset: {
5534
+ address: string;
5535
+ decimals: number;
5536
+ /** ERC-20 symbol, when it could be read. Null otherwise — never guessed. */
5537
+ symbol: string | null;
5538
+ /**
5539
+ * Icon URL for the underlying, from Pantograph's token metadata. Null when
5540
+ * the asset is unresolved, unknown to Pantograph, or the lookup failed — it
5541
+ * is cosmetic, so it never blocks or delays the rest of the description.
5542
+ *
5543
+ * The UNDERLYING's icon, not the receipt token's: a withdraw form shows what
5544
+ * the user receives (USDC, WETH), which is a different image from the
5545
+ * aToken / vault share they hold.
5546
+ */
5547
+ logo: string | null;
5548
+ };
5549
+ /**
5550
+ * Total supplied to this market by everyone (market size), denominated in
5551
+ * {@link asset} — despite the name, which predates non-USDC support and is
5552
+ * kept so existing callers keep compiling.
5553
+ */
5365
5554
  totalSuppliedUsdc: number | null;
5366
5555
  /** Mean of {@link apyHistory} — the headline APY. Null when history is unavailable. */
5367
5556
  avgApyPercent: number | null;
@@ -5374,129 +5563,142 @@ interface LendingMarketOverview extends LendingMarket {
5374
5563
  }
5375
5564
  /** A wallet's live supply position in one lending market. */
5376
5565
  interface LendingSupplyPosition extends LendingMarketOverview {
5377
- /** Supplied USDC, receipt-token balance converted to underlying. */
5566
+ /** Supplied amount, receipt-token balance converted to the underlying {@link asset}. */
5378
5567
  suppliedUsdc: number;
5379
5568
  /** `suppliedUsdc × avgApyPercent` — projected yearly earnings at the average rate. */
5380
5569
  estimatedAnnualYieldUsdc: number | null;
5381
5570
  }
5382
- declare class LendingService {
5383
- private readonly coinPoolBaseUrl;
5384
- /** Passed to each protocol's `fetchApy`, so endpoints stay configurable. */
5385
- private readonly apiEndpoints;
5386
- /** Shared across chains, so a whole-catalogue scan stays within the cap. */
5571
+ /** Endpoint overrides shared by every lending service. */
5572
+ interface LendingServiceConfig {
5573
+ /** Base URL of the CoinPool API. Defaults to `https://api.coinpool.app`. */
5574
+ coinPoolBaseUrl?: string;
5575
+ /** Aave v3 GraphQL endpoint (supply-APY history). */
5576
+ aaveApiUrl?: string;
5577
+ /** Morpho GraphQL endpoint (vault APY history + live net APY). */
5578
+ morphoApiUrl?: string;
5579
+ }
5580
+
5581
+ /**
5582
+ * The description pipeline: markets in, markets WITH their asset, size and APY
5583
+ * out. Protocol-agnostic by design — it knows about no protocol by name, only
5584
+ * about the calls each one declares (see `protocols.ts`).
5585
+ *
5586
+ * This is the half both services share. Reading a wallet's positions and listing
5587
+ * the supply catalogue ask the same question of a market once it is identified,
5588
+ * so asking it lives here rather than in either service.
5589
+ *
5590
+ * Everything is batched per chain: twenty markets across four protocols still
5591
+ * cost one multicall for their sizes and live rates, plus at most one follow-up
5592
+ * round for the rates that are a function of it.
5593
+ */
5594
+
5595
+ /** A receipt-token balance awaiting conversion to its underlying. */
5596
+ interface HeldBalance {
5597
+ market: LendingMarket;
5598
+ /** Receipt-token balance (shares for a vault, underlying for aToken/Comet). */
5599
+ rawBalance: bigint;
5600
+ /** Receipt-token `decimals()`, null when the call failed. */
5601
+ tokenDecimals: number | null;
5602
+ }
5603
+ /**
5604
+ * Describes markets on one chain, sharing an APY concurrency budget across every
5605
+ * call it makes. One instance per service, so a whole-catalogue scan and a
5606
+ * wallet read never together exceed the cap.
5607
+ */
5608
+ declare class MarketDescriber {
5609
+ private readonly endpoints;
5387
5610
  private readonly apyLimiter;
5388
- constructor(config?: LendingServiceConfig);
5389
- /** Hex chain ids with USDC lending markets (intersected with the active set). */
5390
- listSupportedChains(): string[];
5391
- /** True when the given chain (any alias / hex / decimal form) has lending markets. */
5392
- isSupported(chain?: string | null): boolean;
5393
- /**
5394
- * Every curated USDC lending market on a chain. Empty when the chain has none
5395
- * or the API is unreachable — never throws.
5396
- */
5397
- getMarkets(chain: string): Promise<LendingMarket[]>;
5398
- /** The USDC a supply on this chain moves. Null when the chain has no markets. */
5399
- getUsdc(chain: string): {
5400
- address: string;
5401
- decimals: number;
5402
- } | null;
5403
5611
  /**
5404
- * The receipt token a supply into `market` credits — its own ERC-20 symbol and
5405
- * decimals, read on chain in one multicall.
5406
- *
5407
- * This is what "Est. Received" is denominated in, and it is NOT the underlying:
5408
- * Aave's is `aBasUSDC`, Compound's is `cUSDCv3`, and Spark's Base vault is
5409
- * `sUSDC` with **18** decimals against USDC's 6. Scaling a share figure by the
5410
- * asset's decimals overstates it by 10^12, so the form needs these to render a
5411
- * correct number and an honest label.
5412
- *
5413
- * Resolved here, once, when the supply payload is built — the form is a pure
5414
- * renderer and must never go to chain just to display what it was handed.
5415
- *
5416
- * Both fields are independently null when their call failed or decoded
5417
- * implausibly; the caller then falls back to the underlying's metadata rather
5418
- * than blocking a supply over a display detail.
5612
+ * Token metadata source for the underlying's ICON — the one thing about the
5613
+ * asset that is not on chain. Cosmetic only: every failure path here leaves
5614
+ * `logo: null` and changes nothing else about the description.
5419
5615
  */
5420
- readReceiptToken(chain: string, market: Pick<LendingMarket, 'token' | 'type'>): Promise<{
5421
- symbol: string | null;
5422
- decimals: number | null;
5423
- isUnderlying: boolean;
5424
- }>;
5616
+ private readonly pantograph;
5617
+ constructor(endpoints: ApyEndpoints);
5425
5618
  /**
5426
- * Resolve ONE market on a chain from a free-text reference — the market name,
5427
- * the protocol, or the contract address — for the supply flow, which needs a
5428
- * single unambiguous target rather than a ranked list.
5619
+ * Attach market size and the APY series to each market — one batched on-chain
5620
+ * read plus one API call per market. Order is preserved, so callers can zip
5621
+ * the result with their own per-market data. Never throws.
5429
5622
  *
5430
- * Returns every close match rather than guessing when the reference is
5431
- * ambiguous ("Morpho" on a chain with several Morpho vaults): depositing into
5432
- * the wrong vault is not something the user can undo, so the caller asks
5433
- * instead of picking. An exact name or contract match always wins outright.
5623
+ * Asset resolution comes FIRST and is awaited on its own: both the state read
5624
+ * (which reserve to quote, which decimals to scale by) and the APY fetch
5625
+ * (which reserve's history to ask for) are parameterised by it, so they cannot
5626
+ * be started until it lands. That is one extra round-trip per chain, batched
5627
+ * across every market — the price of describing a market in its own asset
5628
+ * rather than assuming the chain's USDC.
5434
5629
  */
5435
- findMarket(chain: string, reference: string): Promise<LendingMarket[]>;
5630
+ describe(chain: string, info: LendingChainInfo, markets: LendingMarket[]): Promise<LendingMarketOverview[]>;
5436
5631
  /**
5437
- * Size + APY for markets already resolved by {@link findMarket}, so the supply
5438
- * flow can quote a rate without re-listing (and re-pricing) the whole chain.
5439
- * Returns them in the order given; empty when the chain is unsupported.
5632
+ * Every market's receipt-token balance + decimals in one batch, narrowed to the
5633
+ * markets the wallet actually holds something in — the step that decides how
5634
+ * much further work the rest of the flow has to do.
5440
5635
  */
5441
- describeResolvedMarkets(chain: string, markets: LendingMarket[]): Promise<LendingMarketOverview[]>;
5636
+ readBalances(chain: string, address: string, markets: LendingMarket[]): Promise<HeldBalance[]>;
5442
5637
  /**
5443
- * Every curated market on `chains`, each with its size and APY — the "where
5444
- * can I supply USDC?" view. Highest average APY first, unrated markets last.
5638
+ * Each held balance in its market's own underlying, aligned with `held`. A
5639
+ * protocol whose receipt token is an ERC-4626 share declares a
5640
+ * `convertToAssets` call; one whose balance is already underlying declares
5641
+ * none. As with {@link readMarketState}, every conversion across every protocol
5642
+ * shares ONE multicall.
5445
5643
  *
5446
- * Chains are queried in parallel and contribute independently: a chain whose
5447
- * API or RPC fails yields nothing rather than failing the whole call.
5448
- */
5449
- getMarketOverviews(params: {
5450
- chains: readonly string[];
5451
- }): Promise<LendingMarketOverview[]>;
5452
- /**
5453
- * Every lending market the wallet currently supplies to, across `chains`,
5454
- * highest supplied amount first. Same parallelism and failure isolation as
5455
- * {@link getMarketOverviews}; positions worth less than {@link DUST_USDC} are
5456
- * dropped as withdrawal residue.
5644
+ * A vault whose conversion reverts falls back to the raw balance in the share
5645
+ * token's own decimals — an approximation that beats dropping the position
5646
+ * outright.
5647
+ *
5648
+ * `assets[i]` carries the decimals to scale by; a market whose asset could not
5649
+ * be resolved has NaN decimals and yields 0, so an unscalable balance is
5650
+ * dropped as dust rather than reported at the wrong magnitude.
5457
5651
  */
5458
- getSupplyPositions(params: {
5459
- address: string;
5460
- chains: readonly string[];
5461
- }): Promise<LendingSupplyPosition[]>;
5462
- /** Supply positions on ONE chain: market list → balances → supplied amount + overview. */
5463
- private positionsForChain;
5652
+ convertToUnderlying(chain: string, held: HeldBalance[], assets: Array<LendingMarketOverview['asset']>): Promise<number[]>;
5464
5653
  /**
5465
- * Attach market size and the APY series to each market — one batched on-chain
5466
- * read plus one API call per market, both at once. Order is preserved, so
5467
- * callers can zip the result with their own per-market data. Never throws.
5654
+ * The asset each market lends, aligned with `markets`, in three batched rounds:
5655
+ * ask every market for its underlying, then ask every distinct underlying for
5656
+ * its `decimals()` and `symbol()`, then ask Pantograph for those same
5657
+ * underlyings' ICONS — the only part of the asset that is not on chain, and the
5658
+ * only round that is allowed to fail without consequence.
5659
+ *
5660
+ * The market is the ONLY source consulted. There used to be a per-chain USDC
5661
+ * fallback for a market whose accessor was missing or reverted, and it was
5662
+ * wrong in exactly the cases it fired: a market that fails to name its asset is
5663
+ * not thereby a USDC market, and calling it one attributes a WETH or DAI size
5664
+ * to the wrong token with the wrong decimals. An unresolvable asset is now
5665
+ * reported unresolved (NaN decimals), which suppresses the size instead of
5666
+ * misstating it — the same treatment a chain with no curated USDC always got.
5667
+ *
5668
+ * This is also what lets a market lend anything at all: nothing here knows or
5669
+ * cares which asset a chain's "real" stablecoin is.
5468
5670
  */
5469
- private describeMarkets;
5671
+ private resolveAssets;
5672
+ /** `decimals()` + `symbol()` for each distinct asset address, in one multicall. */
5673
+ private readAssetMetadata;
5470
5674
  /**
5471
- * Every market's receipt-token balance + decimals in one batch, narrowed to the
5472
- * markets the wallet actually holds something in — the step that decides how
5473
- * much further work the rest of the flow has to do.
5675
+ * Icon URL for each distinct asset address, from Pantograph's token metadata —
5676
+ * one request for the whole set.
5677
+ *
5678
+ * Purely cosmetic, and treated as such throughout: an unknown token, a chain
5679
+ * Pantograph does not index, or an outright failure all yield an EMPTY map, so
5680
+ * the assets come back with `logo: null` and every number in the description is
5681
+ * exactly what it would have been without this call. `getTokensMetadata`
5682
+ * already swallows its own errors; the catch is for the unexpected.
5474
5683
  */
5475
- private readBalances;
5684
+ private fetchAssetLogos;
5476
5685
  /**
5477
- * On-chain state of each market, in ONE batch, aligned with `markets`: its size
5478
- * and — for Aave alone — its live supply rate.
5686
+ * On-chain state of each market, aligned with `markets`: its size and its live
5687
+ * supply rate.
5479
5688
  *
5480
5689
  * This is where the batching lives. Each market's protocol only DECLARES the
5481
- * calls it wants ({@link LendingProtocol.sizeCall}, {@link LendingProtocol.liveRateCall});
5482
- * they are pooled here into a single multicall, and each protocol then decodes
5483
- * its own slice of the result. Twenty markets across four protocols still cost
5484
- * one RPC round-trip.
5690
+ * calls it wants (`sizeCall`, `liveRateCall`); they are pooled here into a
5691
+ * single multicall, and each protocol then decodes its own slice of the result.
5692
+ *
5693
+ * Compound and Spark need a SECOND call that depends on the first's answer
5694
+ * (`getSupplyRate` of the utilization just read; `getAPR` on the rate provider
5695
+ * just named), so a second round follows when any market asks for one. Those
5696
+ * follow-ups are batched together too — two round-trips per chain at worst,
5697
+ * never two per market.
5485
5698
  *
5486
5699
  * Either field is null when its call failed or decoded implausibly.
5487
5700
  */
5488
5701
  private readMarketState;
5489
- /**
5490
- * Each held balance as USDC, aligned with `held`. A protocol whose receipt
5491
- * token is an ERC-4626 share declares a `convertToAssets` call; one whose
5492
- * balance is already underlying declares none. As with {@link readMarketState},
5493
- * every conversion across every protocol shares ONE multicall.
5494
- *
5495
- * A vault whose conversion reverts falls back to the raw balance in the share
5496
- * token's own decimals — an approximation that beats dropping the position
5497
- * outright.
5498
- */
5499
- private convertToUnderlying;
5500
5702
  /**
5501
5703
  * Historical supply-APY samples for one market, from whichever upstream its
5502
5704
  * protocol queries, plus that source's own live rate where it reports one.
@@ -5506,39 +5708,516 @@ declare class LendingService {
5506
5708
  * the fetch itself. Never throws: an unreachable source yields no samples, so
5507
5709
  * the market is still listed, just without APY.
5508
5710
  */
5509
- private fetchApySamples;
5711
+ private fetchApy;
5510
5712
  }
5511
5713
 
5512
- type LendingMarketsToolConfig = LendingServiceConfig;
5513
- /** How the list is ordered. Mirrors the `sort` parameter. */
5514
- type SortKey = 'apy' | 'score' | 'size';
5515
5714
  /**
5516
- * Tool: get-lending-markets
5715
+ * Reading lending markets — **every asset, every chain**, and every protocol the
5716
+ * probes can recognise (see the caveat under "What this does NOT cover").
5517
5717
  *
5518
- * The USDC lending markets a user CAN supply to — the catalogue side of the
5519
- * lending domain, as opposed to `get-wallet-lending-positions` which reports
5520
- * what a wallet already supplies. Each market carries its size, the protocol's
5521
- * live supply APY — the rate the list is ranked on, and the one a depositor is
5522
- * quoted today — and the average over the last week as a stability check on it.
5718
+ * This is the half the Keyring app consumes. The app already knows what a wallet
5719
+ * holds: its token API returns each row with `yieldProtocol` / `yieldAsset`
5720
+ * tags, and {@link file://./yieldTokenValue.ts} converts vault shares to
5721
+ * underlying for the USD figure. What the app cannot get from a token list is
5722
+ * everything ABOUT the market behind a receipt token — its name, its protocol,
5723
+ * the rate it pays, how large it is. That is what this service supplies.
5523
5724
  *
5524
- * See {@link file://../../../services/LendingService.ts} for the data sources.
5725
+ * ## Why this is separate from supplying
5726
+ *
5727
+ * Supplying is narrow on purpose: only the markets CoinPool curates, and only the
5728
+ * protocol families the FE can encode a deposit for. Those limits come from the
5729
+ * write path and have nothing to do with reading.
5730
+ *
5731
+ * A wallet, meanwhile, can hold any receipt token at all — aWETH on Base, an
5732
+ * uncurated Morpho vault, a receipt from a chain `/supply/v2` does not cover.
5733
+ * Each of those describes its own market on chain, so each is readable. Gating a
5734
+ * read on the supply catalogue would make a position the user genuinely holds
5735
+ * vanish from the app for a reason that belongs to a different feature, so this
5736
+ * service applies NO catalogue restriction and NO chain restriction.
5737
+ *
5738
+ * ## What this does NOT cover
5739
+ *
5740
+ * The one real limit is the SHAPE of the receipt token, and it is worth stating
5741
+ * plainly because "reads everything" is the easy thing to assume here.
5742
+ *
5743
+ * {@link file://./discovery.ts} identifies a token by the accessor only its
5744
+ * family implements, and it probes three: Aave v3's `POOL()` +
5745
+ * `UNDERLYING_ASSET_ADDRESS()`, Compound v3's `baseToken()`, and ERC-4626's
5746
+ * `asset()`. A token answering none of them returns null — so Aave **v2**
5747
+ * (`LENDING_POOL()`), Compound **v2** (cToken `underlying()`), and any other
5748
+ * non-4626 design are NOT seen. Verified: `aUSDC` (v2) and `cDAI` (v2) both
5749
+ * resolve to null, while `sDAI` (a genuine 4626) resolves.
5750
+ *
5751
+ * That null is indistinguishable from "this is a plain ERC-20", so an unseen
5752
+ * protocol fails INVISIBLY rather than loudly — no error, the position simply
5753
+ * does not appear. Widening coverage means adding a probe in `discovery.ts`, not
5754
+ * adding a class in `protocols.ts`.
5755
+ *
5756
+ * Note the asymmetry with the catalogue path: a market that arrives from
5757
+ * `/supply/v2` with an unrecognised `type` still gets described, because
5758
+ * `protocolFor` falls back to generic ERC-4626 handling. Only the probe path
5759
+ * drops what it cannot identify.
5760
+ *
5761
+ * ## Chain first, catalogue second
5762
+ *
5763
+ * Identification happens ON CHAIN: a receipt token answers the accessor only its
5764
+ * family implements, so the market behind it is derivable without asking anyone.
5765
+ * That puts curated and uncurated markets on the SAME path. Under catalogue-first,
5766
+ * Base USDC was resolved by an endpoint while Base WETH was resolved by a probe,
5767
+ * so the two could disagree and only one was exercised in testing.
5768
+ *
5769
+ * `/supply/v2` is therefore NOT consulted on this path at all: it defines which
5770
+ * markets can be supplied to, and reading has no business paying for it. The
5771
+ * catalogue would only have contributed cosmetics anyway — a curated display
5772
+ * name, a platform score, a market deep link — so a market read here carries the
5773
+ * name and protocol chain reports. Every number is identical either way.
5774
+ *
5775
+ * (The supply-POSITIONS path below is different, and still catalogue-driven: it
5776
+ * answers "what did the user supply to a curated market", which is a question
5777
+ * about the catalogue by definition.)
5778
+ *
5779
+ * APY history is unaffected — Compound and generic 4626 markets read theirs from
5780
+ * `/supply/rates/history`, a different endpoint, queried per market.
5781
+ *
5782
+ * See {@link file://./LendingSupplyService.ts} for the write path, and
5783
+ * {@link file://./describe.ts} for the pipeline both share.
5525
5784
  */
5526
- declare class LendingMarketsTool extends BaseTool {
5527
- name: string;
5528
- description: string;
5529
- category: string;
5530
- parameters: ToolParameter[];
5531
- private service;
5532
- constructor(config?: LendingMarketsToolConfig);
5533
- protected run(args: Record<string, unknown>, userContext?: UserContext): Promise<{
5534
- _instructions: string;
5535
- requestedProtocol: string;
5536
- protocolSupported: boolean;
5537
- supportedProtocols: string[];
5538
- marketCount: number;
5539
- markets: never[];
5540
- } | {
5541
- _instructions: string;
5785
+
5786
+ declare class LendingReadService {
5787
+ private readonly coinPoolBaseUrl;
5788
+ private readonly endpoints;
5789
+ private readonly describer;
5790
+ constructor(coinPoolBaseUrl: string, endpoints: ApyEndpoints, describer: MarketDescriber);
5791
+ /**
5792
+ * Describe the markets behind a wallet's RECEIPT TOKENS — the app's entry
5793
+ * point. Given the yield-bearing token addresses the app already has, returns
5794
+ * each one's market with its asset, size, live APY and weekly average.
5795
+ *
5796
+ * Keyed by the LOWERCASED token address, with an entry only for tokens that
5797
+ * resolved: a token that identifies itself as no lending receipt is simply
5798
+ * absent, which is the honest answer rather than a null the caller must filter.
5799
+ *
5800
+ * Batched end to end, which is the point of taking a list rather than one
5801
+ * token: identifying five vault shares costs the same two multicalls as
5802
+ * identifying one, and describing them shares a third. Calling
5803
+ * {@link findMarketByReceiptToken} five times instead would cost roughly five
5804
+ * times as much.
5805
+ *
5806
+ * Works on any chain the RPC layer serves, curated or not. Never throws.
5807
+ *
5808
+ * @param rpcUrl Optional endpoint for `chain`, installed as this core's
5809
+ * override before the read — see {@link registerRpcUrl}. Pass it for any chain
5810
+ * this core carries no definition for; omit it to use the resolved defaults.
5811
+ */
5812
+ describeReceiptTokens(chain: string, tokens: readonly string[], rpcUrl?: string): Promise<Map<string, LendingMarketOverview>>;
5813
+ /**
5814
+ * The market ONE receipt token belongs to — "the user holds this aToken /
5815
+ * Comet / vault share; which market is it?" — described with its size and APY.
5816
+ *
5817
+ * A thin wrapper over {@link describeReceiptTokens}; prefer that one whenever
5818
+ * you have more than a single token, since it batches. Null when the token
5819
+ * identifies itself as no lending receipt, or its market could not be
5820
+ * described. Never throws.
5821
+ *
5822
+ * @param rpcUrl Optional endpoint for `chain` — see {@link describeReceiptTokens}.
5823
+ */
5824
+ findMarketByReceiptToken(chain: string, receiptToken: string, rpcUrl?: string): Promise<LendingMarketOverview | null>;
5825
+ /**
5826
+ * Every market on `chains` the wallet currently supplies to, highest supplied
5827
+ * amount first.
5828
+ *
5829
+ * Scoped to the CURATED catalogue — this walks `/supply/v2`'s markets and
5830
+ * checks the wallet's balance in each, so it reports what the CoinPool product
5831
+ * covers, on whichever chains it covers them (asked, never assumed). A wallet
5832
+ * holding a receipt token from outside that set is not found here;
5833
+ * {@link describeReceiptTokens} is the entry point for those, since it starts
5834
+ * from tokens the caller already knows about rather than from a catalogue to
5835
+ * scan.
5836
+ *
5837
+ * Any asset, not just USDC: each market's own underlying decides what its
5838
+ * balance is denominated in, and {@link LendingSupplyPosition.asset} reports it.
5839
+ *
5840
+ * Chains are queried in parallel and contribute independently: a chain whose
5841
+ * API or RPC fails yields nothing rather than failing the whole call.
5842
+ * Positions worth less than {@link DUST_USDC} are dropped as withdrawal residue.
5843
+ */
5844
+ getSupplyPositions(params: {
5845
+ address: string;
5846
+ chains: readonly string[];
5847
+ }): Promise<LendingSupplyPosition[]>;
5848
+ /** Size + APY for markets already resolved elsewhere, in the order given. */
5849
+ describeResolvedMarkets(chain: string, markets: LendingMarket[]): Promise<LendingMarketOverview[]>;
5850
+ /** Supply positions on ONE chain: market list → balances → supplied amount + overview. */
5851
+ private positionsForChain;
5852
+ }
5853
+
5854
+ /**
5855
+ * Supplying — the WRITE path, and the narrower of the two.
5856
+ *
5857
+ * TWO limits define it, and both are stated here rather than scattered across
5858
+ * the tools that enforce them:
5859
+ *
5860
+ * 1. **Curated markets only.** `/supply/v2` is what says a market exists to
5861
+ * deposit into. A market discovered on chain is readable but not suppliable:
5862
+ * nobody curated it, nobody scored it, and it was never checked.
5863
+ * 2. **Encodable protocols only** — {@link SUPPLIABLE_TYPES}. The deposit call
5864
+ * differs per family, so a market outside this set has no correct calldata
5865
+ * and would fail at signing, AFTER the user had already approved the asset
5866
+ * to it. That is the worst possible failure point, which is why the check
5867
+ * lives in the service rather than at the edge.
5868
+ *
5869
+ * There is no third limit any more. Supplying used to be pinned to five hardcoded
5870
+ * chains and to USDC; both are now consequences of limit 1 rather than rules of
5871
+ * their own — the chains are whichever ones the catalogue answers for
5872
+ * ({@link listChains}), and the asset is whatever each market's own underlying
5873
+ * turns out to be. Neither is declared in this repository, so CoinPool adding a
5874
+ * chain or a non-USDC market needs no code change here.
5875
+ *
5876
+ * Those limits belong to supplying alone. Reading is wider still — no catalogue
5877
+ * and no chain set at all — see {@link file://./LendingReadService.ts}.
5878
+ *
5879
+ * As with everything in this core, no transaction is built or signed here: this
5880
+ * resolves and validates a market, and the FE owns the allowance check, the
5881
+ * per-protocol encoding and the signing.
5882
+ */
5883
+
5884
+ /**
5885
+ * The protocol families the FE can encode a deposit for. A market whose `type`
5886
+ * falls outside this set is refused rather than sent to the form.
5887
+ *
5888
+ * NOTE this is narrower than the set of types the READ path handles: reading
5889
+ * falls back to generic ERC-4626 for an unrecognised type, which is right for
5890
+ * describing a market and wrong for depositing into one, where a guess costs the
5891
+ * user their approval.
5892
+ */
5893
+ declare const SUPPLIABLE_TYPES: readonly SupplyProtocolType[];
5894
+ /** A market that passed every supply check — {@link LendingSupplyService.canSupply}. */
5895
+ interface SuppliableMarket extends LendingMarket {
5896
+ type: SupplyProtocolType;
5897
+ }
5898
+ declare class LendingSupplyService {
5899
+ private readonly coinPoolBaseUrl;
5900
+ constructor(coinPoolBaseUrl: string);
5901
+ /**
5902
+ * Hex chain ids a supply can target — the chains the catalogue actually
5903
+ * answers for, asked at call time rather than read from a table.
5904
+ */
5905
+ listChains(): Promise<string[]>;
5906
+ /** True when a chain (any alias / hex / decimal form) can be supplied on. */
5907
+ isSupported(chain?: string | null): Promise<boolean>;
5908
+ /** Every curated market on a chain. Empty when the chain has none. */
5909
+ getMarkets(chain: string): Promise<LendingMarket[]>;
5910
+ /**
5911
+ * Resolve ONE market on a chain from a free-text reference — the market name,
5912
+ * the protocol, or the contract address.
5913
+ *
5914
+ * Returns every close match rather than guessing when the reference is
5915
+ * ambiguous ("Morpho" on a chain with several Morpho vaults): depositing into
5916
+ * the wrong vault is not reversible, so the caller asks instead of picking.
5917
+ */
5918
+ findMarket(chain: string, reference: string): Promise<LendingMarket[]>;
5919
+ /**
5920
+ * Whether a deposit into this market can actually be encoded — the last gate
5921
+ * before a form opens. Narrows the type as it answers, so a caller that passes
5922
+ * this has a {@link SuppliableMarket} rather than a market with a string type.
5923
+ */
5924
+ canSupply(market: LendingMarket): market is SuppliableMarket;
5925
+ /**
5926
+ * The receipt token a supply into `market` credits — its own ERC-20 symbol and
5927
+ * decimals, read on chain in one multicall.
5928
+ *
5929
+ * This is what "Est. Received" is denominated in, and it is NOT the underlying:
5930
+ * Aave's is `aBasUSDC`, Compound's is `cUSDCv3`, and Spark's Base vault is
5931
+ * `sUSDC` with **18** decimals against USDC's 6. Scaling a share figure by the
5932
+ * asset's decimals overstates it by 10^12, so the form needs these to render a
5933
+ * correct number and an honest label.
5934
+ *
5935
+ * Resolved here, once, when the supply payload is built — the form is a pure
5936
+ * renderer and must never go to chain just to display what it was handed.
5937
+ *
5938
+ * Both fields are independently null when their call failed or decoded
5939
+ * implausibly; the caller then falls back to the underlying's metadata rather
5940
+ * than blocking a supply over a display detail.
5941
+ */
5942
+ readReceiptToken(chain: string, market: Pick<LendingMarket, 'token' | 'type'>): Promise<{
5943
+ symbol: string | null;
5944
+ decimals: number | null;
5945
+ isUnderlying: boolean;
5946
+ }>;
5947
+ }
5948
+
5949
+ /**
5950
+ * Chain-id arithmetic for the lending module — a LEAF, importing nothing from
5951
+ * the rest of it.
5952
+ *
5953
+ * `chains.ts` is where "which chains can be supplied on?" is answered, and that
5954
+ * answer now comes from the catalogue, so `chains.ts` imports `catalog.ts`. The
5955
+ * catalogue in turn needs to parse a chain id before it can request one. These
5956
+ * two functions are what it needs and they depend on nothing, so they live here
5957
+ * rather than completing an import cycle.
5958
+ *
5959
+ * `chains.ts` re-exports both, so callers keep importing them from there.
5960
+ */
5961
+
5962
+ /**
5963
+ * Stands in for "this market's asset could not be established" — a sentinel,
5964
+ * never an address to read or approve.
5965
+ *
5966
+ * A market that cannot name its own underlying used to be attributed to the
5967
+ * chain's USDC. That was a guess, and a costly one on the supply path: the user
5968
+ * would approve and spend USDC against a market lending something else. There is
5969
+ * no chain-level asset to fall back to any more, so the resolver reports this
5970
+ * address with NaN decimals instead, which suppresses the market's size on the
5971
+ * read path and blocks the form on the write path.
5972
+ */
5973
+ declare const UNRESOLVED_ASSET = "0x0000000000000000000000000000000000000000";
5974
+
5975
+ /**
5976
+ * Which chains lending works on — and the distinction that runs through this
5977
+ * whole module: **reading is wider than supplying**.
5978
+ *
5979
+ * The two are not the same set and must never be conflated:
5980
+ *
5981
+ * - **Supply chains** — wherever CoinPool actually returns curated markets, asked
5982
+ * at runtime rather than declared here. `/supply/v2` is what says a market
5983
+ * exists; this module's job is to ASK it, not to predict its answer.
5984
+ * - **Read chains** — anywhere at all. A receipt token identifies its own market
5985
+ * on chain (see `discovery.ts`), so describing an aWETH position on a chain
5986
+ * CoinPool never heard of is perfectly possible. Reading is gated by what the
5987
+ * RPC layer supports, not by the supply catalogue.
5988
+ *
5989
+ * Gating a READ on the supply set is the bug this split exists to prevent: it
5990
+ * makes a position the user genuinely holds disappear from the app, for the
5991
+ * unrelated reason that nobody can deposit there through us.
5992
+ *
5993
+ * ## Why there is no chain table here any more
5994
+ *
5995
+ * There used to be a five-entry `SUPPLY_CHAINS` map, each with a hardcoded USDC
5996
+ * address. It was wrong in both directions: CoinPool adding a chain did nothing
5997
+ * until someone edited this file, and a market that lends something other than
5998
+ * USDC had no way to say so. Both facts already exist upstream — the chain list
5999
+ * is whatever `/supply/v2` answers for, and the asset is whatever the market's
6000
+ * own `underlyingCall` returns on chain — so both are read from there now.
6001
+ *
6002
+ * The candidate chains to ASK are the RPC layer's own active set
6003
+ * ({@link listCandidateChains}); a chain the core cannot reach has nothing to
6004
+ * offer a supply flow even if CoinPool lists it.
6005
+ *
6006
+ * Every function that consults the catalogue takes the CoinPool base URL, since
6007
+ * a host may point the core at its own deployment — there is no global default
6008
+ * hiding in here for the same reason there is no chain table.
6009
+ */
6010
+
6011
+ /**
6012
+ * The chains worth ASKING `/supply/v2` about — the RPC layer's active set.
6013
+ *
6014
+ * Not a claim that any of them has markets; that is what {@link listSupplyChains}
6015
+ * resolves. A chain the core has no RPC for is excluded because every downstream
6016
+ * step (market size, balances, receipt-token metadata) needs one.
6017
+ */
6018
+ declare function listCandidateChains(): string[];
6019
+ /**
6020
+ * Hex chain ids that currently have curated supply markets, discovered by asking
6021
+ * `/supply/v2` for every candidate chain in parallel.
6022
+ *
6023
+ * Live, not declared: a chain CoinPool adds shows up here with no code change,
6024
+ * and one it drops disappears. `catalog.ts` caches each chain's answer briefly,
6025
+ * so the repeated calls one turn makes cost a single round of requests.
6026
+ */
6027
+ declare function listSupplyChains(baseUrl: string): Promise<string[]>;
6028
+ /**
6029
+ * True when a chain (any alias / hex / decimal form) has curated supply markets
6030
+ * right now — asked, not assumed.
6031
+ */
6032
+ declare function isSupplyChain(baseUrl: string, chain?: string | null): Promise<boolean>;
6033
+
6034
+ /**
6035
+ * The lending domain, in one object — a facade over two services split by what
6036
+ * they are FOR.
6037
+ *
6038
+ * ## The split, and why it exists
6039
+ *
6040
+ * Reading and supplying want different things, and an earlier single class made
6041
+ * them share limits that belong to only one of them:
6042
+ *
6043
+ * - **{@link read} — {@link LendingReadService}. Every asset, every chain.**
6044
+ * What the Keyring app consumes. A wallet can hold any receipt token at all:
6045
+ * aWETH on Base, an uncurated Morpho vault, a receipt from a chain
6046
+ * `/supply/v2` never covered. Each of those describes its own market on chain,
6047
+ * so each is describable — provided its receipt token is one of the three
6048
+ * shapes the probes recognise (Aave v3 aToken, Comet, ERC-4626); Aave v2 and
6049
+ * Compound v2 are NOT among them. See that service's "What this does NOT
6050
+ * cover". The app already knows WHICH tokens a wallet
6051
+ * holds (its token API tags them `yieldProtocol` / `yieldAsset`, and
6052
+ * {@link file://./lending/yieldTokenValue.ts} values them); what it cannot get
6053
+ * from a token list is the market behind the token, which is what
6054
+ * {@link LendingReadService.describeReceiptTokens} answers — in one batch.
6055
+ *
6056
+ * - **{@link supply} — {@link LendingSupplyService}. Curated and encodable.**
6057
+ * Narrower on purpose, but along two axes only: `/supply/v2` decides a market
6058
+ * exists, and only the protocol families the FE can encode a deposit for may be
6059
+ * targeted. That second limit comes from the write path — a market with no
6060
+ * correct calldata fails at signing, after the user already approved the asset
6061
+ * to it. Neither the CHAIN nor the ASSET is limited here: the chains are
6062
+ * whichever ones the catalogue answers for, and each market's asset is read
6063
+ * from the market itself, so a non-USDC market supplies its own asset.
6064
+ *
6065
+ * Gating a READ on the supply set is the specific bug this split prevents — it
6066
+ * makes a position the user genuinely holds disappear from the app, for the
6067
+ * unrelated reason that nobody can deposit there through us.
6068
+ *
6069
+ * Both halves share one pipeline ({@link file://./lending/describe.ts}) and one
6070
+ * APY concurrency budget, so a wide scan stays polite to every upstream.
6071
+ *
6072
+ * ## Where the numbers come from
6073
+ *
6074
+ * A wallet's supplied balance is NOT read from an indexer: the receipt token
6075
+ * (aToken / Comet / ERC-4626 vault share) is read straight from chain through
6076
+ * Multicall3, so the number always matches what the app shows. Everything else
6077
+ * comes from the same sources the CoinPool web app itself uses — its
6078
+ * `useUsdcLendingData` hook, in the SEPARATE `coinpool-v2` repository
6079
+ * (`src/hooks/useUsdcLendingData.ts`), is the reference this service was checked
6080
+ * against protocol by protocol:
6081
+ *
6082
+ * - market list ................. CoinPool `GET /supply/v2?chainId=…`
6083
+ * - supply-APY history ......... Aave v3 GraphQL (`aave-v3`),
6084
+ * Morpho GraphQL (`morpho-v2`),
6085
+ * CoinPool `GET /supply/rates/history` (rest)
6086
+ * - supplied amount / market size on-chain via Multicall3
6087
+ *
6088
+ * Reported APY is the AVERAGE of the daily supply-APY samples of the last
6089
+ * `APY_HISTORY_DAYS` days plus the live rate — a spot rate swings with borrow
6090
+ * demand, so an average is what a supplier actually earns.
6091
+ *
6092
+ * ## Protocols differ; the pipeline does not
6093
+ *
6094
+ * The market kinds disagree on every input: where the market size lives, whether
6095
+ * the receipt token is 1:1 with USDC or an ERC-4626 share, which API knows the
6096
+ * rate history, and whether a live rate has to come off-chain. Each kind is a
6097
+ * class in {@link file://./lending/protocols.ts}; the pipeline drives them and
6098
+ * knows about no protocol by name.
6099
+ *
6100
+ * | | market size | balance | APY history | live APY |
6101
+ * |--------------|----------------|-------------|-------------|------------|
6102
+ * | aave-v3 | aToken supply | underlying | Aave API | on-chain |
6103
+ * | compound-v3 | Comet supply | underlying | CoinPool | newest row |
6104
+ * | spark* | totalAssets() | ERC-4626 | CoinPool | newest row |
6105
+ * | morpho-v2 | totalAssets() | ERC-4626 | Morpho API | from API |
6106
+ *
6107
+ * Two entries in that last column are worth stating outright, because the app
6108
+ * looks like it disagrees. The app derives EVERY protocol's live rate on-chain,
6109
+ * each with its own formula; here only Aave does. That is not a shortcut taken
6110
+ * blindly — CoinPool's history endpoint refreshes intraday and its newest row
6111
+ * was checked against chain to six decimals for all three protocols that use it.
6112
+ * Aave is the one case where the API and the on-chain figure genuinely differ,
6113
+ * so it is the one case that pays for the extra call.
6114
+ *
6115
+ * Protocols DECLARE their on-chain calls rather than making them, so every
6116
+ * market on a chain still resolves in ONE Multicall3 round-trip regardless of
6117
+ * how many protocols are involved — see the protocols module for why.
6118
+ *
6119
+ * Independent of {@link file://./MoralisService.ts}: these markets are curated
6120
+ * by the CoinPool platform and an indexer neither knows the curated set nor the
6121
+ * vault share → USDC conversion.
6122
+ */
6123
+ declare class LendingService {
6124
+ /** Reading: every asset, every chain; Aave v3 / Comet / ERC-4626 receipt shapes. */
6125
+ readonly read: LendingReadService;
6126
+ /** Supplying: curated markets and encodable protocols only — any chain, any asset. */
6127
+ readonly supply: LendingSupplyService;
6128
+ constructor(config?: LendingServiceConfig);
6129
+ /** Hex chain ids with curated supply markets, as the catalogue reports them now. */
6130
+ listSupportedChains(): Promise<string[]>;
6131
+ /** True when the given chain (any alias / hex / decimal form) can be supplied on. */
6132
+ isSupported(chain?: string | null): Promise<boolean>;
6133
+ /** Every curated market on a chain. Empty when it has none; never throws. */
6134
+ getMarkets(chain: string): Promise<LendingMarket[]>;
6135
+ /** Resolve markets on a chain from a name, protocol or contract address. */
6136
+ findMarket(chain: string, reference: string): Promise<LendingMarket[]>;
6137
+ /** Whether a deposit into this market can be encoded by the FE. */
6138
+ canSupply(market: LendingMarket): boolean;
6139
+ /** ERC-20 symbol + decimals of the receipt token a supply credits. */
6140
+ readReceiptToken(chain: string, market: Pick<LendingMarket, 'token' | 'type'>): Promise<{
6141
+ symbol: string | null;
6142
+ decimals: number | null;
6143
+ isUnderlying: boolean;
6144
+ }>;
6145
+ /**
6146
+ * Describe the markets behind a wallet's receipt tokens, batched. The app's
6147
+ * entry point for showing assets other than USDC — see
6148
+ * {@link LendingReadService.describeReceiptTokens}.
6149
+ *
6150
+ * @param rpcUrl Optional endpoint for `chain`, installed as this core's RPC
6151
+ * override before the read. Pass the host's own endpoint for any chain this
6152
+ * core carries no definition for — without one the read comes back empty as
6153
+ * though the token were a plain ERC-20.
6154
+ */
6155
+ describeReceiptTokens(chain: string, tokens: readonly string[], rpcUrl?: string): Promise<Map<string, LendingMarketOverview>>;
6156
+ /**
6157
+ * The market ONE receipt token belongs to. Prefer {@link describeReceiptTokens} for several.
6158
+ *
6159
+ * @param rpcUrl Optional endpoint for `chain` — see {@link describeReceiptTokens}.
6160
+ */
6161
+ findMarketByReceiptToken(chain: string, receiptToken: string, rpcUrl?: string): Promise<LendingMarketOverview | null>;
6162
+ /** Size + APY for markets already resolved by {@link findMarket}, in the order given. */
6163
+ describeResolvedMarkets(chain: string, markets: LendingMarket[]): Promise<LendingMarketOverview[]>;
6164
+ /**
6165
+ * Every curated market on `chains`, each with its size and APY — the "where
6166
+ * can I supply?" view. Highest average APY first, unrated markets last.
6167
+ *
6168
+ * No chain is filtered out in advance: a chain with no markets contributes an
6169
+ * empty catalogue and therefore nothing, which is the same outcome an
6170
+ * allowlist would produce and costs one request instead of a stale assumption.
6171
+ * Each market reports its own {@link LendingMarketOverview.asset}, so a
6172
+ * non-USDC market is listed as itself rather than dropped.
6173
+ *
6174
+ * Chains are queried in parallel and contribute independently: a chain whose
6175
+ * API or RPC fails yields nothing rather than failing the whole call.
6176
+ */
6177
+ getMarketOverviews(params: {
6178
+ chains: readonly string[];
6179
+ }): Promise<LendingMarketOverview[]>;
6180
+ /**
6181
+ * Every curated lending market the wallet currently supplies to, across
6182
+ * `chains`, highest supplied amount first — see
6183
+ * {@link LendingReadService.getSupplyPositions}.
6184
+ */
6185
+ getSupplyPositions(params: {
6186
+ address: string;
6187
+ chains: readonly string[];
6188
+ }): Promise<LendingSupplyPosition[]>;
6189
+ }
6190
+
6191
+ type LendingMarketsToolConfig = LendingServiceConfig;
6192
+ /** How the list is ordered. Mirrors the `sort` parameter. */
6193
+ type SortKey = 'apy' | 'score' | 'size';
6194
+ /**
6195
+ * Tool: get-lending-markets
6196
+ *
6197
+ * The lending markets a user CAN supply to — the catalogue side of the
6198
+ * lending domain, as opposed to `get-wallet-lending-positions` which reports
6199
+ * what a wallet already supplies. Each market carries its size, the protocol's
6200
+ * live supply APY — the rate the list is ranked on, and the one a depositor is
6201
+ * quoted today — and the average over the last week as a stability check on it.
6202
+ *
6203
+ * See {@link file://../../../services/LendingService.ts} for the data sources.
6204
+ */
6205
+ declare class LendingMarketsTool extends BaseTool {
6206
+ name: string;
6207
+ description: string;
6208
+ category: string;
6209
+ parameters: ToolParameter[];
6210
+ private service;
6211
+ constructor(config?: LendingMarketsToolConfig);
6212
+ protected run(args: Record<string, unknown>, userContext?: UserContext): Promise<{
6213
+ _instructions: string;
6214
+ requestedProtocol: string;
6215
+ protocolSupported: boolean;
6216
+ supportedProtocols: string[];
6217
+ marketCount: number;
6218
+ markets: never[];
6219
+ } | {
6220
+ _instructions: string;
5542
6221
  chain: string;
5543
6222
  connectedChainHasNoMarkets: boolean;
5544
6223
  marketCount: number;
@@ -5569,6 +6248,12 @@ declare class LendingMarketsTool extends BaseTool {
5569
6248
  currentApyPercent: number | null;
5570
6249
  apyChangePercent: number | null;
5571
6250
  totalSuppliedUsdc: number | null;
6251
+ /**
6252
+ * What `totalSuppliedUsdc` is denominated in. Almost always USDC, but a
6253
+ * market on another asset reports its own — so the formatting rule below
6254
+ * can say "dollars" only when this actually is a dollar stablecoin.
6255
+ */
6256
+ suppliedAssetSymbol: string | null;
5572
6257
  platformScore: number | null;
5573
6258
  }[];
5574
6259
  protocolFilter?: string | undefined;
@@ -5627,7 +6312,7 @@ declare class WalletLendingPositionsTool extends BaseTool {
5627
6312
  totals?: undefined;
5628
6313
  } | {
5629
6314
  _instructions: string;
5630
- walletAddress: string;
6315
+ walletAddress: `0x${string}`;
5631
6316
  chain: string;
5632
6317
  positionCount: number;
5633
6318
  positions: never[];
@@ -5637,11 +6322,21 @@ declare class WalletLendingPositionsTool extends BaseTool {
5637
6322
  totals?: undefined;
5638
6323
  } | {
5639
6324
  _instructions: string;
5640
- walletAddress: string;
6325
+ walletAddress: `0x${string}`;
5641
6326
  chain: string;
5642
6327
  chainsQueried: string[];
5643
6328
  positionCount: number;
5644
6329
  totals: {
6330
+ mixedAssets: boolean;
6331
+ suppliedUsdc: null;
6332
+ estimatedAnnualYieldUsdc: null;
6333
+ weightedAvgApyPercent: null;
6334
+ /** Denominated in the single asset every position shares. */
6335
+ assetSymbol?: undefined;
6336
+ } | {
6337
+ mixedAssets: boolean;
6338
+ /** Denominated in the single asset every position shares. */
6339
+ assetSymbol: string | null;
5645
6340
  suppliedUsdc: number;
5646
6341
  estimatedAnnualYieldUsdc: number;
5647
6342
  weightedAvgApyPercent: number | null;
@@ -5652,6 +6347,8 @@ declare class WalletLendingPositionsTool extends BaseTool {
5652
6347
  protocolUrl: string | null;
5653
6348
  chain: string;
5654
6349
  suppliedUsdc: number;
6350
+ /** What `suppliedUsdc` and `estimatedAnnualYieldUsdc` are denominated in. */
6351
+ suppliedAssetSymbol: string | null;
5655
6352
  avgApyPercent: number | null;
5656
6353
  currentApyPercent: number | null;
5657
6354
  apyChangePercent: number | null;
@@ -5668,16 +6365,22 @@ declare class WalletLendingPositionsTool extends BaseTool {
5668
6365
  }
5669
6366
 
5670
6367
  interface OpenSupplyFormToolConfig extends LendingServiceConfig {
5671
- /** Moralis config for the USDC balance shown on the form. */
6368
+ /** Moralis config for the asset balance shown on the form. */
5672
6369
  moralis?: MoralisServiceConfig;
5673
6370
  }
5674
6371
  /**
5675
6372
  * Tool: open-supply-usdc-form
5676
6373
  *
5677
- * Opens the form that deposits USDC into ONE lending market. The counterpart to
6374
+ * Opens the form that deposits into ONE lending market. The counterpart to
5678
6375
  * `get-lending-markets`, which only lists what is available: this resolves the
5679
- * market the user picked, checks their USDC balance, and hands the FE everything
5680
- * it needs to run the approve → supply sequence itself.
6376
+ * market the user picked, reads the asset THAT market lends, checks the wallet's
6377
+ * balance of it, and hands the FE everything it needs to run the approve →
6378
+ * supply sequence itself.
6379
+ *
6380
+ * The asset is never assumed to be USDC. `/supply/v2` decides which markets
6381
+ * exist and `LendingService` resolves each one's underlying on chain, so a
6382
+ * market on WETH is supplied in WETH; USDC is only the fallback for a market
6383
+ * whose asset could not be read. See {@link supplyAsset}.
5681
6384
  *
5682
6385
  * Like every wallet action in this core, the tool does NOT build or sign a
5683
6386
  * transaction — it resolves and validates, then emits a `SupplyUsdcForm` payload.
@@ -5701,7 +6404,8 @@ declare class OpenSupplyFormTool extends BaseTool {
5701
6404
  candidates?: undefined;
5702
6405
  marketName?: undefined;
5703
6406
  protocol?: undefined;
5704
- usdcBalance?: undefined;
6407
+ assetSymbol?: undefined;
6408
+ assetBalance?: undefined;
5705
6409
  requestedAmount?: undefined;
5706
6410
  ui?: undefined;
5707
6411
  apyPercent?: undefined;
@@ -5714,7 +6418,8 @@ declare class OpenSupplyFormTool extends BaseTool {
5714
6418
  candidates?: undefined;
5715
6419
  marketName?: undefined;
5716
6420
  protocol?: undefined;
5717
- usdcBalance?: undefined;
6421
+ assetSymbol?: undefined;
6422
+ assetBalance?: undefined;
5718
6423
  requestedAmount?: undefined;
5719
6424
  ui?: undefined;
5720
6425
  apyPercent?: undefined;
@@ -5727,7 +6432,8 @@ declare class OpenSupplyFormTool extends BaseTool {
5727
6432
  candidates?: undefined;
5728
6433
  marketName?: undefined;
5729
6434
  protocol?: undefined;
5730
- usdcBalance?: undefined;
6435
+ assetSymbol?: undefined;
6436
+ assetBalance?: undefined;
5731
6437
  requestedAmount?: undefined;
5732
6438
  ui?: undefined;
5733
6439
  apyPercent?: undefined;
@@ -5743,7 +6449,8 @@ declare class OpenSupplyFormTool extends BaseTool {
5743
6449
  chainsWithLendingMarkets?: undefined;
5744
6450
  marketName?: undefined;
5745
6451
  protocol?: undefined;
5746
- usdcBalance?: undefined;
6452
+ assetSymbol?: undefined;
6453
+ assetBalance?: undefined;
5747
6454
  requestedAmount?: undefined;
5748
6455
  ui?: undefined;
5749
6456
  apyPercent?: undefined;
@@ -5756,20 +6463,22 @@ declare class OpenSupplyFormTool extends BaseTool {
5756
6463
  chainsWithLendingMarkets?: undefined;
5757
6464
  market?: undefined;
5758
6465
  candidates?: undefined;
5759
- usdcBalance?: undefined;
6466
+ assetSymbol?: undefined;
6467
+ assetBalance?: undefined;
5760
6468
  requestedAmount?: undefined;
5761
6469
  ui?: undefined;
5762
6470
  apyPercent?: undefined;
5763
6471
  } | {
5764
6472
  error: string;
6473
+ marketName: string;
5765
6474
  chain: string;
5766
6475
  _instructions: string;
5767
6476
  chainsWithLendingMarkets?: undefined;
5768
6477
  market?: undefined;
5769
6478
  candidates?: undefined;
5770
- marketName?: undefined;
5771
6479
  protocol?: undefined;
5772
- usdcBalance?: undefined;
6480
+ assetSymbol?: undefined;
6481
+ assetBalance?: undefined;
5773
6482
  requestedAmount?: undefined;
5774
6483
  ui?: undefined;
5775
6484
  apyPercent?: undefined;
@@ -5777,7 +6486,8 @@ declare class OpenSupplyFormTool extends BaseTool {
5777
6486
  error: string;
5778
6487
  marketName: string;
5779
6488
  chain: string;
5780
- usdcBalance: string;
6489
+ assetSymbol: string;
6490
+ assetBalance: string;
5781
6491
  _instructions: string;
5782
6492
  chainsWithLendingMarkets?: undefined;
5783
6493
  market?: undefined;
@@ -5790,8 +6500,9 @@ declare class OpenSupplyFormTool extends BaseTool {
5790
6500
  error: string;
5791
6501
  marketName: string;
5792
6502
  chain: string;
6503
+ assetSymbol: string;
5793
6504
  requestedAmount: string | null;
5794
- usdcBalance: string;
6505
+ assetBalance: string;
5795
6506
  _instructions: string;
5796
6507
  chainsWithLendingMarkets?: undefined;
5797
6508
  market?: undefined;
@@ -5805,7 +6516,8 @@ declare class OpenSupplyFormTool extends BaseTool {
5805
6516
  protocol: string;
5806
6517
  chain: string;
5807
6518
  apyPercent: number | null;
5808
- usdcBalance: string | null;
6519
+ assetSymbol: string;
6520
+ assetBalance: string | null;
5809
6521
  _instructions: string;
5810
6522
  error?: undefined;
5811
6523
  chainsWithLendingMarkets?: undefined;
@@ -5816,24 +6528,24 @@ declare class OpenSupplyFormTool extends BaseTool {
5816
6528
  /** Size + live APY for the one resolved market. Null when it can't be priced. */
5817
6529
  private describeOne;
5818
6530
  /**
5819
- * The wallet's USDC on this chain, for the form's spendable line and the
5820
- * balance checks above.
6531
+ * The wallet's balance of the market's asset on this chain, for the form's
6532
+ * spendable line and the balance checks above.
5821
6533
  *
5822
6534
  * The distinction that matters here is "the call FAILED" vs "the call
5823
6535
  * succeeded and reported nothing", which a bare null cannot express:
5824
6536
  *
5825
6537
  * - `null` — the balance is genuinely UNREADABLE (request failed or threw).
5826
6538
  * The form still opens: blocking a supply over a flaky call would be worse.
5827
- * - `{ amount: '0' }` — the request SUCCEEDED and returned no USDC row.
6539
+ * - `{ amount: '0' }` — the request SUCCEEDED and returned no row for it.
5828
6540
  *
5829
6541
  * The second case is the one that was being missed. `getWalletTokenBalances`
5830
6542
  * serves portfolio LISTS, so it drops zero rows and anything worth under a
5831
6543
  * cent; we asked it for this one token, so a successful call with no row means
5832
6544
  * the wallet holds nothing spendable here — not that the read failed. Reporting
5833
- * it as '0' is what lets the `no_usdc_balance` branch fire instead of opening a
5834
- * form the user cannot submit.
6545
+ * it as '0' is what lets the `no_asset_balance` branch fire instead of opening
6546
+ * a form the user cannot submit.
5835
6547
  */
5836
- private usdcBalance;
6548
+ private assetBalance;
5837
6549
  /**
5838
6550
  * Presentation contract for the synthesizer. Only reached once the supply is
5839
6551
  * actually possible — an empty or short balance returns earlier with its own
@@ -6289,7 +7001,13 @@ declare class PoolDetailTool extends BaseTool {
6289
7001
  * Never throws — returns `[]` on any miss so the detail view is unaffected.
6290
7002
  */
6291
7003
  private fetchPriceRanges;
6292
- /** Trim and enrich the GraphQL payload with derived metrics. */
7004
+ /**
7005
+ * Trim and enrich the GraphQL payload with derived metrics.
7006
+ *
7007
+ * `lpFeeShare` is the fraction of swap fees left to LPs after the pool's
7008
+ * on-chain protocol fee; pass it so fees/APR are the LP-net figures rather
7009
+ * than the gross `feeTier × volume` headline.
7010
+ */
6293
7011
  private formatPool;
6294
7012
  private formatHistorical;
6295
7013
  }
@@ -6368,6 +7086,7 @@ declare class PoolByAddressTool extends BaseTool {
6368
7086
  tvlChange24hPercent: number | undefined;
6369
7087
  volume24hUsd: number | undefined;
6370
7088
  fees24hUsd: number | undefined;
7089
+ lpFeeShare: number;
6371
7090
  aprPercent: number | undefined;
6372
7091
  volumeToTvlRatio: number | undefined;
6373
7092
  txCount: number | undefined;
@@ -6440,6 +7159,7 @@ declare class PoolByAddressTool extends BaseTool {
6440
7159
  private findTokenByAddress;
6441
7160
  private formatToken;
6442
7161
  private formatPoolCandidate;
7162
+ /** `lpFeeShare` is the fraction of swap fees LPs keep after the protocol fee. */
6443
7163
  private formatPoolDetail;
6444
7164
  private formatHistorical;
6445
7165
  }
@@ -8244,52 +8964,636 @@ declare class SendNftTool extends BaseWalletActionTool {
8244
8964
  }
8245
8965
 
8246
8966
  /**
8247
- * Shared JSON-RPC client + default public RPC endpoints.
8248
- *
8249
- * Kept free of PoolService / swap imports so both `PoolService` and the swap
8250
- * adapters can use it without a circular import.
8967
+ * JSON-RPC wire types + the EIP-1193 request function every transport exposes.
8251
8968
  */
8252
- /** Default public RPC endpoint per hex chain id. Single source of truth. */
8253
- declare const DEFAULT_RPC_BY_CHAIN: Record<string, string>;
8254
- /** Resolve a hex chain id to its default RPC URL, or undefined if unsupported. */
8255
- declare function getDefaultRpcUrl(chainId: string): string | undefined;
8969
+
8970
+ /** Block selector accepted wherever an RPC call takes one. */
8971
+ type BlockTag = 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
8972
+ /** The two ways to name a block; `blockNumber` wins when both are given. */
8973
+ interface BlockParameters {
8974
+ blockNumber?: bigint;
8975
+ blockTag?: BlockTag;
8976
+ }
8977
+ /** A single JSON-RPC request, minus the envelope the transport adds. */
8978
+ interface RpcRequestBody {
8979
+ method: string;
8980
+ params?: unknown;
8981
+ }
8982
+ /** Per-request overrides accepted alongside the RPC body. */
8983
+ interface RequestOverrides {
8984
+ retryCount?: number;
8985
+ retryDelay?: number;
8986
+ }
8256
8987
  /**
8257
- * Install the shared RPC overrides for the whole core. Replaces any previous
8258
- * set. Keys are normalised to lowercase hex chain ids; blank/non-string values
8259
- * are ignored so a partial map only overrides the chains it actually names.
8260
- * Called once by AgentCore from `AgentConfig.rpcUrls`.
8988
+ * EIP-1193 `request` — the ONE method every transport implements and every
8989
+ * action is written against, which is what makes actions transport-agnostic.
8261
8990
  */
8262
- declare function setRpcOverrides(overrides?: Record<string, string>): void;
8991
+ type EIP1193RequestFn = <TResult = unknown>(args: RpcRequestBody, overrides?: RequestOverrides) => Promise<TResult>;
8992
+
8263
8993
  /**
8264
- * Resolve a hex chain id to its RPC URL: the caller-supplied override (see
8265
- * {@link setRpcOverrides}) if present, else the built-in public default.
8266
- * Returns undefined only when the chain is both un-overridden and unsupported.
8994
+ * Transport contract — how a client reaches a node.
8995
+ *
8996
+ * A transport is a FACTORY, not an object: the client calls it with its own
8997
+ * chain/retry/timeout defaults, and gets back a configured instance. That's what
8998
+ * lets one `http()` value be reused across clients (and what makes
8999
+ * `fallback([...])` composable), exactly as in viem.
8267
9000
  */
8268
- declare function resolveRpcUrl(chainId: string): string | undefined;
8269
- /** Low-level JSON-RPC call with 429 backoff (5 retries, exponential). */
8270
- declare function rpcCall<T>(rpcUrl: string, method: string, params: unknown[]): Promise<T>;
8271
- /** `eth_call` against an explicit RPC URL. `data` is the encoded calldata. */
8272
- declare function ethCallAt(rpcUrl: string, to: string, data: string): Promise<string>;
9001
+
9002
+ /** Settings the client passes down when it instantiates a transport. */
9003
+ interface TransportFactoryParameters {
9004
+ chain?: Chain;
9005
+ retryCount?: number;
9006
+ retryDelay?: number;
9007
+ timeout?: number;
9008
+ }
9009
+ /** The resolved configuration of an instantiated transport. */
9010
+ interface TransportConfig<TType extends string = string> {
9011
+ /** Short machine key (`http`, `fallback`). */
9012
+ key: string;
9013
+ /** Human name for logs/errors. */
9014
+ name: string;
9015
+ /** Transport kind. */
9016
+ type: TType;
9017
+ /** How many times a failed request is retried. */
9018
+ retryCount: number;
9019
+ /** Base delay (ms) between retries; grows exponentially. */
9020
+ retryDelay: number;
9021
+ /** Per-request timeout (ms). */
9022
+ timeout: number;
9023
+ /** The RAW request fn, without the retry wrapper. */
9024
+ request: EIP1193RequestFn;
9025
+ }
9026
+ /** What a transport factory returns. */
9027
+ interface TransportInstance<TType extends string = string, TValue = unknown> {
9028
+ config: TransportConfig<TType>;
9029
+ /** Retry-wrapped, error-normalised request fn — what the client actually calls. */
9030
+ request: EIP1193RequestFn;
9031
+ /** Transport-specific extras (e.g. the resolved `url` for HTTP). */
9032
+ value?: TValue;
9033
+ }
9034
+ type Transport<TType extends string = string, TValue = unknown> = (parameters?: TransportFactoryParameters) => TransportInstance<TType, TValue>;
9035
+
8273
9036
  /**
8274
- * `eth_call` resolving the RPC URL from the hex chain id, honouring any shared
8275
- * overrides (see {@link setRpcOverrides}) before falling back to the default
8276
- * endpoint. Returns `null` when the chain has no known RPC or the call fails —
8277
- * callers that need to distinguish errors should use {@link ethCallAt} directly.
9037
+ * The minimal client shape ACTIONS are written against.
9038
+ *
9039
+ * Actions take a `Client`, never the concrete `PublicClient` class — which is
9040
+ * what keeps the dependency arrow pointing one way (client → actions) and lets
9041
+ * an action be called standalone, viem-style:
9042
+ *
9043
+ * ```ts
9044
+ * import { multicall } from './actions/multicall';
9045
+ * await multicall(client, { contracts }); // === client.multicall({ contracts })
9046
+ * ```
8278
9047
  */
8279
- declare function ethCallByChain(chainId: string, to: string, data: string): Promise<string | null>;
8280
9048
 
8281
- /** Normalized, `fetch`-like response. `data` is the parsed body (JSON when possible). */
8282
- interface ApiResponse<T = unknown> {
8283
- /** True when the HTTP status is in the 2xx range. */
8284
- ok: boolean;
8285
- status: number;
8286
- statusText: string;
8287
- /** Parsed response body (JSON object/array, or raw string for non-JSON). */
8288
- data: T;
8289
- /** Response headers with lowercased keys. */
8290
- headers: Record<string, string>;
9049
+ /** Client-wide batching policy. */
9050
+ interface ClientBatchConfig {
9051
+ /**
9052
+ * Coalesce eligible `eth_call`s into a single Multicall3 `aggregate3`.
9053
+ * `true` uses the defaults; an object tunes them.
9054
+ */
9055
+ multicall?: boolean | {
9056
+ /** Max calldata bytes per aggregated call (default 1024). */
9057
+ batchSize?: number;
9058
+ /** Extra ms to keep collecting before sending (default 0 — same tick). */
9059
+ wait?: number;
9060
+ /**
9061
+ * On a chain with NO Multicall3, batches degrade to individual
9062
+ * `eth_call`s — this bounds how many are in flight (default 8). Raise it
9063
+ * for a private node, lower it for an endpoint that rate-limits hard.
9064
+ */
9065
+ fallbackConcurrency?: number;
9066
+ /**
9067
+ * Skip the one-off `eth_getCode` that verifies Multicall3 exists, and
9068
+ * assume it does. For hosts that only ever touch chains they know carry
9069
+ * the deployment and want to save the probe. Default `false`.
9070
+ */
9071
+ assumeMulticall3?: boolean;
9072
+ };
8291
9073
  }
8292
- interface ApiClientConfig {
9074
+ interface Client {
9075
+ /** Machine key of the client (`public`). */
9076
+ key: string;
9077
+ /** Human name, used in errors. */
9078
+ name: string;
9079
+ /** Unique per instance — scopes batch queues so two clients never share one. */
9080
+ uid: string;
9081
+ /** The chain this client is bound to, when it has one. */
9082
+ chain?: Chain;
9083
+ /** Resolved transport config (endpoint, retries, timeout). */
9084
+ transport: TransportConfig & Record<string, unknown>;
9085
+ /** EIP-1193 request fn — every action ultimately goes through this. */
9086
+ request: EIP1193RequestFn;
9087
+ /** Optional batching policy (see {@link ClientBatchConfig}). */
9088
+ batch?: ClientBatchConfig;
9089
+ }
9090
+
9091
+ /**
9092
+ * Contract-call shapes shared by `readContract` and `multicall`.
9093
+ */
9094
+
9095
+ /** One contract read: where, which ABI, which function, which arguments. */
9096
+ interface ContractFunctionParameters {
9097
+ address: Address;
9098
+ abi: Abi;
9099
+ /** Function name, full signature or 4-byte selector. */
9100
+ functionName: string;
9101
+ args?: readonly unknown[];
9102
+ }
9103
+ /**
9104
+ * One entry of a `multicall` result when `allowFailure` is on (the default) —
9105
+ * a discriminated union, so narrowing on `status` gives you a typed `result`
9106
+ * with no non-null assertions, the same ergonomics viem has.
9107
+ */
9108
+ type MulticallResult<TResult = unknown> = {
9109
+ status: 'success';
9110
+ result: TResult;
9111
+ error?: undefined;
9112
+ } | {
9113
+ status: 'failure';
9114
+ result?: undefined;
9115
+ error: Error;
9116
+ };
9117
+
9118
+ /**
9119
+ * Chain lookup + RPC-endpoint resolution — the single source of truth for
9120
+ * "which node do we talk to for chain X".
9121
+ *
9122
+ * Resolution order:
9123
+ * 1. a caller-supplied override (`AgentConfig.rpcUrls` → {@link setRpcOverrides}),
9124
+ * 2. the remote Pantograph catalogue ({@link file://./remote.ts}), once loaded —
9125
+ * which also supplies endpoints for chains carrying no definition here,
9126
+ * 3. the chain definition's default public RPC, as the floor beneath both.
9127
+ *
9128
+ * An override changes only which endpoint is PREFERRED — the chain's built-in
9129
+ * endpoints stay behind it as backups, so a host that configures its own node
9130
+ * still degrades to the public ones instead of losing the chain when that node
9131
+ * is down. {@link resolveRpcUrl} returns just the preferred endpoint (what most
9132
+ * callers want); {@link resolveRpcUrls} returns the whole ordered list, which is
9133
+ * what the client hands to a `fallback` transport.
9134
+ *
9135
+ * Keeping it here (rather than in the old `services/rpc.ts`) means the chain
9136
+ * layer is self-contained: transports, clients and the back-compat facade all
9137
+ * read the same table, and there is no import cycle between them.
9138
+ */
9139
+
9140
+ /** Look up a chain by hex id, decimal id, or decimal string. `undefined` if unknown. */
9141
+ declare function getChain(chainId: string | number): Chain | undefined;
9142
+ /** Default public RPC endpoint per hex chain id, derived from the definitions. */
9143
+ declare const DEFAULT_RPC_BY_CHAIN: Record<string, string>;
9144
+ /** The built-in public RPC for a chain, ignoring overrides. */
9145
+ declare function getDefaultRpcUrl(chainId: string | number): string | undefined;
9146
+ /**
9147
+ * Install the shared RPC overrides for the whole core, replacing any previous
9148
+ * set. Keys are normalised to lowercase hex ids (so `'8453'` and `'0x2105'` both
9149
+ * work); blank or non-string values are ignored, so a partial map only overrides
9150
+ * the chains it actually names. Called once by AgentCore.
9151
+ */
9152
+ declare function setRpcOverrides(overrides?: Record<string, string>): void;
9153
+ /** The currently installed overrides (read-only copy). */
9154
+ declare function getRpcOverrides(): Readonly<Record<string, string>>;
9155
+ /**
9156
+ * Every endpoint for a chain, most-preferred first, from three layers:
9157
+ *
9158
+ * 1. the caller-supplied override (`AgentConfig.rpcUrls`),
9159
+ * 2. the remote Pantograph catalogue, when {@link loadRemoteChains} has run,
9160
+ * 3. the chain definition's built-in list.
9161
+ *
9162
+ * Duplicates are dropped, so an override naming an endpoint already present
9163
+ * simply promotes it rather than making it appear twice.
9164
+ *
9165
+ * The catalogue sits AHEAD of the built-ins: it is the same table the wallet
9166
+ * itself dials, maintained live, so an endpoint that has degraded since this
9167
+ * package was published is corrected there without a release. The built-ins
9168
+ * become the floor beneath it — still present, still ordered, and still the
9169
+ * whole answer whenever the catalogue has not loaded (startup, offline host,
9170
+ * API down) or does not carry the chain.
9171
+ *
9172
+ * The trade-off this accepts: the endpoint normally dialled for a known chain is
9173
+ * now chosen upstream rather than pinned in this repo, so a bad head entry in
9174
+ * the catalogue is felt on the first call rather than only as a backup. The
9175
+ * `fallback` transport covers that — it walks to the next endpoint on a
9176
+ * timeout/5xx/rate-limit — but latency is paid before it does.
9177
+ *
9178
+ * Empty only when the chain is overridden by nothing, absent from the
9179
+ * catalogue, and known to no definition.
9180
+ */
9181
+ declare function resolveRpcUrls(chainId: string | number): string[];
9182
+ /**
9183
+ * Resolve a chain to its PREFERRED RPC URL: the caller-supplied override first,
9184
+ * else the chain's first default. `undefined` only when the chain is neither
9185
+ * overridden nor known. Callers that can use the backups too want
9186
+ * {@link resolveRpcUrls}.
9187
+ */
9188
+ declare function resolveRpcUrl(chainId: string | number): string | undefined;
9189
+
9190
+ /**
9191
+ * Well-known-contract lookup on a chain — viem's `getChainContractAddress`.
9192
+ */
9193
+
9194
+ /**
9195
+ * The address of a well-known contract (today: `multicall3`) on `chain`.
9196
+ *
9197
+ * Throws {@link ChainDoesNotSupportContractError} when the chain has no such
9198
+ * deployment, or when `blockNumber` predates it — a read pinned before the
9199
+ * deployment block would otherwise come back as a confusing empty result.
9200
+ */
9201
+ declare function getChainContractAddress({ blockNumber, chain, contract: name, }: {
9202
+ blockNumber?: bigint;
9203
+ chain: Chain;
9204
+ contract: 'multicall3';
9205
+ }): Address;
9206
+
9207
+ /**
9208
+ * Multicall3 — the contract every batched read goes through.
9209
+ *
9210
+ * Restricted to what a READ client needs. `aggregate3` is the one the batching
9211
+ * layer uses: per-call `allowFailure` means one reverting call comes back as
9212
+ * `success: false` instead of reverting the whole batch.
9213
+ */
9214
+ /**
9215
+ * Multicall3, restricted to what a READ client needs. `aggregate3` is the one the
9216
+ * batching layer uses: per-call `allowFailure` means one reverting call comes back
9217
+ * as `success: false` instead of reverting the whole batch.
9218
+ */
9219
+ declare const multicall3Abi: readonly [{
9220
+ readonly type: "function";
9221
+ readonly name: "aggregate3";
9222
+ readonly stateMutability: "payable";
9223
+ readonly inputs: readonly [{
9224
+ readonly name: "calls";
9225
+ readonly type: "tuple[]";
9226
+ readonly components: readonly [{
9227
+ readonly name: "target";
9228
+ readonly type: "address";
9229
+ }, {
9230
+ readonly name: "allowFailure";
9231
+ readonly type: "bool";
9232
+ }, {
9233
+ readonly name: "callData";
9234
+ readonly type: "bytes";
9235
+ }];
9236
+ }];
9237
+ readonly outputs: readonly [{
9238
+ readonly name: "returnData";
9239
+ readonly type: "tuple[]";
9240
+ readonly components: readonly [{
9241
+ readonly name: "success";
9242
+ readonly type: "bool";
9243
+ }, {
9244
+ readonly name: "returnData";
9245
+ readonly type: "bytes";
9246
+ }];
9247
+ }];
9248
+ }, {
9249
+ readonly type: "function";
9250
+ readonly name: "getEthBalance";
9251
+ readonly stateMutability: "view";
9252
+ readonly inputs: readonly [{
9253
+ readonly name: "addr";
9254
+ readonly type: "address";
9255
+ }];
9256
+ readonly outputs: readonly [{
9257
+ readonly name: "balance";
9258
+ readonly type: "uint256";
9259
+ }];
9260
+ }, {
9261
+ readonly type: "function";
9262
+ readonly name: "getBlockNumber";
9263
+ readonly stateMutability: "view";
9264
+ readonly inputs: readonly [];
9265
+ readonly outputs: readonly [{
9266
+ readonly name: "blockNumber";
9267
+ readonly type: "uint256";
9268
+ }];
9269
+ }, {
9270
+ readonly type: "function";
9271
+ readonly name: "getCurrentBlockTimestamp";
9272
+ readonly stateMutability: "view";
9273
+ readonly inputs: readonly [];
9274
+ readonly outputs: readonly [{
9275
+ readonly name: "timestamp";
9276
+ readonly type: "uint256";
9277
+ }];
9278
+ }];
9279
+
9280
+ /**
9281
+ * ERC-20 — the fungible-token standard.
9282
+ *
9283
+ * `erc20Abi` is the full standard surface (reads, writes, events); the whole core
9284
+ * encodes and decodes against this one definition.
9285
+ *
9286
+ * `erc20Abi_bytes32` covers the pre-standard tokens (MKR and friends) that answer
9287
+ * `name()` / `symbol()` with a right-padded `bytes32` instead of a `string` — a
9288
+ * metadata reader retries with it when the `string` decode fails.
9289
+ */
9290
+ /** ERC-20, full standard surface (reads + writes + events). */
9291
+ declare const erc20Abi: readonly [{
9292
+ readonly type: "function";
9293
+ readonly name: "name";
9294
+ readonly stateMutability: "view";
9295
+ readonly inputs: readonly [];
9296
+ readonly outputs: readonly [{
9297
+ readonly name: "";
9298
+ readonly type: "string";
9299
+ }];
9300
+ }, {
9301
+ readonly type: "function";
9302
+ readonly name: "symbol";
9303
+ readonly stateMutability: "view";
9304
+ readonly inputs: readonly [];
9305
+ readonly outputs: readonly [{
9306
+ readonly name: "";
9307
+ readonly type: "string";
9308
+ }];
9309
+ }, {
9310
+ readonly type: "function";
9311
+ readonly name: "decimals";
9312
+ readonly stateMutability: "view";
9313
+ readonly inputs: readonly [];
9314
+ readonly outputs: readonly [{
9315
+ readonly name: "";
9316
+ readonly type: "uint8";
9317
+ }];
9318
+ }, {
9319
+ readonly type: "function";
9320
+ readonly name: "totalSupply";
9321
+ readonly stateMutability: "view";
9322
+ readonly inputs: readonly [];
9323
+ readonly outputs: readonly [{
9324
+ readonly name: "";
9325
+ readonly type: "uint256";
9326
+ }];
9327
+ }, {
9328
+ readonly type: "function";
9329
+ readonly name: "balanceOf";
9330
+ readonly stateMutability: "view";
9331
+ readonly inputs: readonly [{
9332
+ readonly name: "account";
9333
+ readonly type: "address";
9334
+ }];
9335
+ readonly outputs: readonly [{
9336
+ readonly name: "";
9337
+ readonly type: "uint256";
9338
+ }];
9339
+ }, {
9340
+ readonly type: "function";
9341
+ readonly name: "allowance";
9342
+ readonly stateMutability: "view";
9343
+ readonly inputs: readonly [{
9344
+ readonly name: "owner";
9345
+ readonly type: "address";
9346
+ }, {
9347
+ readonly name: "spender";
9348
+ readonly type: "address";
9349
+ }];
9350
+ readonly outputs: readonly [{
9351
+ readonly name: "";
9352
+ readonly type: "uint256";
9353
+ }];
9354
+ }, {
9355
+ readonly type: "function";
9356
+ readonly name: "approve";
9357
+ readonly stateMutability: "nonpayable";
9358
+ readonly inputs: readonly [{
9359
+ readonly name: "spender";
9360
+ readonly type: "address";
9361
+ }, {
9362
+ readonly name: "amount";
9363
+ readonly type: "uint256";
9364
+ }];
9365
+ readonly outputs: readonly [{
9366
+ readonly name: "";
9367
+ readonly type: "bool";
9368
+ }];
9369
+ }, {
9370
+ readonly type: "function";
9371
+ readonly name: "transfer";
9372
+ readonly stateMutability: "nonpayable";
9373
+ readonly inputs: readonly [{
9374
+ readonly name: "to";
9375
+ readonly type: "address";
9376
+ }, {
9377
+ readonly name: "amount";
9378
+ readonly type: "uint256";
9379
+ }];
9380
+ readonly outputs: readonly [{
9381
+ readonly name: "";
9382
+ readonly type: "bool";
9383
+ }];
9384
+ }, {
9385
+ readonly type: "function";
9386
+ readonly name: "transferFrom";
9387
+ readonly stateMutability: "nonpayable";
9388
+ readonly inputs: readonly [{
9389
+ readonly name: "from";
9390
+ readonly type: "address";
9391
+ }, {
9392
+ readonly name: "to";
9393
+ readonly type: "address";
9394
+ }, {
9395
+ readonly name: "amount";
9396
+ readonly type: "uint256";
9397
+ }];
9398
+ readonly outputs: readonly [{
9399
+ readonly name: "";
9400
+ readonly type: "bool";
9401
+ }];
9402
+ }, {
9403
+ readonly type: "event";
9404
+ readonly name: "Transfer";
9405
+ readonly inputs: readonly [{
9406
+ readonly name: "from";
9407
+ readonly type: "address";
9408
+ readonly indexed: true;
9409
+ }, {
9410
+ readonly name: "to";
9411
+ readonly type: "address";
9412
+ readonly indexed: true;
9413
+ }, {
9414
+ readonly name: "value";
9415
+ readonly type: "uint256";
9416
+ readonly indexed: false;
9417
+ }];
9418
+ }, {
9419
+ readonly type: "event";
9420
+ readonly name: "Approval";
9421
+ readonly inputs: readonly [{
9422
+ readonly name: "owner";
9423
+ readonly type: "address";
9424
+ readonly indexed: true;
9425
+ }, {
9426
+ readonly name: "spender";
9427
+ readonly type: "address";
9428
+ readonly indexed: true;
9429
+ }, {
9430
+ readonly name: "value";
9431
+ readonly type: "uint256";
9432
+ readonly indexed: false;
9433
+ }];
9434
+ }];
9435
+ /**
9436
+ * Legacy ERC-20s (MKR and friends) predate the standard's `string` return and
9437
+ * answer `symbol()`/`name()` with a right-padded `bytes32`. Decoding one against
9438
+ * {@link erc20Abi} fails, so metadata readers retry with THIS ABI — the reason
9439
+ * viem ships the same pair.
9440
+ */
9441
+ declare const erc20Abi_bytes32: readonly [{
9442
+ readonly type: "function";
9443
+ readonly name: "name";
9444
+ readonly stateMutability: "view";
9445
+ readonly inputs: readonly [];
9446
+ readonly outputs: readonly [{
9447
+ readonly name: "";
9448
+ readonly type: "bytes32";
9449
+ }];
9450
+ }, {
9451
+ readonly type: "function";
9452
+ readonly name: "symbol";
9453
+ readonly stateMutability: "view";
9454
+ readonly inputs: readonly [];
9455
+ readonly outputs: readonly [{
9456
+ readonly name: "";
9457
+ readonly type: "bytes32";
9458
+ }];
9459
+ }];
9460
+
9461
+ /**
9462
+ * ERC-721 — non-fungible token standard.
9463
+ *
9464
+ * The read surface plus the metadata extension (`tokenURI`), which is what NFT
9465
+ * image resolution needs.
9466
+ */
9467
+ /** ERC-721, the read surface plus the metadata extension. */
9468
+ declare const erc721Abi: readonly [{
9469
+ readonly type: "function";
9470
+ readonly name: "balanceOf";
9471
+ readonly stateMutability: "view";
9472
+ readonly inputs: readonly [{
9473
+ readonly name: "owner";
9474
+ readonly type: "address";
9475
+ }];
9476
+ readonly outputs: readonly [{
9477
+ readonly name: "";
9478
+ readonly type: "uint256";
9479
+ }];
9480
+ }, {
9481
+ readonly type: "function";
9482
+ readonly name: "ownerOf";
9483
+ readonly stateMutability: "view";
9484
+ readonly inputs: readonly [{
9485
+ readonly name: "tokenId";
9486
+ readonly type: "uint256";
9487
+ }];
9488
+ readonly outputs: readonly [{
9489
+ readonly name: "";
9490
+ readonly type: "address";
9491
+ }];
9492
+ }, {
9493
+ readonly type: "function";
9494
+ readonly name: "name";
9495
+ readonly stateMutability: "view";
9496
+ readonly inputs: readonly [];
9497
+ readonly outputs: readonly [{
9498
+ readonly name: "";
9499
+ readonly type: "string";
9500
+ }];
9501
+ }, {
9502
+ readonly type: "function";
9503
+ readonly name: "symbol";
9504
+ readonly stateMutability: "view";
9505
+ readonly inputs: readonly [];
9506
+ readonly outputs: readonly [{
9507
+ readonly name: "";
9508
+ readonly type: "string";
9509
+ }];
9510
+ }, {
9511
+ readonly type: "function";
9512
+ readonly name: "tokenURI";
9513
+ readonly stateMutability: "view";
9514
+ readonly inputs: readonly [{
9515
+ readonly name: "tokenId";
9516
+ readonly type: "uint256";
9517
+ }];
9518
+ readonly outputs: readonly [{
9519
+ readonly name: "";
9520
+ readonly type: "string";
9521
+ }];
9522
+ }, {
9523
+ readonly type: "function";
9524
+ readonly name: "totalSupply";
9525
+ readonly stateMutability: "view";
9526
+ readonly inputs: readonly [];
9527
+ readonly outputs: readonly [{
9528
+ readonly name: "";
9529
+ readonly type: "uint256";
9530
+ }];
9531
+ }];
9532
+
9533
+ /**
9534
+ * ERC-1155 — multi-token standard.
9535
+ *
9536
+ * The metadata read (`uri`) plus the per-id balance, for NFT image resolution.
9537
+ */
9538
+ /** ERC-1155 metadata read, for NFT image resolution. */
9539
+ declare const erc1155Abi: readonly [{
9540
+ readonly type: "function";
9541
+ readonly name: "uri";
9542
+ readonly stateMutability: "view";
9543
+ readonly inputs: readonly [{
9544
+ readonly name: "id";
9545
+ readonly type: "uint256";
9546
+ }];
9547
+ readonly outputs: readonly [{
9548
+ readonly name: "";
9549
+ readonly type: "string";
9550
+ }];
9551
+ }, {
9552
+ readonly type: "function";
9553
+ readonly name: "balanceOf";
9554
+ readonly stateMutability: "view";
9555
+ readonly inputs: readonly [{
9556
+ readonly name: "account";
9557
+ readonly type: "address";
9558
+ }, {
9559
+ readonly name: "id";
9560
+ readonly type: "uint256";
9561
+ }];
9562
+ readonly outputs: readonly [{
9563
+ readonly name: "";
9564
+ readonly type: "uint256";
9565
+ }];
9566
+ }];
9567
+
9568
+ /**
9569
+ * Transport constructor — takes a raw `request` fn and returns the instance a
9570
+ * client consumes: retry-wrapped `request`, plus the resolved config so the
9571
+ * client (and errors) can report which endpoint they used.
9572
+ */
9573
+
9574
+ interface CreateTransportParameters<TType extends string = string> {
9575
+ key: string;
9576
+ name: string;
9577
+ type: TType;
9578
+ request: EIP1193RequestFn;
9579
+ retryCount?: number;
9580
+ retryDelay?: number;
9581
+ timeout?: number;
9582
+ }
9583
+ declare function createTransport<TType extends string, TValue = unknown>({ key, name, type, request, retryCount, retryDelay, timeout }: CreateTransportParameters<TType>, value?: TValue): TransportInstance<TType, TValue>;
9584
+
9585
+ /** Normalized, `fetch`-like response. `data` is the parsed body (JSON when possible). */
9586
+ interface ApiResponse<T = unknown> {
9587
+ /** True when the HTTP status is in the 2xx range. */
9588
+ ok: boolean;
9589
+ status: number;
9590
+ statusText: string;
9591
+ /** Parsed response body (JSON object/array, or raw string for non-JSON). */
9592
+ data: T;
9593
+ /** Response headers with lowercased keys. */
9594
+ headers: Record<string, string>;
9595
+ }
9596
+ interface ApiClientConfig {
8293
9597
  /** Optional base URL prepended to relative request paths. */
8294
9598
  baseURL?: string;
8295
9599
  /** Default headers merged into every request. */
@@ -8326,6 +9630,829 @@ declare class ApiClient {
8326
9630
  /** Shared default client (bot User-Agent, no base URL) for ad-hoc absolute-URL calls. */
8327
9631
  declare const apiClient: ApiClient;
8328
9632
 
9633
+ /**
9634
+ * HTTP transport — `http(url?, config?)`, the default way a client reaches a node.
9635
+ *
9636
+ * Mirrors viem's: an explicit URL wins, otherwise the client's chain supplies one
9637
+ * (already override-aware, see `chains/registry.ts`). With `batch` enabled,
9638
+ * requests raised in the same tick are coalesced into ONE JSON-RPC batch POST —
9639
+ * a separate, lower-level saving than `multicall`, and they compose: a batched
9640
+ * multicall chunk set becomes a single HTTP round-trip.
9641
+ *
9642
+ * ```ts
9643
+ * const client = createPublicClient({ chain: base, transport: http() });
9644
+ * const fast = createPublicClient({ chain: base, transport: http(url, { batch: true }) });
9645
+ * ```
9646
+ */
9647
+
9648
+ interface HttpTransportConfig {
9649
+ /**
9650
+ * Coalesce requests made in the same tick into one JSON-RPC batch POST.
9651
+ * `true` uses the defaults below; an object tunes them.
9652
+ */
9653
+ batch?: boolean | {
9654
+ /** Max requests per batch (default 1000). */
9655
+ batchSize?: number;
9656
+ /** Extra ms to keep collecting before sending (default 0 — same tick). */
9657
+ wait?: number;
9658
+ };
9659
+ /** Extra options merged into every HTTP request (headers, signal …). */
9660
+ fetchOptions?: RequestOptions;
9661
+ key?: string;
9662
+ name?: string;
9663
+ /** Retries per request (default 3). */
9664
+ retryCount?: number;
9665
+ /** Base backoff in ms (default 150, doubling each attempt). */
9666
+ retryDelay?: number;
9667
+ /** Per-request timeout in ms (default 10_000). */
9668
+ timeout?: number;
9669
+ }
9670
+ interface HttpTransportValue {
9671
+ url: string;
9672
+ }
9673
+ declare function http(url?: string, config?: HttpTransportConfig): Transport<'http', HttpTransportValue>;
9674
+
9675
+ /**
9676
+ * Fallback transport — `fallback([http(a), http(b)])`.
9677
+ *
9678
+ * Sends to the first transport; if the failure is the ENDPOINT's (a rate limit,
9679
+ * a 5xx, a timeout, or a 401/403 rejecting our key), moves to the next. Errors
9680
+ * that describe a bad request, or a reverting call, are thrown immediately:
9681
+ * trying another node would only produce the same answer more slowly.
9682
+ *
9683
+ * Note this is WIDER than the retry policy: an auth failure is pointless to
9684
+ * retry against the same URL but perfectly worth sending to a different
9685
+ * provider — see `shouldTryNextEndpoint` vs `shouldRetryError`.
9686
+ *
9687
+ * The fallback's own `retryCount` defaults to 0 — each inner transport already
9688
+ * retries itself, and retrying the whole chain on top of that multiplies the
9689
+ * worst-case latency.
9690
+ */
9691
+
9692
+ interface FallbackTransportConfig {
9693
+ key?: string;
9694
+ name?: string;
9695
+ /** Retries of the WHOLE chain (default 0 — the inner transports retry already). */
9696
+ retryCount?: number;
9697
+ retryDelay?: number;
9698
+ /** Called whenever one transport fails and the next is tried. */
9699
+ onTransportError?: (args: {
9700
+ error: unknown;
9701
+ index: number;
9702
+ method: string;
9703
+ }) => void;
9704
+ }
9705
+ interface FallbackTransportValue {
9706
+ transports: TransportInstance[];
9707
+ }
9708
+ declare function fallback(transports: readonly Transport[], config?: FallbackTransportConfig): Transport<'fallback', FallbackTransportValue>;
9709
+
9710
+ /**
9711
+ * JS values → JSON-RPC wire format.
9712
+ *
9713
+ * The RPC wants hex quantities and no `undefined` members; the action layer wants
9714
+ * plain `bigint`/`number`. These are the only two places that translate, so the
9715
+ * actions stay readable — viem's `formatTransactionRequest` / `serializeStateOverride`.
9716
+ */
9717
+
9718
+ /** A transaction request as the actions accept it (plain numbers, no hex). */
9719
+ interface TransactionRequest {
9720
+ /** `from` — the sender an `eth_call` is simulated as. */
9721
+ account?: Address;
9722
+ to?: Address;
9723
+ data?: Hex;
9724
+ value?: bigint;
9725
+ gas?: bigint;
9726
+ gasPrice?: bigint;
9727
+ maxFeePerGas?: bigint;
9728
+ maxPriorityFeePerGas?: bigint;
9729
+ nonce?: number;
9730
+ }
9731
+ /** Per-address overrides applied to the state a call runs against. */
9732
+ interface StateOverrideAccount {
9733
+ balance?: bigint;
9734
+ nonce?: number;
9735
+ code?: Hex;
9736
+ /** Replaces the account's WHOLE storage. */
9737
+ state?: Record<Hex, Hex>;
9738
+ /** Patches individual storage slots, leaving the rest intact. */
9739
+ stateDiff?: Record<Hex, Hex>;
9740
+ }
9741
+ /** `eth_call`'s third parameter: address → overrides. */
9742
+ type StateOverride = Record<Address, StateOverrideAccount>;
9743
+
9744
+ /**
9745
+ * `call` — a read-only `eth_call`, and the base every contract read sits on.
9746
+ *
9747
+ * Beyond forwarding the RPC it does two things worth knowing about:
9748
+ *
9749
+ * - AUTOMATIC MULTICALL BATCHING. When the client was created with
9750
+ * `batch: { multicall: true }`, plain reads issued in the same tick are
9751
+ * folded into ONE Multicall3 `aggregate3` — so code that just awaits a dozen
9752
+ * `readContract`s in parallel gets one round-trip without being rewritten.
9753
+ * Anything ineligible (a value transfer, an explicit gas/nonce, a state
9754
+ * override) silently takes the normal path.
9755
+ * - TYPED FAILURES. A revert arrives as an RPC error carrying the revert bytes;
9756
+ * they are kept on the error chain so `readContract`/`multicall` can decode
9757
+ * the reason against the contract's ABI.
9758
+ */
9759
+
9760
+ interface CallParameters extends TransactionRequest, BlockParameters {
9761
+ /** Temporary state (balances, code, storage) the call is simulated against. */
9762
+ stateOverride?: StateOverride;
9763
+ /**
9764
+ * Send this call on its own, never folded into the client's shared
9765
+ * `aggregate3`.
9766
+ *
9767
+ * Set by the no-Multicall3 fallback: those calls exist PRECISELY because the
9768
+ * chain has no Multicall3, so re-batching them would route them straight back
9769
+ * into the contract that isn't there.
9770
+ */
9771
+ skipBatch?: boolean;
9772
+ }
9773
+ interface CallReturnType {
9774
+ /** Return data, or `undefined` when the call returned nothing (`0x`). */
9775
+ data: Hex | undefined;
9776
+ }
9777
+ /**
9778
+ * Execute a read-only call.
9779
+ *
9780
+ * `blockNumber` / `blockTag` pin the height (default `latest`); `stateOverride`
9781
+ * simulates against modified state.
9782
+ */
9783
+ declare function call(client: Client, args: CallParameters): Promise<CallReturnType>;
9784
+
9785
+ /**
9786
+ * `readContract` — one read: encode the call, send it, decode the return.
9787
+ *
9788
+ * The whole point of the layer: callers name a function and get a JS value back,
9789
+ * with failures already translated into a typed, self-describing error.
9790
+ */
9791
+
9792
+ interface ReadContractParameters extends ContractFunctionParameters, BlockParameters {
9793
+ /** Sender the read is simulated as (`msg.sender` inside the contract). */
9794
+ account?: Address;
9795
+ stateOverride?: StateOverride;
9796
+ }
9797
+ /**
9798
+ * Call a `view`/`pure` function and return its decoded result.
9799
+ *
9800
+ * The return is unwrapped like viem's: a single output comes back as the value
9801
+ * itself, multiple outputs as an array, no outputs as `undefined`.
9802
+ *
9803
+ * ```ts
9804
+ * const balance = await readContract(client, {
9805
+ * address: usdc, abi: erc20Abi, functionName: 'balanceOf', args: [owner],
9806
+ * }); // bigint
9807
+ * ```
9808
+ *
9809
+ * Throws `ContractFunctionExecutionError`; walk its `cause` for the decoded
9810
+ * revert (`ContractFunctionRevertedError`) or the "returned 0x" case
9811
+ * (`ContractFunctionZeroDataError`).
9812
+ */
9813
+ declare function readContract<TResult = unknown>(client: Client, parameters: ReadContractParameters): Promise<TResult>;
9814
+
9815
+ /**
9816
+ * `multicall` — many contract reads, one (or a few) RPC round-trips, via
9817
+ * Multicall3's `aggregate3`.
9818
+ *
9819
+ * Feature-for-feature with viem's:
9820
+ *
9821
+ * - `allowFailure` (default `true`) → results are `{ status, result | error }`,
9822
+ * so ONE reverting call never sinks the batch. `false` → plain values, and the
9823
+ * first failure throws.
9824
+ * - `batchSize` (default 1024 BYTES of calldata, or the client's
9825
+ * `batch.multicall.batchSize`) → oversized sets are split into several
9826
+ * `aggregate3` calls that run in parallel, keeping any single `eth_call`
9827
+ * under the node's response/gas limits. `0` disables splitting.
9828
+ * - `multicallAddress` → override the chain's Multicall3 deployment.
9829
+ * - `blockNumber` / `blockTag` → read at a specific height.
9830
+ * - `stateOverride` → simulate the whole batch against modified state.
9831
+ * - results are POSITIONALLY ALIGNED with `contracts`, always, including entries
9832
+ * whose calldata could not even be encoded.
9833
+ *
9834
+ * ```ts
9835
+ * const results = await multicall(client, {
9836
+ * contracts: [
9837
+ * { address: usdc, abi: erc20Abi, functionName: 'symbol' },
9838
+ * { address: usdc, abi: erc20Abi, functionName: 'balanceOf', args: [owner] },
9839
+ * ],
9840
+ * });
9841
+ * // [{ status: 'success', result: 'USDC' }, { status: 'success', result: 123n }]
9842
+ * ```
9843
+ */
9844
+
9845
+ interface MulticallParameters extends BlockParameters {
9846
+ /** The reads to perform, in order. */
9847
+ contracts: readonly ContractFunctionParameters[];
9848
+ /** Keep going past a failing call (default `true`). */
9849
+ allowFailure?: boolean;
9850
+ /** Max calldata bytes per aggregated call; `0` disables splitting. */
9851
+ batchSize?: number;
9852
+ /** Multicall3 address override — trusted as-is, skipping the deployment probe. */
9853
+ multicallAddress?: Address;
9854
+ /** Sender each read is simulated as. */
9855
+ account?: Address;
9856
+ stateOverride?: StateOverride;
9857
+ /**
9858
+ * Max `eth_call`s in flight on the no-Multicall3 fallback (default 8, or the
9859
+ * client's `batch.multicall.fallbackConcurrency`).
9860
+ */
9861
+ fallbackConcurrency?: number;
9862
+ }
9863
+ declare function multicall(client: Client, parameters: MulticallParameters & {
9864
+ allowFailure?: true;
9865
+ }): Promise<MulticallResult[]>;
9866
+ declare function multicall(client: Client, parameters: MulticallParameters & {
9867
+ allowFailure: false;
9868
+ }): Promise<unknown[]>;
9869
+ declare function multicall(client: Client, parameters: MulticallParameters): Promise<MulticallResult[] | unknown[]>;
9870
+
9871
+ /**
9872
+ * `multicallRaw` — the ABI-less escape hatch under {@link file://./multicall.ts}.
9873
+ *
9874
+ * Same batching, but calls go in as PRE-ENCODED calldata and come back as raw
9875
+ * return data. Use it when there is no ABI to decode against:
9876
+ * - hand-rolled selectors (`0x70a08231` + a padded address),
9877
+ * - non-standard returns a strict decoder would reject (legacy `bytes32`
9878
+ * symbols, contracts that right-pad their strings),
9879
+ * - anything that wants to inspect the bytes before deciding what they mean.
9880
+ *
9881
+ * Prefer {@link file://./multicall.ts} when you do have an ABI: it decodes and
9882
+ * gives typed per-entry errors. This one only ever reports `success: false`.
9883
+ *
9884
+ * Beyond viem's parameters it takes `maxCalls`, a cap on the number of calls per
9885
+ * batch. viem's `batchSize` bounds the REQUEST (calldata bytes); `maxCalls`
9886
+ * bounds the RESPONSE, which is what matters for reads whose returns are large
9887
+ * and unpredictable — on-chain `data:` token URIs being the case this core hits.
9888
+ *
9889
+ * On a chain with NO Multicall3 deployment it falls back to individual
9890
+ * `eth_call`s at bounded concurrency — see {@link file://./multicallFallback.ts}.
9891
+ * The result contract is identical either way, so callers never branch on it.
9892
+ */
9893
+
9894
+ /** One pre-encoded call. */
9895
+ interface RawCall {
9896
+ target: Address;
9897
+ callData: Hex;
9898
+ }
9899
+ /** Multicall3's own per-call outcome, undecoded. */
9900
+ interface RawCallResult {
9901
+ success: boolean;
9902
+ returnData: Hex;
9903
+ }
9904
+ interface MulticallRawParameters extends BlockParameters {
9905
+ calls: readonly RawCall[];
9906
+ /** Max calldata bytes per aggregate3 (default 1024); `0` disables the split. */
9907
+ batchSize?: number;
9908
+ /** Max calls per aggregate3 (default 50) — bounds the RESPONSE size. */
9909
+ maxCalls?: number;
9910
+ multicallAddress?: Address;
9911
+ account?: Address;
9912
+ stateOverride?: StateOverride;
9913
+ /**
9914
+ * Max `eth_call`s in flight on the no-Multicall3 fallback (default 8, or the
9915
+ * client's `batch.multicall.fallbackConcurrency`). Ignored when the chain has
9916
+ * the deployment, where the whole batch is one request anyway.
9917
+ */
9918
+ fallbackConcurrency?: number;
9919
+ }
9920
+ /**
9921
+ * Run pre-encoded calls through `aggregate3`, chunked and in parallel — or, on a
9922
+ * chain with no Multicall3 deployment, as individual `eth_call`s at bounded
9923
+ * concurrency. Both routes return the same thing, so callers never branch.
9924
+ *
9925
+ * NEVER throws for a partial failure: a chunk whose RPC round-trip fails marks
9926
+ * only ITS OWN entries `success: false`, so one bad batch can't sink the rest.
9927
+ * Results are positionally aligned with `calls`.
9928
+ *
9929
+ * Throws only for a misconfiguration that makes the whole call impossible —
9930
+ * no chain on the client and no `multicallAddress`.
9931
+ */
9932
+ declare function multicallRaw(client: Client, parameters: MulticallRawParameters): Promise<RawCallResult[]>;
9933
+
9934
+ /**
9935
+ * Thin chain-state reads — the actions that are a single RPC method plus
9936
+ * hex↔bigint conversion, grouped here rather than spread over a file each.
9937
+ *
9938
+ * (`call`, `readContract` and `multicall` earn their own files: they have real
9939
+ * behaviour — batching, encoding, error translation — behind them.)
9940
+ */
9941
+
9942
+ /** Latest block number. */
9943
+ declare function getBlockNumber(client: Client): Promise<bigint>;
9944
+ /** The chain id the endpoint actually serves — worth checking against `client.chain`. */
9945
+ declare function getChainId(client: Client): Promise<number>;
9946
+ /** Native-coin balance of an address, in wei. */
9947
+ declare function getBalance(client: Client, { address, ...block }: {
9948
+ address: Address;
9949
+ } & BlockParameters): Promise<bigint>;
9950
+ /** Deployed bytecode at an address — `undefined` for an EOA or empty account. */
9951
+ declare function getCode(client: Client, { address, ...block }: {
9952
+ address: Address;
9953
+ } & BlockParameters): Promise<Hex | undefined>;
9954
+ /** Raw storage slot of a contract. */
9955
+ declare function getStorageAt(client: Client, { address, slot, ...block }: {
9956
+ address: Address;
9957
+ slot: Hex;
9958
+ } & BlockParameters): Promise<Hex | undefined>;
9959
+ /** Transaction count of an address — i.e. its next nonce. */
9960
+ declare function getTransactionCount(client: Client, { address, ...block }: {
9961
+ address: Address;
9962
+ } & BlockParameters): Promise<number>;
9963
+ /** Current gas price, in wei. */
9964
+ declare function getGasPrice(client: Client): Promise<bigint>;
9965
+ /** Gas a transaction would consume. */
9966
+ declare function estimateGas(client: Client, { blockNumber, blockTag, ...request }: TransactionRequest & BlockParameters): Promise<bigint>;
9967
+ /** A block, as the node returns it (hex quantities left untouched). */
9968
+ interface RpcBlock {
9969
+ number?: Hex;
9970
+ hash?: Hex;
9971
+ parentHash?: Hex;
9972
+ timestamp?: Hex;
9973
+ gasLimit?: Hex;
9974
+ gasUsed?: Hex;
9975
+ baseFeePerGas?: Hex;
9976
+ transactions?: unknown[];
9977
+ [key: string]: unknown;
9978
+ }
9979
+ /** A block, with the numeric fields decoded. */
9980
+ interface Block extends RpcBlock {
9981
+ blockNumber?: bigint;
9982
+ blockTimestamp?: bigint;
9983
+ baseFee?: bigint;
9984
+ }
9985
+ /** Fetch a block by number/tag. `includeTransactions` returns full tx objects. */
9986
+ declare function getBlock(client: Client, { includeTransactions, ...block }?: {
9987
+ includeTransactions?: boolean;
9988
+ } & BlockParameters): Promise<Block | null>;
9989
+
9990
+ /**
9991
+ * `PublicClient` — the read-only client, and the object most callers hold.
9992
+ *
9993
+ * Same model as viem: a chain + a transport, with the actions exposed as methods.
9994
+ * Written as a CLASS here (rather than viem's object spread) because it is what
9995
+ * this codebase's services look like, and because it makes the surface
9996
+ * discoverable — `client.` lists every read the core can do.
9997
+ *
9998
+ * ```ts
9999
+ * const client = createPublicClient({ chain: base, transport: http() });
10000
+ * const symbol = await client.readContract({ address, abi: erc20Abi, functionName: 'symbol' });
10001
+ * const many = await client.multicall({ contracts });
10002
+ * ```
10003
+ *
10004
+ * Everything on it is READ-ONLY on purpose: this core never holds a private key —
10005
+ * transactions are handed to the wallet app to sign — so there is no
10006
+ * `WalletClient` counterpart, by design rather than omission.
10007
+ */
10008
+
10009
+ interface PublicClientConfig {
10010
+ /** Chain object, hex id (`'0x2105'`) or decimal id (`8453`). */
10011
+ chain?: Chain | string | number;
10012
+ /** How to reach the node. Defaults to `http()` on the chain's RPC URL. */
10013
+ transport?: Transport;
10014
+ /**
10015
+ * Shortcut for `transport: http(rpcUrl)` — the common case in this core, where
10016
+ * the host app supplies an endpoint per chain.
10017
+ */
10018
+ rpcUrl?: string;
10019
+ /** Batching policy; `{ multicall: true }` folds parallel reads into aggregate3. */
10020
+ batch?: ClientBatchConfig;
10021
+ key?: string;
10022
+ name?: string;
10023
+ /** Retries per request (default 3). */
10024
+ retryCount?: number;
10025
+ /** Base retry backoff in ms (default 150). */
10026
+ retryDelay?: number;
10027
+ /** Per-request timeout in ms (default 10_000). */
10028
+ timeout?: number;
10029
+ }
10030
+ declare class PublicClient implements Client {
10031
+ readonly key: string;
10032
+ readonly name: string;
10033
+ readonly uid: string;
10034
+ readonly chain?: Chain;
10035
+ readonly transport: TransportConfig & Record<string, unknown>;
10036
+ readonly batch?: ClientBatchConfig;
10037
+ /** EIP-1193 request fn — retry-wrapped by the transport. */
10038
+ readonly request: EIP1193RequestFn;
10039
+ constructor(config?: PublicClientConfig);
10040
+ /** {@link file://../actions/call.ts} */
10041
+ call(parameters: CallParameters): Promise<CallReturnType>;
10042
+ /** {@link file://../actions/readContract.ts} */
10043
+ readContract<TResult = unknown>(parameters: ReadContractParameters): Promise<TResult>;
10044
+ /** {@link file://../actions/multicall.ts} */
10045
+ multicall(parameters: MulticallParameters & {
10046
+ allowFailure?: true;
10047
+ }): Promise<MulticallResult[]>;
10048
+ multicall(parameters: MulticallParameters & {
10049
+ allowFailure: false;
10050
+ }): Promise<unknown[]>;
10051
+ /** {@link file://../actions/multicallRaw.ts} — pre-encoded calldata, raw returns. */
10052
+ multicallRaw(parameters: MulticallRawParameters): Promise<RawCallResult[]>;
10053
+ getBlockNumber(): Promise<bigint>;
10054
+ getChainId(): Promise<number>;
10055
+ getBalance(parameters: {
10056
+ address: Address;
10057
+ } & BlockParameters): Promise<bigint>;
10058
+ getCode(parameters: {
10059
+ address: Address;
10060
+ } & BlockParameters): Promise<Hex | undefined>;
10061
+ getStorageAt(parameters: {
10062
+ address: Address;
10063
+ slot: Hex;
10064
+ } & BlockParameters): Promise<Hex | undefined>;
10065
+ getTransactionCount(parameters: {
10066
+ address: Address;
10067
+ } & BlockParameters): Promise<number>;
10068
+ getGasPrice(): Promise<bigint>;
10069
+ estimateMaxPriorityFeePerGas(): Promise<bigint>;
10070
+ estimateGas(parameters: TransactionRequest & BlockParameters): Promise<bigint>;
10071
+ getBlock(parameters?: {
10072
+ includeTransactions?: boolean;
10073
+ } & BlockParameters): Promise<Block | null>;
10074
+ /** Raw JSON-RPC, for methods this client doesn't wrap. */
10075
+ rpc<TResult = unknown>(method: string, params?: unknown[]): Promise<TResult>;
10076
+ /**
10077
+ * Attach custom actions — viem's `extend`. Returns a NEW client carrying both
10078
+ * the built-ins and whatever `fn` adds, so domain helpers can live on the
10079
+ * client without subclassing it.
10080
+ *
10081
+ * ```ts
10082
+ * const withToken = client.extend((c) => ({
10083
+ * balanceOf: (token, owner) =>
10084
+ * c.readContract({ address: token, abi: erc20Abi, functionName: 'balanceOf', args: [owner] }),
10085
+ * }));
10086
+ * ```
10087
+ */
10088
+ extend<TExtension extends Record<string, unknown>>(fn: (client: this) => TExtension): this & TExtension;
10089
+ }
10090
+ /**
10091
+ * Create a read-only client — the entry point of the whole chain stack.
10092
+ *
10093
+ * ```ts
10094
+ * createPublicClient({ chain: '0x2105', transport: http() }); // Base, default RPC
10095
+ * createPublicClient({ chain: base, rpcUrl: 'https://…' }); // explicit endpoint
10096
+ * createPublicClient({ chain: base, transport: fallback([http(a), http(b)]) });
10097
+ * createPublicClient({ chain: base, transport: http(), batch: { multicall: true } });
10098
+ * ```
10099
+ */
10100
+ declare function createPublicClient(config?: PublicClientConfig): PublicClient;
10101
+
10102
+ /**
10103
+ * Per-chain client cache — how the REST of this core gets a client.
10104
+ *
10105
+ * Services shouldn't each construct their own: a client is cheap but not free
10106
+ * (a transport instance, a uid, its own batch queues), and two clients on the
10107
+ * same chain would batch SEPARATELY, silently halving the benefit. One cached
10108
+ * instance per (chain, endpoint, batching) triple fixes both.
10109
+ *
10110
+ * The endpoint is part of the key, so a later {@link setRpcOverrides} simply
10111
+ * yields a different key — no invalidation hook, no stale client pinned to the
10112
+ * old URL.
10113
+ *
10114
+ * Clients built here are RESILIENT by default: a chain that declares several
10115
+ * endpoints gets a {@link fallback} transport over all of them, so a flaky
10116
+ * primary costs a retry rather than the whole read. Pass an explicit `rpcUrl` to
10117
+ * pin one endpoint and opt out.
10118
+ */
10119
+
10120
+ interface GetPublicClientOptions {
10121
+ /**
10122
+ * PREFERRED endpoint for this client — tried first, with the chain's own
10123
+ * endpoints kept behind it as backups, exactly as a `setRpcOverrides` entry
10124
+ * behaves. A caller-supplied URL going down therefore degrades to the public
10125
+ * endpoints instead of failing the read.
10126
+ */
10127
+ rpcUrl?: string;
10128
+ /**
10129
+ * Use ONLY `rpcUrl`, with no backups. For the rare caller that must not talk
10130
+ * to any other endpoint (a private or archive node whose answers differ from
10131
+ * a public one's). Ignored when `rpcUrl` is absent.
10132
+ */
10133
+ pinRpcUrl?: boolean;
10134
+ /** Fold parallel reads into one aggregate3 (default `true` — see below). */
10135
+ batch?: boolean;
10136
+ /**
10137
+ * How many `eth_call`s run at once when the chain turns out to have no
10138
+ * Multicall3 and a batch degrades to individual calls (default 8).
10139
+ */
10140
+ fallbackConcurrency?: number;
10141
+ /**
10142
+ * Trust the canonical Multicall3 address without the one-off `eth_getCode`
10143
+ * that verifies it. Saves a request per chain; only safe when every chain this
10144
+ * client touches is known to carry the deployment.
10145
+ */
10146
+ assumeMulticall3?: boolean;
10147
+ }
10148
+ /**
10149
+ * The shared client for a chain, created on first use.
10150
+ *
10151
+ * Multicall batching is ON by default here (unlike a bare `createPublicClient`):
10152
+ * the core's tools routinely fire several independent reads per turn, and folding
10153
+ * them into one round-trip is the difference between one RPC hop and a dozen.
10154
+ *
10155
+ * Throws {@link ChainNotFoundError} when the chain is unknown AND no `rpcUrl` was
10156
+ * given — with a URL, an unknown chain still works for plain reads (only
10157
+ * multicall needs a known Multicall3 deployment).
10158
+ */
10159
+ declare function getPublicClient(chainId: string | number, options?: GetPublicClientOptions): PublicClient;
10160
+ /**
10161
+ * Drop cached clients. Only needed in tests, or after swapping transports at
10162
+ * runtime — override changes are already handled by the cache key.
10163
+ */
10164
+ declare function clearPublicClientCache(): void;
10165
+
10166
+ /**
10167
+ * Address helpers — EIP-55 checksumming and validation, matching viem's
10168
+ * `isAddress` / `getAddress` / `isAddressEqual`.
10169
+ *
10170
+ * The decoder returns CHECKSUMMED addresses (as viem does), so any comparison
10171
+ * against a lowercase literal must go through {@link isAddressEqual} rather than
10172
+ * `===`.
10173
+ */
10174
+
10175
+ /** True for a well-formed 20-byte hex address (any casing). */
10176
+ declare function isAddress(value: unknown): value is Address;
10177
+ /**
10178
+ * EIP-55 checksum casing for an address. Assumes a well-formed input — use
10179
+ * {@link getAddress} when the value comes from outside.
10180
+ */
10181
+ declare function checksumAddress(address: string): Address;
10182
+ /** Validate + checksum an address, throwing on anything malformed. */
10183
+ declare function getAddress(address: string): Address;
10184
+ /** Case-insensitive address comparison — the only correct way to compare two. */
10185
+ declare function isAddressEqual(a: string, b: string): boolean;
10186
+
10187
+ /**
10188
+ * Canonical ABI type formatting + the keccak-derived selectors built from it —
10189
+ * viem's `formatAbiItem` / `toFunctionSelector` / `toEventSelector` /
10190
+ * `toErrorSelector`, plus the array/type parsing the codec shares.
10191
+ *
10192
+ * A selector is keccak256(canonical signature): the signature MUST use canonical
10193
+ * types (`uint` → `uint256`, tuples flattened to `(a,b)`), which is the whole
10194
+ * reason this lives in one place instead of being spelled out at call sites.
10195
+ */
10196
+
10197
+ /** 4-byte function selector from an ABI item or a signature string. */
10198
+ declare function toFunctionSelector(fn: AbiItem | string): Hex;
10199
+ /** 32-byte event topic0 from an ABI item or a signature string. */
10200
+ declare function toEventSelector(event: AbiItem | string): Hex;
10201
+ /**
10202
+ * Find one item on an ABI — viem's `getAbiItem`.
10203
+ *
10204
+ * `name` accepts three spellings, so callers can be as precise as they need:
10205
+ * a plain name (`'balanceOf'`), a full signature (`'balanceOf(address)'`), or a
10206
+ * 4-byte selector (`'0x70a08231'`). OVERLOADS are resolved with `args`: the
10207
+ * candidate whose input list matches the given arguments wins; without `args`
10208
+ * the first overload is used, exactly as viem does.
10209
+ *
10210
+ * Returns `undefined` rather than throwing — callers that require an item throw
10211
+ * {@link AbiItemNotFoundError} themselves (see {@link requireAbiItem}).
10212
+ */
10213
+ declare function getAbiItem({ abi, name, args, type, }: {
10214
+ abi: readonly AbiItem[];
10215
+ name: string;
10216
+ args?: readonly unknown[];
10217
+ /** ABI item kind to search; defaults to `function`. */
10218
+ type?: string;
10219
+ }): AbiItem | undefined;
10220
+
10221
+ /**
10222
+ * ABI parameter ENCODER — head/tail layout per the Solidity ABI spec, mirroring
10223
+ * viem's `encodeAbiParameters` (same `PreparedParam` shape, same recursion).
10224
+ *
10225
+ * Sits next to {@link file://../decode/decodeAbiParameters.ts} so the two halves of
10226
+ * the codec share one set of type helpers.
10227
+ */
10228
+
10229
+ /**
10230
+ * Encode `values` against `params` — the ABI-encoding entry point, positional
10231
+ * like viem's. Tuples accept either an object keyed by component name or a
10232
+ * positional array.
10233
+ */
10234
+ declare function encodeAbiParameters(params: readonly AbiParameter[], values: readonly unknown[]): Hex;
10235
+
10236
+ /**
10237
+ * Calldata builders: selector + ABI-encoded arguments (viem's
10238
+ * `encodeFunctionData` / `encodeErrorResult`).
10239
+ */
10240
+
10241
+ interface EncodeFunctionDataParameters {
10242
+ abi: Abi;
10243
+ /** Function name, full signature (`transfer(address,uint256)`) or 4-byte selector. */
10244
+ functionName: string;
10245
+ args?: readonly unknown[];
10246
+ }
10247
+ /**
10248
+ * Encode a function call — `0x` + 4-byte selector + arguments.
10249
+ *
10250
+ * Overloads are resolved from `args` (see `getAbiItem`), so an ABI carrying both
10251
+ * `safeTransferFrom(address,address,uint256)` and its 4-arg variant picks the one
10252
+ * matching what you passed.
10253
+ */
10254
+ declare function encodeFunctionData({ abi, functionName, args }: EncodeFunctionDataParameters): Hex;
10255
+ interface EncodeErrorResultParameters {
10256
+ abi: Abi;
10257
+ errorName: string;
10258
+ args?: readonly unknown[];
10259
+ }
10260
+ /**
10261
+ * Encode a custom-error revert payload — the shape a reverting contract returns,
10262
+ * useful for tests and for round-tripping {@link file://../decode/decodeErrorResult.ts}.
10263
+ */
10264
+ declare function encodeErrorResult({ abi, errorName, args }: EncodeErrorResultParameters): Hex;
10265
+
10266
+ /**
10267
+ * ABI parameter DECODER — the exact inverse of
10268
+ * {@link file://../encode/encodeAbiParameters.ts}, matching viem's `decodeAbiParameters`
10269
+ * in both coverage and return shapes:
10270
+ *
10271
+ * - `address` → EIP-55 CHECKSUMMED hex (compare with `isAddressEqual`, not `===`)
10272
+ * - `bool` → boolean
10273
+ * - `string` → string
10274
+ * - `bytes`/`bytesN` → 0x hex
10275
+ * - `(u)intN` → `number` for N ≤ 48, `bigint` above (viem's cut-off: 48 bits is
10276
+ * the largest that always fits a JS number exactly)
10277
+ * - `tuple` → object keyed by component name, or an array when any component
10278
+ * is unnamed
10279
+ * - arrays → arrays, fixed or dynamic, nested to any depth
10280
+ *
10281
+ * Every offset/length read is bounds-checked, so a truncated or non-ABI response
10282
+ * raises {@link AbiDecodingOutOfBoundsError} instead of returning silent garbage —
10283
+ * which is what lets `multicall` mark ONE entry as failed and keep the rest.
10284
+ */
10285
+
10286
+ /**
10287
+ * Decode ABI-encoded `data` against `params`, positionally.
10288
+ *
10289
+ * Throws {@link AbiDecodingZeroDataError} for `0x` (the classic "not a contract
10290
+ * on this chain" signal) and {@link AbiDecodingDataSizeTooSmallError} /
10291
+ * {@link AbiDecodingOutOfBoundsError} for a payload that can't hold the shape —
10292
+ * never a partially-filled result.
10293
+ */
10294
+ declare function decodeAbiParameters<T extends readonly unknown[] = readonly unknown[]>(params: readonly AbiParameter[], data: Hex | Uint8Array): T;
10295
+
10296
+ /**
10297
+ * Return-data decoders for a function call — viem's `decodeFunctionResult`, plus
10298
+ * `decodeFunctionData` for the calldata direction.
10299
+ */
10300
+
10301
+ interface DecodeFunctionResultParameters {
10302
+ abi: Abi;
10303
+ /** Function name, full signature or 4-byte selector. */
10304
+ functionName: string;
10305
+ /** Args of the CALL — only used to pick between overloads. */
10306
+ args?: readonly unknown[];
10307
+ data: Hex;
10308
+ }
10309
+ /**
10310
+ * Decode a call's return data against its ABI outputs.
10311
+ *
10312
+ * Follows viem's unwrapping rule, which is what makes reads ergonomic:
10313
+ * - no outputs → `undefined`
10314
+ * - one output → that value directly (`balanceOf` → `bigint`)
10315
+ * - many outputs → the array of values (a named-tuple output still decodes to
10316
+ * an object, since that is the tuple's own shape)
10317
+ */
10318
+ declare function decodeFunctionResult({ abi, functionName, args, data }: DecodeFunctionResultParameters): unknown;
10319
+ interface DecodeFunctionDataParameters {
10320
+ abi: Abi;
10321
+ data: Hex;
10322
+ }
10323
+ /**
10324
+ * Decode CALLDATA (selector + args) back into `{ functionName, args }` — the
10325
+ * inverse of `encodeFunctionData`. Handy for explaining a pending transaction to
10326
+ * the user before they sign it.
10327
+ */
10328
+ declare function decodeFunctionData({ abi, data }: DecodeFunctionDataParameters): {
10329
+ functionName: string;
10330
+ args: readonly unknown[];
10331
+ };
10332
+
10333
+ /**
10334
+ * Revert-payload decoder — viem's `decodeErrorResult`.
10335
+ *
10336
+ * A reverting EVM call returns data in one of three shapes, and this resolves
10337
+ * all three:
10338
+ * - `Error(string)` — `require(cond, "reason")` / `revert("reason")`
10339
+ * - `Panic(uint256)` — compiler-inserted assertions (overflow, /0, bad index …),
10340
+ * whose codes are translated to the human sentences Solidity documents
10341
+ * - a CUSTOM error from the contract's own ABI
10342
+ *
10343
+ * That's what turns "execution reverted" into "ERC20: transfer amount exceeds
10344
+ * balance" in a tool's output, so it is worth having even though multicall marks
10345
+ * the entry failed either way.
10346
+ */
10347
+
10348
+ interface DecodeErrorResultReturnType {
10349
+ /** Decoded error name (`Error`, `Panic`, or a custom one from the ABI). */
10350
+ errorName: string;
10351
+ /** Decoded arguments, `undefined` when the error takes none. */
10352
+ args?: readonly unknown[];
10353
+ /** The ABI item that matched. */
10354
+ abiItem: AbiItem;
10355
+ }
10356
+ /**
10357
+ * Decode revert data against `abi` plus the two built-in Solidity errors.
10358
+ * Throws when the payload is empty or its selector matches nothing — the caller
10359
+ * (the contract-error layer) then reports the raw data instead.
10360
+ */
10361
+ declare function decodeErrorResult({ abi, data }: {
10362
+ abi?: Abi;
10363
+ data: Hex;
10364
+ }): DecodeErrorResultReturnType;
10365
+ /**
10366
+ * The one-line human reason for revert data, or `undefined` when it decodes to
10367
+ * nothing meaningful: the `require` string, the panic sentence, or
10368
+ * `CustomError(arg, arg)`.
10369
+ */
10370
+ declare function getRevertReason({ abi, data }: {
10371
+ abi?: Abi;
10372
+ data: Hex;
10373
+ }): string | undefined;
10374
+
10375
+ /**
10376
+ * Human-readable ABI parser — viem's `parseAbi` / `parseAbiItem` /
10377
+ * `parseAbiParameters`, so an ABI can be written the way it reads in Solidity:
10378
+ *
10379
+ * ```ts
10380
+ * const abi = parseAbi([
10381
+ * 'function balanceOf(address owner) view returns (uint256)',
10382
+ * 'function transfer(address to, uint256 amount) returns (bool)',
10383
+ * 'event Transfer(address indexed from, address indexed to, uint256 value)',
10384
+ * 'error InsufficientBalance(uint256 available, uint256 required)',
10385
+ * ]);
10386
+ * ```
10387
+ *
10388
+ * Supported: functions, events, errors, constructor, fallback, receive; named and
10389
+ * unnamed parameters; `indexed`; data locations (`calldata`/`memory`/`storage`,
10390
+ * ignored as the ABI has no such concept); inline tuples `(uint256 a, bool b)`
10391
+ * with array suffixes at any depth.
10392
+ *
10393
+ * NOT supported (deliberately — it needs a symbol table, and the JSON form is
10394
+ * always available): named `struct` declarations. Write the tuple inline instead.
10395
+ */
10396
+
10397
+ /** A parameter LIST: `address owner, uint256 amount` (no surrounding parens). */
10398
+ declare function parseAbiParameters(signature: string): AbiParameter[];
10399
+ /** Parse ONE human-readable signature into its ABI item. */
10400
+ declare function parseAbiItem(signature: string): AbiItem;
10401
+ /** Parse a whole human-readable ABI. */
10402
+ declare function parseAbi(signatures: readonly string[]): AbiItem[];
10403
+
10404
+ /**
10405
+ * Public facade over the chain stack ({@link file://../chain/index.ts}).
10406
+ *
10407
+ * Two different things live here, and they age differently:
10408
+ *
10409
+ * - ENDPOINT RESOLUTION — `setRpcOverrides` / `resolveRpcUrl` /
10410
+ * `getDefaultRpcUrl` / `DEFAULT_RPC_BY_CHAIN`. Fully supported, simply
10411
+ * re-exported from `chain/chains/registry.ts`, which now owns the table.
10412
+ * - RAW JSON-RPC HELPERS — `rpcCall` / `ethCallAt` / `ethCallByChain`.
10413
+ * DEPRECATED. Nothing inside the core calls them any more (every on-chain
10414
+ * read goes through a client); they stay because they are part of the
10415
+ * published API.
10416
+ *
10417
+ * New code should take a client instead — it adds ABI encode/decode, multicall
10418
+ * batching and typed errors, none of which the raw helpers provide:
10419
+ *
10420
+ * ```ts
10421
+ * const client = getPublicClient('0x2105');
10422
+ * const balance = await client.readContract({ address, abi: erc20Abi, functionName: 'balanceOf', args: [owner] });
10423
+ * ```
10424
+ */
10425
+
10426
+ /**
10427
+ * Low-level JSON-RPC call against an explicit endpoint.
10428
+ *
10429
+ * Runs through the shared transport, so it gets exponential backoff on 429/5xx
10430
+ * (honouring `Retry-After`) and typed errors — the hand-rolled 429 loop this
10431
+ * used to carry is gone. Still throws on an RPC `error` member or an absent
10432
+ * result.
10433
+ *
10434
+ * @deprecated Use `getPublicClient(chainId)` and an action —
10435
+ * `client.rpc(method, params)` for a raw call, `client.readContract(…)` for a
10436
+ * decoded one.
10437
+ */
10438
+ declare function rpcCall<T>(rpcUrl: string, method: string, params?: unknown[]): Promise<T>;
10439
+ /**
10440
+ * `eth_call` against an explicit RPC URL. `data` is the encoded calldata.
10441
+ *
10442
+ * @deprecated Use `getPublicClient(chainId).call({ to, data })`, or
10443
+ * `readContract` when you have an ABI.
10444
+ */
10445
+ declare function ethCallAt(rpcUrl: string, to: string, data: string): Promise<string>;
10446
+ /**
10447
+ * `eth_call` resolving the endpoint from the hex chain id, honouring the shared
10448
+ * overrides. Returns `null` when the chain has no known RPC or the call fails —
10449
+ * callers that need the reason should use {@link ethCallAt}.
10450
+ *
10451
+ * @deprecated Use `getPublicClient(chainId).readContract(…)` — it decodes the
10452
+ * result and reports WHY a read failed instead of collapsing it to `null`.
10453
+ */
10454
+ declare function ethCallByChain(chainId: string, to: string, data: string): Promise<string | null>;
10455
+
8329
10456
  /**
8330
10457
  * Generic x402 (HTTP 402 "pay-per-call") client for the agent core.
8331
10458
  *
@@ -8621,6 +10748,13 @@ declare function createX402SignatureProvider(opts: {
8621
10748
  * underlying (their decimals match it) and yield arrives as a growing
8622
10749
  * `balanceOf`. Converting these would be a bug, so they are left untouched.
8623
10750
  *
10751
+ * - **Oracle-priced shares** (`spark-l2-susds`) — share-based like the first
10752
+ * group, but with no `convertToAssets` to ask: bridged sUSDS is a plain ERC-20
10753
+ * on its chain (the vault stays on Ethereum), so the conversion reads the SSR
10754
+ * oracle's ray-scaled rate and multiplies. Still ONE call per token, decoded
10755
+ * differently — see {@link YieldConversionPlan.rateKeys}. Needs
10756
+ * {@link YieldTokenInput.chain}, since the oracle is per chain.
10757
+ *
8624
10758
  * Which side a token falls on is decided by an explicit allow-list of
8625
10759
  * share-based protocols, mirroring the wallet app's own `LENDING_PLATFORMS`.
8626
10760
  * The protocol classes encode the same split as `balanceIsUnderlying`, but that
@@ -8678,6 +10812,16 @@ interface YieldTokenInput {
8678
10812
  address?: string;
8679
10813
  decimals?: number;
8680
10814
  } | null;
10815
+ /**
10816
+ * Chain id — hex (`'0x2105'`) or decimal (`8453`), both accepted. Needed ONLY
10817
+ * by `spark-l2-susds`, whose conversion goes to that chain's SSR oracle rather
10818
+ * than to the token, and whose oracle address is per chain.
10819
+ *
10820
+ * Optional so existing callers are unaffected: every ERC-4626 type converts
10821
+ * against the token itself and never reads this. A sUSDS row without it is
10822
+ * passed through unconverted rather than converted against a guessed oracle.
10823
+ */
10824
+ chain?: string | number | null;
8681
10825
  }
8682
10826
  /** One declared `convertToAssets` read, tagged with the token it belongs to. */
8683
10827
  interface YieldConversionCall extends MulticallRequest {
@@ -8688,6 +10832,17 @@ interface YieldConversionCall extends MulticallRequest {
8688
10832
  interface YieldConversionPlan {
8689
10833
  /** Reads to perform, in order. Empty when nothing needs converting. */
8690
10834
  calls: YieldConversionCall[];
10835
+ /**
10836
+ * Keys in {@link calls} whose read returns a ray-scaled RATE rather than an
10837
+ * amount — cross-chain sUSDS, which has no `convertToAssets` and is valued
10838
+ * against its chain's SSR oracle instead.
10839
+ *
10840
+ * Exposed so {@link applyYieldConversions} can tell the two apart: decoding a
10841
+ * ray as though it were assets would report a ~10^27 balance. Callers execute
10842
+ * the plan exactly as before and need not consult this — it stays a single
10843
+ * round-trip, and there is no second phase to forget.
10844
+ */
10845
+ rateKeys: string[];
8691
10846
  }
8692
10847
  /** A token's corrected valuation. */
8693
10848
  interface YieldTokenValue {
@@ -8753,6 +10908,210 @@ declare function planYieldTokenConversions(tokens: YieldTokenInput[]): YieldConv
8753
10908
  */
8754
10909
  declare function applyYieldConversions(tokens: YieldTokenInput[], plan: YieldConversionPlan, returns: Array<string | null>): Map<string, YieldTokenValue>;
8755
10910
 
10911
+ /**
10912
+ * Executing half of the yield-token valuation — the transport `yieldTokenValue`
10913
+ * deliberately leaves to its caller, supplied once here so every consumer stops
10914
+ * writing its own.
10915
+ *
10916
+ * {@link file://./yieldTokenValue.ts} stays what it is: two pure, synchronous
10917
+ * functions that declare reads and fold answers back. That split earns its keep —
10918
+ * it is what makes the arithmetic testable without a node. What it did NOT earn
10919
+ * is a copy of the batching, chunking and error-swallowing in every app that
10920
+ * calls it, which is what actually happened: the wallet grew its own `aggregate3`
10921
+ * encoder and its own sequential fallback, duplicating `multicallRead` almost
10922
+ * line for line.
10923
+ *
10924
+ * So this module supplies the missing half against the core's own chain stack:
10925
+ *
10926
+ * - {@link valueYieldTokens} tokens the caller ALREADY described → values
10927
+ * - {@link getTokenPriceUSD} an address → the price of one unit, metadata
10928
+ * fetched here
10929
+ *
10930
+ * ## Why two entry points rather than one
10931
+ *
10932
+ * They differ in who owns the token's yield IDENTITY, and that is not a detail.
10933
+ *
10934
+ * A wallet's token list resolves `yieldProtocol` / `yieldAsset` from several
10935
+ * sources it alone can see — the live API response, the field persisted on the
10936
+ * token, a by-address re-ask, and its own stored snapshot — because no single one
10937
+ * is complete: the chain-wide discovery list omits the tag for real vaults, and a
10938
+ * vault recovered from a snapshot has no live entry at all. A token arriving with
10939
+ * an identity already resolved that way must be valued AS DESCRIBED;
10940
+ * re-fetching it here would see only the first of those sources and would
10941
+ * silently drop the tag, which understates the position by exactly the yield
10942
+ * accrued — the failure this whole area exists to prevent.
10943
+ *
10944
+ * {@link valueYieldTokens} is therefore the honest shape for a list: the caller
10945
+ * describes, this executes. It is also the only shape that is one batch rather
10946
+ * than N requests.
10947
+ *
10948
+ * {@link getTokenPriceUSD} is for the opposite case — a screen holding nothing
10949
+ * but an address (a token detail, a swap target, a search row). There is no
10950
+ * richer identity to respect, so fetching it here is not a loss, and it removes
10951
+ * the fetch-then-convert dance every such caller was repeating.
10952
+ */
10953
+
10954
+ /** Shared options for the calls in this module. */
10955
+ interface YieldPricingOptions {
10956
+ /**
10957
+ * Preferred RPC endpoint. PREFERS rather than replaces: the chain's other
10958
+ * known endpoints stay behind it as backups, so a caller passing its paid
10959
+ * provider keeps a fallback rather than losing one.
10960
+ */
10961
+ rpcUrl?: string;
10962
+ /**
10963
+ * Token API base URL. Defaults to the same Pantograph host the rest of the
10964
+ * core dials.
10965
+ */
10966
+ apiBaseUrl?: string;
10967
+ }
10968
+ /**
10969
+ * Value a set of ALREADY-DESCRIBED tokens, running their conversions in one
10970
+ * batch.
10971
+ *
10972
+ * Exactly {@link planYieldTokenConversions} → execute → {@link
10973
+ * applyYieldConversions}, which is the sequence every caller was writing by
10974
+ * hand. The contract of the two pure halves is preserved unchanged:
10975
+ *
10976
+ * - the returned map has an entry for EVERY input token, converted or not, so
10977
+ * the caller applies it uniformly;
10978
+ * - a failed read is never destructive — that token falls back to
10979
+ * `balance × price` with `converted: false`, so a flaky RPC understates a
10980
+ * position at worst instead of zeroing it;
10981
+ * - nothing convertible plans no calls and costs no RPC.
10982
+ *
10983
+ * `chainId` is also what reaches each input's `chain` field when the caller left
10984
+ * it unset — needed by cross-chain sUSDS, whose conversion goes to that chain's
10985
+ * SSR oracle rather than to the token. An input that names its own `chain` keeps
10986
+ * it, so a caller mixing chains in one array is not silently re-pointed.
10987
+ */
10988
+ declare function valueYieldTokens(chainId: string | number, tokens: YieldTokenInput[], options?: YieldPricingOptions): Promise<Map<string, YieldTokenValue>>;
10989
+ /**
10990
+ * The USD price of ONE unit of a token, in the unit its balance is actually
10991
+ * denominated in.
10992
+ *
10993
+ * The problem this solves is that the token API quotes a share-based vault at
10994
+ * its UNDERLYING asset's price, while the holder's balance is in SHARES — worth
10995
+ * more, and drifting further up as yield accrues. A screen showing the raw API
10996
+ * price therefore disagrees with the same wallet's token list, which converts.
10997
+ *
10998
+ * Conversion runs against a synthetic ONE-share balance, so the answer needs no
10999
+ * wallet balance and is equally right for a vault the user does not hold — the
11000
+ * token they are swapping INTO, say.
11001
+ *
11002
+ * Returns:
11003
+ * - the API price unchanged, and NO RPC, for every plain token and every
11004
+ * rebasing receipt (`aave-v3`, `compound-v3`), whose balance is already the
11005
+ * underlying;
11006
+ * - the per-SHARE price for a share-based vault that converted;
11007
+ * - `null` when there is no usable price, INCLUDING when a share-based vault's
11008
+ * read fails. That last case is deliberate: the API price is known to be in
11009
+ * the wrong unit there, so no price is better than a wrong one, and the
11010
+ * caller falls back to whatever it already had.
11011
+ */
11012
+ declare function getTokenPriceUSD(chainId: string | number, address: string, options?: YieldPricingOptions): Promise<number | null>;
11013
+ /**
11014
+ * The per-unit price of a token the caller has ALREADY fetched.
11015
+ *
11016
+ * Same answer as {@link getTokenPriceUSD} without the request, for callers that
11017
+ * hold an API row already — a search screen listing many tokens, or a wallet
11018
+ * pricing a vault whose zero balance left it nothing to convert.
11019
+ */
11020
+ declare function resolveTokenPriceUSD(chainId: string | number, token: YieldPricingToken, options?: YieldPricingOptions): Promise<number | null>;
11021
+ /** The fields {@link resolveTokenPriceUSD} reads off a token API row. */
11022
+ interface YieldPricingToken {
11023
+ address?: string | null;
11024
+ decimals?: number | string | null;
11025
+ /** The API's quote — for a share-based vault, the UNDERLYING's price. */
11026
+ price?: number | string | null;
11027
+ yieldProtocol?: string | null;
11028
+ yieldAsset?: {
11029
+ address?: string;
11030
+ decimals?: number;
11031
+ } | null;
11032
+ }
11033
+
11034
+ /**
11035
+ * Spark's PSM3 — the one hard-coded address per chain that makes cross-chain
11036
+ * sUSDS describable, and the reason nothing ELSE about it has to be hard-coded.
11037
+ *
11038
+ * ## Why a constant exists here at all
11039
+ *
11040
+ * Every other family in {@link file://./discovery.ts} is identified by probing
11041
+ * the receipt token: an aToken answers `POOL()`, a Comet answers `baseToken()`,
11042
+ * a 4626 vault answers `asset()`. Cross-chain sUSDS answers NONE of them, and
11043
+ * that is by design rather than by omission — Spark's docs are explicit:
11044
+ *
11045
+ * > The crosschain sUSDS token does not contain any ERC4626 functionality -
11046
+ * > this is only available on Ethereum mainnet.
11047
+ *
11048
+ * The reason is where the assets live. Mainnet sUSDS is a real vault holding
11049
+ * USDS; bridging via SkyLink moves only the SHARE token, leaving the USDS on
11050
+ * Ethereum. The token on Base therefore has no assets to report and nothing to
11051
+ * convert against, so `asset()`, `totalAssets()`, `convertToAssets()` and
11052
+ * `rateProvider()` all revert (verified on Base). It is, on chain, a plain
11053
+ * ERC-20 that happens to appreciate.
11054
+ *
11055
+ * With nothing on the token to probe, identification has to come from somewhere
11056
+ * that KNOWS the token, and PSM3 is that somewhere: it is the contract L2 swaps
11057
+ * route through, and it names all three assets plus the rate oracle.
11058
+ *
11059
+ * ## Why the address cannot be derived
11060
+ *
11061
+ * Checked, in order, before settling for a constant:
11062
+ *
11063
+ * - **CREATE2 / deterministic deploy** — no. `spark-psm/deploy/PSM3Deploy.sol`
11064
+ * is a plain `new PSM3(owner, usdc, usds, susds, rateProvider)`, so the
11065
+ * address falls out of the deployer's nonce. The four live deployments below
11066
+ * share no prefix, which is the same fact observed from outside.
11067
+ * - **An on-chain registry** — no. `sparkdotfi/spark-address-registry` is the
11068
+ * canonical source, but it is a Solidity `library` of `constant`s consumed at
11069
+ * COMPILE time; it is not deployed and cannot be called. No npm package
11070
+ * mirrors it either.
11071
+ * - **Sky's Chainlog** (`0xdA0Ab1e0…740F`) — genuinely on-chain and genuinely a
11072
+ * registry, but the wrong one: it lists Sky's MAINNET contracts (`MCD_PSM_*`,
11073
+ * `MCD_LITE_PSM_*`), holds no `PSM3` key, and is deployed only on Ethereum,
11074
+ * so a Base read cannot reach it.
11075
+ * - **A backlink from the token** — no. sUSDS exposes no `psm()`, `oracle()`,
11076
+ * `usds()` or any other pointer (probed; all revert). The relationship runs
11077
+ * one way, PSM3 → token.
11078
+ *
11079
+ * So one anchor per chain is the floor, not a shortcut.
11080
+ *
11081
+ * ## Why THIS constant rather than the obvious three
11082
+ *
11083
+ * The alternative is hard-coding USDS, sUSDS and the SSR oracle per chain.
11084
+ * PSM3 replaces all three because it names them at runtime, which is better on
11085
+ * two counts beyond arithmetic:
11086
+ *
11087
+ * - It is **self-checking**. A wrong PSM3 address makes `susds()` revert or
11088
+ * return a token that matches no holding, and the position simply stays
11089
+ * undiscovered — exactly today's behaviour, no worse. A wrong hard-coded
11090
+ * USDS, by contrast, yields a market that looks correct while describing the
11091
+ * wrong asset, which is the failure `protocols.ts` refuses to make anywhere
11092
+ * else.
11093
+ * - It **tracks upstream**. Spark governance can repoint the rate oracle;
11094
+ * `rateProvider()` follows it with no code change.
11095
+ *
11096
+ * Addresses come from Spark's own registry, quoted with the version comment it
11097
+ * carries so a future reader can diff against it:
11098
+ * https://github.com/sparkdotfi/spark-address-registry/blob/master/src/Base.sol
11099
+ */
11100
+
11101
+ /**
11102
+ * PSM3 on `chain`, or null where Spark has deployed none.
11103
+ *
11104
+ * Accepts hex (`'0x2105'`) or decimal (`8453`) — the lending paths use hex, the
11105
+ * wallet's token list carries numbers, and keying on the raw value would
11106
+ * silently miss one of them.
11107
+ *
11108
+ * Exported from the package because the app needs it too: exiting a cross-chain
11109
+ * sUSDS position is a PSM3 swap, and the app would otherwise keep its own copy
11110
+ * of this table, which is exactly the pair that drifts. This module is the one
11111
+ * place the addresses are recorded and justified.
11112
+ */
11113
+ declare function psm3For(chain: string | number | null | undefined): string | null;
11114
+
8756
11115
  /**
8757
11116
  * PantographService — Pantograph API client.
8758
11117
  *
@@ -8774,6 +11133,28 @@ declare const HEX_TO_PANTOGRAPH: Record<string, string>;
8774
11133
  */
8775
11134
  declare const TRENDING_DEFAULT_BY_HEX_CHAIN: Record<string, string[]>;
8776
11135
  declare function toPantographChain(hexChain: string): string;
11136
+ /** Raw token shape returned by Pantograph list endpoints (pre-normalization). */
11137
+ interface PantographRawToken {
11138
+ address?: string;
11139
+ token_address?: string;
11140
+ price?: number | string;
11141
+ icon_image?: string;
11142
+ decimals?: number | string;
11143
+ /**
11144
+ * Yield identity, carried through verbatim rather than normalised.
11145
+ *
11146
+ * These decide whether a balance is vault SHARES (which must be converted
11147
+ * on-chain before it can be valued) or already the underlying, so the
11148
+ * distinction between an ABSENT tag and a tag of `null` matters to callers:
11149
+ * absent means the question was never answered and should be re-asked, null
11150
+ * means answered "not a vault". Defaulting either one here would erase that.
11151
+ */
11152
+ yieldProtocol?: string | null;
11153
+ yieldAsset?: {
11154
+ address?: string;
11155
+ decimals?: number;
11156
+ } | null;
11157
+ }
8777
11158
  declare class PantographService {
8778
11159
  private baseUrl;
8779
11160
  constructor(config?: PantographServiceConfig);
@@ -8789,6 +11170,25 @@ declare class PantographService {
8789
11170
  * Mutates the array in-place. Non-fatal: silently skips on failure.
8790
11171
  */
8791
11172
  enrichTokenPrices(tokens: TokenBalance[], moralisChain: string): Promise<void>;
11173
+ /**
11174
+ * Raw pricing rows for specific contracts, with their yield identity intact.
11175
+ *
11176
+ * Separate from {@link enrichTokenPrices} because that one answers a different
11177
+ * question: it folds a price and a logo onto balances it was handed, dropping
11178
+ * everything else. Yield valuation needs the fields it drops — `decimals`, and
11179
+ * the `yieldProtocol` / `yieldAsset` pair that decides whether the quoted price
11180
+ * even belongs to the unit the balance is in.
11181
+ *
11182
+ * Rows are returned VERBATIM rather than normalised: `decimals` arrives as a
11183
+ * string on some tokens and an absent `yieldProtocol` must stay absent (see
11184
+ * {@link PantographRawToken}), so coercing here would destroy the very
11185
+ * distinctions the caller reads.
11186
+ *
11187
+ * Accepts a decimal or hex chain id — this route is keyed by the decimal id and
11188
+ * serves every EVM chain, so no per-chain slug is involved. Never throws: a
11189
+ * failed request yields an empty array, and the caller degrades per token.
11190
+ */
11191
+ getYieldPricingTokens(chainId: string | number, addresses: string[]): Promise<Array<PantographRawToken>>;
8792
11192
  /**
8793
11193
  * Fetch metadata + price for a single token from Pantograph.
8794
11194
  * Returns null if the token is not found or the request fails.
@@ -9152,4 +11552,4 @@ declare class AbortError extends Error {
9152
11552
  */
9153
11553
  declare function isAbortError(err: unknown): boolean;
9154
11554
 
9155
- export { AI_AGENT_TOOL_NAMES, AbortError, type AddLiquidityFormProps, type AddLiquiditySummary, type AffiliateFee, type AgentConfig, AgentCore, type AgentResponse, ApproveTokenTool, type ApyPoint, BaseNftAiTool, BaseSwapService, BaseTool, BaseWalletActionTool, type BuyTokenConfirmTxProps, type BuyTokenSide, BuyTokenTool, type ChainMeta, type ChainRef, type ChainSelector, ChatHistory, type ChatMessage, type ChatOptions, type ChatRole, type CheckApprovalParams, type CheckApprovalResult, type ConfirmAddLiquidityTxProps, 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, EstimatePoolYieldTool, type EstimatePoolYieldToolConfig, type ExchangeProviderConfig, type ExecuteSwapParams, type ExecuteSwapResult, GeminiProvider, GeminiSearchAiTool, type GeminiSearchAiToolConfig, HEX_TO_PANTOGRAPH, 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 LendingMarketOverview, LendingMarketsTool, type LendingMarketsToolConfig, type LendingProtocolType, LendingService, type LendingServiceConfig, type LendingSupplyPosition, ManageLiquidityRedirectTool, type MarketplaceLink, type MoralisApiResponse, MoralisService, type MoralisServiceConfig, 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 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, type QuickRate, type RangePreset, type ReActPhase, type ReActStep, type ReActTrace, RelayAdapter, type ResolvedRange, Router, type RouterAssignment, type RouterDecision, SUPPORTED_CHAINS, SUPPORTED_CHAINS_LABEL, SWAP_PROVIDER_CONFIG, SendNativeTool, SendNftTool, SendTokenTool, 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 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 TrendingToken, type TrendingTokenTimeframeBuckets, TrendingTokensTool, type TrendingTokensToolConfig, type UIPayload, UNISWAP_CHAIN_SLUG, 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 YieldTokenInput, type YieldTokenValue, ZERO_ADDRESS, amazonDomainForLanguage, apiClient, applyYieldConversions, buildChallenge, buildRangePresets, buildUniswapPoolUrl, clampTick, completeX402, configureSupportedChains, createAiAgent, createDefaultSubagents, createNfcAgent, createNftAgent, createPoolAgent, createTokenAgent, createWalletActionAgent, createWalletAgent, createX402SignatureProvider, displayFromChallenge, encodeSignedHeader, ethCallAt, ethCallByChain, fetchTopMarketplaces, getAffiliateFee, getChainMeta, getDefaultRpcUrl, getGatewayAddress, getGatewayChains, getNativeTokenInfo, getPositionManagerAddress, getProviderByChain, ingestKnowledgeBase, isAbortError, isPaymentRequired, isShareBasedProtocol, isShareBasedYieldToken, nfcAmazonSearchUrl, normaliseCountry, normalizePriceRangeToPool, planYieldTokenConversions, priceToTick, readPaymentError, readPaymentRequired, readReceipt, registerMaybeNoForm, requestWithX402, resolveNfcShopLinks, resolveRpcUrl, roundTickToSpacing, rpcCall, setRpcOverrides, swapServiceFactory, tickToPrice, toPantographChain };
11555
+ 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 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 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, createAiAgent, createDefaultSubagents, createNfcAgent, createNftAgent, createPoolAgent, createPublicClient, createTokenAgent, createTransport, createWalletActionAgent, createWalletAgent, createX402SignatureProvider, decodeAbiParameters, decodeErrorResult, decodeFunctionData, decodeFunctionResult, displayFromChallenge, 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 };