@fluppy/reactāœ“ Complete

@fluppy/react

React SDK built on @fluppy/browser. Provides a context provider and four domain hooks for the full Fluppy payment lifecycle.

ℹ
Status: @fluppy/react is complete as an SDK layer. Full migration of the existing Fluppy app to these hooks is a planned next phase. These hooks are ready to be consumed by any React 18+ application with FluppyProvider at the root.
~14 KB
ESM bundle
~14 KB
CJS bundle
~14 KB
TypeScript declarations

Available Hooks

FluppyProvider

Context provider — wraps a React subtree with Fluppy config

useFluppyCredential

Credential lifecycle: create, unlock, delete, status

useFluppyPayment

Full ZK payment flow with abort, progress, and step tracking

useFluppyWallet

Freighter wallet connection state (SSR-safe, dynamic import)

useFluppyHistory

localStorage-persisted payment records with bigint serialization

FluppyProvider

Wrap your application (or a subtree) with FluppyProvider. All Fluppy hooks must be descendants of this provider. Memoize the config object to prevent unnecessary re-renders.

Config fieldTypeDescription
stellarConfigStellarConfigcontractId, rpcUrl, networkPassphrase — Soroban connection config
networkPassphrasestringStellar network passphrase — MUST match the contract's expected chainId
merkleOptions?MerkleClientOptionsOptional: apiBaseUrl override for the Merkle proof backend
layout.tsx
import { FluppyProvider } from '@fluppy/react';

const config = {
  stellarConfig: {
    contractId:        process.env.NEXT_PUBLIC_CONTRACT_ID!,
    rpcUrl:            process.env.NEXT_PUBLIC_RPC_URL!,
    networkPassphrase: process.env.NEXT_PUBLIC_NETWORK_PASSPHRASE!,
  },
  networkPassphrase: process.env.NEXT_PUBLIC_NETWORK_PASSPHRASE!,
};

export default function Layout({ children }: { children: ReactNode }) {
  return <FluppyProvider config={config}>{children}</FluppyProvider>;
}

useFluppyCredential()

Manages the full lifecycle of a locally encrypted ZK credential. Initial credential check runs in a browser-safe useEffect — SSR renders return status: 'unknown'.

šŸ”
The secret returned by create() and unlock() must never be logged, never stored in useState, and never sent to any server. Pass it directly to useFluppyPayment().pay() in the same async function.
PropertyTypeDescription
statusCredentialStatusunknown | exists | not_found
existsboolean | nulltrue/false when status is known; null while unknown
isLoadingbooleanTrue during any async credential operation
errorError | nullLast thrown error; null if none
create(pw)(string) → Promise<{secret}>Creates and encrypts a new credential; returns secret ONCE
unlock(pw)(string) → Promise<string>Decrypts and returns raw secret — never logged internally
remove()() → Promise<void>Permanently deletes credential from IndexedDB
refresh()() → Promise<void>Re-checks credential existence
resetError()() → voidClears current error without changing status

useFluppyPayment()

Orchestrates the full ZK payment flow. Reads configuration from FluppyProvider. The secret is passed as a parameter to pay() — it is never stored in React state.

StateTypeDescription
statusPaymentStatusidle | pending | success | failed
isLoadingbooleanTrue during proof generation or transaction submission
errorError | nullLast thrown error; null if none
txHashstring | nullTransaction hash on success; null otherwise
progressStagestring | nullCurrent proof generation stage label (e.g. "Computing witness")
progressPctnumber | null0–100 during proof generation
currentStepFluppyPaymentStepName | nullNamed orchestrator step: merkle:request | proof:start | tx:submit | tx:confirmed | ...
MethodReturnsDescription
pay(input)Promise<ExecuteFluppyPaymentResult>Initiates payment; throws on failure — caller handles UI feedback
abort()voidCancels in-flight payment, resets status to idle
reset()voidFull state reset: clears status, error, txHash, progress
resetError()voidClears error only — preserves txHash and status
pay() inputTypeDescription
secretstring64-char hex from useFluppyCredential.unlock() — NOT stored in state
merchantstringMerchant Stellar address (G... format)
amountbigintPayment amount in stroops (1 USDC = 10_000_000n)
signal?AbortSignalOptional external abort signal composed with the hook's own controller

