npm package: @skywu/buy-tax
Description: A referral purchase marketplace with Bitcoin/USDT payment integration
Author: Your Name
Latest version: 1.1.3

# Referral Trading Marketplace

A comprehensive npm package for creating a referral purchase marketplace with Bitcoin and USDT payment integration. This package provides a complete trading interface where users can purchase referrals from virtual sellers using cryptocurrency payments.

## Features

- 🏪 **Virtual Marketplace**: Complete trading interface with simulated sellers
- 💰 **Crypto Payments**: Bitcoin (BTC) and USDT payment support
- 📊 **Smart Pricing**: Bulk discount algorithm with decreasing per-unit costs
- 🌍 **Internationalization**: Multi-language support using @skywu/translator
- 🔒 **Security**: Comprehensive validation and security measures
- 📱 **Responsive UI**: Embeddable or modal interface
- ⚡ **Real-time**: Payment status monitoring and updates

## Installation

```bash
npm install @skywu/buy-tax
```

## Quick Start (one‑liner modal)

```javascript
import { openMarketplaceModal } from '@skywu/buy-tax';

// In your button click handler
document.getElementById('open-market-btn').addEventListener('click', async () => {
  await openMarketplaceModal({
    // apiBaseUrl is optional and defaults to same-origin proxy '/api/paybtc-usdt'
    width: 480,                            // optional, default ~480
    onClose: () => console.log('Marketplace closed')
  });
});
```

> Backend setup: provide a reverse proxy at '/api/paybtc-usdt' that forwards to your real PAY API base, adding Authorization header from server-side .env (e.g., PAY_API_BASE, PAY_API_KEY).

> The modal renders the Telegram‑style marketplace UI with the header, info banner ("This marketplace enables peer‑to‑peer trading between users." + sell), single‑column seller list, Buy buttons, standard crypto URIs for QR (bitcoin:/tron:), and auto‑polling.

## Configuration

### MarketplaceConfig

```typescript
interface MarketplaceConfig {
  apiBaseUrl?: string;          // Optional; defaults to same-origin proxy '/api/paybtc-usdt'
  apiKey?: string;              // Optional API key (handled server-side via proxy is recommended)
  theme?: 'light' | 'dark';     // UI theme
  language?: string;            // Language code (e.g., 'en', 'es')
  onPurchaseComplete?: (order: PurchaseOrder) => void;
  onError?: (error: Error) => void;
}
```

### MarketplaceOptions

```typescript
interface MarketplaceOptions {
  containerId?: string;         // Container element ID for embedded mode
  modal?: boolean;              // Show as modal (default: true)
  width?: number;               // Width in pixels (default: 800)
  height?: number;              // Height in pixels (default: 600)
}
```

## Pricing Algorithm

The package implements a sophisticated bulk discount pricing system:

- **Minimum**: 20 referrals for $10 USD ($0.50 per referral)
- **Maximum**: 200 referrals for $60 USD ($0.30 per referral)
- **Algorithm**: Logarithmic scaling for smooth bulk discounts

```javascript
import { PricingCalculator } from '@skywu/buy-tax';

// Calculate price for 100 referrals
const price = PricingCalculator.calculatePrice(100);
const unitPrice = PricingCalculator.calculateUnitPrice(100);
const discount = PricingCalculator.calculateDiscount(100);

console.log(`100 referrals: $${price} ($${unitPrice} each, ${discount}% discount)`);
```

## Payment Integration

The package integrates with your payment API using the following endpoints:

### Get Payment Address

```
POST /api/v1/receive-address
Content-Type: application/json

{
  "user_id": "string",
  "currency": "BTC|USDT",
  "amount_usd": number
}
```

### Check Payment Status

```
GET /api/v1/receive-address/{address}/status
Content-Type: application/json
```

## Usage Examples

### Basic Integration

```javascript
import ReferralMarketplace from '@skywu/buy-tax';

const marketplace = new ReferralMarketplace({
  // apiBaseUrl omitted; defaults to '/api/paybtc-usdt'
  language: 'en'
});

// Show in modal
await marketplace.show({ modal: true });
```

### Embedded Integration

