# Sell PCASH for ETH

A seller lists PCASH, or a token, for an ETH price, and a buyer pays in one Ethereum transaction that also claims it, with no exchange, custodian, or bridge in between. With the `@pcash/marketplace` client, the seller creates an escrow contract on PCASH that holds the note and publishes the listing, and the buyer sends one call to the `PaymentRouter` contract on Ethereum. Nothing has to prove PCASH's state to Ethereum: the Ethereum contract records only the payment, and the PCASH escrow reads that payment from the Ethereum transaction that carries the claim.

## How it works

The escrow contract and the `PaymentRouter` ship with PCASH and are used unchanged; the website's Marketplace runs them, and the code on this page drives the same client.

1. **List.** The seller locks a PCASH or token note in an escrow contract with two functions: `claim()` releases it against a matching payment, and `reclaim()` returns it to the seller after a deadline. The listing publishes the note's opening, so any buyer can build a claim, and only those two functions can spend the note.
2. **Check.** The buyer's client reads the escrow through its PCASH node, checks the contract and the router, and proves a claim on the note before paying anything.
3. **Pay and claim.** One call to the router's `buy` pays the exact ETH price, split into the deployment's website fee and the seller's proceeds, and carries the claim to PCASH in the same transaction. PCASH executes the claim with that Ethereum block, and the escrow pays the note to the buyer.
4. **Retry.** If the claim fails, the router's `retry` carries a fresh claim for the recorded payment until the deadline.
5. **Reclaim.** If no one buys, the seller takes the note back after the deadline.

<figure data-diagram="eth-trade"><figcaption><p>One Ethereum transaction pays the seller and claims the PCASH.</p></figcaption></figure>

One check in `claim()` ties the trade together. The claim must be carried by the router's event for this offer's payment, and that event's context names the buyer's claim-key commitment to this escrow note:

```rust marketplace/l2-contracts/escrow/claim/src/main.nr
    assert(
        private_value.carrier_context_hash
            == payment_carrier_context_hash(
                configuration,
                claim_key_commitment(claim_key, escrow_commitment),
            ),
        "claim must require the router's payment carrier context",
    );
```

The router emits that event only from `buy`, after it has paid the seller, or from `retry`, for a payment it has already recorded. Anyone may call `retry`, but only the holder of the claim key can make a claim that succeeds.

## Set up the client

Each side runs a `MarketplaceController` over its PCASH wallet and an Ethereum account. In a browser app, `ethereum` is the viem wallet client of the user's Ethereum wallet, and the controller proves in the browser, as the website's Marketplace does. A script can sign with `privateKeyL1Signer(privateKey, l1RpcUrl)` instead, and a Node program passes its own `prover`. `router` is the deployment's `PaymentRouter`.

The code on this page uses these imports:

```typescript examples/sell-for-eth/client.ts
import { reclaimNotBefore } from "@pcash/marketplace";
import {
  MarketplaceController,
  openForPurchase,
  publicationAssetDefinition,
  viemL1Signer,
  type MarketplaceBuyResult,
  type MarketplaceStore,
  type OfferPublication,
  type StoredOffer,
} from "@pcash/marketplace/client";
import { awaitAcceptedReceipt, type PcashNodeClient } from "@pcash/sdk/clients";
import { encodeAssetDefinition } from "@pcash/sdk/protocol";
import type { Wallet } from "@pcash/sdk/wallet";
import type { Address, WalletClient } from "viem";
```

The store records each listing's and purchase's progress, so an interrupted action resumes where it stopped. The website keeps it in IndexedDB.

```typescript examples/sell-for-eth/client.ts
/** Listing and purchase progress, kept in memory. A wallet that loses it finds its payments on Ethereum again. */
export function memoryStore(): MarketplaceStore {
  const offers = new Map<string, StoredOffer>();
  const copy = <T>(value: T): T => structuredClone(value);
  return {
    list: async () => [...offers.values()].map(copy),
    get: async (key) => copy(offers.get(key) ?? null),
    put: async (offer) => { offers.set(offer.key, copy(offer)); },
    remove: async (key) => { offers.delete(key); },
    clear: async () => { offers.clear(); },
    update: async (key, operation) => {
      const next = operation(copy(offers.get(key) ?? null));
      if (next === null) offers.delete(key);
      else offers.set(key, copy(next));
      return copy(next);
    },
  };
}

/** The Marketplace client for one PCASH wallet and the Ethereum account that signs its router calls. */
export function openMarket(p: {
  node: PcashNodeClient;
  wallet: Wallet;
  store: MarketplaceStore;
  l1RpcUrl: string;
  ethereum: WalletClient;
  account: Address;
  router: Address;
}): MarketplaceController {
  return new MarketplaceController({
    node: p.node,
    store: p.store,
    l1RpcUrls: [p.l1RpcUrl],
    configuredRouter: { address: p.router },
    identity: { wallet: p.wallet, l1Signer: viemL1Signer(p.ethereum, p.account) },
  });
}
```

