npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@agether/sdk

v2.6.1

Published

TypeScript SDK for Agether - autonomous credit for AI agents on Base

Readme

@agether/sdk

TypeScript SDK for Agether — autonomous credit for AI agents on Ethereum.

Installation

npm install @agether/sdk
# or
yarn add @agether/sdk

📦 SDK Overview

| Client | Purpose | |--------|---------| | AgetherClient | Main client for AI agents — apply, draw, repay credit | | VaultClient | LP operations — deposit, withdraw, check yields | | ScoringClient | Risk checks and scoring service integration | | AgentIdentityClient | ERC-8004 identity via ag0 integration |


🚀 Quick Start

For AI Agents

import { AgetherClient, ChainId, parseUnits } from '@agether/sdk';

// Initialize client
const client = AgetherClient.fromPrivateKey(
  process.env.AGENT_PRIVATE_KEY!,
  BigInt(123), // Your ERC-8004 agent ID
  {
    chainId: ChainId.Ethereum,
    rpcUrl: 'https://eth.llamarpc.com',
    contracts: {
      creditRegistry: '0x...',
      creditVault: '0x...',
    },
    scoringEndpoint: 'https://scoring.agether.ai/v1',
  }
);

// Apply for credit
const creditLineId = await client.apply({
  agentId: BigInt(123),
  requestedLimit: parseUnits('1000', 6), // $1,000 USDC
});

// Scoring service will approve/reject automatically
// Wait for approval event or poll status...

// Draw funds
const result = await client.draw({
  creditLineId,
  amount: parseUnits('50', 6), // $50 USDC
  recipient: '0x...', // Service address
});

console.log('Draw TX:', result.txHash);

// Check balance
const available = await client.getAvailableCredit();
console.log('Available:', available);

// Repay
await client.repay({
  creditLineId,
  amount: parseUnits('52', 6), // $52 (principal + interest)
});

For Liquidity Providers

import { VaultClient, ChainId, parseUnits, formatUnits } from '@agether/sdk';

const vault = new VaultClient({
  config: {
    chainId: ChainId.Ethereum,
    rpcUrl: 'https://eth.llamarpc.com',
    contracts: { creditVault: '0x...' },
  },
  signer: yourSigner,
});

// Deposit USDC
await vault.deposit(parseUnits('10000', 6)); // $10,000

// Check position
const position = await vault.getPosition();
console.log('Shares:', position.shares);
console.log('Value:', formatUnits(position.assets, 6), 'USDC');

// Get vault stats
const stats = await vault.getStats();
console.log('Utilization:', stats.utilizationRate, '%');

// Withdraw
await vault.withdraw(parseUnits('5000', 6));

🔐 Signing Modes

Both MorphoClient (ethers) and X402Client (viem) support two mutually exclusive signing modes: private key (SDK-managed wallet) and external signer/wallet (custody-agnostic).

MorphoClient — Private Key

import { MorphoClient } from '@agether/sdk';

const client = new MorphoClient({
  privateKey: process.env.AGENT_PRIVATE_KEY!,
  rpcUrl: 'https://mainnet.base.org',
  agentId: '42',
});

MorphoClient — External Signer (ethers.AbstractSigner)

import { MorphoClient, AgetherSigner } from '@agether/sdk';

// Any ethers.AbstractSigner works:
// - ethers.Wallet
// - Privy embedded wallet signer
// - Bankr custodial signer
// - Turnkey / MPC wallet signer
// - MetaMask via BrowserProvider.getSigner()
const signer: AgetherSigner = getSignerFromCustodyProvider();

const client = new MorphoClient({
  signer,
  rpcUrl: 'https://mainnet.base.org',
  agentId: '42',
});

// All operations work identically regardless of signing mode
const status = await client.getStatus();
await client.supplyCollateral('WETH', '0.1');
await client.borrow('100');

Note: When using an external signer, the SDK treats it as immutable — it will never recreate or reconnect the signer. Nonce management is the caller's responsibility.

X402Client — Private Key

import { X402Client } from '@agether/sdk';

const client = new X402Client({
  privateKey: process.env.AGENT_PRIVATE_KEY!,
  rpcUrl: 'https://mainnet.base.org',
  backendUrl: 'https://api.agether.ai',
  agentId: '42',
});

X402Client — viem WalletClient (Privy, Turnkey, etc.)

import { X402Client, AgetherViemWallet } from '@agether/sdk';

// Any viem WalletClient with an attached account works:
// - Privy embedded wallet → createWalletClient(...)
// - Turnkey signer → turnkeyToViemAccount(...)
// - MetaMask → createWalletClient({ transport: custom(window.ethereum) })
const walletClient: AgetherViemWallet = privyWalletClient;

const client = new X402Client({
  walletClient,
  rpcUrl: 'https://mainnet.base.org',
  backendUrl: 'https://api.agether.ai',
  agentId: '42',
});

// All x402 operations work identically regardless of signing mode
const result = await client.get('https://paid-api.example.com/data');

Note: The walletClient must have an account property set (i.e. created with createWalletClient({ account: ... })). The SDK will never recreate or reconnect the client.


