npm package: @iqlabsteam/iqdatabase
Description: This library (IQDB SDK) allows you to interact with the IQ Database program on Solana to: - Initialize a Root & TxRef PDA. - Create and manage metadata-driven tables on chain. - Insert rows into those tables (as JSON). - Read and pretty-print table data b
Latest version: 1.0.3



# IQDB SDK — on chain Table Writer & Reader

This library (IQDB SDK) allows you to interact with the IQ Database program on Solana to:
- Initialize a Root & TxRef PDA.
- Create and manage metadata-driven tables on chain.
- Insert rows into those tables (as JSON).
- Read and pretty-print table data by scanning on chain transactions.
- Safely manage extension tables with parent dependencies.

The SDK exposes a high-level API through `src/index.ts` for developers to interact programmatically.

---

## 0) Prerequisites

- **Node.js** ≥ 18
- `ts-node` / `typescript`
- Solana libraries:
  - `@coral-xyz/anchor`
  - `@solana/web3.js`
- A deployed instance of the IQDB program with a compatible **IDL** located in `target/idl/iq_database.json`.
- Solana configuration (via CLI):
  ```bash
  solana config set --url (your mainnet url)
  solana config set --keypair ~/.config/solana/id.json
  ```
- (Optional but highly recommended)
- 
- **Set your RPC endpoint**:
  1. Create a `.env` file in the project root if it does not already exist.
  2. Add `NETWORK_URL=https://your-rpc-endpoint` (replace the value with your own RPC URL / API key).
  3. The SDK reads `process.env.NETWORK_URL`, so this variable overrides the default RPC used by `src/configs.ts`.

---

## 1) Installation

### Install dependencies:
Use `npm`, `pnpm`, or `yarn`.
```
npm i @solana/web3.js @coral-xyz/anchor @noble/hashes bs58
npm i @iqlabsteam/iqdatabase

```

s
### Develop with the SDK:
The SDK is accessed through in `src/index.ts`.

---

## 2) Quick Start & Examples

### 2.1 Core Concepts
- **Root**: A PDA for global table management.
- **Table**: Metadata stored on chain, represented in rows/columns format.
- **TxRef**: Tracks transaction references for on chain table rows.

---

### 2.2 Code Example (High-Level API)

#### Programmatic Usage:
```
typescript
import { createIQDB } from  "@iqlabsteam/iqdb";

const iqdb = createIQDB(); // Initialize IQDB SDK.
const signer = "Your Connected Wallet"; // Make sure Anchor wallet config is loaded.

async function main() {
    // 1. Ensure the Root PDA exists (initialize program if not).
    await iqdb.ensureRoot(signer);

    // 2. Create a Table:
    await iqdb.createTable("YourTableName", ["name", "price"], { idColumn: "name", extKeys: [] });

    // 3. Insert JSON data into rows:
    await iqdb.writeRow("YourTableName", { name: "Laptop", price: 1200 });

    // 4. Read back rows from the table:
    const rows = await iqdb.readRowsByTable("YourTableName");

    console.log("Rows from Table:", rows);

    // 5. Optional: Manage extension tables (e.g., for expiration data):
    await iqdb.createExtTable(
        "YourTableName",
        "Laptop",
        "expire",
        ["expireAt", "manufacturer"],
        "expireAt"
    );

    console.log(" Flow successfully completed.");
}

main().catch((err) => {
    console.error("Error:", err.message);
    process.exit(1);
});
```
---

### 2.3 Interactive CLI Flow
If you're using the SDK in an interactive environment, such as a terminal UI:
- Prompt the user to select tables and rows.
- Use `ensureRoot` to initialize tables if necessary.
- Extend the existing SDK flow with custom interactive prompts.

---

## 3) SDK API Overview

### Writers:
API methods for creating and working with tables:

1. **ensureRoot**
   Ensures the `Root` PDA is initialized.
   ```typescript
   iqdb.ensureRoot(signer);
   ```

2. **createTable**
   Creates a new table with specified columns.
   ```typescript
   iqdb.createTable("TableName", ["column1", "column2"], {
       idColumn: "column1",
       extKeys: []
   });
   ```

3. **writeRow**
   Inserts JSON-encoded row data into a table.
   ```typescript
   iqdb.writeRow("TableName", { column1: "value1", column2: 12345 });
   ```

4. **pushInstruction**
   Pushes a database instruction (update/delete).
   ```typescript
   iqdb.pushInstruction("TableName", txId, { key: "new value" });
   ```

5. **createExtTable**
   Creates an extension table for child-table data.
   ```typescript
   iqdb.createExtTable("ParentTable", "RowId", "Key", ["column1", "column2"], "column1");
   ```

---

### Readers:
API methods for reading on chain table metadata and rows:

1. **readRowsByTable**
   Fetch rows for a specific table.
   ```typescript
   const rows = await iqdb.readRowsByTable("TableName");
   ```

2. **listRootTables**
   Lists all tables present in the `Root` PDA.
   ```typescript
   const tables = await iqdb.listRootTables();
   ```

3. **readTableMeta**
   Reads metadata such as columns, ID columns, etc., for a table.
   ```typescript
   const meta = await iqdb.readTableMeta("TableName");
   ```

4. **searchTableByName**
   Queries a table by its name and retrieves matching information.
   ```typescript
   const tableData = await iqdb.searchTableByName("YourTableName");
   ```

---

## 4) Troubleshooting

- **Environment Variable Errors**: Ensure `ANCHOR_WALLET` and Solana CLI configs are set.
- **PDA Compatibility Issues**: Cross-check the seeds and program ID in `configs.ts`.
- **Decode Failures**:
    - Enable “safe decode” mode: Automatically skips broken table data from bad offsets.

---

## 5) Advanced Topics (Optional)

1. **Internal API (Advanced)**
   For highly customized logic:
   ```javascript
   import {
       createTable, // Full flex builder for tables.
       listRootTables,
       ensureRoot,
   } from  "@iqlabsteam/iqdb";
   ```

2. **Extension Table Flows**
   Detailed flow for extending parent rows with child metadata.
---

## 6) Project Structure (v2 SDK)
```

src/
  index.ts           # SDK entry point and public API.
  functions/writers/ # Public table/row creation/update handlers.
  functions/readers/ # Public table metadata and row reading handlers.
  provider/          # PDA + seed utilities (shared across SDK).
  utils/             # Common helpers (JSON encode, Borsh decode, etc.).
  target/idl/...     # on chain program generated IDL.
```
---
```
```
## 6) Feedback Notes For README Evolution
The updated README.md is crafted to reflect the latest structure and API of your SDK as defined in the `index.ts`. It's focused on correct usage, examples, and flows tied directly to the SDK's features.
# IQDBSDKTEST