## List it

`createAndPublish` creates the escrow contract and funds it with the note in one PCASH transaction, then publishes the listing to the node's catalog. A token listing carries the token's definition, so buyers' wallets can show it. `purchaseMinutes` is how long the listing takes new purchases; the deadline follows 30 minutes later plus a 24-hour claim window. `openFee` is the PCASH a relayer earns for including the funding transaction, and is zero when the wallet posts its own transactions to Ethereum.

```typescript examples/sell-for-eth/client.ts
/** Seller: lock `amount` of PCASH (asset 0n) or a token in a new escrow priced in wei, and publish the listing. */
export async function listForEth(market: MarketplaceController, wallet: Wallet, p: {
  assetId: bigint;
  amount: bigint;
  ethPriceWei: bigint;
  purchaseMinutes: bigint;
  openFee: bigint;
}): Promise<OfferPublication> {
  const token = p.assetId === 0n ? undefined : (await wallet.assets()).find((asset) => asset.assetId === p.assetId)?.definition;
  if (p.assetId !== 0n && token == null) throw new Error("this wallet does not know the token's definition");
  const listed = await market.createAndPublish({
    assetId: p.assetId,
    assetDefinition: token == null ? undefined : encodeAssetDefinition(token),
    amount: p.amount,
    ethPriceWei: p.ethPriceWei,
    purchaseMinutes: p.purchaseMinutes,
    fundingOpenFeeAmount: p.openFee,
  });
  if (!listed.catalogPublished) throw new Error(`the escrow is funded, but the catalog refused the listing: ${listed.catalogError}`);
  return listed.publication;
}
```

If the catalog refuses the listing, the escrow is still funded, and `resumePublication(publication)` publishes it again. A listing can also travel as a link: `listingShareUrl(publication, baseUrl)` puts it in the URL fragment, and `sharedOfferFromUrl(url)` reads it back.

The router pays the seller's PCASH address, which is the seller's Ethereum address. The seller never calls the router.

## Find and check it

The catalog is a convenience, and its records are untrusted. `verify` checks the listing itself: the escrow contract and its two functions bind the advertised terms, a token's definition hashes to its asset ID, the router is the configured one and its bytecode and fee terms match, the router has no payment for the listing yet, and the escrow note is unspent on a node that is current. `buy` runs the same checks again before it pays.

```typescript examples/sell-for-eth/client.ts
/** Buyer: the catalog's listings of one asset that are still open for purchase. */
export async function findListings(market: MarketplaceController, assetId: bigint): Promise<OfferPublication[]> {
  const now = BigInt(Math.floor(Date.now() / 1000));
  const { catalogOffers } = await market.refresh();
  return catalogOffers.filter((offer) => BigInt(offer.terms.assetId) === assetId && openForPurchase(offer, now));
}

/** Buyer: check a listing against the node and Ethereum, and show what it sells and what the payment splits into. */
export async function checkListing(market: MarketplaceController, listing: OfferPublication) {
  const check = await market.verify(listing);
  if (!check.safeToPay || check.feeQuote === null) throw new Error(`not safe to pay: ${check.checks.join("; ")}`);
  return {
    symbol: publicationAssetDefinition(listing)?.metadata.symbol ?? "PCASH",
    amount: BigInt(listing.terms.amount),
    priceWei: check.feeQuote.buyerGrossWei,
    sellerGetsWei: check.feeQuote.sellerNetWei,
    websiteFeeWei: check.feeQuote.websiteFeeWei,
  };
}
```

## Pay and claim

`buy` proves the claim against the state it just checked, has the node dry-run it as the router would carry it, and only then sends `buy` from the Ethereum account with the exact price. It returns once the escrow has paid the buyer a private note. `claimedIn` is the payment's own transaction unless the first claim failed and a `retry` carried the second.

```typescript examples/sell-for-eth/client.ts
/** Buyer: pay and claim in one Ethereum transaction. Resolves once the escrow has paid this wallet. */
export async function buyListing(market: MarketplaceController, node: PcashNodeClient, listing: OfferPublication) {
  const { paymentHash, claimContentHash } = await market.buy(listing);
  const claim = await awaitAcceptedReceipt(node, claimContentHash);
  return { paymentHash, claimedIn: claim.inclusion.l1TransactionHash };
}
```

The router records one payment of a listing's price, so a second buyer's `buy` reverts. `buy` also reverts unless the Ethereum block of the PCASH state the buyer's proof used is still canonical, so a reorganization can't make a buyer pay for a claim built on state that no longer exists.

