@agether/sdk 1.6.0 → 1.6.2

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.mts CHANGED
@@ -318,6 +318,71 @@ declare class MorphoClient {
318
318
  * Full status: positions across all discovered markets.
319
319
  */
320
320
  getStatus(): Promise<StatusResult>;
321
+ /**
322
+ * Get the USDC balance of the AgentAccount.
323
+ * @returns USDC balance in raw units (6 decimals)
324
+ */
325
+ getUsdcBalance(): Promise<bigint>;
326
+ /**
327
+ * Calculate the maximum additional USDC that can be borrowed
328
+ * given the agent's current collateral and debt across all markets.
329
+ *
330
+ * For each market with collateral deposited:
331
+ * maxBorrow = (collateralValue * LLTV) - currentDebt
332
+ *
333
+ * Uses the Morpho oracle to price collateral → loan token.
334
+ *
335
+ * @returns Maximum additional USDC borrowable (6 decimals)
336
+ */
337
+ getMaxBorrowable(): Promise<{
338
+ total: bigint;
339
+ byMarket: Array<{
340
+ collateralToken: string;
341
+ maxAdditional: bigint;
342
+ currentDebt: bigint;
343
+ collateralValue: bigint;
344
+ }>;
345
+ }>;
346
+ /**
347
+ * Fetch current supply/borrow APY for a collateral market from Morpho GraphQL API.
348
+ *
349
+ * Note: On Morpho Blue, collateral does NOT earn yield directly. Supply APY
350
+ * is what lenders earn; borrow APY is what borrowers pay.
351
+ */
352
+ getMarketRates(collateralSymbolOrAddress?: string): Promise<Array<{
353
+ collateralToken: string;
354
+ loanToken: string;
355
+ supplyApy: number;
356
+ borrowApy: number;
357
+ utilization: number;
358
+ totalSupplyUsd: number;
359
+ totalBorrowUsd: number;
360
+ lltv: string;
361
+ marketId: string;
362
+ }>>;
363
+ /**
364
+ * Estimate theoretical yield for a given collateral amount over a period.
365
+ *
366
+ * ⚠️ IMPORTANT: On Morpho Blue, collateral does NOT earn yield directly.
367
+ * This estimates what the collateral WOULD earn if it were instead supplied
368
+ * as a lender (not used as collateral). This is a theoretical upper bound
369
+ * useful for setting spending caps.
370
+ *
371
+ * @param collateralSymbol - e.g. 'WETH'
372
+ * @param amount - collateral amount in human-readable (e.g. '1.5')
373
+ * @param periodDays - estimation period in days (default: 1)
374
+ * @param ethPriceUsd - ETH price in USD for value conversion (if not provided, uses oracle)
375
+ * @returns Estimated yield in USD for the period
376
+ */
377
+ getYieldEstimate(collateralSymbol: string, amount: string, periodDays?: number, ethPriceUsd?: number): Promise<{
378
+ collateralToken: string;
379
+ amount: string;
380
+ periodDays: number;
381
+ theoreticalSupplyApy: number;
382
+ estimatedYieldUsd: number;
383
+ collateralValueUsd: number;
384
+ disclaimer: string;
385
+ }>;
321
386
  /**
322
387
  * Deposit collateral into Morpho Blue.
323
388
  *
@@ -409,6 +474,13 @@ declare class MorphoClient {
409
474
  * 4. Client → Resource Server (retries with PAYMENT-SIGNATURE header)
410
475
  * 5. Resource Server → verifies via facilitator → settles → 200 + data
411
476
  *
477
+ * Auto-Draw: When autoDraw is enabled and USDC balance is insufficient,
478
+ * the client automatically borrows from Morpho Blue before paying.
479
+ *
480
+ * Spending Limits: Optional daily spending cap (dailySpendLimitUsdc) and
481
+ * yield-limited spending (yieldLimitedSpending) to keep borrows within
482
+ * theoretical collateral yield.
483
+ *
412
484
  * Chain support: Base (8453), Base Sepolia (84532), Ethereum (1).
413
485
  */
414
486
  interface X402Config {
@@ -417,6 +489,27 @@ interface X402Config {
417
489
  backendUrl: string;
418
490
  agentId?: string;
419
491
  accountAddress?: string;
492
+ /**
493
+ * Auto-draw: automatically borrow from Morpho Blue when USDC balance
494
+ * is insufficient for x402 payment. Requires agentId to be set.
495
+ * Default: false
496
+ */
497
+ autoDraw?: boolean;
498
+ /**
499
+ * Daily spending limit in USDC (e.g. '100' for $100/day).
500
+ * Tracks cumulative daily borrows and rejects auto-draw if exceeded.
501
+ */
502
+ dailySpendLimitUsdc?: string;
503
+ /**
504
+ * When true, auto-calculates the daily spending limit based on
505
+ * theoretical yield of deposited collateral. Overrides dailySpendLimitUsdc.
506
+ */
507
+ yieldLimitedSpending?: boolean;
508
+ /**
509
+ * Safety margin: borrow this much extra beyond what's needed (in USDC, e.g. '1').
510
+ * Helps avoid rounding issues. Default: '0.5'
511
+ */
512
+ autoDrawBuffer?: string;
420
513
  }
421
514
  interface X402Response<T = unknown> {
422
515
  success: boolean;
@@ -428,6 +521,11 @@ interface X402Response<T = unknown> {
428
521
  network: string;
429
522
  txHash?: string;
430
523
  };
524
+ autoDrawInfo?: {
525
+ borrowed: string;
526
+ borrowTx: string;
527
+ reason: string;
528
+ };
431
529
  }
432
530
  /** One item inside the `accepts` array returned by the resource server */
433
531
  interface PaymentRequirements {
@@ -439,15 +537,58 @@ interface PaymentRequirements {
439
537
  maxTimeoutSeconds: number;
440
538
  extra?: Record<string, unknown>;
441
539
  }
540
+ /** Spending tracker — tracks cumulative daily borrows */
541
+ interface SpendingTracker {
542
+ /** Date string (YYYY-MM-DD UTC) */
543
+ date: string;
544
+ /** Cumulative USDC borrowed today (6 decimal raw units) */
545
+ totalBorrowed: bigint;
546
+ /** Daily limit in raw units (6 decimals), 0 = unlimited */
547
+ dailyLimit: bigint;
548
+ }
442
549
  declare class X402Client {
443
550
  private config;
444
551
  private paidFetch;
445
552
  private address;
553
+ private _spendingTracker;
446
554
  constructor(config: X402Config);
447
555
  get<T = unknown>(url: string, opts?: RequestInit): Promise<X402Response<T>>;
448
556
  post<T = unknown>(url: string, body?: unknown, opts?: RequestInit): Promise<X402Response<T>>;
449
557
  getAddress(): string;
558
+ /** Get the current spending tracker state */
559
+ getSpendingTracker(): SpendingTracker;
560
+ /** Get remaining daily spending allowance in USDC (human-readable) */
561
+ getRemainingDailyAllowance(): string;
562
+ /**
563
+ * Pay with auto-draw: Make an x402 request with automatic Morpho borrowing.
564
+ *
565
+ * Flow:
566
+ * 1. Check USDC balance on AgentAccount
567
+ * 2. Probe the URL to discover payment amount (if 402)
568
+ * 3. If insufficient USDC, calculate deficit
569
+ * 4. Check spending limit
570
+ * 5. Borrow from Morpho via MorphoClient
571
+ * 6. Proceed with x402 payment
572
+ */
573
+ payWithAutoDraw<T = unknown>(url: string, opts?: RequestInit & {
574
+ morphoClient?: any;
575
+ }): Promise<X402Response<T>>;
450
576
  private request;
577
+ /**
578
+ * Probe a URL to discover payment requirements without paying.
579
+ * Makes a request and parses the 402 PAYMENT-REQUIRED header.
580
+ * @returns Payment amount in raw USDC units (6 decimals), or null if not a 402.
581
+ */
582
+ private _probePaymentAmount;
583
+ /** Reset spending tracker if it's a new day */
584
+ private _resetTrackerIfNewDay;
585
+ /** Track a new spending amount */
586
+ private _trackSpending;
587
+ /**
588
+ * Check if a borrow amount is within spending limits.
589
+ * Considers both fixed daily limits and yield-limited spending.
590
+ */
591
+ private _checkSpendingLimit;
451
592
  }
452
593
 
453
594
  /**
@@ -805,4 +946,4 @@ declare function getDefaultConfig(chainId: ChainId): AgetherConfig;
805
946
  */
806
947
  declare function createConfig(chainId: ChainId, options?: Partial<AgetherConfig>): AgetherConfig;
807
948
 
808
- export { ACCOUNT_FACTORY_ABI, AGENT_ACCOUNT_ABI, AGENT_REPUTATION_ABI, AgentIdentityClient, type AgentIdentityClientOptions, AgentNotApprovedError, AgetherClient, type AgetherClientOptions, type AgetherConfig, AgetherError, type BalancesResult, type BorrowResult, ChainId, type ContractAddresses, type DepositAndBorrowResult, type DepositResult, ERC20_ABI, type FundResult, IDENTITY_REGISTRY_ABI, InsufficientBalanceError, MORPHO_BLUE_ABI, MorphoClient, type MorphoClientConfig, type MorphoMarketInfo, type MorphoMarketParams, type MorphoPosition, type PaymentRequirements, type PositionResult, type RegisterResult, type RepayResult, type ScoreAttestation, type ScoreResult, ScoringClient, type ScoringClientConfig, ScoringRejectedError, type StatusResult, type TransactionResult, VALIDATION_REGISTRY_ABI, type WithdrawResult, X402Client, type X402Config, type X402PaymentRequest, type X402PaymentResult, type X402Response, bpsToRate, createConfig, formatAPR, formatAddress, formatHealthFactor, formatPercent, formatTimestamp, formatUSD, formatUnits, getDefaultConfig, parseUnits, rateToBps };
949
+ export { ACCOUNT_FACTORY_ABI, AGENT_ACCOUNT_ABI, AGENT_REPUTATION_ABI, AgentIdentityClient, type AgentIdentityClientOptions, AgentNotApprovedError, AgetherClient, type AgetherClientOptions, type AgetherConfig, AgetherError, type BalancesResult, type BorrowResult, ChainId, type ContractAddresses, type DepositAndBorrowResult, type DepositResult, ERC20_ABI, type FundResult, IDENTITY_REGISTRY_ABI, InsufficientBalanceError, MORPHO_BLUE_ABI, MorphoClient, type MorphoClientConfig, type MorphoMarketInfo, type MorphoMarketParams, type MorphoPosition, type PaymentRequirements, type PositionResult, type RegisterResult, type RepayResult, type ScoreAttestation, type ScoreResult, ScoringClient, type ScoringClientConfig, ScoringRejectedError, type SpendingTracker, type StatusResult, type TransactionResult, VALIDATION_REGISTRY_ABI, type WithdrawResult, X402Client, type X402Config, type X402PaymentRequest, type X402PaymentResult, type X402Response, bpsToRate, createConfig, formatAPR, formatAddress, formatHealthFactor, formatPercent, formatTimestamp, formatUSD, formatUnits, getDefaultConfig, parseUnits, rateToBps };
package/dist/index.d.ts CHANGED
@@ -318,6 +318,71 @@ declare class MorphoClient {
318
318
  * Full status: positions across all discovered markets.
319
319
  */
320
320
  getStatus(): Promise<StatusResult>;
321
+ /**
322
+ * Get the USDC balance of the AgentAccount.
323
+ * @returns USDC balance in raw units (6 decimals)
324
+ */
325
+ getUsdcBalance(): Promise<bigint>;
326
+ /**
327
+ * Calculate the maximum additional USDC that can be borrowed
328
+ * given the agent's current collateral and debt across all markets.
329
+ *
330
+ * For each market with collateral deposited:
331
+ * maxBorrow = (collateralValue * LLTV) - currentDebt
332
+ *
333
+ * Uses the Morpho oracle to price collateral → loan token.
334
+ *
335
+ * @returns Maximum additional USDC borrowable (6 decimals)
336
+ */
337
+ getMaxBorrowable(): Promise<{
338
+ total: bigint;
339
+ byMarket: Array<{
340
+ collateralToken: string;
341
+ maxAdditional: bigint;
342
+ currentDebt: bigint;
343
+ collateralValue: bigint;
344
+ }>;
345
+ }>;
346
+ /**
347
+ * Fetch current supply/borrow APY for a collateral market from Morpho GraphQL API.
348
+ *
349
+ * Note: On Morpho Blue, collateral does NOT earn yield directly. Supply APY
350
+ * is what lenders earn; borrow APY is what borrowers pay.
351
+ */
352
+ getMarketRates(collateralSymbolOrAddress?: string): Promise<Array<{
353
+ collateralToken: string;
354
+ loanToken: string;
355
+ supplyApy: number;
356
+ borrowApy: number;
357
+ utilization: number;
358
+ totalSupplyUsd: number;
359
+ totalBorrowUsd: number;
360
+ lltv: string;
361
+ marketId: string;
362
+ }>>;
363
+ /**
364
+ * Estimate theoretical yield for a given collateral amount over a period.
365
+ *
366
+ * ⚠️ IMPORTANT: On Morpho Blue, collateral does NOT earn yield directly.
367
+ * This estimates what the collateral WOULD earn if it were instead supplied
368
+ * as a lender (not used as collateral). This is a theoretical upper bound
369
+ * useful for setting spending caps.
370
+ *
371
+ * @param collateralSymbol - e.g. 'WETH'
372
+ * @param amount - collateral amount in human-readable (e.g. '1.5')
373
+ * @param periodDays - estimation period in days (default: 1)
374
+ * @param ethPriceUsd - ETH price in USD for value conversion (if not provided, uses oracle)
375
+ * @returns Estimated yield in USD for the period
376
+ */
377
+ getYieldEstimate(collateralSymbol: string, amount: string, periodDays?: number, ethPriceUsd?: number): Promise<{
378
+ collateralToken: string;
379
+ amount: string;
380
+ periodDays: number;
381
+ theoreticalSupplyApy: number;
382
+ estimatedYieldUsd: number;
383
+ collateralValueUsd: number;
384
+ disclaimer: string;
385
+ }>;
321
386
  /**
322
387
  * Deposit collateral into Morpho Blue.
323
388
  *
@@ -409,6 +474,13 @@ declare class MorphoClient {
409
474
  * 4. Client → Resource Server (retries with PAYMENT-SIGNATURE header)
410
475
  * 5. Resource Server → verifies via facilitator → settles → 200 + data
411
476
  *
477
+ * Auto-Draw: When autoDraw is enabled and USDC balance is insufficient,
478
+ * the client automatically borrows from Morpho Blue before paying.
479
+ *
480
+ * Spending Limits: Optional daily spending cap (dailySpendLimitUsdc) and
481
+ * yield-limited spending (yieldLimitedSpending) to keep borrows within
482
+ * theoretical collateral yield.
483
+ *
412
484
  * Chain support: Base (8453), Base Sepolia (84532), Ethereum (1).
413
485
  */
414
486
  interface X402Config {
@@ -417,6 +489,27 @@ interface X402Config {
417
489
  backendUrl: string;
418
490
  agentId?: string;
419
491
  accountAddress?: string;
492
+ /**
493
+ * Auto-draw: automatically borrow from Morpho Blue when USDC balance
494
+ * is insufficient for x402 payment. Requires agentId to be set.
495
+ * Default: false
496
+ */
497
+ autoDraw?: boolean;
498
+ /**
499
+ * Daily spending limit in USDC (e.g. '100' for $100/day).
500
+ * Tracks cumulative daily borrows and rejects auto-draw if exceeded.
501
+ */
502
+ dailySpendLimitUsdc?: string;
503
+ /**
504
+ * When true, auto-calculates the daily spending limit based on
505
+ * theoretical yield of deposited collateral. Overrides dailySpendLimitUsdc.
506
+ */
507
+ yieldLimitedSpending?: boolean;
508
+ /**
509
+ * Safety margin: borrow this much extra beyond what's needed (in USDC, e.g. '1').
510
+ * Helps avoid rounding issues. Default: '0.5'
511
+ */
512
+ autoDrawBuffer?: string;
420
513
  }
421
514
  interface X402Response<T = unknown> {
422
515
  success: boolean;
@@ -428,6 +521,11 @@ interface X402Response<T = unknown> {
428
521
  network: string;
429
522
  txHash?: string;
430
523
  };
524
+ autoDrawInfo?: {
525
+ borrowed: string;
526
+ borrowTx: string;
527
+ reason: string;
528
+ };
431
529
  }
432
530
  /** One item inside the `accepts` array returned by the resource server */
433
531
  interface PaymentRequirements {
@@ -439,15 +537,58 @@ interface PaymentRequirements {
439
537
  maxTimeoutSeconds: number;
440
538
  extra?: Record<string, unknown>;
441
539
  }
540
+ /** Spending tracker — tracks cumulative daily borrows */
541
+ interface SpendingTracker {
542
+ /** Date string (YYYY-MM-DD UTC) */
543
+ date: string;
544
+ /** Cumulative USDC borrowed today (6 decimal raw units) */
545
+ totalBorrowed: bigint;
546
+ /** Daily limit in raw units (6 decimals), 0 = unlimited */
547
+ dailyLimit: bigint;
548
+ }
442
549
  declare class X402Client {
443
550
  private config;
444
551
  private paidFetch;
445
552
  private address;
553
+ private _spendingTracker;
446
554
  constructor(config: X402Config);
447
555
  get<T = unknown>(url: string, opts?: RequestInit): Promise<X402Response<T>>;
448
556
  post<T = unknown>(url: string, body?: unknown, opts?: RequestInit): Promise<X402Response<T>>;
449
557
  getAddress(): string;
558
+ /** Get the current spending tracker state */
559
+ getSpendingTracker(): SpendingTracker;
560
+ /** Get remaining daily spending allowance in USDC (human-readable) */
561
+ getRemainingDailyAllowance(): string;
562
+ /**
563
+ * Pay with auto-draw: Make an x402 request with automatic Morpho borrowing.
564
+ *
565
+ * Flow:
566
+ * 1. Check USDC balance on AgentAccount
567
+ * 2. Probe the URL to discover payment amount (if 402)
568
+ * 3. If insufficient USDC, calculate deficit
569
+ * 4. Check spending limit
570
+ * 5. Borrow from Morpho via MorphoClient
571
+ * 6. Proceed with x402 payment
572
+ */
573
+ payWithAutoDraw<T = unknown>(url: string, opts?: RequestInit & {
574
+ morphoClient?: any;
575
+ }): Promise<X402Response<T>>;
450
576
  private request;
577
+ /**
578
+ * Probe a URL to discover payment requirements without paying.
579
+ * Makes a request and parses the 402 PAYMENT-REQUIRED header.
580
+ * @returns Payment amount in raw USDC units (6 decimals), or null if not a 402.
581
+ */
582
+ private _probePaymentAmount;
583
+ /** Reset spending tracker if it's a new day */
584
+ private _resetTrackerIfNewDay;
585
+ /** Track a new spending amount */
586
+ private _trackSpending;
587
+ /**
588
+ * Check if a borrow amount is within spending limits.
589
+ * Considers both fixed daily limits and yield-limited spending.
590
+ */
591
+ private _checkSpendingLimit;
451
592
  }
452
593
 
453
594
  /**
@@ -805,4 +946,4 @@ declare function getDefaultConfig(chainId: ChainId): AgetherConfig;
805
946
  */
806
947
  declare function createConfig(chainId: ChainId, options?: Partial<AgetherConfig>): AgetherConfig;
807
948
 
808
- export { ACCOUNT_FACTORY_ABI, AGENT_ACCOUNT_ABI, AGENT_REPUTATION_ABI, AgentIdentityClient, type AgentIdentityClientOptions, AgentNotApprovedError, AgetherClient, type AgetherClientOptions, type AgetherConfig, AgetherError, type BalancesResult, type BorrowResult, ChainId, type ContractAddresses, type DepositAndBorrowResult, type DepositResult, ERC20_ABI, type FundResult, IDENTITY_REGISTRY_ABI, InsufficientBalanceError, MORPHO_BLUE_ABI, MorphoClient, type MorphoClientConfig, type MorphoMarketInfo, type MorphoMarketParams, type MorphoPosition, type PaymentRequirements, type PositionResult, type RegisterResult, type RepayResult, type ScoreAttestation, type ScoreResult, ScoringClient, type ScoringClientConfig, ScoringRejectedError, type StatusResult, type TransactionResult, VALIDATION_REGISTRY_ABI, type WithdrawResult, X402Client, type X402Config, type X402PaymentRequest, type X402PaymentResult, type X402Response, bpsToRate, createConfig, formatAPR, formatAddress, formatHealthFactor, formatPercent, formatTimestamp, formatUSD, formatUnits, getDefaultConfig, parseUnits, rateToBps };
949
+ export { ACCOUNT_FACTORY_ABI, AGENT_ACCOUNT_ABI, AGENT_REPUTATION_ABI, AgentIdentityClient, type AgentIdentityClientOptions, AgentNotApprovedError, AgetherClient, type AgetherClientOptions, type AgetherConfig, AgetherError, type BalancesResult, type BorrowResult, ChainId, type ContractAddresses, type DepositAndBorrowResult, type DepositResult, ERC20_ABI, type FundResult, IDENTITY_REGISTRY_ABI, InsufficientBalanceError, MORPHO_BLUE_ABI, MorphoClient, type MorphoClientConfig, type MorphoMarketInfo, type MorphoMarketParams, type MorphoPosition, type PaymentRequirements, type PositionResult, type RegisterResult, type RepayResult, type ScoreAttestation, type ScoreResult, ScoringClient, type ScoringClientConfig, ScoringRejectedError, type SpendingTracker, type StatusResult, type TransactionResult, VALIDATION_REGISTRY_ABI, type WithdrawResult, X402Client, type X402Config, type X402PaymentRequest, type X402PaymentResult, type X402Response, bpsToRate, createConfig, formatAPR, formatAddress, formatHealthFactor, formatPercent, formatTimestamp, formatUSD, formatUnits, getDefaultConfig, parseUnits, rateToBps };
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAIH,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,YAAY,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAEpE,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,YAAY,EACV,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,cAAc,EACd,YAAY,EACZ,aAAa,EACb,YAAY,EACZ,sBAAsB,EACtB,WAAW,EACX,cAAc,EACd,UAAU,GACX,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,YAAY,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAEnE,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACpE,YAAY,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAEhF,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAI3G,cAAc,SAAS,CAAC;AAIxB,OAAO,EACL,UAAU,EACV,WAAW,EACX,SAAS,EACT,aAAa,EACb,SAAS,EACT,kBAAkB,EAClB,aAAa,EACb,eAAe,EACf,SAAS,EACT,SAAS,GACV,MAAM,gBAAgB,CAAC;AAIxB,OAAO,EACL,qBAAqB,EACrB,mBAAmB,EACnB,iBAAiB,EACjB,oBAAoB,EACpB,uBAAuB,EACvB,eAAe,EACf,SAAS,GACV,MAAM,cAAc,CAAC;AAItB,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC"}