# Reforge SDK

[![npm version](https://badge.fury.io/js/%40aryze%2Freforge.svg)](https://badge.fury.io/js/%40aryze%2Freforge)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Build Status](https://github.com/aryze/reforge/workflows/CI/badge.svg)](https://github.com/aryze/reforge/actions)

Professional TypeScript/JavaScript SDK for Reforge - Cross-chain token operations made simple.

## Features

- 🚀 **Type-Safe**: Full TypeScript support with comprehensive type definitions
- 🔗 **Cross-Chain**: Support for ERC20, ERC721, and ERC1155 token operations
- 🛡️ **Robust Error Handling**: Comprehensive error types with context
- 🔄 **Automatic Retry**: Intelligent retry logic with exponential backoff
- 📝 **Extensive Logging**: Configurable logging for debugging and monitoring
- 🌐 **Universal**: Works in Node.js, browsers, and React Native
- 📦 **Multiple Formats**: ESM, CommonJS, and UMD builds included
- 🧪 **Well Tested**: Comprehensive test suite with high coverage

## Installation

```bash
npm install @aryze/reforge
```

Or with yarn:

```bash
yarn add @aryze/reforge
```

Or with pnpm:

```bash
pnpm add @aryze/reforge
```

## Quick Start

### Basic Usage

```typescript
import reforge from '@aryze/reforge';

// Configure the SDK
reforge.config({
  apiKey: 'your-api-key',
  apiUrl: 'https://api.reforge.com',
  debug: false, // Enable for development
});

// Initiate a reforge operation
const initiateResult = await reforge.initiateReforge({
  chainIdHex0: '0x1', // Ethereum
  chainIdHex1: '0x89', // Polygon
  token0: '0xA0b86a33E6441d52E0b40ca83A3d2b7c83C32c05',
  token1: '0x2791bca1f2de4661ed88a30c99a7a9449aa84174',
  amount0: '1000000000000000000', // 1 token with 18 decimals
  priceToken0InUSD: 100.0,
  tx0: '0x...',
  account0: '0x742e4540d8a4b62bf2e0c14e7bed8e42ba81b938',
  tx0Timestamp: Math.floor(Date.now() / 1000),
  tokenType: 'erc20',
});

if (initiateResult.error) {
  console.error('Initiation failed:', initiateResult.error);
} else {
  console.log('Initiation successful:', initiateResult.data);
}

// Complete the reforge operation
const finishResult = await reforge.finishReforge({
  historyId: '0x1_0x...',
  amount1: '995000000000000000',
  priceToken1InUSD: 99.5,
  tx1: '0x...',
  tx1Timestamp: Math.floor(Date.now() / 1000),
});
```

### Advanced Usage with Custom Configuration

```typescript
import { ReforgeSDK, createLogger } from '@aryze/reforge';

// Create a custom SDK instance
const sdk = new ReforgeSDK({
  apiKey: process.env.REFORGE_API_KEY!,
  apiUrl: process.env.REFORGE_API_URL!,
  timeout: 30000,
  debug: process.env.NODE_ENV === 'development',
});

// Test connection
const connectionStatus = await sdk.testConnection();
console.log('Connection status:', connectionStatus);

// Use the SDK
const result = await sdk.initiateReforge({
  // ... your data
});
```

### NFT Operations

```typescript
// Reforge NFTs (ERC721/ERC1155)
const nftResult = await reforge.initiateReforge({
  chainIdHex0: '0x1',
  chainIdHex1: '0x89',
  token0: '0xNFTContract...',
  token1: '0xTokenContract...',
  amount0: '1', // Single NFT
  priceToken0InUSD: 500.0,
  tx0: '0x...',
  account0: '0x...',
  tx0Timestamp: Math.floor(Date.now() / 1000),
  tokenType: 'erc721',
  payload: [
    {
      tokenId: 12345,
      amount: 1,
      tokenURI: 'https://api.example.com/metadata/12345',
    },
  ],
});
```

## API Reference

### Configuration

```typescript
interface ReforgeSDKConfig {
  apiKey: string; // Your Reforge API key
  apiUrl: string; // Reforge API endpoint
  timeout?: number; // Request timeout in ms (default: 30000)
  debug?: boolean; // Enable debug logging (default: false)
}
```

### Reforge Operations

#### `initiateReforge(data: IReforgeInitiate)`

Initiates a cross-chain reforge operation.

```typescript
interface IReforgeInitiate {
  historyId?: HistoryId; // Optional unique identifier
  chainIdHex0: string; // Source chain ID in hex
  chainIdHex1: string; // Destination chain ID in hex
  token0: string; // Source token contract address
  token1: string; // Destination token contract address
  amount0: string; // Amount in wei
  amount1?: string; // Optional destination amount
  decimals0?: number; // Source token decimals (default: 18)
  decimals1?: number; // Destination token decimals (default: 18)
  priceToken0InUSD: number; // Source token price in USD
  priceToken1InUSD?: number; // Optional destination token price
  tx0: string; // Source transaction hash
  account0: string; // Source wallet address
  tx0Timestamp: number; // Source transaction timestamp
  tokenType: TokenType; // 'erc20' | 'erc721' | 'erc1155'
  payload?: NFTPayload[]; // NFT-specific data
}
```

#### `finishReforge(data: IReforgeFinish)`

Completes a reforge operation.

```typescript
interface IReforgeFinish {
  historyId: HistoryId; // Operation identifier
  amount1: string; // Received amount in wei
  decimals0?: number; // Source token decimals
  decimals1?: number; // Destination token decimals
  priceToken1InUSD: number; // Final token price in USD
  tx1: string; // Destination transaction hash
  account1?: string; // Destination wallet (if different)
  tx1Timestamp: number; // Completion timestamp
}
```

### Error Handling

The SDK provides comprehensive error types for different scenarios:

```typescript
import {
  ReforgeError,
  ReforgeApiError,
  ReforgeNetworkError,
  ReforgeValidationError,
  ReforgeConfigurationError,
  ReforgeOperationError,
} from '@aryze/reforge';

try {
  await reforge.initiateReforge(data);
} catch (error) {
  if (error instanceof ReforgeApiError) {
    console.error('API Error:', error.message, error.status);
  } else if (error instanceof ReforgeNetworkError) {
    console.error('Network Error:', error.message);
  } else if (error instanceof ReforgeValidationError) {
    console.error('Validation Error:', error.field, error.message);
  }
}
```

### HTTP Client

For advanced usage, you can access the underlying HTTP client:

```typescript
const client = reforge.getInstance().getClient();

// Make custom requests
const response = await client.get('/custom-endpoint');

// Add event listeners
client.on('request:start', event => {
  console.log('Request started:', event.data);
});

client.on('request:error', event => {
  console.error('Request failed:', event.data);
});
```

## Development

### Setup

```bash
# Clone the repository
git clone https://github.com/aryze/reforge-sdk.git
cd reforge-sdk

# Install dependencies
pnpm install

# Run tests
pnpm test

# Run tests with coverage
pnpm test:coverage

# Start development mode
pnpm dev
```

### Scripts

- `pnpm build` - Build all distribution formats
- `pnpm test` - Run test suite
- `pnpm test:watch` - Run tests in watch mode
- `pnpm test:coverage` - Run tests with coverage report
- `pnpm lint` - Run ESLint
- `pnpm lint:fix` - Fix ESLint issues
- `pnpm format` - Format code with Prettier
- `pnpm typecheck` - Run TypeScript type checking
- `pnpm validate` - Run full validation (typecheck + lint + test)

### Project Structure

```
src/
├── client/              # HTTP client implementation
│   ├── base.ts         # Base HTTP client
│   ├── errors.ts       # Error transformation
│   ├── interceptors.ts # Request/response interceptors
│   ├── retry.ts        # Retry logic handler
│   └── reforge-client.ts # Main client class
├── errors/             # Error classes
├── types/              # TypeScript definitions
│   ├── core.ts        # Core types
│   ├── http.ts        # HTTP-related types
│   ├── reforge.ts     # Reforge-specific types
│   └── index.ts       # Type exports
├── utils/              # Utility functions
│   ├── logger.ts      # Logging utilities
│   └── index.ts       # Utility exports
├── client.ts          # Legacy client export
├── reforge.ts         # Main SDK class
└── index.ts           # Main exports
```

## Browser Support

The SDK supports all modern browsers and environments:

- **Node.js**: 16.0.0+
- **Browsers**: Chrome 70+, Firefox 65+, Safari 12+, Edge 79+
- **React Native**: 0.60+

## TypeScript

This package is written in TypeScript and includes comprehensive type definitions. No additional `@types` packages are needed.

## Contributing

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

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Run the test suite
6. Submit a pull request

## License

MIT © [Aryze](https://github.com/aryze)

## Support

- [Documentation](https://docs.reforge.com)
- [GitHub Issues](https://github.com/aryze/reforge-sdk/issues)
- [Discord Community](https://discord.gg/aryze)

---

Made with ❤️ by the [Aryze](https://aryze.io) team.
