Skip to main content

Client Reference

What this does

This page documents the published Zkp2pClient API surface for @zkp2p/sdk. Use it as the reference layer for custom integrations after you have read the higher-level walkthroughs:

Constructor

Create a client with new Zkp2pClient(opts).

FieldRequiredDescription
walletClientYesviem WalletClient with an attached account for signing
chainIdYesChain ID used for contract and API routing
rpcUrlNoOptional RPC override; otherwise the SDK uses the wallet client's chain transport
runtimeEnvNoRuntime environment: production, preproduction, or staging. Defaults to production
indexerUrlNoOverride for the indexer GraphQL endpoint
baseApiUrlNoOverride for ZKP2P service APIs
apiKeyNoOptional curator API key — not required to get started. When provided, it enables auto-fetching signalIntent() gating signatures and enriches authenticated quote responses with maker payeeData
authorizationTokenNoOptional bearer token for hybrid authentication
getAuthorizationTokenNoAsync token provider for long-lived clients
indexerApiKeyNoOptional x-api-key header for indexer proxy authentication
timeouts.apiNoAPI timeout in milliseconds
import { Zkp2pClient } from '@zkp2p/sdk';

const client = new Zkp2pClient({
walletClient,
chainId: 8453,
});
No API key required

Most public SDK methods work without apiKey or authorizationToken. Auth credentials are optional for normal deposit, quote, and intent flows and mostly affect response richness. signalIntent() can auto-fetch its gating signature when you provide apiKey or authorizationToken; if you do not want the SDK to make that request, pass gatingServiceSignature and signatureExpiration yourself.

Service roots

Set baseApiUrl to the service root, for example https://api.zkp2p.xyz. Do not append /v1, /v2, or /v3; the SDK appends the current versioned paths internally.

Runtime requirements

The published 0.5.0 package declares node >= 22 for Node runtimes and viem ^2.37.3 as a peer dependency.

Prepared transactions

Most write methods are "prepareable":

  • Calling the method directly sends the transaction and returns a hash
  • Calling .prepare() on the same method returns a PreparedTransaction with { to, data, value, chainId }
const prepared = await client.signalIntent.prepare({
depositId: 42n,
amount: 100_000000n,
toAddress: '0xYourRecipientAddress',
processorName: 'wise',
payeeDetails: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',
fiatCurrencyCode: 'USD',
conversionRate: 1_020000000000000000n,
});

await relayer.submit({
to: prepared.to,
data: prepared.data,
value: prepared.value,
});

createDeposit() is the main exception because it may also post curator data. Use prepareCreateDeposit() when you need calldata without sending:

const { depositDetails, prepared } = await client.prepareCreateDeposit({
token: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
amount: 1_000_000000n,
intentAmountRange: { min: 10_000000n, max: 500_000000n },
processorNames: ['wise'],
payeeData: [{ offchainId: 'maker@example.com' }],
conversionRates: [[
{ currency: 'USD', conversionRate: '1020000000000000000' },
]],
});

Payee registration

Use registerPayeeDetails() when you want to register payment details first and reuse the returned hashes in a later createDeposit() call.

ParameterTypeDescription
processorNamesstring[]Payment platforms such as wise, revolut, or venmo
payeeDataArray<Record<string, string>>Processor-specific payment details in the same order as processorNames
depositDataArray<Record<string, string>>Deprecated alias for payeeData
const { hashedOnchainIds } = await client.registerPayeeDetails({
processorNames: ['wise', 'revolut'],
payeeData: [
{ offchainId: 'maker@example.com' },
{ offchainId: 'maker' },
],
});

await client.createDeposit({
token: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
amount: 1_000_000000n,
intentAmountRange: { min: 10_000000n, max: 500_000000n },
processorNames: ['wise', 'revolut'],
payeeData: [
{ offchainId: 'maker@example.com' },
{ offchainId: 'maker' },
],
conversionRates: [
[{ currency: 'USD', conversionRate: '1020000000000000000' }],
[{ currency: 'EUR', conversionRate: '950000000000000000' }],
],
payeeDetailsHashes: hashedOnchainIds,
});

Intent operations

signalIntent() / signalIntent.prepare()

Signals a taker-side intent and reserves liquidity from a deposit.

