import { Address, Hash, WalletClient, Hex, Log, Transport } from 'viem'; import { IndexerIntentStatus, Zkp2pClient, IndexerIntent, CurrencyType, PreparedTransaction, RuntimeEnv, VenmoGmailConnectResult } from '@zkp2p/sdk'; import { Execute, RelayClient, RelayChain, ProgressData } from '@relayprotocol/relay-sdk'; /** * Name-mapping shim over the published `@zkp2p/sdk` (^0.9). * * The reference implementation imported these from internal SDK paths; the * published package exports them under indexer-prefixed names, and one type * (`CuratorPayeeDataInput`) is not exported at all - it is recovered here from * the `registerPayeeDetails` method signature. Everything else in this package * imports SDK types from this module so the mapping lives in exactly one place. */ type IntentStatus = IndexerIntentStatus; type IntentEntity = IndexerIntent; type CuratorPayeeDataInput = NonNullable[0]['payeeData']>[number]; type CreateDepositParamsArg = Parameters[0]; /** * Peer Cash - public domain types for the engine. */ /** * The lifecycle state of a cash-out, derived purely from on-chain-observable * intent events against the user's deposit. * * - `awaiting-buyer` - deposit is live, no buyer has signaled yet. * - `matched` - a buyer signaled an intent (`SIGNALED`); fiat not yet proven. * - `delivering` - partial fill in progress (some intents fulfilled, some still signaled). * - `delivered` - fiat paid + proven, escrow released (`FULFILLED`). * - `returned` - buyer didn't deliver; intent pruned, deposit recoverable/recovered. */ type CashOrderState = 'awaiting-buyer' | 'matched' | 'delivering' | 'delivered' | 'returned'; /** What the caller can do next. The lifecycle is self-driving - no consumer heuristics. */ type CashNextAction = 'wait' | 'withdraw'; /** * One buyer's intent against the deposit (one "fill"). The order id is the * `intentHash`. Hashes are decoded to human units wherever the protocol * catalogs know them; the raw values stay available for anything unknown. */ interface CashFill { /** The order id once a buyer has signaled. */ intentHash: string; status: IntentStatus; /** Intent amount in USDC base units (6 decimals). */ amount: bigint; /** The buyer (taker) address. */ buyer: string; /** Decoded fiat currency code the buyer pays in, e.g. `'EUR'`. */ currency?: string; /** Raw on-chain currency hash (bytes32), for anything the catalog can't decode. */ currencyHash?: string; /** Fiat per USDC locked at signal time - the binding rate for THIS fill. */ rate?: number; /** Raw locked conversion rate (1e18 precision). */ conversionRate?: bigint; /** Fiat the buyer must send: `amount × rate`, rounded up to the cent. */ fiatOwed?: number; /** Verified receipt - actual fiat paid, from the payment proof. */ fiatPaid?: number; /** Verified receipt - decoded currency actually paid (may differ from `currency`). */ paidCurrency?: string; /** Verified receipt - the platform's external payment id. */ paymentId?: string; /** Verified receipt - unix seconds the fiat payment was made. */ paidAt?: number; /** USDC actually released from escrow for this fill (gross, base units). */ releasedAmount?: bigint; /** Seconds from buyer signal to proven delivery. */ fillLatencySeconds?: number; /** Indexer reconciler flag: the intent's window has lapsed on-chain. */ isExpired?: boolean; /** Unix seconds - when the buyer signaled (matched). */ signaledAt?: number; /** Unix seconds - when the signaled intent expires and becomes prunable. */ expiresAt?: number; /** Unix seconds - when fiat was proven and escrow released (delivered). */ fulfilledAt?: number; /** Unix seconds - when the intent expired and was pruned (returned). */ prunedAt?: number; } /** Pricing state of one payout tuple, reconstructed from indexed data. */ interface CashPayoutPricing { /** Depositor-configured oracle spread in basis points (0 on oracle Cash corridors). */ spreadBps?: number; /** Oracle kind, e.g. `'oracle_chainlink'`. */ kind?: string; /** Which source currently binds the rate: `ORACLE` | `MANAGER` | `ESCROW_FLOOR` | …. */ rateSource?: string; /** Current oracle rate (fiat per USDC), decoded from 1e18. */ oracleRate?: number; /** Unix seconds of the last accepted oracle snapshot. */ lastOracleUpdatedAt?: number; /** True when the tuple is priced by an oracle at zero spread. */ marketRate: boolean; /** True when the maker floor was fixed from a fresh rate snapshot at deposit creation. */ fixedAtCreation?: boolean; /** Fixed maker floor in fiat units per USDC. */ fixedRate?: number; } /** One payout leg reconstructed from the chain - platform, currency, payee hash, pricing. */ interface CashPayoutInfo { /** Decoded active platform id, e.g. `'venmo'`. */ platform: string; /** Raw payment method hash (bytes32). */ platformHash: string; /** Decoded fiat currency code, e.g. `'USD'`. */ currency?: string; /** Raw currency hash (bytes32). */ currencyHash?: string; /** Hashed payee details (the handle itself never touches the chain). */ payeeHash: string; /** Whether the method still accepts new intents. */ active: boolean; pricing: CashPayoutPricing; } /** * The full, resumable view of a cash-out order, reconstructed from the indexer * by `depositId` alone - survives a closed tab, new device, or wallet reconnect. */ interface CashOrder { /** Composite deposit id (`escrow_onchainId`) - the resume key. */ depositId: string; state: CashOrderState; /** Every buyer intent against the deposit (>1 only for partial fills). */ fills: CashFill[]; /** Deposit amount in USDC base units. */ totalAmount: bigint; /** Sum of fulfilled (delivered) intent amounts. */ filledAmount: bigint; /** Sum of signaled-but-not-yet-fulfilled intent amounts. */ pendingAmount: bigint; /** Sum returned (withdrawn) to the maker. */ returnedAmount: bigint; /** Self-driving lifecycle - what the caller can do right now. */ nextActions: CashNextAction[]; /** The primary order id (first/active intent's `intentHash`) once matched. */ primaryIntentHash?: string; /** Unix seconds - earliest signal (first match). */ matchedAt?: number; /** Unix seconds - latest fulfilment (delivery). */ deliveredAt?: number; /** Unix seconds - when the deposit last changed on-chain. */ updatedAt?: number; /** Total number of buyer intents against the deposit (from the indexer aggregate). */ intentCount?: number; /** * Payout legs reconstructed from the chain (platform, currency, payee hash, * pricing proof). Present on `order()`; absent on `orders()` list rows. */ payouts?: CashPayoutInfo[]; /** Deposit quality signal takers see (basis points, 0–10000; new deposits start at 10000). */ successRateBps?: number; /** True while the order still needs the user's attention / a buyer to act. */ isInFlight: boolean; /** Whether the deposit has been withdrawn on-chain (terminal return). */ withdrawn?: boolean; /** One honest sentence from live data - never a fake countdown. */ explain(): string; } /** A buyer's protocol track record, aggregated from their full intent history. */ interface CashBuyerProfile { address: string; /** Lifetime intents this buyer has signaled (all statuses). */ totalIntents: number; /** Intents completed: fiat paid, proven, escrow released. */ fulfilled: number; /** Intents that expired unpaid and were pruned. */ pruned: number; /** Intents currently open. */ signaled: number; /** fulfilled / (fulfilled + pruned) in basis points; undefined until they have history. */ successRateBps?: number; /** Unix seconds of the buyer's first and latest signal. */ firstSeenAt?: number; lastSeenAt?: number; } interface CashPayoutBase { /** Payment platform / processor name, e.g. `'venmo'`, `'revolut'`, `'wise'`. */ processorName: string; /** The user's payee handle for that platform (e.g. a Venmo username, Wisetag). */ payeeData: CuratorPayeeDataInput; } /** One payment method offering either one currency or a non-empty currency set. */ type CashPayout = CashPayoutBase & ({ currency: CurrencyType; currencies?: never; } | { currency?: never; currencies: readonly [CurrencyType, ...CurrencyType[]]; }); /** * Input to create a market-rate (0% spread) cash-out deposit. * * Deliberately narrow: no rate/spread knobs, no vault/DRM delegate, no * retain-on-empty override - a cash-out is a one-shot order that cleans up * when fully filled. The API cannot express what Peer Cash does not offer. */ interface CashDepositInput { /** Deposit asset - Base USDC (defaults to {@link BASE_USDC_ADDRESS}). */ token?: Address; /** Total amount to cash out, in USDC base units (6 decimals). */ amount: bigint; /** One or more payout legs (platform + currency choice + payee). */ payouts: CashPayout[]; /** Per-order min/max in USDC base units. Defaults derive from {@link buildIntentAmountRange}. */ intentAmountRange?: { min: bigint; max: bigint; }; } interface CashAsset { chainId: number; address: string; symbol: string; decimals: number; name?: string; isNative?: boolean; } interface CashChain { id: number; name: string; displayName: string; disabled: boolean; depositEnabled: boolean; blockProductionLagging: boolean; vmType?: string; tokens: CashAsset[]; } interface CashSourceCapabilities { destination: CashAsset; chains: CashChain[]; source: 'relay-sdk'; asOf: number; } interface RelayOptions { apiUrl?: string; apiKey?: string; source?: string; client?: RelayClient; chains?: RelayChain[]; } interface RelaySourceInput { chainId: number; currency: string; } interface RelayQuoteInput { user: string; /** Interpreted according to `tradeType`; defaults to exact source input. */ amount: bigint; source: RelaySourceInput; recipient?: string; tradeType?: 'EXACT_INPUT' | 'EXACT_OUTPUT' | 'EXPECTED_OUTPUT'; } interface RelayQuote { requestId?: string; source: CashAsset; destination: CashAsset; /** Source amount Relay expects the route to consume. */ inputAmount: bigint; /** Conservative Base USDC output (Relay minimum output when supplied). */ outputAmount: bigint; rate?: number; timeEstimateSeconds?: number; fees?: unknown; txs: PreparedTransaction[]; raw: Execute; } interface RelayExecutionResult { requestId?: string; txHashes: string[]; /** Chain-aware evidence (emitted by 0.1.4+; optional for wire compatibility). */ transactions?: { origin: RelayTransaction[]; destination: RelayTransaction[]; }; quote: Execute; } interface RelayTransaction { hash: string; chainId: number; /** Relay batch-call identifiers are not transaction hashes. */ isBatchTx?: boolean | undefined; } interface RelayStatus { requestId: string; status: 'refund' | 'waiting' | 'depositing' | 'failure' | 'pending' | 'submitted' | 'success'; details?: string; inTxHashes: string[]; txHashes: string[]; updatedAt?: number; originChainId?: number; destinationChainId?: number; quoteCreatedAt?: number; raw: unknown; } /** * Peer Cash - engine constants. * * Peer Cash is an async crypto→fiat offramp built on the maker/deposit side of * the protocol: the cashing-out user IS the maker. They create a deposit at the * zero-spread market rate; a buyer (a standard taker) signals an * intent, pays fiat, and proves it via the standard TEE-TLS flow, releasing the * user's crypto. The protocol is reused in its existing direction - no proof * inversion, no sell-side quote. */ /** Base chain id - Peer Cash settles in Base USDC. */ declare const BASE_CHAIN_ID = 8453; /** Canonical USDC on Base (6 decimals). The deposit asset for every cash-out. */ declare const BASE_USDC_ADDRESS: "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"; /** USDC has 6 decimals. */ declare const USDC_DECIMALS = 6; /** * Signal-time oracle corridors use zero spread. Alipay/CNY instead fixes a * fresh creation-time snapshot because Base has no CNY oracle adapter. */ declare const MARKET_SPREAD_BPS = 0; /** * EscrowV2 rejects a zero `minConversionRate` even when an oracle-backed rate * config is attached. Use the smallest non-zero sentinel so the oracle rate * still fully determines pricing while satisfying the on-chain invariant. */ declare const ORACLE_MIN_CONVERSION_RATE_SENTINEL = 1n; /** * The full intent-status set a cash-out order can pass through. The indexer's * `getIntentsForDeposits` defaults to `['SIGNALED']` only - passing this * explicit set is REQUIRED, otherwise `delivered`/`returned` states are * silently filtered out. */ declare const CASH_ORDER_STATUSES: IntentStatus[]; /** Default polling cadence for an in-flight order (ms). Matches the protocol's active-intent polling. */ declare const CASH_ORDER_POLL_INTERVAL_MS = 5000; /** * Default deposit config for every Peer Cash deposit: a one-shot cash-out * cleans up when fully filled rather than lingering empty. */ declare const CASH_RETAIN_ON_EMPTY = false; declare const NEAR_INTENTS_API_URL = "https://1click.chaindefuser.com"; declare const NEAR_INTENTS_BASE_USDC_ASSET_ID = "nep141:base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913.omft.near"; declare const NEAR_INTENTS_DEFAULT_SLIPPAGE_BPS = 100; interface NearIntentsToken { [key: string]: unknown; assetId: string; symbol: string; decimals: number; blockchain: string; price?: string | number | null | undefined; priceUpdatedAt?: string | undefined; contractAddress?: string | null | undefined; } interface NearIntentsSourceCapabilities { destination: { assetId: typeof NEAR_INTENTS_BASE_USDC_ASSET_ID; chainId: typeof BASE_CHAIN_ID; address: typeof BASE_USDC_ADDRESS; symbol: 'USDC'; decimals: typeof USDC_DECIMALS; }; assets: NearIntentsToken[]; source: 'near-intents'; asOf: number; } interface NearIntentsOptions { /** 1Click origin. Defaults to the official API, or to the app proxy root in proxy mode. */ apiUrl?: string; /** Server-side 1Click JWT. Never expose this option in browser code. */ token?: string; fetch?: typeof globalThis.fetch; /** Direct uses official `/v0/*` endpoints; proxy uses `/tokens|quote|submit|status`. */ transport?: 'direct' | 'proxy'; timeoutMs?: number; } type NearIntentsTradeType = 'EXACT_INPUT' | 'EXACT_OUTPUT'; interface NearIntentsQuoteInput { /** NEAR Intents asset id from `nearIntentsCapabilities()`. */ sourceAsset: string; /** Source units for EXACT_INPUT; Base USDC units for EXACT_OUTPUT. */ amount: bigint; /** Base address that will receive canonical USDC. */ recipient: string; /** Refund address on the source chain. */ refundTo: string; tradeType: NearIntentsTradeType; deadline: string; slippageTolerance?: number; dry?: boolean; } interface NearIntentsQuoteRequest { dry: boolean; swapType: NearIntentsTradeType; slippageTolerance: number; originAsset: string; depositType: 'ORIGIN_CHAIN'; destinationAsset: typeof NEAR_INTENTS_BASE_USDC_ASSET_ID; amount: string; refundTo: string; refundType: 'ORIGIN_CHAIN'; recipient: string; recipientType: 'DESTINATION_CHAIN'; deadline: string; depositMode: 'SIMPLE'; } interface NearIntentsQuote { provider: 'near-intents'; correlationId?: string; sourceAsset: string; destinationAsset: typeof NEAR_INTENTS_BASE_USDC_ASSET_ID; inputAmount: bigint; minInputAmount: bigint; outputAmount: bigint; minOutputAmount: bigint; timeEstimateSeconds?: number; depositAddress?: string; depositMemo?: string; deadline?: string; signature: string; request: NearIntentsQuoteRequest; raw: unknown; } interface NearIntentsDepositInput { depositAddress: string; txHash: string; depositMemo?: string; } interface NearIntentsStatusInput { depositAddress: string; depositMemo?: string; /** Persisted signed quote used to reject status for a different route identity. */ expectedQuote?: NearIntentsQuote; } declare const NEAR_INTENTS_STATUSES: readonly ["PENDING_DEPOSIT", "KNOWN_DEPOSIT_TX", "PROCESSING", "SUCCESS", "INCOMPLETE_DEPOSIT", "REFUNDED", "FAILED"]; type NearIntentsStatusCode = (typeof NEAR_INTENTS_STATUSES)[number]; interface NearIntentsTransaction { hash: string; explorerUrl?: string; } interface NearIntentsStatus { provider: 'near-intents'; correlationId?: string; depositAddress: string; depositMemo?: string; status: NearIntentsStatusCode; updatedAt?: string; inputAmount?: bigint; outputAmount?: bigint; refundedAmount?: bigint; refundReason?: string; intentHashes: string[]; nearTransactionHashes: string[]; originTransactions: NearIntentsTransaction[]; destinationTransactions: NearIntentsTransaction[]; raw: unknown; } interface NearIntentsClient { capabilities(): Promise; quoteToBaseUsdc(input: NearIntentsQuoteInput): Promise; submitDeposit(input: NearIntentsDepositInput): Promise; status(input: NearIntentsStatusInput): Promise; } declare function createNearIntentsClient(options?: NearIntentsOptions): NearIntentsClient; declare function readNearIntentsSourceCapabilities(options?: NearIntentsOptions): Promise; declare function quoteNearIntentsToBaseUsdc(input: NearIntentsQuoteInput, options?: NearIntentsOptions): Promise; declare function submitNearIntentsDeposit(input: NearIntentsDepositInput, options?: NearIntentsOptions): Promise; declare function readNearIntentsStatus(input: NearIntentsStatusInput, options?: NearIntentsOptions): Promise; /** Hard floor: below one cent a deposit is dust and can never fill. */ declare const MIN_CASHOUT_AMOUNT = 10000n; /** Recommended floor: sub-1-USDC deposits force min==max fills and starve matching. */ declare const RECOMMENDED_MIN_CASHOUT_AMOUNT = 1000000n; type CashCorridorPricing = { kind: 'oracle-at-intent-signal'; spreadBps: 0; } | { kind: 'fixed-at-deposit-creation'; source: 'chainlink-ethereum'; spreadBps: 0; }; interface CashPlatformCapability { /** Platform id, e.g. `'venmo'` - the value `receive.platform` accepts. */ platform: string; /** Supported currencies this platform can pay out. */ currencies: CurrencyType[]; /** Pricing semantics for each advertised currency. */ pricing: Partial>; /** Human hint for the payee handle format. */ payeeHint: string; /** * When true, registering a payee for this platform requires a signed maker * identity attestation the SDK cannot produce. First-party Peer web obtains * it through the Peer TEE browser extension. Existing registrations can be * reused with bare payee data; a new bare handle throws * `PAYEE_VERIFICATION_REQUIRED`. */ requiresIdentityAttestation: boolean; /** * @deprecated Always false. This does not report the sequential restricted- * platform policy; prepared hosts must inspect * `PrepareResult.accessPolicyPaymentMethods`. */ requiresAtomicAccessPolicy: boolean; } interface CashCapabilities { chainId: number; token: { address: string; symbol: 'USDC'; decimals: number; }; environment: RuntimeEnv; /** Destination asset for every Peer Cash order. */ destination: { chainId: number; token: { address: string; symbol: 'USDC'; decimals: number; }; }; /** * Source discovery. The sync default is Base USDC only; pass * `{ includeRelaySources: true }` or `{ includeNearIntentsSources: true }` * to `capabilities()` for live bridge source assets. */ source: { default: { chainId: number; token: { address: string; symbol: 'USDC'; decimals: number; }; }; relay?: CashSourceCapabilities; nearIntents?: NearIntentsSourceCapabilities; }; /** Every payout corridor supported by the Cash product. */ platforms: CashPlatformCapability[]; /** All supported currencies across platforms. */ currencies: CurrencyType[]; /** Amount bounds in USDC base units. */ amount: { min: bigint; recommendedMin: bigint; max: null; }; /** Default pricing for corridors without a platform-level creation-time exception. */ pricing: { kind: 'oracle-market-rate'; spreadBps: 0; }; } declare function buildCapabilities(environment: RuntimeEnv): CashCapabilities; interface CashPairFillStats { /** Fulfilled intents through this pair or currency set inside the rolling 30-day window. */ fills: number; /** Median deposit-to-first-fill seconds, sampled once per deposit for this pair or set. */ medianFillSeconds?: number; } /** * Raw demand and speed evidence keyed by `basePlatform:currencyCode` or a * sorted multi-currency set such as `revolut:EUR+GBP+USD`. */ type CashFillStats = Record; interface CashFillEta { /** Simple headline ETA from recent deposits. Undefined when no recent sample exists. */ seconds?: number; /** Display-ready copy. Historical, not a guarantee. */ label: string; } /** * Estimate - currency + amount only. No payee, no side effects, no expiry, * idempotent, cacheable. * * Existing corridors read the same Chainlink feed the protocol uses when an * intent is signaled. Creation-rate corridors read Chainlink on Ethereum (CNY) * or Polygon (INR), fixing the fresh snapshot when preparing the deposit. */ interface EstimateInput { /** * Without `source`, Base USDC base units. With `source`, Relay interprets * this according to `tradeType`; default `EXACT_INPUT` uses source-token units. */ amount: bigint; /** Target fiat currency. */ currency: CurrencyType; /** Optional payout platform for pricing semantics and pair-specific ETA sampling. */ platform?: string; /** Optional Relay EVM source asset. Omit for the current Base USDC default path. */ source?: RelaySourceInput & { /** Source wallet that will submit Relay's origin transaction. Required by Relay quote. */ user: string; /** Base recipient for bridged USDC; defaults to `user`. */ recipient?: string; /** Relay amount mode. Omit for the recommended exact source-input estimate. */ tradeType?: 'EXACT_INPUT' | 'EXACT_OUTPUT' | 'EXPECTED_OUTPUT'; }; } interface EstimateOptions { /** * Include the historical indexer-backed ETA. Disable for progressive UIs * that render the oracle rate first and load pair fill stats separately. */ includeEta?: boolean; } interface CashEstimate { /** Always `'oracle-estimate'`; inspect `binding` for when it becomes a maker floor. */ kind: 'oracle-estimate'; /** When this estimate becomes the deposit's binding maker floor. */ binding?: 'intent-signal' | 'deposit-creation'; currency: CurrencyType; /** Base USDC amount that Peer Cash would deposit after any source routing. */ amount: bigint; /** Target-currency units per 1 USDC at the time of the read. */ rate: number; /** `amount × rate` in target-currency units. */ receiveAmount: number; /** Unix seconds when the oracle was read. */ asOf: number; /** Unix seconds the Chainlink feed last updated (absent for the USD passthrough). */ oracleUpdatedAt?: number; /** True when the feed reading is older than a day - treat the rate with caution. */ stale?: boolean; /** Optional source asset route. Absent means same-chain Base USDC. */ source?: { kind: 'relay'; asset: CashAsset; inputAmount: bigint; relayQuote: RelayQuote; }; /** Simple recent-fill ETA from indexer history. */ eta?: CashFillEta; } type CashPayeeInput = string | CuratorPayeeDataInput; /** Convert user-entered handles into the curator form for a payment platform. */ declare function normalizeCashPayee(platform: string, payee: CashPayeeInput): CuratorPayeeDataInput; /** * `createCashClient` - the cash lifecycle facade over a read-only `Zkp2pClient`. * * The facade keeps the outward surface tiny (capabilities / estimate / cashout * / order / orders / watch / withdraw / topUp) while reusing the published * SDK's battle-tested internals. A React app, a Node service, and an AI agent * are equal consumers: Base-USDC mutations have unsigned `prepare` paths, * Relay execution is explicitly signer-backed, every wire type is serializable, * and every protocol transaction carries ERC-8021 attribution * ({@link CASH_ATTRIBUTION_CODE}). */ /** * ERC-8021 attribution code stamped on every transaction this package * produces (signed and prepare paths, including approves). The optional * namespaced `CashClientOptions.referralCode` marker and analytics-only * `referrer` codes follow it; the SDK appends the Base builder code last. */ declare const CASH_ATTRIBUTION_CODE = "peer-cash"; declare const CASH_REFERRAL_ATTRIBUTION_PREFIX = "peer-ref-"; /** Convert a Peer referral code into its financially meaningful ERC-8021 marker. */ declare function toCashReferralAttributionCode(rawCode: string): string; interface PreparedVenmoGmailConnect { payeeDetails: Hash; url: string; } interface CashClientOptions { /** `'production' | 'preproduction' | 'staging'` - selects contracts, curator, and indexer. */ environment: RuntimeEnv; /** viem transport for RPC reads; defaults to the public Base RPC. */ transport?: Transport; /** Convenience alternative to `transport`. */ rpcUrl?: string; /** Indexer URL override. */ indexerUrl?: string; /** Optional indexer API key. */ indexerApiKey?: string; /** Curator (ZKP2P API) URL override. */ curatorUrl?: string; /** Peer web origin override for optional Venmo receipt linking. Defaults by environment. */ peerOrigin?: string; /** Optional ZKP2P API key. */ apiKey?: string; /** Ethereum transport used only to snapshot Alipay/CNY's creation-time rate. */ creationRateTransport?: Transport; /** Convenience alternative to `creationRateTransport`. */ creationRateRpcUrl?: string; /** Polygon transport used only to snapshot UPI/INR's creation-time rate. */ upiCreationRateTransport?: Transport; /** Convenience alternative to `upiCreationRateTransport`; requires Polygon mainnet. */ upiCreationRateRpcUrl?: string; /** Relay API configuration for source assets outside Base USDC. */ relay?: RelayOptions; /** NEAR Intents 1Click configuration for externally funded source routes. */ nearIntents?: NearIntentsOptions; /** * Your six-character referral code from the Peer mobile or web app. The SDK * emits `peer-ref-XXXXXX`; when this deposit fills, Curator routes the * integration share to the Privy wallet that owns the code. */ referralCode?: string; /** * Analytics-only ERC-8021 attribution code(s), appended after the Peer Cash * and optional integration-referral markers (e.g. `'acme-app'`). */ referrer?: string | string[]; } /** One payout leg: platform + currency + payee handle. */ interface CashLeg { /** Platform id from `capabilities()`, e.g. `'venmo'`. */ platform: string; /** Fiat currency to receive. */ currency: CurrencyType; /** Raw handle or prepared curator data (needed for identity attestations). */ payee: CashPayeeInput; currencies?: never; } interface CashMultiCurrencyLeg { /** Platform id from `capabilities()`, e.g. `'revolut'`. */ platform: string; /** Fiat currencies a buyer may use to fill this cash-out. */ currencies: readonly [CurrencyType, ...CurrencyType[]]; /** Raw handle or prepared curator data shared by every offered currency. */ payee: CashPayeeInput; currency?: never; } /** One payout leg of a cash-out - single-currency or multi-currency. */ type CashReceiveLeg = CashLeg | CashMultiCurrencyLeg; interface CashoutInput { /** * Amount to cash out. Without `source`, this is Base USDC base units. With * `source`, Relay interprets it according to `tradeType`; the default * `EXACT_INPUT` treats it as source-token base units. */ amount: bigint; /** Optional Relay source asset. Omit for the Base USDC default path. */ source?: RelaySourceInput & { /** Base recipient for bridged USDC; defaults to the signer address. */ recipient?: string; /** Relay amount mode. Omit for the recommended exact source-input flow. */ tradeType?: 'EXACT_INPUT' | 'EXACT_OUTPUT' | 'EXPECTED_OUTPUT'; }; /** * Where the fiat should arrive. One leg, or an array of legs to offer the * buyer several payout platforms (each platform at most once). One method * may offer multiple currencies. Inspect `capabilities().platforms[].pricing` * for whether a corridor binds at intent signal or deposit preparation. */ receive: CashReceiveLeg | readonly [CashReceiveLeg, ...CashReceiveLeg[]]; /** Per-order min/max override (USDC base units). */ intentAmountRange?: { min: bigint; max: bigint; }; } interface SignerOptions { /** Any viem WalletClient with a Base account, including a local or external EOA. */ signer: WalletClient; } interface CashoutOptions extends SignerOptions { /** Source-chain signer for Relay. Required when `input.source.chainId` is not Base. */ sourceSigner?: WalletClient; /** Relay execution progress callback when `input.source` is present. */ onSourceProgress?: (data: ProgressData) => void; /** Forwarded to Relay SDK for wallets with broken EIP-5792 capability calls. */ disableSourceCapabilitiesCheck?: boolean; } interface WithdrawOptions extends SignerOptions { /** * Partial amount to withdraw (USDC base units). Only unlocked funds are * withdrawable partially - a live buyer intent does not block it. Omit to * close the order fully (prunes expired intents first when needed). */ amount?: bigint; } interface TopUpResult { depositId: string; txHash: Hash; } type CashPreparedStepKind = 'approve' | 'createDeposit' | 'pruneExpiredIntents' | 'withdrawDeposit' | 'removeFunds' | 'addFunds'; interface CashPreparedStep { /** Stable action label for the transaction at the same index in `txs[]`. */ kind: CashPreparedStepKind; /** Human-readable reason to show in approval UIs, logs, or policy reviews. */ description: string; } interface CashoutResult { /** Composite deposit id (`escrow_onchainId`) - the resume key. Bind it to your user. */ depositId: string; txHash: Hash; escrowAddress: string; onchainDepositId: bigint; /** Optimistic snapshot (`awaiting-buyer`); poll `order(depositId)` for live state. */ order: CashOrder; /** Last confirmed access-policy transaction. Retained for single-policy compatibility. */ accessPolicyTxHash?: Hash; /** Confirmed method-scoped policy transactions for restricted payout legs. */ accessPolicyTxHashes?: Hash[]; /** Present when `cashout()` first routed a source asset through Relay. */ source?: { /** Conservative Base USDC amount deposited (Relay's guaranteed minimum output). */ amount: bigint; requestId?: string; txHashes: string[]; /** Chain-aware evidence (emitted by 0.1.4+; optional for wire compatibility). */ transactions?: { origin: RelayTransaction[]; destination: RelayTransaction[]; }; }; } interface PrepareResult { /** * Unsigned transactions in submission order: `[approve, createDeposit]`. * Submit with any signer - agent wallet, AA bundler, server key. Drop the * approve when the escrow already has sufficient allowance. */ txs: PreparedTransaction[]; /** One label per transaction in `txs[]`, same order. */ steps: CashPreparedStep[]; /** Curator payee registration output - the payee hashes now live on the deposit params. */ register: { hashedOnchainIds: string[]; }; /** Whether the host must submit and confirm the policy after `createDeposit` confirms. */ accessPolicyRequired: boolean; /** Method hashes that each require a post-deposit Peer Pay policy transaction. */ accessPolicyPaymentMethods: Hex[]; } /** Confirmed createDeposit receipt from an externally executed prepare() plan. */ interface PreparedCashoutReceipt { transactionHash: Hash; status: 'success' | 'reverted'; logs: readonly Log[]; } interface WithdrawResult { depositId: string; /** Present when expired intents had to be pruned before withdrawal. */ pruneTxHash?: Hash; withdrawTxHash: Hash; } interface WatchOptions { signal?: AbortSignal; pollIntervalMs?: number; timeoutMs?: number; } interface OrdersOptions { /** Only orders still needing attention (`awaiting-buyer` / `matched` / `delivering`). */ inFlight?: boolean; /** Max deposits to scan (default 100). */ limit?: number; } interface CashClient { /** Optional: register the Venmo handle before enabling a separate link button. No deposit. */ prepareVenmoGmailConnect(payee: string): Promise; /** Optional, browser-only: call directly from a click handler with the prepared payee hash. */ openVenmoGmailConnect(payeeDetails: Hash): Promise; /** True only for an active Google receipt credential; errors reject instead of reporting unlinked. */ isVenmoGmailConnected(payeeDetails: Hash): Promise; /** 0 - Discovery: sync, static. */ capabilities(): CashCapabilities; /** 0b - Discovery with live Relay-supported EVM source chains/tokens. */ capabilities(options: { includeRelaySources: true; includeNearIntentsSources?: true; }): Promise; /** 0c - Discovery with live NEAR Intents 1Click source assets. */ capabilities(options: { includeRelaySources?: true; includeNearIntentsSources: true; }): Promise; /** * 0d - Raw 30-day demand and first-fill speed evidence keyed by an exact * `platform:currency` pair or sorted multi-currency set. A recommended * consumer gate is `fills >= 10 && medianFillSeconds <= 48h`; fail open to * the full capability catalog when stats are unavailable or the gate would * remove every pair. */ fillStats(): Promise; /** Relay-only source discovery helper. */ sourceCapabilities(): Promise; /** Quote any Relay-supported EVM source asset into Base USDC. */ quoteSource(input: RelayQuoteInput): Promise; /** Execute a Relay SDK quote into Base USDC before starting the Peer Cash order. */ executeSourceQuote(quote: RelayQuote | Execute, opts: { /** Wallet signer on the quote's source chain. */ signer: WalletClient; /** Expected Base recipient. Defaults to the source signer. */ recipient?: string; onProgress?: (data: ProgressData) => void; disableCapabilitiesCheck?: boolean; }): Promise; /** Track Relay execution status by quote/request id. */ relayStatus(requestId: string): Promise; /** Discover live NEAR Intents assets that can route into canonical Base USDC. */ nearIntentsCapabilities(): Promise; /** Quote a NEAR Intents external-deposit route into canonical Base USDC. */ quoteNearIntentsSource(input: NearIntentsQuoteInput): Promise; /** Optionally register an already-broadcast origin transaction with 1Click. */ submitNearIntentsDeposit(input: NearIntentsDepositInput): Promise; /** Track a NEAR Intents route by its provider-issued deposit address and memo. */ nearIntentsStatus(input: NearIntentsStatusInput): Promise; /** 1 - Estimate: currency + amount only. No payee, no side effects, no expiry. */ estimate(input: EstimateInput, options?: EstimateOptions): Promise; /** 2 - Cash out: payee registration + deposit params + submission happen here. */ cashout(input: CashoutInput, opts: CashoutOptions): Promise; /** 2b - Unsigned path: `txs[]` for agent wallets, AA, server keys, policy layers. */ prepare(input: CashoutInput): Promise; /** Resolve an externally executed createDeposit receipt into resumable cash-out state. */ finalizePreparedCashout(receipt: PreparedCashoutReceipt): CashoutResult; /** Prepare one method-scoped Peer Pay follow-up for a restricted cash-out. */ prepareAccessPolicy(depositId: string, paymentMethod: Hex): PreparedTransaction; /** 3 - Observe: resumable from `depositId` alone; no session state anywhere. */ order(depositId: string): Promise; /** * 3b - Observe helper: a buyer's protocol track record from their full * intent history. Answers "who just matched my order?" during `matched`. */ buyer(address: string): Promise; /** 4 - List: indexer-native. A cash order IS a deposit; the chain is the database. */ orders(owner: string, opts?: OrdersOptions): Promise; /** 5 - Watch: yields on change; ends at a terminal state, abort, or timeout. */ watch(depositId: string, opts?: WatchOptions): AsyncGenerator; /** * 6 - Withdraw: ONE unwind verb. With `amount`, withdraws that much of the * unlocked balance (partial; a live buyer intent does not block it). * Without, closes the order fully - pruning expired intents first when * needed. */ withdraw(depositId: string, opts: WithdrawOptions): Promise; /** * 6b - Unsigned path for the unwind verb (agent surface): the same state * checks as `withdraw()`, returning `txs[]` for host-side signing. */ prepareWithdraw(depositId: string, opts?: { amount?: bigint; }): Promise<{ txs: PreparedTransaction[]; steps: CashPreparedStep[]; }>; /** 7 - Top up: add USDC to a live order (same payee, same market rate). */ topUp(depositId: string, amount: bigint, opts: SignerOptions): Promise; /** 7b - Unsigned path: `[approve, addFunds]` for host-side signing. */ prepareTopUp(depositId: string, amount: bigint): Promise<{ txs: PreparedTransaction[]; steps: CashPreparedStep[]; }>; } declare function createCashClient(options: CashClientOptions): CashClient; export { type EstimateInput as $, type CashChain as A, BASE_CHAIN_ID as B, type CashPayoutInfo as C, type CashClient as D, type CashClientOptions as E, type CashCorridorPricing as F, type CashFillEta as G, type CashLeg as H, type IntentEntity as I, type CashMultiCurrencyLeg as J, type CashNextAction as K, type CashOrderState as L, type CashPairFillStats as M, type NearIntentsSourceCapabilities as N, type CashPayeeInput as O, type PrepareResult as P, type CashPayout as Q, type RelayExecutionResult as R, type CashPayoutPricing as S, type TopUpResult as T, type CashPlatformCapability as U, type CashPreparedStepKind as V, type WithdrawResult as W, type CashReceiveLeg as X, type CashoutInput as Y, type CashoutOptions as Z, type CuratorPayeeDataInput as _, type CashBuyerProfile as a, type EstimateOptions as a0, MARKET_SPREAD_BPS as a1, MIN_CASHOUT_AMOUNT as a2, NEAR_INTENTS_API_URL as a3, NEAR_INTENTS_BASE_USDC_ASSET_ID as a4, NEAR_INTENTS_DEFAULT_SLIPPAGE_BPS as a5, NEAR_INTENTS_STATUSES as a6, type NearIntentsClient as a7, type NearIntentsOptions as a8, type NearIntentsQuoteRequest as a9, type NearIntentsStatusCode as aa, type NearIntentsToken as ab, type NearIntentsTradeType as ac, type NearIntentsTransaction as ad, ORACLE_MIN_CONVERSION_RATE_SENTINEL as ae, type OrdersOptions as af, type PreparedCashoutReceipt as ag, RECOMMENDED_MIN_CASHOUT_AMOUNT as ah, type RelayOptions as ai, type RelayQuoteInput as aj, type RelaySourceInput as ak, type RelayTransaction as al, type SignerOptions as am, USDC_DECIMALS as an, type WatchOptions as ao, type WithdrawOptions as ap, buildCapabilities as aq, createCashClient as ar, createNearIntentsClient as as, normalizeCashPayee as at, quoteNearIntentsToBaseUsdc as au, readNearIntentsSourceCapabilities as av, readNearIntentsStatus as aw, submitNearIntentsDeposit as ax, toCashReferralAttributionCode as ay, type CashDepositInput as b, type CreateDepositParamsArg as c, type CashOrder as d, type CashFill as e, type CashCapabilities as f, type CashoutResult as g, type CashEstimate as h, type CashFillStats as i, type NearIntentsDepositInput as j, type NearIntentsQuote as k, type NearIntentsQuoteInput as l, type NearIntentsStatus as m, type NearIntentsStatusInput as n, type CashPreparedStep as o, type PreparedVenmoGmailConnect as p, type RelayQuote as q, type RelayStatus as r, type CashSourceCapabilities as s, BASE_USDC_ADDRESS as t, CASH_ATTRIBUTION_CODE as u, CASH_ORDER_POLL_INTERVAL_MS as v, CASH_ORDER_STATUSES as w, CASH_REFERRAL_ATTRIBUTION_PREFIX as x, CASH_RETAIN_ON_EMPTY as y, type CashAsset as z };