/** * Keeping a drop-in wallet funded: deposits from the signer's own address, * in whole floats, and withdrawals by the wallet's own refill rule. * * The explicit path leaves both to the agent: send `wallet.depositTx`'s two * transactions from a depositor, then `prewarm` well before spending. The * drop-in surface (`dropin.ts`) is given a key that can sign, and does both * itself, through {@link AutoFunder}. * * # Two levels, two rules * * - **The coin buffer** is refilled by the wallet's own machinery, * `wallet.prewarm`, toward `wallet.refillTarget()`: two hours of observed * spend or the float, whichever is larger, moved ±20 % at random * (`REFILL_JITTER`), and shaped to the prices the wallet has been paying. * Before a payment the buffer cannot cover even once its held coins * unlock, the withdrawal is raised past it, to a whole number of floats. * - **The reserve** is topped up from the signer's address only in **whole * floats**, never an amount sized by the payment in hand: what the payment * needs, in the fewest floats that cover it, and otherwise the refill * rounded to the *nearest* float, so the ±20 % jitter never adds one. A * payment of $0.37 and one of $4.20 on an empty wallet with a $5 float * both deposit one float; an address holding $6 is enough. The deposit is * limited by what the address holds and by `maxAutoDeposit`, and the * withdrawal by what the reserve then holds (see {@link AutoFunder}). * * # Consistent against a load-balanced RPC * * Every read that decides a deposit is made at a block at or after our own * last transaction (`evm.ts`, the floor), the nonce is counted here as well * as read, a `deposit` right after an `approve` is not estimated (a node * behind the approve would revert the estimate) but sent with * {@link DEPOSIT_GAS_LIMIT}, and a top-up that fails on something transient * -- a node that has not caught up, an answer lost -- is tried again a few * times before it fails, each time from what the chain says now. * * # Ahead of need, where it can be * * The drop-in tops up when it starts and again between calls, a random * moment after a payment that left the buffer below its target -- not at the * head of the next payment. Only a payment the buffer cannot cover at all * funds itself in its own request path, and it then waits out the fresh * coins' hold (60 to 120 seconds). Start the wallet early, so payments spend * coins withdrawn well before them (a spend soon after its own withdrawal is * attributable by timing, README "Timing"). * * # Bounded * * `maxAutoDeposit` caps what one funder deposits while the process runs; a * deposit past it is refused with {@link PX402AutoFundLimitError} before * anything is sent. A signer without the USDC, or without the ETH for gas, is * refused with {@link PX402InsufficientFundsError}, naming which and how much, * before anything is sent. * * Without a signer (`autoFund: false`, or an account that cannot sign * transactions) the funder never deposits; it still withdraws from what the * reserve holds, and the reserve is funded by hand (`wallet.depositTx`). */ import { type FetchLike } from "./client.js"; import { PX402Error } from "./errors.js"; import { type EvmRpc, type TransactionSigner } from "./evm.js"; import { type AuthorizationSigner } from "./gasless.js"; import { type Wallet } from "./wallet.js"; /** * The float when none is given: $5.00, the buffer the examples keep * (`examples/wallet.ts`, twenty $0.25 calls). It is both the coin buffer's * refill floor (`minRunwayBaseUnits`) and the unit every deposit is a whole * number of. */ export declare const DEFAULT_FLOAT_BASE_UNITS = 5000000n; /** `maxAutoDeposit` when none is given: ten floats ($50 at the default float). */ export declare const DEFAULT_MAX_AUTO_DEPOSIT_FLOATS = 10n; /** * What a `deposit` is expected to cost at most. Measured: a first deposit * into a fresh reserve, pulling an exact allowance, used 64,436 gas on anvil * (the reserve contract and the EIP-3009 mock USDC; the end-to-end test * checks it stays under this), and the heaviest deposit in the Foundry tests * spends 81,928 of execution before the intrinsic 21,000. Circle's USDC on * mainnet costs more per transfer than the mock; this leaves it room. */ export declare const DEPOSIT_GAS_BUDGET = 150000n; /** * The gas limit a `deposit` sent right after its `approve` carries: the * budget and a quarter. Not estimated, because an estimate can reach a node * that has not seen the approve and revert; unused gas is not charged. */ export declare const DEPOSIT_GAS_LIMIT: bigint; /** * How many times a top-up that failed on something transient (a node behind * the others, an answer lost: `PX402TransportError`) is tried again, from * scratch, before the failure is the caller's. */ export declare const TOPUP_ATTEMPTS = 3; /** * How many times a withdrawal the issuer refuses `INSUFFICIENT_VALUE` is * asked again while our own read of the reserve says it holds enough: the * issuer's node has not seen our deposit yet. */ export declare const ISSUER_LAG_RETRIES = 6; /** * How many times a balance that looks too small to deposit from is read * again, past a fresher head, before the address is called short: funds sent * to it just before the agent started are in a block this client never saw, * and the node that answered may not have reached it. */ export declare const BALANCE_RECHECKS = 3; /** How long a deposit's transactions may take to be mined. */ export declare const DEFAULT_RECEIPT_TIMEOUT_MS = 180000; /** How often a pending transaction's receipt is asked for. */ export declare const RECEIPT_POLL_MS = 1000; /** * How long a gasless deposit's authorization stays valid, in seconds of * chain time: ten minutes. Long enough for the relayer to submit it and for * a lost answer to be asked about again; short enough that one the relayer * never sends provably expires soon, and the next top-up may sign another. */ export declare const GASLESS_VALIDITY_SECONDS = 600n; /** `maxSponsorFee` when none is given: $0.10 per gasless deposit. */ export declare const DEFAULT_MAX_SPONSOR_FEE = 100000n; /** * How many times one gasless authorization is posted again when its * transaction reverted with the authorization still unused (the relayer * then submits it afresh). */ export declare const GASLESS_SUBMIT_ROUNDS = 3; /** * The signer's address cannot pay for a deposit: too little USDC, or too * little ETH for the gas. Nothing was sent. Retryable once the address holds * {@link required}. */ export declare class PX402InsufficientFundsError extends PX402Error { /** What is short. */ readonly asset: "USDC" | "ETH"; /** The address that pays: the signer's. */ readonly address: string; /** What the deposit needs, in the asset's base units (USDC: 6 decimals; ETH: wei). */ readonly required: bigint; /** What the address holds. */ readonly available: bigint; constructor(detail: { asset: "USDC" | "ETH"; address: string; required: bigint; available: bigint; deposit: bigint; /** Why a gasless deposit could not stand in, when one was tried. */ gasless?: string; }); } /** A deposit that would take the funder past its `maxAutoDeposit`. Nothing was sent. */ export declare class PX402AutoFundLimitError extends PX402Error { /** `maxAutoDeposit`, in base units. */ readonly ceiling: bigint; /** What this funder has deposited so far. */ readonly deposited: bigint; /** The deposit it refused. */ readonly wanted: bigint; constructor(detail: { ceiling: bigint; deposited: bigint; wanted: bigint; }); } /** What {@link AutoFunder} needs of a wallet: its refill rule, its buffer, and its unsigned deposit. */ export type FundableWallet = Pick; /** Where the deposits go. */ export interface FundingTarget { readonly chainId: number; /** The `PX402Reserve` address. */ readonly reserveContract: string; /** The USDC it takes. */ readonly usdc: string; /** The wallet's own reserve address, `0x`-prefixed. */ readonly reserveAddress: string; } /** * Gasless deposits (`gasless.ts`): the signer's USDC, deposited through * `PX402GaslessDepositor` by a relayer that pays the gas and keeps a fee. */ export interface GaslessFunding { /** The `PX402GaslessDepositor` the authorization is signed for: the wallet's own setting, never a server's. */ readonly depositor: string; /** The facilitator: its `/supported` names the fee, its `/deposit/sponsor` takes the authorization. */ readonly facilitator: string; /** The `fetch` the facilitator is reached through. */ readonly fetch: FetchLike; /** Signs the USDC authorization; its address is where the USDC comes from. */ readonly signer: AuthorizationSigner; /** * `"always"`: every deposit is gasless. `"auto"`: only when the address * cannot pay a direct deposit's gas (or has no transaction signer). */ readonly mode: "auto" | "always"; /** The most fee one deposit may pay, USDC base units ({@link DEFAULT_MAX_SPONSOR_FEE}). */ readonly maxFee: bigint; /** The salt's randomness. Defaults to `crypto.getRandomValues`. */ readonly randomBytes?: (n: number) => Uint8Array; } /** Construction-time wiring for {@link AutoFunder}. */ export interface AutoFunderOptions { readonly wallet: FundableWallet; readonly target: FundingTarget; /** The float, in base units: the refill floor and the deposit unit. */ readonly float: bigint; /** The most this funder deposits while the process runs, in base units. */ readonly maxAutoDeposit: bigint; /** Deposits from this address. Without one (and without {@link gasless}) the funder only withdraws. */ readonly signer?: TransactionSigner; /** Gasless deposits: with no ETH at the address, or always (see {@link GaslessFunding.mode}). */ readonly gasless?: GaslessFunding; /** The chain the deposits are sent through. Required with a signer or gasless funding. */ readonly rpc?: EvmRpc; /** How it waits between receipt polls. Defaults to a timer. */ readonly sleep?: (ms: number) => Promise; readonly receiptTimeoutMs?: number; readonly pollMs?: number; readonly onWarning?: (message: string) => void; } /** * The drop-in's funding: see the module docs. * * One top-up runs at a time: every call to {@link ensure} queues behind the * one in flight and then looks at the wallet and the chain afresh, so a * background refill and the first payment's top-up deposit once between * them. What a failed attempt leaves is only what is true on chain: a * transaction it sent and did not see mined (sent again, the same bytes, * before anything else), and the next nonce it counted. A failure before * anything was sent leaves nothing. */ export declare class AutoFunder { private readonly options; private readonly sleep; private queue; private total; private readonly made; private pending; private pendingGasless; /** USDC's EIP-712 domain, read from the token once and checked. */ private domain; /** The nonce after the last transaction a node accepted from us; `undefined` to read it afresh. */ private nextNonce; constructor(options: AutoFunderOptions); /** The float, in base units. */ get float(): bigint; /** Whether this funder deposits (directly, or gaslessly), or only withdraws. */ get deposits(): boolean; /** Whether this funder can deposit through a sponsor. */ get gasless(): boolean; /** The address deposits come from, when this funder deposits. */ private fundingAddress; /** What it has deposited while the process ran, in base units. */ get deposited(): bigint; /** Each deposit it made, in order, in base units: every one a whole number of floats. */ depositsMade(): readonly bigint[]; /** * Make the wallet able to pay `cost` (once any hold passes) and its buffer * at least near its refill target: deposit whole floats when the reserve * holds less than that needs, then withdraw. Without `cost`, only the * refill. Queued behind any top-up in flight. Something transient (a node * behind the others, a lost answer) is tried again, up to * {@link TOPUP_ATTEMPTS} times, each time from what the chain says then. * * @throws PX402InsufficientFundsError, PX402AutoFundLimitError before * anything is sent; PX402TransportError when the chain would not answer * consistently; the issuer's own errors from the withdrawal. */ ensure(cost?: bigint): Promise; /** Resolves once every top-up queued so far has ended, however it ended. */ idle(): Promise; private attempts; private topUp; /** * Deposit the floats this top-up calls for, and return what was deposited. * * `need` (the least the payment withdraws) is met in the fewest floats * that cover it. `want` (the refill) is met to the **nearest** float: the * refill target's ±20 % jitter moves it by at most a fifth of its base, so * rounding to the nearest lands where the base would, and the jitter alone * never adds a float. Both are limited by what the address holds and by * `maxAutoDeposit`: the refill is cut to fit, the payment's need is not. * Nothing without a signer or gasless funding. * * Returns what the reserve was **credited**: the whole floats for a direct * deposit, the floats less the sponsor's fee for a gasless one. A gasless * deposit is sized so that what it credits still covers the payment: one * float more when the fee would otherwise leave the payment short. */ private depositFor; /** * How this deposit is paid for. Without gasless funding: directly. With * it, `"always"` (or no transaction signer): through the sponsor. `"auto"`: * directly when the address holds the gas -- read once, not waited for -- * and through the sponsor when it does not and one is offered. */ private route; /** * A direct deposit of `amount`, priced: the approve when the allowance is * short, both gas figures, the fee, and the ETH the address holds -- * re-read past fresher heads while it looks short when `recheck`. */ private directPlan; /** `approve` (when the allowance is short) then `deposit`, each mined before the next. */ private depositDirect; /** * A balance, read again while it looks short of `enough`, each time past * a fresher head (see {@link BALANCE_RECHECKS}): what it says after that is * what the address holds. */ private recheck; /** * The next nonce: the larger of what the chain says at the floor (every * transaction of ours seen mined), what a node's pool says, and our own * count -- so a node that lags can never hand us a nonce we have used. */ private takeNonce; private send; /** The receipt of `hash` once a node shows it mined, or `undefined` when none has in time. */ private mined; /** * A transaction an earlier top-up sent and did not see mined: sent again * (the same bytes: a node that holds it says so, one that lost it takes it * back) and waited for, and counted once mined -- never sent around, which * would deposit twice. When a node says its nonce is used and no receipt * for it ever shows, it was replaced: forgotten, and the nonce read afresh. */ private settlePending; /** * The facilitator's offer for this funder's depositor, within * `maxSponsorFee`. * * @throws PX402SponsorError `unavailable` when no relayer behind it * sponsors the depositor, `fee` when the least fee is above the ceiling. */ private sponsorOffer; /** * USDC's EIP-712 domain, from the token: its `name()` and `version()` on * this chain, checked against its own `DOMAIN_SEPARATOR()` before anything * is signed under it, and kept. */ private tokenDomain; /** * Sign a `ReceiveWithAuthorization` of `amount` for the depositor, bound * to this wallet's reserve and the offer's fee, hand it to the * facilitator, and wait until it lands. Returns what the reserve was * credited: `amount` less the fee. */ private depositGasless; /** * Post `p` (again) and wait for its transaction: landed is the token * showing the authorization used, at or after the receipt's block. A * refusal before anything was sent drops it; no answer, or a transaction * not mined in time, keeps it for the next top-up. */ private landGasless; /** * Whether `receipt` carries the reserve's `Deposit(reserveAddr, credited, * depositor)`. A node that returns no logs cannot say; the token's nonce * map, which the caller read, is then the word. */ private depositSeen; private gaslessLanded; /** * A gasless authorization an earlier top-up signed and did not see land: * landed now (counted), provably expired (forgotten: nothing left the * address), or asked about again -- the same authorization, never a second. */ private settlePendingGasless; /** * Withdraw `amount` past the buffer as it is when the withdrawal is asked * for -- not as it was when the top-up began: a payment that spent coins in * between would otherwise be withdrawn again, an amount equal to its price. * `amount` 0 still lets `prewarm` buy coins that carry a price the buffer * holds in coins too small (its fragmented case). * * Asked again a few times when the issuer refuses `INSUFFICIENT_VALUE` * while our own read of the reserve -- at or after our deposit's block -- * says it holds `amount`: the issuer's node has not seen the deposit yet. * Without a signer the refusal is the caller's at once, as before. */ private withdraw; /** * Wait, briefly, until a read shows the issuer's withdrawal: the reserve's * withdraw nonce past `before`. The issuer's transaction is in a block this * client did not send, so nothing else raises the floor past it, and the * next top-up's reads of the reserve -- its balance, the nonce the next * withdrawal signs -- could come from before it. Each try asks for a fresh * head first. Best effort: when no node shows it in time, the next * top-up's own retries cover the rest. */ private seeWithdrawal; }