ParameterRequiredDescription
depositIdYesDeposit ID to use
amountYesToken amount in base units
toAddressYesRecipient address for the on-chain asset
processorNameYesPayment platform name
payeeDetailsYesHashed payee details for the deposit/payment method
fiatCurrencyCodeYesFiat currency such as USD or EUR
conversionRateYesAgreed conversion rate with 18 decimals
referralFeesNoMulti-recipient referral fee list
referrer / referrerFeeNoDeprecated legacy single-referrer fields
referrerFeeConfigNoOnramp-friendly referrer fee configuration
postIntentHookNoPost-intent hook contract address
preIntentHookDataNoData for a pre-intent hook
dataNoArbitrary bytes passed into hook-enabled flows
escrowAddressNoEscrow override when you want explicit routing
orchestratorAddressNoOrchestrator override
gatingServiceSignatureNoPre-obtained signature if you do not want SDK auto-fetching
signatureExpirationNoSignature expiration timestamp
txOverridesNoviem transaction overrides plus optional referrer code(s)

cancelIntent() / cancelIntent.prepare()

Cancels a signaled intent before fulfillment.

ParameterRequiredDescription
intentHashYes0x-prefixed 32-byte intent hash
orchestratorAddressNoExplicit orchestrator override
txOverridesNoviem transaction overrides

fulfillIntent() / fulfillIntent.prepare()

Fulfills a signaled intent with a payment proof. The SDK handles attestation encoding for you.

ParameterRequiredDescription
intentHashYes0x-prefixed 32-byte intent hash
proofYeszkTLS proof object/JSON string or a buyer TEE proof input
timestampBufferMsNoAllowed timestamp variance in milliseconds
attestationServiceUrlNoOverride for the attestation service
orchestratorAddressNoExplicit orchestrator override
postIntentHookDataNoHook payload passed to the orchestrator
txOverridesNoviem transaction overrides
callbacksNoUI lifecycle callbacks such as onAttestationStart, onAttestationComplete, onTxSent, and onTxMined
precomputedAttestationNoPre-encoded attestation data for advanced flows

releaseFundsToPayer() / releaseFundsToPayer.prepare()

Manual release path for returning reserved funds to the deposit owner when an intent should not be fulfilled.

ParameterRequiredDescription
intentHashYes0x-prefixed 32-byte intent hash
orchestratorAddressNoExplicit orchestrator override
txOverridesNoviem transaction overrides

Deposit hook controls

The V2 orchestrator lets deposit owners configure hooks around intent signaling.

MethodDescriptionKey parameters
setDepositPreIntentHook() / .prepare()Set the hook called before an intent is accepteddepositId, preIntentHook, escrowAddress?, orchestratorAddress?
getDepositPreIntentHook()Read the configured pre-intent hookdepositId, escrowAddress?, orchestratorAddress?
setDepositWhitelistHook() / .prepare()Set the whitelist hook for private orderbook or gated depositsdepositId, whitelistHook, escrowAddress?, orchestratorAddress?
getDepositWhitelistHook()Read the configured whitelist hookdepositId, escrowAddress?, orchestratorAddress?
cleanupOrphanedIntents() / .prepare()Permissionless cleanup for orphaned V2 intentsintentHashes, escrowAddress?, orchestratorAddress?

Vault and rate-manager operations

At the client layer, vaults are exposed as rate managers. These flows are most relevant when you are delegating deposits or managing shared pricing.

note

The 0.5.x client routes against EscrowV2 and OrchestratorV2. Pass explicit escrowAddress or orchestratorAddress only when targeting a configured V2 deployment.

Create a vault

Use createRateManager() to create a new vault.

FieldRequiredDescription
config.managerYesManager address
config.feeRecipientYesAddress that receives manager fees
config.maxFeeYesMaximum allowed fee
config.feeYesCurrent fee
config.depositHookNoOptional deposit hook contract
config.minLiquidityNoMinimum USDC liquidity required for delegation
config.nameYesHuman-readable name
config.uriYesMetadata URI
txOverridesNoviem transaction overrides

Delegation methods

Use one of the delegation paths below depending on how the deposit is routed.

MethodUse it whenKey parameters
setDepositRateManager()Delegating through the controller/registry pathescrow, depositId, registry, rateManagerId
clearDepositRateManager()Clearing controller-based delegationescrow, depositId
setRateManager()Writing directly to EscrowV2depositId, rateManagerAddress, rateManagerId, escrowAddress?
clearRateManager()Clearing direct EscrowV2 delegationdepositId, escrowAddress?

Vault configuration

