Skip to main content

Sell Integration Guide

This guide takes a peer.sell() integration from discovery to order recovery. If you are choosing between peer.sell() and the lower-level client, read Sell USDC with the Peer SDK first.

Prerequisites​

  • @zkp2p/sdk@0.16.0-rc.1 and viem ^2.37.3
  • Node 22 or newer for a Node runtime
  • A Base RPC endpoint
  • A Base wallet that holds the USDC to sell
  • A valid payee handle for the chosen payment platform

Test with a small, separately funded wallet. Never put a private key in client-side code or commit one to source control.

1. Create the client​

import { createPeer } from "@zkp2p/sdk";
import { http } from "viem";

const peer = createPeer({
environment: "production",
transport: http("https://your-base-rpc.example"),
referrer: "your-analytics-code",
});

environment selects the matching contracts, indexer, and Peer API: production for live sales, staging or preproduction for testing. transport (or rpcUrl) sets the Base RPC for reads and defaults to the public Base RPC. indexerUrl, indexerApiKey, curatorUrl, and apiKey override the environment's services.

The client reads without a signer. Each signed method takes a viem WalletClient as { signer }, so signing and user approval stay in the system that owns them. Sales register payees anonymously; getAuthorizationToken is used only by peer.buy.

Earn from the flow you bring​

Pass the six-character code from the referral screen in the Peer web or mobile app as referralCode. You need no API key, registration transaction, or second wallet.

const peer = createPeer({
environment: "production",
referralCode: "ABC123",
});
  • The SDK adds peer-ref-ABC123 to the ERC-8021 attribution of every sale transaction it prepares or signs.
  • When liquidity from that deposit fills, Peer pays the code owner 50 bps, capped by Peer's service fee. The user pays no extra fee.
  • The share replaces the maker's Level 1/Level 2 referral split for that deposit. Deposits without a code keep that split.
  • The code stays bound to the same Peer account if you rename it later, so open deposits keep paying the same wallet. View earnings or rename the code on the same referral screen.
  • A malformed code throws INVALID_REFERRAL_CODE when you create the client. A transaction with an unknown code or more than one peer-ref- marker earns no share.
  • referrer adds analytics-only attribution codes, such as your-app. It never selects a fee recipient.

Show your brand on your deposits​

Pass a label and a hosted logo as brand. Peer's order books show both on the deposits this client creates.

const peer = createPeer({
environment: "production",
brand: {
label: "Acme payouts",
logoUrl: "https://acme.example/logo.png",
},
});
  • The SDK adds one ERC-8021 code, peer-brand:Acme payouts|https://acme.example/logo.png, to every sale transaction it prepares or signs. You register nothing with Peer and need no API key.
  • The label is 1 to 32 letters, numbers, single spaces, or . & ' -.
  • The logo is an https:// URL without commas, pipes, spaces, or credentials. Host a small square image; Peer loads it from that URL.
  • All attribution codes together must fit in 255 bytes, so keep the URL short. An invalid brand throws INVALID_BRAND when you create the client.
  • The brand is written with the transaction that creates the deposit, so a deposit keeps the label and URL it was created with. To change the picture later, replace the image at the same URL.
  • The brand is display only. It doesn't verify who created a deposit, and it doesn't change fees or matching.

2. Discover the live product boundary​

Don't hardcode payment platforms, currencies, payee formats, or amount limits.

const capabilities = peer.sell.capabilities();

for (const platform of capabilities.platforms) {
console.log({
id: platform.platform,
currencies: platform.currencies,
payeeHint: platform.payeeHint,
requiresIdentityAttestation: platform.requiresIdentityAttestation,
});
}

console.log(capabilities.amount); // { min, recommendedMin, max: null } in USDC base units
console.log(capabilities.pricing); // { kind: "oracle-market-rate", spreadBps: 0 }

capabilities() is synchronous and makes no network call. Every sale is Base USDC in and fiat out.

Payee verification​

Peer's API validates payee data when the sale registers the payee, before any approval or deposit.

PlatformNew payee registration
Venmo, Revolut, Cash App, MonzoChecked against the live platform. An account that doesn't exist fails with PAYEE_NOT_FOUND.
PayPal, WiseChecked against the live platform. PayPal takes the PayPal.Me username, not the account email; Wise takes a personal Wisetag that Wise can find. Otherwise PAYEE_NOT_FOUND.
AlipayNeeds a signed identity attestation that the SDK cannot create (requiresIdentityAttestation: true). A handle already registered through Peer can be reused. A new handle fails with PAYEE_VERIFICATION_REQUIRED before funds move.
UPIAny valid UPI ID from any bank. No bank login, identity attestation, extension, or prior registration. Buyers pay through Amazon Pay.
X MoneySee X Money sales.
Other platformsFormat-checked. Follow payeeHint.

Shape input with payeeHint and handle PAYEE_NOT_FOUND and PAYEE_VERIFICATION_REQUIRED. Don't hide Alipay outright: an existing registration still works.

X Money sales​

X Money pays out in USD:

const receive = {
platform: "xmoney",
currency: "USD",
payee: "@YourHandle",
} as const;

