> ## Documentation Index
> Fetch the complete documentation index at: https://docs.polygon.technology/llms.txt
> Use this file to discover all available pages before exploring further.

# Private balances with TypeScript

> Shield tokens into a private balance, send privately, unshield, and recover undelivered sends from an OMS Ethereum wallet.

`@polygonlabs/oms-wallet-privacy` adds a private balance to the active Ethereum wallet. Shielding moves tokens from the wallet into its private balance, unshielding moves them from the private balance to any address, and a private send pays a recipient with no onchain link to the sender.

Every privacy operation requires an active Ethereum wallet session and acts for the wallet that was active when it was called.

> [!WARNING]
>
> Private balances exist only on mainnets. Every operation moves real funds and pays real fees.

## Install

```bash theme={null}
pnpm add @polygonlabs/oms-wallet @polygonlabs/oms-wallet-privacy viem
```

The package is ESM-only and requires `@polygonlabs/oms-wallet` 0.5 or later. It runs in browsers through a bundler and in Node 22 without polyfills or bundler settings. It loads its privacy library, about 2 MB gzipped, on the first private-balance call.

## Add the extension

Pass `privacy()` to `OMSWallet.extend`. It returns a new `OMSWallet` with an `omsWallet.privacy` member; `wallet` and `indexer` are the same objects as on the original instance.

```typescript theme={null}
import { OMSWallet } from '@polygonlabs/oms-wallet'
import { privacy } from '@polygonlabs/oms-wallet-privacy'

export const omsWallet = new OMSWallet({
  publishableKey: 'YOUR_PUBLISHABLE_KEY',
}).extend(privacy())
```