MethodDescriptionKey parameters
setVaultFee()Update vault manager feerateManagerId, newFee
setVaultMinRate()Set floor rate for one payment method/currency pairrateManagerId, paymentMethodHash, currencyHash, rate
setVaultMinRatesBatch()Batch version of setVaultMinRate()rateManagerId, paymentMethods, currencies, rates
setVaultConfig()Update manager, fee recipient, hook, name, or URIrateManagerId, newManager, newFeeRecipient, newHook?, newName, newUri

Payment method management

MethodDescriptionKey parameters
addPaymentMethods()Add new payment platforms to an existing depositdepositId, paymentMethods, paymentMethodData, currencies
setPaymentMethodActive()Activate or deactivate a payment methoddepositId, paymentMethod, isActive
removePaymentMethod()Convenience alias for deactivating a payment methoddepositId, paymentMethod

Currency management

MethodDescriptionKey parameters
addCurrencies()Add currencies to an existing payment methoddepositId, paymentMethod, currencies
deactivateCurrency()Disable a currency for a payment methoddepositId, paymentMethod, currencyCode
removeCurrency()Alias for deactivateCurrency()depositId, paymentMethod, currencyCode

Rate-manager reads

MethodReturnsNotes
getDepositRateManager(escrow, depositId){ registry, rateManagerId }Reads current delegation state
getManagerFee(escrow, depositId)bigintReads the effective manager fee
getEffectiveRate({ escrow, depositId, paymentMethod, fiatCurrency })bigintReads effective EscrowV2 rate after manager logic

For EscrowV2 pricing flows, the client also exposes setOracleRateConfig(), removeOracleRateConfig(), setOracleRateConfigBatch(), updateCurrencyConfigBatch(), and deactivateCurrenciesBatch().

Quote API

Use getQuote(req, opts?) to fetch available liquidity for a taker flow.

Request fieldRequiredDescription
paymentPlatformsYesPlatforms to search, such as ['wise', 'revolut']
fiatCurrencyYesFiat currency code
userYesTaker address
recipientYesAsset recipient address
destinationChainIdYesDestination chain ID
destinationTokenYesDestination token address
amountYesAmount as a string
referrerNoReferrer code for quote attribution
referrerFeeConfigNoReferrer fee recipient and BPS
useMultihopNoEnable multihop routing
quotesToReturnNoLimit quote count
isExactFiatNoTreat amount as fiat instead of token amount
escrowAddressesNoLimit search to specific escrows
includeNearbyQuotesNoInclude nearby suggestions when no exact quote is available
nearbySearchRangeNoMax percent deviation for nearby quote search
nearbyQuotesCountNoNumber of nearby suggestions above and below
includePrivateOrderbooksNoInclude whitelist-gated private orderbook deposits scoped to the requesting user

The response includes:

  • responseObject.quotes: matched quotes
  • responseObject.nearbySuggestions: optional nearby matches when includeNearbyQuotes is enabled and no exact quote is available
  • signalIntentAmount: gross amount you should pass into signalIntent() when a referrer fee is applied
  • referrerFeeAmount: computed fee output for the supplied referrerFeeConfig
const quote = await client.getQuote({
paymentPlatforms: ['wise'],
fiatCurrency: 'USD',
user: '0xYourAddress',
recipient: '0xRecipientAddress',
destinationChainId: 8453,
destinationToken: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
amount: '100',
isExactFiat: true,
includeNearbyQuotes: true,
});

getQuotesBestByPlatform()

Use getQuotesBestByPlatform(req, opts?) when you want the single best quote per supported payment platform instead of a flat list. The SDK calls /v2/quote/best-by-platform (or /v2/quote/best-by-platform-exact-token when isExactFiat is false) and returns one entry per platform with maker payeeData enriched into each bestQuote.

Request fieldRequiredDescription
fiatCurrencyYesFiat currency code
userYesTaker address
recipientYesAsset recipient address
destinationChainIdYesDestination chain ID
destinationTokenYesDestination token address
amountYesAmount as a string
isExactFiatNoTreat amount as fiat instead of token amount. Defaults to true
referrerNoReferrer code for quote attribution
referrerFeeConfigNoReferrer fee recipient and BPS
escrowAddressesNoLimit search to specific escrows. Defaults to the client's configured escrows
minDepositSuccessRateBpsNoMinimum maker success rate in basis points (0-10000)
supportBusinessAccountsNoAllow quotes from business accounts
intentGatingServiceNoFilter by a specific intent gating service address
includePrivateOrderbooksNoInclude whitelist-gated private orderbook deposits. Defaults to false