useFluppyWallet()

Manages Freighter wallet connection state. Uses dynamic import for the Freighter API to avoid bundling it in SSR contexts. refresh() is a no-op on the server.

PropertyTypeDescription
addressstring | nullConnected Stellar address; null if not connected
connectionStatusWalletConnectionStatusdisconnected | connecting | connected | error
isConnectedbooleanDerived: true when status is connected
isConnectingbooleanDerived: true when status is connecting
errorError | nullLast error from connect(); null if none
connect()() → Promise<string>Calls Freighter requestAccess(), returns address; throws on rejection
refresh()() → Promise<void>Re-checks Freighter isConnected(); no-op on SSR
resetError()() → voidClears error only
ℹ
The user signs the Soroban transaction directly via Freighter and pays the Stellar network fee from their own wallet. There is no production relayer and no gas sponsorship in the current Testnet MVP.

useFluppyHistory()

Persists payment record metadata to localStorage using the key fluppy:payment-history:v1. Records are loaded on mount inside a browser-safe useEffect — SSR renders return an empty array. Capped at 50 records.

ℹ
amount is a bigint in the public API but serialized as a decimal string in localStorage (JSON cannot encode bigint natively). Deserialization is handled automatically — callers always receive bigint. No secrets, passwords, ZK proof internals, or private keys are stored.
MethodSignatureDescription
add(record)(FluppyPaymentRecord) → voidPrepends record; deduplicates by txHash; persists
update(txHash, patch)(string, Partial) → voidUpdates matching record fields; persists
remove(txHash)(string) → voidRemoves record by txHash; persists
clear()() → voidClears all records from state and localStorage
refresh()() → voidReloads records from localStorage
FluppyPaymentRecord fieldTypeDescription
txHashstringStellar transaction hash
amountbigintPayment amount in stroops
merchantstringMerchant Stellar address
timestampnumberUnix timestamp in milliseconds
status'pending' | 'success' | 'failed'Payment outcome
explorerUrl?stringOptional Stellar Expert explorer URL

Combined Example

ℹ
See Installation for monorepo setup. Do not use public npm package installation yet — packages are not yet published.
PaymentCard.tsx
'use client';

import {
  useFluppyCredential,
  useFluppyPayment,
  useFluppyHistory,
  useFluppyWallet,
} from '@fluppy/react';

export function PaymentCard({ merchant }: { merchant: string }) {
  const wallet  = useFluppyWallet();
  const cred    = useFluppyCredential();
  const payment = useFluppyPayment();
  const history = useFluppyHistory();

  async function handlePay(password: string) {
    if (!wallet.isConnected) await wallet.connect();

    // unlock() returns secret in memory only — NOT stored in state
    const secret = await cred.unlock(password);

    const result = await payment.pay({
      secret,
      merchant,
      amount: 10_000_000n, // 1 USDC
    });

    // Store metadata — NOT secret, NOT proof internals
    history.add({
      txHash:      result.txHash,
      amount:      10_000_000n,
      merchant,
      timestamp:   Date.now(),
      status:      'success',
      explorerUrl: `https://stellar.expert/explorer/testnet/tx/${result.txHash}`,
    });
  }

  return (
    <div>
      {payment.status === 'pending' && (
        <div>
          <div>{payment.currentStep}</div>
          <div>{payment.progressPct ?? 0}% — {payment.progressStage}</div>
        </div>
      )}
      {payment.status === 'success' && <p>āœ“ {payment.txHash}</p>}
      {payment.error && <p>Error: {payment.error.message}</p>}
      <button
        onClick={() => handlePay(passwordFromSecureInput)}
        disabled={payment.isLoading}
      >
        Pay 1 USDC
      </button>
    </div>
  );
}