npm package: @kaizen-trade/sdk
Description: TypeScript SDK for Kaizen Core - Price Range Prediction Market Protocol
Author: Kaizen Core Team
Latest version: 0.1.16

# @kaizen-trade/sdk

TypeScript SDK for interacting with Kaizen Core - a price range prediction market protocol.

## Installation

```bash
npm install @kaizen-trade/sdk viem
# or
pnpm add @kaizen-trade/sdk viem
# or
yarn add @kaizen-trade/sdk viem
```

> **Note:** `viem` is a peer dependency and must be installed separately.

## Quick Start

```typescript
import { createClient, createSigner } from "@kaizen-trade/sdk";

// Create a client
const client = createClient({
  rpcUrl: "https://rpc.kaizen.network",
  wsUrl: "wss://ws.kaizen.network", // optional
  chainId: 1,
});

// Connect with a private key
client.connectSigner("0x...");

// Get account balance
const balance = await client.getMyBalance();
console.log(`Balance: ${balance.balance}`);

// Transfer funds
const receipt = await client.transfer(
  "0xRecipientAddress",
  1000000n, // 1 USDC (6 decimals)
  { waitForConfirmation: true }
);
```

## Features

- **Full RPC Support**: Query accounts, balances, theses, oracle prices, and blocks
- **WebSocket Subscriptions**: Real-time updates for blocks, theses, and oracle prices
- **Transaction Signing**: EIP-712 compatible signing with timestamp-based replay protection
- **API Wallet Support**: Delegate trading operations to API wallets
- **Borsh Serialization**: Efficient binary encoding for transactions

## API Reference

### Client

```typescript
import { createClient, KaizenClient } from "@kaizen-trade/sdk";

const client = createClient({
  rpcUrl: string, // Required: JSON-RPC endpoint
  wsUrl: string, // Optional: WebSocket endpoint
  chainId: number, // Optional: Chain ID (default: 1)
});
```

### Signer Management

```typescript
// Connect as owner
client.connectSigner(privateKey: Hex);

// Connect as API wallet (delegated signing)
client.connectAsApiWallet(privateKey: Hex, ownerAddress: Address);

// Disconnect
client.disconnectSigner();

// Check status
client.hasSigner;        // boolean
client.signerAddress;    // Address | null
client.accountAddress;   // Address | null (owner if API wallet)
client.isApiWallet;      // boolean
```

### Account Operations

```typescript
// Get account info
const account = await client.getAccount(address);
const balance = await client.getBalance(address);

// Get your own account (requires connected signer)
const myAccount = await client.getMyAccount();
const myBalance = await client.getMyBalance();
```

### Transactions

```typescript
// Transfer
await client.transfer(to, amount, options?);

// Withdraw to external chain
await client.withdraw(amount, destinationAddress, destinationChainId, options?);

// API Wallet management
await client.nominateApiWallet(walletAddress, expiryTimestamp, options?);
await client.revokeApiWallet(walletAddress, options?);

// RFQ (Request for Quote)
await client.submitRfq(solverQuote, options?);
await client.settleRfq(thesisId, options?);

// Options
interface SendTransactionOptions {
  waitForConfirmation?: boolean;  // Wait for tx confirmation
  confirmationTimeout?: number;   // Timeout in ms (default: 30000)
}
```

### Thesis Queries

```typescript
// Get thesis by ID
const thesis = await client.getThesis(thesisId);

// Get theses by user
const { items, total, hasMore } = await client.getThesesByUser(address, limit?, offset?);

// Get theses by solver
const { items } = await client.getThesesBySolver(address, limit?, offset?);

// Get your theses
const myTheses = await client.getMyTheses(limit?, offset?);
```

### Oracle

```typescript
// Get current price
const price = await client.getOraclePrice(baseAddress, quoteAddress);

// Get price history
const history = await client.getOraclePriceHistory(base, quote, fromTimestamp, toTimestamp, limit?);
```

### Blocks

```typescript
const block = await client.getBlock(height);
const currentHeight = await client.getBlockHeight();
const stateRoot = await client.getStateRoot();
```

### WebSocket Subscriptions

```typescript
// Connect WebSocket
await client.connectWebSocket();

// Subscribe to new blocks
const unsubscribe = client.subscribeBlocks((event) => {
  console.log("New block:", event.block.height);
});

// Subscribe to thesis updates
client.subscribeUserTheses(address, (event) => {
  console.log("Thesis update:", event.thesis);
});

// Subscribe to oracle prices
client.subscribeOraclePrices({ base, quote }, (event) => {
  console.log("Price:", event.price);
});

// Unsubscribe
unsubscribe();

// Disconnect
client.disconnectWebSocket();
```

## External Wallet Integration

For browser wallets (MetaMask, WalletConnect, etc.), use the typed data builders:

```typescript
import { buildTypedData, buildSignedTransaction } from "@kaizen-trade/sdk";

// Build EIP-712 typed data
const typedData = buildTypedData(
  { type: "Transfer", to: "0x...", amount: 1000000n },
  BigInt(Date.now()),
  signerAddress,
  chainId
);

// Sign with external wallet (e.g., wagmi)
const signature = await signTypedData(typedData);

// Build the signed transaction
const signedTx = buildSignedTransaction(
  payload,
  timestamp,
  signerAddress,
  signature,
  chainId
);

// Send it
const receipt = await rpcClient.sendTransaction(signedTx.encoded);
```

## Types

All types are exported for TypeScript users:

```typescript
import type {
  // Core
  Account,
  Balance,
  Block,
  TransactionReceipt,

  // Thesis
  Thesis,
  ThesisType,
  ThesisStatus,
  SolverQuote,

  // Oracle
  OraclePair,
  OraclePrice,

  // Events
  TransactionEvent,
  EventType,

  // WebSocket
  WebSocketEvent,
  BlockEvent,
  ThesisEvent,
  OraclePriceEvent,

  // Config
  KaizenClientConfig,
} from "@kaizen-trade/sdk";
```

## Schema (Borsh Serialization)

For advanced use cases, the SDK exports Borsh schema classes:

```typescript
import {
  TransactionSchema,
  TransferTxSchema,
  RfqSubmitTxSchema,
  // ... and more
  hexToBytes,
  bytesToHex,
} from "@kaizen-trade/sdk";
```

## Requirements

- Node.js >= 18.0.0
- `viem` >= 2.0.0 (peer dependency)

## License

MIT