# TypeScript

> Markdown export of the Gearbox Protocol documentation page for agents and retrieval systems.

Canonical page: https://docs.gearbox.finance/developers/gm-start-ts
Source file: content/developers/gm-start-ts.mdx
Section router: https://docs.gearbox.finance/developers/llms.txt
Section full export: https://docs.gearbox.finance/developers/llms-full.txt

Install and initialize the Gearbox SDK, then read your first market data.

## Installation

```bash
npm install @gearbox-protocol/sdk viem
```

## Initialize the SDK

```typescript
import { GearboxSDK } from '@gearbox-protocol/sdk';
import { createPublicClient, http } from 'viem';
import { mainnet } from 'viem/chains';

const client = createPublicClient({
  chain: mainnet,
  transport: http(),
});

const sdk = await GearboxSDK.attach({
  client,
  marketConfigurators: [], // Empty = auto-discover all markets
});
```

| Parameter | Type | Description |
| --- | --- | --- |
| `client` | `PublicClient` | viem client instance |
| `marketConfigurators` | `Address[]` | Filter to specific configurators, or `[]` for all |

## Read Market Data

The SDK exposes markets through `marketRegister`:

```typescript
// All markets
const markets = sdk.marketRegister.markets;

// Find by pool address
const market = sdk.marketRegister.findByPool(poolAddress);

// Find by credit manager
const market = sdk.marketRegister.findByCreditManager(cmAddress);

// Access market data
const pool = market.pool;
console.log(`Underlying: ${pool.underlying.symbol}`);
console.log(`Total assets: ${pool.totalAssets}`);
console.log(`Available liquidity: ${pool.availableLiquidity}`);
```

## Read Pool State

```typescript
const pool = market.pool;

// Interest rates (RAY = 27 decimals)
const RAY = 10n ** 27n;
const supplyAPY = Number(pool.supplyRate * 10000n / RAY) / 100;
const borrowAPR = Number(pool.baseInterestRate * 10000n / RAY) / 100;
console.log(`Supply APY: ${supplyAPY}%`);
console.log(`Borrow APR: ${borrowAPR}%`);

// Share price
console.log(`Diesel rate: ${pool.dieselRate}`);
```

## Read Credit Manager Config

```typescript
for (const cm of market.creditManagers) {
  console.log(`Credit Manager: ${cm.address}`);
  console.log(`Min debt: ${cm.minDebt}`);
  console.log(`Max debt: ${cm.maxDebt}`);

  // Allowed collateral tokens
  for (const token of cm.collateralTokens) {
    console.log(`  ${token.symbol}: LT ${token.liquidationThreshold}`);
  }
}
```

## Use Plugins

Plugins extend SDK functionality:

```typescript
import { AccountsPlugin, AdaptersPlugin } from '@gearbox-protocol/sdk';

sdk.use(new AccountsPlugin());
sdk.use(new AdaptersPlugin());

// Query accounts
const accounts = sdk.accounts.byCreditManager(cmAddress);

// Query adapters
const adapters = sdk.adapters.byProtocol('uniswap-v3');
```

| Plugin | Purpose |
| --- | --- |
| `AccountsPlugin` | Credit account indexing and filtering |
| `AdaptersPlugin` | Protocol adapter discovery and metadata |

## Address Provider

The SDK wraps AddressProvider for contract discovery:

```typescript
import { AP_MARKET_COMPRESSOR, VERSION_RANGE_310 } from '@gearbox-protocol/sdk';

const [compressor] = sdk.addressProvider.mustGetLatest(
  AP_MARKET_COMPRESSOR,
  VERSION_RANGE_310
);
```

## Real-Time Data via Compressors

The SDK caches data on initialization. For live data, call compressors directly:

```typescript
import { marketCompressorAbi, AP_MARKET_COMPRESSOR, VERSION_RANGE_310 } from '@gearbox-protocol/sdk';

const [compressor] = sdk.addressProvider.mustGetLatest(
  AP_MARKET_COMPRESSOR,
  VERSION_RANGE_310
);

const freshData = await client.readContract({
  address: compressor,
  abi: marketCompressorAbi,
  functionName: 'getMarketData',
  args: [poolAddress],
});
```

## Complete Example

```typescript
import { GearboxSDK, createCreditAccountService } from '@gearbox-protocol/sdk';
import { createPublicClient, http } from 'viem';
import { mainnet } from 'viem/chains';

async function main() {
  const client = createPublicClient({
    chain: mainnet,
    transport: http(),
  });

  const sdk = await GearboxSDK.attach({
    client,
    marketConfigurators: [],
  });

  const RAY = 10n ** 27n;

  for (const market of sdk.marketRegister.markets) {
    const pool = market.pool;
    const supplyAPY = Number(pool.supplyRate * 10000n / RAY) / 100;

    console.log(`\n=== ${pool.underlying.symbol} Market ===`);
    console.log(`Pool: ${pool.address}`);
    console.log(`Total assets: ${pool.totalAssets}`);
    console.log(`Supply APY: ${supplyAPY.toFixed(2)}%`);
    console.log(`Credit Managers: ${market.creditManagers.length}`);
  }

  // Create service for account operations
  const service = createCreditAccountService(sdk, 310);
  const usdcMarket = sdk.marketRegister.markets.find(
    m => m.pool.underlying.symbol === 'USDC'
  );

  if (usdcMarket) {
    const accounts = await service.getCreditAccounts(
      { creditManager: usdcMarket.creditManagers[0].address },
      sdk.currentBlock
    );
    console.log(`\nFound ${accounts.length} USDC credit accounts`);
  }
}

main().catch(console.error);
```

## Next Steps

- [Markets Data](https://docs.gearbox.finance/developers/gm-markets-data) — Query pools, rates, and collateral info
- [Credit Accounts](https://docs.gearbox.finance/developers/gm-accounts) — Open and manage leveraged positions
- [Multicalls](https://docs.gearbox.finance/developers/gm-accounts-multicalls) — Build and execute operations
