percolator-engine 1.0.0

Formally verified risk engine for perpetual futures — fair exits (H) and O(1) overhang clearing (A/K)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
# percli Program ABI (v1.0.0)

This is the canonical wire-format reference for the percli Solana program. It
documents every instruction's discriminator, account list, argument layout,
emitted events, error codes, and the engine call it dispatches to. Use this
document when:

- Building an off-chain client in a language other than Rust.
- Auditing a third-party integration that talks to percli directly.
- Reproducing transactions for forensic analysis.

For the high-level operator workflow, see [`DEPLOYMENT.md`](./DEPLOYMENT.md).

> **Layout version:** v1 (`MARKET_DISCRIMINATOR_V1 = b"percmrk\x01"`).
> Programs running v0.9.x markets must run [`migrate_header_v1`]#19-migrate_header_v1
> before any other instruction will succeed.

---

## Conventions

### Account modifiers

| Symbol | Meaning |
|---|---|
| `s` | signer |
| `w` | writable |
| `r` | read-only |

`[ws]` = writable signer, `[r]` = read-only non-signer, etc.

### Argument encoding

All arguments are Borsh-encoded in the order listed and prefixed with the
8-byte Anchor discriminator (`sha256("global:<snake_case_name>")[0..8]`).
The full instruction data layout is:

```
<8-byte discriminator><borsh args>
```

### Account-data layout

Every market PDA has the same on-disk layout:

```
[0..8)              discriminator (b"percmrk" + version byte)
[8..176)            MarketHeader (168 bytes, v1 layout)
[176..176 + E)      RiskEngine state (E = SBF size_of::<RiskEngine>())
```

### `MarketHeader` fields (168 bytes, Borsh-encoded)

| Offset (within header) | Size | Field | Type |
|---|---|---|---|
| 0 | 32 | `authority` | `Pubkey` |
| 32 | 32 | `mint` | `Pubkey` |
| 64 | 32 | `oracle` | `Pubkey` |
| 96 | 32 | `matcher` | `Pubkey` |
| 128 | 32 | `pending_authority` | `Pubkey` |
| 160 | 1 | `bump` | `u8` |
| 161 | 1 | `vault_bump` | `u8` |
| 162 | 6 | `_padding` | `[u8; 6]` |

Add 8 to each offset for the absolute position inside the account data buffer.

### PDA derivation

| PDA | Seeds | Description |
|---|---|---|
| Market | `[b"market", authority]` | Stores header + engine; `bump` is recorded in the header. |
| Vault | `[b"vault", market]` | SPL token account holding all collateral; `vault_bump` is recorded in the header. |

### Error codes

| Code | Variant | Meaning |
|---:|---|---|
| 6000 | `InsufficientBalance` | Not enough free collateral / vault funds |
| 6001 | `Undercollateralized` | Operation would leave the account below maintenance margin |
| 6002 | `Unauthorized` | Signer doesn't match the required authority/owner/matcher |
| 6003 | `InvalidMatchingEngine` | Trade legs are invalid (size, account kind, etc.) |
| 6004 | `PnlNotWarmedUp` | PnL conversion attempted before the warmup period elapsed |
| 6005 | `Overflow` | Engine arithmetic overflowed |
| 6006 | `AccountNotFound` | Discriminator/owner/size mismatch, or engine slot empty |
| 6007 | `NotAnLPAccount` | Operation requires an LP account but the slot is a trader |
| 6008 | `PositionSizeMismatch` | Trade leg sizes don't sum to zero |
| 6009 | `AccountKindMismatch` | Wrong AccountKind for this operation |
| 6010 | `SideBlocked` | Side is in drain-only or reset-pending mode |
| 6011 | `CorruptState` | Header deserialization or PDA bump check failed |
| 6012 | `InvalidOraclePrice` | Pyth account is malformed or status is not Trading |
| 6013 | `AccountIndexOutOfRange` | `account_idx >= max_accounts` |
| 6014 | `StaleOracle` | Pyth timestamp is too old |
| 6015 | `InvalidOraclePriceValue` | Oracle price is zero or negative |
| 6016 | `AmountOverflow` | Token amount exceeds `u64::MAX` |
| 6017 | `AlreadyMigrated` | `migrate_header_v1` called on a v1 account |
| 6018 | `NotLegacyLayout` | `migrate_header_v1` called on an account whose discriminator isn't v0 |
| 6019 | `NoPendingAuthority` | `accept_authority` called when `pending_authority == default` |

