# @wireio/stake — LIQ Staking SDK

TypeScript SDK for interacting with the **Liquidity Staking System (LIQ)** on **Wire Network**.

- **Today:** Solana (Wire testnet) implementation
- **Next:** Ethereum (shared interface, coming soon)
- **Later:** Sui and additional chains (all conforming to the same `IStakingClient` interface)

---

## Features

- 🔑 Unified **Staker** facade across multiple chains  
- 💸 **Deposit** (stake) funds on supported networks  
- 🧾 **Register** untracked liquid stake tokens (correct &amp; register flow on Solana)  
- 📊 **Portfolio** helper (native / actual / tracked balances)  
- 🧱 Low-level Solana clients:
  - `DepositClient` – builds &amp; submits deposit transactions
  - `DistributionClient` – balance reconciliation &amp; registration (updateUser)
  - `ValidatorLeaderboardClient` – Interact with the validator leaderboard program
- 🧩 Clean, typed program access via `SolanaProgramService`

---

## Installation

The package is published on npm.

```bash
npm install @wireio/stake
```

---

## Getting Started

### 1) Construct a `Staker`

Create the staker with one or more chain configs (only Solana client is active today):

```ts
import { Staker, StakerConfig } from '@wireio/stake';
import { PublicKey as WirePubKey, KeyType } from '@wireio/core';
import { BaseSignerWalletAdapter } from '@solana/wallet-adapter-base';

// Example: Solana (Wire testnet)
const adapter: BaseSignerWalletAdapter = /* your connected wallet adapter */;
const network = {
  chainId: 13371337,               // your Wire testnet chain ID
  name: 'Wire Testnet',
  rpcUrls: ['https://...http', 'wss://...ws'],
  nativeCurrency: { symbol: 'SOL', decimals: 9 }
};

const cfg: StakerConfig = {
  provider: adapter,
  network,
  pubKey: new WirePubKey(KeyType.ED, adapter.publicKey!.toBytes()),
};

const staker = new Staker(cfg /* or [cfg1, cfg2, ...] */, network.chainId);
```

> **Note:** If you pass multiple networks, `Staker` can switch between them via `staker.setChain(chainId)`.

### 2) Get the active client &amp; portfolio

```ts
const client = staker.client;          // current chain’s client (or undefined if not configured)
if (!client) throw new Error('Chain not configured');

const portfolio = await client.getPortfolio();
/**
 * portfolio.native.amount   // wallet SOL in lamports
 * portfolio.actual.amount   // liqSOL in ATA
 * portfolio.tracked.amount  // tracked on distribution program
 */
```

### 3) Deposit

Amounts must be passed in the chain’s **smallest unit** (lamports on Solana, wei on EVM).

```ts
// Human → smallest unit (e.g., 0.5 SOL → 0.5 * 10^9)
const human = 0.5;
const smallest = Math.round(human * Math.pow(10, client.network.nativeCurrency.decimals));

const sig = await client.deposit(smallest);
console.log('Deposit tx:', sig);
```

### 4) Register (Correct &amp; Register on Solana)

Registers any **untracked** liqSOL (if your actual token balance &gt; tracked) and, if necessary,
first corrects other users with positive tracked deltas to free available balance.

```ts
const sig = await client.register();
console.log('Register tx:', sig);
```

---

## Solana-specific Clients (low-level)

You typically don’t need these directly if you use `Staker`, but they’re available.

### `DepositClient`

- `buildDepositTx(user: PublicKey, amount: number)` → `{ transaction, ephemeralStakePubkey }`
- `deposit(user: PublicKey, amount: number)` → confirmed signature

### `DistributionClient`

- `getDistributionState()`, `getUserRecord(user)`
- `getActualBalance(user)`, `getTrackedBalance(user)`
- `updateUser(targetUser)` – register/correct a user
- `buildCorrectRegisterTx({ amount?, preloadCandidates? })` – build a tx that:
  - if your mismatch &lt; 0 → just **correct self**
  - else → **free available** by updating top candidates, then **register self**

---

## Core Types

```ts
import { BaseSignerWalletAdapter } from '@solana/wallet-adapter-base';
import { PublicKey as SolPubKey } from '@solana/web3.js';
import { ExternalNetwork, PublicKey } from '@wireio/core';
import { ethers } from 'ethers';

export interface IStakingClient {
  pubKey: PublicKey;
  network: ExternalNetwork;

  /** Amount is in the chain's smallest unit (lamports/wei, etc.) */
  deposit(amount: number): Promise<string>;

  /** Register any untracked LIQ staked tokens */
  register(): Promise<string>;

  /** Fetch the portfolio for the LIQ stake user */
  getPortfolio(): Promise<Portfolio>;
}

export type StakerConfig = {
  network: ExternalNetwork;
  provider: BaseSignerWalletAdapter | ethers.providers.Web3Provider;
  pubKey: PublicKey;
}

export interface Portfolio {
  /** Native SOL balance on chain */
  native: BalanceView;
  /** Actual liquid SOL balance from ATA */
  actual: BalanceView;
  /** Tracked liquid SOL balance from distribution program */
  tracked: BalanceView;
  /** Extra PDAs and account addresses */
  extras?: Record&lt;string, any&gt;;
}

export type BalanceView = {
  amount: bigint;   // raw on-chain integer value
  decimals: number; // number of decimal places
  symbol?: string;  // optional token symbol identifier
  ata?: SolPubKey;  // associated token account address
};
```

