Skip to content

@opaquecash/stellar

Classes

ClassDescription
OpaqueClient-
SchemaRegistry-
AttestationEngine-
StealthRegistry-
StealthAnnouncer-
PrivacyPool-
RelayerRegistry-
Groth16Verifier-
ReputationVerifierHigh-level reputation-verifier binding. verify_reputation enforces root validity + nullifier-replay protection and calls the groth16-verifier; this is the on-chain entry point for proving reputation (vs. the lower-level Groth16Verifier).
SchemaParseError-
AttestationDataError-
OpaqueErrorTyped error hierarchy for the SDK. Every thrown error carries a stable, machine-readable code so callers can branch without string-matching messages. Soroban contract failures map to ContractError with the decoded contract error code (and a name when the contract's error enum is known to the SDK).
ConfigErrorConfiguration is missing or invalid (e.g. mainnet without RPC URLs).
SignerErrorA signer adapter failed to produce a signature.
RpcErrorAn RPC or Horizon request failed (network, timeout, or HTTP status).
SimulationErrorA transaction failed during pre-flight simulation.
ContractErrorA Soroban contract invocation reverted with a contract error code.
RootUnavailableErrorThe published reputation/pool root is unavailable or not yet indexed.
ArtifactErrorA circuit artifact failed to resolve or failed its integrity check.
NotWiredErrorA capability that depends on a layer not yet wired in this build (e.g. the proving layer, the WASM scanner, or the relayer gateway client). Thrown so the surface is discoverable and the failure is explicit rather than silent.
PoolMerkleTreeDepth-20 Poseidon Merkle tree, byte-matching the contract / circuit / ASP.
RelayerGateway-
RpcClient-
PaymentsService-
PoolService-
RelayerService-
ReputationService-
SchemasService-
MemoryNoteStoreIn-memory NoteStore. Notes are keyed by commitment.
MemoryVaultStoreIn-memory VaultStore. Ghost entries are keyed by stealth address.
MemoryScanStoreIn-memory ScanStore.

Interfaces

InterfaceDescription
ArtifactResolver-
OpaqueClientOptions-
ContractAddresses-
PoolWiring-
RelayerWiring-
NetworkDeployment-
OpaqueConfig-
ResolvedConfig-
NetworkPreset-
PoolWithdrawInputs-
VerifyProofV2Inputs-
VerifyReputationInputs-
MemoRisk-
MemoValidationResult-
PaymentLinkParams-
PaymentLink-
PaymentLinkError-
StealthAnnouncement-
ScanMatch-
FieldDef-
LoggerPluggable logger. The SDK logs nothing by default (no console.log noise in a library); a host app can pass consoleLogger or its own implementation.
PoolWithdrawProof-
ReputationProveInput-
ReputationWitnessV2-
ReputationProof-
Groth16ProofLike-
SerializedProof-
RpcClientOptions-
InvokeOptions-
ReadOptions-
ContractInvokerThe subset of RpcClient the contract bindings depend on. Bindings are written against this interface so they can be unit-tested with a stub invoker (no network) and dogfooded with the real client in production.
ScannerModuleTyped interface to the Rust/WASM DKSAP scanner. The scanner does the performance-critical view-tag filtering, stealth-key reconstruction, and reputation-witness generation. The binary ships with the package and is loaded lazily by an environment-specific ScannerLoader (browser instantiates via WebAssembly, Node reads the file); both resolve to this interface.
ContractBindings-
OpaqueClientContext-
StealthIdentity-
SignerContext-
OpaqueSigner-
NoteStorePersistence for privacy-pool notes (spending material).
VaultStorePersistence for stealth "ghost" entries (ephemeral keys + metadata).
ScanStorePersistence for the announcement-scan cursor (last processed ledger).
ContractCallEventPluggable telemetry hooks. The SDK emits structured events at meaningful points (contract calls, scans) so a host app can wire its own metrics without the SDK depending on any monitoring library. All hooks are optional; the default is a no-op.
ScannerSyncEvent-
Telemetry-

Type Aliases

Type AliasDescription
ArtifactId-
ArtifactKind-
OpaqueNetworkStellar network presets: passphrase and default RPC / Horizon endpoints per network. Mainnet ships with no default endpoints — callers must supply production providers explicitly.
GhostEntryLike-
EncryptedGhostPayload-
Hex0x-prefixed hex string.
DomainSeparationOpts-
MemoTypeDestination memo risk + validation.
PoolNote-
DerivedDeposit-
NetworkOpaque payment-link format: opaque://v{version}/{network}/{metaAddress}?{params} with versioning, network binding, and optional SEP-compatible parameters.
FieldTypeSchema field primitives shared by the schema codec and the schema service.
X25519Keypair-
VerifiedBid-
RelayerJobDraft-
RelayerJobStatus-
JobAdvert-
RelayerBid-
EncryptedPayload-
RelayerMessage-
PoolWithdrawPayload-
SerializablePoolWithdrawPayload-
ScannerLoaderLazily load and instantiate the scanner module.
WithdrawProofBundleA withdrawal proof bundle (everything except the public recipient/fee/relayer).
SignTxFnLow-level callback form: sign a transaction XDR, return the signed XDR.

Variables

VariableDescription
DEFAULT_ARTIFACT_PATHSDefault relative paths, matching the published circuit release layout.
TESTNET_DEPLOYMENTGenerated from deployments/v1/testnet.json.
DEPLOYMENTSKnown deployments by network. Testnet is the only live deployment today.
NETWORK_PRESETS-
SCHEME_ID_SECP256K1secp256k1 stealth scheme id, as registered on-chain.
formatXlmAlias for formatStroopsToXlm.
LEGACY_SETUP_MESSAGE-
POOL_TREE_DEPTHPrivacy-pool note model and cryptographic derivation.
BN254_R-
MAX_FIELDS-
MAX_FIELD_NAME_LEN-
MAX_STRING_VALUE_LEN-
MAX_ATTESTATION_DATA_LEN-
CONTRACT_ERROR_NAMESKnown contract error enums, keyed by contract package name. Populated as the SDK binds each contract; an unknown code still surfaces as a numeric ContractError. Source of truth is each contract's #[contracterror].
VERSIONThe installed SDK version.
silentLoggerDefault logger: discards everything.
consoleLoggerLogger that forwards to the global console.
RELAY_PAYLOAD_DOMAIN-
RELAY_CHAIN_STELLAR-
NEW_ACCOUNT_MIN_RESERVE_STROOPSMinimum starting balance (stroops) to create a fresh Stellar account (1 XLM).
noopTelemetryDefault telemetry: records nothing.

Functions

FunctionDescription
urlArtifactResolverBuild a resolver that maps artifacts to URLs under a base URL. Pass paths to override individual artifact locations.
fileArtifactResolverBuild a resolver that maps artifacts to local filesystem paths under a base directory. The returned path strings are consumed directly by snarkjs in Node.
resolveConfigResolve user config into a complete, validated configuration: network preset + baked deployment + explicit overrides. Throws ConfigError when a required endpoint or contract address is missing (e.g. mainnet usage).
parseXlmToStroopsParse an XLM string into stroops. Enforces at most 7 decimal places and rejects malformed input.
parseHorizonBalanceToStroopsParse a Horizon balance string into stroops. Returns 0 for empty or malformed input (defensive against unexpected API responses).
formatStroopsToXlmFormat stroops as an XLM string with trailing zeros removed.
encryptGhostEntriesEncrypt ghost entries. Only ephemeralPrivKeyHex is encrypted; metadata (cluster, stealth address, timestamp) stays readable.
decryptGhostEntriesDecrypt ghost entries produced by encryptGhostEntries.
exportEncryptedBackupExport ghost entries as an encrypted JSON string.
importEncryptedBackupImport ghost entries from an encrypted backup string.
hexToBytesParse a hex string (with or without 0x) into bytes.
bytesToHexEncode bytes as a lowercase hex string (no 0x prefix).
bytesToBigIntInterpret bytes as a big-endian unsigned integer.
bigIntToBytes32Encode a bigint as a fixed 32-byte big-endian array.
toHex32bigint -> 0x-prefixed 32-byte big-endian hex.
concatBytesConcatenate byte arrays into one.
buildDomainSeparatedMessageBuild the human-readable, domain-separated message a wallet signs to derive its Opaque stealth keys. Signing it is not a transaction and moves no funds.
deriveKeysFromSignatureDerive viewing key (v) and spending key (s) from a wallet signature used as entropy. Expands the signature into 64 bytes via HKDF-SHA256, then splits into two 32-byte private keys. Domain string is "opaque-cash-v1".
keysToStealthMetaAddressBuild the stealth meta-address from viewing and spending private keys. Meta-address = compressed(V)
stealthMetaAddressToHexEncode the 66-byte stealth meta-address as 0x-prefixed hex.
parseStealthMetaAddressParse a recipient stealth meta-address into viewing and spending public keys. Format: first 33 bytes = compressed viewing key V, next 33 = compressed S.
computeStealthAddressAndViewTagSender-side: compute a one-time stealth address and view tag for a recipient meta-address. Generates a fresh ephemeral key per call.
buildGhostAnnouncementPayloadRebuild announce() parameters for a manual ghost receive using a stored ephemeral private key (deterministic re-derivation of a prior send).
recipientSharedSecretHashRecipient-side: recompute the DKSAP shared-secret hash and view tag from the sender's ephemeral public key and the recipient's viewing key. Mirrors the sender computation via ECDH symmetry (viewPriv·EphPub == ephPriv·ViewPub).
checkViewTagMatchCheap recipient-side prefilter: does this announcement's view tag match? Lets a recipient skip the expensive point math for non-matching transfers.
reconstructStealthPrivateKeyRecipient-side: reconstruct the one-time stealth private key for a transfer. stealthPriv = (spendingKey + sH) mod n, where sH = keccak(viewPriv·EphPub). The returned key controls the same secp256k1 point the sender derived, hence the same deterministic Stellar account.
deriveAnnouncerEphemeralKeyDeterministic ephemeral scalar for the "Announcer" stealth signer.
deriveStealthStellarKeypairDerive the deterministic Ed25519 Stellar keypair from a stealth secp256k1 point.
deriveStealthStellarAddressDerive the deterministic Stellar G-address from a stealth secp256k1 point.
stealthIdFromPrivateKeyRecompute the 20-byte EVM-style stealth id (0x + 40 hex) from a stealth private key. Used to confirm a view-tag match against an announcement.
deriveStealthStellarAddressFromStealthPrivKeyDerive the deterministic Stellar G-address from a stealth private key.
deriveStealthStellarKeypairFromStealthPrivKeyDerive the deterministic Stellar keypair from a stealth private key.
memoRiskForLook up the memo risk for a destination. Safe for any input.
validateMemoValidate a memo value against the Stellar memo spec for the given type.
memoWarningCopyWarning copy for the inline banner, or null when no warning is needed.
getPoseidonLazily build (and cache) the circomlibjs Poseidon instance.
hashFieldsHash a list of field elements with Poseidon, returning the field result.
randomFieldElementCryptographically-random field element < r (decimal string).
deriveDepositDerive the commitment material for one deposit from its secrets.
newNoteSecretsBuild a fresh note's secrets (commitment is filled once the leaf index is known).
unspentTotalUnspent total across notes, in stroops.
isValidMetaAddressValidate a DKSAP meta-address: 0x + 132 hex chars (66 bytes).
isValidNetwork-
isValidStellarPublicKeyValidate a Stellar public key (G..., 56 chars, base32).
isValidAssetCode-
isValidAmount-
isValidIso8601-
isValidUrl-
encodePaymentLinkEncode a payment link from components. Throws on invalid input.
decodePaymentLinkDecode a payment-link string into components, or a structured error.
createPaymentLinkCreate a v1 payment link from a meta-address and network.
isOpaquePaymentLinkTrue when the string parses as a valid opaque payment link.
convertLegacyLinkConvert a legacy https://host/pay/{metaAddress} link into opaque format.
scanAnnouncementsScan announcements for transfers to the recipient. Each candidate is view-tag prefiltered, then confirmed by reconstructing the one-time key and checking its stealth id equals the announced one (so a coincidental tag match is rejected).
parseFieldDefinitionsParse and validate "type name" comma-separated field definitions.
fieldDefsToCanonicalString-
encodeCanonicalFieldDefs-
addressToAuthorityBytes-
computeSchemaIdFromBytesCompute a schema id (SHA-256 of authority
computeSchemaId-
encodeAttestationDataEncode attestation payload bytes in schema field order.
decodeAttestationDataDecode canonical attestation bytes into a field-value map.
contractErrorNameLook up a contract error name for a code, if the SDK knows the enum.
computeWithdrawContextWithdrawal context binding: keccak256(recipient_xdr ‖ withdrawn(16) ‖ fee(16) ‖ relayer_xdr ‖ scope(8)) mod r.
provePoolWithdrawGenerate a full-withdrawal proof for note, paying recipient (minus fee to relayer). The caller supplies the reconstructed pool leaves: stateLeaves (commitment per state-tree index) and depositIndices (state index of each deposit, in ASP-tree order).
buildReputationWitnessV2Build the canonical V2 reputation witness for a holder's own attestation.
proveReputationV2Generate a V2 reputation proof and return a bundle ready for reputation.verifyOnChain / the reputation-verifier contract.
serializeGroth16Proof-
generateX25519Keypair-
sealBox-
openBox-
randomJobIdCryptographically random 32-byte job id.
buildRelayedWithdrawPayloadBuild the blind withdrawal payload. The pool fee is zero (the registry escrow pays the relayer) and the proof binds the registry as the pool relayer, so the payload hash is deterministic before a relayer is chosen.
buildRelayerJobDraft-
pickStakeWeightedBidStake-weighted random choice among verified bids.
makeAdvert-
bidSigningDigest-
makeBid-
verifyBid-
validateAdvert-
validateBid-
poolWithdrawPayloadPreimage-
hashPoolWithdrawPayload-
hashPoolWithdrawPayloadHex-
serializePoolWithdrawPayload-
parsePoolWithdrawPayload-
encodePoolWithdrawPayload-
decodePoolWithdrawPayload-
describeScErrorRender an ScError into a short token like ContractError#4 or sceBudget.
decodeDiagnosticsDecode an array of diagnostic events (XDR) into a compact, de-duplicated string. Bounded to keep error messages readable.
extractContractErrorCodeBest-effort extraction of a contract error code from diagnostic events. Returns the first ContractError#N code found, or null.
addressToScValStellar address (G/C-strkey) -> ScVal address.
bytesToScValRaw bytes -> ScVal bytes.
u32ToScValNumber/bigint -> ScVal u32.
u64ToScValNumber/bigint -> ScVal u64.
i128ToScValBigint -> ScVal i128 (Soroban's signed amount type).
u128ToScValBigint -> ScVal u128.
symbolToScValString -> ScVal symbol.
stringToScValString -> ScVal string.
boolToScValBoolean -> ScVal bool.
optionAddressToScValOptional address -> ScVal address, or a void ScVal when null/undefined.
fromScValDecode an ScVal into its native JS representation.
keypairSignerBuild a signer from a raw Ed25519 keypair (server / non-browser use). Accepts a Stellar secret seed (S...) or a Keypair instance.
callbackSignerBuild a signer from caller-supplied callbacks. Use this to adapt Freighter or any external signing service.

Released under the MIT License.