npm package: @hermetica/transactions
Description: Hermetica Transactions Library
Latest version: 0.3.1
Deprecated: This package has been renamed to @hermetica/sdk

# @hermetica/transactions

A TypeScript library for creating and managing stake, unstake, and claim transactions on the Hermetica protocol. This library supports both Stacks and Bitcoin blockchains.

## Features

- Generate transaction hex for staking, unstaking, and claiming rewards
- Support for both Stacks and Bitcoin blockchains
- USDh/sUSDh supported on Stacks and Bitcoin; hBTC supported on Stacks only
- Claims data retrieval for both chains
- sUSDh and hBTC rate, price, and APY information retrieval
- Configurable API host and affiliate code support

## Installation

```bash
npm install @hermetica/transactions
```

## Configuration

The library can be configured with the following options:

```typescript
const config = {
  // Optional: Custom API host (defaults to https://app.hermetica.fi)
  HOST: string;
  // Optional: Your Hermetica affiliate code
  AFFILIATE_CODE: string;
};
```

## Usage

### Initialization

```typescript
import { TransactionBuilder } from '@hermetica/transactions';

const transactionBuilder = new TransactionBuilder({
  HOST: 'CUSTOM_HERMETICA_API', // optional
  AFFILIATE_CODE: 'YOUR_AFFILIATE_CODE' // optional
});
```

### Generating Transactions

#### For Stacks (USDh or hBTC)

```typescript
const stakeResult = await transactionBuilder.generateTransactionHex({
  amount: '94.2', // Amount to stake
  type: 'stake', // 'stake' | 'unstake' | 'withdraw'
  chain: 'stacks',
  protocol: 'USDh', // 'USDh' | 'hBTC'
  public_key: '923xcv2...' // Your Stacks public key
});

// Response format
{
  status: 'success' | 'failed';
  message: string;
  data: {
    tx_hex: string; // The transaction hex to be signed
    type: 'stake' | 'unstake' | 'withdraw';
    chain: 'stacks';
  }
}
```

#### Multisig Transactions (Stacks only)

For multisig wallets (e.g., Asigna), pass comma-separated public keys and the signing threshold:

```typescript
const stakeResult = await transactionBuilder.generateTransactionHex({
  amount: '100',
  type: 'stake',
  chain: 'stacks',
  protocol: 'USDh',
  public_key: 'pubKey1,pubKey2,pubKey3', // Comma-separated signer public keys
  threshold: 2 // 2-of-3 multisig (required signatures)
});
```

| Parameter    | Type     | Required | Description                                                                                      |
| ------------ | -------- | -------- | ------------------------------------------------------------------------------------------------ |
| `public_key` | `string` | Yes      | Single key for standard wallets, or comma-separated keys for multisig                            |
| `threshold`  | `number` | No       | Number of required signatures. Defaults to 1. Only used when `public_key` contains multiple keys |

> **Note:** Multisig is only supported on **Stacks**. Bitcoin USDh/sUSDh transactions do not support multisig.

#### For Bitcoin (USDh only)

```typescript
const stakeResult = await transactionBuilder.generateTransactionHex({
  amount: '94.2', // Amount to stake in BTC
  type: 'stake', // 'stake' | 'unstake' | 'withdraw'
  chain: 'bitcoin',
  protocol: 'USDh', // Only USDh is supported on Bitcoin
  addresses: {
    payment_btc_address: {
      address: '38byQL...', // Your Bitcoin payment address
      pubKey: '0000231...', // Public key for the payment address
      type: 'p2sh' // Address type: p2wpkh, p2sh, etc.
    },
    taproot_btc_address: {
      address: 'bc1pkd...', // Your Taproot address
      pubKey: '023xc0...', // Public key for the Taproot address
      type: 'p2tr'
    }
  },
  satvBFee: 5 // Optional: Fee rate in sat/vB (defaults to highest from mempool)
});

// Response format
{
  status: 'success' | 'failed';
  message: string;
  data: {
    tx_hex: string; // The transaction hex to be signed
    type: 'stake' | 'unstake' | 'withdraw';
    chain: 'bitcoin';
    inputs_to_sign?: {
      [address: string]: number[]; // Input indices that need to be signed
    }
  }
}
```

### Retrieving Claims Data

#### For Stacks (USDh or hBTC)

