npm package: @marcedivault/app-wallet-sdk
Description: TypeScript SDK for integrating with MarcediVault App Wallet API
Author: MarcediVault
Latest version: 1.1.8

# MarcediVault App Wallet SDK

Official TypeScript/JavaScript SDK for MarcediVault's **non-custodial** App Wallet system with zero-knowledge security.

## Overview

Integrate blockchain wallets into your app without requiring users to manage private keys or seed phrases. With **Zero-Sight Protocol (ZSP)**, you maintain full control over wallets through your PIN while MarcediVault provides secure infrastructure.

### Key Features

- **Non-Custodial Security** - You control wallets via your ZSP PIN, not MarcediVault
- **Zero-Knowledge Architecture** - MarcediVault cannot access wallets without your PIN
- **Multi-Chain Support** - Ethereum, Polygon, Base, Arbitrum, Optimism
- **OAuth 2.0 Authentication** - Industry-standard security
- **TypeScript Support** - Full type definitions included
- **Automatic PIN Encryption** - PIN encrypted during transmission
- **Session Management** - Efficient transaction batching
- **Comprehensive Error Handling** - Typed errors for all scenarios

## Installation

```bash
npm install @marcedivault/app-wallet-sdk
```

## Quick Start

```typescript
import { MarcediVaultClient } from '@marcedivault/app-wallet-sdk';

// Initialize the client (API URL is hardcoded - no configuration needed!)
const client = new MarcediVaultClient({
  clientId: process.env.MARCEDIVAULT_CLIENT_ID!,
  clientSecret: process.env.MARCEDIVAULT_CLIENT_SECRET!,
  appZspPin: process.env.MARCEDIVAULT_APP_ZSP_PIN!, // Your wallet encryption PIN
  debug: true,
});

// Create a wallet (encrypted with YOUR PIN)
const wallet = await client.createWallet({
  appUserId: 'user-12345',
  chain: 'ethereum',
  label: 'Main Wallet',
});

console.log('Wallet created:', wallet.address);
console.log('Security: This wallet is encrypted with YOUR PIN');
console.log('Security: MarcediVault cannot access it without your PIN');

// Send a transaction (requires YOUR PIN to decrypt and sign)
const session = await client.initializeSession(wallet.id);
const tx = await client.sendTransaction({
  sessionId: session.sessionId,
  to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0',
  value: '0.1',
});

console.log('Transaction sent:', tx.hash);
console.log('Security: Your PIN was used to sign, then immediately discarded');
```

## Environment Variables

You only need **3 environment variables** - the API URL is hardcoded in the SDK!

```bash
# Required
MARCEDIVAULT_CLIENT_ID=your_client_id_here
MARCEDIVAULT_CLIENT_SECRET=your_client_secret_here
MARCEDIVAULT_APP_ZSP_PIN=your_secure_pin_here

# Optional (for development)
NODE_ENV=development
```

**Security Note**: Never commit these values to version control. Use a `.env` file and add it to `.gitignore`.

## Security Model

### Zero-Knowledge Architecture

MarcediVault operates on a **zero-knowledge security model** where you maintain full control:

1. **Wallet Creation**
   - Private keys encrypted with **your ZSP PIN**
   - MarcediVault never sees unencrypted private keys
   - Only encrypted data (ciphertext, IV, tag, salt) is stored

2. **Transaction Signing**
   - Your PIN required for each transaction
   - Private key temporarily decrypted in memory
   - Used only for signing, then immediately discarded
   - PIN also immediately discarded after use

3. **PIN Security**
   - Your PIN is **NEVER** stored by MarcediVault
   - PIN sent encrypted during transmission
   - Used only for cryptographic operations
   - Without your PIN, MarcediVault **CANNOT** access wallets

### What This Means

✅ **You are in control** - Wallets cannot be accessed without your PIN
✅ **Non-custodial** - MarcediVault provides infrastructure, not custody
✅ **Zero-knowledge** - MarcediVault cannot decrypt your wallets
✅ **PIN-based access** - Your PIN is the master key to all wallets

⚠️ **Important**: Keep your ZSP PIN secure. If lost, wallets cannot be recovered!

## API Reference

### Client Initialization

```typescript
const client = new MarcediVaultClient({
  clientId: string;          // Your OAuth client ID
  clientSecret: string;      // Your OAuth client secret
  appZspPin: string;         // Your ZSP PIN for wallet encryption
  timeout?: number;          // Request timeout (default: 30000ms)
  debug?: boolean;           // Enable debug logging
});
```

**Note**: The API URL is hardcoded to `https://api.marcedivault.com` - you don't need to configure it!