The response shape mirrors getQuote but is keyed by platform:

  • responseObject.platformQuotes: array of { platform, bestQuote } entries
  • responseObject.quoteExpiresAt: quote expiration timestamp
  • Each bestQuote carries the same referrerFeeAmount / display fields as getQuote when a referrerFeeConfig is supplied
const best = await client.getQuotesBestByPlatform({
fiatCurrency: 'USD',
user: '0xYourAddress',
recipient: '0xRecipientAddress',
destinationChainId: 8453,
destinationToken: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
amount: '100',
isExactFiat: true,
});

for (const { platform, bestQuote } of best.responseObject?.platformQuotes ?? []) {
console.log(platform, bestQuote?.intent?.depositId, bestQuote?.payeeData);
}

Taker tiers

Use getTakerTier(req, opts?) to fetch tiering, cooldown, and platform-limit data for a taker address.

Request fieldRequiredDescription
ownerYesTaker address
chainIdYesChain ID for tier evaluation

The response object includes:

  • tier: one of PEASANT, PEER, PLUS, PRO, PLATINUM, or PEER_PRESIDENT
  • perIntentCapBaseUnits and perIntentCapDisplay
  • cooldown metadata such as cooldownHours, cooldownActive, and nextIntentAvailableAt
  • platformLimits, including risk level and minimum required tier per payment platform

Seller Autopilot

Use these methods to upload seller credentials, inspect credential status, and verify seller payments for Seller Autopilot flows. Supported seller platforms are venmo, cashapp, wise, and paypal.

uploadSellerCredential()

Use uploadSellerCredential(params, opts?) to create a signed credential bundle through the attestation service and store the public credential status in curator. Returns CuratorSellerCredentialUploadResponse.

For registered payee platforms (venmo, cashapp, and paypal), pass the seller identity plus platform-specific session material:

FieldRequiredDescription
platformYesvenmo, cashapp, or paypal
offchainIdYesStable seller identity used for payee registration
payeeIdYesPlatform payee identifier
telegramUsernameNoOptional seller Telegram username
metadataNoOptional curator metadata
sessionMaterialYesPlatform-specific session material

For Wise, pass only the platform and Wise session material. The enclave derives the payee hash from the submitted token:

FieldRequiredDescription
platformYeswise
sessionMaterial.apiTokenYesWise Personal API Token
sessionMaterial.profileIdNoWise profile identifier. If omitted and multiple profiles exist, handle the profile-selection response

Optional opts fields:

FieldRequiredDescription
baseApiUrlNoOverride for the curator base API URL
attestationServiceUrlNoOverride for the attestation service used to sign the credential bundle
timeoutMsNoRequest timeout in milliseconds
attestationRuntimeNoRuntime overrides for fetch, subtle, or getRandomValues

VenmoSessionMaterial

FieldRequiredDescription
recipientUsernameYesVenmo username that receives the seller payment
accountIdYesVenmo account identifier
sessionCookieYesAuthenticated Venmo session cookie
requestHeadersNoOptional request headers captured from the authenticated session

CashAppSessionMaterial

FieldRequiredDescription
recipientCashtagYesCash App cashtag that receives the seller payment
customerIdYesCash App customer identifier
sessionCookieYesAuthenticated Cash App session cookie
requestHeadersNoOptional request headers captured from the authenticated session
requestPayloadYesCaptured Cash App request payload used during verification

WiseSessionMaterial

FieldRequiredDescription
apiTokenYesWise API token
profileIdNoWise profile identifier

PayPalSessionMaterial

FieldRequiredDescription
payeeEmailYesPayPal seller email
forwardingBaseMailboxYesGmail forwarding base mailbox
forwardingMailboxAliasYesPer-seller forwarding alias
import { Zkp2pClient } from '@zkp2p/sdk';

const client = new Zkp2pClient({
walletClient,
chainId: 8453,
});

const response = await client.uploadSellerCredential(
{
platform: 'venmo',
offchainId: 'peer-seller',
payeeId: '123456789',
sessionMaterial: {
recipientUsername: 'peer-seller',
accountId: '123456789',
sessionCookie: 'session_cookie',
requestHeaders: {
'user-agent': 'Mozilla/5.0',
},
},
},
{ timeoutMs: 10_000 },
);