Authenticate and select an Ethereum wallet with `omsWallet.wallet` as described in [authentication](https://docs.polygon.technology/wallets/sdk/typescript/authentication.md).

## Supported networks and tokens

Private balances are available on Ethereum, BNB Chain, Polygon, Base, and Arbitrum. `omsWallet.privacy.networks` lists them as `Network` values.

Tokens are contract addresses. Use `0x0000000000000000000000000000000000000000` for the network's native token. Amounts are `bigint` values in the token's base units.

## Quote, then confirm

Every operation starts with a quote. Show the quote to the user, then pass it to the matching call.

```typescript theme={null}
import { Networks } from '@polygonlabs/oms-wallet'

const usdc = '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359'

const quote = await omsWallet.privacy.quoteShield({
  network: Networks.polygon,
  token: usdc,
  amount: 1_000_000n,
})

console.log(quote.amount, quote.fee, quote.total, quote.expiresAt)

await omsWallet.privacy.shield(quote)
```

`amount` is what arrives, `fee` is the privacy fee in the same token, and `total` is `amount + fee`: what leaves the wallet or the private balance. Shielding has no privacy fee. Network fees are separate.

A quote is valid for 5 minutes, can be used once, and only for the wallet that was active when it was made. Otherwise the call fails with `OMS_PRIVACY_QUOTE_INVALID`; request a new quote.

### Send privately

A private send deposits `total` from the wallet into the sender's private balance and authorizes a payment of `amount` to `to`. The privacy service delivers it later.

```typescript theme={null}
const quote = await omsWallet.privacy.quotePrivateSend({
  network: Networks.polygon,
  token: usdc,
  amount: 1_000_000n,
  to: '0x1111111111111111111111111111111111111111',
})

const sent = await omsWallet.privacy.privateSend(quote)

console.log(sent.deliveryId)
```

### Unshield

Unshielding pays from the private balance to `to`, or to the active wallet when `to` is omitted.

```typescript theme={null}
const quote = await omsWallet.privacy.quoteUnshield({
  network: Networks.polygon,
  token: usdc,
  amount: 500_000n,
})

const { txnHash } = await omsWallet.privacy.unshield(quote)
```

Unshielding sends no wallet transaction. The privacy service submits the withdrawal, and its fee is part of the quote.

## Pay network fees

`shield` and `privateSend` send up to three wallet transactions: an allowance reset to 0, an approval of exactly `total`, and the deposit. Steps that are not needed are skipped, and native-token deposits need no approval. The result's `transactions` lists every transaction sent, in order, with its `networkFee` when one was paid. Sponsored transactions have no `networkFee`.

By default, each transaction's network fee is paid in the token being moved. If the wallet cannot pay it on top of `total`, the call fails with `OMS_PRIVACY_NETWORK_FEE` before that transaction executes. Pass `selectFeeOption` to choose another fee token, as described in [send transactions](https://docs.polygon.technology/wallets/sdk/typescript/send-transactions.md#select-fees-accurately), or `maxNetworkFee` to cap the fee each transaction may pay in the moved token.

```typescript theme={null}
import { FeeOptionSelector } from '@polygonlabs/oms-wallet'

await omsWallet.privacy.shield(quote, {
  selectFeeOption: FeeOptionSelector.firstAvailable,
})
```

To store each transaction ID before it is submitted, pass `onProgress`. Each wallet transaction reports `prepared` with its `txnId` before execution and `confirmed` once it executed. The SDK awaits the callback for `prepared` events; if it throws or rejects, that transaction is not executed.

```typescript theme={null}
await omsWallet.privacy.shield(quote, {
  onProgress: (event) => {
    if (event.step !== 'delivery' && event.state === 'prepared') {
      // Store event.txnId durably. Return a promise to hold execution until it is stored.
    }
  },
})
```

## Track delivery

`deliveryId` identifies a private send's delivery. Treat it as private, because it reveals the delivery. Check its status with `getDeliveryStatus`:

```typescript theme={null}
const delivery = await omsWallet.privacy.getDeliveryStatus({
  deliveryId: sent.deliveryId,
})

console.log(delivery.status) // 'pending', 'delivered', or 'failed'
```

To wait for delivery instead, pass `waitForDelivery: true`. The SDK polls every 3 seconds for up to 15 minutes and returns the delivered status in `delivery`. Override these values with `deliveryPolling`.

```typescript theme={null}
const sent = await omsWallet.privacy.privateSend(quote, {
  waitForDelivery: true,
  deliveryPolling: { timeoutMs: 5 * 60_000 },
})
```

While waiting, a failed delivery throws `OMS_PRIVACY_DELIVERY_FAILED`, and a delivery that does not finish in time throws `OMS_PRIVACY_DELIVERY_TIMEOUT`. A timed-out delivery can still finish; check it later with `getDeliveryStatus`.

## Read balances and recover funds

`getBalances` returns the active wallet's private balances with a non-zero amount, across every supported network unless you pass `networks`.

```typescript theme={null}
const balances = await omsWallet.privacy.getBalances()

for (const balance of balances) {
  console.log(balance.network.name, balance.token, balance.amount, balance.recoverable)
}
```

`amount` is spendable. `recoverable` holds private sends that were deposited but not delivered. When a delivery fails, its funds stay there until you call `recover`, which pays all recoverable funds of one token back to the active wallet:

```typescript theme={null}
const { txnHashes } = await omsWallet.privacy.recover({
  network: Networks.polygon,
  token: usdc,
})
```

Funds also show as `recoverable` while a delivery is pending. `recover` and the delivery spend the same funds, so only one of them goes through. Like unshielding, `recover` sends no wallet transaction.

## Handle errors

Every failure is an `OMSWalletPrivacyError`. It has a `code`, the `operation`, the `stage` the operation reached, if any, and `txnIds`: every wallet transaction the operation created. When a private send fails after its deposit, the error can also carry its `deliveryId`.

```typescript theme={null}
import { isOMSWalletPrivacyError } from '@polygonlabs/oms-wallet-privacy'

try {
  await omsWallet.privacy.privateSend(quote)
} catch (error) {
  if (isOMSWalletPrivacyError(error)) {
    console.error(error.code, error.stage, error.txnIds, error.deliveryId)
  }
  throw error
}
```

For `shield` and `privateSend`, an empty `txnIds` means no wallet transaction was sent, and you can request a new quote and try again. Otherwise, check each ID with `omsWallet.wallet.getTransactionStatus({ txnId })`, then call `getBalances` for funds to recover. A failed or timed-out call never sends a deposit again on its own.

Do not send a private send again when its error carries a `deliveryId`: the send went through, and only its delivery status is unknown. The same applies to an `OMS_PRIVACY_SERVICE_ERROR` at the `delivery` stage without a `deliveryId`: the deposit executed and the delivery may still happen.

`unshield` and `recover` send no wallet transaction, so their `txnIds` is always empty. When the error message says the withdrawal may have been submitted, check `getBalances` before trying again.

If the active wallet changes or signs out while an operation runs, even when the same wallet becomes active again, the operation stops with `OMS_PRIVACY_WALLET_CHANGED`. Balance reads and quotes fail the same way instead of returning results for a wallet that is no longer active.

## Keys and trust

The private balance's keys are derived from the wallet's signature over a fixed message. A connected dApp, such as one using the [wagmi connector](https://docs.polygon.technology/wallets/sdk/typescript/using-with-wagmi-connector.md), cannot request that signature; code running in your application can. Setting up keys sends no wallet transaction.

The keys stay the same when the wallet is deployed or its configuration changes, for example when remote access is granted, revoked, or expires. The package stores a fingerprint of the derived keys and stops with `OMS_PRIVACY_KEY_MISMATCH` if they change, instead of showing an empty balance. It stores the fingerprint in `localStorage` in browsers and in memory elsewhere; pass `privacy({ storage })` to use your own `StorageManager`. A change is detected only where a fingerprint was stored before.

The privacy service generates proofs remotely and receives the private balance's viewing key, so it can see private balances and history. It cannot move funds: withdrawals are authorized by a spending key that stays on the device and signs the recipient, amount, and fee. The service delivers private sends on its own schedule.

Deposit transactions can only approve and call allowlisted contracts, and the approval is exactly `total`, so a deposit can move at most `total`. Operations for one wallet run one at a time within a page.
