npm package: @fiatsend/sdk
Description: Official Fiatsend JavaScript SDK for building custom payment applications
Author: Fiatsend Team
Latest version: 1.0.0

# Fiatsend JavaScript SDK

[![npm version](https://badge.fury.io/js/%40fiatsend%2Fsdk.svg)](https://badge.fury.io/js/%40fiatsend%2Fsdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

The official **Fiatsend JavaScript SDK** for building custom payment applications with seamless fiat-to-crypto and crypto-to-fiat conversions, mobile money integration, and Web3 identity management.

## Features

- 🚀 **Easy Integration** - Simple API for payment processing
- 💰 **Multi-Currency Support** - GHS, USD, USDT, and more
- 📱 **Mobile Money Integration** - MTN, AirtelTigo, Telecel support
- 🔐 **Identity Management** - NFT-based phone number resolution
- 🌐 **Web3 Ready** - Full blockchain integration with viem
- ⚡ **React Hooks** - Ready-to-use React hooks for frontend apps
- 🛡️ **Type Safe** - Full TypeScript support
- 🔄 **Real-time Updates** - Webhook support and live balance tracking

## Installation

```bash
npm install @fiatsend/sdk
# or
yarn add @fiatsend/sdk
# or
pnpm add @fiatsend/sdk
```

## Quick Start

### Basic Setup

```typescript
import { FiatsendSDK } from '@fiatsend/sdk';

const sdk = new FiatsendSDK({
  apiKey: 'your-api-key',
  environment: 'production', // or 'staging', 'development'
});

// Check if SDK is configured
console.log(sdk.isConfigured()); // true
```

### Payment Processing

```typescript
// Initiate a payment
const payment = await sdk.payment.initiatePayment({
  amount: 100,
  currency: 'GHS',
  recipient: '+233551234567',
  description: 'Payment for services'
});

console.log(payment.transactionId);
```

### Mobile Money Integration

```typescript
// MTN Mobile Money payment
const mtnPayment = await sdk.payment.createMTNPayment({
  amount: 50,
  phoneNumber: '0551234567',
  externalRef: 'PAY-12345',
  wallet: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6'
});

// AirtelTigo payment
const airtelPayment = await sdk.payment.createAirtelTigoPayment({
  amount: 25,
  phoneNumber: '0241234567',
  externalRef: 'PAY-12346',
  wallet: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6'
});
```

### Identity Management

```typescript
// Mint identity NFT
const identity = await sdk.identity.mintIdentity({
  phoneNumber: '+233551234567',
  countryCode: 'GH',
  metadata: 'User metadata'
});

// Resolve phone to wallet address
const wallet = await sdk.identity.resolvePhoneToAddress('+233551234567');
console.log(wallet.wallet); // 0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6
```

### Wallet Operations

```typescript
// Get wallet balance
const balance = await sdk.wallet.getBalance('0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6');
console.log(balance.balances);

// Get transaction history
const transactions = await sdk.wallet.getTransactions({
  walletAddress: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6',
  page: 1,
  limit: 20
});
```

## React Integration

### Using Hooks

```tsx
import React from 'react';
import { useFiatsendSDK, usePayment, useBalance } from '@fiatsend/sdk';

function PaymentComponent() {
  const { sdk } = useFiatsendSDK({
    apiKey: 'your-api-key',
    environment: 'production'
  });

  const { initiatePayment, isLoading } = usePayment(sdk);
  const { balance, refreshBalance } = useBalance(sdk, '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6');

  const handlePayment = async () => {
    const result = await initiatePayment({
      amount: 100,
      currency: 'GHS',
      recipient: '+233551234567'
    });
    
    if (result) {
      console.log('Payment successful:', result.transactionId);
      refreshBalance();
    }
  };

  return (
    <div>
      <h2>Wallet Balance</h2>
      <p>GHS: {balance?.balances.GHSFIAT?.balance || '0'}</p>
      
      <button onClick={handlePayment} disabled={isLoading}>
        {isLoading ? 'Processing...' : 'Send Payment'}
      </button>
    </div>
  );
}
```

## API Reference

### FiatsendSDK

The main SDK class that provides access to all functionality.

```typescript
const sdk = new FiatsendSDK(config);
```

#### Configuration

```typescript
interface FiatsendConfig {
  apiKey: string;                    // Required: Your API key
  baseUrl?: string;                  // Optional: Custom API endpoint
  chainId?: number;                  // Optional: Blockchain chain ID (default: 324)
  rpcUrl?: string;                   // Optional: Custom RPC endpoint
  environment?: 'development' | 'staging' | 'production';
}
```

### Payment Client

```typescript
// Initiate payment
await sdk.payment.initiatePayment(request);

// Mobile money payments
await sdk.payment.createMTNPayment(params);
await sdk.payment.createAirtelTigoPayment(params);
await sdk.payment.createTelecelPayment(params);

// Generate request address
await sdk.payment.generateRequestAddress(params);
```

### Identity Client

```typescript
// Mint identity NFT
await sdk.identity.mintIdentity(request);

// Resolve phone to address
await sdk.identity.resolvePhoneToAddress(phoneNumber);

// Check if number exists
await sdk.identity.checkNumberExists(phoneNumber);

// KYC operations
await sdk.identity.createVeriffSession(userId);
await sdk.identity.submitKyc(request);
```

### Wallet Client

```typescript
// Balance operations
await sdk.wallet.getBalance(walletAddress);

// Transaction history
await sdk.wallet.getTransactions(params);

// Token transfers
await sdk.wallet.transferTokens(params);

// Withdrawals
await sdk.wallet.requestWithdrawal(params);
await sdk.wallet.getWithdrawalStatus(withdrawalId);
```

### Core Blockchain Operations

```typescript
// Check if wallet has identity NFT
await sdk.core.hasAccount(walletAddress);

// Get nonce for signature
await sdk.core.getNonce(walletAddress);

// Register mobile with signature
await sdk.core.registerMobileWithSignature(params);
```

### Resolver

```typescript
// Resolve mobile number from wallet
await sdk.resolver.resolveMobile(walletAddress);

// Get owned NFTs
await sdk.resolver.getOwnedNFTs(walletAddress);

// Get NFT metadata
await sdk.resolver.getNFTMetadata(tokenId);
```

## Error Handling

The SDK uses custom error types for better error handling:

```typescript
import { FiatsendError } from '@fiatsend/sdk';

try {
  await sdk.payment.initiatePayment(request);
} catch (error) {
  if (error instanceof FiatsendError) {
    console.error('Error:', error.message);
    console.error('Code:', error.code);
    console.error('Status:', error.statusCode);
  }
}
```

## Webhook Integration

Handle webhooks for real-time updates:

```typescript
// Payment webhook
app.post('/webhook/payment', async (req, res) => {
  const result = await sdk.payment.handlePaymentWebhook(req.body);
  res.json(result);
});

// Withdrawal webhook
app.post('/webhook/withdrawal', async (req, res) => {
  const result = await sdk.wallet.handleWithdrawalWebhook(req.body);
  res.json(result);
});
```

## Supported Networks

- **Lisk Sepolia** (Chain ID: 324) - Testnet
- **Polygon** (Chain ID: 137) - Mainnet
- **Ethereum** (Chain ID: 1) - Mainnet

## Supported Currencies

- **GHS** - Ghana Cedi
- **USD** - US Dollar
- **USDT** - Tether USD
- **GHSFIAT** - Ghana Fiat Token
- **FSEND** - Fiatsend Token

## Mobile Money Providers

- **MTN** - Channel 1
- **AirtelTigo** - Channel 7
- **Telecel** - Channel 6

## Development

### Building the SDK

```bash
npm run build
```

### Running Tests

```bash
npm test
npm run test:coverage
```

### Linting

```bash
npm run lint
npm run lint:fix
```

## Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Support

- 📖 [Documentation](https://developer.fiatsend.network)
- 💬 [Discord Community](https://discord.gg/fiatsend)
- 📧 [Email Support](mailto:support@fiatsend.network)
- 🐛 [Report Issues](https://github.com/fiatsend/fiatsend-monorepo/issues)

## Changelog

See [CHANGELOG.md](CHANGELOG.md) for a list of changes and version history.