# Program errors

What each error code from covr's program means, when a desk hits it, and what to do.

## How codes are numbered

The program has one Anchor error enum. Anchor numbers custom errors from 6000. The enum counts up from 0, with fixed jumps (for example `CustodyInvalidAccount = 1400`), so its codes come in blocks: 6000 to 6014, 7400s, 7600s, 8000s, 8200s, 8300s, 8400s and so on. A unit test in the program pins every code.

A failed transaction shows the code in hex in its last log line, and the name and message in an Anchor log line:

```text
Program log: AnchorError thrown in <source file>:<line>. Error Code: InvalidOrder. Error Number: 6003. Error Message: Invalid quote, lifecycle state, nonce or time window.
Program 8ZpbTPnDECPTDGN5VHHKH5gfer6EUTnRHcFwfUAbkJDg failed: custom program error: 0x1773
```

Codes below 6000 come from Anchor itself, and codes from another program (System, SPL Token) are that program's own. See [Errors from Anchor and other programs](#errors-from-anchor-and-other-programs).

Codes not listed on this page are not returned by the instructions in this reference.

## Reason lines

For some errors the program also logs a line that names the exact cause. Look for it just above the AnchorError line.

| Log line | Comes with | Reasons you can see |
| --- | --- | --- |
| `COVR_TOKEN_ACCOUNTING: <reason>` | 8302, from call and put fills and exits | `Unbootstrapped` (run `bootstrap_mint_usage_v1`), `Paused` (mint policy disabled), `Terms` (policy `terms_id` or `profile_hash` differs from the market), `Limit` (a mint policy cap would be exceeded), `Identity`, `Arithmetic` |
| `COVR_TOKEN_CUSTODY: <reason>` | 7400 to 7406 | `InsufficientBacking` (source account short), `Frozen`, `Uninitialized`, `Identity` (wrong mint or owner), `RecipientDelegate`, `RecipientCloseAuthority`, `UnsupportedCapability { … }` |
| `COVR_RESTRICTED: <reason>` | 8400 to 8405 | `Terms`, `State`, `Time`, `Approval`, `Impaired`, `Escrow` |
| `COVR_MINT_PURCHASE: <reason>` | 8302 from `buy_position_v3`, `buy_put_position_v3` or a put purchase policy update | Same reasons as the accounting line, for your purchase policy |

## Order, signature and limits (6000 to 6014)

| Code | Hex | Name | Message |
| --- | --- | --- | --- |
| 6000 | `0x1770` | `BadSignature` | Ethereum authorization does not match this program and Solana authority |
| 6001 | `0x1771` | `InvalidTerms` | Invalid immutable market terms or mint decimals |
| 6002 | `0x1772` | `InvalidAmount` | Invalid token amount |
| 6003 | `0x1773` | `InvalidOrder` | Invalid quote, lifecycle state, nonce or time window |
| 6004 | `0x1774` | `Unauthorized` | Account is not authorized for this action |
| 6006 | `0x1776` | `ExposureLimit` | Maker aggregate collateral exposure exceeds configured capacity |
| 6007 | `0x1777` | `PremiumBudgetExceeded` | Maker premium spend exceeds its enabled lifetime ceiling or overflows |
| 6008 | `0x1778` | `JitoSolOrderLimit` | JitoSOL order exceeds 50 SOL of stake-pool backing |
| 6009 | `0x1779` | `InvalidJitoPool` | JitoSOL stake pool identity, accounting state or epoch is invalid |
| 6010 | `0x177a` | `MintPolicyIdentity` | Mint policy or usage identity does not match the canonical maker/mint/payment cohort |
| 6011 | `0x177b` | `MintPolicySchema` | Mint policy or usage schema or allocation length is unsupported |
| 6012 | `0x177c` | `MintPolicyGeneration` | Mint policy generation is zero, stale or exhausted |
| 6013 | `0x177d` | `MintPolicyUnauthorized` | Only the registered maker owner or configured watcher may pause this policy |
| 6014 | `0x177e` | `MintPolicySettings` | Mint policy settings are not canonical or omit terms/profile identifiers |