uploadSellerCredentialBundle()

Use uploadSellerCredentialBundle(params, opts?) when the encrypted credential bundle was already created elsewhere — typically inside a capture extension via apiCreateSellerCredentialBundle() — and you only need to register the payee and store the bundle with curator. This is the page-side half of the extension Seller Autopilot capture flow. Available from 0.5.0.

For registered payee platforms (venmo, cashapp, and paypal):

FieldRequiredDescription
platformYesvenmo, cashapp, or paypal
offchainIdYesStable seller identity used for payee registration
bundleYesEncrypted SellerCredentialBundle returned by the capture
telegramUsernameNoOptional seller Telegram username
metadataNoOptional curator metadata

For Wise, pass only platform: 'wise' and the bundle. Optional opts fields are baseApiUrl and timeoutMs.

const response = await client.uploadSellerCredentialBundle({
platform: 'venmo',
offchainId: capture.offchainId,
bundle: capture.credentialBundle,
});

confirmPayPalForwarding()

Use confirmPayPalForwarding(params, opts?) after a PayPal seller has configured Gmail forwarding. The SDK forwards any configured apiKey or bearer token to curator.

FieldRequiredDescription
payeeDetailsYesHashed payee details for the PayPal maker
payeeEmailYesPayPal seller email
forwardingInitiatorEmailYesGmail account that initiated forwarding

The package exports PayPalForwardingConfirmationErrorCode for UI-specific handling of rejected, expired, missing, or mismatched forwarding confirmations.

uploadGoogleOAuthSellerCredential()

Use uploadGoogleOAuthSellerCredential(params, opts?) when curator owns the Google OAuth encryption hop for PayPal or Venmo credentials.

FieldRequiredDescription
platformYespaypal or venmo
authorizationCodeYesOne-time Google OAuth code
payeeDetailsYesHashed payee details
redirectUriYesOAuth redirect URI used to obtain the code
payeeEmailPayPal onlyPayPal seller email
accountIdVenmo onlyVenmo account identifier

getSellerCredentialStatus()

Use getSellerCredentialStatus(params, opts?) to fetch public seller credential status from curator. Returns CuratorSellerCredentialStatusResponse.

FieldRequiredDescription
processorNameYesSeller payment platform: venmo, cashapp, wise, or paypal
payeeDetailsYesHashed payee details bytes32

Optional opts fields:

FieldRequiredDescription
baseApiUrlNoOverride for the curator base API URL
timeoutMsNoRequest timeout in milliseconds
import { Zkp2pClient } from '@zkp2p/sdk';

const client = new Zkp2pClient({
walletClient,
chainId: 8453,
});

const response = await client.getSellerCredentialStatus(
{
processorName: 'paypal',
payeeDetails: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',
},
{ timeoutMs: 10_000 },
);

verifySellerPayment()

Use verifySellerPayment(params, opts?) to verify a seller payment through curator's seller-credential proxy. Returns CuratorSellerVerifyResponse.

Internal-only authentication

verifySellerPayment() requires curator's internal x-api-key, not standard SDK consumer keys. It returns 410 GONE when the seller credential is inactive or fails a re-probe.

FieldRequiredDescription
platformYesSeller payment platform: venmo, cashapp, wise, or paypal
txIdYesPayment transaction identifier to verify
chainIdYesChain ID associated with the verification request
intentYesSellerVerifyIntentDetails payload for the seller payment verification

Optional opts fields:

FieldRequiredDescription
baseApiUrlNoOverride for the curator base API URL
timeoutMsNoRequest timeout in milliseconds
import {
Zkp2pClient,
type SellerVerifyIntentDetails,
} from '@zkp2p/sdk';

declare const sellerVerifyIntentDetails: SellerVerifyIntentDetails;

const client = new Zkp2pClient({
walletClient,
chainId: 8453,
});

const response = await client.verifySellerPayment(
{
platform: 'wise',
txId: 'transfer_123',
chainId: 8453,
intent: sellerVerifyIntentDetails,
},
{ timeoutMs: 10_000 },
);

Standalone API and attestation helpers

The package also exports low-level helpers for integrations that call service APIs directly instead of going through Zkp2pClient.

