@fluppy/browser✓ Complete

@fluppy/browser

Browser runtime SDK built on @fluppy/core. Provides identity management, Merkle proof client, ZK proof generation, and Stellar/Freighter payment submission.

~31 KB
ESM bundle
~32 KB
CJS bundle
~11 KB
TypeScript declarations

Module Map

merkle-client.tsComputes commitment locally, enrolls to backend, fetches Merkle proof path
artifacts.tsLoads and caches WASM witness generator and ZKey proving key from CDN/public dir
prover.tsgenerateZkProof() via snarkjs.groth16.fullProve(), verifyProofLocally()
identity.tsAES-GCM credential (IndexedDB + PBKDF2): create, unlock, delete
stellar.tsFreighter signing, Soroban contract invocation, transaction polling
payment.tsexecuteFluppyPayment() high-level orchestrator composing all modules

executeFluppyPayment()

The top-level payment orchestrator. Composes all browser SDK modules into a single call. The caller is responsible for credential decryption (passing the unlocked secret) and for UI feedback (toast, telemetry, history).

Input fieldTypeDescription
secretstring64-char hex secret from unlockCredential() — passed through, never stored
merchantstringMerchant Stellar address (G... format)
amountbigintPayment amount in stroops (1 USDC = 10_000_000n)
networkPassphrasestringStellar network passphrase — used to compute chainId signal
stellarConfigStellarConfigcontractId, rpcUrl, networkPassphrase
merkleOptions?MerkleClientOptionsOptional: override Merkle API base URL
signal?AbortSignalOptional: cancel in-flight payment
onStep?(step) => voidOptional: receives named steps (merkle:request, proof:done, tx:submit, ...)
onProofProgress?(stage, pct) => voidOptional: receives proof generation progress (0–100)
Output fieldTypeDescription
txHashstringStellar transaction hash of the confirmed payment
proofPaymentProofOutputThe Groth16 proof in Soroban wire format
merkleRootbigintThe Merkle root used for this proof
txResultunknownRaw Soroban RPC transaction status object
ℹ
RootSyncError: if the frontend Merkle tree root does not match the on-chain contract root, executeFluppyPayment() throws a RootSyncError with frontendRootHex and contractRootHex fields. The admin must call set_merkle_root on the contract to resync. See Troubleshooting.

Identity Module

🔐
Security model: The raw secret is derived locally and stored only in encrypted form (AES-GCM, PBKDF2) in IndexedDB. It is never transmitted to any server. Only the commitment — Poseidon(LEAF_TAG, secret) — is sent to the backend Merkle API. The password is used only to derive the AES decryption key and is never stored or logged.
FunctionReturnsDescription
generateSecret()stringGenerates a 32-byte CSPRNG secret as a 64-char hex string
credentialExists()Promise<boolean>Returns true if an encrypted credential exists in IndexedDB
createCredential(password)Promise<{ secret: string }>Encrypts and stores a new credential; returns the secret ONCE
unlockCredential(password)Promise<string>Decrypts and returns the raw secret (never logged internally)
deleteCredential()Promise<void>Permanently removes the credential from IndexedDB

Prover Module

Wraps snarkjs.groth16.fullProve() with generation lock, progress callbacks, AbortSignal support, and Soroban wire format encoding. Local verification via snarkjs.groth16.verify() is enforced in development before every transaction submission as a defense-in-depth measure.

FunctionReturnsDescription
generateZkProof(input)Promise<PaymentProofOutput>Full Groth16 proof generation — validates, builds circuit inputs, runs fullProve, encodes
verifyProofLocally(proof)Promise<boolean>Verifies proof against the loaded verification key using snarkjs.groth16.verify()

Generation lock

Only one proof can be generated at a time per browser session. Calling generateZkProof() while another is in progress throws immediately. Use AbortSignal to cancel an in-flight generation before starting a new one.

Merkle Client Module

FunctionReturnsDescription
computeCommitment(secret)Promise<bigint>Computes Poseidon(LEAF_TAG=2, secret) locally — never sends raw secret
enrollCommitment(secret)Promise<EnrollResult>POSTs commitment hash to /api/merkle-proof/enroll
getMerkleProof(secret)Promise<MerkleProof>POSTs commitment hash, returns pathElements/pathIndices/root
ℹ
The backend Merkle API uses a sparse Merkle tree with pre-computed zero hashes. After the first build (cold cache ~0.7s), subsequent proof requests are served from an in-memory singleton cache in ~14ms.

Stellar & Freighter Module

payWithZkGroth16()

Builds and submits the execute_payment() Soroban transaction. The user signs via Freighter and pays the Stellar network fee from their own wallet. No relayer, no gas sponsorship.

getContractMerkleRoot()

Fetches the current Merkle root from the backend API (/api/merkle-root). Used by the root sync guard inside executeFluppyPayment() to ensure the frontend tree matches the on-chain root before submitting.

Usage Example

ℹ
See Installation for monorepo setup. Do not use public npm package installation yet — packages are not yet published.
payment-example.ts
import {
  executeFluppyPayment,
  unlockCredential,
  RootSyncError,
  type StellarConfig,
} from '@fluppy/browser';

const config: 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, merchant: string, amount: bigint) {
  // Step 1: Decrypt credential (browser only)
  const secret = await unlockCredential(password);

  // Step 2: Orchestrate full payment (secret passed through, not stored)
  try {
    const result = await executeFluppyPayment({
      secret,
      merchant,
      amount,
      networkPassphrase: config.networkPassphrase!,
      stellarConfig:     config,
      onStep:         (step) => console.log('[step]', step.name),
      onProofProgress:(stage, pct) => console.log('[proof]', stage, pct),
    });

    return result.txHash;

  } catch (err) {
    if (err instanceof RootSyncError) {
      // Admin action required: set_merkle_root on contract
      console.error('Root mismatch. Frontend:', err.frontendRootHex);
    }
    throw err;
  }
}