> For the complete documentation index, see [llms.txt](https://docs.kpk.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.kpk.io/funds/infrastructure/architecture/onchain-accounting/attested-balance-adapters/merkl.md).

# Merkl Rewards

Reports an account's unclaimed Merkl rewards, held by the Distributor, valued from a proof-verified cache, per reward token and campaign share.

Reports an account's **unclaimed Merkl rewards**, per reward token.

Campaign funders transfer the reward tokens to Merkl's **Distributor**, which custodies them until each account claims. The **split** is not onchain: Merkl's offchain engine derives each account's cumulative entitlement per token, publishes the reward file, and pushes only a **merkle root over it** to the Distributor. The contract holds the tokens, the current root, and `claimed` (how much each account has withdrawn), but nothing that yields an entitlement on its own.

This is the [attested](https://docs.kpk.io/funds/infrastructure/architecture/onchain-accounting/attested-balance-adapters.md) shape: the value is **verifiable but not derivable**. The family page covers the model, trust boundaries, introspection reads and error taxonomy; this page covers what is specific to Merkl.

* **Type:** Attested adapter, the family's first member
* **protocolBrand / protocolId / protocolSubId:** all three are `ProtocolIds.MERKL`; Merkl has no product split
* **positionId:** `abi.encode(DISTRIBUTOR)`, **identical for every leg of every token**
* **positionInstanceId:** the campaign coordinate, where a breakdown was submitted
* **positionKind:** `Rewards` · **protocolName():** `"Merkl"` · **labels:** `["Claimable Rewards"]`
* **Distributor:** `0x3Ef3D8bA38EBe18DB133cEc108f4D14CE00Dd9Ae`, Angle Labs, the same address on every supported chain
* **Admin:** the Security Council Safe holds `DEFAULT_ADMIN_ROLE` on every chain the adapter is deployed on, and grants and revokes the keeper's `SUBMITTER_ROLE`
* **Source:** `MerklRewardsAttestedBalanceAdapter.sol`

## What it reports

A token's unclaimed total is its **proof-verified cumulative minus the amount already claimed onchain**, with `claimed` read live from the Distributor on every read. One leg per cached reward token, or one per campaign share where a breakdown was submitted.

A claim moves value into the account's wallet, where the [default adapter](https://docs.kpk.io/funds/infrastructure/architecture/onchain-accounting/balance-adapters.md) reports it as an ERC-20 balance. Because Merkl's leaves carry a *cumulative* figure, subtracting `claimed` removes exactly the settled portion.

| Leg               | PositionKind | isDebt  | Amount                                           |
| ----------------- | ------------ | ------- | ------------------------------------------------ |
| Claimable Rewards | `Rewards`    | `false` | Proven cumulative − claimed, in the reward token |

## Reading the legs: sum them, never de-duplicate

{% hint style="danger" %}
**Every Merkl leg of one token shares an identical reconciliation key.**

`positionId` is the same for every leg of every token, and the campaign coordinate in `positionInstanceId` is **excluded** from the stable key. Legs of *different* tokens still separate, because the key includes `balanceAsset.asset`; legs of the *same* token do not.

A consumer that treats a repeated key as duplicate data and keeps one row **under-reports that token by up to the per-campaign cap**. Sum the legs.

Campaign attribution is **display-grade, not audit-grade**: the proof binds only the per-token total, and the contract checks only that the shares sum to it. **The per-token total, the sum of a token's legs, is the proof-backed figure.**
{% endhint %}

`campaignsOf(user, token)` returns the cached `CampaignShare[]` directly, for display and debugging. The shares sum to the proof-verified per-token cumulative; it is empty where the token was submitted untagged.

## The proof shape

Merkl decodes the family's opaque `bytes` into `Allocation[]`, the same shape for the write path and the cache-free read:

```solidity
struct CampaignShare {
    bytes32 campaignId;
    bytes32 subCampaignId;
    uint256 cumulativeAmount;
}

struct Allocation {
    address        token;             // reward token
    uint256        cumulativeAmount;  // proof-bound total for (account, token)
    bytes32[]      proof;             // merkle proof against the Distributor's live root
    CampaignShare[] campaigns;        // optional breakdown; must SUM to cumulativeAmount
}
```

The leaf proved is `keccak256(abi.encode(account, token, cumulativeAmount))`. Typed wrappers `submitProofs(user, allocations)` and `submitProofsBatch(users, allocations)` carry the same atomicity as the family's `submit` and `submitBatch`.

## Reading a position without the cache

`previewPositions(account, abi.encode(allocations))` values an account from caller-supplied proof data, the same payload the write path takes. See [reading without the cache](https://docs.kpk.io/funds/infrastructure/architecture/onchain-accounting/attested-balance-adapters.md#reading-without-the-cache). As on the write path, the **campaign split is not proof-bound**: a preview built from fabricated shares that sum correctly returns those shares.

## Staleness and the dispute window

Each new root is published subject to a short dispute window, in which watchers can post collateral to challenge the reward file; a challenged tree can be resolved back to its predecessor or revoked. During the window, or while a disputer is set, `getMerkleRoot()` returns the **previous** root. The root is therefore **not monotonic**, which is why the family's staleness check is a straight equality test.

* **`isAttestationLive` can flap**: `false` during a rotation, `true` again if the root rolls back. A monitor that pages on a single `false` will page on dispute windows.
* **A clear performed while the root is rolled back is not undone when it returns.** An element cleared inside the window stays gone until the keeper resubmits; the under-count self-heals on the next feed cycle.

{% hint style="info" %}
**`AmountRegression` should never fire.** For a well-formed tree it is unreachable, since the amount is committed inside the leaf. It is a tripwire: alert on any occurrence rather than retrying.
{% endhint %}

## Bounds

Two caps bound the per-account leg count, and a read budget must size against their **product**, not the token cap alone: the campaign split is not proof-bound, so whoever submits can influence it. Read `MAX_TOKENS_PER_USER` and `MAX_CAMPAIGNS_PER_TOKEN` off the adapter rather than from a figure here. `maxAssetsPerAccount()` returns the token cap.

Two consequences of the token cap, resolved by garbage collection rather than configuration:

* Under upsert semantics the cache **accumulates every token ever proven**. Stale entries go only via the permissionless, stale-gated clears, so an account drifts toward the cap unless the keeper also collects garbage.
* **At the cap, a submit carrying a new token reverts**, and because a submit is atomic, that also blocks the refresh of the account's *other* tokens.

Per-token isolation does not make an under-budgeted read survivable: with a full cache and an expensive token valued last, the read can revert outright.

## Failure behaviour

Writes fail closed with named errors: `InvalidProof` (proof does not verify against the live root), `AmountRegression` (a cumulative below the cached value for the *same* root), `CampaignSumMismatch` (shares do not sum to the proven total), `TooManyCampaigns` (breakdown over the cap). A rejected submit leaves the previous cached value intact.

Reads never revert on a bad cache entry: a stale epoch reads `0`, and a token whose asset is unregistered on the NAV contributes nothing.

{% hint style="warning" %}
**One silent failure mode worth monitoring.** The live netting reads `claimed` off the Distributor unguarded and ABI-decodes the result. If the Distributor, an upgradeable proxy under Angle governance, ever returns something undecodable, the read reverts and, on the NAV path, this adapter's whole leg set drops out for the account: an under-report with no error surfaced. The [family diagnostic](https://docs.kpk.io/funds/infrastructure/architecture/onchain-accounting/attested-balance-adapters.md#error-taxonomy) applies.
{% endhint %}


---

# 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.kpk.io/funds/infrastructure/architecture/onchain-accounting/attested-balance-adapters/merkl.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.
