import { BigNumber } from 'ethers'; import { SponsoredCall } from '../domain/sponsored-calls'; import { KycParams } from '../facade/types'; import { Flow } from './flow'; import { WaitableTransaction } from './observable'; /** * The withdrawal pipeline, headless — the small sibling of `DepositFlow`. * * Much less happens here, and that is the point of it being separate: no loan * agreement, no approval (the lender is handing tranche shares back, not * granting a spend), no on-chain KYC payload. What survives is the shape both * applications need — an observable phase, one `'max'`-aware submission, and * the same `cancelled` / `failed` split, so a lender who pressed Reject is * never told something broke. * * The run lifecycle — the re-entrancy guard, `state`, `isRunning`, * `subscribe`, `reset` — is `Flow`'s, shared with the deposit pipeline. It was * a second copy here until 2.7.0, which is two places for one guard to be * wrong. * * Same house rules as the deposit flow: no React, no copy, no I/O of its own. * `state` carries codes; the consumer owns every word a lender reads. * * ```ts * const flow = new WithdrawFlow(ports); * flow.subscribe(render); * await flow.start({ poolId, trancheId, amount: 'max', userAddress }); * ``` * * ## The sponsored path (2.10.0) * * Supply `submitCall` and the run never touches `withdraw` / `withdrawMax`: * it encodes the ONE `requestWithdrawal` call itself (`encodeWithdrawal`, * which `kasu.flows.withdraw()` defaults to `kasu.calls.requestWithdrawal`) * and hands it to the port, whose `wait()` settles it. `state.sponsored` says * which path this flow runs, from its first state. * * A submitted call's outcome is read with the batch path's taxonomy, and at * its word: `BatchRevertedError` → `reverted`; `BatchSubmissionError` → its * own outcome (`failed`, `pending`, `already-submitted`); a WALLET rejection * (`isUserRejected`) thrown by `submitCall` itself → `cancelled`, exactly as a * raw `depositBatch` throw is read — the lender declined to sign, nothing was * posted; ANY other throw from `submitCall`, and every throw from `wait()` * that is not one of the typed errors, → `pending`. The SDK cannot know * whether an unrecognised error left before or after the call was accepted, * and calling that `failed` invites a second withdrawal request. * `submitSponsoredCall` is the port body that already speaks this; note that * a rejection raised INSIDE its `post` is wrapped as `pending` (the 2.9.0 * rule for `post`), so sign in `submitCall` before calling it when the app * wants `cancelled`. */ export type WithdrawPhase = 'idle' | 'checking-kyc' | 'request-sign' | 'request-confirm' | 'success' | 'error'; /** * `kyc` only exists when the consumer supplies `getKycSignature`. kasu-mobile * does, to fail early and legibly when a lender's KYC has lapsed rather than * let the on-chain call revert; kasu-ui does not. */ export type WithdrawStep = 'kyc' | 'request'; export type WithdrawFailure = { step: WithdrawStep; reason: 'cancelled'; } | { step: WithdrawStep; reason: 'failed'; error: unknown; } | { /** * Sponsored path only: the call is KNOWN to revert (or reverted) — * nothing was requested. `revertError` is the contract's error name * (`'CannotProcessRequestIfClearingIsPending'`, * `'InsufficientSharesBalance'`, …) or `''`. */ step: 'request'; reason: 'reverted'; revertError: string; error: unknown; } | { /** * Sponsored path only — NOT failures. `pending`: the call was, or * may have been, accepted and nothing proves whether it ran; never * render it as a failure, which invites a second request. * `already-submitted`: the port refused it because an earlier one * was proven. */ step: 'request'; reason: 'pending' | 'already-submitted'; error: unknown; }; export interface WithdrawPorts { /** * Build the Nexera KYC params for the pre-check. Defaults to * `kasu.deposits.buildKycParams`, exactly as the deposit flow's does. */ buildKycParams?(userAddress: `0x${string}`): KycParams | Promise; /** * Exchange those params for a signature at the consumer's own backend, and * so verify the lender's KYC BEFORE the wallet is opened — a lapsed one * surfaces as `{ step: 'kyc' }` instead of an opaque revert. The * withdrawal call itself does not carry the signature. * * Supplying this port is what turns the pre-check on; there is no default, * because the SDK does not know the application's backend. This is the * same pair the deposit flow uses, rather than the opaque `ensureKyc` of * earlier drafts, so one KYC pre-check exists across both money paths. */ getKycSignature?(params: KycParams): Promise; /** `requestWithdrawalInAsset`. Defaults to `kasu.deposits.withdraw`. */ withdraw(params: { poolId: string; trancheId: string; amount: BigNumber; }): Promise; /** `requestWithdrawalMax`. Defaults to `kasu.deposits.withdrawMax`. */ withdrawMax(poolId: string, trancheId: string, userAddress: string): Promise; /** * Submit ONE encoded call through a sponsored submitter (a gas-sponsoring * relay) and return a handle whose `wait()` settles it. Supplying it is * what turns the sponsored path on; it has no default, because how a call * is relayed is the application's business. Post `call.kind` and * `[call.call]` exactly as given — `submitSponsoredCall` does this, with * the polling and the receipt proof. * * Throw `BatchRevertedError` for a known revert and * `BatchSubmissionError(code, 'failed')` ONLY when nothing was sent. A * wallet rejection thrown here (the lender declined to sign the call, * `isUserRejected`) is `cancelled`; any other throw — here or from * `wait()` — is read as `pending`. */ submitCall?(call: SponsoredCall): Promise; /** * Encode the withdrawal for `submitCall`. Defaults (in * `kasu.flows.withdraw()`) to `kasu.calls.requestWithdrawal`, which * converts the amount to shares exactly as `withdraw` / `withdrawMax` * do. Only read when `submitCall` is supplied. */ encodeWithdrawal?(params: { poolId: string; trancheId: string; amount: BigNumber | 'max'; userAddress: string; }): Promise; } export interface WithdrawFlowInput { poolId: string; trancheId: string; /** * The amount in BASE units, or the literal `'max'`. * * `'max'` is not "the balance as I last read it": it routes to the * all-shares request, whose share count is the lender's tranche * `balanceOf`, read by the SDK at submission rather than converted from * an asset figure. Deciding max-ness from a number the consumer read a * moment ago is how dust gets stranded in a tranche, so the decision is a * code, made by the consumer, and carried here intact. */ amount: BigNumber | 'max'; userAddress: `0x${string}`; } export interface WithdrawState { phase: WithdrawPhase; step: WithdrawStep | null; /** True when this run routed through the all-shares call. */ isMax: boolean; /** * True when this flow submits through `submitCall` — fixed when the flow * is built, so it is right from the first state, `idle` included. */ sponsored: boolean; failure: WithdrawFailure | null; } /** What a KYC pre-check with no `buildKycParams` to call fails with. */ export declare const NO_KYC_PARAMS_MESSAGE = "WithdrawFlow: getKycSignature was supplied without buildKycParams; build the flow with kasu.flows.withdraw() or pass both"; /** What a sponsored run with no `encodeWithdrawal` to call fails with. */ export declare const NO_WITHDRAWAL_ENCODER_MESSAGE = "WithdrawFlow: submitCall was supplied without encodeWithdrawal; build the flow with kasu.flows.withdraw() or pass both"; /** What a sponsored run fails with when the encoder returned another kind of call. */ export declare const NOT_A_WITHDRAWAL_CALL_MESSAGE = "WithdrawFlow: encodeWithdrawal returned a call that is not a withdrawal"; export declare class WithdrawFlow extends Flow { private readonly _ports; constructor(_ports: WithdrawPorts); protected _run(input: WithdrawFlowInput, token: number): Promise; /** * 2'. The sponsored submission: encode, re-check the run, submit, settle. * * The encode reads the chain (the shares), so a run abandoned during it * must stop BEFORE `submitCall` — nothing has been sent yet, and an * abandoned run must never send. A throw while encoding is `failed`: * nothing left. After `submitCall` is called, only the taxonomy decides. */ private _runSponsored; }