📚 API Reference

AgetherClient

Main client for AI agents to manage credit lines.

Constructor

// From private key
const client = AgetherClient.fromPrivateKey(privateKey, agentId, config);

// From signer (ethers.js or viem)
const client = new AgetherClient({ config, signer, agentId });

Methods

| Method | Returns | Description | |--------|---------|-------------| | apply(application) | Promise<bigint> | Apply for a credit line | | getCreditLine(id?) | Promise<CreditLine> | Get credit line details | | getAvailableCredit() | Promise<bigint> | Get available credit | | getTotalDebt() | Promise<bigint> | Get total debt (principal + interest) | | draw(request) | Promise<DrawResult> | Draw funds from credit line | | repay(request) | Promise<RepayResult> | Repay credit line | | repayFull() | Promise<RepayResult> | Repay entire debt | | isHealthy() | Promise<boolean> | Check if position is healthy | | getStatus() | Promise<CreditStatus> | Get credit line status |


VaultClient

Client for liquidity providers.

Methods

| Method | Returns | Description | |--------|---------|-------------| | deposit(amount) | Promise<DepositResult> | Deposit USDC to vault | | withdraw(amount) | Promise<WithdrawResult> | Withdraw USDC from vault | | redeem(shares) | Promise<WithdrawResult> | Redeem shares for USDC | | getStats() | Promise<VaultStats> | Get vault statistics | | getPosition(address?) | Promise<LPPosition> | Get LP position | | maxDeposit() | Promise<bigint> | Max depositable amount | | maxWithdraw() | Promise<bigint> | Max withdrawable amount |


ScoringClient

Client for the off-chain scoring service.

Methods

| Method | Returns | Description | |--------|---------|-------------| | evaluateCredit(request) | Promise<ScoringResult> | Request credit evaluation | | checkRisk(agentId, amount) | Promise<RiskCheckResponse> | Quick risk check | | getStatus() | Promise<ServiceStatus> | Get service status |

Usage

import { ScoringClient } from '@agether/sdk';

const scoring = new ScoringClient('https://scoring.agether.ai/v1');

// Check risk score for a potential draw
const risk = await scoring.checkRisk(BigInt(123), parseUnits('50', 6));

console.log('Risk score:', risk.riskScore);
console.log('Level:', risk.level); // 'low' | 'medium' | 'high'
console.log('Would approve:', risk.wouldApprove);

// Get detailed evaluation
const result = await scoring.evaluateCredit({
  agentId: BigInt(123),
  requestedLimit: parseUnits('1000', 6),
  context: {
    purpose: 'API payments',
  },
});

if (result.approved) {
  console.log('Credit limit:', result.creditLimit);
  console.log('APR:', result.aprBps / 100, '%');
}

AgentIdentityClient

Client for ERC-8004 agent identity management via ag0 SDK.

Methods

| Method | Returns | Description | |--------|---------|-------------| | register() | Promise<{agentId}> | Minimal agent registration | | registerWithURI(uri) | Promise<{agentId}> | Register with metadata URI | | getReputation(agentId) | Promise<Reputation> | Get ERC-8004 reputation | | verifyForCredit(agentId) | Promise<CreditCheck> | Verify credit eligibility | | isOwner(agentId, address) | Promise<boolean> | Check agent ownership |


🔒 KYA (Know Your Agent) Gate

The protocol includes an optional KYA code verification gate. When enabled, agents must have their code approved by a validator in the ValidationRegistry before they can call execute() or executeBatch() on their AgentAccount.

When is it active?

  • If the AccountFactory was deployed with a non-zero validationRegistry address, KYA is enabled
  • If validationRegistry = address(0), KYA is disabled — agents can transact immediately after registration

Checking from the SDK:

const kyaRequired = await client.isKyaRequired();
if (kyaRequired) {
  console.log('KYA gate is active — agent code must be approved before executing');
} else {
  console.log('KYA gate is disabled — agents can execute immediately');
}

The register() method also returns kyaRequired: boolean so consumers know the state at registration time.


📝 Types

CreditStatus

enum CreditStatus {
  Pending = 0,      // Application submitted
  Active = 1,       // Approved and usable
  Frozen = 2,       // Temporarily suspended
  Liquidating = 3,  // In liquidation process
  Defaulted = 4,    // Permanently defaulted
  Closed = 5,       // Voluntarily closed
}

ChainId

enum ChainId {
  Ethereum = 1,
  Sepolia = 11155111,
}

CreditLine

interface CreditLine {
  creditLineId: bigint;
  agentId: bigint;
  limit: bigint;
  used: bigint;
  aprBps: bigint;
  accruedInterest: bigint;
  status: CreditStatus;
  createdAt: bigint;
  lastActivityAt: bigint;
}

⚠️ Error Handling

import { 
  AgetherError, 
  InsufficientCreditError, 
  ScoringRejectedError,
  CreditNotActiveError,
} from '@agether/sdk';

