# react-native-rgb

A React Native Turbo Module for the Bitcoin RGB Protocol. This library provides a high-level TypeScript API to manage RGB assets, keys, and wallets. It wraps the native [rgb-lib-swift](https://github.com/RGB-Tools/rgb-lib-swift) and [rgb-lib-kotlin](https://github.com/RGB-Tools/rgb-lib-kotlin) libraries.

## Table of Contents

- [Installation](#installation)
- [Quick Start](#quick-start)
- [API Reference](#api-reference)
- [Running the Example](#running-the-example)
- [Project Structure](#project-structure)
- [Troubleshooting](#troubleshooting)

## Features

- **Full Asset Support**: Handle NIA, UDA, CFA, and IFA.
- **Key Management**: BIP39 mnemonic support for key generation and restoration.
- **Performance**: Built as a Turbo Module for efficient native communication.
- **Type Safety**: Written in TypeScript.

## Installation

```bash
yarn add react-native-rgb
```

### iOS Setup

The native Rust framework (`rgb_libFFI.xcframework`) is automatically downloaded during `postinstall`. 

```bash
cd ios && pod install
```

### Android Setup

The library requires `minSdkVersion` 24. Make sure your `android/build.gradle` includes JitPack if necessary for transitive dependencies:

```gradle
allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}
```

## Quick Start

### 1. Setup Keys
```typescript
import { generateKeys, BitcoinNetwork } from 'react-native-rgb';

const keys = await generateKeys(BitcoinNetwork.TESTNET4);
```

### 2. Initialize Wallet
```typescript
import { Wallet } from 'react-native-rgb';

const wallet = new Wallet(keys, { network: BitcoinNetwork.TESTNET4 });
```

### 3. Basic Operations
```typescript
// Bring the wallet online
await wallet.goOnline('ssl://electrum.iriswallet.com:50053');

// Issue a new NIA asset
const asset = await wallet.issueAssetNia('TICKER', 'Name', 2, [1000]);

// Check your balance
const btcBalance = await wallet.getBtcBalance();
```

## Error Handling

The library uses structured error handling with error codes for better error management. All methods that can fail will throw an `RgbError` with a specific error code.

### Using RgbError

```typescript
import { Wallet, RgbError, RgbErrorCode } from 'react-native-rgb';

try {
  await wallet.goOnline('ssl://indexer.example.com:50053');
} catch (error) {
  // Convert React Native error to RgbError
  const rgbError = RgbError.fromReactNativeError(error);
  
  if (rgbError instanceof RgbError) {
    // Handle specific error codes
    switch (rgbError.code) {
      case RgbErrorCode.GO_ONLINE_ERROR:
        console.error('Failed to connect:', rgbError.message);
        // Handle connection error
        break;
      case RgbErrorCode.INITIALIZE_WALLET_ERROR:
        console.error('Wallet initialization failed:', rgbError.message);
        // Handle initialization error
        break;
      default:
        console.error(`Error [${rgbError.code}]:`, rgbError.message);
    }
  } else {
    // Handle generic errors
    console.error('Unexpected error:', error);
  }
}
```


## API Reference

### Keys & Wallet Setup
- `generateKeys(network)` / `restoreKeys(network, mnemonic)`
- `new Wallet(keys, options)`: Options include `network`, `maxAllocationsPerUtxo`, and `vanillaKeychain`.

### Wallet
- `goOnline(indexerUrl, skipSync?)`: Connect to infrastructure.
- `sync()`: Manually trigger a blockchain sync.
- `close()`: Shut down the wallet and free native resources.

### Balance & Assets
- `getBtcBalance()`: Returns `{ vanilla: Balance, colored: Balance }`.
- `getAddress()`: Returns the funding address.
- `getAssetBalance(assetId)` / `getAssetMetadata(assetId)`
- `listAssets(filter[])`: List assets by schema (NIA, UDA, CFA, IFA).

### Asset Issuance
- `issueAssetNia(ticker, name, precision, amounts)`
- `issueAssetCfa(name, details, precision, amounts, filePath?)`
- `issueAssetUda(ticker, name, details, precision, mediaPath, attachments[])`
- `issueAssetIfa(ticker, name, precision, amounts, ...)`

### Sending & Receiving
- `blindReceive(assetId, amount, duration, endpoints, confirmations)`: Get a blinded invoice.
- `witnessReceive(...)`: Get a witness invoice.
- `send(recipientMap, donation, feeRate, confirmations)`: Send RGB assets.
- `sendBtc(address, amount, feeRate)`: Send regular Bitcoin.


## Project Structure

- `src/`: TypeScript source (Wallet class, Interfaces).
- `android/` & `ios/`: Native Turbo Module implementations.
- `scripts/`: Build and setup scripts.
- `example/`: Sample React Native app.

## Running the Example

1. `yarn install` (root)
2. `yarn prepare` (build library)
3. `cd example && yarn install`
4. `cd ios && pod install`
5. `yarn ios` or `yarn android`

## Troubleshooting

- **iOS framework**: If a postinstall fails, run `node scripts/download-rgb-lib-ios.js` manually.
- **Linker issues**: Ensure you use the `.xcworkspace` on iOS.
- **Android SDK**: Must have `minSdkVersion >= 24`.

## License

MIT
