/** * `px402` — a wallet for privacy-preserving x402 payments. * * The drop-in, x402's own three lines (`dropin.ts`): * * ```ts * import { wrapFetchWithPayment } from "px402"; * * const pay = wrapFetchWithPayment(fetch, account); // or a 0x private key * const res = await pay("https://api.example.com/data"); * ``` * * It derives the seed from the key, funds the wallet from the key's address * in whole floats, and pays on Base through PRXVT's hosted services unless * told otherwise. One key then controls the address and the coins. * The explicit path, below, keeps the depositor's key out of the SDK: * * ```ts * import { chainConfig, px402 } from "px402"; * * const chain = chainConfig(); // Base's reserve, domain separator, RPC * const wallet = await px402.recover({ seed, issuer, chain }); // every start (§6.10); * // px402.open only for a seed never used * const fetch402 = wallet.wrapFetch(fetch, { privacy: "strict" }); * * wallet.runway(); // spendable capacity, and whether it was measured * wallet.depositTx("25.00"); // UNSIGNED tx for the user's own wallet * await wallet.prewarm(target); // withdraw into the coin buffer -- well * // before you spend: a spend soon after * // its own withdrawal is attributable * // by timing (v3 §25.3) * await wallet.ready({ amountBaseUnits: presented }); // the price plus the * // facilitator's fee, rounded * // up (v3 §25.1). §9.1 holds * // each coin one issuance * // window; this is when that * // hold lifts, and where * // leftover residual is * // melted (v3 §25.2) * wallet.receipts.list(); * wallet.receipts.export("csv"); * ``` * * `px402.recover` with no `sources` reads the SDK's public ones (`sources`): * the issuer's `/log`, the chain through `chain.rpcUrl`, and the registry's * spent totals. `px402.open` refuses a seed that has been used * (`PX402SeedUsedError`). * * # Read this before you deploy it * * **The seed derives the coin keys *and* the reserve key.** An attacker who * compromises the agent gets the coin buffer **and the entire reserve * balance** — they can authorize withdrawals and sweep the reserve with * `reclaimBalance`. What survives is the external depositor wallet, whose key * this SDK never holds, so the blast radius is capped at what is already in * that reserve. **Keep reserve balances near one refill cycle.** The full * statement is on {@link px402}. * * # What each layer is * * - `encoding`, `kdf`, `selectSeeded` — the byte-level primitives every other * module shares, byte-for-byte equal to `crates/px402-core`. * - `keys`, `blind`, `refresh` — coin derivation, RFC 9474 blind signatures, * and §6.6's refresh. * - `denom`, `terms` — the keyset and the EIP-712 contract terms. * - `commitment` — §4's mandatory "is this keyset committed on-chain" check, * which `px402.open` now runs for you. * - `client`, `errors` — the issuer protocol and §6.5's taxonomy. * - `store`, `spend`, `fetch` — the coin buffer, deposit permissions, and the * x402 wrapper. * - `bridge`, `recourse` — the exact-scheme bridge (v3 §26): a merchant that * quotes only `exact` is paid through a relayer's EIP-3009 authorization, * which the wallet checks and delivers (`wrapFetch`'s `bridge` option), and * the payer's own recourse when the merchant was not paid * (`wallet.pursueBridgeRecourse()`). * - `refresher` — the driver that melts the residual §7 retires and puts it * back as coins no merchant has seen; `meltScheduler` — when it runs: after * the payment that made the residual, never beside a spend (v3 §25.2). * - `recover`, `receipts`, `wallet` — §6.10 recovery (with its progress, * `onProgress`), the local receipt chain, and the surface above; `sources` — * the chain reads over JSON-RPC, the default recovery sources, and the scan * checkpoint that lets the next recovery's log scan start where this one * stopped (`wallet.recoveryCheckpoint()`). * - `quotedPrice` (in `fetch`) — what a 402 asks, px402 or `exact`, before * anything is paid. * - `dropin` — `wrapFetchWithPayment` and `createWallet`, over everything * else: `networks` (the presets and where each service URL comes from), * `keyseed` (a seed from a private key or an account's EIP-712 signature), * `topup` (deposits in whole floats from the signer, withdrawals by the * wallet's own rule) and `evm` (an EIP-1559 transaction, signed and sent). * - `keyring` — every key epoch a wallet holds coins of (K1): a new epoch * changes nothing an agent does. Old coins spend beside new ones, each * presented with its own keyset; their change melts into the new epoch; * withdrawals use the newest. Only an epoch the issuer can no longer * refresh asks anything of the agent (`PX402EpochRetiredError`). * * Everything is exported: the layers below `wallet` are usable on their own, * because a facilitator, a verifier or a second wallet implementation needs * the primitives without the buffer. */ export { createWallet, wrapFetchWithPayment, REFILL_DELAY_MAX_SECONDS, type CreateWalletOptions, type DropInOptions, type PaidFetch, type PaymentOptions, type PaymentSigner, type WalletState, type WalletStore, } from "./dropin.js"; export { chainConfig, networks, networkForChain, resolveGasless, resolveNetwork, resolveServices, resolveSetting, BASE_MAINNET_GASLESS_DEPOSITOR, DEFAULT_NETWORK, ENV_VARS, GASLESS_ENV_VARS, NETWORK_ENV_VAR, PX402MissingSettingError, PX402NetworkNotDeployedError, type ChainConfigOptions, type Network, type NetworkName, type NetworkServices, type NetworkSetting, type ResolvedGasless, type ResolvedServices, type ServiceOverrides, type UndeployedNetwork, } from "./networks.js"; export { seedFromAccount, seedFromPrivateKey, seedTypedData, seedTypedDataDigest, signSeedTypedData, PX402NondeterministicSignerError, SEED_FROM_SIGNATURE_INFO, SEED_TYPED_DATA_PURPOSE, SEED_TYPED_DATA_TYPE, SEED_TYPED_DATA_VERSION, type AccountTransaction, type PaymentAccount, type SeedTypedData, } from "./keyseed.js"; export { AutoFunder, PX402AutoFundLimitError, PX402InsufficientFundsError, DEFAULT_FLOAT_BASE_UNITS, DEFAULT_MAX_AUTO_DEPOSIT_FLOATS, DEFAULT_MAX_SPONSOR_FEE, GASLESS_SUBMIT_ROUNDS, GASLESS_VALIDITY_SECONDS, DEPOSIT_GAS_BUDGET, DEPOSIT_GAS_LIMIT, BALANCE_RECHECKS, ISSUER_LAG_RETRIES, TOPUP_ATTEMPTS, type AutoFunderOptions, type FundableWallet, type FundingTarget, type GaslessFunding, } from "./topup.js"; export { accountAuthorizationSigner, gaslessDepositNonce, keyAuthorizationSigner, postSponsor, readSponsorOffer, receiveAuthorizationDigest, receiveAuthorizationTypedData, PX402SponsorError, GASLESS_DEPOSIT_TYPE, RECEIVE_WITH_AUTHORIZATION_TYPE, type AuthorizationSigner, type ReceiveAuthorization, type ReceiveAuthorizationTypedData, type SponsorAnswer, type SponsorOffer, type SponsorRefusal, type SponsorRequestWire, } from "./gasless.js"; export { EvmRpc, accountSigner, keySigner, rlpEncode, signEip1559, transactionHashOf, RPC_LAG_BACKOFF_MAX_MS, RPC_LAG_BACKOFF_MS, RPC_LAG_RETRIES, type Eip1559Transaction, type EvmRpcOptions, type MinedReceipt, type RlpItem, type TransactionSigner, } from "./evm.js"; export { px402, Wallet, PX402ConfigError, USDC_DECIMALS, REFILL_HORIZON_SECONDS, REFILL_JITTER, DEFAULT_OBSERVATION_WINDOW_SECONDS, DEFAULT_MIN_RUNWAY_BASE_UNITS, DEFAULT_ASSUMED_CALL_COST_BASE_UNITS, DEFAULT_MAX_COINS_PER_REFILL, DEFAULT_PRICE_HISTORY_LIMIT, DEFAULT_WITHDRAW_DEADLINE_SECONDS, ISSUER_MAX_WITHDRAW_ITEMS, DEFAULT_READY_TIMEOUT_MS, type ChainConfig, type CostBasis, type DepositRequest, type EpochBalance, type KeysetVerification, type OpenOptions, type Readiness, type ReadyOptions, type ReadyStatus, type RecordRefundOptions, type RecoverConfig, type ReserveTotals, type Runway, type UnsignedTx, type WalletConfig, type WrapOptions, } from "./wallet.js"; export { KeyRing, type HeldKeyset, type KeyRingEntry, type KeysetVerificationResult, } from "./keyring.js"; export { recoverFromSeed, COIN_GAP_LIMIT, MAX_REFRESH_DEPTH, SPENT_LOOKUP_CONCURRENCY, RESERVE_LOOKAHEAD, RESERVE_GAP_LIMIT, type IssuanceRecord, type MeltRecord, type RecoverParams, type RecoveredCoin, type RecoveredReserve, type RecoveryProgress, type RecoveryResult, type RecoverySources, type ReserveActivity, } from "./recover.js"; export { JsonRpcChain, parseRecoveryCheckpoint, publicRecoverySources, recoveryCheckpointToJson, DEFAULT_LOG_BLOCK_RANGE, DEFAULT_RPC_TIMEOUT_MS, RECOVERY_CHECKPOINT_CONFIRMATIONS, RECOVERY_CHECKPOINT_VERSION, type CheckpointReading, type CheckpointScope, type JsonRpcChainOptions, type PublicRecoverySourcesParams, type RecoveryCheckpoint, type ReserveScanCoverage, } from "./sources.js"; export { ReceiptLog, ReceiptChainError, receiptHash, receiptsFromJson, verifyChain, BRIDGE_STATES, GENESIS_PREV_HASH, RECEIPT_HASH_LEN, type BridgeRecourse, type BridgeState, type ChainTotals, type Receipt, type ReceiptBridge, type ReceiptEntry, type ReceiptStatus, type Reconciliation, type RecourseOutcome, type RecourseStage, type StoredReceipt, } from "./receipts.js"; export { wrapFetch, jcsStringify, quotedPrice, stripPrivacyFields, termsNonce, INSTANT_TIER, NONCE_LEN, PAYMENT_HEADER, PAYMENT_RESPONSE_HEADER, PX402_VERSION, type BridgeOptions, type PaymentBridge, type PaymentInfo, type PaymentKeysets, type QuotedPrice, type QuotedPriceOptions, type SpendLifecycle, type WrapFetchOptions, } from "./fetch.js"; export { bridgeTimeoutSeconds, caip2Network, checkBridgeAnswer, exactPaymentHeader, lookupBridgePayment, merchantSettlementOf, parseBridgeAnswer, parsePaymentRequired, recoverAuthorizationSigner, redeliverable, tokenDomainSeparator, transferWithAuthorizationDigest, transferWithAuthorizationStructHash, BRIDGE_DELIVERY_ATTEMPTS, BRIDGE_MAX_TIMEOUT_SECONDS, BRIDGE_MIN_TIMEOUT_SECONDS, BRIDGE_REDELIVERY_JITTER_MS, BRIDGE_REDELIVERY_PAUSE_MS, EIP712_DOMAIN_TYPE, EXACT_SCHEME, LEASE_TTL_SECONDS, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_V2_HEADER, PAYMENT_SIGNATURE_HEADER, PAYOUT_DEADLINE_SECONDS, RECORD_GRACE_SECONDS, REDELIVERY_MARGIN_SECONDS, TRANSFER_WITH_AUTHORIZATION_TYPE, VALID_BEFORE_MARGIN_SECONDS, X402_NETWORK_NAMES, type BridgeAnswer, type BridgeCheck, type BridgeLookup, type DeliveryHeader, type ExactEntry, type MerchantSettlement, type PaymentRequired, type TokenDomain, type TransferAuthorization, } from "./bridge.js"; export { recourseDueAt, recourseRound, DEFAULT_RECOURSE_TIMING, MIN_RECOURSE_RETRY_SECONDS, type BridgeRecourseReport, type RecoursePorts, type RecourseStepReport, type RecourseTiming, } from "./recourse.js"; export { encodePaymentHeader, paymentHeaderSizer, maxCoinsWithinHeaderBudget, planKeysetTags, DEFAULT_MAX_PAYMENT_HEADER_BYTES, NGINX_DEFAULT_HEADER_LINE_BYTES, NODE_DEFAULT_MAX_HEADER_BYTES, REFERENCE_RESOURCE_URL_BYTES, type PaymentPayload, type Px402Payload, type WireCoin, } from "./payload.js"; export { MeltScheduler, MELT_SPEND_SEPARATION_SECONDS, SYSTEM_MELT_TIMERS, type MeltSchedulerOptions, type MeltTimers, } from "./meltScheduler.js"; export { CoinStore, holdJitterSeconds, ANONYMITY_FLOOR, DEFAULT_HOLD_JITTER_SECONDS, ISSUANCE_WINDOW_SECONDS, MAX_COINS_PER_SPEND, SPEND_WINDOW_MARGIN_SECONDS, sumOfLargest, type AnonymityGauges, type CoinPolicy, type CoinStoreOptions, type HeaderBudget, type MerchantRef, type PrivacyMode, type SelectOptions, type Selection, type StoredCoin, type ValueSnapshot, } from "./store.js"; export { Refresher, ladderTargets, DEFAULT_MAX_MELTS_PER_RUN, type RefreshOutcome, type RefresherOptions, } from "./refresher.js"; export { depositPermission, depositPermissionMessage, signSpend, verifyDepositPermission, BadDepositPermissionError, DEPOSIT_PERMISSION_CONTEXT, type SignedSpend, type SpendPart, } from "./spend.js"; export { IssuerClient, planWithdraw, meltAuthorizationMessage, reserveAddressFrom, signWithdrawAuthorize, withdrawAuthorizeDigest, withdrawCommitmentDigest, withdrawCommitmentHash, withdrawIdOf, denomIdFor, keysetFromJson, keysetToJson, COMMITMENT_DIGEST_LEN, COMMITMENT_HASH_LEN, KAPPA, MELT_RESERVE_CONTEXT, WITHDRAW_TYPEHASH_STRING, type CoinSpent, type FetchLike, type IssuedCoin, type IssuerClientOptions, type IssuerKeys, type KeysetStatus, type IssuerLogEntry, type IssuerLogPage, type MeltParams, type MeltSession, type MeltTarget, type RetryOptions, type ServedKeyset, type ServiceAnswer, type WithdrawAuthorize, type WithdrawItem, type WithdrawParams, type WithdrawPlan, } from "./client.js"; export { SupportedCache, checkFee, feeCeiling, parseSupported, presentedAmount, quotePayment, relayerFee, roundUpTo, BPS_DENOMINATOR, DEFAULT_MAX_FEE_BPS, DEFAULT_SUPPORTED_TTL_SECONDS, FEE_ROUNDING_RULE, type FacilitatorSupport, type PresentedAmount, type Quote, type SupportedCacheOptions, type SupportedLookup, type SupportedRelayer, type SupportedVersion, } from "./supported.js"; export { PX402Error, PX402BridgeError, PX402ConflictError, PX402EpochRetiredError, PX402FeeError, PX402GoneError, PX402HeaderBudgetError, PX402NoCoinsError, PX402NotFoundError, PX402ProtocolError, PX402RpcUnsupportedError, PX402RequestError, PX402SeedUsedError, PX402ServerError, PX402TierError, PX402TransportError, px402ErrorFrom, isPX402ErrorCode, CANONICAL_STATUS, EPOCH_RETIRED, PX402_ERROR_CODES, type BridgeRefusal, type FeeRefusal, type PX402ErrorCode, } from "./errors.js"; export { verifyKeysetCommitment, PX402KeysetCommitmentError, DEFAULT_KEYSET_COMMITMENT_TIMEOUT_MS, type KeysetCommitmentCheck, type KeysetCommitmentFailure, type KeysetCommitmentReader, } from "./commitment.js"; export { canonicalBytes, denomById, denomId, keysetId, smallestDenomination, LAUNCH_LADDER, type Denomination, type Keyset, } from "./denom.js"; export { abiEncoded, acceptedHash, contractTermsFromWire, contractTermsHash, contractTermsToWire, contractTermsTypehash, keccak256, payoutNonce, resourceUrlHash, CONTRACT_TERMS_TYPEHASH_STRING, PAYOUT_NONCE_TAG, TERMS_SALT_LEN, type ContractTerms, type ContractTermsWire, } from "./terms.js"; export { commitHash, encodeBlindedItems, linkRecover, linkSign, linkSigMessage, linkVerify, refreshDerive, refreshSeed, resolveTarget, uncheckedTarget, checkCanonicalX25519, BadLinkSignatureError, LINK_SIG_CONTEXT, type BlindedTarget, type Derived, type RevealedSeed, } from "./refresh.js"; export { coinPublic, deriveCoinSecret, deriveReserveKey, deriveWithdrawBlindIkm, ecdh, toX25519Public, toX25519Secret, validateCoinPublic, KEY_LEN, RESERVE_ADDR_LEN, SEED_LEN, } from "./keys.js"; export { blindSeeded, encodeMessage, finalize, fromWire, modulusBits, modulusLen, toWire, unblind, verify, verifyBytes, BadSignatureError, MAX_MODULUS_BITS, MIN_MODULUS_BITS, RSA_PUBLIC_EXPONENT, SALT_LEN, type DenomPublic, } from "./blind.js"; export { selectSeeded, BlindingExhaustedError, } from "./selectSeeded.js"; export { hkdf, hkdf32, INFO } from "./kdf.js"; export { be32, be64, concat, i2osp, os2ip, MAX_HKDF_OUT } from "./encoding.js";