---

## Multi-chain Notes &amp; Roadmap

- **Ethereum** client is planned (will implement `IStakingClient` with the same methods).
- **Sui** (and other chains) to follow the same interface for a unified developer experience.
- Your app can rely on the `Staker` facade today and gain new chains later without API changes.

---

## Error Handling

- All public methods throw on failure. Wrap calls with `try/catch` and surface errors to your users.
- For Solana, failed transactions carry logs; some SDK methods surface logs in thrown errors.

---

## Development

Requires:

- **Node.js** (LTS recommended)
- **npm**
- **Make** (optional, for convenience targets)

Common tasks:

```bash
# Install deps
npm ci

# Build
npm run prepare
```

---

## Testnet Deployment 11/19/25
```
RPC URL: https://sol.gitgo.app/
Deploying cluster: http://solana-genesis:8899
Upgrade authority: ./wallets/deploymentWallet/universalDeploymentWallet.json
Deploying program "liq_sol_token"...
Program path: /app/program/target/deploy/liq_sol_token.so...
Program Id: FsRiJLqerifBSpZjzdWxSyJ3sQmJ3ScFwHv4VRi9ghVT

Signature: 26JPXjiNXBzPk7p8PQx8y1bQog1baWCjyRqWYyQKNxEpK9reAHpeNwcw9Sh7dAyaAhyuosQueE4XrnTZibXdwx99

Deploying program "validator_leaderboard"...
Program path: /app/program/target/deploy/validator_leaderboard.so...
Program Id: 9SW7GqRTzEc5KjSnXXTqvojcyCvzHjn8J4xdBeS91Gbq

Signature: 5nobXLXnnMD9MmPjcJ5xbmawV4wDXxCYEBR2CwoBkvEQ4iLAVQCpzZWw7Pgb7eGwk6bu88VvpC2occCJh2EYajfJ

Deploying program "liqsol_core"...
Program path: /app/program/target/deploy/liqsol_core.so...
Program Id: 8zBGapo9WvnGskgXyKmgNgLACimELqJzAPEHyShWg5Dj

Signature: 2wakzKzaxkRLC4nMw3t8pCSL4PfG32EoSKZXo6og8mAgVq54twWUhqG5JLAQejvsqGgEBaZ7zwWj9tvsijt8vwbi

Deploy success
🪙 Initializing token mint...
🚀 Initializing Liquid SOL Token...

📍 Mint Authority PDA: 3XwUD4Sy6Aua1ceC8yEHTWk16vMmmWAdFMfJpzwvwveD
🪙 Deterministic Mint Address: Empuao5KEK7zq3rFz8Q8fVSmNwhbkrqkNctdfZKdY9b2
🔗 Network: http://solana-genesis:8899
👤 Payer: Ebar1nLiEpHEFH4DmYasqJHMm3fn6g1jJY3WBfwc6GsD
📝 Token Name: Liquid Staked SOL
🏷️  Token Symbol: liqSOL

🏦 Receiver ATA: 3B9dtsRGYvB1aVQYR8yHfzbbECgohHkH7U67v6gPJ1HQ
🔄 Sending mint creation transaction...
✅ Liquid SOL Token mint created! Transaction: 5fgNuuNorhBcvjp28AQhHK1jkSG6fRCPBbxsHbEnB3CyuRYPRTGybH2gjLhGdb7kD8CUohibUzd1wnPLUDUauret

📊 Created Mint Information:
   Mint Address: Empuao5KEK7zq3rFz8Q8fVSmNwhbkrqkNctdfZKdY9b2
   Mint Authority: 3XwUD4Sy6Aua1ceC8yEHTWk16vMmmWAdFMfJpzwvwveD
   Token Name: Liquid Staked SOL
   Token Symbol: liqSOL
   Decimals: 9
   Receiver ATA: 3B9dtsRGYvB1aVQYR8yHfzbbECgohHkH7U67v6gPJ1HQ

🎉 Liquid SOL Token is ready to use!
   Mint Address: Empuao5KEK7zq3rFz8Q8fVSmNwhbkrqkNctdfZKdY9b2
   Program ID: FsRiJLqerifBSpZjzdWxSyJ3sQmJ3ScFwHv4VRi9ghVT
   Mint Authority PDA: 3XwUD4Sy6Aua1ceC8yEHTWk16vMmmWAdFMfJpzwvwveD
▶ Initializing Distribution Program...
  Distribution Program: 8zBGapo9WvnGskgXyKmgNgLACimELqJzAPEHyShWg5Dj
  Wallet: Ebar1nLiEpHEFH4DmYasqJHMm3fn6g1jJY3WBfwc6GsD
  LiqSOL Mint: Empuao5KEK7zq3rFz8Q8fVSmNwhbkrqkNctdfZKdY9b2
  Distribution State PDA: BHMC9S1J8jy7nitVt4CHGeRHVK8kh9jpm4xKhf4cJWgn
```

## Autodocs

- **API Docs:** <https://Wire-Network.github.io/sdk-stake/>
- **Coverage:** coming soon

---

## License

MIT – see [LICENSE](./LICENSE).