| Code | When you hit it | What to do |
| --- | --- | --- |
| 6000 | `register_maker_v3`: the grant was signed for another authority, program or deployment. `fill_v3`: the quote was signed in another market's domain, or for another writer, auction id, price, size or nonce. Also `early_close_v3` and `buy_position_v3`. | Sign in the domain from `registrationGrantDomain()` or `quoteDomain(decodedMarket)`. Check your signer against the golden vectors. Signatures must be low-s with `v` 27 or 28. |
| 6001 | `configure_maker` with a `min_nonce` below the current one. Vault instructions with a mint that does not have 6 decimals. | Re-read your Maker and send a `min_nonce` at or above `minNonce`. Pass the USDC mint. |
| 6002 | `deposit` or `withdraw` of 0. A fill whose premium or strike is not a whole USDC atom. `early_close_v3` or `buy_position_v3` with a 0 amount. | Send a positive amount. Price with `exactPriceAtOrBelow`. Quote sizes that are multiples of `minimumExactLot`. |
| 6003 | `fill_v3`: the market is paused, `now >= expiry`, `now >= valid_until`, `valid_until > expiry`, the nonce is below `min_nonce` or is `u64::MAX`, the size is 0 or above `max_quantity_atoms`, or the auction id is zero. `exercise_v3`: outside `[expiry, expiry + window)`, or the position is not open. `release_v3`: before `expiry + window`, or not open. Also early close, sale and transfer outside their time rules. | For fills: quote with a nonce at or above `min_nonce`, and a `valid_until` inside the market's life. For exercise: send inside the window, with margin for confirmation. Read the position's `state` first. |
| 6004 | `buy_position_v3` from a signer that is not the position's writer, or with a recipient that is not a plain wallet. Writer instructions with a recipient or refund account that holds data. | Pass the current writer as seller and your authority's wallet as recipient. |
| 6006 | `fill_v3`: `exposure.active + quantity` would exceed `exposure.limit`. | Raise the limit with `set_exposure_limit`, or wait for open positions to settle. |
| 6007 | `fill_v3` or `buy_position_v3`: the budget is enabled and `spent + amount` would exceed `limit`. `spent` never goes down. | Raise `limit` with `set_premium_budget`, or disable it. |
| 6008 | A JitoSOL fill (call or put) worth more than 50 SOL of stake-pool value: `quantity_atoms × total_lamports > 50,000,000,000 × pool_token_supply`. The cap was 2 SOL before the 4 November 2026 upgrade. | Quote smaller sizes, from a fresh read of the pool. The cap is per fill, not per desk. See [JitoSOL size cap](https://docs.covr.markets/reference/program/instructions.md#jitosol-size-cap). |
| 6009 | A JitoSOL fill with a different account in the stake-pool slot, with that account writable or signing, or before the pool has been updated for the current epoch. (A missing pool account gives 8800.) | Pass `JITO_STAKE_POOL` read-only. Near an epoch boundary, retry after the pool updates. |
| 6010 | `update_mint_policy_v1` with a collateral mint whose token program or decimals changed, or a payment mint without 6 decimals. A fill whose policy or usage does not match your Maker, authority or this mint. | Derive the policy and usage with `deriveMintPolicy(maker, mint)`. |
| 6011 | A policy or usage account of the wrong size or version. | Pass the accounts created by `initialize_mint_policy_v1`. |
| 6012 | `update_mint_policy_v1` or `pause_mint_policy_v1` with an `expected_generation` that is not current. | Re-read the policy's `generation` (`decodeMintPolicy(...).generation`, or the `u64` at byte 204) and retry. |
| 6013 | `pause_mint_policy_v1` signed by a key that is neither your authority nor the watcher. | Sign with the authority or the watcher. |
| 6014 | `initialize_mint_policy_v1` or `update_mint_policy_v1` with a zero `terms_id` or `profile_hash`, or a non-zero lifetime limit while it is disabled. | Build settings with `mintPolicySettingsFor(decodedMarket, caps)`. |

Put setup and put fills return the same codes for the put accounts. 6006 is your put exposure. 6007 is your premium budget for the market's payment token. 6010 to 6014 are your put mint policy (`MintPolicyV2`), and `init_mint_policy_v2` also refuses `enabled = true` with 6014: a put policy is born disabled. See [Cash-secured puts](#cash-secured-puts-9200s) for the codes only puts return.

## Token custody (7400s)

Every V3 token movement goes through a checked custody step. It runs before the transfer, so a failed check moves nothing.

| Code | Hex | Name | Message |
| --- | --- | --- | --- |
| 7400 | `0x1ce8` | `CustodyInvalidAccount` | Custody account identity, state or raw layout is invalid |
| 7401 | `0x1ce9` | `CustodyUnsupportedCapability` | This token capability is not implemented by the custody adapter |
| 7402 | `0x1cea` | `CustodyUnauthorized` | Custody authority is not the verified owner signer or canonical program PDA |
| 7403 | `0x1ceb` | `CustodyUnsafeRecipient` | Custody recipient has a delegate or foreign close authority |
| 7404 | `0x1cec` | `CustodyUnsafeSource` | Custody source has a delegate or foreign close authority |
| 7405 | `0x1ced` | `CustodyInvalidAmount` | Custody transfer is zero, unbacked or overflows the recipient balance |
| 7406 | `0x1cee` | `CustodyPostTransferMismatch` | Custody transfer did not produce its exact spendable balance changes |

| Code | When you hit it | What to do |
| --- | --- | --- |
| 7400 | A token account in the transfer is frozen. | Use an account that is not frozen. Wrong mint or owner shows up earlier as another code: `TokenLifecycleIdentity` (8300) for `writer_payment` and `maker_collateral` at exercise, and Anchor 2014 or 2015 for `writer_collateral` and the fill's customer accounts. |
| 7401 | A token account carries a Token-2022 extension the program does not support. | Use plain token accounts. |
| 7403 | A destination has a delegate, or a close authority other than its owner. At exercise: `writer_collateral`, `writer_payment` or `maker_collateral`. At fill: the customer's USDC account or the fee account. | Use a clean account. At exercise and release, use `exerciseV3Instructions` / `releaseV3Instructions`: they create fresh token accounts for the writer in the same transaction. |
| 7405 | **Your vault holds less than the gross premium (fill) or the strike (exercise, restricted funding).** On a put: your vault for the payment token holds less than the premium, or your put asset vault holds less than the quantity at exercise. Also: the position's collateral vault holds less than its quantity, or the customer lacks the collateral or the lock at fill. | Top up the vault with `deposit` (or the put asset vault with `deposit_put_asset_v1`). For an exercise, do it before the window closes. After the window, anyone can release the position. |
| 7402, 7404, 7406 | Internal custody checks: the transfer authority is not the owner that signed or the program's own address (7402), a program-owned source account such as your vault or an escrow has a delegate or a foreign close authority (7404), or the balances after a transfer did not change by exactly the amount (7406). | You should not see these with SDK builders and plain token accounts. Simulate, and keep the transaction logs if you do. |

## Maker and registration (7600s, 8000s, 8700s, 8800)

| Code | Hex | Name | Message | When you hit it and what to do |
| --- | --- | --- | --- | --- |
| 7600 | `0x1db0` | `MakerFenceSchema` | Maker fence allocation, discriminator, tail or current data is invalid | The account passed as your Maker is not a well-formed Maker. Pass `deriveMaker(makerEthAddress).maker`. |
| 7602 | `0x1db2` | `MakerFenceUnauthorized` | Maker fence requires the canonical account and registered owner authority | The Maker account is not the PDA of its own quote key, or not owned by the program. Pass `deriveMaker(makerEthAddress).maker`. |
| 8000 | `0x1f40` | `MakerOriginSchema` | First-registration maker origin schema is unsupported | `bootstrap_mint_usage_v1` with a wrong origin account. Pass `deriveMaker(makerEthAddress).origin`. |
| 8001 | `0x1f41` | `MakerOriginIdentity` | First-registration origin is not bound to this maker, deployment or payment cohort | Same: the origin belongs to another Maker or deployment. |
| 8002 | `0x1f42` | `MakerOriginState` | Maker birth fence or unused mint-usage bootstrap state is invalid | `bootstrap_mint_usage_v1` on a usage account that is already bootstrapped. It runs once per mint, so check `bootstrapped` (offset 204) first. Also `initialize_mint_purchase_policy_v1` before bootstrap. |
| 8700 | `0x21fc` | `MakerMigrationSchema` | Maker migration schema or provenance allocation is unsupported | An internal account check failed: the `origin` account of a fill or sale is not your MakerOriginV1. You should not see this with SDK builders. Pass `deriveMaker(makerEthAddress).origin`. |
| 8701 | `0x21fd` | `MakerMigrationIdentity` | Maker migration provenance, historical record or selected seal differs | An internal account check failed: the `origin` account belongs to another Maker or deployment. You should not see this with SDK builders. Pass `deriveMaker(makerEthAddress).origin`. |
| 8800 | `0x2260` | `MakerMigrationHoldsSchema` | Maker migration holds or terminal evidence schema is unsupported | Wrong number of remaining accounts on a fill: a JitoSOL fill **without the stake pool account**, or any extra account. A JitoSOL fill takes exactly one (`JITO_STAKE_POOL`, read-only). Other mints take none. SDK builders add it for you. |

## Markets (8200s)

| Code | Hex | Name | Message | When you hit it and what to do |
| --- | --- | --- | --- | --- |
| 8200 | `0x2008` | `MarketV3Schema` | V3 market schema is unsupported | The market account is not a 376-byte V3 market owned by the program, or its mode does not match the instruction (ordinary versus restricted). Decode it with `decodeMarketV3` and use `settlementMode`. |
| 8201 | `0x2009` | `MarketV3Identity` | V3 market identity or canonical address is invalid | The market is not at its own PDA, its payment or deployment is wrong, or **the collateral mint changed since the market was created** (for example a new mint authority). Fills on that market stay closed. Use a newer market. |
| 8202 | `0x200a` | `MarketV3Terms` | V3 market terms are invalid | `create_market_v3` with `expiry` less than 60 s or more than 90 days away, a window outside 60 to 3,600 s, a zero strike or size, a fee above 1,000 bps, or a zero fee owner. |
| 8203 | `0x200b` | `MarketV3Unsupported` | Token requires a settlement capability not implemented by ordinary V3 | `create_market_v3` with native SOL, a mint with a freeze authority, or a Token-2022 mint with extensions. |

## Position lifecycle (8300s)

| Code | Hex | Name | Message | When you hit it and what to do |
| --- | --- | --- | --- | --- |
| 8300 | `0x206c` | `TokenLifecycleIdentity` | V3 lifecycle account identity is invalid | An account does not match the position or market: wrong exposure, budget, policy, usage, writer, mint or token program; a non-USDC payment mint; an extra remaining account on exercise or release. Rebuild the instruction with the SDK builder from a fresh, finalized read. |
| 8301 | `0x206d` | `TokenLifecycleTerms` | V3 lifecycle terms or transition are invalid | `buy_position_v3` on a position whose terms do not match its market, or a writer instruction on a restricted position. |
| 8302 | `0x206e` | `TokenLifecycleAccounting` | V3 lifecycle accounting or admission rejected the transition | Your mint policy refused the fill. Read the `COVR_TOKEN_ACCOUNTING` reason line: `Unbootstrapped`, `Paused`, `Terms` or `Limit`. Fix the policy with `update_mint_policy_v1`, or wait for open positions to settle. |
| 8304 | `0x2070` | `TokenLifecycleAuthority` | V3 lifecycle authority is invalid | `exercise_v3` or `fund_restricted_exercise_v3` signed by a key that is neither your authority nor your current operator. `early_close_v3` signed by someone other than the writer. |

## Restricted settlement (8400s)

Restricted markets are covr-only for now.

| Code | Hex | Name | Message |
| --- | --- | --- | --- |
| 8400 | `0x20d0` | `RestrictedTerms` | Restricted timeout, terms identifier or record mode is not the agreed restricted terms |
| 8401 | `0x20d1` | `RestrictedState` | Restricted position state does not permit this transition |
| 8402 | `0x20d2` | `RestrictedTime` | Restricted transition is outside its funding, completion or cancellation time |
| 8403 | `0x20d3` | `RestrictedApproval` | Restricted cancellation request does not bind both parties to the exact current amounts |
| 8404 | `0x20d4` | `RestrictedImpaired` | Restricted collateral vault no longer backs the full claimed quantity |
| 8405 | `0x20d5` | `RestrictedEscrow` | Restricted strike escrow is not exactly funded, fresh or fully refundable |

`RestrictedTime` on `fund_restricted_exercise_v3` means you are outside the exercise window. `RestrictedImpaired` means the position's collateral vault holds less than its quantity, so funding is refused.

## Flash exercise (9100s)

`begin_flash_exercise_v3`, `finish_flash_exercise_v3` and the flash policy instructions return these codes. [Flash exercise](https://docs.covr.markets/concepts/flash-exercise.md#errors) explains each one. The flash put pair, `begin_flash_put_v3` and `finish_flash_put_v3`, also returns 9100 to 9103, 9114 and 9118. Its policy and floor codes are in the [9200s](#cash-secured-puts-9200s).

| Code | Hex | Name |
| --- | --- | --- |
| 9100 | `0x238c` | `FlashNotTopLevel` |
| 9101 | `0x238d` | `FlashInstructionsSysvar` |
| 9102 | `0x238e` | `FlashPairing` |
| 9103 | `0x238f` | `FlashProtectedAccount` |
| 9104 | `0x2390` | `FlashPolicySchema` |
| 9105 | `0x2391` | `FlashPolicyOwner` |
| 9106 | `0x2392` | `FlashPolicyDisabled` |
| 9107 | `0x2393` | `FlashPolicyGeneration` |
| 9108 | `0x2394` | `FlashPolicySettings` |
| 9109 | `0x2395` | `FlashPolicyLimit` |
| 9110 | `0x2396` | `FlashPairUnsupported` |
| 9111 | `0x2397` | `FlashFloorArithmetic` |
| 9112 | `0x2398` | `FlashFloorBelowPolicy` |
| 9113 | `0x2399` | `FlashPaymentBelowFloor` |
| 9114 | `0x239a` | `FlashDelegate` |
| 9115 | `0x239b` | `FlashEndpoint` |
| 9116 | `0x239c` | `FlashRecipient` |
| 9117 | `0x239d` | `FlashContext` |
| 9118 | `0x239e` | `FlashPositionState` |

Code 9000 (`0x2328`, `LegacyCloseNeedsMigrationConsumption`) also exists. It applies only when a migrated maker closes an old settled position. Desks registered with `register_maker_v3` never see it.

## Cash-secured puts (9200s)

The put instructions added on 4 November 2026 return these codes. Desks cannot quote puts yet: see [Cash-secured puts](https://docs.covr.markets/reference/program/instructions.md#cash-secured-puts). The [Users error table](https://docs.covr.markets/users/contract/instructions.md#puts) lists which instruction returns which.

| Code | Hex | Name | Meaning |
| --- | --- | --- | --- |
| 9200 | `0x23f0` | `PositionKind` | The market, position or policy is not a put, or its terms id is not the put terms id. For example, a call market passed to `fill_put_v3`. |
| 9201 | `0x23f1` | `AccountingVersion` | A USDC covered-call market or position was passed to a put instruction. |
| 9202 | `0x23f2` | `KindNotEnabled` | `kind` 0 (call) on a put setup instruction. This release accepts only `kind = 2`. |
| 9203 | `0x23f3` | `KindInvalid` | `kind` is neither 0 nor 2. |
| 9204 | `0x23f4` | `PaymentProfile` | The payment mint is not a plain 6-decimal SPL Token mint (82 bytes, initialized, not native SOL), differs from the market's or the policy's, or has changed since your put policy last approved it. Re-approve it with `update_mint_policy_v2`. |
| 9205 | `0x23f5` | `PutFunding` | A put position carries funding fields or a cancellation timeout. Puts have neither. |
| 9206 | `0x23f6` | `PutState` | The put position's state is not open, exercised, released or early-closed. |
| 9207 | `0x23f7` | `PutBacking` | A put policy's `put_backing` is not 1, 2 or 3. |
| 9208 | `0x23f8` | `PurchasePolicyForeign` | The purchase policy or usage passed to `buy_put_position_v3` or `update_mint_purchase_policy_v2` is not the buyer's own for this asset, payment token and kind. |
| 9209 | `0x23f9` | `PutEscrow` | The strike escrow does not hold exactly T right after the fill's lock, or holds less than T at an exit. |
| 9210 | `0x23fa` | `PutAssetSource` | The put asset vault passed is not your canonical one for this asset (seeds `"put-asset-v1"`, Maker, asset), at exercise or when creating a flash put policy. |
| 9211 | `0x23fb` | `PaymentSpendLedger` | Your spend ledger for this payment token is missing, belongs to another Maker or token, or is malformed. Create it with `init_payment_spend_ledger_v1`. |
| 9212 | `0x23fc` | `PaymentSpendBalance` | For a payment token other than USDC, your premium budget's `spent` no longer equals the ledger's total, or a ledger counter would overflow. |
| 9213 | `0x23fd` | `OriginRequired` | Reserved for call fills in a payment token other than USDC. No instruction returns it in this build. |
| 9214 | `0x23fe` | `FlashPutPolicySchema` | The flash put policy's address, bump, size or version is wrong. |
| 9215 | `0x23ff` | `FlashPutPolicyOwner` | A policy write not signed by your Maker's authority, or a policy whose stored Maker or owner differs from your Maker and its authority. |
| 9216 | `0x2400` | `FlashPutPolicyDisabled` | The flash put policy is disabled. |
| 9217 | `0x2401` | `FlashPutPolicyGeneration` | `expected_generation` (update) or `expected_policy_generation` (begin) is stale, exhausted or reserved. Re-read the policy and retry. |
| 9218 | `0x2402` | `FlashPutPolicySettings` | Invalid flash put settings: enabled with a zero cap or a zero maximum price, a cap that overflows the floor math, or `enabled = true` in `init_flash_put_policy_v1`. |
| 9219 | `0x2403` | `FlashPutPolicyLimit` | The position's quantity or lock is above the policy's caps. |
| 9220 | `0x2404` | `FlashPutPairUnsupported` | The asset and payment pair is not admitted (JitoSOL with USDC or USDT only), or does not match the position. |
| 9221 | `0x2405` | `FlashPutFloorArithmetic` | The asset floor overflowed. |
| 9222 | `0x2406` | `FlashPutFloorBelowPolicy` | Your `min_asset_atoms` is below the policy floor `max(Q + A, ceil(T × 10^d / R))`, where A is your minimum asset surplus and R your maximum price. |
| 9223 | `0x2407` | `FlashPutAssetBelowFloor` | The swap left less new asset in the output account than your floor. |
| 9224 | `0x2408` | `FlashPutEndpoint` | A temporary input or output account has the wrong owner, mint, delegate, close authority or starting balance. |
| 9225 | `0x2409` | `FlashPutRecipient` | The writer's asset account or your put asset vault is not acceptable as a destination: wrong owner, mint or program, frozen, native, or with a delegate or foreign close authority. |
| 9226 | `0x240a` | `FlashPutContext` | The flash put context's address, version or bound accounts do not match. |

## Errors from Anchor and other programs

| Code | Hex | From | Meaning for a desk |
| --- | --- | --- | --- |
| 0 | `0x0` | System program, on an account the instruction creates | The account already exists. On `fill_v3`: that quote nonce already opened a position. On setup: you already ran that step. |
| 1 | `0x1` | SPL Token, on `deposit` or `withdraw` | Insufficient funds in the source account. |
| 2001 | `0x7d1` | Anchor `ConstraintHasOne` | The signer is not `Maker.authority`, or an account does not belong to your Maker. |
| 2006 | `0x7d6` | Anchor `ConstraintSeeds` | An account is not at the PDA the instruction expects. Re-derive it with the SDK. |
| 2012 | `0x7dc` | Anchor `ConstraintAddress` | A mint or program account is not the one the market names (for example, not USDC). |
| 2014, 2015 | `0x7de`, `0x7df` | Anchor `ConstraintTokenMint`, `ConstraintTokenOwner` | A token account has the wrong mint or owner, for example a `deposit` source not owned by your authority. |
| 3002 | `0xbba` | Anchor `AccountDiscriminatorMismatch` | An account of the wrong type was passed, for example a Maker where a market is expected. |
| 3007 | `0xbbf` | Anchor `AccountOwnedByWrongProgram` | An account is owned by another program, for example a Token-2022 mint passed to `set_exposure_limit` (the SDK's `setExposureLimit` refuses that before you send). |
| 3012 | `0xbc4` | Anchor `AccountNotInitialized` | An account the instruction reads does not exist yet. Run the setup step that creates it. |

## Decode an error from a failed transaction

From the command line, `solana confirm -v <signature>` prints the logs of a sent transaction. In code, simulate first and read `logs`:

```ts
import type { Base64EncodedWireTransaction, Rpc, SolanaRpcApi } from '@solana/kit';
import { PROGRAM_ID } from '@covrfun/maker-sdk';

const COVR_ERRORS: Record<number, string> = {
  6000: 'BadSignature', 6001: 'InvalidTerms', 6002: 'InvalidAmount', 6003: 'InvalidOrder',
  6004: 'Unauthorized', 6006: 'ExposureLimit', 6007: 'PremiumBudgetExceeded',
  6008: 'JitoSolOrderLimit', 6009: 'InvalidJitoPool', 6010: 'MintPolicyIdentity',
  6011: 'MintPolicySchema', 6012: 'MintPolicyGeneration', 6013: 'MintPolicyUnauthorized',
  6014: 'MintPolicySettings', 7400: 'CustodyInvalidAccount', 7401: 'CustodyUnsupportedCapability',
  7402: 'CustodyUnauthorized', 7403: 'CustodyUnsafeRecipient', 7404: 'CustodyUnsafeSource',
  7405: 'CustodyInvalidAmount', 7406: 'CustodyPostTransferMismatch', 7600: 'MakerFenceSchema',
  7602: 'MakerFenceUnauthorized', 8000: 'MakerOriginSchema', 8001: 'MakerOriginIdentity',
  8002: 'MakerOriginState', 8200: 'MarketV3Schema', 8201: 'MarketV3Identity',
  8202: 'MarketV3Terms', 8203: 'MarketV3Unsupported', 8300: 'TokenLifecycleIdentity',
  8301: 'TokenLifecycleTerms', 8302: 'TokenLifecycleAccounting', 8304: 'TokenLifecycleAuthority',
  8400: 'RestrictedTerms', 8401: 'RestrictedState', 8402: 'RestrictedTime',
  8403: 'RestrictedApproval', 8404: 'RestrictedImpaired', 8405: 'RestrictedEscrow',
  8700: 'MakerMigrationSchema', 8701: 'MakerMigrationIdentity', 8800: 'MakerMigrationHoldsSchema',
  9100: 'FlashNotTopLevel', 9101: 'FlashInstructionsSysvar', 9102: 'FlashPairing',
  9103: 'FlashProtectedAccount', 9104: 'FlashPolicySchema', 9105: 'FlashPolicyOwner',
  9106: 'FlashPolicyDisabled', 9107: 'FlashPolicyGeneration', 9108: 'FlashPolicySettings',
  9109: 'FlashPolicyLimit', 9110: 'FlashPairUnsupported', 9111: 'FlashFloorArithmetic',
  9112: 'FlashFloorBelowPolicy', 9113: 'FlashPaymentBelowFloor', 9114: 'FlashDelegate',
  9115: 'FlashEndpoint', 9116: 'FlashRecipient', 9117: 'FlashContext', 9118: 'FlashPositionState',
  9200: 'PositionKind', 9201: 'AccountingVersion', 9202: 'KindNotEnabled', 9203: 'KindInvalid',
  9204: 'PaymentProfile', 9205: 'PutFunding', 9206: 'PutState', 9207: 'PutBacking',
  9208: 'PurchasePolicyForeign', 9209: 'PutEscrow', 9210: 'PutAssetSource',
  9211: 'PaymentSpendLedger', 9212: 'PaymentSpendBalance', 9213: 'OriginRequired',
  9214: 'FlashPutPolicySchema', 9215: 'FlashPutPolicyOwner', 9216: 'FlashPutPolicyDisabled',
  9217: 'FlashPutPolicyGeneration', 9218: 'FlashPutPolicySettings', 9219: 'FlashPutPolicyLimit',
  9220: 'FlashPutPairUnsupported', 9221: 'FlashPutFloorArithmetic', 9222: 'FlashPutFloorBelowPolicy',
  9223: 'FlashPutAssetBelowFloor', 9224: 'FlashPutEndpoint', 9225: 'FlashPutRecipient',
  9226: 'FlashPutContext',
};

/** The first program that failed, its custom error code, and covr's name and reason if it is covr's. */
export function decodeFailure(logs: readonly string[]) {
  for (const line of logs) {
    const m = /^Program (\w+) failed: custom program error: (0x[0-9a-fA-F]+)$/.exec(line);
    if (!m) continue;
    const program = m[1], code = Number.parseInt(m[2], 16);
    const ours = program === PROGRAM_ID && code >= 6000;
    const reason = logs.find((l) => /^Program log: COVR_[A-Z_]+: /.test(l))?.slice('Program log: '.length);
    return { program, code, name: ours ? (COVR_ERRORS[code] ?? `covr error ${code}`) : undefined, reason };
  }
  return undefined;
}

export async function simulateAndDecode(rpc: Rpc<SolanaRpcApi>, tx: Base64EncodedWireTransaction) {
  const { value } = await rpc.simulateTransaction(tx, { encoding: 'base64' }).send();
  return value.err ? decodeFailure(value.logs ?? []) : undefined;
}

// decodeFailure(['…', 'Program 8ZpbTPnDECPTDGN5VHHKH5gfer6EUTnRHcFwfUAbkJDg failed: custom program error: 0x1773'])
// -> { program: '8ZpbT…', code: 6003, name: 'InvalidOrder', reason: undefined }
```

The first `failed` line belongs to the innermost program that failed. If it is the SPL Token program, the code is a token program error, not covr's.

---

Source: https://docs.covr.markets/reference/program/errors · Part of covr Docs, https://docs.covr.markets/llms.txt
