1.1.8 • Published 5 months ago

@faktoryfun/styx-sdk v1.1.8

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

@faktoryfun/styx-sdk

A Bitcoin deposit SDK for Stacks applications, enabling trustless Bitcoin-to-sBTC deposits.

Installation

npm install @faktoryfun/styx-sdk
# or
yarn add @faktoryfun/styx-sdk

For a complete working example of an application integrating this SDK, check out the Styx Integration Example repository.

Features

  • Manage Bitcoin deposits to sBTC
  • Handle UTXOs and transaction preparation
  • Support for popular Stacks/Bitcoin wallets (Leather, Xverse)
  • Fee estimation and management
  • Transaction execution and status tracking
  • Protection against inscriptions in UTXOs
  • Pool status monitoring
  • BTC price fetching

Usage

Basic Setup

import { styxSDK, TransactionPriority } from "@faktoryfun/styx-sdk";

// The default export uses pre-configured credentials
// You can also create a customized instance:
const customSDK = new StyxSDK("https://your-api-url.com", "your-api-key");

Preparing a Transaction

const prepareTransaction = async () => {
  try {
    const transactionData = await styxSDK.prepareTransaction({
      amount: "0.001", // BTC amount as string
      userAddress: "SP...", // STX address
      btcAddress: "bc1...", // BTC address
      feePriority: TransactionPriority.Medium,
      walletProvider: "leather", // "leather" or "xverse"
    });

    console.log("Transaction prepared:", transactionData);
    return transactionData;
  } catch (error) {
    console.error("Error preparing transaction:", error);
  }
};

Creating a Deposit

const createDeposit = async () => {
  try {
    const depositId = await styxSDK.createDeposit({
      btcAmount: 0.001, // BTC amount as number
      stxReceiver: "SP...", // STX address
      btcSender: "bc1...", // BTC address
    });

    console.log("Deposit created with ID:", depositId);
    return depositId;
  } catch (error) {
    console.error("Error creating deposit:", error);
  }
};

Executing a Transaction

const executeTransaction = async (depositId, preparedData) => {
  try {
    const result = await styxSDK.executeTransaction({
      depositId,
      preparedData,
      walletProvider: "leather", // "leather" or "xverse"
      btcAddress: "bc1...", // BTC address
    });

    console.log("Transaction executed:", result);
    return result;
  } catch (error) {
    console.error("Error executing transaction:", error);
  }
};

Updating Deposit Status

const updateDepositStatus = async (depositId, txId) => {
  try {
    const result = await styxSDK.updateDepositStatus({
      id: depositId,
      data: {
        btcTxId: txId,
        status: "broadcast",
      },
    });

    console.log("Deposit status updated:", result);
    return result;
  } catch (error) {
    console.error("Error updating deposit status:", error);
  }
};

Transaction Status Tracking

The Styx SDK now provides flexible methods to monitor deposit status throughout the transaction lifecycle. Use getDepositStatus(depositId) to look up deposits by their unique identifier or getDepositStatusByTxId(btcTxId) to query using the Bitcoin transaction hash. The latter is especially valuable for wallet integrations, allowing users to recover deposit information even if they've lost track of the deposit ID. Implementation is straightforward:

// Check status using deposit ID
const depositStatus = await styxSDK.getDepositStatus("123");

// Check status using Bitcoin transaction ID after broadcast
const sameDepositStatus = await styxSDK.getDepositStatusByTxId(
  "2f9ad639e10d0609431a5c1c5b0b5a0f369c14a46f5f3452ababc85c7b2be7d3"
);

console.log("Current status:", depositStatus.status); // "broadcast", "processing", "confirmed", etc.

Getting Deposit History

const getHistory = async (userAddress) => {
  const history = await styxSDK.getDepositHistory(userAddress);
  console.log("Deposit history:", history);
  return history;
};

Getting All Deposits History

const getAllDepositsHistory = async () => {
  const allDeposits = await styxSDK.getAllDepositsHistory();
  console.log("All deposits:", allDeposits);
  return allDeposits;
};

Getting Fee Estimates

const getFees = async () => {
  const fees = await styxSDK.getFeeEstimates();
  console.log("Current fee estimates (sats/vB):", fees);
  return fees;
};

Getting Pool Status

