npm package: @pbpcanada/projectdam-sdk
Description: TypeScript SDK for ProjectDAM - Agent-operated NFT AMM on Solana
Author: PBP Canada
Latest version: 1.7.1

# @pbpcanada/projectdam-sdk

TypeScript SDK for **ProjectDAM** - Agent-operated NFT AMM on Solana

ProjectDAM is a decentralized NFT Automated Market Maker (AMM) built on Solana that enables instant NFT liquidity through algorithmic pricing curves.

## Features

- 🔍 **Account Decoders** - Parse all ProjectDAM account types from raw buffer data
- 🔑 **PDA Helpers** - Generate Program Derived Addresses for all seeds
- 📝 **Instruction Builders** - Create transactions for all core operations
- 🛡️ **Type Safety** - Full TypeScript interfaces and enums
- 📋 **IDL Export** - Complete program interface definition
- 🚀 **Client Class** - High-level API for common operations

## Installation

```bash
npm install @pbpcanada/projectdam-sdk @solana/web3.js @coral-xyz/anchor
```

## Quick Start

```typescript
import { Connection, PublicKey } from '@solana/web3.js';
import { 
  ProjectDAMClient, 
  PROGRAM_ID, 
  findPoolPDA,
  decodePool,
  CurveType,
  PoolType 
} from '@pbpcanada/projectdam-sdk';

// Initialize connection and client
const connection = new Connection('https://api.mainnet-beta.solana.com');
const client = new ProjectDAMClient(connection);

// Get protocol configuration
const config = await client.getConfig();
console.log('Protocol fee:', config?.protocolFeeBps, 'bps');

// Find a pool PDA
const owner = new PublicKey('...');
const uuid = Buffer.from([1, 2, 3, 4, 5, 6]);
const [poolPDA, bump] = findPoolPDA(owner, uuid);

// Decode pool data
const poolAccount = await connection.getAccountInfo(poolPDA);
if (poolAccount) {
  const pool = decodePool(poolAccount.data);
  console.log('Pool type:', PoolType[pool.poolType]);
  console.log('Curve type:', CurveType[pool.curveType.type]);
  console.log('Spot price:', pool.spotPrice, 'lamports');
}

// Get all pools by collection
const collectionMint = new PublicKey('...');
const pools = await client.getPoolsByCollection(collectionMint);
console.log(`Found ${pools.length} pools for collection`);
```

## Core Concepts

### Pool Types

```typescript
enum PoolType {
  Nft = 0,    // Buy NFTs from pool
  Token = 1,  // Sell NFTs to pool  
  Trade = 2   // Both buy and sell
}
```

### Curve Types

```typescript
enum CurveType {
  Fixed = 0,       // Constant price
  Linear = 1,      // Price increases linearly
  Exponential = 2  // Price increases exponentially
}
```

### Account Types

- **Config** - Protocol configuration and global stats
- **Pool** - Individual liquidity pool for a collection
- **PoolNft** - NFT deposit tracking
- **Season** - Monthly trading competitions
- **TraderVolume** - Individual trader statistics
- **CollectionStats** - Collection-wide analytics

## API Reference

### Client Methods

```typescript
const client = new ProjectDAMClient(connection, programId?);

// Account fetching
await client.getConfig()
await client.getPool(poolAddress)
await client.getPoolNft(poolNftAddress)

// Bulk queries
await client.getPoolsByOwner(owner)
await client.getPoolsByCollection(collection)
await client.getPoolNfts(pool)
```

### PDA Helpers

```typescript
import { 
  findConfigPDA,
  findPoolPDA,
  findSolVaultPDA,
  findPoolNftPDA,
  findSeasonPDA,
  generatePoolUuid
} from '@pbpcanada/projectdam-sdk';

// Generate PDAs
const [config] = findConfigPDA();
const [pool] = findPoolPDA(owner, uuid);
const [vault] = findSolVaultPDA(pool);
const [poolNft] = findPoolNftPDA(pool, nftMint);

// Generate random UUID for new pools
const uuid = generatePoolUuid();
```

### Instruction Builders