Raw string payees are trimmed, lowercased, and stripped of one leading @. Structured payee data must already use offchainId: "yourhandle". Registration doesn't check X Money enrollment, so confirm the receiving account has X Money enabled. No identity attestation is required.

Optional receipt linking​

Venmo and X Money sellers can link the inbox that receives their payment receipts on a page Peer hosts. Offer it as a separate, optional step: peer.sell() and peer.sell.prepare() never open a mailbox, check receipt credentials, or require linking.

@zkp2p/sdk exports the primitives:

  1. Register the handle with registerPayeeDetails() on a Zkp2pClient to get its payeeDetails hash.
  2. Call openVenmoGmailConnect({ payeeDetails }) or openXMoneyConnect({ payeeDetails, payeeUsername }) directly from a click handler. Native apps open getVenmoGmailConnectUrl() or getXMoneyConnectUrl() in a system browser session instead.
  3. A closed window or a return to your app doesn't prove the link worked. Read getSellerCredentialStatus({ processorName, payeeDetails }): the inbox is linked only when status is active and isMailboxSellerCredentialType(credentialType) is true.

The hosted page owns consent and credentials; emails, mailbox tokens, app-specific passwords, and authorization codes never reach your app. See the client reference for error codes, return URLs, and popup styling.

Protected payout rails​

Venmo and PayPal keep the protocol's default dispute protection without an extra transaction. Don't gate deposit creation on it or send setDisputeProtectionEnabled(true). Cash App is non-chargebackable and needs no stake.

3. Show an honest estimate​

Amounts use token base units. Base USDC has six decimals; build common values with usdc() and format them with formatUsdc().

import { usdc } from "@zkp2p/sdk";

const estimate = await peer.sell.estimate({
amount: usdc(250),
currency: "EUR",
platform: "revolut",
});

console.log({
kind: estimate.kind, // "oracle-estimate"
receiveAmount: estimate.receiveAmount,
rate: estimate.rate,
stale: estimate.stale,
eta: estimate.eta,
});

estimate() has no side effects. rate is a current oracle reading for display; each buyer's rate binds when they signal an intent. Use approximate language, and when stale is true, warn the user or hide the rate until a fresh reading is available.

eta, when present, comes from recent comparable fills. It is not a countdown, service-level commitment, or guarantee. Pass { includeEta: false } as the second argument to render the rate first, and read peer.sell.fillStats() for 30-day demand and first-fill speed by platform:currency.

4. Start a sale​

import { createWalletClient, custom } from "viem";
import { base } from "viem/chains";
import { usdc } from "@zkp2p/sdk";

const signer = createWalletClient({
account: sellerAddress,
chain: base,
transport: custom(window.ethereum),
});

const sale = await peer.sell(
{
amount: usdc(250),
receive: {
platform: "revolut",
currency: "EUR",
payee: "your-revtag",
},
},
{ signer },
);

await salesTable.insert({
userId,
depositId: sale.depositId,
depositTransactionHash: sale.txHash,
});

peer.sell() registers the payee, approves USDC if needed, creates the deposit, waits for the receipt, and decodes DepositReceived. depositId has the form escrowAddress_onchainId and comes from the confirmed receipt, so you don't wait for the indexer.

payee takes a raw handle, which the SDK normalizes for the platform, or structured payee data such as { offchainId: "your-revtag" }.

By default a buyer can take from 1 USDC up to the whole order; Order sizing shows how to change that with intentAmountRange.

Offer several currencies or platforms​

A payout leg can list several currencies, and receive accepts an array of legs on different platforms. Both widen the set of buyers who can fill the order. The buyer picks an option they can pay, and each option fills at the live zero-spread oracle rate for its currency.

const sale = await peer.sell(
{
amount: usdc(250),
receive: [
{
platform: "revolut",
currencies: ["EUR", "GBP"],
payee: "your-revtag",
},
{
platform: "chime",
currency: "USD",
payee: "$your-chime-sign",
},
],
},
{ signer },
);

Each platform may appear once. An empty or duplicate leg set fails with INVALID_PAYOUT_PLATFORMS, and a bad currency list with INVALID_PAYOUT_CURRENCIES, before any wallet interaction. Multi-leg sales work the same through peer.sell.prepare(), and order().payouts has one entry per platform-currency pair.

Persist your user ID, depositId, and the Base transaction hash. The SDK has no session store; your userId → depositId mapping is enough to resume.

5. Observe and reconcile the order​

Read once with order():

const order = await peer.sell.order(depositId);

console.log(order.state);
console.log(order.nextActions);
console.log(order.explain());

Or watch until the order reaches a terminal state:

for await (const order of peer.sell.watch(depositId, {
pollIntervalMs: 5_000,
timeoutMs: 30 * 60_000,
})) {
await saveOrderSnapshot(order);
}

ORDER_NOT_FOUND right after a successful sale usually means the indexer hasn't seen the deposit yet. Keep the receipt and retry the read. watch() retries through this window on its own and throws WATCH_TIMEOUT when timeoutMs passes first.

Treat fulfilled fills as receipts. Reconcile against their verified fiatPaid, paidCurrency, paymentId, paidAt, and releasedAmount, not the original estimate. peer.sell.buyer(address) returns a matched buyer's protocol track record.