HelperPurpose
apiGetOrderbook(params, opts)Fetch orderbook entries for a fiat currency, optional platform, sort, limit, chain, and token
apiGetDepositBundle(params, opts)Fetch one deposit with related intents, events, profit snapshots, fund activities, and daily snapshots
apiValidatePayeeDetails(req, baseApiUrl, timeoutMs?)Validate a payee identity before registration
apiGetPayeeDetails(req, apiKey, baseApiUrl, authToken?, timeoutMs?)Resolve curator payee details from a hashed on-chain ID
apiGetOwnerDeposits(req, apiKey, baseApiUrl, authToken?, timeoutMs?)Fetch owner deposits from the service API
apiRequestIdentityAttestation(payload, attestationServiceUrl, platform, actionType)Request a maker identity attestation
createEncryptedBuyerTeeSessionMaterial(input)Encrypt buyer TEE session material for a buyer-payment proof
apiCreateSellerCredentialBundle(payload, attestationServiceUrl, platform, timeoutMs?, runtime?)Create a signed seller credential bundle directly through attestation service

apiGetOrderbook() accepts { currency, paymentPlatform?, sortBy?, sortDirection?, limit?, chainId?, token? }. apiGetDepositBundle() accepts { depositId, escrowAddress, dailySnapshotLimit? }.

Querying on-chain data

For common read flows, start with the RPC-first methods:

  • getDeposits()
  • getAccountDeposits(owner)
  • getDeposit(depositId)
  • getDepositsById(ids)
  • getIntents()
  • getAccountIntents(owner)
  • getIntent(intentHash)
  • getPvDepositById(depositId)
  • getPvDepositsFromIds(ids)
  • getPvAccountDeposits(owner)
  • getPvAccountIntents(owner)
  • getPvIntent(intentHash)
  • resolvePayeeHash(depositId, paymentMethodHash)
  • getFulfillIntentInputs(intentHash)
  • getDepositPreIntentHook(depositId, options?)
  • getDepositWhitelistHook(depositId, options?)
  • getDeployedAddresses()
  • getUsdcAddress()

For copy-paste examples around deposits and intents, see Offramp Integration.

Indexer

Use client.indexer when you need historical data, richer filtering, or pagination across all deposits and intents. All methods live on a flat namespace.

Deposit queries

  • getDeposits(filter?, pagination?)
  • getDepositsWithRelations(filter?, pagination?, options?)
  • getDepositById(compositeId, options?)
  • getDepositsByIds(ids)
  • getDepositsByIdsWithRelations(ids, options?)
  • getDepositsByPayeeHash(payeeHash, options?)

Intent queries

  • getIntentsForDeposits(depositIds, statuses?)
  • getOwnerIntents(owner, statuses?)
  • getIntentsByRateManager(rateManagerId, statuses?)
  • getIntentByHash(intentHash)
  • getExpiredIntents({ now, depositIds, limit? })
  • getFulfilledIntentEvents(intentHashes) — fulfillment events, including takerAmountNetFees
  • getIntentFulfillmentAmounts(intentHash) — includes takerAmountNetFees, the net USDC the taker received after fees
  • getFulfillmentAndPayment(intentHash)

Fund activity and snapshots

  • getDepositFundActivities(depositId)
  • getMakerFundActivities(depositor, limit?)
  • getDepositDailySnapshots(depositId, limit?)
  • getProfitSnapshotsByDeposits(depositIds)

Rate manager (vault) queries

  • getRateManagers(pagination?, filter?)
  • getRateManagerDetail(managerId, options?)
  • getRateManagerDelegations(managerId, pagination?)
  • getDelegationForDeposit(depositId, options?)
  • getManagerDailySnapshots(managerId, options?)
  • getManualRateUpdates(managerId, options?)
  • getOracleConfigUpdates(managerId, options?)

Raw access

  • query<T>({ query, variables? }) — raw GraphQL
  • client — raw IndexerClient instance

The package also exports IndexerRateManagerService and the standalone helper fetchIndexerFulfillmentAndPayment(client.indexer.client, intentHash).

Indexer converters

The SDK exports converter helpers for turning indexer payloads into the same EscrowDepositView shape produced by RPC reads.

HelperPurpose
convertIndexerDepositToEscrowView(deposit, chainId, escrowAddress)Converts a single indexer deposit (with relations) into an EscrowDepositView
convertDepositsForLiquidity(deposits, chainId, escrowAddress, options?)Filters and converts indexer deposits into the active liquidity set used by takers. Pass { includePrivateOrderbooks: true } to also include deposits gated by a non-zero whitelist hook (defaults to false, public orderbooks only)
convertIndexerIntentsToEscrowViews(intents, depositViewsById)Converts indexer intents into EscrowIntentView[]

