npm package: @gluex/sdk
Description: A TypeScript SDK for token swaps and DeFi operations, providing optimized routing and real-time pricing. Built for efficient token management, price discovery, and transaction execution.
Latest version: 1.0.23

# GlueX SDK

A TypeScript SDK for token swaps and DeFi operations, providing optimized routing and real-time pricing. Built for efficient token management, price discovery, and transaction execution.

## Table of Contents
- [Installation](#installation)
- [Core Services](#core-services)
  - [Balance Service](#balance-service)
  - [Chain Service](#chain-service)
  - [Exchange Rate Service](#exchange-rate-service)
  - [Gas Service](#gas-service)
  - [Liquidity Module Service](#liquidity-module-service)
  - [Name Service](#name-service)
  - [Router Service](#router-service)
  - [Token Service](#token-service)
  - [Transaction Service](#transaction-service)
  - [Yield Service](#yield-service)

## Installation

```bash
# Using npm
npm install @gluex/sdk viem

# Using yarn
yarn add @gluex/sdk viem

# Using pnpm
pnpm add @gluex/sdk viem
```

## Core Services


### Balance Service

Returns token balances across all aggregated chains:

```typescript
import { type Token, type TokenWithPriceAndAmount } from "@gluex/types"

// Get balance for a single token
const balance = await getTokenBalance(
  walletAddress: string,  // A wallet address
  token: Token           // A Token object
): Promise<TokenWithPriceAndAmount | null>

// Get balances for multiple tokens
const balances = await getTokenBalances(
  walletAddress: string,  // A wallet address
  tokens: Token[]        // A list of Token objects
): Promise<TokenWithPriceAndAmount[]>

// Get balances organized by chain
const balancesByChain = await getTokenBalancesByChain(
  walletAddress: string,  // A wallet address
  tokensByChain: {       // A list of token objects organized by chain ids
    [chainId: number]: Token[]
  }
): Promise<{ [chainId: number]: TokenWithPriceAndAmount[] }>
```

#### Key Features:

1. **Fast Balance Checks**: Gets multiple token balances in one call
2. **Chain Organization**: Groups tokens by chain for better performance
3. **Error Recovery**: Handles failed balance checks gracefully


### Chain Service

Manages chain information and configurations with caching:

```typescript
import { getChains, getChain } from '@gluex/sdk';

// Get all supported chains with optional filters
const chains = await getChains({
  chains: ["ethereum"],      // Filter by chain identifiers
  chainTypes: ["EVM"]       // Filter by chain types
});

// Get specific chain by identifier or ID
const chain = await getChain({
  chain: "ethereum"  // Chain identifier or chain ID
});

// Response types:
interface Chain {
  id: number;
  identifier: string;
  type: string;
  tokens: {
    native: Token;
    stablecoins: Token[];
  };
  // Additional chain properties
}

type ChainsResponse = Chain[];
type ChainResponse = Chain;
```

#### Key Features:

1. **Chain Management**: Comprehensive chain information with filtering
2. **Smart Caching**: 10-minute TTL with automatic invalidation
3. **Request Optimization**: Deduplication and retry mechanisms


### Exchange Rate Service

Handles token pricing and exchange rates:

```typescript
import { getExchangeRate, getTokenPrice } from '@gluex/sdk';

// Get exchange rates for multiple tokens
const rates = await getExchangeRates([{
  chainId: 1,
  tokenAddress: "0x...",
  decimals: 18
}]);

// Response includes:
interface ExchangeRateResponse {
  chainId?: number;
  tokenAddress: string;
  price: number;
  domestic_blockchain: string;
  domestic_token: string;
  foreign_blockchain: string;
  foreign_token: string;
}
```

#### Key Features:

1. **Real-time Pricing**: Cross-chain rate aggregation with 2-minute TTL caching
2. **Price Normalization**: Handles scientific notation and token decimals with fallbacks
3. **Batch Processing**: Efficient multi-token rate fetching with parallel processing


### Gas Service

Handles gas price fetching and recommendations:

```typescript
import { getCurrentGasPrice, getGasRecommendation } from '@gluex/sdk';

// Get current gas price for a chain
const gasPrice = await getCurrentGasPrice(
  "ethereum",  // Chain identifier
  "EVM"        // Chain type
);

// Get gas recommendations (feature in development)
const recommendation = await getGasRecommendation({
  chain: "ethereum"
});
```
#### Key Features:

1. **Real-time Gas**: Current gas prices across EVM chains
2. **Smart Recommendations**: Chain-specific gas price suggestions
3. **Fallback System**: Multiple provider support with graceful degradation

### Liquidity Module Service

Interacts with liquidity pools and protocols:

```typescript
import { getLiquidityModules, getLiquidityModule } from '@gluex/sdk';

// Get all liquidity modules
const allModules = await getLiquidityModules();

// Get specific modules by reference
const modules = await getLiquidityModules({ 
  references: ['aave_v3', 'compound_v3'] 
});

// Get a single module
const aaveModule = await getLiquidityModule({ 
  reference: 'aave_v3' 
});
```

#### Key Features:

1. **Module Discovery**: Fetch and filter liquidity modules by reference or identifier
2. **Caching System**: Request deduplication and local storage optimization
3. **Error Recovery**: Robust validation and fallback mechanisms

### Name Service

Resolves domain names to addresses across multiple chains:

```typescript
import { getAddressFromDomainName } from '@gluex/sdk';

// Resolve any domain name to address
const address = await getAddressFromDomainName(
  "vitalik.eth"  // Domain name
);

// Resolve with specific chain type
const ethAddress = await getAddressFromDomainName(
  "vitalik.eth",
  "EVM"  // Chain type
);
```

#### Key Features:

1. **Multi-Provider**: Domain resolution across multiple name services
2. **Chain Support**: Cross-chain address resolution with type filtering

### Router Service

Handles price discovery and quote management for token swaps:

```typescript
import { getPartialFill, getPrice, getQuote } from '@gluex/sdk';

// 1. Check if a transaction will be partially filled
const isPartial = getPartialFill(
  effectiveInputAmount,  // Effective amount that will be used
  inputAmount           // Original requested amount
);

// 2. Get optimal route with price quote
const route = await getPrice({
  fromChainId: 1,
  fromAmount: "1000000000000000000",
  fromTokenAddress: "0x...",
  fromAddress: "0x...",
  fromToken: { /* Token details */ },
  
  toChainId: 137,
  toTokenAddress: "0x...",
  toAddress: "0x...",
  toToken: { /* Token details */ },
  
  options: {
    integrator: "your-integrator-id",
    slippage: 0.03,              // 3% default
    maxPriceImpact: 0.05,        // optional
    referrer: "referrer-address", // optional
    allowSwitchChain: false,     // default
    allowDestinationCall: true   // default
  }
});

// 3. Get executable quote with transaction data
const quote = await getQuote(route.steps[0]); // route.steps[0] is GlueXStep

// Types:
interface GlueXStep extends Step {
  parameters: Partial<RoutesRequest>;
  substeps: Step[];
  liquidityModules: string[];
}

```

#### Key Features:

1. **Price Discovery**: Real-time cross-chain price discovery with partial fill detection
2. **Quote Generation**: Executable transaction data with gas estimates and final amounts

### Token Service

Handles token information and metadata:

```typescript
import { getToken, getTokens } from '@gluex/sdk';

// Get single token information
const token = await getToken({
  chain: "ethereum",
  token: "0x..."
});

// Get multiple tokens with optional filters
const tokens = await getTokens({
  // All parameters are optional
  chain: "ethereum",
  // Additional filter parameters
});
```
#### Key Features:

1. **Token Discovery**: Comprehensive token information across chains
2. **Metadata Management**: Price, symbol, and decimals with validation
3. **Smart Caching**: Efficient token data caching with auto-invalidation

### Transaction Service

Manages transaction status and history:

```typescript
import { getTransactionStatus, getTransactionHistory } from '@gluex/sdk';

// Get transaction status with receipt
const status = await getTransactionStatus({
  txHash: "0x...",
  fromChain: "ethereum"  // Optional, defaults to ethereum
});

// Response includes:
interface StatusResponse {
  fromAddress: string;
  toAddress: string;
  status: "DONE" | "FAILED" | "NOT_FOUND";
  transactionId?: string;
}

// Get transaction history (coming soon)
const history = await getTransactionHistory({
  address: "0x..."
});
```

#### Key Features:

1. **Status Tracking**: Real-time transaction status with receipt validation

### Yield Service

Manages yield farming operations:

```typescript
import { getHistoricalYield, getDilutedYield, getRiskAdjustedYield } from '@gluex/sdk';

// Get historical yield data
const historicalYield = await getHistoricalYield({
  chain: "ethereum",
  address: "0x...",
  type: "pool"  // or "lp_token"
});

// Get diluted yield with amount
const dilutedYield = await getDilutedYield({
  chain: "ethereum",
  address: "0x...",
  type: "pool",
  amount: "1000000000000000000"
});
```
#### Key Features:

1. **Yield Tracking**: Historical APY and diluted yield calculations