6. Withdraw or top up​

withdraw() is the only unwind call:

const order = await peer.sell.order(depositId);

if (order.nextActions.includes("withdraw")) {
const result = await peer.sell.withdraw(depositId, { signer });
console.log(result.withdrawTxHash);
}

Without an amount, withdraw() closes what remains of the order, pruning expired buyer intents first. A live buyer intent blocks a full close because that buyer may still complete the payment.

Pass an amount to withdraw only unlocked funds. A live buyer intent doesn't block a partial withdrawal.

await peer.sell.withdraw(depositId, {
signer,
amount: usdc(25),
});

Add funds to a live order without changing its payee or market-rate pricing:

await peer.sell.topUp(depositId, usdc(100), { signer });

7. Use unsigned transaction plans​

When an account-abstraction wallet, policy engine, remote signer, or agent host does the signing, use the prepare methods:

import type { TransactionReceipt } from "viem";

const plan = await peer.sell.prepare({
amount: usdc(250),
receive: {
platform: "revolut",
currency: "EUR",
payee: "your-revtag",
},
});

let createDepositReceipt: TransactionReceipt | undefined;

for (let index = 0; index < plan.txs.length; index += 1) {
const transaction = plan.txs[index];
const step = plan.steps[index];

await policy.review({ step, transaction });
const hash = await hostSigner.sendTransaction(transaction);
const receipt = await hostSigner.waitForReceipt(hash);
if (step.kind === "createDeposit") createDepositReceipt = receipt;
}

if (!createDepositReceipt) throw new Error("createDeposit receipt missing");

const sale = peer.sell.finalizePrepared(createDepositReceipt);
await saveSale({
depositId: sale.depositId,
transactionHash: sale.txHash,
});

prepare() registers the payee, then returns unsigned transactions. txs[] and steps[] share the same order: approve then createDeposit. You can skip approve when the allowance already covers the amount. finalizePrepared() takes the confirmed createDeposit receipt, rejects a reverted one with TRANSACTION_FAILED, and returns the same result as peer.sell().

prepareWithdraw(depositId, { amount? }) and prepareTopUp(depositId, amount) return the same plan shape with pruneExpiredIntents, withdrawDeposit, removeFunds, approve, or addFunds steps. prepareWithdraw() runs the same state checks as withdraw().

The host keeps custody, policy checks, user approval, ordered submission, and receipt confirmation.

8. Handle typed failures​

import { isPeerError } from "@zkp2p/sdk";

try {
await peer.sell(input, { signer });
} catch (error) {
if (!isPeerError(error)) throw error;

logger.warn({
code: error.code,
retryable: error.retryable,
remediation: error.remediation,
recovery: error.recovery,
});
}
CodeAction
ORDER_NOT_FOUND right after a saleRetry the read. Keep the confirmed receipt and never recreate the deposit.
PAYEE_NOT_FOUNDThe handle doesn't exist on the platform. Ask for a corrected handle in the payeeHint format; retrying the same input fails again. No deposit was created.
PAYEE_VERIFICATION_REQUIREDRegister the new Alipay handle through Peer, or reuse a registered handle.
PAYEE_REGISTRATION_FAILEDPeer's API failed for another reason. Retry; no deposit was created.
ACTIVE_INTENT_BLOCKS_WITHDRAWALWait for delivery or expiry, then retry the full withdrawal when the order allows it.
TRANSACTION_SUBMISSION_UNKNOWNTreat the call as possibly broadcast. For a sale, error.recovery is inspect-base-sale-submission with amount and depositor; inspect orders() first.
TRANSACTION_STATUS_UNKNOWNInspect error.recovery.transactionHash before resubmitting.
INDEXER_UNAVAILABLE or ORACLE_READ_FAILEDRetry the failed read only.
SIGNER_REQUIREDPass { signer } with a viem WalletClient that has an account.
SIGNER_CHAIN_MISMATCHSwitch the signer to Base.

remediation is written for logs, operator interfaces, and agent results. Serialize a PeerError with error.toJSON(). isUserRejectedError(error) detects a wallet rejection.

9. Serialize across process boundaries​

Orders contain bigint values and an explain() method, so JSON.stringify(order) throws. Persist depositId and read the order again with order() when you need it. To cache a snapshot, convert bigints to decimal strings:

const snapshot = JSON.stringify(order, (_key, value) =>
typeof value === "bigint" ? value.toString() : value,
);
await cache.set(depositId, snapshot);

A cached snapshot is a display copy. Call order(depositId) for live state and explain().

10. Verify on staging​

Before shipping, prove the seller-side lifecycle with a small funded wallet. Don't wait for a buyer.

  1. Create a 1–2 USDC sale with environment: "staging".
  2. Save the depositId and transaction hash.
  3. Retry through indexer lag until order(depositId) is awaiting-buyer.
  4. Confirm orders(owner) includes the deposit.
  5. Withdraw it.
  6. Confirm the order is returned and the wallet's USDC is restored, less gas.

If a withdrawal fails and funds look stuck, stop and investigate. Don't retry transactions blindly.