```html
<div id="marketplace-container"></div>

<script>
import { createMarketplace } from '@skywu/buy-tax';

const marketplace = createMarketplace({
  // apiBaseUrl omitted; defaults to '/api/paybtc-usdt'
});

marketplace.show({
  containerId: 'marketplace-container',
  modal: false,
  width: 1000,
  height: 700
});
</script>
```

### Event Handling

```javascript
const marketplace = createMarketplace({
  // apiBaseUrl omitted; defaults to '/api/paybtc-usdt'
});

// Listen to events
marketplace.on('onSellerSelect', (seller) => {
  console.log('Selected seller:', seller.name);
});

marketplace.on('onPackageSelect', (package) => {
  console.log('Selected package:', package.referralCount, 'referrals');
});

marketplace.on('onPaymentInitiated', (order) => {
  console.log('Payment initiated:', order.id);
});

marketplace.on('onPurchaseComplete', (order) => {
  console.log('Purchase completed:', order);
  // Credit referrals to user account
  creditReferrals(order.userId, order.referralCount);
});
```

### Custom Language Support

```javascript
import { TranslationService } from '@skywu/buy-tax';

const translationService = new TranslationService('es');
await translationService.initialize();

// Add custom translations
translationService.addTranslations('es', {
  marketplace: {
    customMessage: 'Mensaje personalizado'
  }
});

const marketplace = new ReferralMarketplace({
  apiBaseUrl: 'https://api.example.com',
  language: 'es'
});
```

## API Reference

### ReferralMarketplace

Main marketplace class that orchestrates all components.

#### Methods

- `show(options?: MarketplaceOptions): Promise<void>` - Show the marketplace
- `hide(): void` - Hide the marketplace
- `purchaseReferrals(sellerId, packageId, currency, userId): Promise<PurchaseOrder>` - Purchase referrals
- `getOrder(orderId): PurchaseOrder | undefined` - Get order by ID
- `getUserOrders(userId): PurchaseOrder[]` - Get user's orders
- `on(event, callback): void` - Add event listener
- `off(event, callback): void` - Remove event listener
- `getStats()` - Get marketplace statistics

### PricingCalculator

Utility class for pricing calculations.

#### Static Methods

- `calculatePrice(referralCount): number` - Calculate total price
- `calculateUnitPrice(referralCount): number` - Calculate per-referral price
- `calculateDiscount(referralCount): number` - Calculate discount percentage
- `generatePackages(): ReferralPackage[]` - Generate predefined packages
- `isValidQuantity(referralCount): boolean` - Validate quantity
- `getClosestValidQuantity(referralCount): number` - Get closest valid quantity

### PaymentService

Service for handling payment API integration.

#### Methods

- `getPaymentAddress(request): Promise<PaymentResponse>` - Get payment address
- `checkPaymentStatus(address): Promise<PaymentStatusResponse>` - Check payment status
- `pollPaymentStatus(address, callback?, interval?, maxAttempts?): Promise<PaymentStatusResponse>` - Poll payment status

## Error Handling

The package includes comprehensive error handling:

```javascript
import { ErrorHandler, ErrorCode, MarketplaceError } from '@skywu/buy-tax';

const errorHandler = ErrorHandler.getInstance();

// Handle specific error types
errorHandler.onError(ErrorCode.PAYMENT_FAILED, (error) => {
  console.log('Payment failed:', error.message);
  // Show retry option to user
});

errorHandler.onError(ErrorCode.NETWORK_ERROR, (error) => {
  console.log('Network error:', error.message);
  // Show offline message
});

// Global error handler
errorHandler.onGlobalError((error) => {
  console.log('Global error:', error.toJSON());
  // Log to external service
});
```

## Security Features

- Input validation and sanitization
- Cryptocurrency address validation
- Rate limiting
- Suspicious activity detection
- API timeout handling
- XSS protection

## TypeScript Support

The package is written in TypeScript and includes full type definitions:

```typescript
import {
  ReferralMarketplace,
  MarketplaceConfig,
  PurchaseOrder,
  Currency
} from '@skywu/buy-tax';

const config: MarketplaceConfig = {
  // apiBaseUrl optional; defaults to '/api/paybtc-usdt'
  theme: 'dark',
  language: 'en'
};

const marketplace = new ReferralMarketplace(config);
```

## Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

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

## Support

For support, email support@example.com or create an issue on GitHub.