@zkp2p/sdk
v0.17.0
Published
Peer SDK - sell USDC for fiat with peer.sell(), buy USDC with peer.buy(), and the lower-level ZKP2P client for deposits, intents and liquidity
Readme
@zkp2p/sdk
TypeScript SDK for the Peer protocol on Base. createPeer() sells USDC for fiat with peer.sell() and buys USDC with peer.buy(). The lower-level Zkp2pClient creates and manages USDC deposits, quote liquidity, signal and fulfill intents, and run vault, staking, referral, and Seller Autopilot flows.
New intents use EscrowV2 and OrchestratorV4. The SDK retains reads for historical OrchestratorV3 intents. See the client reference.
Installation
npm install @zkp2p/sdk viemVersion 0.17.0 on npm’s latest tag includes createPeer(), with peer.sell() premiums and prepareSpeedUp(), including its rate-only { fund: false } option, and supports the UnifiedPaymentVerifierV5 and DisputeVerifierV2 stack on Base and Base staging. viem ^2.37.3 is a peer dependency. React (>=16.8.0) is optional and only needed for @zkp2p/sdk/react. Node.js runtimes need version 22 or later.
Peer quickstart
Sell Base USDC
import { createPeer, isPeerError, usdc } from '@zkp2p/sdk';
import { createWalletClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { base } from 'viem/chains';
const signer = createWalletClient({
account: privateKeyToAccount('0x...'),
chain: base,
transport: http(),
});
const peer = createPeer({ environment: 'production' });
try {
const sale = await peer.sell(
{ amount: usdc('25'), receive: { platform: 'venmo', currency: 'USD', payee: '@alice' } },
{ signer },
);
// Persist sale.depositId: it resumes order(), watch() and withdraw() later.
for await (const order of peer.sell.watch(sale.depositId)) {
console.log(order.state, order.explain());
}
} catch (err) {
if (isPeerError(err)) console.error(err.code, err.remediation);
else throw err;
}peer.sell() registers the payee, approves and deposits the USDC at the zero-spread oracle market rate, and returns once the deposit confirms. watch() yields awaiting-buyer, matched and delivering until the sale ends delivered or returned. peer.sell.capabilities() lists each platform's currencies and payee format. Curator checks that the handle exists on its platform, PayPal.Me usernames and Wisetags included (PAYEE_NOT_FOUND otherwise); a new Alipay payee needs a signed identity attestation (PAYEE_VERIFICATION_REQUIRED). Use peer.sell.prepare() for unsigned transactions, and peer.sell.withdraw(depositId, { signer }) to take back unsold USDC.
Sell another asset (Relay)
const peer = createPeer({
environment: 'production',
relay: { apiKey: process.env.RELAY_API_KEY },
});
const { chains } = await peer.sell.sourceCapabilities(); // source chains and tokens Relay can route
const quote = await peer.sell.quoteSource({
user: signer.account.address,
amount: 5_000_000n, // source-token base units
source: { chainId: 10, currency: '0x0b2c639c533813f4aa9d7837caf62653d097ff85' }, // USDC on Optimism
});
// Send quote.txs from the source-chain wallet, then follow the route:
const status = await peer.sell.relayStatus(quote.requestId!);
// Once it succeeds, sell the Base USDC: peer.sell({ amount: quote.outputAmount, receive }, { signer })quoteSource() only returns routes that deliver canonical Base USDC to the requested recipient from the requested wallet and asset; outputAmount is Relay's guaranteed minimum. Relay's quote endpoint requires an API key.
Buy Base USDC
const peer = createPeer({ environment: 'production', getAuthorizationToken: getAccessToken });
const [offer] = await peer.buy.quote({
platforms: ['venmo'],
currency: 'USD',
amount: { fiat: usdc('50') }, // or { usdc: usdc('50') } for an exact USDC amount
recipient: signer.account.address,
});
const { intentHash } = await peer.buy(offer, { signer }); // locks the seller's USDC
const { payee } = await peer.buy.payment(intentHash); // pay this Venmo user off-platform
await peer.buy.complete({ intentHash, proof }, { signer }); // proof from the PeerAuth extensiongetAuthorizationToken returns the buyer's Privy access token (for example Privy's getAccessToken) for an account linked to signer; Curator's intent signing and payee reveal use it, and the buyer's payment identity must be enrolled for the rail when Curator requires it. A failure before broadcast rejects with TRANSACTION_PREPARATION_FAILED and is safe to retry. After TRANSACTION_SUBMISSION_UNKNOWN or TRANSACTION_STATUS_UNKNOWN, the intent may already exist: check the buyer's open intents before calling peer.buy() again. Each offer carries its fiat and USDC amounts, expiresAt, and whether Curator requires dispute-protection stake.
Quick start
import { Zkp2pClient } from '@zkp2p/sdk';
import { createWalletClient, http } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { base } from 'viem/chains';
const account = privateKeyToAccount('0x...');
const walletClient = createWalletClient({ account, chain: base, transport: http() });
const client = new Zkp2pClient({
walletClient,
chainId: base.id,
baseApiUrl: 'https://api.zkp2p.xyz',
});Set baseApiUrl so signalIntent() can fetch gating signatures from Peer's API. For browser signing, pass Privy's getAccessToken as getAuthorizationToken and use a wallet linked to that user. Servers can sign each API request with the customer's wallet and pass the returned gating signature to the SDK.
Maker registration through registerPayeeDetails() and deposit preparation also sends the current token, or authorizationToken when no getter is configured, along with apiHeaders. New makers can still register anonymously; updating an existing maker requires its owner's Privy token. An x-pp-key header skips automatic bearer lookup. Standalone apiPostDepositDetails(request, baseApiUrl, timeoutMs?, authorizationToken?, headers?) accepts the same optional auth and headers.
When payment-account verification is required, first check authenticated GET /v3/identity?platform=<rail>&callerAddress=<wallet>. If unverified, obtain the attestation service's canonical signed /identity output and submit it unchanged as { identityAttestation } to authenticated POST /v3/identity. Curator checks persisted verification on every public signing request; an expired, revoked, or unavailable identity must stop the purchase. Browser clients use their Privy access token on both identity endpoints. Servers use the wallet-signature headers described in the server-side guide. Trusted Peer Pay integrations retain their existing x-pp-key signing path without requesting a Privy token.
Create a deposit
const usdc = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
const amount = 1_000_000000n; // 1,000 USDC
const approval = await client.ensureAllowance({ token: usdc, amount });
// When approval.hadAllowance is false, wait for approval.hash to confirm.
const { hash } = await client.createDeposit({
token: usdc,
amount,
intentAmountRange: { min: 10_000000n, max: 500_000000n },
processorNames: ['revolut'],
payeeData: [{ offchainId: 'your-revtag' }],
conversionRates: [[{ currency: 'USD', conversionRate: '1020000000000000000' }]], // 1.02
});Manage the deposit with addFunds, removeFunds, setAcceptingIntents, setIntentRange, setCurrencyMinRate, and withdrawDeposit.
Quote, signal, and fulfill
const quote = await client.getQuote({
paymentPlatforms: ['wise'],
fiatCurrency: 'USD',
user: account.address,
recipient: account.address,
destinationChainId: 8453,
destinationToken: usdc,
amount: '250000000', // 250 USD, in 6-decimal units
});
const [best] = quote.responseObject.quotes;
const signalTxHash = await client.signalIntent({
depositId: BigInt(best.intent.depositId),
amount: best.signalIntentAmount ?? best.intent.amount,
toAddress: account.address,
processorName: best.intent.processorName,
payeeDetails: best.intent.payeeDetails,
fiatCurrencyCode: 'USD',
conversionRate: best.conversionRate,
});
// After the fiat payment, prove it with a Buyer TEE proof.
await client.fulfillIntent({
intentHash,
proof: { proofType: 'buyerTee', encryptedSessionMaterial, params },
});signalIntent() returns the transaction hash; read intentHash from its IntentSignaled event. To capture the payment proof in a web app, see Onramp Integration.
Most write methods also have .prepare(), which returns { to, data, value, chainId } for relayers, smart accounts, and batching. Deposits use prepareCreateDeposit().
Venmo and X Money receipt linking
openVenmoGmailConnect() opens Peer's hosted page, where a seller links Gmail, personal Outlook, or iCloud Mail to a registered Venmo payee for Seller Autopilot. Your app never receives OAuth codes, passwords, tokens, or email contents. Call it directly from a click handler:
import { openVenmoGmailConnect, VenmoGmailConnectError } from '@zkp2p/sdk';
try {
await openVenmoGmailConnect({ payeeDetails });
} catch (error) {
if (error instanceof VenmoGmailConnectError) console.error(error.code, error.message);
}A closed or timed-out window doesn't mean linking failed, and a return doesn't prove it worked. Read client.getSellerCredentialStatus({ processorName: 'venmo', payeeDetails }): the inbox is linked only when status is active and isMailboxSellerCredentialType(credentialType) is true.
openXMoneyConnect({ payeeDetails, payeeUsername }) and getXMoneyConnectUrl() do the same for X Money. For a peer.sell() app, see optional receipt linking. See the client reference for error codes and options.
Native app return
Native apps build the page URL and open it in a system browser session:
import { getVenmoGmailConnectUrl } from '@zkp2p/sdk';
import * as WebBrowser from 'expo-web-browser';
const returnUrl = 'partner-app://venmo-linked'; // a scheme registered in your app binary
const connectUrl = getVenmoGmailConnectUrl({ payeeDetails, returnUrl });
await WebBrowser.openAuthSessionAsync(connectUrl, returnUrl);
// Check the credential status after return or dismissal.After a successful link, the page opens returnUrl unchanged; it adds no codes, tokens, or status. Without returnUrl, the page tries to close itself. Without the SDK, build the URL as https://app.peer.xyz/connect/venmo?returnUrl=<URL-encoded callback>#<payeeDetails>.
Popup customization
Pass appearance to any of the hosted-page helpers, and popup to the browser openers:
await openVenmoGmailConnect({
payeeDetails,
popup: { width: 500, height: 620 },
appearance: {
logoUrl: 'https://your-app.example/logo.png',
logoAlt: 'Your app',
backgroundColor: '#FFFFFF',
textColor: '#172033',
buttonColor: '#6246EA',
buttonTextColor: '#FFFFFF',
fontFamily: 'Arial, sans-serif',
buttonBorderRadius: 24,
},
});Colors take #RGB or #RRGGBB: backgroundColor, cardBackgroundColor, textColor, secondaryTextColor, buttonColor, buttonTextColor, buttonHoverColor, focusColor, borderColor, successColor, errorColor, logoBackgroundColor, and logoBorderColor.
| Option | Accepted values |
| --------------------------------------------- | ----------------------------------------------------- |
| fontSize | 12 to 24 px |
| headingFontSize | 20 to 48 px |
| buttonBorderRadius, cardBorderRadius | 0 to 40 px |
| buttonHeight | 44 to 80 px |
| contentWidth | 280 to 960 px |
| padding | 16 to 64 px |
| gap | 12 to 48 px |
| logoHeight | 24 to 80 px |
| fontFamily, headingFontFamily | A font-family list |
| fontUrl | A hosted WOFF or WOFF2 file; its host must allow CORS |
| logoUrl, logoAlt | Your logo URL and its alt text (up to 80 characters) |
| headingTextTransform, buttonTextTransform | none or uppercase |
popup takes width from 320 to 1200 px and height from 480 to 1600 px; the default is 500 by 700. Mobile browsers open a tab instead. Asset URLs must use HTTPS, except on localhost. Invalid options throw ValidationError before the window opens. Google and Microsoft consent screens keep their own styling.
Deposit access policy
client.accessPolicy reads deposit whitelists and prepares the depositor's transactions to turn a whitelist off or remove entries. See the client reference.
React hooks
import { useSignalIntent } from '@zkp2p/sdk/react';
const { signalIntent, prepareSignalIntent, isLoading, error, txHash } = useSignalIntent({ client });Hooks cover deposits, intents, payment methods, currencies, delegation, vaults, and intent lifetime extension. See React Hooks.
Errors and logging
SDK errors extend ZKP2PError (ValidationError, NetworkError, APIError, and ContractError) and carry a code. Call setLogLevel('debug') for verbose logs.
Documentation
- Sell USDC with the Peer SDK
- Migrate from @zkp2p/cash
- SDK overview
- Client reference
- React hooks
- Offramp integration
- Onramp integration
- React Native SDK
Publishing
Maintainers bump the version and changelog in a PR, merge to main, then run
gh workflow run publish-sdk.yml --ref main -f version=X.Y.Z and verify the run
and npm tags. Publication uses GitHub OIDC in npm-publish; local npm publish
is rejected by npm. See PUBLISHING.md for setup, prerelease tags,
and human passkey-2FA promotion of existing versions.
License
MIT