```typescript
const withdrawalsData = await transactionBuilder.getWithdrawalsData({
  chain: 'stacks',
  protocol: 'USDh', // 'USDh' | 'hBTC'
  public_key: '923xcv2...' // Your Stacks public key
});

// Response formats
{
  total_to_claim: number; // Total amount of tokens currently available to claim
  next_amount_to_unlock: number; // Amount of tokens that will be unlocked in the next unlock period
  next_claim_timestamp: number; // The timestamp in ms at which the next amount will become claimable
  last_claim_timestamp: number; // The timestamp in ms at which the last unstake request will be fully unlocked
}
```

#### For Bitcoin (USDh only)

```typescript
const withdrawalsData = await transactionBuilder.getWithdrawalsData({
  chain: 'bitcoin',
  protocol: 'USDh', // Only USDh is supported on Bitcoin
  addresses: {
    payment_btc_address: {
      address: '38byQL...',
      pubKey: '0000231...',
      type: 'p2sh'
    },
    taproot_btc_address: {
      address: 'bc1pkd...',
      pubKey: '023xc0...',
      type: 'p2tr'
    }
  }
});

// Response format
{
  total_to_claim: number; // Total amount of tokens currently available to claim
  next_amount_to_unlock: number; // Amount of tokens that will be unlocked in the next unlock period
  next_claim_timestamp: number; // The timestamp in ms at which the next amount will become claimable
  last_claim_timestamp: number; // The timestamp in ms at which the last unstake request will be fully unlocked
}
```

The claims data response provides information about:

- Currently claimable amounts
- Future unlock amounts
- Timestamps for tracking unlock periods
- This information is useful for displaying countdown timers, progress bars, or other UI elements related to the staking lifecycle

### Retrieving hBTC Rate

Get the current hBTC share price rate:

```typescript
const hbtcRate = await transactionBuilder.gethBTCRate();

// Returns: number — The hBTC share price rate
```

### Retrieving hBTC Price

Get the current hBTC price in USD:

```typescript
const hbtcPrice = await transactionBuilder.gethBTCPrice();

// Returns: number — The hBTC price in USD
```

### Retrieving hBTC APY

Get the current hBTC APY (Annual Percentage Yield):

```typescript
const hbtcApy = await transactionBuilder.gethBTCApy({
  range: '7d' // Optional: Time range for APY calculation ('7d', '30d' or '365d')
});

// Returns: number — The current hBTC APY percentage
```

### Retrieving hBTC Remaining Capacity

Get the remaining BTC deposit capacity for the hBTC vault:

```typescript
const remainingCapacity = await transactionBuilder.gethBTCRemainingCapacity();

// Returns: number — The remaining BTC room available for deposits into the hBTC vault
```

### Retrieving sUSDh Rate

Get the current sUSDh rate:

```typescript
const susdhRate = await transactionBuilder.getsUSDhRate();

// Returns: number — The rate of USDh per sUSDh
```

### Retrieving sUSDh APY

Get the current sUSDh APY (Annual Percentage Yield):

```typescript
const susdhApy = await transactionBuilder.getsUSDhApy({
  range: '7d' // Optional: Time range for APY calculation ('7d', '30d' or '365d')
});

// Returns: number — The current sUSDh APY percentage
```

The APY functions support different time ranges to get historical or current yield data.

## Supported Blockchains

- **Stacks**: Full support for USDh and hBTC staking, unstaking, and claiming rewards
- **Bitcoin**: Support for USDh staking, unstaking, and claiming rewards with:
  - Payment address (p2sh, p2wpkh)
  - Taproot address (p2tr)

> **Note:** hBTC transactions are only supported on Stacks. Bitcoin chain support is limited to USDh/sUSDh.
>
> **Note:** Multisig transactions are only supported on **Stacks**. Bitcoin USDh/sUSDh transactions do not support multisig.

## Transaction Types

- **stake**: Lock your tokens in the protocol to start earning rewards
- **unstake**: Initiate the withdrawal process for your staked tokens (requires waiting period)
- **withdraw**: Collect your available rewards and/or unlocked tokens after the waiting period

## Error Handling

The library throws errors in the following cases:

- Invalid configuration
- Insufficient funds
- Invalid address format
- Network errors
- Invalid transaction parameters

Example error handling:

```typescript
try {
  const result = await transactionBuilder.generateTransactionHex({
    // ... transaction parameters
  });
} catch (error) {
  console.error('Transaction generation failed:', error.message);
}
```

## License

GPL-3.0