# @zubari/sdk

Multi-chain self-custodial wallet SDK for the Web3 creator economy. Manage Bitcoin, Ethereum, TON, TRON, Solana, and Lightning (Spark) from a single BIP-39 seed phrase.

[![npm version](https://img.shields.io/npm/v/@zubari/sdk.svg)](https://www.npmjs.com/package/@zubari/sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)

## Features

- **Multi-Chain Support**: Ethereum, Bitcoin, TON, TRON, Solana, and Lightning (Spark)
- **Single Seed Phrase**: Derive addresses for all chains from one BIP-39 mnemonic
- **Self-Custodial**: Your keys, your crypto - encrypted locally with AES-256-GCM
- **Creator Economy Protocols**: NFTs, Tips, Subscriptions, and Payouts
- **TypeScript First**: Full type safety with comprehensive type definitions
- **React Hooks**: Ready-to-use hooks for React applications
- **Tether WDK Integration**: Powered by Tether's Wallet Development Kit

## Installation

```bash
# npm
npm install @zubari/sdk

# yarn
yarn add @zubari/sdk

# pnpm
pnpm add @zubari/sdk
```

## Quick Start

### Create a New Wallet

```typescript
import { WalletManager } from '@zubari/sdk';

// Initialize wallet manager
const wallet = new WalletManager({
  network: 'testnet', // or 'mainnet'
});

// Create a new wallet with password protection
const { seed, address } = await wallet.createWallet('your-secure-password');

console.log('Seed phrase (SAVE THIS!):', seed);
console.log('Ethereum address:', address);

// Derive addresses for all supported chains
const addresses = await wallet.deriveAllAddressesWithWdk();

console.log('Multi-chain addresses:', addresses);
// {
//   ethereum: '0x...',
//   bitcoin: 'tb1q...',
//   ton: 'UQ...',
//   tron: 'T...',
//   solana: '...',
//   spark: 'sp1...'
// }
```

### Import Existing Wallet

```typescript
import { WalletManager } from '@zubari/sdk';

const wallet = new WalletManager({ network: 'testnet' });

// Import from seed phrase
const { address } = await wallet.importWallet(
  'your twelve word seed phrase goes here ...',
  'your-secure-password'
);

// Unlock and derive all addresses
await wallet.unlock('your-secure-password');
const addresses = await wallet.deriveAllAddressesWithWdk();
```

### React Hook Usage

```tsx
import { useWalletManager } from '@zubari/sdk/react';

function WalletComponent() {
  const {
    state,
    createWallet,
    unlock,
    lock,
    deriveAllAddresses,
  } = useWalletManager({ network: 'testnet' });

  const handleCreate = async () => {
    const { seed, address } = await createWallet('password123');
    console.log('Created wallet:', address);
  };

  return (
    <div>
      <p>Status: {state.isLocked ? 'Locked' : 'Unlocked'}</p>
      <p>Address: {state.address}</p>
      <button onClick={handleCreate}>Create Wallet</button>
    </div>
  );
}
```

## API Reference

### WalletManager

The main class for wallet operations.

```typescript
import { WalletManager } from '@zubari/sdk';

const wallet = new WalletManager({
  network: 'testnet' | 'mainnet',
  rpcUrl?: string,          // Custom RPC URL
  enabledChains?: string[], // Chains to enable
  apiUrl?: string,          // Backend API URL (optional)
});
```

#### Methods

| Method | Description | Returns |
|--------|-------------|---------|
| `createWallet(password)` | Create new wallet with encrypted seed | `{ seed, address }` |
| `importWallet(seed, password)` | Import existing seed phrase | `{ address }` |
| `unlock(password)` | Unlock wallet | `{ address }` |
| `lock()` | Lock wallet (clear seed from memory) | `void` |
| `deleteWallet()` | Delete wallet from storage | `Promise<void>` |
| `deriveAllAddressesWithWdk()` | Derive real addresses using WDK | `MultiChainAddresses` |
| `deriveAllAddressesAsync()` | Derive with fallback strategies | `MultiChainAddresses` |
| `fetchBalance()` | Get ETH balance | `string` |
| `getState()` | Get wallet state | `WalletState` |

### ZubariWallet

High-level wallet class with multi-chain transaction support.

```typescript
import { ZubariWallet } from '@zubari/sdk';

const zubariWallet = new ZubariWallet({
  seed: 'your seed phrase',
  network: 'testnet',
});

// Send ETH
const tx = await zubariWallet.sendEth({
  to: '0x...',
  amount: '0.1',
});

// Send Bitcoin
const btcTx = await zubariWallet.sendBitcoin({
  to: 'tb1q...',
  amount: '0.001',
});
```

### WdkService

Native Tether WDK integration for address derivation.

```typescript
import { WdkService } from '@zubari/sdk/services';

const wdk = new WdkService({ network: 'testnet' });

// Generate seed phrase
const seed = await wdk.generateSeedPhrase();

// Initialize and derive addresses
await wdk.initialize(seed);
const addresses = await wdk.deriveAllAddresses();
```

### Protocols

Creator economy protocols for monetization.

```typescript
import {
  ZubariNFTProtocol,
  ZubariTipsProtocol,
  ZubariSubscriptionProtocol,
  ZubariPayoutsProtocol,
} from '@zubari/sdk/protocols';

// NFT Protocol - Lazy minting with EIP-712 signatures
const nft = new ZubariNFTProtocol(wallet, config);
const voucher = await nft.createLazyMintVoucher(metadata);
const mintedNFT = await nft.redeemVoucher(voucher);

// Tips Protocol - Send tips to creators
const tips = new ZubariTipsProtocol(wallet, config);
await tips.sendTip({ to: '0x...', amount: '1.0', token: 'ETH' });

// Subscription Protocol
const subs = new ZubariSubscriptionProtocol(wallet, config);
await subs.subscribe(planId);

// Payouts Protocol
const payouts = new ZubariPayoutsProtocol(wallet, config);
await payouts.claimEarnings();
```

### Storage

Secure storage adapters for different platforms.

```typescript
import {
  createSecureStorage,
  WebEncryptedStorageAdapter,
  MemoryStorageAdapter,
} from '@zubari/sdk/storage';

// Auto-detect platform (Web, React Native, Node.js)
const storage = createSecureStorage();

// Or use specific adapter
const webStorage = new WebEncryptedStorageAdapter('app-prefix');
await webStorage.initialize('encryption-password');
```

### Utilities

```typescript
import {
  formatAddress,
  formatBalance,
  isValidAddress,
  normalizeAddress,
} from '@zubari/sdk';

formatAddress('0x1234...5678');     // '0x1234...5678'
formatBalance(1000000000000000000n); // '1.0000'
isValidAddress('0x...');            // true/false
normalizeAddress('0xABC...');       // '0xabc...'
```

## Supported Chains

| Chain | Derivation Path | Address Format | Testnet |
|-------|-----------------|----------------|---------|
| Ethereum | m/44'/60'/0'/0/0 | 0x... | Sepolia |
| Bitcoin | m/84'/0'/0'/0/0 | bc1q.../tb1q... | Testnet |
| TON | m/44'/607'/0' | UQ.../EQ... | Testnet |
| TRON | m/44'/195'/0'/0/0 | T... | Shasta |
| Solana | m/44'/501'/0'/0' | Base58 | Devnet |
| Spark | m/44'/998'/0'/0/0 | sp1... | Testnet |

## Security

- **AES-256-GCM** encryption for seed storage
- **PBKDF2** key derivation (100,000 iterations)
- Seeds cleared from memory on lock
- Platform-native secure storage (Keychain/Keystore)
- No private keys transmitted over network

## Requirements

- Node.js >= 18.0.0
- React >= 18.0.0 (for React hooks, optional)

## TypeScript Support

Full TypeScript support with exported types:

```typescript
import type {
  WalletState,
  WalletManagerConfig,
  NetworkType,
  MultiChainAddresses,
  NFTMetadata,
  LazyMintVoucher,
  TipData,
  SubscriptionPlan,
  SwapQuote,
} from '@zubari/sdk';
```

## Subpath Exports

Import specific modules for better tree-shaking:

```typescript
// Core wallet only
import { WalletManager } from '@zubari/sdk/wallet';

// Protocols only
import { ZubariNFTProtocol } from '@zubari/sdk/protocols';

// Services only
import { WdkService } from '@zubari/sdk/services';

// Storage only
import { createSecureStorage } from '@zubari/sdk/storage';

// React hooks only
import { useWalletManager } from '@zubari/sdk/react';
```

## Contributing

Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md) for details.

## License

MIT - see [LICENSE](LICENSE) for details.

## Links

- [GitHub Repository](https://github.com/anthropics/zubari-wallet)
- [Documentation](https://docs.zubari.io)
- [Tether WDK](https://docs.wallet.tether.io)