### Wallet Management

#### Create Wallet

```typescript
const wallet = await client.createWallet({
  appUserId: string;         // Your app's user ID
  chain: string;             // 'ethereum', 'polygon', 'base', etc.
  label?: string;            // Optional wallet label
  metadata?: object;         // Optional metadata
});

// Returns: Wallet object with address, id, chain, etc.
// Security: Wallet is encrypted with YOUR ZSP PIN
```

#### Get Wallet

```typescript
const wallet = await client.getWallet(walletId: string);
```

#### List Wallets

```typescript
const result = await client.listWallets({
  appUserId?: string;        // Filter by user
  chain?: string;            // Filter by chain
  page?: number;             // Page number
  limit?: number;            // Results per page
});
```

#### Get User's Wallets

```typescript
const wallets = await client.getWalletsByAppUserId(
  appUserId: string,
  chain?: string             // Optional chain filter
);
```

### Session Management

#### Initialize Session

```typescript
const session = await client.initializeSession(walletId: string);

// Returns: { sessionId, expiresAt }
// Security: Requires YOUR ZSP PIN for validation
```

#### End Session

```typescript
await client.endSession(sessionId: string);
```

### Transactions

#### Send Transaction

```typescript
const tx = await client.sendTransaction({
  sessionId: string;         // Active session ID
  to: string;                // Recipient address
  value?: string;            // Amount in native currency
  data?: string;             // Contract call data
  gasLimit?: string;         // Gas limit
  maxFeePerGas?: string;     // EIP-1559 max fee
  maxPriorityFeePerGas?: string; // EIP-1559 priority fee
  metadata?: object;         // Optional metadata
});

// Returns: { transactionId, hash, signedTransaction }
// Security: Requires YOUR ZSP PIN to decrypt and sign
```

#### Get Transaction

```typescript
const tx = await client.getTransaction(transactionId: string);
```

#### Get Transaction History

```typescript
const history = await client.getTransactionHistory(
  walletId: string,
  page?: number,
  limit?: number
);
```

### Balance & Assets

#### Get Balance

```typescript
const balance = await client.getBalance(
  walletId: string,
  tokenAddress?: string      // Optional: specific token
);

// Returns: { native: { balance, symbol }, tokens: [...] }
```

### Client Stats

#### Get Client Stats

```typescript
const stats = await client.getClientStats();

// Returns: { totalWallets, activeWallets, totalTransactions, ipWhitelist, lastActivity }
```

### Error Handling

```typescript
import {
  AuthenticationError,
  ValidationError,
  NotFoundError,
  IPWhitelistError,
  SessionExpiredError,
  InsufficientBalanceError,
  RateLimitError,
  NetworkError,
} from '@marcedivault/app-wallet-sdk';

try {
  await client.createWallet({ ... });
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Invalid input:', error.message);
  } else if (error instanceof IPWhitelistError) {
    console.error('IP not whitelisted:', error.message);
  } else if (error instanceof SessionExpiredError) {
    // Reinitialize session
  }
  // ... handle other errors
}
```

## Examples

See the `/examples` directory for complete examples:

- **basic-usage.ts** - Wallet creation, balance checks, transactions
- **error-handling.ts** - Handling all error types
- **multi-user-wallets.ts** - Managing wallets for multiple users
- **session-management.ts** - Efficient session handling

## Best Practices

### Security

1. **Server-Side Only** - Never use this SDK in frontend code
2. **Secure Your PIN** - Store ZSP PIN in environment variables or secrets manager
3. **Verify Ownership** - Always verify users own wallets before operations
4. **Audit Logging** - Log all wallet operations for compliance
5. **Rate Limiting** - Implement rate limiting on your endpoints
6. **Backup Your PIN** - Keep secure backup of ZSP PIN (wallets unrecoverable without it)

### Performance

1. **Reuse Sessions** - Initialize session once for multiple transactions
2. **Batch Operations** - Use Promise.all() for parallel wallet creation
3. **Cache Balances** - Don't fetch balance on every page load
4. **Connection Pooling** - SDK handles this automatically

### Development

1. **Enable Debug Mode** - Set `debug: true` during development
2. **Test with Testnet** - Use testnet chains before production
3. **Handle All Errors** - Implement comprehensive error handling
4. **Monitor IP Whitelist** - Ensure all servers are whitelisted

## Support

- **Documentation**: [Full Integration Guide](./INTEGRATION_GUIDE.md)
- **Examples**: [Code Examples](./examples/)
- **Email**: support@marcedivault.com
- **Status**: https://status.marcedivault.com

## License

MIT License - see LICENSE file for details