@typesol/cli 0.37.0 → 0.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +352 -1
- package/README.md +31 -14
- package/SECURITY.md +1 -1
- package/dist/compiler/analyze.d.ts +7 -6
- package/dist/compiler/analyze.js +350 -38
- package/dist/compiler/emit/alias.js +3 -2
- package/dist/compiler/emit/base.d.ts +5 -0
- package/dist/compiler/emit/base.js +2 -0
- package/dist/compiler/emit/borsh.js +63 -2
- package/dist/compiler/emit/calls.d.ts +9 -1
- package/dist/compiler/emit/calls.js +147 -18
- package/dist/compiler/emit/cpi-core.js +21 -6
- package/dist/compiler/emit/cpi.js +81 -27
- package/dist/compiler/emit/create.d.ts +7 -0
- package/dist/compiler/emit/create.js +27 -0
- package/dist/compiler/emit/expressions.js +7 -4
- package/dist/compiler/emit/function.d.ts +7 -0
- package/dist/compiler/emit/function.js +168 -30
- package/dist/compiler/emit/program.js +15 -2
- package/dist/compiler/emit/shared.d.ts +5 -5
- package/dist/compiler/emit/shared.js +5 -0
- package/dist/compiler/emit/statements.d.ts +8 -0
- package/dist/compiler/emit/statements.js +93 -6
- package/dist/compiler/emit/storage.d.ts +10 -1
- package/dist/compiler/emit/storage.js +50 -11
- package/dist/compiler/idl.d.ts +2 -2
- package/dist/compiler/idl.js +48 -13
- package/dist/compiler/model.d.ts +47 -10
- package/dist/compiler/model.js +14 -4
- package/dist/testing.js +8 -0
- package/dist/tools/clientgen.js +10 -1
- package/dist/tools/portgen.d.ts +6 -0
- package/dist/tools/portgen.js +68 -17
- package/docs/architecture.md +5 -4
- package/docs/audit.md +31 -19
- package/docs/case-study-escrow.md +5 -5
- package/docs/case-study-jito-mev.md +171 -0
- package/docs/case-study-marginfi.md +797 -0
- package/docs/case-study-multisig.md +3 -3
- package/docs/case-study-raydium-clmm.md +151 -101
- package/docs/case-study-raydium-cp-swap.md +3 -3
- package/docs/cli.md +5 -5
- package/docs/client.md +1 -1
- package/docs/errors.md +15 -4
- package/docs/language.md +39 -26
- package/docs/migrate-from-anchor.md +4 -1
- package/docs/runtime.md +1 -1
- package/docs/security-model.md +2 -1
- package/docs/testing.md +33 -1
- package/lib/typesol.d.ts +48 -9
- package/package.json +9 -7
- package/runtime/typesol_rt.h +111 -17
|
@@ -0,0 +1,797 @@
|
|
|
1
|
+
# Case study: Marginfi v2
|
|
2
|
+
|
|
3
|
+
This page ports [Marginfi v2](https://github.com/mrgnlabs/marginfi-v2), a lending protocol, from
|
|
4
|
+
`programs/marginfi` at c5d440f6 (Anchor 1.0.2, Apache-2.0). The port is checked against the binary that runs on
|
|
5
|
+
mainnet as `MFv2hWf31Z9kbCa1snEPYctwafyhdvnV7FZnsebVacA` (version 0.1.12 in its on-chain IDL, deployed in slot
|
|
6
|
+
456093551), not a rebuild.
|
|
7
|
+
|
|
8
|
+
Marginfi is large: 124 instructions, 12 zero-copy accounts, 255 errors, and its amounts, prices and rates in I80F48
|
|
9
|
+
fixed point. The port comes in parts, each checked before the next:
|
|
10
|
+
|
|
11
|
+
| Part | What | Status |
|
|
12
|
+
| --- | --- | --- |
|
|
13
|
+
| 1 | Errors, I80F48 arithmetic, the zero-copy accounts and the types they hold | done |
|
|
14
|
+
| 2 | Group and bank administration, interest; accounts, deposits, repayments and fees | done |
|
|
15
|
+
| 3 | Oracles, the risk engine, withdrawals and borrows | done |
|
|
16
|
+
| 4 | Liquidation and bankruptcy | done |
|
|
17
|
+
| 5 | The rest: flash loans, administration, orders, staked SOL, the integrations | in progress: flash loans, account, group and fee state administration, bank administration (but resizing), placing, closing and executing orders, rebalances, resizing, the monitor archive, staked-SOL administration and Scope configuration, Solend, Kamino, Drift and JupLend banks, every oracle setup's pricing and venue rebalance legs done (all 124 instructions) |
|
|
18
|
+
|
|
19
|
+
The files are in [`showcase/mainnet/marginfi`](https://github.com/typesol-lang/typesol/tree/main/showcase/mainnet/marginfi):
|
|
20
|
+
|
|
21
|
+
| File | Holds |
|
|
22
|
+
| --- | --- |
|
|
23
|
+
| `marginfi.ts` | the instructions |
|
|
24
|
+
| `bank.ts` | a bank: creating one, checking its config, configuring it, accruing interest, the rate cache, its shares and limits, the states that refuse an instruction, the rate limiter, the price cache and the circuit breaker |
|
|
25
|
+
| `account.ts` | a marginfi account's balances: finding or opening one, growing it, closing it, their order, the flags indexers read |
|
|
26
|
+
| `oracle.ts` | the price adapter: oracle setups, validating a feed, reading Pyth push and Switchboard pull accounts, a Solend or Kamino reserve's, a Drift spot market's or a JupLend Lending's exchange rate applied to them, prices and confidence intervals |
|
|
27
|
+
| `solend.ts`, `kamino.ts`, `drift.ts`, `juplend.ts` | what the venue banks read from Solend's, klend's, Drift's and JupLend's accounts: reserves, obligations, a lending market's emergency mode, spot markets and users, Lendings |
|
|
28
|
+
| `risk.ts` | the risk engine: an account's assets and liabilities weighted and priced, e-mode, the isolated tier, the premium a liability projects and the rates its snapshot moves to, the circuit breaker's gate, the health cache |
|
|
29
|
+
| `interest_rate.ts` | the seven-point interest curve, the rates and fees it gives, the accrual arithmetic |
|
|
30
|
+
| `i80f48.ts` | I80F48, bit for bit as the `fixed` crate (1.28.0) computes it, including the release build's wrapping `*`, `/` and `from_num` |
|
|
31
|
+
| `state.ts`, `events.ts`, `args.ts`, `errors.ts` | accounts, events, instruction arguments and errors, as the on-chain IDL describes them |
|
|
32
|
+
|
|
33
|
+
## What is ported
|
|
34
|
+
|
|
35
|
+
**Part 1.** The 255 errors with their codes; I80F48 (products round toward −∞, quotients toward zero, conversions to
|
|
36
|
+
f64 to the nearest double); the 12 zero-copy accounts and the 32 types they hold. The accounts read mainnet's main
|
|
37
|
+
group, a USDC bank and the fee state as Anchor decodes them, and the port's IDL describes all 44 types as the on-chain
|
|
38
|
+
IDL does.
|
|
39
|
+
|
|
40
|
+
**Part 2, administration.** Eleven instructions:
|
|
41
|
+
|
|
42
|
+
- `init_global_fee_state`, `propagate_fee_state` (the program's fees and its pause, copied into a group);
|
|
43
|
+
- `marginfi_group_initialize`, `marginfi_group_configure` (the fast admin roles);
|
|
44
|
+
- `lending_pool_add_bank` and `lending_pool_add_bank_with_seed`: the bank, its three vaults and their authorities, the
|
|
45
|
+
flat SOL fee to the fee wallet, the config checks;
|
|
46
|
+
- `lending_pool_configure_bank`: the fast admin's settings, including the circuit breaker's switch and settings, the
|
|
47
|
+
liquidation fees, operational states (only risk-reducing changes), and the e-mode entries checked against the new
|
|
48
|
+
weights; a bank with frozen settings takes only its limits;
|
|
49
|
+
- `lending_pool_configure_bank_interest_only`, `lending_pool_configure_bank_limits_only`;
|
|
50
|
+
- `lending_pool_accrue_bank_interest`: interest over the seconds since the last update, less any circuit-breaker halt,
|
|
51
|
+
with the group's, the insurance fund's and the program's fees, and the rate cache;
|
|
52
|
+
- `lending_pool_update_fees_destination_account`.
|
|
53
|
+
|
|
54
|
+
Every one checks the transaction for a durable nonce as the original does.
|
|
55
|
+
|
|
56
|
+
**Part 2, accounts and deposits.** Five instructions:
|
|
57
|
+
|
|
58
|
+
- `marginfi_account_initialize` (a keypair account) and `marginfi_account_initialize_pda` (at
|
|
59
|
+
["marginfi_account", group, authority, index, third-party id]; a registered third-party id only through that
|
|
60
|
+
party's program);
|
|
61
|
+
- `lending_account_deposit`: the bank's interest accrued, the balance found or opened (at most 16, four of them
|
|
62
|
+
staked or integration positions), the deposit limit (or `deposit_up_to_limit`), the bank's state and the circuit
|
|
63
|
+
breaker, staked and default assets kept apart, the rate limiter, then the transfer: SPL Token, or Token-2022 with the
|
|
64
|
+
mint as the first remaining account and the amount before its transfer fee;
|
|
65
|
+
- `lending_account_close_balance`: a balance whose assets and liabilities are both below 0.0001, its dust assets to
|
|
66
|
+
the insurance fund;
|
|
67
|
+
- `marginfi_account_close`, for an account with no balances, orders, liquidation record or rebalance fees.
|
|
68
|
+
|
|
69
|
+
After each, the balances are sorted by bank key and the indexer flags recomputed, as the original does.
|
|
70
|
+
|
|
71
|
+
**Part 2, repayments and fees.** Five instructions:
|
|
72
|
+
|
|
73
|
+
- `lending_account_repay`: the booked premium settled before principal, never more than owed (a remainder under one
|
|
74
|
+
share is refused); `repay_all` repays the whole liability and premium rounded up to a token, the rounding and any
|
|
75
|
+
asset dust to the insurance fund, and closes the balance. The risk admin may clear a debt with nothing in a bank that
|
|
76
|
+
allows tokenless repayments (the premium written off; once the bank owes nothing it is marked done). Liquidators and
|
|
77
|
+
order keepers may repay for an account in receivership or order execution; a deleveraged account may repay while the
|
|
78
|
+
protocol is paused;
|
|
79
|
+
- `lending_pool_collect_bank_fees`: what the liquidity vault holds of the outstanding fees, in whole tokens, the
|
|
80
|
+
insurance fund's first, then the group's (to the fee vault), then the program's (to the fee wallet's associated token
|
|
81
|
+
account);
|
|
82
|
+
- `lending_pool_withdraw_fees`, `lending_pool_withdraw_insurance` (admin) and
|
|
83
|
+
`lending_pool_withdraw_fees_permissionless` (to the destination the admin set).
|
|
84
|
+
|
|
85
|
+
**Part 3, oracles.** Three instructions:
|
|
86
|
+
|
|
87
|
+
- `lending_pool_configure_bank_oracle`: a Pyth push or Switchboard pull feed for a bank (the governance admin), the
|
|
88
|
+
feed account checked as it is set: its key, then a Pyth `PriceUpdateV2`'s discriminator and Borsh form, or a
|
|
89
|
+
Switchboard feed's owner, discriminator and size. A bank in same-asset e-mode keeps its feed account and kind of
|
|
90
|
+
feed. Fixed and PT prices are refused (they go through `set_oracle_price`), Scope feeds too (their own instruction);
|
|
91
|
+
the venue setups (Kamino, Drift, Solend, JupLend) are refused on a bank of another asset tag, as the original's
|
|
92
|
+
first check does;
|
|
93
|
+
- `lending_pool_set_oracle_price`: a fixed price (never negative; the venue kind of fixed price for a venue bank),
|
|
94
|
+
refused on staked and same-asset banks; the PT start price's checks (in (0, 1], the accounts it takes);
|
|
95
|
+
- `lending_pool_pulse_bank_price_cache` (anyone): the bank's interest accrued (not while the protocol is paused),
|
|
96
|
+
then its spot price and confidence into the cache, and the circuit breaker's observation of them. Pyth must be
|
|
97
|
+
fully verified and no older than the bank's maximum age; its confidence interval is 2.12 × the reported one,
|
|
98
|
+
refused past the bank's maximum (10% by default) and capped at 5%. Switchboard's value is divided by 10^18, its
|
|
99
|
+
confidence the configured share of the price. The breaker counts one observation per two slots and per oracle
|
|
100
|
+
publication; a move from its EMA reference past a tier (beyond the confidence band), or past the long window's cap,
|
|
101
|
+
halts the bank for that tier's time, a breach within the escalation window raises the tier, three tier-3 trips in a
|
|
102
|
+
row break the bank, and a clean move pulls the reference by at most 5%.
|
|
103
|
+
|
|
104
|
+
**Part 3, withdrawals and the risk engine.** One instruction, `lending_account_withdraw`: part of a deposit (before a
|
|
105
|
+
Token-2022 transfer fee) or all of it (the fraction of a token to the insurance fund), refused past the deposit;
|
|
106
|
+
the bank's rate limits and the group's (priced in USD), a deleverage's daily limit, receivership and order execution
|
|
107
|
+
(anyone may withdraw, priced, no health check), a tokenless bank's remainder. Then the account's health, as the
|
|
108
|
+
risk engine computes it over the banks and oracles after the instruction's accounts (one [bank, oracle] group per
|
|
109
|
+
balance):
|
|
110
|
+
|
|
111
|
+
- each balance priced at the oracle's EMA for Initial health (spot for Maintenance), collateral less its
|
|
112
|
+
confidence interval and liabilities plus it, weighted, collateral in a paused or reduce-only bank worth nothing,
|
|
113
|
+
an isolated bank's collateral worth nothing, deposits past a bank's USD cap counted in proportion;
|
|
114
|
+
- a collateral leg whose oracle fails is skipped for Initial health and its error recorded in the health cache
|
|
115
|
+
(a liability's fails the instruction);
|
|
116
|
+
- e-mode: the tags every liability's bank offers, at their least favorable weights, and same-asset e-mode
|
|
117
|
+
(liabilities that all price one asset through one feed lift that asset's collateral to
|
|
118
|
+
`liability weight × (1 − 1 / leverage)`);
|
|
119
|
+
- the premium a premium-active liability has accrued since its last claim, projected into its value; after the
|
|
120
|
+
check, each liability's premium is claimed and its rate snapshot set from the collateral mix (an unpriceable
|
|
121
|
+
collateral leg only ratchets it up);
|
|
122
|
+
- the isolated tier (an isolated liability must be the only one), the circuit breaker's gate while the account owes
|
|
123
|
+
anything (a halted bank, or a price past the first tier or the long window), the liquidation tag cleared once
|
|
124
|
+
Maintenance health is positive (any error in that pass keeps it), the health cache (values, prices as f64,
|
|
125
|
+
the first oracle error, HEALTHY and ENGINE_OK, version 3), and the bank's price cache last.
|
|
126
|
+
|
|
127
|
+
**Part 3, borrows and health pulses.** Two instructions:
|
|
128
|
+
|
|
129
|
+
- `lending_account_borrow`: a new or larger liability (more than 0.0001 of a share, or the original refuses it as
|
|
130
|
+
dust), never from a balance holding assets, from a bank that is operational, not halted and not tokenless, within
|
|
131
|
+
its borrow limit and utilization; the bank's origination fee owed too and booked to the group and the program (at
|
|
132
|
+
the group's cached program fee rate); an isolated liability flags the account. Then the account's health as for a
|
|
133
|
+
withdrawal, refused when a premium-active debt has collateral it could not price, the circuit breaker's gate
|
|
134
|
+
always, the premium rates, and the rate limits after the check (priced at the bank's spot price; a group limit with
|
|
135
|
+
no price refuses it);
|
|
136
|
+
- `lending_account_pulse_health` (anyone): the health cache refreshed from three passes that each keep what they
|
|
137
|
+
get to when they fail: Initial health (the engine's or an oracle's fault in the flags, the first oracle error and
|
|
138
|
+
the prices so far), the premium rates when that pass was complete, Maintenance health (liquidatable or not, a
|
|
139
|
+
healthy account's liquidation tag cleared) and equity (bankrupt or not); the indexer flags (underwater, a trivial
|
|
140
|
+
balance, isolated debt, activity over 30 and 60 days); the event carrying the cache.
|
|
141
|
+
|
|
142
|
+
**Part 4, liquidation records and bankruptcy.** Four instructions:
|
|
143
|
+
|
|
144
|
+
- `marginfi_account_init_liq_record` and `marginfi_account_close_liq_record`: the liquidation record a liquidator
|
|
145
|
+
pays for, closed to its payer once the account has not been liquidated for 60 days, never during receivership or
|
|
146
|
+
with a receiver set;
|
|
147
|
+
- `marginfi_account_tag_liq_record` (anyone): an account the risk engine finds liquidatable at Maintenance is tagged
|
|
148
|
+
in its record, the health cache reset and filled from that pass, the event emitted; a healthy one is refused;
|
|
149
|
+
- `lending_pool_handle_bankruptcy` (the risk admin, or anyone on a bank flagged for permissionless settlement, past
|
|
150
|
+
the circuit breaker's gate): an account whose equity is gone has its debt in one bank covered from the insurance
|
|
151
|
+
vault (after a Token-2022 transfer fee, the transfer grossed up for it) and the rest socialized over the
|
|
152
|
+
depositors, the bank killed when nothing is left to share it; the premium claimed and the rest written off, the
|
|
153
|
+
bank's caches updated, the account disabled and marked as having been bankrupt.
|
|
154
|
+
|
|
155
|
+
**Part 4, classic liquidation.** One instruction, `lending_account_liquidate`: a liquidator takes some of an
|
|
156
|
+
unhealthy account's collateral in one bank at a discount and, for it, takes on the account's debt in another, worth
|
|
157
|
+
the collateral less the liquidator's cut; the account is credited that less the insurance fund's cut too, which the
|
|
158
|
+
liability bank's vault pays to its insurance vault (whole tokens; the fraction is booked). In the original's order:
|
|
159
|
+
both banks' interest; the liquidatee's banks checked for a circuit-breaker halt (then only the admins may liquidate)
|
|
160
|
+
or else its gate; the banks' and accounts' asset tags and states; the debt there and the account unhealthy at
|
|
161
|
+
Maintenance; the asset priced at spot less its confidence and the liability plus it; the liquidator's deposit in the
|
|
162
|
+
liability bank drawn down before it borrows, past the borrow limit; the seized collateral settling any premium the
|
|
163
|
+
liquidator owes in that bank first; both banks' caches. Then the liquidatee must still owe and be no healthier than
|
|
164
|
+
zero but better than before (its premium rates from the new collateral mix), its liquidation tag cleared, restarted
|
|
165
|
+
when a quarter of its deficit or debt went, or kept; the liquidator's Initial health over its own accounts, its tag,
|
|
166
|
+
its premium rates ratcheted and a premium-active debt it could not price raised to the highest rate for its tag; the
|
|
167
|
+
breaker's gate on the liquidator. The remaining accounts: a Token-2022 liability bank's mint, the asset bank's
|
|
168
|
+
oracles (only their count matters), the liability bank's, the liquidator's [bank, oracle…] groups after the
|
|
169
|
+
liquidation, then the liquidatee's; the last two counted by the instruction's arguments.
|
|
170
|
+
|
|
171
|
+
**Part 4, receivership.** Two instructions that open and close one transaction:
|
|
172
|
+
|
|
173
|
+
- `start_liquidation` (anyone): an account unhealthy at Maintenance, none of whose banks is halted and which passes
|
|
174
|
+
the breaker's gate, is put in receivership; its Maintenance and equity health are recorded (in its record and its
|
|
175
|
+
health cache, with no time or version, as the original leaves it) and each of its banks locks the prices those
|
|
176
|
+
passes took (real-time and time-weighted, with their confidence; 0 where a leg took none), so the bank must be
|
|
177
|
+
writable. The transaction is checked as the original checks it: only allowed programs, the start first but for
|
|
178
|
+
compute budget, integration refreshes and creating the record, once; the end last; between them only this
|
|
179
|
+
program's withdrawals and repayments; not through CPI. A receiver signing as the risk admin is marked so;
|
|
180
|
+
- `end_liquidation` (the receiver): the account's health at the locked prices (one bank account per balance, the
|
|
181
|
+
locks cleared after), its premium rates from the new mix; health may fall by no more than the value taken out and
|
|
182
|
+
a solvent account must stay solvent; the account must still be unhealthy unless its collateral was under $5 (a
|
|
183
|
+
close-out); the collateral seized within the premium (the fee state's, at least 5%, grown since the tag unless the
|
|
184
|
+
account is e-mode boosted or in bad debt); the tag after it, the record's newest entry (the oldest rotated out,
|
|
185
|
+
its unused bytes kept), the flat SOL fee from the fee payer or the receiver.
|
|
186
|
+
|
|
187
|
+
**Part 4, deleverage.** The risk admin's side of receivership, and the bookkeeping around it:
|
|
188
|
+
|
|
189
|
+
- `start_deleverage` and `end_deleverage` (the risk admin): any account, healthy or not, in receivership with the
|
|
190
|
+
risk admin as its receiver (no circuit-breaker checks, no durable nonce); at the end its health at the locked prices
|
|
191
|
+
may not have fallen, and no premium or fee applies;
|
|
192
|
+
- `configure_deleverage_withdrawal_limit` (the admin or the limit admin) and `update_deleverage_withdrawals` (the
|
|
193
|
+
flow admin, from the withdrawal events aggregated off-chain: in sequence, in slot order, at most 1,500 slots old):
|
|
194
|
+
the group's daily limit on what deleverages withdraw, which withdrawals already enforce;
|
|
195
|
+
- `lending_pool_force_tokenless_repay_complete` (the risk admin) and `purge_deleverage_balance` (the risk admin): a
|
|
196
|
+
bank whose tokenless repayments are done has the deposits left in it written off, balance by balance.
|
|
197
|
+
|
|
198
|
+
**Part 5, flash loans.** `lending_account_start_flashloan` and `lending_account_end_flashloan` (the account's
|
|
199
|
+
authority): the start checks, through the Instructions sysvar, that it is called top-level, that `end_index` comes
|
|
200
|
+
after it and is this program's end instruction naming the same account; until then the account's withdrawals and
|
|
201
|
+
borrows skip their health checks. The end runs them: Initial health over the account's banks and oracles, the
|
|
202
|
+
isolated tier, the tag cleared when healthy at Maintenance, every collateral priced when it owes a premium-active
|
|
203
|
+
bank, the premium rates (ratcheted), the breaker's gate while it owes anything.
|
|
204
|
+
|
|
205
|
+
**Part 5, account administration.** `marginfi_account_set_freeze` (the admin freezes, the governance admin
|
|
206
|
+
unfreezes), `marginfi_account_update_emissions_destination_account` (the authority, not while frozen),
|
|
207
|
+
`sync_indexer_flags` (any marginfi accounts that follow, writable), `transfer_to_new_account` and
|
|
208
|
+
`transfer_to_new_account_pda` (for the fee state's transfer fee to the global fee wallet: the new account, at a
|
|
209
|
+
keypair or the PDA `marginfi_account_initialize_pda` uses, takes the old one's balances, flags and tag under its new
|
|
210
|
+
authority; the old one is emptied, disabled and points at it), `admin_close_account` (anyone, an empty account idle
|
|
211
|
+
for 60 days with no orders, record or rebalance fee pool, its rent to the global fee wallet).
|
|
212
|
+
|
|
213
|
+
**Part 5, group and fee state administration.** `config_group_fee`, `edit_global_fee_state` (every field given
|
|
214
|
+
replacing the stored one) and `edit_fee_state_premium` (the global fee admin); `panic_pause` (the global fee admin or the pause delegate: 6 hours, extended while running, at most 3 a day
|
|
215
|
+
and 4 in a row), `panic_unpause` (the global fee admin) and `panic_unpause_permissionless` (anyone, once a pause has
|
|
216
|
+
run out); `marginfi_group_set_governance_admin` (the admin the first time, the governance admin after) and
|
|
217
|
+
`marginfi_group_configure_gov` (the governance admin: the admin, e-mode and risk admins; e-mode and same-asset
|
|
218
|
+
e-mode leverage caps from 1 to 100, both set or both unset, initial below maintenance);
|
|
219
|
+
`configure_bank_rate_limits` and `configure_group_rate_limits` (the admin or the limit admin, each window restarted);
|
|
220
|
+
`update_group_rate_limiter` (the flow admin's aggregated flows: in sequence and slot order, at most 1,500 slots old,
|
|
221
|
+
an inflow giving capacity back, an outflow within the windows); `lending_pool_configure_group_premium` (the admin:
|
|
222
|
+
the premium matrix kept sorted by collateral and liability tag, at most 64 pairs, a rate of 0 removing one).
|
|
223
|
+
|
|
224
|
+
**Part 5, bank administration.** `lending_pool_configure_bank_emode` (the governance admin: a bank's e-mode tag and
|
|
225
|
+
10 entries, sorted by collateral tag as Rust's stable sort does, their padding cleared, checked against its liability
|
|
226
|
+
weights and the group's caps, e-mode on when any is set), `lending_pool_clone_emode` (one bank's e-mode settings to
|
|
227
|
+
another), `lending_pool_configure_bank_premium` (the admin: its premium tag, on or off, the activation time when it
|
|
228
|
+
turns on, the original's warning when it turns off), `lending_pool_clear_circuit_breaker` (the admin or the risk
|
|
229
|
+
admin: interest first, the halt reset, the references too if asked), `lending_pool_backfill_bank_is_t22_flag`
|
|
230
|
+
(anyone: a seed that derives the bank under the mainnet program, IS_T22 from a Token-2022 mint),
|
|
231
|
+
`lending_pool_close_bank` (the admin: a bank made to close with no positions, or forced; no shares or emissions left
|
|
232
|
+
either way; its rent to the admin), `lending_pool_configure_bank_gov` (the governance admin: weights, risk tier, asset
|
|
233
|
+
tag, the oracle's confidence cap and age, the freeze and tokenless flags, the operational state only back to
|
|
234
|
+
Operational; a frozen bank takes none, with the original's warning), `lending_pool_collect_bank_premium_fees`
|
|
235
|
+
(anyone: the collected premium, in whole tokens and as much as the vault holds, to the premium wallet's token
|
|
236
|
+
account). `super_admin_deposit` and `super_admin_withdraw` panic in the mainnet build once their accounts and the
|
|
237
|
+
durable-nonce check pass (they are for staging and localnet), and so does the port. `lending_pool_emissions_deposit` (anyone: same-mint
|
|
238
|
+
tokens straight into the liquidity vault, the asset share value raised by them after accrual; refused for mints with
|
|
239
|
+
a transfer fee or a transfer hook, and below 2^20 asset shares), `lending_pool_init_same_asset_emode_registry` and
|
|
240
|
+
`lending_pool_set_bank_same_asset_emode_eligibility` (the governance admin: the group's registry PDA, and a bank in or
|
|
241
|
+
out of it under its (mint, `oracle_keys[0]`) group, removed by moving the last entry into its place and an emptied
|
|
242
|
+
group by moving the last group into its, as the original does; Pyth push or Switchboard pull feeds only, not frozen
|
|
243
|
+
banks). `init_bank_metadata` (anyone pays: the metadata PDA of a bank that may not exist yet; a bank of
|
|
244
|
+
the program whose seed is known must be its own PDA), `write_bank_metadata` and `write_bank_metadata_pre_init` (the
|
|
245
|
+
metadata admin: a ticker of at most 64 bytes and a description of at most 128, each when given, zero-filled, the index
|
|
246
|
+
of its last byte kept; before the bank exists, for the PDA its group, mint and seed will give). These take
|
|
247
|
+
`Option<Vec<u8>>` arguments, which TypeSOL reads as Anchor does. `lending_pool_clone_bank` copies a mainnet bank on
|
|
248
|
+
staging and localnet builds; the mainnet build panics once the bank and its vaults are created, and so does the port.
|
|
249
|
+
|
|
250
|
+
**Part 5, orders.** `marginfi_account_place_order` (the authority: a stop loss, a take profit or both on two balances,
|
|
251
|
+
one asset and one liability found by the original's binary search over the balances, which need not be sorted (the
|
|
252
|
+
port's search misses where Rust's does: checked on unsorted balances and in the fuzz steps); each
|
|
253
|
+
tagged for the order, new tags searched from the last one used; the order is the PDA of the account and the sha256 of
|
|
254
|
+
the two bank keys in byte order, so a pair has one; the fee state's flat fee to the fee wallet),
|
|
255
|
+
`marginfi_account_close_order` (the authority or the governance admin, the rent to whom they name),
|
|
256
|
+
`marginfi_account_set_keeper_close_flags` (untag the named balances, or all of them) and
|
|
257
|
+
`marginfi_account_keeper_close_order` (anyone, once a tagged balance is gone or untagged, or the account is closed).
|
|
258
|
+
The original hashes any number of bank keys for the order's address and wants two afterwards; the port wants two
|
|
259
|
+
first, so only a transaction wrong in that and in another way fails differently. `marginfi_account_start_execute_order`
|
|
260
|
+
and `marginfi_account_end_execute_order` run an order in a sandwich like receivership's (the same instruction rules):
|
|
261
|
+
the start checks the trigger at the equity value of the order's two tagged balances (a stop loss keeps that value as
|
|
262
|
+
the level to hold), marks the account as executing so the executor may withdraw and repay as its authority, and
|
|
263
|
+
records every other balance; the end wants the order's liability repaid in full and what is left within the order's
|
|
264
|
+
slippage of the level (a take profit also within the fee state's maximum fee of where it started), every recorded
|
|
265
|
+
balance as it was, the account no less healthy unless it is healthy, then refreshes the health cache and premium
|
|
266
|
+
snapshots and closes the order and the record to whom the executor names.
|
|
267
|
+
|
|
268
|
+
**Part 5, rebalance orders (their keeping).** `marginfi_account_place_rebalance_order` (the authority: the PDA of the
|
|
269
|
+
account and a mint, 2 to 8 allowed banks it deposits into one of and owes none, a minimum improvement, cooldown,
|
|
270
|
+
budget and keeper tip, defaults where not given), `marginfi_account_update_rebalance_order` (each field when given),
|
|
271
|
+
`marginfi_account_close_rebalance_order` (the authority, or anyone once the account holds nothing in the allowed banks
|
|
272
|
+
or is closed; an optional signer), `marginfi_account_top_up_rebalance_fee_pool` (anyone: the account's system PDA,
|
|
273
|
+
its rent reserve first) and `marginfi_account_withdraw_rebalance_fee_pool` (the authority; all of it rather than leave
|
|
274
|
+
it short of the reserve). Their events carry the allowed banks as a Vec, sent in declared order as Anchor does.
|
|
275
|
+
`marginfi_account_start_rebalance`, `marginfi_account_end_rebalance` and `marginfi_account_settle_rebalance_tip` run
|
|
276
|
+
them: the start reads the order's banks from the remaining accounts, accrues them, and checks each move's destination
|
|
277
|
+
with its whole inflow landed beats its source by the order's minimum improvement while no other bank with room pays
|
|
278
|
+
those tokens more (the supply rate from each bank's curve at the utilization after the deposit), then records the
|
|
279
|
+
banks' amounts, rates and tags; the executor withdraws and deposits in between; the end checks each destination still
|
|
280
|
+
beats its source, every bank's token amount moved as declared (within 3 native units per move), the budget, the
|
|
281
|
+
account's Maintenance health and every other balance, carries order tags with their balances, and escrows the
|
|
282
|
+
keeper's share of the tip; settlement pays it once the destinations out-yielded their sources, else refunds it.
|
|
283
|
+
Rebalances across Kamino, Drift and JupLend banks price each leg at the venue's supply rate
|
|
284
|
+
(`programs/marginfi/src/state/rate.rs` and the mocks' rate math), as the original does: klend's 11-point borrow curve
|
|
285
|
+
times utilization less its take rate, plus the reserve's reward emissions (capped by its lending market), at the
|
|
286
|
+
chain's measured pace for a per-slot reserve (slots over the elapsed part of the epoch, from `epochStartTimestamp()`);
|
|
287
|
+
Drift's piecewise curve less the insurance fund's factor (a market without borrows exempt from staleness); JupLend's
|
|
288
|
+
liquidity-layer rate (the mint's rate model at the diluted utilization) plus its Lending's reward rate. Amounts
|
|
289
|
+
convert through the venue's exchange rate (Drift's in its 9-decimal balances), deposit room is the tighter of the
|
|
290
|
+
bank's limit and the venue's cap, settlement reads the venues' rates through the yield index, and the conservation
|
|
291
|
+
dust widens by the largest exchange rate. Solend banks are refused (RebalanceVenueUnsupported), as there.
|
|
292
|
+
|
|
293
|
+
**Part 5, resizing and the monitor archive.** `lending_pool_resize_group_account`, `lending_pool_resize_bank_account`
|
|
294
|
+
and `resize_global_fee_state` grow a v1-sized account to the current struct size (anyone pays the rent short of it;
|
|
295
|
+
TypeSOL's `resizeAccount`, Rust's `AccountInfo::resize`). `monitor_archive_initialize` and
|
|
296
|
+
`monitor_archive_upsert_batch` keep the snapshot manager's archive, raw bytes in a large account the client allocated
|
|
297
|
+
(a tag, the meta, an index map, then a ring of 168 hourly snapshots per mint), written with `writeData`.
|
|
298
|
+
|
|
299
|
+
**Part 5, staked SOL and Scope.** `init_staked_settings`, `edit_staked_settings`, `disable_staked_oracles` and
|
|
300
|
+
`enable_staked_oracle_onramp` (the governance admin: a group's staked-SOL settings, the PDA of the group, checked as the
|
|
301
|
+
original checks them; the oracle flags), `propagate_staked_settings` (anyone: the settings onto a staked bank, a new
|
|
302
|
+
oracle checked), `lending_pool_add_bank_permissionless` (anyone: a bank for a validator's SPL single-pool LST, from the
|
|
303
|
+
settings, with a placeholder curve; the pool, its LST mint, stake account and on-ramp must be the PDAs of the vote
|
|
304
|
+
account, owned as the original wants) and `lending_pool_backfill_staked_bank_validator_vote_account`. The tests write
|
|
305
|
+
the pool's accounts into both ledgers (marginfi reads their owners, addresses and the LST mint; nothing calls the pool
|
|
306
|
+
program). `lending_pool_configure_bank_oracle_scope` prices a bank by a Scope feed entry, Scope's `OraclePrices`
|
|
307
|
+
account checked as the original checks it. Pricing staked banks (the pool's stake per LST) and Scope feeds comes with
|
|
308
|
+
part 5f.
|
|
309
|
+
|
|
310
|
+
**Part 5, Solend and Kamino banks.** A venue bank deposits into a Solend or Kamino (klend) reserve of its mint through
|
|
311
|
+
an obligation its liquidity vault authority owns, and holds the reserve's collateral tokens; it never lends.
|
|
312
|
+
`lending_pool_add_bank_solend` and `lending_pool_add_bank_kamino` (the governance admin: the bank from a compact
|
|
313
|
+
config, the reserve of its mint, the obligation's address, the feed and the reserve checked; Kamino's event names the
|
|
314
|
+
group's admin as its signer, as the original's does), `solend_init_obligation` and `kamino_init_obligation` (anyone:
|
|
315
|
+
the obligation, klend's user metadata and farm state first, and a deposit of at least 10 tokens that keeps it open;
|
|
316
|
+
Solend's obligation is created as Anchor's `init` does, over an address someone funded too),
|
|
317
|
+
`solend_deposit`, `kamino_deposit`, `solend_withdraw` and `kamino_withdraw` (the tokens through the liquidity vault
|
|
318
|
+
into the reserve and back, the obligation's change checked against the amount at the reserve's rate, give or take one
|
|
319
|
+
token; withdrawals in collateral tokens, then the account's health), `propagate_kamino_market_emergency` (the market's
|
|
320
|
+
emergency mode onto the bank) and `kamino_harvest_reward` (a klend farm's reward, harvested by the liquidity vault
|
|
321
|
+
authority, to the global fee wallet's account). These CPI into Solend's and klend's mainnet programs (and kfarms'),
|
|
322
|
+
loaded into both ledgers; the tests make markets, reserves and a farm with those programs' own instructions and write
|
|
323
|
+
a reserve's settings into its config.
|
|
324
|
+
|
|
325
|
+
Their banks are priced by `SolendPythPull`, `SolendSwitchboardPull`, `KaminoPythPush` and `KaminoSwitchboardPull`: the
|
|
326
|
+
feed's prices and confidences times the reserve's exchange rate (its liquidity per collateral token, from its supplies,
|
|
327
|
+
borrows and fees, scaled to the mint's decimals), the reserve refreshed this slot. The bank's price cache keeps the
|
|
328
|
+
feed's price before the rate (Pyth's confidence uncapped) and the rate as its multiplier, and the circuit breaker
|
|
329
|
+
watches the price times the rate. A Kamino reserve or market in emergency mode takes the collateral's Initial value
|
|
330
|
+
(it backs no new borrows) but leaves its Maintenance value. One behaviour of the original is kept as it is:
|
|
331
|
+
`solend_withdraw` still holds its bank when it runs the circuit-breaker gate, so a Solend withdrawal from an account
|
|
332
|
+
with any liability fails (`AccountBorrowFailed` in the original, error 12 in the port) once its health checks pass.
|
|
333
|
+
|
|
334
|
+
**Part 5, Drift and JupLend banks.** A Drift bank deposits into a Drift spot market of its mint through a user
|
|
335
|
+
(sub-account 0) and user stats its liquidity vault authority owns, and holds Drift's scaled balance (9 decimals; its
|
|
336
|
+
deposit limit, in the mint's decimals, scaled to them). `lending_pool_add_bank_drift`, `drift_init_user` (anyone: the
|
|
337
|
+
user stats and user, the user moved into the market's pool, and a deposit of at least 10 tokens), `drift_deposit` and
|
|
338
|
+
`drift_withdraw` (the market's interest brought up first; the user's scaled balance must change by exactly the amount's;
|
|
339
|
+
a withdrawal's rewards in other markets passed with their spot markets and mints), `drift_harvest_reward` (a reward
|
|
340
|
+
Drift's admin paid into the bank's user in another market, withdrawn whole and sent to the global fee wallet's account)
|
|
341
|
+
and `drift_claim_bad_debt` (a claim on Drift's bad-debt Merkle distributor: the claim status' rent prefunded, the
|
|
342
|
+
distributor's `new_claim` signed by the liquidity vault authority, what it paid swept to the fee wallet). Drift's
|
|
343
|
+
program on mainnet is now a withdraw-only wind-down build, so the tests load the Drift v2 build Marginfi's own tests use
|
|
344
|
+
(2.114), and the distributor as it runs on mainnet; a distributor's admin is a fixed key, so the tests write one into
|
|
345
|
+
both ledgers.
|
|
346
|
+
|
|
347
|
+
A JupLend bank deposits into JupLend's Lending of its mint (the Fluid liquidity layer behind it) and holds its
|
|
348
|
+
fTokens, in a vault the bank owns. `lending_pool_add_bank_juplend` (the bank starts Uninitialized),
|
|
349
|
+
`juplend_init_position` (anyone, once: a seed deposit of at least 10 tokens, and the bank is Operational),
|
|
350
|
+
`juplend_deposit` (the Lending's rate brought up to date; the fTokens minted must be exactly the amount's at its
|
|
351
|
+
prices) and `juplend_withdraw` (the fTokens burned rounded up, or all of them redeemed; the tokens come back through the
|
|
352
|
+
liquidity vault authority's associated token account). The tests build the liquidity layer, its token reserves and the
|
|
353
|
+
Lendings with JupLend's mainnet programs and their own instructions.
|
|
354
|
+
|
|
355
|
+
They are priced by `DriftPythPull`, `DriftSwitchboardPull`, `JuplendPythPull` and `JuplendSwitchboardPull`: the feed
|
|
356
|
+
times the spot market's cumulative deposit interest (over 10^10) or the Lending's token exchange price (over 10^12),
|
|
357
|
+
the market or Lending updated this second, the cache keeping the rate as its multiplier, as for Solend and Kamino.
|
|
358
|
+
|
|
359
|
+
**Part 5, every oracle setup.** The setups that price from another program's account
|
|
360
|
+
(`programs/marginfi/src/state/lst_stake_price.rs`) are priced as the original prices them, the accounts written into
|
|
361
|
+
both ledgers (Marginfi only reads them):
|
|
362
|
+
|
|
363
|
+
- `StakedWithPythPush`: the SOL feed times the validator single pool's SOL per LST — before the pool's on-ramp, its
|
|
364
|
+
stake account's delegated stake less the 1 SOL bootstrap over the LST supply; after it, the stake account's and the
|
|
365
|
+
on-ramp's lamports above rent exemption over the supply plus 1 SOL of phantom tokens; nothing while staked oracles
|
|
366
|
+
are switched off;
|
|
367
|
+
- `PythMSOL`, `PythLST` and their `KaminoMSOL`, `KaminoLST`, `JuplendMSOL`, `JuplendLST` kinds: the SOL feed times
|
|
368
|
+
Marinade's mSOL rate (its staked, cooling down and reserve SOL less tickets, over the mSOL supply) or an SPL or
|
|
369
|
+
Sanctum stake pool's LST rate (updated this epoch or the last), each in (0, 3), then the venue's rate;
|
|
370
|
+
- `Scope`, `ScopeKamino`, `ScopeJuplend`: an entry of Scope's `OraclePrices` (value over 10^exp, no confidence),
|
|
371
|
+
dated, not in the future nor older than the bank's maximum age, then the venue's rate;
|
|
372
|
+
- `PTPyth`, `PTFixed`: an Exponent PT accreting linearly from the bank's start price to par at maturity, capped by
|
|
373
|
+
what a PT redeems for, and not priced while the vault is in emergency mode, except for an account in deleverage or a
|
|
374
|
+
risk admin's liquidation (the original's `ignore_pt_emergency`);
|
|
375
|
+
- `FixedKamino`, `FixedDrift`, `FixedJuplend`: a venue bank's fixed price times the venue's rate.
|
|
376
|
+
|
|
377
|
+
Rebalance legs in Kamino, Drift and JupLend banks are ported too (see Part 5, rebalances, above).
|
|
378
|
+
|
|
379
|
+
The venue tests (Solend, Kamino, Drift, JupLend) hold a refused transaction to the original's error, code included,
|
|
380
|
+
not only to failing: one difference turned up that way and was fixed (a claim given one token account for two, which
|
|
381
|
+
the original lets through to its own check).
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
## What it needed
|
|
385
|
+
|
|
386
|
+
- **Another program's struct account.** JupLend's `Lending` is an `AccountLoader` of another program's type, with
|
|
387
|
+
`has_one = f_token_mint`: `HasOne<Owner<Account<Lending>, "jup3Y…">, "f_token_mint", …>` loads it with that program as
|
|
388
|
+
its owner (3007), Anchor's discriminator for the name, and records the relation in the IDL.
|
|
389
|
+
- **The venues' accounts loaded first.** Marginfi takes Solend's reserve, klend's reserve, obligation and lending
|
|
390
|
+
market, and Drift's spot market and user as `AccountLoader`s of the venues' types, which Anchor loads (owner 3007,
|
|
391
|
+
discriminator 3001 / 3002) before it checks any account's constraints. They are `Owner<Account<T>, "…">` in the port
|
|
392
|
+
(a struct of the venue's bytes with its discriminator), so a foreign account gets 3007 there too and not the bank's
|
|
393
|
+
`has_one` error; Solend's reserve has a one-byte discriminator (its version), `/** @discriminator 0x01 */`.
|
|
394
|
+
- **The epoch's start time.** Kamino's per-slot rates are rescaled at the chain's measured pace, slots over the
|
|
395
|
+
seconds since the epoch began: `epochStartTimestamp()` reads it from the Clock (with `slotsPerEpoch()`,
|
|
396
|
+
`firstNormalEpoch()` and `firstNormalSlot()` for the epoch's first slot).
|
|
397
|
+
- **A CPI into an address-checked account.** Marginfi takes JupLend's programs as `UncheckedAccount`s with
|
|
398
|
+
`address = …`: `Address<AccountInfo, "jup3Y…">` is now a CPI's program, checked by its key alone (2012).
|
|
399
|
+
- **The Clock in a constraint and in the body.** Solend's deposit and withdrawal refuse a reserve not refreshed this
|
|
400
|
+
slot in an account constraint, and use the time in their bodies; the compiler declared the instruction's Clock
|
|
401
|
+
cache twice (or after the constraint that read it). It is now declared first.
|
|
402
|
+
- **An associated token account of a stored key.** `kamino_harvest_reward` pays into the ATA of the fee state's
|
|
403
|
+
`global_fee_wallet`: `Ata<Mut<TokenAccount>, "@fee_state.global_fee_wallet", "reward_mint">`, the owner read from the
|
|
404
|
+
struct account, recorded in the IDL as the account (`fee_state`), as Anchor records `fee_state.load()?.…`.
|
|
405
|
+
- **Zero-copy accounts checked as Anchor's `AccountLoader` checks them.** For `@serialization bytemuck` structs the
|
|
406
|
+
owner comes first (3007, also for an account that was never created, where `Account<T>` gives 3012), then a
|
|
407
|
+
discriminator to read (3001) and match (3002), then the size.
|
|
408
|
+
- **The Instructions sysvar behind an address constraint.** Marginfi takes it as an `UncheckedAccount` with
|
|
409
|
+
`address = sysvar::instructions::ID`: a wrong account is ConstraintAddress (2012). `Address<InstructionsSysvar,
|
|
410
|
+
"Sysvar1nstructions…">` gives that code, in Anchor's constraint order.
|
|
411
|
+
- **Anchor's order for `init` accounts.** Anchor creates an instruction's `init` accounts before it checks the other
|
|
412
|
+
accounts' constraints. Adding a bank whose seeded address is taken, signed by someone who is not the governance
|
|
413
|
+
admin, fails creating the bank (system error 0), not with Unauthorized. The fuzzer found this. Creates at the start
|
|
414
|
+
of a body now run before the other accounts' constraints in every TypeSOL program.
|
|
415
|
+
- **Borsh arguments full of Options.** `BankConfigFast` holds an `Option<InterestRateConfigOpt>`, itself all Options,
|
|
416
|
+
and two `Option<[u16; 3]>`; the configure event repeats them. Part 2a added these to the compiler.
|
|
417
|
+
- **f64 in events.** The accrual event reports the fees as `f64`: the port converts the I80F48 bits as `fixed`'s
|
|
418
|
+
`to_num::<f64>()` does (nearest, ties to even).
|
|
419
|
+
- **An Option argument with a default as a seed.** The PDA account's seeds end with `third_party_id.unwrap_or(0)`. In
|
|
420
|
+
TypeSOL that is `third_party_id ?? 0n`, and the IDL records it as Anchor's text, `third_party_id.unwrap_or(0)`.
|
|
421
|
+
`typesol client` and `typesol/testing` derive such PDAs; before, `typesol client` refused Marginfi's on-chain IDL
|
|
422
|
+
over that seed.
|
|
423
|
+
- **Token accounts never created.** Collecting fees to a fee wallet that has no associated token account yet fails
|
|
424
|
+
with AccountNotInitialized (3012) in Anchor, before the owner check. TypeSOL's token account and mint checks gave
|
|
425
|
+
3007; they now follow Anchor.
|
|
426
|
+
- **Remaining accounts in helpers.** A bank's oracle accounts come after its declared accounts, and the price adapter
|
|
427
|
+
reads them in helpers. A helper may now take a `RemainingAccount` parameter (`remainingAccounts().get(i)`): its key,
|
|
428
|
+
owner and data length, `readData` at any offset, `loadAccount` / `loadAccountMut` of a struct.
|
|
429
|
+
- **`Option<WrappedI80F48>` arguments.** `edit_global_fee_state` and `marginfi_group_configure_gov` take Options of
|
|
430
|
+
a struct as instruction arguments, not inside a struct argument. TypeSOL accepts them now: a tag byte, then the
|
|
431
|
+
struct when Some, read after `x !== null`.
|
|
432
|
+
- **Errors as values.** Marginfi's price reads return `Result`s that its risk engine sometimes records instead of
|
|
433
|
+
failing. The adapter's helpers return their error as a value, and the instructions fail with it:
|
|
434
|
+
`require(r.err === 0n, r.err)`, a `require` whose code is computed at run time.
|
|
435
|
+
- **The remaining accounts in helpers.** The risk engine walks [bank, oracle…] groups after the instruction's
|
|
436
|
+
accounts. A helper may now take them as a list (`RemainingAccounts`, `remainingAccounts()` at the call): `.length`,
|
|
437
|
+
`.get(i)`, `loadAccount`, as the instruction would.
|
|
438
|
+
- **Error codes as the original computes them.** A collateral leg whose oracle fails with a runtime error (an
|
|
439
|
+
undecodable Pyth account) records `MarginfiError::InternalLogicError as u32`: the variant's index, 0, so nothing is
|
|
440
|
+
recorded; a liability's becomes `InvalidOracleSetup as u32`, 25, which `MarginfiError::from` turns into
|
|
441
|
+
InternalLogicError. The fuzzer found the first.
|
|
442
|
+
- **Large struct values without copies.** The risk engine's result (totals, prices, the premium scratch: 620 bytes)
|
|
443
|
+
was copied four times a pass, which made a health pulse of an empty account cost more than the original's
|
|
444
|
+
(9,859 compute units against 7,560). A struct a function holds itself (a literal, or what a helper returned) now
|
|
445
|
+
passes to helpers in place, a struct literal fills a new local directly, and `fixedArray<T, N>(fill)` may be a
|
|
446
|
+
field's value: 6,450 now, and 2,000–3,000 fewer on every withdrawal and borrow.
|
|
447
|
+
- **The release build's arithmetic.** `fixed` debug-asserts on overflow in `*`, `/` and `from_num`, so the deployed
|
|
448
|
+
build wraps there (a Switchboard value past 2^79 wraps converting to I80F48), while `+`, `-` and `abs` panic
|
|
449
|
+
(overflow checks are on). The circuit breaker's deviation math uses each as the original does.
|
|
450
|
+
- **One account as two parameters.** Anchor leaves `AccountLoader`s out of its duplicate check, so a liquidation
|
|
451
|
+
naming one bank as both banks fails in the handler (SameAssetAndLiabilityBanks), not at entry. `Dup<…>` on both
|
|
452
|
+
banks and both marginfi accounts lifts TypeSOL's own check there; the handler refuses each pair where the original
|
|
453
|
+
does, before anything changes.
|
|
454
|
+
- **Faster Pubkey ordering.** The balances are sorted by bank key after every deposit or close, comparing mostly empty
|
|
455
|
+
(all-zero) keys. Comparing eight bytes at a time instead of one cut a balance close from 6,610 to 1,865 compute
|
|
456
|
+
units and a deposit from 9,712 to 5,271. Every program that orders Pubkeys or hashes gains from it.
|
|
457
|
+
|
|
458
|
+
## How it is checked
|
|
459
|
+
|
|
460
|
+
[`showcase/test/marginfi.test.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/test/marginfi.test.ts) loads
|
|
461
|
+
the binary dumped from mainnet on 2026-11-01 (sha256 in
|
|
462
|
+
[`test/programs/SOURCES.md`](https://github.com/typesol-lang/typesol/blob/main/test/programs/SOURCES.md)), cut where the
|
|
463
|
+
ELF ends. The original runs in one LiteSVM and the port in another, under the same program id and with the same clock.
|
|
464
|
+
For each transaction the test requires the same outcome (success, or the same error down to the code), the same
|
|
465
|
+
lamports, owner and data for every account involved, and the same events byte for byte. The port's IDL must also
|
|
466
|
+
describe every ported instruction as the on-chain IDL does (accounts with their flags, PDA seeds, relations and
|
|
467
|
+
addresses; discriminators; arguments), and their events, so a client generated from either IDL works with both.
|
|
468
|
+
|
|
469
|
+
To reach a state quickly, the tests also write it straight into both ledgers: liabilities and a bank's asset and
|
|
470
|
+
liability shares (a debt to accrue, repay or settle without borrowing it first), e-mode entries, a recorded
|
|
471
|
+
circuit-breaker halt, a frozen bank, the fee state's pause, an account's flags and balances, rate limits.
|
|
472
|
+
|
|
473
|
+
There are 244 transactions in that file, 174 in
|
|
474
|
+
[`showcase/test/marginfi-oracle.test.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/test/marginfi-oracle.test.ts)
|
|
475
|
+
for the oracles, and 1,022 in
|
|
476
|
+
[`showcase/test/marginfi-risk.test.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/test/marginfi-risk.test.ts)
|
|
477
|
+
for withdrawals, borrows, health pulses, liquidation records, bankruptcy, liquidation, receivership, deleverage, flash loans, account, group and fee state administration, bank administration and the risk engine. The last two write Pyth and Switchboard accounts byte for
|
|
478
|
+
byte into both ledgers:
|
|
479
|
+
|
|
480
|
+
- **Fee state and groups (18).** Created; refused with the wrong fee state, the wrong sysvar, a durable nonce; roles
|
|
481
|
+
set, handed over, refused to the old admin; the pause propagated.
|
|
482
|
+
- **Banks and interest (44).** 15 refused configs (each weight rule, isolated banks, the oracle age, five broken
|
|
483
|
+
curves), a durable nonce; banks added with SPL Token and Token-2022 mints, with and without a seed; accrual over
|
|
484
|
+
utilizations from 0.0001% to 200% and periods from one second to a year, then liabilities only, a locked cache, no
|
|
485
|
+
program fees, a halt's seconds left out, a clock behind the bank's (the original panics), a pause and its end.
|
|
486
|
+
- **Configuration (53).** Each operational-state change the fast admin may and may not make; curves and fees; the
|
|
487
|
+
liquidation fees' cap; the circuit breaker refused with a cold, stale or future price and with each bad setting,
|
|
488
|
+
then enabled, and disabled during a halt (the interest accrues first); e-mode entries that fit, repeat, or exceed
|
|
489
|
+
the leverage caps; same-asset fees; a frozen bank; the curve and limit admins; the fees destination.
|
|
490
|
+
- **Accounts and deposits (66).** Accounts opened as keypairs and PDAs (taken, a registered and an unregistered
|
|
491
|
+
third-party id called directly, the wrong address); deposits refused to another signer, into the wrong vault, past
|
|
492
|
+
the user's tokens or the limit, from a frozen, disabled or receivership account, into a paused, reduce-only, killed,
|
|
493
|
+
uninitialized, tokenless or halted bank, as a repayment, into a staked account, with no slot left; deposits capped
|
|
494
|
+
at the limit, with no limit, after interest, with a stale premium written off, under rate limits; the governance
|
|
495
|
+
admin into a frozen account and a keeper during a rebalance (Marginfi lets both through; the token program then
|
|
496
|
+
refuses, the tokens not being theirs); Token-2022 deposits without, with another and with a
|
|
497
|
+
non-mint as the mint, and with a 1.5% transfer fee at five amounts; balances closed with assets, as dust, twice;
|
|
498
|
+
accounts closed with a balance, frozen, with an order, by another signer, and closed.
|
|
499
|
+
- **Repayments and fees (63).** Repayments in part and in full, more than owed, by another signer, into the wrong
|
|
500
|
+
vault, after interest, leaving dust shares, of a closed or missing balance, of an asset balance; from a disabled,
|
|
501
|
+
order-execution, receivership (by a liquidator and by the owner) and frozen account; into paused, reduce-only,
|
|
502
|
+
killed and circuit-broken banks; while the protocol is paused, and deleveraging; with a premium booked and settled
|
|
503
|
+
in part, past it and in full; tokenless by the risk admin and by the owner; Token-2022 with a transfer fee. Fees
|
|
504
|
+
accrued, collected to the wrong account, collected, again with nothing owed, with more owed than the vault holds,
|
|
505
|
+
with a negative balance (the original asserts); withdrawn by the admin and another signer, past the vault, with a
|
|
506
|
+
durable nonce; the insurance vault likewise; the permissionless withdrawal with no destination set, to another
|
|
507
|
+
account, in part and capped at the vault.
|
|
508
|
+
|
|
509
|
+
- **Oracles (174).** Feeds set by another signer, on another group's bank, with the wrong sysvar or a durable nonce,
|
|
510
|
+
on a frozen bank (a panic), with setup bytes past 28 and the deprecated ones (panics), and each setup that belongs
|
|
511
|
+
to another instruction; Pyth with no, two and the wrong account, too short, with the wrong discriminator, not
|
|
512
|
+
Borsh-decodable (four ways), Partial and stale (accepted here); Switchboard with the wrong owner, too short, the
|
|
513
|
+
wrong discriminator, longer than needed; venue, mSOL and LST setups by account count and asset tag; a staked bank;
|
|
514
|
+
same-asset e-mode. Fixed prices refused (signer, group, frozen, same-asset, setup, negative, SOL and staked banks,
|
|
515
|
+
an extra account), set, zero; PT prices by count and range. Pulses with no oracle, the wrong accounts, stale, Partial
|
|
516
|
+
and future Pyth updates, the confidence at, past and under the bank's maximum, exponents from −24 to 100 (panics past
|
|
517
|
+
±23), an overflowing price, negative prices; Switchboard stale, cents, negative, past 2^79 (wrapped) and at i128's
|
|
518
|
+
maximum, with confidence and capped; fixed prices, negative in raw state; with interest to accrue, while paused, with
|
|
519
|
+
a locked cache. The circuit breaker: off, enabled, clean moves pulling the reference, slot and publication dedup, a
|
|
520
|
+
tier-1 trip, a halt, an escalation, its expiry (the cleared event), three tier-3 trips breaking the bank; a long
|
|
521
|
+
window walked up and down with its anchor creeping after it ran out, a reference at the floor reseeded, a tier past
|
|
522
|
+
3 in raw state (a panic).
|
|
523
|
+
|
|
524
|
+
- **Withdrawals, borrows, health pulses, liquidation records, bankruptcy, liquidation, receivership, deleverage, flash loans, account, group and fee state administration, bank administration and the risk engine (1,022, with the deposits they start from).** Part of a deposit, more than it, from a bank without a balance, by
|
|
525
|
+
another signer, to the wrong mint, from disabled and frozen accounts, paused and reduce-only banks; the health
|
|
526
|
+
accounts left out, short an oracle, out of order, with extras; healthy and unhealthy after; a stale liability
|
|
527
|
+
oracle (fails) and a stale collateral oracle (skipped, recorded), an undecodable collateral oracle (skipped,
|
|
528
|
+
nothing recorded) and liability oracle (InternalLogicError), an EMA past its confidence cap; all of it, again, of a
|
|
529
|
+
liability. An isolated liability beside another; e-mode lifting a collateral weight; the deposit cap's discount; a
|
|
530
|
+
reduce-only collateral bank; the breaker's gate on a price jump, a halted bank with and without debt; a bank's
|
|
531
|
+
hourly limit and the group's daily limit (and the bank missing from the accounts); receivership by a liquidator,
|
|
532
|
+
without a price, at a zero price, at a zero weight; deleverage alone and within and past the day's limit; a
|
|
533
|
+
tokenless bank's remainder; the liquidation tag cleared; premium rates from the collateral mix, projected into
|
|
534
|
+
health, ratcheted on a stale leg, written off; an account with 16 positions (40 accounts in the transaction), healthy
|
|
535
|
+
and not; in a flash loan (no check, the cache reset); Token-2022 with a transfer fee, without the mint, all of it.
|
|
536
|
+
Borrows that fit and one that does not, without health accounts, by another signer, against the account's own
|
|
537
|
+
deposit; from disabled, receivership and frozen accounts, paused, reduce-only, killed and tokenless banks; past the
|
|
538
|
+
borrow limit and the vault; dust shares; an isolated liability and another; origination fees, split with the
|
|
539
|
+
program; the group's limit within, past, and with a price of 0; a premium-active debt, then with a stale collateral
|
|
540
|
+
oracle; the protocol paused; Token-2022. Health pulses of an empty account, a healthy one, one short at Initial but
|
|
541
|
+
not at Maintenance, a liquidatable one, one healthy again (its tag cleared), a bankrupt one; with a stale collateral
|
|
542
|
+
oracle, then a stale liability oracle; without accounts, short an oracle; with isolated debt, in a flash loan, idle
|
|
543
|
+
for 45 days, with premium-active debt. Tags of a healthy account, a liquidatable one, one tagged already, one
|
|
544
|
+
healthy again; without accounts, disabled, the protocol paused. Records initialized, again, closed to another
|
|
545
|
+
payer, used lately, with a receiver set, in receivership, after 61 idle days, initialized after a close. Bankruptcy
|
|
546
|
+
by someone who is not the admin, of a bank the account owes nothing, of an account still solvent, in receivership,
|
|
547
|
+
without its health accounts; the insurance covering part of the debt, the bank disabled after, a permissionless
|
|
548
|
+
bank fully covered, a debt past every deposit (the bank killed); in a Token-2022 bank with a transfer fee, and
|
|
549
|
+
without its mint. Liquidations of part of a collateral, a tagged account's (a little, then a quarter of its debt),
|
|
550
|
+
just enough and one too many (healthy after), a fixed-price debt, a Token-2022 debt and one without its mint, by a
|
|
551
|
+
liquidator owing a premium in the asset bank, by one without collateral of its own, by one in a flash loan (a
|
|
552
|
+
premium-active debt raised to its tag's highest rate), by the risk admin through a halted bank; refused: a zero
|
|
553
|
+
amount, one bank as both, past the collateral, a bank the account owes nothing, a healthy account, the liquidatee's
|
|
554
|
+
or the liquidator's accounts left out or miscounted, another signer, the liquidatee as its own liquidator, either
|
|
555
|
+
in receivership, the liquidatee in a flash loan, a circuit-broken bank,
|
|
556
|
+
the protocol paused.
|
|
557
|
+
Receiverships: seizing and repaying, again, seizing without repaying, too high a premium, repaying only, nothing
|
|
558
|
+
in between, a separate fee payer, a close-out under $5, a tagged account's grown premium; refused: the end
|
|
559
|
+
missing, an instruction before the start, two starts, a borrow in between, a bank not writable, the end by
|
|
560
|
+
someone else or alone, another account's record, a healthy account, a circuit-broken bank. Deleverages of a
|
|
561
|
+
healthy account, within the day's limit; refused: health falling, past the limit, another signer, the end by
|
|
562
|
+
someone else or alone, a durable nonce. The limit set (not by an admin, zero) and the flow admin's updates (by
|
|
563
|
+
someone else, empty, slots reversed, in the future, stale, out of sequence, an old slot, past the limit, in order,
|
|
564
|
+
a day later). Tokenless repayments forced complete (by someone else, not allowed, allowed) and balances purged
|
|
565
|
+
(before that, by someone else, none there, owing, a deposit). Flash loans with nothing in between, borrowing past
|
|
566
|
+
the limit and repaying it all, borrowing within it; refused at the end: kept past the limit, the health accounts
|
|
567
|
+
left out; refused at the start: the end index at another instruction, at the start, past the transaction, no end,
|
|
568
|
+
another signer, an end naming another account, an end alone, a second start, a frozen account. Freezing (by
|
|
569
|
+
someone else, unfreezing by the admin, freezing, a durable nonce, unfreezing by the governance admin); the
|
|
570
|
+
emissions destination (frozen, by the authority, by someone else); indexer flags (two accounts, one read-only, a
|
|
571
|
+
bank, none); transfers (by someone else, to the wrong fee wallet, in a flash loan, with balances, again, to a PDA,
|
|
572
|
+
with a third-party id outside its program, with an open id); closes (active lately, the wrong wallet, with a
|
|
573
|
+
balance, a rebalance fee pool left, idle 61 days). The group's program fees (by someone else, off, on), the premium
|
|
574
|
+
wallet; pauses (by someone else, an unpause unpaused, a pause, an early permissionless unpause, extended, a third,
|
|
575
|
+
a fourth in a day, an unpause by someone else and by the admin, the next day, expired, again); the governance admin
|
|
576
|
+
(to nobody, by someone else, handed over and back, the first by the admin); rate limits for a bank and the group
|
|
577
|
+
(by someone else, past i64, set, off); the flow admin's updates (by someone else, empty, slots reversed, in the
|
|
578
|
+
future, out of sequence, an inflow past i64, an outflow, an old slot, past the hourly limit, an inflow then an
|
|
579
|
+
outflow, stale); the premium matrix (by someone else, an empty tag, past the highest rate, three pairs in sorted
|
|
580
|
+
places, a new rate, removals, one already gone); the fee state edited (by someone else, nothing, every field, by
|
|
581
|
+
the new admin); governance (by someone else, roles, a leverage under 1 and over 100, one cap, initial at
|
|
582
|
+
maintenance, caps, same-asset caps alone, reversed and set, a new admin). E-mode entries (by someone else, out of
|
|
583
|
+
order, an initial weight over maintenance, a tag twice, past the caps, none, one) and their copy; premium tags (by
|
|
584
|
+
someone else, on, on again, off with its warning, off again); the breaker cleared (by someone else, by the admin,
|
|
585
|
+
reseeding); backfills (the wrong mint, nothing, another bank's seed, its own, a Token-2022 mint); closes (by someone
|
|
586
|
+
else, with deposits, forced, not made to close, forced, an empty bank); the governance admin's bank settings (by
|
|
587
|
+
someone else, paused, weights, an initial weight over maintenance, isolated with weights and without, back to
|
|
588
|
+
Operational, tokenless, frozen, ignored while frozen); premium sweeps (no premium wallet, someone else's account, a
|
|
589
|
+
fraction left, only the fraction, more than the vault holds); super-admin moves (by someone else, on the mainnet
|
|
590
|
+
build).
|
|
591
|
+
|
|
592
|
+
Besides these, [`showcase/test/fuzz-marginfi.test.ts`](https://github.com/typesol-lang/typesol/blob/main/showcase/test/fuzz-marginfi.test.ts)
|
|
593
|
+
sends random sequences of the same instructions: random bank configs and curves (most valid, some broken in one
|
|
594
|
+
way), fees, balances across scales, clock jumps, frozen banks, circuit-breaker settings and halts, accounts opened and
|
|
595
|
+
closed, deposits into SPL Token, Token-2022 and transfer-fee banks at every scale, balances closed after being written
|
|
596
|
+
down to dust, liabilities written in and repaid in part or in full (premiums, tokenless banks), fees collected and
|
|
597
|
+
withdrawn, account flags, wrong signers; oracles set (mostly the bank's own Pyth or Switchboard account, sometimes
|
|
598
|
+
the wrong one, count or setup), fixed prices, and pulses over Pyth and Switchboard accounts rewritten each time (a
|
|
599
|
+
random walk with jumps, random confidence, exponents and ages, now and then a broken account), the slot moving on so
|
|
600
|
+
the circuit breaker counts them; withdrawals of part of a deposit or all of it over those prices, the health
|
|
601
|
+
accounts as a client sends them or now and then short, out of order or with extras, account flags (disabled,
|
|
602
|
+
receivership, deleverage, frozen, flash loan) and liquidation tags; borrows with origination and program fees; health
|
|
603
|
+
pulses of any account; liquidation tags and bankruptcies of any account (mostly a borrower's in its own bank, so some
|
|
604
|
+
succeed), the insurance vault's balance rewritten now and then; liquidations of any account by any account, or of a
|
|
605
|
+
fresh account holding collateral against a debt written in, with the accounts now and then miscounted;
|
|
606
|
+
receiverships and deleverages of any account (its record created when missing) around a repayment or nothing, the
|
|
607
|
+
receiver signing or not, the accounts now and then short; flash loans around a borrow of any amount or nothing, the
|
|
608
|
+
end index now and then wrong. The keys come from the seed too (the order of keys decides how balances sort), so a seed
|
|
609
|
+
reproduces a run exactly.
|
|
610
|
+
Every step must match. Inputs the original panics on (a negative fee rate trips its asserts) only have to fail in the
|
|
611
|
+
port too. Each run takes a new seed, CI's included; `FUZZ_SEED=<seed>` reproduces one, `FUZZ_STEPS=<n>` lengthens it.
|
|
612
|
+
|
|
613
|
+
## Differences
|
|
614
|
+
|
|
615
|
+
- **A flash loan's end index past the transaction.** The original fails reading that instruction with
|
|
616
|
+
`InvalidArgument`, a runtime error without a custom code; the port with 5104. The tests check that both fail.
|
|
617
|
+
- **This program's id in the receivership checks.** The original compares the transaction's instructions with its
|
|
618
|
+
mainnet id; the port with the id it runs under. At `MFv2hWf31Z9kbCa1snEPYctwafyhdvnV7FZnsebVacA` they are the same.
|
|
619
|
+
- **The liquidatee as its own liquidator.** The original fails loading the second account (`AccountBorrowFailed`, a
|
|
620
|
+
runtime error without a custom code), after the checks before it; the port fails at the same point with 2040.
|
|
621
|
+
The tests check that both fail.
|
|
622
|
+
- **Logs.** The original writes about 160 `msg!` lines (configs echoed when a bank is added, values before and after a
|
|
623
|
+
change). The port writes only the `WARN` lines, which the tests compare. Events, which indexers read, are the same.
|
|
624
|
+
- **Panics.** Where the original panics (an assert on a negative rate, a clock behind the bank's last update, an
|
|
625
|
+
unknown curve type in an account, an oracle setup byte past 28, a Pyth exponent past ±23), the port fails with a
|
|
626
|
+
numbered error. The tests check that both fail.
|
|
627
|
+
- **Undecodable Pyth accounts.** Where the original fails with `BorshIoError`, a runtime error without a custom code
|
|
628
|
+
(setting or pulsing a feed, a withdrawal's up-front price), the port fails with error 1. The tests check that both
|
|
629
|
+
fail. Inside the risk engine both record and re-raise it alike (see above).
|
|
630
|
+
- **Health accounts.** A remaining account that is not a bank of the program fails the original's `AccountLoader`
|
|
631
|
+
with the same codes as the port's (3007, 3001, 3002); one owned by the program, with a bank's discriminator but
|
|
632
|
+
too short, panics in the original and fails with 3003 in the port.
|
|
633
|
+
- **Undecodable stake accounts.** Where the original fails with `BorshIoError` on a staked pool's stake account that
|
|
634
|
+
does not decode (a runtime error without a custom code), the port fails with its own error; both fail.
|
|
635
|
+
- **Token-2022 in a bad-debt claim.** `drift_claim_bad_debt`'s claim mint and distributor vault are SPL Token accounts
|
|
636
|
+
in the original (3007 for Token-2022 ones); the port takes either token program there.
|
|
637
|
+
- **One account for two unchecked ones.** Anchor does not refuse an `UncheckedAccount` passed twice as writable; TypeSOL
|
|
638
|
+
refuses any writable account passed twice (2040) unless the pair is `Dup<…>`. `drift_claim_bad_debt`'s two token
|
|
639
|
+
accounts are, so its own check answers as the original's does (6311); elsewhere such a transaction fails earlier in
|
|
640
|
+
the port than in the original.
|
|
641
|
+
- **AccountBorrowFailed.** Where the original's `solend_withdraw` fails borrowing a bank it holds (see above), the port
|
|
642
|
+
fails with error 12. The tests, the fuzz's included, check that the original fails that way and the port with 12 (the
|
|
643
|
+
only refused venue transaction not held to the original's code).
|
|
644
|
+
|
|
645
|
+
## Cost
|
|
646
|
+
|
|
647
|
+
Compute units per transaction, mainnet original against the port, from one run of the differential test:
|
|
648
|
+
|
|
649
|
+
| Instruction | Marginfi (mainnet) | TypeSOL | |
|
|
650
|
+
| --- | ---: | ---: | ---: |
|
|
651
|
+
| `init_global_fee_state` | 7,116 | 2,310 | −68% |
|
|
652
|
+
| `marginfi_group_initialize` | 27,404 | 7,162 | −74% |
|
|
653
|
+
| `marginfi_group_configure`, five roles | 22,917 | 1,232 | −95% |
|
|
654
|
+
| `propagate_fee_state` | 3,821 | 776 | −80% |
|
|
655
|
+
| `lending_pool_add_bank` (SPL Token) | 97,333 | 20,072 | −79% |
|
|
656
|
+
| `lending_pool_add_bank_with_seed` (Token-2022) | 100,585 | 29,973 | −70% |
|
|
657
|
+
| `lending_pool_accrue_bank_interest`, an empty bank | 4,002 | 1,689 | −58% |
|
|
658
|
+
| `lending_pool_accrue_bank_interest`, 25% utilization over a minute | 40,135 | 18,696 | −53% |
|
|
659
|
+
| `lending_pool_accrue_bank_interest`, 80% utilization over a year | 41,642 | 22,733 | −45% |
|
|
660
|
+
| `lending_pool_accrue_bank_interest`, 98,765,432,101 / 123,456,789,012 | 42,657 | 22,853 | −46% |
|
|
661
|
+
| `lending_pool_configure_bank`, a new curve | 13,716 | 3,389 | −75% |
|
|
662
|
+
| `lending_pool_configure_bank`, circuit breaker on | 12,743 | 3,391 | −73% |
|
|
663
|
+
| `lending_pool_configure_bank`, circuit breaker off during a halt (accrues first) | 33,226 | 15,453 | −53% |
|
|
664
|
+
| `lending_pool_configure_bank`, checked against an e-mode entry | 17,282 | 5,463 | −68% |
|
|
665
|
+
| `lending_pool_configure_bank_interest_only`, every field | 25,668 | 847 | −97% |
|
|
666
|
+
| `lending_pool_configure_bank_limits_only` | 9,043 | 461 | −95% |
|
|
667
|
+
| `lending_pool_update_fees_destination_account` | 8,926 | 479 | −95% |
|
|
668
|
+
| `marginfi_account_initialize` | 6,550 | 2,603 | −60% |
|
|
669
|
+
| `marginfi_account_initialize_pda` | 8,670 | 3,176 | −63% |
|
|
670
|
+
| `lending_account_deposit`, a new balance | 15,739 | 7,026 | −55% |
|
|
671
|
+
| `lending_account_deposit`, interest accrued first | 51,033 | 25,544 | −50% |
|
|
672
|
+
| `lending_account_deposit`, Token-2022 with a transfer fee | 18,990 | 9,525 | −50% |
|
|
673
|
+
| `lending_account_deposit`, up to the deposit limit | 15,170 | 7,523 | −50% |
|
|
674
|
+
| `lending_account_close_balance`, dust to the insurance fund | 20,236 | 9,349 | −54% |
|
|
675
|
+
| `lending_account_close_balance`, an empty balance | 6,677 | 3,055 | −54% |
|
|
676
|
+
| `marginfi_account_close` | 7,734 | 3,383 | −56% |
|
|
677
|
+
| `lending_account_repay`, part | 50,404 | 26,697 | −47% |
|
|
678
|
+
| `lending_account_repay`, all (rounded up, the balance closed) | 10,997 | 5,142 | −53% |
|
|
679
|
+
| `lending_account_repay`, part, with a premium settled first | 52,678 | 31,831 | −40% |
|
|
680
|
+
| `lending_account_repay`, tokenless, by the risk admin | 25,228 | 12,684 | −50% |
|
|
681
|
+
| `lending_account_repay`, Token-2022 with a transfer fee | 32,985 | 15,516 | −53% |
|
|
682
|
+
| `lending_pool_collect_bank_fees` | 29,598 | 13,619 | −54% |
|
|
683
|
+
| `lending_pool_withdraw_fees` | 13,558 | 2,493 | −82% |
|
|
684
|
+
| `lending_pool_withdraw_insurance` | 13,536 | 2,527 | −81% |
|
|
685
|
+
| `lending_pool_withdraw_fees_permissionless` | 10,773 | 2,412 | −78% |
|
|
686
|
+
| `lending_pool_configure_bank_oracle`, Pyth | 7,337 | 1,215 | −83% |
|
|
687
|
+
| `lending_pool_configure_bank_oracle`, Switchboard | 7,258 | 1,215 | −83% |
|
|
688
|
+
| `lending_pool_set_oracle_price` | 4,644 | 1,133 | −76% |
|
|
689
|
+
| `lending_pool_pulse_bank_price_cache`, Pyth | 14,147 | 5,152 | −64% |
|
|
690
|
+
| `lending_pool_pulse_bank_price_cache`, Switchboard | 7,755 | 2,934 | −62% |
|
|
691
|
+
| `lending_pool_pulse_bank_price_cache`, fixed | 3,815 | 997 | −74% |
|
|
692
|
+
| `lending_pool_pulse_bank_price_cache`, an hour of interest first | 41,299 | 19,318 | −53% |
|
|
693
|
+
| `lending_pool_pulse_bank_price_cache`, the breaker's reference moved | 27,267 | 10,648 | −61% |
|
|
694
|
+
| `lending_pool_pulse_bank_price_cache`, a tier-3 trip breaking the bank | 24,401 | 9,115 | −63% |
|
|
695
|
+
| `lending_account_withdraw`, part, no debt | 52,841 | 28,814 | −45% |
|
|
696
|
+
| `lending_account_withdraw`, healthy after, against a USDC debt | 46,485 | 26,504 | −43% |
|
|
697
|
+
| `lending_account_withdraw`, a stale collateral oracle skipped | 43,441 | 25,122 | −42% |
|
|
698
|
+
| `lending_account_withdraw`, all of it | 41,512 | 24,821 | −40% |
|
|
699
|
+
| `lending_account_withdraw`, e-mode lifting the collateral | 46,182 | 26,463 | −43% |
|
|
700
|
+
| `lending_account_withdraw`, premium rates from the collateral mix | 63,341 | 37,898 | −40% |
|
|
701
|
+
| `lending_account_withdraw`, Token-2022 with a transfer fee | 53,306 | 27,801 | −48% |
|
|
702
|
+
| `lending_account_withdraw`, in receivership, by a liquidator | 39,987 | 16,590 | −59% |
|
|
703
|
+
| `lending_account_withdraw`, 16 positions, the tag cleared | 538,319 | 296,477 | −45% |
|
|
704
|
+
| `lending_account_borrow` | 71,645 | 37,550 | −48% |
|
|
705
|
+
| `lending_account_borrow`, an isolated bank | 71,024 | 36,908 | −48% |
|
|
706
|
+
| `lending_account_borrow`, with an origination fee | 75,830 | 42,111 | −44% |
|
|
707
|
+
| `lending_account_borrow`, premium-active debt | 106,636 | 58,252 | −45% |
|
|
708
|
+
| `lending_account_borrow`, Token-2022 with a transfer fee | 77,107 | 41,398 | −46% |
|
|
709
|
+
| `lending_account_pulse_health`, an empty account | 7,560 | 6,302 | −17% |
|
|
710
|
+
| `lending_account_pulse_health`, healthy | 81,619 | 46,772 | −43% |
|
|
711
|
+
| `lending_account_pulse_health`, liquidatable | 74,068 | 46,374 | −37% |
|
|
712
|
+
| `lending_account_pulse_health`, bankrupt | 65,817 | 39,377 | −40% |
|
|
713
|
+
| `lending_account_pulse_health`, a stale collateral oracle | 36,258 | 23,831 | −34% |
|
|
714
|
+
| `marginfi_account_tag_liq_record`, liquidatable | 25,168 | 13,904 | −45% |
|
|
715
|
+
| `marginfi_account_init_liq_record` | 10,318 | 2,855 | −72% |
|
|
716
|
+
| `marginfi_account_close_liq_record` | 2,444 | 636 | −74% |
|
|
717
|
+
| `lending_pool_handle_bankruptcy`, insurance covering part | 91,747 | 48,664 | −47% |
|
|
718
|
+
| `lending_pool_handle_bankruptcy`, permissionless, covered | 69,730 | 33,101 | −53% |
|
|
719
|
+
| `lending_pool_handle_bankruptcy`, past the deposits | 35,143 | 19,708 | −44% |
|
|
720
|
+
| `lending_pool_handle_bankruptcy`, Token-2022 with a transfer fee | 97,583 | 50,868 | −48% |
|
|
721
|
+
| `lending_account_liquidate`, part of a collateral | 194,785 | 122,645 | −37% |
|
|
722
|
+
| `lending_account_liquidate`, a liquidator owing a premium | 222,725 | 138,807 | −38% |
|
|
723
|
+
| `lending_account_liquidate`, a fixed-price debt | 225,420 | 139,274 | −38% |
|
|
724
|
+
| `lending_account_liquidate`, Token-2022 | 199,451 | 125,412 | −37% |
|
|
725
|
+
| a receivership: start, withdraw 1 SOL, repay 140 USDC, end | 149,945 | 95,527 | −36% |
|
|
726
|
+
| a receivership: start, end | 87,094 | 61,272 | −30% |
|
|
727
|
+
| a receivership: a close-out under $5 | 130,094 | 78,290 | −40% |
|
|
728
|
+
| a deleverage: start, withdraw 1 SOL, repay 150 USDC, end | 160,288 | 94,646 | −41% |
|
|
729
|
+
| a flash loan: start, borrow past the limit, repay it all, end | 75,214 | 35,898 | −52% |
|
|
730
|
+
| a flash loan: start, end | 18,114 | 10,818 | −40% |
|
|
731
|
+
| `marginfi_account_set_freeze` | 5,368 | 1,237 | −77% |
|
|
732
|
+
| `transfer_to_new_account`, with balances | 12,906 | 7,259 | −44% |
|
|
733
|
+
| `transfer_to_new_account_pda` | 15,008 | 7,831 | −48% |
|
|
734
|
+
| `admin_close_account` | 5,755 | 3,591 | −38% |
|
|
735
|
+
| `panic_pause` | 7,188 | 863 | −88% |
|
|
736
|
+
| `update_group_rate_limiter`, an outflow | 5,152 | 1,397 | −73% |
|
|
737
|
+
| `lending_pool_configure_group_premium`, a new pair | 5,558 | 1,155 | −79% |
|
|
738
|
+
| `lending_pool_configure_bank_emode`, three entries sorted | 79,762 | 10,384 | −87% |
|
|
739
|
+
| `lending_pool_close_bank` | 4,530 | 2,498 | −45% |
|
|
740
|
+
| `lending_pool_configure_bank_gov`, weights | 42,109 | 11,196 | −73% |
|
|
741
|
+
| `lending_pool_collect_bank_premium_fees` | 18,080 | 7,158 | −60% |
|
|
742
|
+
| `lending_pool_emissions_deposit` | 12,486 | 5,070 | −59% |
|
|
743
|
+
| `lending_pool_init_same_asset_emode_registry` | 9,301 | 2,314 | −75% |
|
|
744
|
+
| `lending_pool_set_bank_same_asset_emode_eligibility` | 7,346 | 1,677 | −77% |
|
|
745
|
+
| `init_bank_metadata` | 8,789 | 2,541 | −71% |
|
|
746
|
+
| `write_bank_metadata`, ticker and description | 5,354 | 1,988 | −63% |
|
|
747
|
+
| `write_bank_metadata_pre_init` | 8,719 | 2,764 | −68% |
|
|
748
|
+
| `marginfi_account_place_order`, stop loss | 16,332 | 6,273 | −62% |
|
|
749
|
+
| `marginfi_account_close_order` | 4,142 | 1,355 | −67% |
|
|
750
|
+
| `marginfi_account_set_keeper_close_flags`, one bank | 3,094 | 1,083 | −65% |
|
|
751
|
+
| `marginfi_account_keeper_close_order` | 2,709 | 1,403 | −48% |
|
|
752
|
+
| an order executed (start, withdraw, repay, end), stop loss | 158,349 | 70,948 | −55% |
|
|
753
|
+
| `marginfi_account_place_rebalance_order` | 10,820 | 3,570 | −67% |
|
|
754
|
+
| `marginfi_account_update_rebalance_order` | 3,980 | 1,610 | −60% |
|
|
755
|
+
| `marginfi_account_top_up_rebalance_fee_pool` | 6,498 | 2,970 | −54% |
|
|
756
|
+
| a rebalance (start, withdraw, deposit, end), a tip escrowed | 270,773 | 116,319 | −57% |
|
|
757
|
+
| `marginfi_account_settle_rebalance_tip`, paid | 72,189 | 36,058 | −50% |
|
|
758
|
+
| `lending_pool_resize_bank_account` | 4,711 | 2,807 | −40% |
|
|
759
|
+
| `monitor_archive_upsert_batch`, two mints | 2,741 | 973 | −65% |
|
|
760
|
+
| `init_staked_settings` | 17,865 | 2,786 | −84% |
|
|
761
|
+
| `lending_pool_add_bank_permissionless` | 77,694 | 19,023 | −76% |
|
|
762
|
+
| `lending_pool_configure_bank_oracle_scope` | 9,597 | 1,225 | −87% |
|
|
763
|
+
| `lending_pool_add_bank_solend` | 82,881 | 19,012 | −77% |
|
|
764
|
+
| `solend_init_obligation` | 88,717 | 66,142 | −25% |
|
|
765
|
+
| `solend_deposit` | 100,480 | 73,502 | −27% |
|
|
766
|
+
| `solend_withdraw` | 191,792 | 137,009 | −29% |
|
|
767
|
+
| `lending_pool_add_bank_kamino` | 77,023 | 17,759 | −77% |
|
|
768
|
+
| `kamino_init_obligation` (with a farm) | 206,172 | 169,852 | −18% |
|
|
769
|
+
| `kamino_deposit` | 133,066 | 106,321 | −20% |
|
|
770
|
+
| `kamino_withdraw` | 181,565 | 125,229 | −31% |
|
|
771
|
+
| `propagate_kamino_market_emergency` | 2,327 | 366 | −84% |
|
|
772
|
+
| `kamino_harvest_reward` | 120,337 | 101,049 | −16% |
|
|
773
|
+
| `lending_pool_add_bank_drift` | 76,034 | 17,489 | −77% |
|
|
774
|
+
| `drift_init_user` | 106,471 | 83,160 | −22% |
|
|
775
|
+
| `drift_deposit` | 76,268 | 57,301 | −25% |
|
|
776
|
+
| `drift_withdraw` (with a debt) | 157,716 | 113,786 | −28% |
|
|
777
|
+
| `drift_harvest_reward` | 78,993 | 58,487 | −26% |
|
|
778
|
+
| `drift_claim_bad_debt` | 89,488 | 66,105 | −26% |
|
|
779
|
+
| `lending_pool_add_bank_juplend` | 81,844 | 20,279 | −75% |
|
|
780
|
+
| `juplend_init_position` | 71,441 | 49,524 | −31% |
|
|
781
|
+
| `juplend_deposit` | 90,443 | 62,075 | −31% |
|
|
782
|
+
| `juplend_withdraw` (with a debt) | 141,752 | 91,212 | −36% |
|
|
783
|
+
|
|
784
|
+
Across the 125 transactions of the first file that succeed, the port uses 40–97% fewer compute units; across the 118
|
|
785
|
+
refused ones, 56–93% fewer. Repayments with a premium and accrual, nearly all I80F48 arithmetic, save least (from
|
|
786
|
+
40%). In the oracle file, the 72 that succeed use 47–83% fewer; the 76 refused ones 46–92% fewer. In the risk file,
|
|
787
|
+
the withdrawals that succeed use 38–63% fewer, the borrows 43–48%, the health pulses 17–64% (the least: an empty
|
|
788
|
+
account, where the original does little), tags 44–45%, records 69–74%, bankruptcies 44–53%, liquidations 35–39%,
|
|
789
|
+
receiverships 30–40%, deleverages 41–42% flash loans 40–52% (whole transactions, the withdrawals and repayments in them included), account administration
|
|
790
|
+
38–86%, group and fee state administration 68–97%, bank administration 45–96%, emissions 53–60%, bank metadata 50–90%, orders 48–72%, executions 55–57% (whole transactions), rebalance orders 50–67%, rebalances 56–57% (whole transactions), monitor snapshots 28–80% (the least: 20 snapshots, byte by byte), staked SOL and Scope 75–87%;
|
|
791
|
+
refused withdrawals and borrows 41–92% fewer, refused liquidations 46–90%. A health check is mostly I80F48 products
|
|
792
|
+
and quotients, like accrual. The rates' u32 encodings (a curve point, a fee, a premium rate) decode in 64-bit
|
|
793
|
+
arithmetic: `(x << 48) / (2^32 − 1)` is `y + y / (2^32 − 1)` for `y = x << 16`, with no 128-bit division.
|
|
794
|
+
|
|
795
|
+
The venue banks' instructions save less (16–36%): most of their cost is Solend's, klend's, kfarms', Drift's, the
|
|
796
|
+
distributor's and JupLend's own instructions, which run the same in both; creating a venue bank and propagating an
|
|
797
|
+
emergency, which call none, save 75–84%.
|