const getPoolStatus = async () => {
  const status = await styxSDK.getPoolStatus();
  console.log("Pool status:", status);
  /*
    {
      realAvailable: 0.5,      // BTC
      estimatedAvailable: 0.45, // BTC (accounting for pending deposits)
      lastUpdated: 1687245600000 // timestamp
    }
  */
  return status;
};

Getting BTC Price

const getBTCPrice = async () => {
  const price = await styxSDK.getBTCPrice();
  console.log("Current BTC price (USD):", price);
  return price;
};

Deposit Limitations

  • Minimum deposit: 10,000 sats (0.0001 BTC)
  • Maximum deposit: 400,000 sats (0.004 BTC)

Status Management

The SDK handles different deposit statuses which are crucial for properly managing sBTC liquidity in the pool:

  • initiated - Initial deposit record created
  • broadcast - Bitcoin transaction has been broadcast to the network
  • processing - Transaction is being processed (has at least 1 confirmation)
  • confirmed - Transaction is confirmed (has required number of confirmations)
  • refund-requested - User has requested a refund
  • canceled - Deposit was canceled and liquidity released back to the pool

Important: Always update the deposit status after a transaction is broadcast or canceled to ensure accurate pool liquidity accounting.

API Reference

StyxSDK Class

MethodParametersReturn TypeDescription
getFeeEstimatesNonePromise<FeeEstimates>Get current Bitcoin network fee estimates
createDepositDepositCreateParamsPromise<string>Create a new deposit record and get its ID
updateDepositDepositUpdateParamsPromise<any>Update an existing deposit record
updateDepositStatusid, dataPromise<any>Update the status of an existing deposit
getDepositStatusdepositIdPromise<Deposit>Get status of a deposit by its ID
getDepositStatusByTxIdbtcTxIdPromise<Deposit>Get status of a deposit by Bitcoin transaction ID
getDepositHistoryuserAddressPromise<Deposit[]>Get deposit history for a specific user
getAllDepositsHistoryNonePromise<Deposit[]>Get all deposits (admin function)
prepareTransactionTransactionPrepareParamsPromise<PreparedTransactionData>Prepare a transaction with UTXOs and fee calculation
executeTransactiondepositId, preparedData, walletProvider, btcAddressPromise<ExecuteTransactionResponse>Execute a prepared transaction
getPoolStatusNonePromise<PoolStatus>Get current pool status and available liquidity
getBTCPriceNonePromise<number \| null>Get current BTC price in USD

Types

// Important types used in the SDK
export type TransactionPriority = "low" | "medium" | "high";

export interface DepositCreateParams {
  btcAmount: number;
  stxReceiver: string;
  btcSender: string;
}

export interface PreparedTransactionData {
  utxos: Array<any>;
  opReturnData: string;
  depositAddress: string;
  fee: number;
  changeAmount: number;
  amountInSatoshis: number;
  feeRate: number;
  inputCount: number;
  outputCount: number;
  inscriptionCount: number;
}

export interface PoolStatus {
  realAvailable: number;
  estimatedAvailable: number;
  lastUpdated: number;
}

export interface FeeEstimates {
  low: number;
  medium: number;
  high: number;
}

Constants

The SDK provides useful constants for minimum and maximum deposit amounts:

import { MIN_DEPOSIT_SATS, MAX_DEPOSIT_SATS } from "@faktoryfun/styx-sdk";

console.log("Minimum deposit (sats):", MIN_DEPOSIT_SATS); // 10000 sats (0.0001 BTC)
console.log("Maximum deposit (sats):", MAX_DEPOSIT_SATS); // 400000 sats (0.004 BTC)

License

MIT

1.1.8

5 months ago

1.1.7

5 months ago

1.1.6

6 months ago

1.1.5

6 months ago

1.1.4

6 months ago

1.1.3

6 months ago

1.1.2

6 months ago

1.1.1

6 months ago

1.1.0

6 months ago

1.0.14

6 months ago

1.0.12

7 months ago

1.0.11

7 months ago

1.0.10

7 months ago

1.0.9

7 months ago

1.0.8

7 months ago

1.0.7

7 months ago

1.0.6

7 months ago

1.0.5

7 months ago

1.0.4

7 months ago

1.0.3

7 months ago

1.0.2

7 months ago

1.0.1

7 months ago

1.0.0

7 months ago