npm package: @skacaniku/libyachain-sdk
Description: Official JavaScript/TypeScript SDK for LibyaChain blockchain - Three-currency system (LYDD, LYDC, UCBL) with comprehensive blockchain operations
Author: LibyaChain Team
Latest version: 0.1.0

# @libyachain/sdk

Official JavaScript/TypeScript SDK for LibyaChain blockchain - Libya's three-currency digital ecosystem.

[![npm version](https://img.shields.io/npm/v/@libyachain/sdk.svg)](https://www.npmjs.com/package/@libyachain/sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.3-blue)](https://www.typescriptlang.org/)

## Features

- 🚀 **Complete TypeScript Support** - Full type definitions and IntelliSense
- 💰 **Three-Currency System** - LYDD (stablecoin), LYDC (cryptocurrency), UCBL (CBDC)
- 🔍 **Comprehensive Queries** - Blocks, transactions, accounts, validators, governance
- 🌐 **Universal** - Works in browser and Node.js
- ⚡ **Optimized** - Request caching, retry logic, <100KB bundle size
- 📚 **Well Documented** - 50+ code examples and complete API reference

## Installation

```bash
npm install @libyachain/sdk

# or
yarn add @libyachain/sdk

# or
pnpm add @libyachain/sdk
```

### Peer Dependencies

```bash
npm install @cosmjs/amino @cosmjs/proto-signing @cosmjs/stargate @cosmjs/tendermint-rpc @cosmjs/encoding
```

## Quick Start

```typescript
import { LibyaChainClient, DENOMS } from '@libyachain/sdk'

// Initialize client
const client = new LibyaChainClient({
  rpcUrl: 'https://rpc.libyachain.net',
  restUrl: 'https://api.libyachain.net',
  chainId: 'libyachain-1'
})

// Get network status
const status = await client.getStatus()
console.log('Chain ID:', status.chainId)
console.log('Block height:', status.blockHeight)

// Query account balance
const balance = await client.getBalance('libya1...', DENOMS.LYDC)
console.log('LYDC balance:', balance.amount)

// Get all three currency balances
const balances = await client.getThreeCurrencyBalances('libya1...')
console.log('LYDD:', balances.LYDD)
console.log('LYDC:', balances.LYDC)
console.log('UCBL:', balances.UCBL)

// Get latest block
const block = await client.getBlock()
console.log('Latest height:', block.header.height)

// Get transaction
const tx = await client.getTransaction('A1B2C3...')
console.log('Gas used:', tx.tx_result.gas_used)
```

## LibyaChain Three-Currency System

LibyaChain supports three currencies designed for Libya's digital economy:

### LYDD - Libyan Digital Dinar (CBDC Stablecoin)
- **Purpose**: General-purpose digital currency for everyday transactions
- **Type**: CBDC stablecoin
- **Denomination**: `ulydd` (1 LYDD = 1,000,000 ulydd)

### LYDC - Libyan Digital Currency (Cryptocurrency)
- **Purpose**: Appreciating value asset, base for tokens and dApps
- **Type**: Cryptocurrency backed by oil, gas, and compute resources
- **Denomination**: `ulydc` (1 LYDC = 1,000,000 ulydc)

### UCBL - Central Bank of Libya CBDC
- **Purpose**: Banking sector and institutional transactions
- **Type**: Central bank digital currency
- **Denomination**: `uucbl` (1 UCBL = 1,000,000 uucbl)

All three currencies are freely interchangeable on the blockchain.

## Usage Examples

### Query Operations

```typescript
// Get account info
const account = await client.getAccount('libya1...')
console.log('Sequence:', account.sequence)

// Get specific currency balance
const lydcBalance = await client.getBalance('libya1...', DENOMS.LYDC)
const lyddBalance = await client.getBalance('libya1...', DENOMS.LYDD)
const ucblBalance = await client.getBalance('libya1...', DENOMS.UCBL)

// Get all balances
const allBalances = await client.getAllBalances('libya1...')

// Get total supply
const supply = await client.getSupply(DENOMS.LYDC)
console.log('LYDC supply:', supply)

// Get all three supplies
const supplies = await client.getThreeCurrencySupplies()

// Get block by height
const block = await client.getBlock(12345)

// Search transactions
const txs = await client.searchTransactions("message.sender='libya1...'")

// Get validators
const validators = await client.getValidators()

// Get governance proposals
const proposals = await client.getProposals()
```

### Conversion Rates

```typescript
// Get conversion rate between currencies
const rate = await client.getConversionRate(DENOMS.LYDC, DENOMS.LYDD)
console.log('1 LYDC =', rate.rate, 'LYDD')
```

### Wallet Operations

```typescript
import { WalletFactory, DENOMS } from '@libyachain/sdk'

// Connect to Keplr wallet (browser)
const wallet = await WalletFactory.connect('keplr', 'libyachain-1')
const accounts = await wallet.getAccounts()
console.log('Connected:', accounts[0].address)

// Create wallet from mnemonic (browser or Node.js)
const wallet = await WalletFactory.fromMnemonic(
  'word1 word2 word3 ... word24',
  { prefix: 'libya' }
)

// Create wallet from private key
const wallet = await WalletFactory.fromPrivateKey(
  'a1b2c3d4...',
  { prefix: 'libya' }
)

// Sign arbitrary message
const signature = await wallet.signArbitrary(
  accounts[0].address,
  'Hello LibyaChain!'
)
```

### Transaction Operations

The SDK provides three ways to send transactions:

#### 1. High-Level API (Recommended)

```typescript
import { createTxHelper } from '@libyachain/sdk'

const txHelper = createTxHelper(client, wallet)

// Send tokens
const result = await txHelper.send({
  to: 'libya1abc...',
  amount: '1000000',
  denom: 'ulydc',
  memo: 'Payment for services'
})
console.log('TX hash:', result.hash)
console.log('Gas used:', result.gasUsed)

// Delegate to validator
await txHelper.delegate({
  validatorAddress: 'libyavaloper1...',
  amount: '5000000',  // 5 LYDC
  denom: 'ulydc'
})

// Withdraw all staking rewards
await txHelper.withdrawAllRewards()

// Vote on governance proposal
await txHelper.vote({
  proposalId: 1,
  option: 'yes'
})

// Convert between currencies
await txHelper.convert({
  from: 'ulydc',
  to: 'ulydd',
  amount: '1000000'
})

// Mint tokens (requires authorization)
await txHelper.mint({
  denom: 'ulydc',
  amount: '10000000',
  recipient: 'libya1...'
})
```

#### 2. Signing Client API

```typescript
import { createSigningClient } from '@libyachain/sdk'

const signingClient = await createSigningClient(client, wallet)
const account = await wallet.getAccount()

// Send tokens
const result = await signingClient.sendTokens(
  account.address,
  'libya1to...',
  [{ denom: 'ulydc', amount: '1000000' }],
  'auto',
  'Payment memo'
)

// Delegate tokens
await signingClient.delegateTokens(
  account.address,
  'libyavaloper1...',
  { denom: 'ulydc', amount: '5000000' },
  'auto'
)

// Withdraw rewards
await signingClient.withdrawRewards(
  account.address,
  'libyavaloper1...',
  'auto'
)
```

#### 3. Transaction Builder API (Advanced)

```typescript
import { TxBuilder, MessageBuilder } from '@libyachain/sdk'

const builder = new TxBuilder(client, wallet)

// Build transaction with multiple messages
const result = await builder
  .addMessage(MessageBuilder.send({
    fromAddress: 'libya1from...',
    toAddress: 'libya1to...',
    amount: [{ denom: 'ulydc', amount: '1000000' }]
  }))
  .addMessage(MessageBuilder.delegate({
    delegatorAddress: 'libya1from...',
    validatorAddress: 'libyavaloper1...',
    amount: { denom: 'ulydc', amount: '5000000' }
  }))
  .setMemo('Multi-operation transaction')
  .setFee('auto')
  .setGasAdjustment(1.5)
  .signAndBroadcast()

console.log('TX hash:', result.hash)
```

### LibyaChain-Specific Operations

```typescript
// Mint tokens (requires proper authorization)
await txHelper.mint({
  denom: 'ulydc',
  amount: '1000000',
  recipient: 'libya1...'
})

// Burn tokens
await txHelper.burn({
  denom: 'ulydc',
  amount: '500000'
})

// Convert between currencies
await txHelper.convert({
  from: 'ulydc',
  to: 'ulydd',
  amount: '1000000'
})

// Get conversion rate first
const rate = await client.getConversionRate('ulydc', 'ulydd')
console.log('Rate:', rate.rate)

// Get mint/burn statistics
const stats = await client.getMintStats()
console.log('Total minted:', stats.totalMinted)
console.log('Total burned:', stats.totalBurned)
```

### Advanced Usage

```typescript
// Configure custom timeout and caching
const client = new LibyaChainClient({
  rpcUrl: 'https://rpc.libyachain.net',
  restUrl: 'https://api.libyachain.net',
  chainId: 'libyachain-1',
  timeout: 60000, // 60 seconds
  cache: true,
  cacheTTL: 120000, // 2 minutes
  retries: true,
  maxRetries: 5,
  gasPrice: '0.025ulydc',
  gasAdjustment: 1.5
})

// Direct RPC access
const rpcStatus = await client.rpc.status()

// Direct REST access
const validators = await client.rest.stakingValidators()

// Clear cache
client.clearCache()

// Get client info
const info = client.getInfo()
```

## API Reference

### LibyaChainClient

Main client class providing unified interface to LibyaChain blockchain.

#### Constructor

```typescript
new LibyaChainClient(config: LibyaChainClientConfig)
```

#### Network Methods

- `getStatus()` - Get network status and info
- `isHealthy()` - Check if node is healthy
- `getBlockHeight()` - Get current block height

#### Block Methods

- `getBlock(height?)` - Get block by height
- `getBlocks(minHeight, maxHeight)` - Get multiple blocks

#### Transaction Methods

- `getTransaction(hash)` - Get transaction by hash
- `searchTransactions(query, options?)` - Search transactions
- `getTransactionsByAddress(address)` - Get transactions for account

#### Account & Balance Methods

- `getAccount(address)` - Get account information
- `getBalance(address, denom)` - Get balance for currency
- `getAllBalances(address)` - Get all balances
- `getThreeCurrencyBalances(address)` - Get LYDD, LYDC, UCBL balances

#### Supply Methods

- `getSupply(denom)` - Get total supply
- `getThreeCurrencySupplies()` - Get all three supplies

#### Staking Methods

- `getValidators(status?)` - Get validators
- `getValidator(validatorAddr)` - Get validator by address
- `getDelegations(delegatorAddr)` - Get delegations
- `getStakingPool()` - Get staking pool info

#### Governance Methods

- `getProposals(status?)` - Get governance proposals
- `getProposal(proposalId)` - Get proposal by ID
- `getVote(proposalId, voter)` - Get vote

#### LibyaChain Custom Methods

- `getLibyaChainParams()` - Get module parameters
- `getConversionRate(from, to)` - Get currency conversion rate
- `getMintStats()` - Get minting/burning statistics
- `getGovernanceMode()` - Get governance mode status

#### Utility Methods

- `clearCache()` - Clear query cache
- `getInfo()` - Get client info

### Constants

```typescript
// Currency denominations
DENOMS.LYDD  // 'ulydd' - Libyan Digital Dinar
DENOMS.LYDC  // 'ulydc' - Libyan Digital Currency
DENOMS.UCBL  // 'uucbl' - Central Bank of Libya CBDC

// SDK version
SDK_VERSION  // '0.1.0'

// Default configuration
DEFAULT_CONFIG  // Default client settings
```

## TypeScript Support

The SDK is written in TypeScript with full type definitions:

```typescript
import type {
  LibyaChainClientConfig,
  NetworkInfo,
  Block,
  Transaction,
  Account,
  Balance,
  Coin
} from '@libyachain/sdk'
```

## Browser Support

The SDK works in modern browsers:

```html
<script type="module">
  import { LibyaChainClient, DENOMS } from 'https://unpkg.com/@libyachain/sdk/dist/esm/index.js'

  const client = new LibyaChainClient({
    rpcUrl: 'https://rpc.libyachain.net',
    restUrl: 'https://api.libyachain.net',
    chainId: 'libyachain-1'
  })

  const balance = await client.getBalance('libya1...', DENOMS.LYDC)
  console.log('Balance:', balance.amount)
</script>
```

## Network Endpoints

### Mainnet
- **RPC**: `https://rpc.libyachain.net`
- **REST**: `https://api.libyachain.net`
- **Chain ID**: `libyachain-1`

### Testnet
- **RPC**: `https://rpc.testnet.libyachain.net`
- **REST**: `https://api.testnet.libyachain.net`
- **Chain ID**: `libyachain-testnet-1`

### Local Development
- **RPC**: `http://localhost:26657`
- **REST**: `http://localhost:1317`
- **Chain ID**: `libyachain-local`

## Documentation

- [Getting Started Guide](https://docs.libyachain.net/sdk/getting-started)
- [API Reference](https://docs.libyachain.net/sdk/api)
- [Examples](https://docs.libyachain.net/sdk/examples)
- [Migration Guide](https://docs.libyachain.net/sdk/migration)

## Examples

See [docs/examples](./docs/examples) for 50+ code examples covering:
- Basic queries
- Account operations
- Transaction handling
- Staking operations
- Governance participation
- Currency conversion
- Advanced patterns

## Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](../../CONTRIBUTING.md) for guidelines.

## License

MIT © LibyaChain Team

## Support

- **Documentation**: https://docs.libyachain.net
- **Issues**: https://github.com/libyachain/sdk/issues
- **Discord**: https://discord.gg/libyachain
- **Twitter**: https://twitter.com/libyachain

## Changelog

See [CHANGELOG.md](./CHANGELOG.md) for version history.