```typescript
import {
  createPoolInstruction,
  buyInstruction,
  sellInstruction,
  depositSolInstruction,
  depositNftInstruction
} from '@pbpcanada/projectdam-sdk';

// Create a new pool
const createPoolIx = createPoolInstruction(
  {
    uuid: generatePoolUuid(),
    curveType: { type: CurveType.Linear, delta: 100000000n }, // 0.1 SOL
    spotPrice: 1000000000n, // 1 SOL
    spreadBps: 50, // 0.5%
    poolType: PoolType.Trade
  },
  owner.publicKey,
  collectionMint
);

// Buy an NFT
const buyIx = buyInstruction(
  pool,
  nftMint,
  buyer.publicKey,
  poolOwner,
  feeBuffer,
  creatorWallet,
  { maxPrice: 2000000000n } // 2 SOL max
);
```

### Account Decoders

```typescript
import {
  decodeConfig,
  decodePool,
  decodePoolNft,
  parseAccount,
  fromBase64
} from '@pbpcanada/projectdam-sdk';

// Decode specific account types
const config = decodeConfig(accountData);
const pool = decodePool(accountData);
const poolNft = decodePoolNft(accountData);

// Auto-detect account type
const parsed = parseAccount(accountData);
if (parsed.type === 'pool') {
  console.log('Pool owner:', parsed.data.owner.toBase58());
}

// Decode from base64 string
const buffer = fromBase64(base64String);
const pool = decodePool(buffer);
```

## Program IDs

```typescript
import { PROGRAM_IDS, PROGRAM_ID } from '@pbpcanada/projectdam-sdk';

// Mainnet: DAmKEbaRoFMKRqdYb6zSrfYvH7Zyx1VLBoixKenii25e
console.log(PROGRAM_IDS.MAINNET);

// Devnet: GyX8E52YsmuaojfbhGo6Y5ey8Qg31nbkvYUydEtfY4Ci  
console.log(PROGRAM_IDS.DEVNET);

// Default (mainnet)
console.log(PROGRAM_ID);
```

## Advanced Usage

### Working with Curves

```typescript
import { CurveType } from '@pbpcanada/projectdam-sdk';

// Fixed price pool
const fixedCurve = { type: CurveType.Fixed };

// Linear bonding curve (price increases by delta each trade)
const linearCurve = { 
  type: CurveType.Linear, 
  delta: 50000000n // 0.05 SOL increase per trade
};

// Exponential bonding curve (price multiplies by factor each trade)
const expCurve = { 
  type: CurveType.Exponential, 
  delta: 110 // 1.1% increase per trade (110 bps)
};
```

### Event Parsing

```typescript
import { DAM_PROTOCOL_IDL } from '@pbpcanada/projectdam-sdk';

// Use IDL with Anchor for event parsing
import { Program } from '@coral-xyz/anchor';

const program = new Program(DAM_PROTOCOL_IDL, PROGRAM_ID, provider);

// Listen to trade events
program.addEventListener('TradeEvent', (event) => {
  console.log('Trade:', {
    pool: event.pool.toBase58(),
    nftMint: event.nftMint.toBase58(),
    price: event.price.toString(),
    isBuy: event.isBuy
  });
});
```

### Error Handling

```typescript
import { DAM_PROTOCOL_IDL } from '@pbpcanada/projectdam-sdk';

// Error codes from IDL
const ERRORS = {
  InvalidPrice: 6000,
  SpreadTooHigh: 6001,
  PoolInactive: 6002,
  ProtocolPaused: 6003,
  Unauthorized: 6004,
  SlippageExceeded: 6005,
  PoolCantBuy: 6006,
  InsufficientLiquidity: 6007,
  InvalidAmount: 6008,
  InvalidCollection: 6009,
  MathOverflow: 6010
};
```

## Examples

Check out the [examples directory](./examples) for complete working examples:

- **Pool Creation** - Create new liquidity pools
- **Trading** - Buy and sell NFTs through pools  
- **Liquidity Management** - Deposit/withdraw SOL and NFTs
- **Analytics** - Query pool statistics and performance
- **Season Tracking** - Volume competitions and leaderboards

## Contributing

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

## License

MIT License - see [LICENSE](./LICENSE) for details.

## Links

- **Program:** [DAmKEbaRoFMKRqdYb6zSrfYvH7Zyx1VLBoixKenii25e](https://solscan.io/account/DAmKEbaRoFMKRqdYb6zSrfYvH7Zyx1VLBoixKenii25e)
- **Documentation:** [ProjectDAM Docs](https://docs.projectdam.io)
- **Discord:** [PBP Canada](https://discord.gg/pbpcanada)
- **Twitter:** [@ProjectDAM_io](https://twitter.com/ProjectDAM_io)