---

## 1. `initialize_market`

**Discriminator:** `0x2323bdc19b30aacb` (`sha256("global:initialize_market")[0..8]`)
**Auth:** Authority (becomes `header.authority`)
**Engine call:** `RiskEngine::init_in_place(params, init_slot, init_oracle_price)`

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[ws]` | `authority` | Pays for the vault token account; becomes the market authority |
| 1 | `[w]` | `market` | Market PDA (must be pre-created by the client at `8 + 168 + size_of::<RiskEngine>()` bytes) |
| 2 | `[r]` | `mint` | SPL token mint for collateral |
| 3 | `[w]` | `vault` | Vault token account PDA (initialized by this instruction) |
| 4 | `[r]` | `oracle` | Pyth `Price` account (validated on later cranks) |
| 5 | `[r]` | `matcher` | Matcher signing key (stored in header) |
| 6 | `[r]` | `token_program` | SPL Token program |
| 7 | `[r]` | `system_program` | System program |

### Args

```rust
struct InitializeMarketArgs {
    init_slot: u64,
    init_oracle_price: u64,
    params: RiskParamsInput, // 15 × u64, see below
}

struct RiskParamsInput {
    warmup_period_slots: u64,
    maintenance_margin_bps: u64,
    initial_margin_bps: u64,
    trading_fee_bps: u64,
    max_accounts: u64,
    new_account_fee: u64,
    maintenance_fee_per_slot: u64,
    max_crank_staleness_slots: u64,
    liquidation_fee_bps: u64,
    liquidation_fee_cap: u64,
    min_liquidation_abs: u64,
    min_initial_deposit: u64,
    min_nonzero_mm_req: u64,
    min_nonzero_im_req: u64,
    insurance_floor: u64,
}
```

### Events

```rust
MarketInitialized {
    authority: Pubkey,
    mint: Pubkey,
    oracle: Pubkey,
    matcher: Pubkey,
    init_slot: u64,
    init_oracle_price: u64,
}
```

### Errors

| Code | When |
|---|---|
| `AccountNotFound` (6006) | Market account is too small, has the wrong owner, or has been initialized already |
| `InvalidOraclePriceValue` (6015) | `init_oracle_price == 0` |

---

## 2. `deposit`

**Discriminator:** `0xf223c68952e1f2b6`
**Auth:** Account owner (signer)
**Engine call:** `RiskEngine::deposit(account_idx, amount, ...)`

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[ws]` | `user` | Account owner (signer) |
| 1 | `[w]` | `market` | Market PDA |
| 2 | `[r]` | `mint` | Collateral mint |
| 3 | `[w]` | `user_token_account` | Source token account |
| 4 | `[w]` | `vault` | Vault token account PDA |
| 5 | `[r]` | `token_program` | SPL Token program |

### Args

```rust
struct DepositArgs { account_idx: u16, amount: u64 }
```

### Events

```rust
Deposited { user: Pubkey, account_idx: u16, amount: u64 }
```

### Errors

`AccountNotFound`, `Unauthorized`, `AccountIndexOutOfRange`, `AmountOverflow`,
`InsufficientBalance`, plus any underlying SPL token transfer error.

---

## 3. `withdraw`