Oracle helpers

The SDK exports helper constants and encoders for oracle-backed ARM spread pricing.

HelperPurpose
getSpreadOracleConfig(currency, adapters?)Resolve bundled Chainlink-first oracle config for a fiat currency
encodeSpreadOracleAdapterConfig(config)Encode Chainlink adapter config
encodePythAdapterConfig(config)Encode Pyth adapter config
validateOracleFeedsOnChain(publicClient, pythContract?)Return currencies whose bundled feeds are available on-chain
supportsInlineOracleRateConfig({ escrowAddress? })Client method that reports whether the target Escrow ABI accepts inline oracle configs

Useful constants include CHAINLINK_ORACLE_ADAPTER, PYTH_ORACLE_ADAPTER, DEFAULT_ORACLE_MAX_STALENESS_SECONDS, CHAINLINK_ORACLE_FEEDS, SPREAD_ORACLE_FEEDS, and PYTH_ORACLE_FEEDS.

Referrer fees

Use these helpers when you want to validate or normalize referrer fee settings before calling getQuote() or signalIntent().

HelperPurpose
assertValidReferrerFeeConfig(config, context)Throws if the config is invalid for getQuote, getQuotesBestByPlatform, or signalIntent
isValidReferrerFeeRecipient(value)Checks whether a referrer fee recipient is a valid address
isValidReferrerFeeBps(value)Checks whether a BPS value is allowed
parseReferrerFeeConfig(recipient, feeBpsValue)Builds a ReferrerFeeConfig from loosely typed input
referrerFeeConfigToPreciseUnits(config)Converts the fee config into precise units for on-chain use

Attribution

The SDK includes ERC-8021 helpers for Base builder attribution.

HelperPurpose
getAttributionDataSuffix(referrer?)Builds the attribution suffix
appendAttributionToCalldata(calldata, referrer?)Appends attribution to existing calldata
encodeWithAttribution(request, referrer?)Encodes calldata and appends attribution in one step
sendTransactionWithAttribution(walletClient, request, referrer?, overrides?)Sends a transaction with appended attribution

Useful constants:

  • BASE_BUILDER_CODE
  • ZKP2P_IOS_REFERRER
  • ZKP2P_ANDROID_REFERRER

Contract helpers

HelperDescription
getContracts(chainId, env?)Returns deployed addresses and ABIs for escrow, orchestrator, verifier, ProtocolViewer, USDC, and related contracts
getRateManagerContracts(chainId, env?)Returns rate-manager registry/controller addresses and ABIs
getPaymentMethodsCatalog(chainId, env?)Returns the platform-to-hash catalog used for payment-method resolution
getGatingServiceAddress(chainId, env?)Returns the signer used for intent gating

Common companion helpers:

  • currencyInfo
  • getCurrencyInfoFromHash()
  • getCurrencyInfoFromCountryCode()
  • resolveFiatCurrencyBytes32()
  • resolvePaymentMethodHash()
  • resolvePaymentMethodHashFromCatalog()
  • resolvePaymentMethodNameFromHash()

Error handling

All SDK-specific errors extend ZKP2PError.

ClassCodeExtra fieldsUse it for
ZKP2PErrorAny ErrorCodedetails?, field?Shared base class
ValidationErrorVALIDATIONfield?, details?Invalid input
NetworkErrorNETWORKdetails?RPC or network failures
APIErrorAPIstatus?, details?Failed API requests
ContractErrorCONTRACTdetails?Contract call or simulation failures

Available error codes: VALIDATION, NETWORK, API, CONTRACT, UNKNOWN.

import {
APIError,
ContractError,
ValidationError,
ZKP2PError,
} from '@zkp2p/sdk';

try {
await client.createDeposit({ /* ... */ });
} catch (error) {
if (error instanceof ValidationError) {
console.error(error.field, error.message);
} else if (error instanceof APIError) {
console.error(error.status, error.message);
} else if (error instanceof ContractError) {
console.error(error.details);
} else if (error instanceof ZKP2PError) {
console.error(error.code, error.message);
}
}

Logging

Use setLogLevel() to adjust SDK logging.

import { setLogLevel } from '@zkp2p/sdk';

setLogLevel('debug'); // 'debug' | 'info' | 'error'

Help?

If you run into issues, join our Discord.