# @iota-big3/sdk-blockchain

Comprehensive blockchain integration platform with multi-chain support, smart contracts, DeFi protocols, NFT infrastructure, Web3 authentication, and seamless SDK ecosystem integration.

## Features

### 🔗 Multi-Chain Support

- **Ethereum & EVM Chains**: Ethereum, Polygon, Arbitrum, Optimism, BSC
- **Solana**: Native Solana integration
- **Bitcoin**: UTXO-based transactions, Lightning Network support
- **Chain Abstraction**: Unified interface across all chains
- **Automatic Switching**: Seamless chain transitions
- **Custom Chains**: Add any EVM-compatible chain

### 📝 Smart Contracts

- **Contract Deployment**: Deploy contracts to any chain
- **Type-Safe Interactions**: Full TypeScript support
- **Event Monitoring**: Real-time contract events
- **ABI Management**: Automatic ABI handling
- **Gas Optimization**: Smart gas strategies

### 💰 DeFi Protocols

- **Lending/Borrowing**: Aave, Compound integration
- **DEX Trading**: Uniswap, SushiSwap support
- **Liquidity Provision**: Add/remove liquidity
- **Yield Farming**: Auto-compound strategies
- **Cross-Protocol**: Unified DeFi interface

### 🎨 NFT Infrastructure

- **Minting**: Create NFTs with metadata
- **Marketplace**: Built-in NFT marketplace
- **IPFS Storage**: Decentralized metadata
- **Collection Management**: Deploy collections
- **Royalties**: EIP-2981 standard support

### 🔐 Web3 Authentication

- **Multiple Wallets**: MetaMask, WalletConnect, Phantom
- **Session Management**: Secure sessions
- **Message Signing**: Sign and verify messages
- **Multi-Signature**: Support for multi-sig
- **Social Recovery**: Recovery mechanisms

### 🔌 SDK Ecosystem Integration (New!)

- **Event System**: Real-time blockchain event notifications
- **Database Integration**: Automatic transaction history persistence
- **Performance Caching**: Reduced RPC calls and improved response times
- **Feature Flags**: Toggle integrations on/off as needed
- **Graceful Fallbacks**: Works standalone without integrations

## Installation

```bash
npm install @iota-big3/sdk-blockchain
```

## Quick Start

### Basic Usage (Standalone)

```typescript
import { createBlockchainManager } from "@iota-big3/sdk-blockchain";

// Initialize blockchain manager
const blockchain = createBlockchainManager({
  defaultChain: 1, // Ethereum mainnet
  supportedChains: [1, 137, 56], // ETH, Polygon, BSC
  rpcEndpoints: {
    1: "https://eth.llamarpc.com",
    137: "https://polygon-rpc.com",
    56: "https://bsc-dataseed.binance.org",
  },
});

// Initialize and connect
await blockchain.multiChain.initialize();
const balance = await blockchain.multiChain.getBalance("0x...");
```

### With SDK Integrations

```typescript
import { EventBus } from "@iota-big3/sdk-events";
import { createBlockchainManager } from "@iota-big3/sdk-blockchain";

// Create event bus for real-time notifications
const eventBus = new EventBus();

// Listen to blockchain events
eventBus.on("blockchain:transaction.sent", (event) => {
  console.log("Transaction sent:", event.data.hash);
  console.log("Block number:", event.data.blockNumber);
});

eventBus.on("blockchain:chain.changed", (event) => {
  console.log("Switched from chain", event.data.previousChain);
  console.log("To chain", event.data.newChain);
});

// Initialize with full integrations
const blockchain = createBlockchainManager({
  defaultChain: 1,
  supportedChains: [1, 137, 56],
  rpcEndpoints: {
    1: "https://eth.llamarpc.com",
    137: "https://polygon-rpc.com",
    56: "https://bsc-dataseed.binance.org",
  },

  // SDK Integrations
  eventBus, // Event notifications

  database: {
    // Transaction persistence
    type: "postgres",
    host: "localhost",
    database: "blockchain_db",
    user: "admin",
    password: "password",
  },

  performance: {
    // RPC caching
    cache: {
      ttl: 60000, // 1 minute cache
      maxSize: 1000,
    },
  },

  features: {
    // Feature flags
    eventIntegration: true,
    databaseIntegration: true,
    cacheIntegration: true,
  },
});

// All operations now emit events and use caching
await blockchain.multiChain.initialize();
const tx = await blockchain.multiChain.sendTransaction({
  to: "0x...",
  value: "1.0",
});
```

## Advanced Usage

### Smart Contract Deployment

```typescript
// Deploy an ERC20 token
const deployment = await blockchain.contracts.deployContract({
  bytecode: ERC20_BYTECODE,
  abi: ERC20_ABI,
  constructorArgs: ["MyToken", "MTK", ethers.parseEther("1000000")],
});

// Contract deployment event automatically emitted
// Event: blockchain:contract.deployed

// Interact with contract
const contract = await blockchain.contracts.getContract(
  deployment.address,
  ERC20_ABI
);

const balance = await contract.balanceOf(address);

// Listen to contract events
eventBus.on("blockchain:contract.event", (event) => {
  if (event.data.address === deployment.address) {
    console.log("Contract event:", event.data.event);
    console.log("Args:", event.data.args);
  }
});
```

### Transaction History (with Database Integration)

```typescript
// All transactions are automatically stored when database is configured
const history = await blockchain.multiChain.getTransactionHistory("0x...");

console.log("Transaction history:", history);
// Returns: Array of transaction records with full details
```

