npm package: @meme-sdk/trade
Description: A focused Node.js library for core trading functions on Four.meme platform
Author: fourmeme.trade@gmail.com
Latest version: 1.0.1

# FourMeme Trading Library - Core Functions

A focused Node.js library for core trading functions on Four.meme platform with automatic migration detection and dual exchange support.

## Features

- **Migration Detection**: Automatically detects if token has migrated to PancakeSwap
- **Four.meme Trading**: Buy/sell tokens before migration (using Four.meme contracts)
- **PancakeSwap Trading**: Buy/sell tokens after migration (using PancakeRouter)
- **Smart Routing**: Automatically chooses the correct exchange based on migration status
- **TypeScript Support**: Full TypeScript support with comprehensive type definitions

## Installation

```bash
npm install @meme-sdk/trade
```

## Quick Start

```typescript
import { FourMemeTrader } from '@meme-sdk/trade';

// Initialize trader
const trader = new FourMemeTrader({
  rpcUrl: 'https://bsc-dataseed.binance.org',
  privateKey: 'your-private-key-here'
});

// Check migration status
const migrationStatus = await trader.getMigrationStatus('0x...');

if (migrationStatus.migrated) {
  // Token migrated to PancakeSwap
  const buyResult = await trader.buyPancakeToken('0x...', 0.01); // Buy with 0.01 BNB
  console.log(`Bought tokens: ${buyResult.estimatedTokens}`);
  
  const sellResult = await trader.sellPancakeToken('0x...', 1000); // Sell 1000 tokens
  console.log(`Sold tokens: ${sellResult.txHash}`);
} else {
  // Token still on Four.meme
  const buyResult = await trader.buyToken('0x...', 0.01); // Buy with 0.01 BNB
  console.log(`Bought tokens: ${buyResult.estimatedTokens}`);
  
  const sellResult = await trader.sellToken('0x...', 1000); // Sell 1000 tokens
  console.log(`Sold tokens: ${sellResult.txHash}`);
}
```

## API Reference

### FourMemeTrader

Main trading class for Four.meme platform operations.

#### Constructor

```typescript
new FourMemeTrader(config: TraderConfig)
```

**TraderConfig:**
- `rpcUrl: string` - BSC RPC endpoint
- `privateKey: string` - Your wallet private key
- `tokenManagerAddress?: string` - Four.meme TokenManager contract (optional)
- `helper3Address?: string` - Four.meme Helper3 contract (optional)
- `pancakeRouterAddress?: string` - PancakeSwap Router contract (optional)
- `wbnbAddress?: string` - WBNB token address (optional)

#### Methods

##### `getMigrationStatus(tokenAddress: string): Promise<MigrationStatus>`

Check if a token has migrated to PancakeSwap.

**Returns:**
```typescript
{
  migrated: boolean;
  timestamp: number;
}
```

##### `buyToken(tokenAddress: string, bnbAmount: number): Promise<BuyResult>`

Buy tokens using Four.meme (before migration).

**Returns:**
```typescript
{
  estimatedTokens: string;
  realTokenBalance: bigint;
  txHash: string;
  gasUsed: string;
  duration: number;
}
```

##### `sellToken(tokenAddress: string, tokenAmount: number): Promise<SellResult>`

Sell tokens using Four.meme (before migration).

**Returns:**
```typescript
{
  txHash: string;
  gasUsed: string;
}
```

##### `buyPancakeToken(tokenAddress: string, bnbAmount: number): Promise<BuyResult>`

Buy tokens using PancakeSwap (after migration).

##### `sellPancakeToken(tokenAddress: string, tokenAmount: number): Promise<SellResult>`

Sell tokens using PancakeSwap (after migration).

##### `getWalletAddress(): string`

Get the current wallet address.

### Utilities

```typescript
import { formatBNB, parseBNB, isValidAddress, sleep } from '@meme-sdk/trade';

// Format BNB amount
const formatted = formatBNB(ethers.parseEther('1.0')); // "1.0"

// Parse BNB string
const parsed = parseBNB('1.0'); // 1000000000000000000n

// Validate address
const isValid = isValidAddress('0x...'); // boolean

// Sleep
await sleep(1000); // Wait 1 second
```

### Constants

```typescript
import { DEFAULT_ADDRESSES, DEFAULT_RPC_URLS } from '@meme-sdk/trade';

// Default contract addresses
DEFAULT_ADDRESSES.TOKEN_MANAGER
DEFAULT_ADDRESSES.HELPER3
DEFAULT_ADDRESSES.PANCAKE_ROUTER
DEFAULT_ADDRESSES.WBNB

// Default RPC URLs
DEFAULT_RPC_URLS.BSC_MAINNET
DEFAULT_RPC_URLS.BSC_TESTNET
```

## How It Works

### Migration Detection

The library automatically detects the migration status of any Four.meme token:

- **Before Migration**: Uses Four.meme contracts for trading
- **After Migration**: Uses PancakeSwap Router for trading

The library checks the `liquidityAdded` status from the Helper3 contract:
- `false` = Token still on Four.meme (use Four.meme contracts)
- `true` = Token migrated to PancakeSwap (use PancakeRouter)

### Trading Flow

1. **Check Migration Status**: Determines if token has migrated
2. **Route to Correct Exchange**:
   - Four.meme → Uses `buyToken` and `sellToken`
   - PancakeSwap → Uses `buyPancakeToken` and `sellPancakeToken`
3. **Execute Trade**: Handles approvals, timing, and transaction execution

## Error Handling

The library throws descriptive errors for common issues:

- **"PRIVATE_KEY is required"**: Missing private key in configuration
- **"RPC_URL is required"**: Missing RPC URL in configuration
- **"Insufficient BNB balance"**: Not enough BNB for the transaction
- **"Insufficient token balance"**: Not enough tokens to sell

## Security Notes

- Keep your private keys secure
- Use environment variables for sensitive data
- Test with small amounts first
- Consider using hardware wallets for large amounts

## License

MIT

## Support

For issues and questions, please visit: https://github.com/meme-sdk/fourmeme-trading/issues