Examples

Complete code examples for integrating the Fluppy SDK into a React application. All examples use the internal monorepo workspace packages.

β„Ή
These examples demonstrate the SDK API. Current packages are internal monorepo workspace packages β€” see Installation for setup. Full migration of the existing Fluppy app to these hooks is a planned next phase.

1. Provider Setup

Place FluppyProvider near your application root. Memoize the config object with useMemo to prevent unnecessary re-renders in child hooks.

app/layout.tsx
'use client';

import { useMemo } from 'react';
import { FluppyProvider } from '@fluppy/react';
import type { FluppyReactConfig } from '@fluppy/react';

export default function RootLayout({ children }: { children: ReactNode }) {
  const config = useMemo((): FluppyReactConfig => ({
    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!,
    // merkleOptions is optional β€” defaults to /api/merkle-proof
  }), []);

  return (
    <html lang="en">
      <body>
        <FluppyProvider config={config}>
          {children}
        </FluppyProvider>
      </body>
    </html>
  );
}

2. Wallet Connection

useFluppyWallet wraps Freighter wallet state. All Freighter calls use dynamic import β€” safe in SSR environments.

WalletButton.tsx
'use client';

import { useFluppyWallet } from '@fluppy/react';

export function WalletButton() {
  const { address, isConnected, isConnecting, error, connect, resetError } = useFluppyWallet();

  if (isConnected && address) {
    return (
      <div className="flex items-center gap-2">
        <span className="h-2 w-2 rounded-full bg-green-400" />
        <span>{address.slice(0, 6)}…{address.slice(-4)}</span>
      </div>
    );
  }

  return (
    <div>
      {error && <p onClick={resetError}>Error: {error.message} (click to dismiss)</p>}
      <button onClick={connect} disabled={isConnecting}>
        {isConnecting ? 'Connecting…' : 'Connect Freighter'}
      </button>
    </div>
  );
}

3. Credential Lifecycle

πŸ”
The secret returned by create() and unlock() must never be logged to console, never stored in useState, and never sent to any server. Pass it directly to pay() in the same async function. Display the backup secret to the user exactly once after create().
CredentialManager.tsx
'use client';

import { useFluppyCredential } from '@fluppy/react';

export function CredentialManager({
  onSecretCreated,   // caller shows this backup secret to the user ONCE
  onUnlocked,        // caller passes secret directly to payment flow
}: {
  onSecretCreated: (backupSecret: string) => void;
  onUnlocked:      (secret: string)       => void;
}) {
  const { status, isLoading, error, create, unlock, remove, refresh } = useFluppyCredential();

  async function handleCreate(password: string) {
    // createCredential returns { secret } β€” show it to user ONCE as backup
    const { secret } = await create(password);
    onSecretCreated(secret); // your UI responsibility β€” never log it
  }

  async function handleUnlock(password: string) {
    // unlockCredential decrypts and returns the secret in memory
    const secret = await unlock(password);
    onUnlocked(secret); // pass directly to payment β€” do not store
  }

  if (status === 'unknown') return <p>Checking credential storage…</p>;

  if (status === 'not_found') {
    return (
      <div>
        <p>No credential found. Create one to start paying.</p>
        <button onClick={() => handleCreate(passwordFromYourUI)}>
          Create Credential
        </button>
      </div>
    );
  }

  return (
    <div>
      <p>Credential ready.</p>
      <button onClick={() => handleUnlock(passwordFromYourUI)}>Unlock to Pay</button>
      <button onClick={remove}>Delete Credential</button>
    </div>
  );
}

4. Payment Flow

PaymentForm.tsx
'use client';

import { useFluppyPayment } from '@fluppy/react';

export function PaymentForm({
  merchantAddress,  // your application supplies this β€” do not hardcode in SDK
  getSecretFromUI,  // function that returns unlocked secret from your credential flow
}: {
  merchantAddress: string;
  getSecretFromUI: () => Promise<string>;
}) {
  const {
    status, isLoading, error, txHash,
    progressPct, progressStage, currentStep,
    pay, abort, reset, resetError,
  } = useFluppyPayment();

  async function handlePay() {
    // Get the unlocked secret from your credential unlock flow
    const secret = await getSecretFromUI();

    // pay() accepts secret directly β€” it is NOT stored in React state internally
    await pay({
      secret,
      merchant: merchantAddress,
      amount:   10_000_000n, // 1 USDC in stroops
    });
  }

  return (
    <div>
      {/* Progress display */}
      {status === 'pending' && (
        <div>
          <p>Step: {currentStep}</p>
          <p>Progress: {progressPct ?? 0}% β€” {progressStage}</p>
          <button onClick={abort}>Cancel</button>
        </div>
      )}

      {/* Success */}
      {status === 'success' && txHash && (
        <div>
          <p>βœ“ Payment confirmed</p>
          
            href={`https://stellar.expert/explorer/testnet/tx/${txHash}`}
            target="_blank"
            rel="noopener noreferrer"
          >
            View on Stellar Expert β†—
          </a>
          <button onClick={reset}>Pay again</button>
        </div>
      )}

      {/* Error */}
      {error && (
        <div>
          <p>Error: {error.message}</p>
          <button onClick={resetError}>Dismiss</button>
        </div>
      )}

      {/* Pay button */}
      {status === 'idle' && (
        <button onClick={handlePay} disabled={isLoading}>
          Pay 1 USDC
        </button>
      )}
    </div>
  );
}

