npm package: @stochain/dex-swap
Description: DEX swap utilities for PancakeSwap and other DEXs
Author: Stochain
Latest version: 1.0.0

# @stochain/dex-swap

DEX swap utilities for PancakeSwap and other decentralized exchanges.

## Installation

```bash
npm install @stochain/dex-swap ethers simple-pancakeswap-sdk
```

## Features

- 🥞 PancakeSwap integration
- 💱 Token swap utilities
- 📊 Exchange rate calculation
- ✅ Swap validation
- 🎣 React hooks for swap management
- 💰 Token balance queries

## Usage

### Basic Swap with PancakeSwap

```typescript
import { trade, swap } from '@stochain/dex-swap';
import { Wallet } from 'ethers';

// Create trade
const tradeContext = await trade({
  ethAddress: '0x...',
  fromTokenAddress: '0x...',
  toTokenAddress: '0x...',
  amount: '1.0',
  slippage: 0.005, // 0.5%
  deadlineMinutes: 20
});

// Execute swap
const wallet = new Wallet('private-key');
const result = await swap(wallet, tradeContext);
```

### React Hook for Swap Management

```typescript
import { useSwap } from '@stochain/dex-swap';

function SwapScreen() {
  const {
    fromToken,
    toToken,
    setFromToken,
    setToToken,
    fromAmount,
    toAmount,
    handleFromAmountChange,
    handleMaxAmount,
    swapTokens,
    executeSwap,
    isSwapEnabled,
    exchangeRate
  } = useSwap({
    onSwapComplete: () => console.log('Swap completed'),
    onSwapError: (error) => console.error('Swap failed:', error)
  });

  return (
    <View>
      <TextInput
        value={fromAmount}
        onChangeText={handleFromAmountChange}
        placeholder="0.00"
      />
      <Text>Exchange Rate: {exchangeRate}</Text>
      <Text>You will receive: {toAmount}</Text>
      <Button
        title="Swap"
        onPress={executeSwap}
        disabled={!isSwapEnabled()}
      />
    </View>
  );
}
```

### Swap Validation

```typescript
import { validateSwap } from '@stochain/dex-swap';

const validation = validateSwap(fromToken, toToken, '1.0');

if (!validation.isValid) {
  console.error('Validation errors:', validation.errors);
}
```

### Exchange Rate Calculation

```typescript
import { calculateExchangeRate } from '@stochain/dex-swap';

const result = calculateExchangeRate(
  fromToken,
  toToken,
  '1.0'
);

console.log('Rate:', result.rate);
console.log('To Amount:', result.toAmount);
```

### Token Balance

```typescript
import { getTokenBalance, getBNBToken } from '@stochain/dex-swap';
import { Wallet } from 'ethers';

const wallet = new Wallet('private-key');

// Get BNB balance
const bnbToken = await getBNBToken(wallet);
console.log('BNB balance:', bnbToken.balance.val);

// Get ERC20 token balance
const balance = await getTokenBalance(wallet, {
  address: '0x...'
});
console.log('Token balance:', balance.val);
```

## API Reference

### PancakeSwap Functions

- `trade(params)`: Create a trade on PancakeSwap
- `swap(wallet, tradeContext)`: Execute swap transaction
- `getTokenBalance(wallet, token, providerUrl?)`: Get token balance
- `getBNBToken(wallet)`: Get BNB token info
- `getToken(tokenAddress, chainId)`: Get token information

### Swap Service Functions

- `calculateExchangeRate(fromToken, toToken, fromAmount)`: Calculate exchange rate
- `validateSwap(fromToken, toToken, fromAmount)`: Validate swap parameters
- `executeSwap(fromToken, toToken, fromAmount, toAmount)`: Execute swap
- `updateBalancesAfterSwap(...)`: Update balances after swap

### React Hooks

- `useSwap(options?)`: Hook for swap state management

## Types

```typescript
interface Token {
  symbol: string;
  name: string;
  address?: string;
  network: string;
  balance?: string;
  price?: number;
}

interface TradeParams {
  ethAddress: string;
  fromTokenAddress: string;
  toTokenAddress: string;
  amount: string;
  providerUrl?: string;
  slippage?: number;
  deadlineMinutes?: number;
}

interface ValidationResult {
  isValid: boolean;
  errors: string[];
}
```

## License

MIT