### Performance Optimization (with Cache Integration)

```typescript
// First call hits RPC endpoint
const balance1 = await blockchain.multiChain.getBalance("0x...");
// Takes ~200ms

// Second call uses cache (within TTL)
const balance2 = await blockchain.multiChain.getBalance("0x...");
// Takes ~1ms

// Gas prices cached with shorter TTL (30 seconds)
const gasPrice = await blockchain.multiChain.getGasPrice();
```

### Bitcoin Support

```typescript
// Enable Bitcoin in configuration
const blockchain = createBlockchainManager({
  // ... other config
  bitcoin: {
    enabled: true,
    network: "testnet",
    rpcUrl: "http://localhost:8332",
    rpcUser: "user",
    rpcPass: "pass",
  },
});

// Bitcoin operations
const btcAddress = await blockchain.bitcoin.generateAddress("p2wpkh");
const utxos = await blockchain.bitcoin.getUTXOs(btcAddress);

// Send Bitcoin transaction
const txid = await blockchain.bitcoin.sendTransaction({
  to: "bc1q...",
  amount: 0.001,
  fee: 0.00001,
});
```

## Configuration Options

### Full Configuration Example

```typescript
const config = {
  // Chain configuration
  defaultChain: 1,
  supportedChains: [1, 137, 56, 43114],
  rpcEndpoints: {
    1: process.env.ETH_RPC_URL,
    137: process.env.POLYGON_RPC_URL,
    56: process.env.BSC_RPC_URL,
    43114: process.env.AVALANCHE_RPC_URL,
  },

  // Web3 Authentication
  web3Auth: {
    enabled: true,
    clientId: process.env.WEB3_AUTH_CLIENT_ID,
    network: "mainnet",
  },

  // SDK Integrations
  eventBus: new EventBus(), // From @iota-big3/sdk-events

  database: {
    // From @iota-big3/sdk-database
    type: "postgres",
    connectionString: process.env.DATABASE_URL,
    // OR
    host: "localhost",
    port: 5432,
    database: "blockchain",
    user: "admin",
    password: "password",
  },

  performance: {
    // From @iota-big3/sdk-performance
    cache: {
      ttl: 60000, // Default cache TTL (1 minute)
      maxSize: 1000, // Maximum cache entries
      layers: [
        {
          name: "memory",
          type: "memory",
        },
      ],
    },
  },

  // Feature flags
  features: {
    eventIntegration: true, // Enable event emission
    databaseIntegration: true, // Enable transaction storage
    cacheIntegration: true, // Enable RPC caching
  },

  // Bitcoin configuration (optional)
  bitcoin: {
    enabled: false,
    network: "mainnet",
    rpcUrl: "http://localhost:8332",
    rpcUser: "bitcoin",
    rpcPass: "password",
  },
};
```

## Event Types

The SDK emits various events when integrated with `@iota-big3/sdk-events`:

### Transaction Events

- `blockchain:transaction.sent` - Transaction broadcast
- `blockchain:transaction.failed` - Transaction failed
- `blockchain:transaction.confirmed` - Transaction confirmed

### Chain Events

- `blockchain:multichain.initialized` - Multi-chain connector ready
- `blockchain:chain.changed` - Active chain switched
- `blockchain:provider.connected` - Provider connected

### Contract Events

- `blockchain:contract.deployed` - Contract deployed
- `blockchain:contract.event` - Contract event emitted

### DeFi Events

- `blockchain:defi.swap` - Token swap executed
- `blockchain:defi.liquidity.added` - Liquidity added
- `blockchain:defi.liquidity.removed` - Liquidity removed

### NFT Events

- `blockchain:nft.minted` - NFT minted
- `blockchain:nft.transferred` - NFT transferred

### Bitcoin Events

- `blockchain:bitcoin.utxo.received` - UTXO received
- `blockchain:bitcoin.transaction.broadcast` - Bitcoin transaction sent

## Benefits of SDK Integration

### 1. **Observability**

- Real-time event notifications for all blockchain operations
- Easy monitoring and debugging
- Integration with logging and analytics systems

### 2. **Data Persistence**

- Automatic transaction history storage
- Query historical data without blockchain scanning
- Reduced dependency on external block explorers

### 3. **Performance**

- Cached RPC responses reduce latency
- Lower RPC costs through intelligent caching
- Configurable TTL for different data types

### 4. **Flexibility**

- All integrations are optional
- Feature flags for granular control
- Graceful fallbacks ensure reliability

### 5. **Ecosystem Benefits**

- Seamless integration with other IOTA Big3 SDKs
- Consistent patterns across the ecosystem
- Shared infrastructure reduces complexity

## Migration Guide

### From v1.x to v2.x

```typescript
// Old way (v1.x)
const blockchain = new BlockchainSDK({
  network: "mainnet",
  provider: "infura",
});

// New way (v2.x) - Basic
const blockchain = createBlockchainManager({
  defaultChain: 1,
  supportedChains: [1],
  rpcEndpoints: { 1: "https://eth.llamarpc.com" },
});

// New way (v2.x) - With integrations
const blockchain = createBlockchainManager({
  defaultChain: 1,
  supportedChains: [1],
  rpcEndpoints: { 1: "https://eth.llamarpc.com" },
  eventBus: new EventBus(),
  database: { type: "postgres", connectionString: "..." },
  performance: { cache: { ttl: 60000 } },
});
```

## API Reference

See full API documentation at [https://docs.iota-big3.com/sdk-blockchain](https://docs.iota-big3.com/sdk-blockchain)

## License

MIT