5. Payment History

β„Ή
useFluppyHistory stores only public metadata β€” txHash, amount, merchant address, timestamp, and status. No secrets, passwords, ZK proof inputs, or private keys are stored. The amount field is a bigint in the public API and serialized as a decimal string in localStorage.
PaymentHistory.tsx
'use client';

import { useFluppyHistory } from '@fluppy/react';
import type { FluppyPaymentRecord } from '@fluppy/react';

export function PaymentHistory() {
  const { records, update, remove, clear } = useFluppyHistory();

  if (records.length === 0) {
    return <p>No payments recorded yet.</p>;
  }

  return (
    <div>
      <div>
        {records.map((record) => (
          <div key={record.txHash}>
            <span>{record.status}</span>
            <span>{(Number(record.amount) / 10_000_000).toFixed(2)} USDC</span>
            <span>{record.merchant.slice(0, 6)}…</span>
            <span>{new Date(record.timestamp).toLocaleDateString()}</span>
            {record.explorerUrl && (
              <a href={record.explorerUrl} target="_blank" rel="noopener noreferrer">
                View β†—
              </a>
            )}
            <button onClick={() => remove(record.txHash)}>Γ—</button>
          </div>
        ))}
      </div>
      <button onClick={clear}>Clear all</button>
    </div>
  );
}

// Adding a record after payment:
function addPaymentToHistory(
  history: ReturnType<typeof useFluppyHistory>,
  result: { txHash: string },
  merchant: string,
  amount: bigint,
) {
  const record: FluppyPaymentRecord = {
    txHash:      result.txHash,
    amount,
    merchant,
    timestamp:   Date.now(),
    status:      'success',
    explorerUrl: `https://stellar.expert/explorer/testnet/tx/${result.txHash}`,
  };
  history.add(record);
}

6. Combined Payment Card

A compact example combining all hooks. In a real application, supply merchantAddress from your configuration and password from a secure password input β€” never hardcode them.

PaymentCard.tsx
'use client';

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

export function PaymentCard({
  merchantAddress,        // from your app config β€” do not hardcode
  amountInStroops,        // e.g. 10_000_000n = 1 USDC
  passwordFromSecureInput, // from a password input field in your UI
}: {
  merchantAddress:         string;
  amountInStroops:         bigint;
  passwordFromSecureInput: string;
}) {
  const wallet  = useFluppyWallet();
  const cred    = useFluppyCredential();
  const payment = useFluppyPayment();
  const history = useFluppyHistory();

  async function handlePay() {
    // Connect wallet if needed
    if (!wallet.isConnected) {
      await wallet.connect();
    }

    // Decrypt credential β€” secret lives in memory only, never stored in state
    const secret = await cred.unlock(passwordFromSecureInput);

    // Execute payment β€” secret passed directly, not cached
    const result = await payment.pay({
      secret,
      merchant: merchantAddress,
      amount:   amountInStroops,
    });

    // Record metadata β€” NOT secret, NOT proof data
    history.add({
      txHash:      result.txHash,
      amount:      amountInStroops,
      merchant:    merchantAddress,
      timestamp:   Date.now(),
      status:      'success',
      explorerUrl: `https://stellar.expert/explorer/testnet/tx/${result.txHash}`,
    });
  }

  if (payment.status === 'success') {
    return <p>βœ“ Payment confirmed: {payment.txHash?.slice(0, 12)}…</p>;
  }

  return (
    <div>
      {payment.status === 'pending' && (
        <div>
          <p>{payment.currentStep} β€” {payment.progressPct ?? 0}%</p>
          <p>{payment.progressStage}</p>
        </div>
      )}
      {payment.error && <p>Error: {payment.error.message}</p>}
      <button onClick={handlePay} disabled={payment.isLoading}>
        Pay {(Number(amountInStroops) / 10_000_000).toFixed(2)} USDC
      </button>
    </div>
  );
}

7. Browser SDK Without React

@fluppy/browser works without React β€” useful for vanilla TypeScript integrations or non-React frameworks.

payment-vanilla.ts
import {
  unlockCredential,
  executeFluppyPayment,
  RootSyncError,
  type StellarConfig,
} from '@fluppy/browser';

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

async function pay(
  password:        string, // from user input
  merchantAddress: string, // from your config
  amountInStroops: bigint,
) {
  // Decrypt credential β€” secret in memory only
  const secret = await unlockCredential(password);

  try {
    const result = await executeFluppyPayment({
      secret,
      merchant:          merchantAddress,
      amount:            amountInStroops,
      networkPassphrase: stellarConfig.networkPassphrase!,
      stellarConfig,
      onStep:          (step) => updateUI(step.name),
      onProofProgress: (stage, pct) => updateProgress(stage, pct),
    });

    return result.txHash;

  } catch (err) {
    if (err instanceof RootSyncError) {
      // On-chain root needs resync β€” admin action required
      console.error('Root mismatch. Expected on-chain:', err.contractRootHex);
    }
    throw err;
  }
}

function updateUI(step: string) { /* your UI update logic */ }
function updateProgress(stage: string, pct: number) { /* your progress logic */ }