**Discriminator:** `0xb712469c946da122`
**Auth:** Account owner (signer)
**Engine call:** `RiskEngine::withdraw(account_idx, amount, funding_rate, ...)`

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[ws]` | `user` | Account owner |
| 1 | `[w]` | `market` | Market PDA (signs the SPL transfer via vault PDA) |
| 2 | `[r]` | `mint` | Collateral mint |
| 3 | `[w]` | `user_token_account` | Destination token account |
| 4 | `[w]` | `vault` | Vault token account PDA |
| 5 | `[r]` | `token_program` | SPL Token program |

### Args

```rust
struct WithdrawArgs { account_idx: u16, amount: u64, funding_rate: i64 }
```

### Events

```rust
Withdrawn { user: Pubkey, account_idx: u16, amount: u64 }
```

### Errors

`Unauthorized`, `Undercollateralized`, `InsufficientBalance`,
`AccountIndexOutOfRange`, `AmountOverflow`.

---

## 4. `trade`

**Discriminator:** `0xb2901ad8f1bbce82`
**Auth:** Matcher (signer must equal `header.matcher`)
**Engine call:** `RiskEngine::trade(a, b, size_q, exec_price, funding_rate, ...)`

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[rs]` | `authority` | Matcher signing key |
| 1 | `[w]` | `market` | Market PDA |

### Args

```rust
struct TradeArgs {
    account_a: u16,
    account_b: u16,
    size_q: i128,
    exec_price: u64,
    funding_rate: i64,
}
```

### Events

```rust
TradeExecuted { matcher: Pubkey, account_a: u16, account_b: u16, size_q: i128, exec_price: u64 }
```

### Errors

`Unauthorized`, `InvalidMatchingEngine`, `PositionSizeMismatch`,
`AccountKindMismatch`, `SideBlocked`, `Undercollateralized`,
`AccountIndexOutOfRange`.

---

## 5. `crank`

**Discriminator:** `0x00e803c37c756935`
**Auth:** Permissionless
**Engine call:** `RiskEngine::crank(oracle_price, slot, funding_rate)`

Reads the latest Pyth price and applies it as the new mark.

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[rs]` | `cranker` | Anyone (signer) |
| 1 | `[w]` | `market` | Market PDA |
| 2 | `[r]` | `oracle` | Pyth `Price` account; must equal `header.oracle` |

### Args

```rust
struct CrankArgs { funding_rate: i64 }
```

### Events

```rust
Cranked { cranker: Pubkey, oracle_price: u64, slot: u64 }
```

### Errors

`InvalidOraclePrice`, `StaleOracle`, `InvalidOraclePriceValue`,
`Unauthorized` (if oracle pubkey doesn't match header).

---

## 6. `liquidate`

**Discriminator:** `0xdfb3e27d302e274a`
**Auth:** Permissionless
**Engine call:** `RiskEngine::liquidate(account_idx, funding_rate)`
**Returns:** `bool` — `true` if the account was actually liquidated.

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[rs]` | `liquidator` | Anyone (signer) |
| 1 | `[w]` | `market` | Market PDA |

### Args

```rust
struct LiquidateArgs { account_idx: u16, funding_rate: i64 }
```

### Events

```rust
Liquidated { liquidator: Pubkey, account_idx: u16, liquidated: bool }
```

### Errors

`AccountIndexOutOfRange`, `AccountNotFound`.

---

## 7. `settle`

**Discriminator:** `0xaf2ab957908366d4`
**Auth:** Account owner (signer)
**Engine call:** `RiskEngine::settle(account_idx, funding_rate)`

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[rs]` | `user` | Account owner |
| 1 | `[w]` | `market` | Market PDA |

### Args

```rust
struct SettleArgs { account_idx: u16, funding_rate: i64 }
```

### Events

```rust
Settled { user: Pubkey, account_idx: u16 }
```

### Errors

`Unauthorized`, `AccountIndexOutOfRange`.

---

## 8. `close_account`

**Discriminator:** `0x7dff950e6e224818`
**Auth:** Account owner (signer)
**Engine call:** `RiskEngine::close_account(account_idx, funding_rate)`

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[rs]` | `user` | Account owner |
| 1 | `[w]` | `market` | Market PDA |

### Args

```rust
struct CloseAccountArgs { account_idx: u16, funding_rate: i64 }
```

### Events

```rust
AccountClosed { user: Pubkey, account_idx: u16 }
```

### Errors

