> For the complete documentation index, see [llms.txt](https://docs.peach.ag/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.peach.ag/documentation/arc/launchpad/launchpad-classic/core-features/uniswap-v4-hooks/fee-settlement-and-state.md).

# Fee settlement and state

Hook accounting separates trading accrual, conversion, Escrow credits and withdrawals. A successful sweep does not prove every pending balance was converted or that every recipient can claim immediately.

```mermaid
flowchart LR
  Swap[Swap fees in either currency] --> Pending[Hook pending ledgers]
  Pending --> Begin[Operator begins epoch]
  Begin --> Convert[Bounded launch-token to quote conversion]
  Convert --> Regular[Protocol and creator allocation]
  Convert --> Partner[Paginated Partner allocation]
  Convert --> Buyback[Buyback budget]
  Regular --> Escrow[FeeEscrow claimable balances]
  Partner --> Escrow
  Escrow --> Claim[Recipient claims one asset]
  Buyback --> Vault[BuybackVault / burn and vesting]
  Convert --> Residual[Unconsumed pending / next-epoch Partner carry]
```

### Read pending and claimable separately

Read both pool currencies at one block. Use integers with each currency's own decimals; never add raw launch-token units to raw quote-token units.

| Contract / view             | Keys                       | Meaning                                                     |
| --------------------------- | -------------------------- | ----------------------------------------------------------- |
| Hook `pendingProtocol`      | poolId, currency           | Unsettled protocol allocation                               |
| Hook `pendingCreator`       | poolId, currency           | Unsettled creator allocation, including Creator Tax         |
| Hook `pendingCreatorTax`    | poolId, currency           | Informational subset of pendingCreator; do not add it again |
| Hook `pendingBuyback`       | poolId, currency           | Budget awaiting buyback processing                          |
| Hook `pendingPartnerLaunch` | poolId, epochId, partnerId | Unsettled launch-token amount for that Partner              |
| Hook `pendingPartnerQuote`  | same                       | Unsettled direct quote amount for that Partner              |
| Escrow `balanceOfToken`     | recipient, asset           | ERC-20 balance that recipient can claim                     |
| Escrow `balanceOf`          | recipient                  | Native balance; distinct from ERC-20 USDC                   |
| Escrow `partnerBalance`     | partnerId, asset           | Partner ledger, claimed by its current enabled recipient    |

Escrow is `0x305bf6885Ba7D1a9Ac9Fbc4F7e7b687F559761d4`. Recipient balances aggregate credits across launches and authorized credit paths; they are not per-pool revenue reports. Partner balances aggregate by ID and asset. Index credit/claim events when attribution by launch is required.

Reuse the configured Launchpad `client` and `publicClient` from Quickstart. Set `recipient` to the fee recipient and `asset` to the ERC-20 asset being queried.

```ts
const blockNumber = await publicClient.getBlockNumber();
const claimable = await client.getClaimableBalance({ recipient, asset }, { blockNumber });
console.log(claimable.amount); // Raw units of this asset.
```

To claim, connect the recipient wallet, simulate `claimToken(asset)` (or `claimPartner(partnerId, asset)` for the registered Partner recipient), submit that simulated request and require a successful receipt. Reread the balance after confirmation. Zero balance, wrong recipient and disabled Partner are actionable failures, not reasons to run a claim loop. Existing SDK instructions remain in [Fees and claims](https://docs.peach.ag/documentation/arc/launchpad/core-features/fees-and-claims).

### Operator: Begin → paginated Settle → Finalize

These are MemeHook contract calls. They are not methods added to the Aggregator SDK or Pons interfaces. Every write needs the correct caller, simulation and receipt handling.

| Call / view                        | Arguments and result                                                                                    | Who / conditions                                                                                 |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| `beginPoolFeeSweep`                | `(address token, uint256 minConversionQuoteOut, uint256 minBuybackTokensOut) returns (uint256 epochId)` | Configured factory feeSweepOperator; active pool, pending work, no other settling epoch          |
| `settlePoolFeeSweepPartners`       | `(bytes32 poolId, uint256 epochId, bytes32[] partnerIds)`                                               | Permissionless; nonempty page of unique, active, unsettled IDs in this epoch                     |
| `finalizePoolFeeSweep`             | `(bytes32 poolId, uint256 epochId)`                                                                     | Permissionless after all snapshotted Partner obligations and accounting remainders are processed |
| `currentEpoch`                     | `(poolId) → uint256`                                                                                    | Accrual epoch for new swaps                                                                      |
| `settlingEpoch`                    | `(poolId) → uint256`                                                                                    | Zero means none; nonzero value is settling epoch ID **plus one**                                 |
| `partnerActive` / `partnerSettled` | `(poolId, epochId, partnerId) → bool`                                                                   | Check before including an ID in a page                                                           |
| `partnerEpoch`                     | `(poolId, epochId) → counters and totals`                                                               | Snapshot, conversion, remaining amounts and progress                                             |
| `partnerLaunchInputSettled`        | `(poolId, epochId) → uint256`                                                                           | Original Partner launch input already processed, including carried remainder                     |

1. Read the pool, current epoch, pending currencies, current pool price and configured operator. Calculate conversion and buyback minimums in output-token raw units. Positive minima are required when the corresponding conversion/buyback input exists. A minimum of zero is not a supported way to disable protection.
2. Simulate and send Begin from the operator. Read `PoolFeeSweepBegun` from the confirmed Hook receipt to obtain the epoch and snapshot totals. Begin advances `currentEpoch` before conversion, so new trades accrue into the next epoch. Only one epoch may settle per pool at a time.
3. Build the Partner ID set from `PartnerFeeAccrued` plus IDs carried from earlier epochs. Validate each candidate with `partnerActive` and `partnerSettled`. Page by transaction gas, simulate each page and wait for its receipt. A duplicate/already-settled ID reverts the page; do not blindly resubmit a successful page after a client timeout.
4. Read the epoch totals after all pages. Finalize requires settled count = active count, processed launch input = snapshotted Partner launch input, and zero remaining consumed input, converted quote and direct quote. Simulate and send Finalize. Even a zero-Partner epoch requires finalization.
5. Reconcile Escrow credits, new pending balances and the next epoch. `settlingEpoch = 0` means this settlement closed; it does not mean the pool has no pending fees.

`partnerEpoch` returns, in ABI order: `partnerLaunchInputTotal`, `partnerLaunchInputConsumed`, `partnerLaunchInputConsumedRemaining`, `partnerConvertedQuoteTotal`, `partnerConvertedQuoteRemaining`, `partnerDirectQuoteTotal`, `partnerDirectQuoteRemaining`, `activePartnerCount`, `settledPartnerCount`, `totalLaunchInput`, `totalQuoteOutput` (all uint256), then `settling` (bool). The last two totals record actual conversion consumption/output, not a promise that all requested input was converted.

### Partial conversion and integer allocation

The internal swap is constrained by a price-impact boundary calculated from the current pool spot price. It is not an independent oracle. Reaching that boundary can consume only part of the input, or none. Non-Partner unconsumed input remains in the original pending ledgers. A minimum output is checked when conversion consumes input; zero consumption can leave funds pending without failing the sweep. This is why success cannot be interpreted as full conversion.

Consumed input is split proportionally among Partner, protocol, creator and buyback buckets using floor division. Input rounding remainder is assigned with available capacity in the order buyback → creator → protocol → Partner. Converted quote is split from actual consumed allocations; remaining quote rounding goes to the first nonempty bucket in that same priority order.

Partner pagination uses cumulative floor differences to allocate consumed launch input. Each Partner's unconsumed portion is carried into the new current epoch. Converted quote uses floor division, and the last settled Partner receives any final quote rounding remainder. Settlement order can therefore change a rounding unit; use confirmed ledger values rather than independently rounding each Partner as though settlement were one unordered division.

Example without rounding: a Partner has 100 launch units pending; its allocated consumed portion is 40 and its allocated converted quote is 8. Settlement credits 8 quote units (plus any direct quote already accrued) and carries 60 launch units into the next epoch. The 60 are not claimable. The carry operation does **not** emit a new `PartnerFeeAccrued` event, so an indexer that discovers IDs only from new-epoch events can permanently miss this Partner.

### Buyback and recipient credits

Begin can already credit non-Partner quote balances to Escrow and process buyback. Partner credits arrive during Settle pages; Finalize closes accounting rather than crediting every recipient at once. Quote allocated to buyback is distinct from creator claimable quote. The internal buyback can also partially consume its quote budget. Any unspent quote from that buyback is credited to the creator in Escrow; it is not retained as pendingBuyback quote. Launch-token fees left unconverted in the earlier conversion step can still remain pending. Inspect actual consumption, Escrow credits and each currency separately. Purchased tokens follow BuybackVault's burn/vesting handling. See [Buyback and vesting](https://docs.peach.ag/documentation/arc/launchpad/core-features/buyback-and-vesting).

If normal conversion cannot progress, authorized factory rescue paths may credit the original asset instead of quote. Reconcile `PoolFeesRescued` and `PartnerFeesRescued`; never assume all Escrow assets are the launch quote currency. These are authorized recovery controls, not permissionless replacements for Begin.

### Troubleshooting and indexing

| Symptom                                      | Check                                                             | Action                                                                  |
| -------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------- |
| Begin reports NotFeeSweepOperator            | Factory's configured operator and tx sender                       | Use the authorized operator                                             |
| Begin fails InvalidConfiguration             | Active pool, existing settling epoch, nonzero pending work        | Finish current settlement or refresh state                              |
| MinimumOutputRequired / SlippageExceeded     | Relevant input and fresh simulated output                         | Set nonzero, user-approved minima and retry from current state          |
| Page fails AlreadySet / PartnerNotFound      | Active and settled mappings; duplicates within the page           | Rebuild only the remaining valid ID set                                 |
| Finalize fails despite no new accrual events | Active count, carried IDs and remaining totals                    | Include carried Partners and finish every page                          |
| Sweep succeeded but claimable unchanged      | Partial consumption, asset, recipient and settlement phase        | Read pending and Escrow separately; continue settlement when applicable |
| Claim fails with positive displayed revenue  | Display may be pending, wrong asset/recipient or disabled Partner | Read the exact claim ledger and registry state                          |

Index the actual Hook/Escrow addresses and confirmed block hashes. In `PoolFeeAllocated`, the `creatorImmediate` field excludes `creatorTax`; their sum is the increase to pendingCreator. Use this event for accrual breakdown, `PoolFeeCurrencyConverted` for actual conversion, Begin/Settle/Finalize events for progress, Escrow credit/claim events for withdrawable balances, and rescue events for reconciliation. Handle reorgs and retained Partner carry sets as described in [Events and indexing](https://docs.peach.ag/documentation/arc/launchpad/core-features/events-and-indexing).

### Direct contract calls

MemeHook.beginPoolFeeSweep(address token, uint256 minConversionQuoteOut, uint256 minBuybackTokensOut) → uint256 epochId requires Factory.feeSweepOperator(). Both minimums are raw output units and must protect any conversion or buyback performed.

Once a Hook epoch begins, anyone can call `settlePoolFeeSweepPartners(bytes32 poolId, uint256 epochId, bytes32[] partnerIds)` in gas-bounded batches, then `finalizePoolFeeSweep(bytes32 poolId, uint256 epochId)` after all snapshotted Partners are settled. Do not skip carried Partner liabilities. See [Fee settlement and state](https://docs.peach.ag/documentation/arc/launchpad/core-features/uniswap-v4-hooks/fee-settlement-and-state).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.peach.ag/documentation/arc/launchpad/launchpad-classic/core-features/uniswap-v4-hooks/fee-settlement-and-state.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