## Finish a failed claim

A claim fails when the node the buyer relied on was wrong about the escrow. `buy` notices: if no claim has spent the escrow by a canonical block after the payment, it proves the claim again and carries it in `retry`. The escrow accepts a claim until the deadline, and a guardian's pause doesn't stop `retry`. Running your own node removes the reliance.

If the buyer's app closes before the claim lands, the purchase isn't lost. The claim key comes from the wallet's keys, so a restored wallet with an empty store finds its payments on Ethereum. Calling `buy` on a listing the wallet has paid for sends no second payment: it waits for the claim, or retries it.

```typescript examples/sell-for-eth/client.ts
/** Buyer, on a restored wallet with an empty store: find this wallet's payments on Ethereum and finish their claims. */
export async function finishPurchases(market: MarketplaceController, wallet: Wallet): Promise<MarketplaceBuyResult[]> {
  const { localOffers, recoveryErrors = [] } = await market.refresh();
  if (recoveryErrors.length > 0) throw new Error(recoveryErrors.join("; "));
  const finished: MarketplaceBuyResult[] = [];
  for (const offer of localOffers) {
    const paid = offer.buys?.[wallet.address];
    if (paid?.txHash !== undefined) finished.push(await market.buy(paid.publication));
  }
  return finished;
}
```

## Reclaim an unsold listing

After the deadline no claim can succeed, and the seller's `reclaim()` returns the note. The escrow measures the deadline by Ethereum's clock and refuses a reclaim until it has passed. A reclaim is a PCASH transaction that never touches the router, so a pause can't stop it.

```typescript examples/sell-for-eth/client.ts
/** Seller: the first Ethereum timestamp at which an unsold listing can be reclaimed. */
export function reclaimOpensAt(listing: OfferPublication): bigint {
  return reclaimNotBefore(BigInt(listing.terms.deadlineT));
}

/** Seller: return an unsold listing's escrow to this wallet. Returns the reclaim's content hash. */
export async function reclaimUnsold(market: MarketplaceController, listing: OfferPublication, openFee: bigint): Promise<string> {
  return market.reclaim(listing, openFee);
}
```

## Fees

The router can't see PCASH's protocol fee, so the claim `buy` carries burns the most the fee could reach by the time `buy` can still execute, about three minutes past the Ethereum head. While the fee is waived and would stay waived through an hour of full blocks, it burns nothing. A claim for `retry` burns the fee projected for its inclusion.

A PCASH claim or reclaim pays its burn from the note. A token escrow holds no PCASH, so the buyer's own PCASH pays a claim's burn while the fee is positive, and the seller's own PCASH pays a reclaim's fees. A buyer with no PCASH can buy a token listing only while the fee is zero, and the client refuses to pay for a claim the buyer's PCASH can't fund.

## Pauses and transfer rules

A deployment names a guardian that can pause new purchases. It can't move funds, change a listing or the fee, or stop `retry` or a reclaim.

The same escrow sells any asset. An asset with a transfer rule stays under it in escrow: the rule judges the escrow contract as the sender, so a freeze of the escrow's address holds both the sale and the reclaim until it is lifted.

## What's public

A listing is public: the seller's address, the asset, the amount, the price, and the deadline. The payment is an ordinary Ethereum transaction from the buyer's Ethereum account, and the router's record of it names the listing, the seller, and the price. The buyer receives a private note, which it spends like any other.

## Building something like it

The same shape fits any "pay on Ethereum, receive privately" flow. An Ethereum contract takes the payment and carries a claim to PCASH in the same transaction, and a PCASH contract function releases funds only to a claim whose carrier context names that payment. The reference client accepts only its pinned escrow, but anyone can publish a different design.

## Run it

* `just e2e marketplace`: a listing, a buy that pays and claims in one Ethereum transaction, a failed claim finished by a restored wallet through `retry`, and a timed reclaim.
* `just e2e token-market`: a token listed for ETH, bought and claimed with no PCASH, and an unsold listing reclaimed.

Both run against local Ethereum and PCASH nodes with real proofs. `token-market` drives these same `MarketplaceController` calls in Node, signing with `privateKeyL1Signer` and proving natively.

Further reading: [`PaymentRouter.sol`](../../marketplace/l1-contracts/src/PaymentRouter.sol), the escrow's [`claim()` and `reclaim()`](../../marketplace/l2-contracts/escrow/), the [client flows](../../marketplace/src/client/), [`marketplace/README.md`](../../marketplace/README.md), and the scenarios [`marketplace.ts`](../../e2e/src/scenarios/marketplace.ts) and [`tokenMarket.ts`](../../e2e/src/scenarios/tokenMarket.ts).