`Unauthorized`, `AccountIndexOutOfRange`, `Undercollateralized`
(if there's residual debt).

---

## 9. `reclaim_account`

**Discriminator:** `0xe6d9263c2b208dd2`
**Auth:** Permissionless
**Engine call:** `RiskEngine::reclaim_account(account_idx)`

Permissionlessly reclaims a slot whose owner has zero collateral, zero
position, and zero fee debt — typically a closed account whose owner has
walked away. Frees the slot for reuse.

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[rs]` | `reclaimer` | Anyone (signer) |
| 1 | `[w]` | `market` | Market PDA |

### Args

```rust
struct ReclaimAccountArgs { account_idx: u16 }
```

### Events

```rust
AccountReclaimed { reclaimer: Pubkey, account_idx: u16 }
```

### Errors

`AccountIndexOutOfRange`, `AccountNotFound`.

---

## 10. `withdraw_insurance`

**Discriminator:** `0xc9859176eb595abd`
**Auth:** Authority only
**Engine call:** `RiskEngine::withdraw_insurance(amount)`

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[ws]` | `authority` | Market authority |
| 1 | `[w]` | `market` | Market PDA (signs SPL transfer via vault) |
| 2 | `[r]` | `mint` | Collateral mint |
| 3 | `[w]` | `authority_token_account` | Destination token account |
| 4 | `[w]` | `vault` | Vault token account PDA |
| 5 | `[r]` | `token_program` | SPL Token program |

### Args

```rust
struct WithdrawInsuranceArgs { amount: u64 }
```

### Events

```rust
InsuranceWithdrawn { authority: Pubkey, amount: u64 }
```

### Errors

`Unauthorized`, `InsufficientBalance` (would breach `insurance_floor`).

---

## 11. `top_up_insurance`

**Discriminator:** `0xa5be6dc7a347316e`
**Auth:** Permissionless
**Engine call:** `RiskEngine::top_up_insurance(amount)`

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[ws]` | `depositor` | Anyone with tokens to spare |
| 1 | `[w]` | `market` | Market PDA |
| 2 | `[r]` | `mint` | Collateral mint |
| 3 | `[w]` | `depositor_token_account` | Source token account |
| 4 | `[w]` | `vault` | Vault token account PDA |
| 5 | `[r]` | `token_program` | SPL Token program |

### Args

```rust
struct TopUpInsuranceArgs { amount: u64 }
```

### Events

```rust
InsuranceToppedUp { depositor: Pubkey, amount: u64 }
```

### Errors

`AmountOverflow`, plus SPL transfer errors.

---

## 12. `deposit_fee_credits`

**Discriminator:** `0x7a749118bcace52c`
**Auth:** Account owner (signer)
**Engine call:** `RiskEngine::deposit_fee_credits(account_idx, amount)`

Lets an account holder pre-pay accumulated fees without touching the trading
collateral.

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[ws]` | `user` | Account owner |
| 1 | `[w]` | `market` | Market PDA |
| 2 | `[r]` | `mint` | Collateral mint |
| 3 | `[w]` | `user_token_account` | Source token account |
| 4 | `[w]` | `vault` | Vault token account PDA |
| 5 | `[r]` | `token_program` | SPL Token program |

### Args

```rust
struct DepositFeeCreditsArgs { account_idx: u16, amount: u64 }
```

### Events

```rust
FeeCreditsDeposited { user: Pubkey, account_idx: u16, amount: u64 }
```

### Errors

`Unauthorized`, `AccountIndexOutOfRange`, `AmountOverflow`.

---

## 13. `convert_released_pnl`

**Discriminator:** `0x71b5227b854f5da2`
**Auth:** Account owner (signer)
**Engine call:** `RiskEngine::convert_released_pnl(account_idx, x_req, oracle_price, slot, funding_rate)`

Converts matured (post-warmup) realized PnL into withdrawable collateral.
Reads the current oracle price as part of the conversion math.

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[rs]` | `user` | Account owner |
| 1 | `[w]` | `market` | Market PDA |
| 2 | `[r]` | `oracle` | Pyth `Price` account; must equal `header.oracle` |

### Args

```rust
struct ConvertReleasedPnlArgs { account_idx: u16, x_req: u64, funding_rate: i64 }
```

### Events

```rust
PnlConverted { user: Pubkey, account_idx: u16, x_req: u64 }
```

### Errors

`Unauthorized`, `PnlNotWarmedUp`, `AccountIndexOutOfRange`, `StaleOracle`,
`InvalidOraclePrice`, `InvalidOraclePriceValue`.

---

## 14. `accrue_market`

**Discriminator:** `0x67b8692c22f08f59`
**Auth:** Permissionless
**Engine call:** `RiskEngine::accrue_market(oracle_price, slot)`

Mark-to-market + funding accrual without touching individual accounts.
Cheaper than `crank` when you only need to advance the global state.

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[rs]` | `signer` | Anyone |
| 1 | `[w]` | `market` | Market PDA |
| 2 | `[r]` | `oracle` | Pyth `Price` account; must equal `header.oracle` |

### Args

None.

### Events

```rust
MarketAccrued { signer: Pubkey, oracle_price: u64, slot: u64 }
```

### Errors

`StaleOracle`, `InvalidOraclePrice`, `InvalidOraclePriceValue`,
`Unauthorized` (oracle pubkey mismatch).

---

## 15. `update_matcher`

**Discriminator:** `0x4d0f04f0c4768b97`
**Auth:** Authority only

Rotates the matcher signing key. The new matcher takes effect immediately.

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[rs]` | `authority` | Market authority |
| 1 | `[w]` | `market` | Market PDA |

### Args

```rust
struct UpdateMatcherArgs { new_matcher: Pubkey }
```

### Events

```rust
MatcherUpdated { authority: Pubkey, old_matcher: Pubkey, new_matcher: Pubkey }
```

### Errors

`Unauthorized`.

---

## 16. `update_oracle`

**Discriminator:** `0x7029d112f8e2fcbc`
**Auth:** Authority only

Rotates the Pyth oracle account. The new oracle is validated on the next
`crank` / `accrue_market` / `convert_released_pnl` call.

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[rs]` | `authority` | Market authority |
| 1 | `[w]` | `market` | Market PDA |
| 2 | `[r]` | `new_oracle` | New Pyth `Price` account (pubkey copied into header) |

### Args

None.

### Events

```rust
OracleUpdated { authority: Pubkey, old_oracle: Pubkey, new_oracle: Pubkey }
```

### Errors

`Unauthorized`.

---

## 17. `transfer_authority`

**Discriminator:** `0x30a94c48e5b437a1`
**Auth:** Authority only

Step 1 of the two-step authority handoff. Writes `new_authority` into
`header.pending_authority` without rotating `header.authority`. Self-transfer
is rejected with `Unauthorized`. Passing `Pubkey::default()` cancels any
in-flight transfer and emits `AuthorityTransferCancelled` instead of
`AuthorityTransferInitiated`.

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[rs]` | `authority` | Current market authority |
| 1 | `[w]` | `market` | Market PDA |

### Args

```rust
struct TransferAuthorityArgs { new_authority: Pubkey }
```

### Events

```rust
// Emitted when new_authority != Pubkey::default()
AuthorityTransferInitiated {
    market: Pubkey,
    old_authority: Pubkey,
    pending_authority: Pubkey,
}

// Emitted when new_authority == Pubkey::default()
AuthorityTransferCancelled {
    market: Pubkey,
    authority: Pubkey,
    previous_pending: Pubkey,
}
```

### Errors

`AccountNotFound` (not a v1 market), `Unauthorized` (signer mismatch or
self-transfer), `CorruptState` (header deserialization failed).

---

## 18. `accept_authority`

**Discriminator:** `0x6b56c65b210c6ba0`
**Auth:** Pending authority only

Step 2 of the two-step handoff. Rotates `header.authority` to
`header.pending_authority` and clears `pending_authority`.

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[rs]` | `new_authority` | Must equal `header.pending_authority` |
| 1 | `[w]` | `market` | Market PDA |

### Args

None.

### Events

```rust
AuthorityAccepted { market: Pubkey, old_authority: Pubkey, new_authority: Pubkey }
```

### Errors

`AccountNotFound` (not a v1 market), `NoPendingAuthority`
(`pending_authority == default`), `Unauthorized` (signer doesn't match
pending or signer is `Pubkey::default()`).

---

## 19. `migrate_header_v1`

**Discriminator:** `0x4cd8855fd38625cd`
**Auth:** Authority only (must match the v0-encoded authority)

One-time, idempotent-by-rejection migration from the legacy v0.9 layout
(136-byte header) to the v1.0 layout (168-byte header). Performed in-place
via `copy_within` — no realloc and no rent top-up are needed because real
v0.9 mainnet accounts were created with a host-side allocation that's
strictly larger than the SBF v1 size.

### Accounts

| # | Mod | Name | Description |
|---:|---|---|---|
| 0 | `[ws]` | `authority` | Must equal the v0-encoded authority |
| 1 | `[w]` | `market` | v0.9 market PDA (discriminator `b"percmrkt"`) |

### Args

None.

### Algorithm

1. Verify program ownership (Anchor `owner` constraint).
2. Verify discriminator `[0..7] == b"percmrk"` and version byte `[7]`:
   - `0x01``AlreadyMigrated`.
   - non-`0x74``NotLegacyLayout`.
3. Re-derive the Market PDA from the v0-encoded `authority` and verify the
   stored bump matches the canonical PDA bump (`CorruptState` if not).
4. Verify the signer matches the v0-encoded authority.
5. Shift engine bytes from `[144..)` to `[176..)` via `copy_within`.
6. Write the v1 header at `[8..176)` with `pending_authority = default`,
   preserving authority/mint/oracle/matcher/bump/vault_bump.
7. Stamp `data[7] = 0x01`.

### Events

```rust
HeaderMigrated {
    authority: Pubkey,
    market: Pubkey,
    mint: Pubkey,
    oracle: Pubkey,
    matcher: Pubkey,
    /// Actual on-chain data.len() after migration. Migration is in-place,
    /// so this equals the v0 host-side account size (NOT the SBF v1 size).
    account_size: u64,
}
```

### Errors

`AccountNotFound` (wrong owner, too small, or `[0..7] != b"percmrk"`),
`AlreadyMigrated` (version byte already `0x01`), `NotLegacyLayout`
(version byte is neither `0x01` nor `0x74`), `Unauthorized` (signer mismatch),
`CorruptState` (PDA bump mismatch).

---

## Discriminator quick-reference

| Instruction | Discriminator |
|---|---|
| `initialize_market` | `0x2323bdc19b30aacb` |
| `deposit` | `0xf223c68952e1f2b6` |
| `withdraw` | `0xb712469c946da122` |
| `trade` | `0xb2901ad8f1bbce82` |
| `crank` | `0x00e803c37c756935` |
| `liquidate` | `0xdfb3e27d302e274a` |
| `settle` | `0xaf2ab957908366d4` |
| `close_account` | `0x7dff950e6e224818` |
| `reclaim_account` | `0xe6d9263c2b208dd2` |
| `withdraw_insurance` | `0xc9859176eb595abd` |
| `top_up_insurance` | `0xa5be6dc7a347316e` |
| `deposit_fee_credits` | `0x7a749118bcace52c` |
| `convert_released_pnl` | `0x71b5227b854f5da2` |
| `accrue_market` | `0x67b8692c22f08f59` |
| `update_matcher` | `0x4d0f04f0c4768b97` |
| `update_oracle` | `0x7029d112f8e2fcbc` |
| `migrate_header_v1` | `0x4cd8855fd38625cd` |
| `transfer_authority` | `0x30a94c48e5b437a1` |
| `accept_authority` | `0x6b56c65b210c6ba0` |

These are computed from `sha256("global:<snake_case_name>")[0..8]`. Verify
locally:

```bash
python3 -c '
import hashlib, sys
print(hashlib.sha256(("global:" + sys.argv[1]).encode()).hexdigest()[:16])
' initialize_market
# → 2323bdc19b30aacb
```