try {
  await client.draw({ ... });
} catch (error) {
  if (error instanceof InsufficientCreditError) {
    console.log('Not enough credit');
    console.log('Available:', error.details?.available);
    console.log('Requested:', error.details?.requested);
  } else if (error instanceof ScoringRejectedError) {
    console.log('Scoring rejected');
    console.log('Risk score:', error.details?.riskScore);
    console.log('Reason:', error.details?.reason);
  } else if (error instanceof CreditNotActiveError) {
    console.log('Credit line status:', error.details?.status);
  } else if (error instanceof AgetherError) {
    console.log('Agether error:', error.message);
  }
}

🔧 Utilities

import { 
  parseUnits, 
  formatUnits, 
  formatUSD,
  formatPercent,
  formatAPR,
  formatAddress,
  getDefaultConfig,
  getUSDCAddress,
} from '@agether/sdk';

// Parse $100 USDC
const amount = parseUnits('100', 6); // 100000000n

// Format for display
console.log(formatUnits(amount, 6));  // "100.000000"
console.log(formatUSD(amount));        // "$100.00"
console.log(formatAPR(1200));          // "12.00%"

// Get default config for a chain
const config = getDefaultConfig(ChainId.Sepolia);

🔗 ag0/ERC-8004 Integration

The SDK integrates with ag0 for ERC-8004 agent identity:

ERC-8004 Contracts (Sepolia):

  • IdentityRegistry: 0x8004A818BFB912233c491871b3d84c89A494BD9e
  • ReputationRegistry: 0x8004B663056A597Dffe9eCcC1965A193B7388713

�️ CLI Usage

The SDK includes a command-line interface for easy testing and integration.

Installation

npm install -g @agether/sdk
# or use npx
npx agether help

Commands

# Initialize with your private key
agether init <private-key>

# Register agent on ERC-8004 + submit code for KYA audit
agether register --name "MyAgent" --code-url "https://github.com/user/agent"

# Apply for credit (shows collateral requirements!)
agether apply --limit 5000

# Deposit collateral (if required)
agether collateral --amount 4000

# Draw funds from credit line
agether draw --amount 1000

# Repay debt
agether repay --amount 500

# Check status
agether status

# View credit scores (Bayesian, ChainRisk subscores)
agether score

# Check balances
agether balance

Example Flow

# 1. Initialize
$ agether init 0x5de4...
✅ Initialized Agether CLI
   Address: 0x3C44C...
   RPC:     http://95.179.189.214:8545
   Backend: http://95.179.189.214

# 2. Register agent
$ agether register --name "OpenClaw" --code-url "https://github.com/user/openclaw"
🤖 Registering agent: OpenClaw
  [1/5] Fetching contract addresses...
  [2/5] Registering on ERC-8004 IdentityRegistry...
        ✓ Agent #42 registered
  [3/5] Minting test USDC...
        ✓ Minted $50,000 USDC
  [4/5] Registering code (CodeRegistry)...
        ✓ Code registered
  [5/5] Code registered in Pending state

  📊 Fetching initial credit scores...
  Credit Score Summary:
     Bayesian Score:    900/1000
     Internal Score:    335/1000
     External Score:    900/1000 (Cred Protocol)
     Confidence:        0%

✅ Agent #42 registered on ERC-8004!

# 3. Apply for credit
$ agether apply --limit 5000
📋 Applying for $5000 credit line (Agent #42)...

  [1/2] Evaluating credit application...

  📊 Evaluation Results:
     Approved:          ✅ Yes
     Credit Limit:      $5000.00
     APR:               8%
     Risk Score:        10/100
     Bayesian Score:    900/1000
     Confidence:        0%

  🏦 Collateral Required:
     Amount:            $4000.00 USDC
     Ratio:             80%

  ⚠️  You will need to deposit collateral before drawing funds.
     After approval, run: agether collateral --amount 4000

  [2/2] Submitting application onchain...
        ✓ TX: 0x...

✅ Credit Line #1 created (Pending)

# 4. Admin approves (via /test Admin Panel)

# 5. Deposit collateral
$ agether collateral --amount 4000
🏦 Depositing $4000 collateral...
  [1/2] Approving USDC...
        ✓ Approved
  [2/2] Depositing collateral...
✅ Deposited $4000 collateral

# 6. Draw funds
$ agether draw --amount 1000
💸 Drawing $1000...
✅ Drew $1000
   Remaining credit: $4000.00

Environment Variables

export AGETHER_RPC_URL=http://95.179.189.214:8545
export AGETHER_BACKEND_URL=http://95.179.189.214

�📁 Project Structure

sdk/
├── src/
│   ├── clients/
│   │   ├── AgetherClient.ts      # Main agent client
│   │   ├── VaultClient.ts        # LP client
│   │   ├── ScoringClient.ts      # Scoring service client
│   │   └── AgentIdentityClient.ts # ERC-8004 client
│   ├── types/
│   │   └── index.ts              # Type definitions
│   ├── utils/
│   │   ├── format.ts             # Formatting utilities
│   │   ├── config.ts             # Config helpers
│   │   └── abis.ts               # Contract ABIs
│   └── index.ts                  # Main exports
├── package.json
└── README.md                     # This file

📄 License

MIT