npm package: @hydrawallet-sdk/core
Description: Hydra wallet
Latest version: 1.0.2
Deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

# @hydrawallet/core

A comprehensive Cardano wallet SDK designed specifically for **Browser DApps**. This core library provides essential wallet functionality with full support for modern build tools including **Vite** and **Rollup**, making it perfect for decentralized applications running in web browsers.

[![Join us on Discord](https://img.shields.io/discord/1249288501383579738?color=5865F2&label=Join%20us%20on%20Discord&logo=discord&style=flat-square)](https://discord.gg/MaqrYbdKzM)


## 🎯 Purpose

**@hydrawallet/core** is built specifically for browser-based decentralized applications (DApps) that need to interact with the Cardano blockchain. Whether you're building a DeFi protocol, NFT marketplace, or any Cardano-based web application, this SDK provides all the wallet functionality you need.

## ✨ Key Features

- **🌐 Browser-First**: Optimized for web browsers and DApp integration
- **⚡ Modern Build Tools**: Full support for Vite, Rollup, and Webpack
- **🔐 Wallet Management**: Create, restore, and manage Cardano wallets
- **📱 DApp Integration**: Easy integration with browser-based applications
- **🔗 Network Support**: Mainnet, Testnet, and Preprod networks
- **💎 TypeScript**: Complete TypeScript support with type definitions
- **🚀 WASM Powered**: High-performance Cardano operations via WebAssembly
- **🏗️ HD Wallets**: Hierarchical Deterministic wallet implementation (BIP44)

## 🛠️ Build Tool Support

### Vite Integration

Perfect for modern Vite-based projects:

```javascript
// vite.config.js
import { defineConfig } from 'vite'
import wasm from 'vite-plugin-wasm'
import topLevelAwait from 'vite-plugin-top-level-await'

export default defineConfig({
  plugins: [
    wasm(),
    topLevelAwait()
  ],
  optimizeDeps: {
    exclude: ['@emurgo/cardano-serialization-lib-browser']
  }
})
```

### Rollup Integration

Seamless integration with Rollup:

```javascript
// rollup.config.js
import wasm from '@rollup/plugin-wasm'

export default {
  plugins: [
    wasm({
      maxFileSize: 0 // Remove file size limit for WASM
    })
  ],
  external: ['@emurgo/cardano-serialization-lib-browser']
}
```

### Webpack Integration

Compatible with Webpack-based projects:

```javascript
// webpack.config.js
module.exports = {
  experiments: {
    asyncWebAssembly: true,
    topLevelAwait: true
  },
  externals: {
    '@emurgo/cardano-serialization-lib-browser': 'CardanoWasm'
  }
}
```

## 📦 Installation

```bash
npm install @hydrawallet/core
# or
yarn add @hydrawallet/core
# or
pnpm add @hydrawallet/core
```

## 🚀 Quick Start for DApps

### 1. Basic DApp Integration

```typescript
import { AppWallet, NETWORK_ID } from '@hydrawallet/core'

// Initialize wallet for your DApp
class MyDApp {
  private wallet: AppWallet | null = null

  async connectWallet() {
    // Create new wallet or restore existing
    const mnemonic = AppWallet.brew()
    
    this.wallet = new AppWallet({
      networkId: NETWORK_ID.PREPROD, // Use MAINNET for production
      key: {
        type: 'mnemonic',
        words: mnemonic
      }
    })

    console.log('Wallet connected to DApp')
    return this.wallet
  }

  async getWalletAddress() {
    if (!this.wallet) throw new Error('Wallet not connected')
    
    const account = this.wallet.getAccount(0, 0)
    return account.address
  }

  async getWalletBalance() {
    if (!this.wallet) throw new Error('Wallet not connected')
    
    const address = await this.getWalletAddress()
    return await this.wallet.getBalance(address)
  }
}

// Usage in your DApp
const dapp = new MyDApp()
await dapp.connectWallet()
const address = await dapp.getWalletAddress()
const balance = await dapp.getWalletBalance()
```

### 2. React DApp Example

```tsx
import React, { useState, useEffect } from 'react'
import { AppWallet, NETWORK_ID } from '@hydrawallet/core'

function WalletConnector() {
  const [wallet, setWallet] = useState<AppWallet | null>(null)
  const [address, setAddress] = useState<string>('')
  const [balance, setBalance] = useState<string>('0')

  const connectWallet = async () => {
    try {
      // In a real DApp, you might restore from localStorage or user input
      const mnemonic = AppWallet.brew()
      
      const newWallet = new AppWallet({
        networkId: NETWORK_ID.PREPROD,
        key: { type: 'mnemonic', words: mnemonic }
      })

      setWallet(newWallet)
      
      const account = newWallet.getAccount(0, 0)
      setAddress(account.address)
      
      const walletBalance = await newWallet.getBalance(account.address)
      setBalance(walletBalance)
      
    } catch (error) {
      console.error('Failed to connect wallet:', error)
    }
  }

  return (
    <div className="wallet-connector">
      {!wallet ? (
        <button onClick={connectWallet}>
          Connect Wallet
        </button>
      ) : (
        <div>
          <p>Address: {address}</p>
          <p>Balance: {balance} lovelace</p>
        </div>
      )}
    </div>
  )
}
```

### 3. Vue DApp Example

```vue
<template>
  <div class="wallet-connector">
    <button v-if="!wallet" @click="connectWallet">
      Connect Wallet
    </button>
    <div v-else>
      <p>Address: {{ address }}</p>
      <p>Balance: {{ balance }} lovelace</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { AppWallet, NETWORK_ID } from '@hydrawallet/core'

const wallet = ref<AppWallet | null>(null)
const address = ref('')
const balance = ref('0')

const connectWallet = async () => {
  try {
    const mnemonic = AppWallet.brew()
    
    const newWallet = new AppWallet({
      networkId: NETWORK_ID.PREPROD,
      key: { type: 'mnemonic', words: mnemonic }
    })

    wallet.value = newWallet
    
    const account = newWallet.getAccount(0, 0)
    address.value = account.address
    
    balance.value = await newWallet.getBalance(account.address)
    
  } catch (error) {
    console.error('Failed to connect wallet:', error)
  }
}
</script>
```

## 🏗️ DApp Architecture

### Recommended Architecture for Browser DApps

```mermaid
graph TD
    A[Browser DApp] --> B[Wallet Manager]
    B --> C[@hydrawallet/core]
    C --> D[Cardano WASM]
    C --> E[Network Provider]
    
    F[User Interface] --> B
    G[Transaction Builder] --> C
    H[State Management] --> B
    
    E --> I[Blockfrost API]
    E --> J[Custom RPC]
    
    K[Local Storage] --> B
    L[Session Storage] --> B
```

### Core Components for DApps

#### 1. **Wallet Manager**
```typescript
export class WalletManager {
  private wallet: AppWallet | null = null
  private network: NETWORK_ID = NETWORK_ID.PREPROD

  async initialize(mnemonic?: string) {
    const words = mnemonic || this.loadFromStorage() || AppWallet.brew()
    
    this.wallet = new AppWallet({
      networkId: this.network,
      key: { type: 'mnemonic', words }
    })

    this.saveToStorage(words)
    return this.wallet
  }

  private saveToStorage(mnemonic: string) {
    // Encrypt and save to localStorage
    localStorage.setItem('wallet_mnemonic', this.encrypt(mnemonic))
  }

  private loadFromStorage(): string | null {
    const encrypted = localStorage.getItem('wallet_mnemonic')
    return encrypted ? this.decrypt(encrypted) : null
  }
}
```

#### 2. **Transaction Handler**
```typescript
export class TransactionHandler {
  constructor(private wallet: AppWallet) {}

  async sendADA(toAddress: string, amount: string) {
    const account = this.wallet.getAccount(0, 0)
    
    const transaction = await this.wallet.buildTransaction({
      outputs: [{
        address: toAddress,
        amount: amount
      }],
      changeAddress: account.address
    })

    const signedTx = await this.wallet.signTransaction(transaction)
    return await this.wallet.submitTransaction(signedTx)
  }

  async sendNFT(toAddress: string, policyId: string, assetName: string) {
    // NFT transfer logic
  }
}
```

## 🌐 Network Configuration for DApps

### Environment-based Network Selection

```typescript
// config/networks.ts
export const getNetworkConfig = () => {
  const env = process.env.NODE_ENV || 'development'
  
  switch (env) {
    case 'production':
      return {
        networkId: NETWORK_ID.MAINNET,
        blockfrostUrl: 'https://cardano-mainnet.blockfrost.io/api/v0'
      }
    case 'staging':
      return {
        networkId: NETWORK_ID.PREPROD,
        blockfrostUrl: 'https://cardano-preprod.blockfrost.io/api/v0'
      }
    default:
      return {
        networkId: NETWORK_ID.TESTNET,
        blockfrostUrl: 'https://cardano-testnet.blockfrost.io/api/v0'
      }
  }
}

// Usage in DApp
const config = getNetworkConfig()
const wallet = new AppWallet({
  networkId: config.networkId,
  key: { type: 'mnemonic', words: mnemonic }
})
```

## 🔧 Advanced DApp Features

### 1. Multi-Account Support

```typescript
class MultiAccountWallet {
  private wallet: AppWallet

  constructor(wallet: AppWallet) {
    this.wallet = wallet
  }

  getAccounts(count: number = 5) {
    const accounts = []
    for (let i = 0; i < count; i++) {
      accounts.push(this.wallet.getAccount(0, i))
    }
    return accounts
  }

  async getAccountBalances() {
    const accounts = this.getAccounts()
    const balances = await Promise.all(
      accounts.map(account => 
        this.wallet.getBalance(account.address)
      )
    )
    
    return accounts.map((account, index) => ({
      ...account,
      balance: balances[index]
    }))
  }
}
```

### 2. Transaction History

```typescript
class TransactionHistory {
  constructor(private wallet: AppWallet) {}

  async getHistory(address: string, page: number = 1, limit: number = 10) {
    const allTxs = await this.wallet.getTransactionHistory(address)
    
    const start = (page - 1) * limit
    const end = start + limit
    
    return {
      transactions: allTxs.slice(start, end),
      total: allTxs.length,
      page,
      hasMore: end < allTxs.length
    }
  }

  async getTransactionDetails(txHash: string) {
    // Get detailed transaction information
    return await this.wallet.getTransaction(txHash)
  }
}
```

### 3. Asset Management

```typescript
class AssetManager {
  constructor(private wallet: AppWallet) {}

  async getNativeAssets(address: string) {
    const utxos = await this.wallet.getUtxos(address)
    const assets = new Map()

    utxos.forEach(utxo => {
      if (utxo.assets) {
        utxo.assets.forEach(asset => {
          const key = `${asset.policyId}.${asset.assetName}`
          const current = assets.get(key) || 0
          assets.set(key, current + parseInt(asset.quantity))
        })
      }
    })

    return Array.from(assets.entries()).map(([key, quantity]) => {
      const [policyId, assetName] = key.split('.')
      return { policyId, assetName, quantity }
    })
  }

  async sendAsset(toAddress: string, policyId: string, assetName: string, quantity: string) {
    // Send native asset logic
  }
}
```

## 🧪 Testing Your DApp

### Unit Testing

```typescript
// tests/wallet.test.ts
import { AppWallet, NETWORK_ID } from '@hydrawallet/core'

describe('DApp Wallet Integration', () => {
  let wallet: AppWallet

  beforeEach(() => {
    const mnemonic = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'
    wallet = new AppWallet({
      networkId: NETWORK_ID.PREPROD,
      key: { type: 'mnemonic', words: mnemonic }
    })
  })

  test('should create wallet for DApp', () => {
    expect(wallet).toBeDefined()
    
    const account = wallet.getAccount(0, 0)
    expect(account.address).toBeTruthy()
    expect(account.publicKey).toBeTruthy()
  })

  test('should generate multiple accounts', () => {
    const accounts = []
    for (let i = 0; i < 3; i++) {
      accounts.push(wallet.getAccount(0, i))
    }

    expect(accounts).toHaveLength(3)
    expect(new Set(accounts.map(a => a.address)).size).toBe(3)
  })
})
```

### Integration Testing

```typescript
// tests/integration.test.ts
import { WalletManager, TransactionHandler } from '../src'

describe('DApp Integration', () => {
  test('should handle complete wallet flow', async () => {
    const manager = new WalletManager()
    const wallet = await manager.initialize()
    
    const handler = new TransactionHandler(wallet)
    const account = wallet.getAccount(0, 0)
    
    // Test wallet creation
    expect(wallet).toBeDefined()
    expect(account.address).toBeTruthy()
    
    // Test balance retrieval
    const balance = await wallet.getBalance(account.address)
    expect(typeof balance).toBe('string')
  })
})
```

## 📚 Complete API Reference

### AppWallet Class

#### Constructor
```typescript
new AppWallet(config: WalletConfig)

interface WalletConfig {
  networkId: NETWORK_ID
  key: {
    type: 'mnemonic' | 'private_key'
    words?: string
    key?: string
  }
  provider?: NetworkProvider
}
```

#### Static Methods
```typescript
// Generate new mnemonic (12, 15, 18, 21, or 24 words)
AppWallet.brew(wordCount?: number): string

// Validate mnemonic phrase
AppWallet.validateMnemonic(mnemonic: string): boolean

// Validate Cardano address
AppWallet.validateAddress(address: string): boolean

// Convert mnemonic to entropy
AppWallet.mnemonicToEntropy(mnemonic: string): string

// Convert entropy to mnemonic
AppWallet.entropyToMnemonic(entropy: string): string
```

#### Instance Methods
```typescript
// Account management
getAccount(accountIndex: number, addressIndex: number): Account
getPrivateKey(accountIndex: number, addressIndex: number): string

// Transaction operations
buildTransaction(params: TransactionParams): Promise<Transaction>
signTransaction(transaction: Transaction): Promise<SignedTransaction>
submitTransaction(signedTx: SignedTransaction): Promise<string>

// Blockchain queries
getUtxos(address: string): Promise<UTXO[]>
getBalance(address: string): Promise<string>
getTransactionHistory(address: string): Promise<Transaction[]>
getTransaction(txHash: string): Promise<TransactionDetails>

// Asset operations
getAssets(address: string): Promise<Asset[]>
sendAsset(params: AssetTransferParams): Promise<string>
```

### Type Definitions

```typescript
interface Account {
  address: string
  publicKey: string
  accountIndex: number
  addressIndex: number
}

interface UTXO {
  txHash: string
  outputIndex: number
  amount: string
  address: string
  assets?: Asset[]
}

interface Asset {
  policyId: string
  assetName: string
  quantity: string
}

interface TransactionParams {
  outputs: {
    address: string
    amount: string
    assets?: Asset[]
  }[]
  changeAddress: string
  metadata?: any
}

enum NETWORK_ID {
  MAINNET = 1,
  TESTNET = 0,
  PREPROD = 0
}
```

## 🔧 Configuration

### Environment Variables for DApps

```bash
# Network Configuration
VITE_CARDANO_NETWORK=preprod
VITE_BLOCKFROST_PROJECT_ID=your_project_id

# DApp Configuration
VITE_DAPP_NAME="My Cardano DApp"
VITE_DAPP_URL=https://mydapp.com

# Development
VITE_DEBUG_MODE=true
```

### Vite Environment Setup

```typescript
// vite-env.d.ts
interface ImportMetaEnv {
  readonly VITE_CARDANO_NETWORK: string
  readonly VITE_BLOCKFROST_PROJECT_ID: string
  readonly VITE_DAPP_NAME: string
  readonly VITE_DAPP_URL: string
  readonly VITE_DEBUG_MODE: string
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}
```

## 🚀 Deployment for DApps

### Build Configuration

```json
{
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "deploy": "npm run build && npm run deploy:ipfs"
  }
}
```

### IPFS Deployment

```bash
# Build for production
npm run build

# Deploy to IPFS
ipfs add -r dist/

# Or use services like Fleek, Pinata
```

## 🤝 Contributing

### Development Setup

```bash
# Clone repository
git clone https://github.com/aniadev/hydra-wallet-sdk.git
cd hydra-wallet-sdk

# Install dependencies
pnpm install

# Build packages
pnpm build:packages

# Run tests
pnpm --filter @hydrawallet/core test

# Start development
pnpm --filter @hydrawallet/core dev
```

## 📄 License

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

## 🔗 Related Resources

- **Packages**:
  - [`@hydrawallet-sdk/cardano-wasm`](../cardano-wasm/README.md) - Cardano WASM bindings
  - [`@hydrawallet-sdk/transaction`](../hydrawallet-transaction/README.md) - Transaction utilities
- **Documentation**: [Hydra Wallet SDK Docs](https://hydrawallet-sdk.dev)
- **Examples**: [DApp Examples](../../examples/)
- **Community**: [Discord](https://discord.gg/hydrawallet)

---

**@hydrawallet/core** - The essential Cardano wallet SDK for browser DApps with Vite & Rollup support