@elmntl/jlpd-sdk 0.2.0 → 0.13.5

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.
Files changed (115) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +185 -404
  3. package/dist/common/ata.d.ts +26 -0
  4. package/dist/common/ata.js +48 -0
  5. package/dist/common/buffer.d.ts +15 -0
  6. package/dist/common/buffer.js +118 -0
  7. package/dist/common/connection.d.ts +13 -0
  8. package/dist/common/connection.js +2 -0
  9. package/dist/common/constants.d.ts +14 -0
  10. package/dist/common/constants.js +31 -0
  11. package/dist/common/index.d.ts +6 -0
  12. package/dist/common/index.js +28 -0
  13. package/dist/common/strategy-interface.d.ts +59 -0
  14. package/dist/common/strategy-interface.js +42 -0
  15. package/dist/elemental-lend/accounts.d.ts +103 -0
  16. package/dist/elemental-lend/accounts.js +354 -0
  17. package/dist/elemental-lend/constants.d.ts +25 -0
  18. package/dist/elemental-lend/constants.js +48 -0
  19. package/dist/elemental-lend/index.d.ts +8 -0
  20. package/dist/elemental-lend/index.js +24 -0
  21. package/dist/elemental-lend/instructions.d.ts +104 -0
  22. package/dist/elemental-lend/instructions.js +266 -0
  23. package/dist/elemental-lend/jupiter-lend.d.ts +91 -0
  24. package/dist/elemental-lend/jupiter-lend.js +189 -0
  25. package/dist/elemental-lend/kamino-vault.d.ts +173 -0
  26. package/dist/elemental-lend/kamino-vault.js +483 -0
  27. package/dist/elemental-lend/pda.d.ts +12 -0
  28. package/dist/elemental-lend/pda.js +24 -0
  29. package/dist/elemental-lend/protocol-actions.d.ts +56 -0
  30. package/dist/elemental-lend/protocol-actions.js +244 -0
  31. package/dist/elemental-lend/types.d.ts +113 -0
  32. package/dist/elemental-lend/types.js +2 -0
  33. package/dist/elemental-lend-v2/accounts.d.ts +14 -0
  34. package/dist/elemental-lend-v2/accounts.js +136 -0
  35. package/dist/elemental-lend-v2/adapters.d.ts +22 -0
  36. package/dist/elemental-lend-v2/adapters.js +50 -0
  37. package/dist/elemental-lend-v2/constants.d.ts +48 -0
  38. package/dist/elemental-lend-v2/constants.js +104 -0
  39. package/dist/elemental-lend-v2/index.d.ts +8 -0
  40. package/dist/elemental-lend-v2/index.js +24 -0
  41. package/dist/elemental-lend-v2/instructions.d.ts +96 -0
  42. package/dist/elemental-lend-v2/instructions.js +190 -0
  43. package/dist/elemental-lend-v2/lut.d.ts +20 -0
  44. package/dist/elemental-lend-v2/lut.js +65 -0
  45. package/dist/elemental-lend-v2/pda.d.ts +9 -0
  46. package/dist/elemental-lend-v2/pda.js +27 -0
  47. package/dist/elemental-lend-v2/types.d.ts +105 -0
  48. package/dist/elemental-lend-v2/types.js +2 -0
  49. package/dist/elemental-lend-v2/update-aum.d.ts +29 -0
  50. package/dist/elemental-lend-v2/update-aum.js +82 -0
  51. package/dist/index.d.ts +5 -4199
  52. package/dist/index.js +37 -5187
  53. package/dist/jlpd-strategy/accounts.d.ts +83 -0
  54. package/dist/jlpd-strategy/accounts.js +216 -0
  55. package/dist/jlpd-strategy/adapter.d.ts +81 -0
  56. package/dist/jlpd-strategy/adapter.js +118 -0
  57. package/dist/jlpd-strategy/base-to-base-swap.d.ts +74 -0
  58. package/dist/jlpd-strategy/base-to-base-swap.js +205 -0
  59. package/dist/jlpd-strategy/constants.d.ts +127 -0
  60. package/dist/jlpd-strategy/constants.js +174 -0
  61. package/dist/jlpd-strategy/fluid-view.d.ts +199 -0
  62. package/dist/jlpd-strategy/fluid-view.js +799 -0
  63. package/dist/jlpd-strategy/hedge-derived.d.ts +135 -0
  64. package/dist/jlpd-strategy/hedge-derived.js +231 -0
  65. package/dist/jlpd-strategy/hedge-instructions.d.ts +206 -0
  66. package/dist/jlpd-strategy/hedge-instructions.js +296 -0
  67. package/dist/jlpd-strategy/hedge-state.d.ts +88 -0
  68. package/dist/jlpd-strategy/hedge-state.js +110 -0
  69. package/dist/jlpd-strategy/index.d.ts +17 -0
  70. package/dist/jlpd-strategy/index.js +33 -0
  71. package/dist/jlpd-strategy/instructions.d.ts +159 -0
  72. package/dist/jlpd-strategy/instructions.js +234 -0
  73. package/dist/jlpd-strategy/jlp-borrow.d.ts +63 -0
  74. package/dist/jlpd-strategy/jlp-borrow.js +87 -0
  75. package/dist/jlpd-strategy/jlp-data.d.ts +166 -0
  76. package/dist/jlpd-strategy/jlp-data.js +611 -0
  77. package/dist/jlpd-strategy/jupusd-earn.d.ts +90 -0
  78. package/dist/jlpd-strategy/jupusd-earn.js +166 -0
  79. package/dist/jlpd-strategy/live-jlp-price.d.ts +46 -0
  80. package/dist/jlpd-strategy/live-jlp-price.js +267 -0
  81. package/dist/jlpd-strategy/pda.d.ts +13 -0
  82. package/dist/jlpd-strategy/pda.js +28 -0
  83. package/dist/jlpd-strategy/settle-yield.d.ts +45 -0
  84. package/dist/jlpd-strategy/settle-yield.js +113 -0
  85. package/dist/jlpd-strategy/swap-jlp.d.ts +198 -0
  86. package/dist/jlpd-strategy/swap-jlp.js +586 -0
  87. package/dist/jlpd-strategy/types.d.ts +101 -0
  88. package/dist/jlpd-strategy/types.js +29 -0
  89. package/dist/p-stv-core/accounts.d.ts +152 -0
  90. package/dist/p-stv-core/accounts.js +407 -0
  91. package/dist/p-stv-core/constants.d.ts +138 -0
  92. package/dist/p-stv-core/constants.js +181 -0
  93. package/dist/p-stv-core/events.d.ts +7 -0
  94. package/dist/p-stv-core/events.js +246 -0
  95. package/dist/p-stv-core/index.d.ts +11 -0
  96. package/dist/p-stv-core/index.js +27 -0
  97. package/dist/p-stv-core/instructions.d.ts +637 -0
  98. package/dist/p-stv-core/instructions.js +670 -0
  99. package/dist/p-stv-core/lut.d.ts +41 -0
  100. package/dist/p-stv-core/lut.js +81 -0
  101. package/dist/p-stv-core/pda.d.ts +30 -0
  102. package/dist/p-stv-core/pda.js +65 -0
  103. package/dist/p-stv-core/prices.d.ts +20 -0
  104. package/dist/p-stv-core/prices.js +77 -0
  105. package/dist/p-stv-core/remaining-accounts.d.ts +107 -0
  106. package/dist/p-stv-core/remaining-accounts.js +326 -0
  107. package/dist/p-stv-core/send-tx.d.ts +72 -0
  108. package/dist/p-stv-core/send-tx.js +290 -0
  109. package/dist/p-stv-core/sol-wrap.d.ts +34 -0
  110. package/dist/p-stv-core/sol-wrap.js +74 -0
  111. package/dist/p-stv-core/types.d.ts +361 -0
  112. package/dist/p-stv-core/types.js +2 -0
  113. package/package.json +56 -15
  114. package/dist/index.d.mts +0 -4199
  115. package/dist/index.mjs +0 -5090
@@ -0,0 +1,296 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.HedgeManifestRole = void 0;
7
+ exports.createHedgeSupplyCollateralIx = createHedgeSupplyCollateralIx;
8
+ exports.createHedgeBorrowIx = createHedgeBorrowIx;
9
+ exports.createHedgeRepayIx = createHedgeRepayIx;
10
+ exports.createHedgeWithdrawCollateralIx = createHedgeWithdrawCollateralIx;
11
+ exports.createHedgeSwapIx = createHedgeSwapIx;
12
+ exports.createInitOrUpdateHedgeStateIx = createInitOrUpdateHedgeStateIx;
13
+ const web3_js_1 = require("@solana/web3.js");
14
+ const spl_token_1 = require("@solana/spl-token");
15
+ const bn_js_1 = __importDefault(require("bn.js"));
16
+ const buffer_1 = require("../common/buffer");
17
+ const constants_1 = require("./constants");
18
+ function toBigIntAmount(v) {
19
+ if (typeof v === "bigint")
20
+ return v;
21
+ const asBn = v;
22
+ return typeof asBn.toBigInt === "function" ? asBn.toBigInt() : BigInt(asBn.toString());
23
+ }
24
+ /** Serialize `{ slot_index: u8, amount: u64 }`, Borsh-identical across all four hedge ops. */
25
+ function serializeSlotIndexAmountParams(disc, slotIndex, amount) {
26
+ if (!Number.isInteger(slotIndex) || slotIndex < 0 || slotIndex > 255) {
27
+ throw new RangeError(`slotIndex must be an integer in 0..255, got ${slotIndex}`);
28
+ }
29
+ const data = Buffer.alloc(8 + 1 + 8);
30
+ disc.copy(data, 0);
31
+ data.writeUInt8(slotIndex, 8);
32
+ data.writeBigUInt64LE(toBigIntAmount(amount), 9);
33
+ return data;
34
+ }
35
+ function buildHedgeOpKeys(args) {
36
+ const { manager, config, managerRole, hedgeState, jlpSourceAta, debtAta, jlpMint, debtMint, fluidOracle, borrowPosition, vaultConfig, vaultState, jupLendBorrowProgram = constants_1.JUP_LEND_BORROW_PROGRAM_ID, tokenProgram = spl_token_1.TOKEN_PROGRAM_ID, associatedTokenProgram = spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, systemProgram = web3_js_1.SystemProgram.programId, remainingAccounts = [], } = args;
37
+ return [
38
+ { pubkey: manager, isSigner: true, isWritable: false },
39
+ { pubkey: config, isSigner: false, isWritable: true },
40
+ { pubkey: managerRole, isSigner: false, isWritable: false },
41
+ { pubkey: hedgeState, isSigner: false, isWritable: false },
42
+ { pubkey: jlpSourceAta, isSigner: false, isWritable: true },
43
+ { pubkey: debtAta, isSigner: false, isWritable: true },
44
+ { pubkey: jlpMint, isSigner: false, isWritable: false },
45
+ { pubkey: debtMint, isSigner: false, isWritable: false },
46
+ { pubkey: fluidOracle, isSigner: false, isWritable: false },
47
+ { pubkey: borrowPosition, isSigner: false, isWritable: true },
48
+ { pubkey: vaultConfig, isSigner: false, isWritable: false },
49
+ { pubkey: vaultState, isSigner: false, isWritable: true },
50
+ { pubkey: jupLendBorrowProgram, isSigner: false, isWritable: false },
51
+ { pubkey: tokenProgram, isSigner: false, isWritable: false },
52
+ { pubkey: associatedTokenProgram, isSigner: false, isWritable: false },
53
+ { pubkey: systemProgram, isSigner: false, isWritable: false },
54
+ ...remainingAccounts,
55
+ ];
56
+ }
57
+ /** Build the on-chain `hedge_supply_collateral` instruction. */
58
+ function createHedgeSupplyCollateralIx(args, programId = constants_1.PROGRAM_ID) {
59
+ const data = serializeSlotIndexAmountParams(constants_1.IX_HEDGE_SUPPLY_COLLATERAL, args.slotIndex, args.amount);
60
+ return new web3_js_1.TransactionInstruction({ keys: buildHedgeOpKeys(args), programId, data });
61
+ }
62
+ /** Build the on-chain `hedge_borrow` instruction. */
63
+ function createHedgeBorrowIx(args, programId = constants_1.PROGRAM_ID) {
64
+ const data = serializeSlotIndexAmountParams(constants_1.IX_HEDGE_BORROW, args.slotIndex, args.amount);
65
+ return new web3_js_1.TransactionInstruction({ keys: buildHedgeOpKeys(args), programId, data });
66
+ }
67
+ /** Build the on-chain `hedge_repay` instruction. */
68
+ function createHedgeRepayIx(args, programId = constants_1.PROGRAM_ID) {
69
+ const data = serializeSlotIndexAmountParams(constants_1.IX_HEDGE_REPAY, args.slotIndex, args.amount);
70
+ return new web3_js_1.TransactionInstruction({ keys: buildHedgeOpKeys(args), programId, data });
71
+ }
72
+ /** Build the on-chain `hedge_withdraw_collateral` instruction. */
73
+ function createHedgeWithdrawCollateralIx(args, programId = constants_1.PROGRAM_ID) {
74
+ const data = serializeSlotIndexAmountParams(constants_1.IX_HEDGE_WITHDRAW_COLLATERAL, args.slotIndex, args.amount);
75
+ return new web3_js_1.TransactionInstruction({ keys: buildHedgeOpKeys(args), programId, data });
76
+ }
77
+ // ---------------------------------------------------------------------------
78
+ // hedge_swap — the general, RISK-INCREASING hedge swap between two `HedgeState` manifest ATAs
79
+ // via Jupiter. BLOCKED while the hedge is disabled (unlike the risk-decreasing hedge ops above).
80
+ //
81
+ // Account order verified against `instructions/hedge/hedge_swap.rs`'s `#[derive(Accounts)]
82
+ // HedgeSwap` struct (post-B0): the B0 change inserted a NEW fixed account, `jupsol_rate`, at
83
+ // position 13 (0-indexed 12) between `lending_dst` and `jupiter_program` — `jupiter_program` is
84
+ // therefore now position 14 (0-indexed 13), not 13. NOTE: `target/idl/jlpd_strategy.json` has NOT
85
+ // been regenerated since B0 landed — its `hedge_swap.accounts` list is stale (13 entries, missing
86
+ // `jupsol_rate`); the discriminator and `HedgeSwapParams`/`HedgeManifestRole` type entries in that
87
+ // same IDL DO match the Rust source (params/enum are unaffected by B0 — only the account list
88
+ // changed), so this builder trusts the Rust struct for account order and the IDL for the
89
+ // discriminator + param shape.
90
+ //
91
+ // Fixed accounts (14):
92
+ // 0. manager [signer]
93
+ // 1. config [] JLPD Config PDA (read-only — this ix never writes it)
94
+ // 2. manager_role [] ManagerRole PDA
95
+ // 3. hedge_state [writable] writes swap_notional_since_settle
96
+ // 4. src_ata [writable] == manifest_role_ata(hedge_state, params.src_role)
97
+ // 5. dst_ata [writable] == manifest_role_ata(hedge_state, params.dst_role)
98
+ // 6. price_oracle_src [] Doves oracle for src_role, if Doves-priced; else unused
99
+ // 7. price_oracle_dst [] Doves oracle for dst_role; same rules
100
+ // 8. strategy_state_src [] StrategyState PDA for src_role's base asset; else unused
101
+ // 9. strategy_state_dst [] StrategyState PDA for dst_role's base asset; else unused
102
+ // 10. lending_src [] Jup-Lend Earn `lending` for src_role if an fToken role; else unused
103
+ // 11. lending_dst [] Jup-Lend Earn `lending` for dst_role; same rules
104
+ // 12. jupsol_rate [] JupSOL Sanctum stake-pool account — ONE shared account
105
+ // regardless of which leg (or both) is JupSol; unused
106
+ // otherwise. Defaults to `JUPSOL_STAKE_POOL_ACCOUNT`.
107
+ // 13. jupiter_program [] Jupiter aggregator program
108
+ //
109
+ // remaining_accounts: the caller-supplied Jupiter route accounts (source must be src_ata,
110
+ // destination must be dst_ata) — unchanged passthrough, exactly like base_to_base_swap.
111
+ //
112
+ // A JupSol leg additionally requires the `jupsol_rate` stake-pool account to be EPOCH-FRESH
113
+ // (cranked this epoch) — a stale pool reverts `StaleJupSolStakePool` even though the fixed
114
+ // address/owner/mint pin passes. See `oracle::jupsol_to_sol_native`'s module doc for the
115
+ // chain-verified rate-source spec.
116
+ // ---------------------------------------------------------------------------
117
+ /**
118
+ * Mirrors the on-chain `HedgeManifestRole` enum exactly (`instructions/hedge/hedge_swap.rs`) —
119
+ * Borsh-serializes as a single `u8` by declaration order, which coincides with each variant's
120
+ * explicit `= N` discriminant (verified by the Rust module's own
121
+ * `test_borsh_round_trip_matches_declared_discriminants`).
122
+ */
123
+ var HedgeManifestRole;
124
+ (function (HedgeManifestRole) {
125
+ HedgeManifestRole[HedgeManifestRole["JupUsd"] = 0] = "JupUsd";
126
+ HedgeManifestRole[HedgeManifestRole["JupSol"] = 1] = "JupSol";
127
+ HedgeManifestRole[HedgeManifestRole["Wbtc"] = 2] = "Wbtc";
128
+ HedgeManifestRole[HedgeManifestRole["Weth"] = 3] = "Weth";
129
+ HedgeManifestRole[HedgeManifestRole["Wsol"] = 4] = "Wsol";
130
+ HedgeManifestRole[HedgeManifestRole["JlJupUsd"] = 5] = "JlJupUsd";
131
+ HedgeManifestRole[HedgeManifestRole["JlWbtc"] = 6] = "JlWbtc";
132
+ HedgeManifestRole[HedgeManifestRole["JlWeth"] = 7] = "JlWeth";
133
+ })(HedgeManifestRole || (exports.HedgeManifestRole = HedgeManifestRole = {}));
134
+ /**
135
+ * Build the on-chain `hedge_swap` instruction — see this module's `hedge_swap` section doc
136
+ * comment above for the full account-order rationale and the JupSOL stake-pool default.
137
+ *
138
+ * Instruction data layout (Anchor Borsh, `HedgeSwapParams`):
139
+ * [8-byte disc, 1-byte src_role, 1-byte dst_role, 8-byte amount_in (LE), 8-byte min_out (LE),
140
+ * 4-byte jupiter_data_len (LE), ...jupiter_data_bytes]
141
+ *
142
+ * A JupSol leg requires a FRESH (epoch-current) `jupsolRate` stake-pool account — a stale pool
143
+ * reverts `StaleJupSolStakePool` on-chain.
144
+ */
145
+ function createHedgeSwapIx(args, programId = constants_1.PROGRAM_ID) {
146
+ const { manager, config, managerRole, hedgeState, srcAta, dstAta, priceOracleSrc, priceOracleDst, strategyStateSrc, strategyStateDst, lendingSrc, lendingDst, jupsolRate = constants_1.JUPSOL_STAKE_POOL_ACCOUNT, jupiterProgram = constants_1.JUPITER_PROGRAM, srcRole, dstRole, amountIn, minOut, jupiterData, remainingAccounts = [], } = args;
147
+ const amountInBi = toBigIntAmount(amountIn);
148
+ const minOutBi = toBigIntAmount(minOut);
149
+ const jupBytes = Buffer.from(jupiterData);
150
+ const dataLen = 8 + 1 + 1 + 8 + 8 + 4 + jupBytes.length;
151
+ const data = Buffer.alloc(dataLen);
152
+ constants_1.IX_HEDGE_SWAP.copy(data, 0);
153
+ data.writeUInt8(srcRole, 8);
154
+ data.writeUInt8(dstRole, 9);
155
+ data.writeBigUInt64LE(amountInBi, 10);
156
+ data.writeBigUInt64LE(minOutBi, 18);
157
+ data.writeUInt32LE(jupBytes.length, 26);
158
+ jupBytes.copy(data, 30);
159
+ const keys = [
160
+ { pubkey: manager, isSigner: true, isWritable: false },
161
+ { pubkey: config, isSigner: false, isWritable: false },
162
+ { pubkey: managerRole, isSigner: false, isWritable: false },
163
+ { pubkey: hedgeState, isSigner: false, isWritable: true },
164
+ { pubkey: srcAta, isSigner: false, isWritable: true },
165
+ { pubkey: dstAta, isSigner: false, isWritable: true },
166
+ { pubkey: priceOracleSrc, isSigner: false, isWritable: false },
167
+ { pubkey: priceOracleDst, isSigner: false, isWritable: false },
168
+ { pubkey: strategyStateSrc, isSigner: false, isWritable: false },
169
+ { pubkey: strategyStateDst, isSigner: false, isWritable: false },
170
+ { pubkey: lendingSrc, isSigner: false, isWritable: false },
171
+ { pubkey: lendingDst, isSigner: false, isWritable: false },
172
+ { pubkey: jupsolRate, isSigner: false, isWritable: false },
173
+ { pubkey: jupiterProgram, isSigner: false, isWritable: false },
174
+ ...remainingAccounts,
175
+ ];
176
+ return new web3_js_1.TransactionInstruction({ keys, programId, data });
177
+ }
178
+ // ---------------------------------------------------------------------------
179
+ // init_or_update_hedge_state — ADMIN-gated (config.admin, NOT `require_manager`). Provisions or
180
+ // updates the singleton `HedgeState` PDA (seeds `["hedge", config]`) every manager op above reads.
181
+ // Not part of the manager-facing hedge-op family, but lives here (rather than instructions.ts) to
182
+ // keep every hedge-shaped builder + its account-order doc together in one module.
183
+ //
184
+ // Verified against `instructions/hedge/init_or_update_hedge_state.rs`:
185
+ // - `#[derive(Accounts)] pub struct InitOrUpdateHedgeState<'info>` (5 fixed accounts)
186
+ // - `InitOrUpdateHedgeStateParams` (Borsh field order)
187
+ //
188
+ // Fixed accounts (5):
189
+ // 0. payer [signer, writable] rent payer; must equal JlpdConfig.admin (both init+update)
190
+ // 1. config [] JlpdConfig PDA (already initialized; read-only — this ix
191
+ // never writes it)
192
+ // 2. hedge_state [writable] HedgeState PDA, seeds ["hedge", config] (init_if_needed)
193
+ // 3. token_program [] validates/derives every canonical manifest ATA
194
+ // 4. system_program [] account creation on init
195
+ //
196
+ // remaining_accounts: config-owned token accounts backing any manifest ATA slot set to a NEW
197
+ // value THIS call (order-independent, matched by pubkey on-chain; an unchanged slot needs none).
198
+ //
199
+ // Instruction data: [8-byte disc, Borsh(InitOrUpdateHedgeStateParams)]
200
+ // Borsh field order (Option-per-field; `None` keeps the stored value on update / a fail-closed
201
+ // default on init):
202
+ // positions: [Option<HedgePositionSlotParams>; MAX_HEDGE_POSITIONS(4)]
203
+ // each HedgePositionSlotParams (Some case) = 5 Pubkeys in order:
204
+ // borrow_position, vault_config, vault_state, fluid_oracle, debt_mint
205
+ // jupusd / jupsol / wbtc / weth / wsol: Option<Pubkey> (5) — config-owned ATA manifest
206
+ // jl_jupusd / jl_wbtc / jl_weth: Option<Pubkey> (3) — Earn fToken ATAs
207
+ // jl_jupusd_mint / jl_wbtc_mint / jl_weth_mint: Option<Pubkey> (3) — admin-set fToken mints
208
+ // jl_jupusd_lending / jl_wbtc_lending / jl_weth_lending: Option<Pubkey> (3) — Earn rate sources
209
+ // max_pledged_collateral_jlp: Option<u64>
210
+ // max_swap_notional_per_settle: Option<u64>
211
+ // max_ltv_bps: Option<u16>
212
+ // enabled: Option<bool>
213
+ // ---------------------------------------------------------------------------
214
+ // sha256("global:init_or_update_hedge_state")[..8]. Defined locally rather than re-exported from
215
+ // `constants.ts` (this SDK task's touch-scope is limited to this file/index.ts/the parity test) —
216
+ // verified by an independent Node `crypto` computation in `__tests__/abi-parity.test.ts` and
217
+ // matches the identical hardcoded constant the two jlpd-server setup scripts each carry.
218
+ const IX_INIT_OR_UPDATE_HEDGE_STATE = Buffer.from([126, 123, 249, 65, 182, 100, 250, 254]);
219
+ /** Serialize `Option<HedgePositionSlotParams>` — 1-byte tag, then 5 Pubkeys (160 bytes) if `Some`. */
220
+ function writeOptionalHedgePositionSlot(parts, slot) {
221
+ if (slot != null) {
222
+ parts.push(0x01);
223
+ parts.push(...slot.borrowPosition.toBuffer());
224
+ parts.push(...slot.vaultConfig.toBuffer());
225
+ parts.push(...slot.vaultState.toBuffer());
226
+ parts.push(...slot.fluidOracle.toBuffer());
227
+ parts.push(...slot.debtMint.toBuffer());
228
+ }
229
+ else {
230
+ parts.push(0x00);
231
+ }
232
+ }
233
+ /** Serialize `Option<bool>` — 1-byte tag, then 1 byte (0/1) if `Some`. */
234
+ function writeOptionalBool(parts, value) {
235
+ if (value != null) {
236
+ parts.push(0x01);
237
+ parts.push(value ? 1 : 0);
238
+ }
239
+ else {
240
+ parts.push(0x00);
241
+ }
242
+ }
243
+ /**
244
+ * Build the on-chain `init_or_update_hedge_state` instruction (provisions/updates the singleton
245
+ * `HedgeState` PDA). See this section's module doc comment above for the full account list and
246
+ * Borsh field order.
247
+ */
248
+ function createInitOrUpdateHedgeStateIx(args, programId = constants_1.PROGRAM_ID) {
249
+ const { payer, config, hedgeState, tokenProgram = spl_token_1.TOKEN_PROGRAM_ID, systemProgram = web3_js_1.SystemProgram.programId, positions = [], remainingAccounts = [], } = args;
250
+ if (positions.length !== 0 && positions.length !== constants_1.MAX_HEDGE_POSITIONS) {
251
+ throw new RangeError(`createInitOrUpdateHedgeStateIx: positions must have exactly ${constants_1.MAX_HEDGE_POSITIONS} entries ` +
252
+ `(or be omitted/empty to leave every slot untouched), got ${positions.length}`);
253
+ }
254
+ if (args.maxLtvBps != null &&
255
+ (!Number.isInteger(args.maxLtvBps) || args.maxLtvBps < 0 || args.maxLtvBps > constants_1.MAX_HEDGE_LTV_BPS)) {
256
+ throw new RangeError(`createInitOrUpdateHedgeStateIx: maxLtvBps must be an integer in 0..${constants_1.MAX_HEDGE_LTV_BPS}, got ${args.maxLtvBps}`);
257
+ }
258
+ const parts = [...IX_INIT_OR_UPDATE_HEDGE_STATE];
259
+ // positions: [Option<HedgePositionSlotParams>; MAX_HEDGE_POSITIONS] — a fixed-size Rust array,
260
+ // so the wire format is always exactly MAX_HEDGE_POSITIONS Option tags, no length prefix.
261
+ const slots = positions.length === constants_1.MAX_HEDGE_POSITIONS ? positions : new Array(constants_1.MAX_HEDGE_POSITIONS).fill(null);
262
+ for (const slot of slots)
263
+ writeOptionalHedgePositionSlot(parts, slot);
264
+ // Config-owned ATA manifest (5 Option<Pubkey>, Rust field order).
265
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jupusd ?? null);
266
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jupsol ?? null);
267
+ (0, buffer_1.writeOptionalPubkey)(parts, args.wbtc ?? null);
268
+ (0, buffer_1.writeOptionalPubkey)(parts, args.weth ?? null);
269
+ (0, buffer_1.writeOptionalPubkey)(parts, args.wsol ?? null);
270
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlJupusd ?? null);
271
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlWbtc ?? null);
272
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlWeth ?? null);
273
+ // Admin-set Earn fToken mints (3 Option<Pubkey>).
274
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlJupusdMint ?? null);
275
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlWbtcMint ?? null);
276
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlWethMint ?? null);
277
+ // Earn rate sources (3 Option<Pubkey>).
278
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlJupusdLending ?? null);
279
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlWbtcLending ?? null);
280
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlWethLending ?? null);
281
+ // Guards.
282
+ (0, buffer_1.writeOptionalU64)(parts, args.maxPledgedCollateralJlp != null ? new bn_js_1.default(toBigIntAmount(args.maxPledgedCollateralJlp).toString()) : null);
283
+ (0, buffer_1.writeOptionalU64)(parts, args.maxSwapNotionalPerSettle != null ? new bn_js_1.default(toBigIntAmount(args.maxSwapNotionalPerSettle).toString()) : null);
284
+ (0, buffer_1.writeOptionalU16)(parts, args.maxLtvBps ?? null);
285
+ writeOptionalBool(parts, args.enabled ?? null);
286
+ const data = Buffer.from(parts);
287
+ const keys = [
288
+ { pubkey: payer, isSigner: true, isWritable: true },
289
+ { pubkey: config, isSigner: false, isWritable: false },
290
+ { pubkey: hedgeState, isSigner: false, isWritable: true },
291
+ { pubkey: tokenProgram, isSigner: false, isWritable: false },
292
+ { pubkey: systemProgram, isSigner: false, isWritable: false },
293
+ ...remainingAccounts,
294
+ ];
295
+ return new web3_js_1.TransactionInstruction({ keys, programId, data });
296
+ }
@@ -0,0 +1,88 @@
1
+ import { PublicKey } from "@solana/web3.js";
2
+ import BN from "bn.js";
3
+ import type { SolanaConnection } from "../common/connection";
4
+ /**
5
+ * One Fluid borrow position: the position NFT, that vault's pinned
6
+ * `VaultConfig`/`VaultState`/oracle, and its `debt_mint`. All-`PublicKey.default()`
7
+ * = disabled (see `isHedgePositionSlotDisabled`).
8
+ */
9
+ export interface HedgePositionSlot {
10
+ /** This fund's Fluid position NFT account in that vault. */
11
+ borrowPosition: PublicKey;
12
+ /** That vault's `VaultConfig` account (pinned). */
13
+ vaultConfig: PublicKey;
14
+ /** That vault's `VaultState` account. */
15
+ vaultState: PublicKey;
16
+ /** That vault's own oracle account (pinned). */
17
+ fluidOracle: PublicKey;
18
+ /** Which asset this vault's debt side borrows (JupUSD long leg; SOL/wBTC/wETH short legs). */
19
+ debtMint: PublicKey;
20
+ }
21
+ /** A slot with every field at its fail-closed default — the only valid "off" state. */
22
+ export declare function isHedgePositionSlotDisabled(slot: HedgePositionSlot): boolean;
23
+ /** Is `mint` one of the Fluid debt mints a `HedgePositionSlot` may borrow? */
24
+ export declare function isKnownHedgeDebtMint(mint: PublicKey): boolean;
25
+ /**
26
+ * The shared Jup-Lend hedge positions, the config-owned token manifest, and
27
+ * the on-chain risk guards. Total 1256 bytes (8-byte discriminator + 1248
28
+ * data bytes).
29
+ */
30
+ export interface HedgeState {
31
+ /** Up to `MAX_HEDGE_POSITIONS` independent Fluid borrow positions. */
32
+ positions: HedgePositionSlot[];
33
+ /** Free JupUSD working ATA (long-leg borrow destination / short-leg swap source). */
34
+ jupusd: PublicKey;
35
+ /** Free JupSOL working ATA (long-SOL exposure). */
36
+ jupsol: PublicKey;
37
+ /** Free raw wBTC working ATA. */
38
+ wbtc: PublicKey;
39
+ /** Free raw wETH working ATA. */
40
+ weth: PublicKey;
41
+ /** Free wSOL working ATA (short-leg borrowed SOL, pre-swap). */
42
+ wsol: PublicKey;
43
+ /** Jupiter Lend Earn jlJupUSD fToken ATA (short-leg earn parking). */
44
+ jlJupusd: PublicKey;
45
+ /** Jupiter Lend Earn jlwBTC fToken ATA (disabled until `jlWbtcMint` is set). */
46
+ jlWbtc: PublicKey;
47
+ /** Jupiter Lend Earn jlwETH fToken ATA (disabled until `jlWethMint` is set). */
48
+ jlWeth: PublicKey;
49
+ jlJupusdMint: PublicKey;
50
+ jlWbtcMint: PublicKey;
51
+ jlWethMint: PublicKey;
52
+ /** Canonical Jup-Lend Earn `lending` account for the JupUSD pool (`exchange_rate@115` values `jlJupusd`). */
53
+ jlJupusdLending: PublicKey;
54
+ /** Canonical `lending` account for the wBTC pool (disabled until `jlWbtcMint` is set). */
55
+ jlWbtcLending: PublicKey;
56
+ /** Canonical `lending` account for the wETH pool (disabled until `jlWethMint` is set). */
57
+ jlWethLending: PublicKey;
58
+ /** Max JLP (base units) that may be pledged as Fluid collateral, summed across every enabled slot. */
59
+ maxPledgedCollateralJlp: BN;
60
+ /** Swap-churn budget: max input notional (USD, 6-dec) `hedge_swap` may spend between settles. */
61
+ maxSwapNotionalPerSettle: BN;
62
+ /** Swap-churn accumulator: input notional spent since the last settle. Reset only by `settle_yield`. */
63
+ swapNotionalSinceSettle: BN;
64
+ /** Liquidation-probability cap in basis points, valued on each position's own pinned Fluid oracle. */
65
+ maxLtvBps: number;
66
+ /** Hedge switch bitfield; bit 0 (`HEDGE_FLAG_ENABLED`) is the master switch. */
67
+ flags: number;
68
+ /** Account version for migrations. 0 = uninitialized. */
69
+ version: number;
70
+ /** PDA bump seed. */
71
+ bump: number;
72
+ }
73
+ /** The hedge master switch: `flags` bit 0 (`HEDGE_FLAG_ENABLED`) — mirrors `HedgeState::is_enabled`. */
74
+ export declare function isHedgeEnabled(state: Pick<HedgeState, "flags">): boolean;
75
+ /** Derive the singleton `HedgeState` PDA. Seeds: ["hedge", config]. */
76
+ export declare function findHedgeStatePda(config: PublicKey, programId?: PublicKey): [PublicKey, number];
77
+ /**
78
+ * Deserialize a `HedgeState` account buffer. Layout (offsets include the
79
+ * 8-byte Anchor discriminator) — see this module's `HedgeState` doc comment
80
+ * for the full field map; verified against
81
+ * `hedge_state.rs::test_hedge_state_field_offsets`.
82
+ */
83
+ export declare function deserializeHedgeState(data: Buffer): HedgeState;
84
+ /**
85
+ * Fetch + decode the singleton `HedgeState` account. `config` defaults to the
86
+ * derived JlpdConfig PDA (the only config this program has).
87
+ */
88
+ export declare function fetchHedgeState(connection: SolanaConnection, config?: PublicKey, programId?: PublicKey): Promise<HedgeState>;
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isHedgePositionSlotDisabled = isHedgePositionSlotDisabled;
4
+ exports.isKnownHedgeDebtMint = isKnownHedgeDebtMint;
5
+ exports.isHedgeEnabled = isHedgeEnabled;
6
+ exports.findHedgeStatePda = findHedgeStatePda;
7
+ exports.deserializeHedgeState = deserializeHedgeState;
8
+ exports.fetchHedgeState = fetchHedgeState;
9
+ const web3_js_1 = require("@solana/web3.js");
10
+ const buffer_1 = require("../common/buffer");
11
+ const constants_1 = require("./constants");
12
+ const pda_1 = require("./pda");
13
+ /** A slot with every field at its fail-closed default — the only valid "off" state. */
14
+ function isHedgePositionSlotDisabled(slot) {
15
+ return (slot.borrowPosition.equals(web3_js_1.PublicKey.default) &&
16
+ slot.vaultConfig.equals(web3_js_1.PublicKey.default) &&
17
+ slot.vaultState.equals(web3_js_1.PublicKey.default) &&
18
+ slot.fluidOracle.equals(web3_js_1.PublicKey.default) &&
19
+ slot.debtMint.equals(web3_js_1.PublicKey.default));
20
+ }
21
+ /** Is `mint` one of the Fluid debt mints a `HedgePositionSlot` may borrow? */
22
+ function isKnownHedgeDebtMint(mint) {
23
+ return (mint.equals(constants_1.MINT_JUPUSD) ||
24
+ mint.equals(constants_1.MINT_WSOL) ||
25
+ mint.equals(constants_1.MINT_WBTC) ||
26
+ mint.equals(constants_1.MINT_WETH));
27
+ }
28
+ /** The hedge master switch: `flags` bit 0 (`HEDGE_FLAG_ENABLED`) — mirrors `HedgeState::is_enabled`. */
29
+ function isHedgeEnabled(state) {
30
+ return (state.flags & constants_1.HEDGE_FLAG_ENABLED) !== 0;
31
+ }
32
+ // ---------------------------------------------------------------------------
33
+ // PDA derivation
34
+ // ---------------------------------------------------------------------------
35
+ /** Derive the singleton `HedgeState` PDA. Seeds: ["hedge", config]. */
36
+ function findHedgeStatePda(config, programId = constants_1.PROGRAM_ID) {
37
+ return web3_js_1.PublicKey.findProgramAddressSync([constants_1.HEDGE_STATE_SEED, config.toBuffer()], programId);
38
+ }
39
+ // ---------------------------------------------------------------------------
40
+ // Deserialization
41
+ // ---------------------------------------------------------------------------
42
+ function deserializeHedgePositionSlot(data, offset) {
43
+ return {
44
+ borrowPosition: (0, buffer_1.readPubkey)(data, offset),
45
+ vaultConfig: (0, buffer_1.readPubkey)(data, offset + 32),
46
+ vaultState: (0, buffer_1.readPubkey)(data, offset + 64),
47
+ fluidOracle: (0, buffer_1.readPubkey)(data, offset + 96),
48
+ debtMint: (0, buffer_1.readPubkey)(data, offset + 128),
49
+ };
50
+ }
51
+ /**
52
+ * Deserialize a `HedgeState` account buffer. Layout (offsets include the
53
+ * 8-byte Anchor discriminator) — see this module's `HedgeState` doc comment
54
+ * for the full field map; verified against
55
+ * `hedge_state.rs::test_hedge_state_field_offsets`.
56
+ */
57
+ function deserializeHedgeState(data) {
58
+ if (data.length < constants_1.HEDGE_STATE_SIZE) {
59
+ throw new Error(`HedgeState data too short: ${data.length} < ${constants_1.HEDGE_STATE_SIZE}`);
60
+ }
61
+ const disc = data.subarray(0, 8);
62
+ if (!disc.equals(constants_1.DISC_HEDGE_STATE)) {
63
+ throw new Error("Invalid HedgeState discriminator");
64
+ }
65
+ // positions[MAX_HEDGE_POSITIONS], starting right after the 8-byte discriminator.
66
+ const positions = [];
67
+ for (let i = 0; i < constants_1.MAX_HEDGE_POSITIONS; i++) {
68
+ positions.push(deserializeHedgePositionSlot(data, 8 + i * constants_1.HEDGE_POSITION_SLOT_SIZE));
69
+ }
70
+ const afterPositions = 8 + constants_1.MAX_HEDGE_POSITIONS * constants_1.HEDGE_POSITION_SLOT_SIZE; // 648
71
+ return {
72
+ positions,
73
+ jupusd: (0, buffer_1.readPubkey)(data, afterPositions),
74
+ jupsol: (0, buffer_1.readPubkey)(data, afterPositions + 32),
75
+ wbtc: (0, buffer_1.readPubkey)(data, afterPositions + 64),
76
+ weth: (0, buffer_1.readPubkey)(data, afterPositions + 96),
77
+ wsol: (0, buffer_1.readPubkey)(data, afterPositions + 128),
78
+ jlJupusd: (0, buffer_1.readPubkey)(data, afterPositions + 160),
79
+ jlWbtc: (0, buffer_1.readPubkey)(data, afterPositions + 192),
80
+ jlWeth: (0, buffer_1.readPubkey)(data, afterPositions + 224),
81
+ jlJupusdMint: (0, buffer_1.readPubkey)(data, afterPositions + 256),
82
+ jlWbtcMint: (0, buffer_1.readPubkey)(data, afterPositions + 288),
83
+ jlWethMint: (0, buffer_1.readPubkey)(data, afterPositions + 320),
84
+ jlJupusdLending: (0, buffer_1.readPubkey)(data, afterPositions + 352),
85
+ jlWbtcLending: (0, buffer_1.readPubkey)(data, afterPositions + 384),
86
+ jlWethLending: (0, buffer_1.readPubkey)(data, afterPositions + 416),
87
+ maxPledgedCollateralJlp: (0, buffer_1.readU64)(data, afterPositions + 448),
88
+ maxSwapNotionalPerSettle: (0, buffer_1.readU64)(data, afterPositions + 456),
89
+ swapNotionalSinceSettle: (0, buffer_1.readU64)(data, afterPositions + 464),
90
+ maxLtvBps: (0, buffer_1.readU16)(data, afterPositions + 472),
91
+ flags: (0, buffer_1.readU16)(data, afterPositions + 474),
92
+ version: (0, buffer_1.readU8)(data, afterPositions + 476),
93
+ bump: (0, buffer_1.readU8)(data, afterPositions + 477),
94
+ };
95
+ }
96
+ // ---------------------------------------------------------------------------
97
+ // Fetch helper
98
+ // ---------------------------------------------------------------------------
99
+ /**
100
+ * Fetch + decode the singleton `HedgeState` account. `config` defaults to the
101
+ * derived JlpdConfig PDA (the only config this program has).
102
+ */
103
+ async function fetchHedgeState(connection, config, programId = constants_1.PROGRAM_ID) {
104
+ const configKey = config ?? (0, pda_1.findJlpdConfigPda)(programId)[0];
105
+ const [pda] = findHedgeStatePda(configKey, programId);
106
+ const info = await connection.getAccountInfo(pda);
107
+ if (!info)
108
+ throw new Error("HedgeState account not found");
109
+ return deserializeHedgeState(info.data);
110
+ }
@@ -0,0 +1,17 @@
1
+ export * from "./constants";
2
+ export * from "./types";
3
+ export * from "./pda";
4
+ export * from "./accounts";
5
+ export * from "./instructions";
6
+ export * from "./swap-jlp";
7
+ export * from "./base-to-base-swap";
8
+ export * from "./settle-yield";
9
+ export * from "./jlp-data";
10
+ export * from "./jlp-borrow";
11
+ export * from "./jupusd-earn";
12
+ export * from "./adapter";
13
+ export * from "./hedge-state";
14
+ export * from "./hedge-instructions";
15
+ export * from "./fluid-view";
16
+ export * from "./hedge-derived";
17
+ export * from "./live-jlp-price";
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./constants"), exports);
18
+ __exportStar(require("./types"), exports);
19
+ __exportStar(require("./pda"), exports);
20
+ __exportStar(require("./accounts"), exports);
21
+ __exportStar(require("./instructions"), exports);
22
+ __exportStar(require("./swap-jlp"), exports);
23
+ __exportStar(require("./base-to-base-swap"), exports);
24
+ __exportStar(require("./settle-yield"), exports);
25
+ __exportStar(require("./jlp-data"), exports);
26
+ __exportStar(require("./jlp-borrow"), exports);
27
+ __exportStar(require("./jupusd-earn"), exports);
28
+ __exportStar(require("./adapter"), exports);
29
+ __exportStar(require("./hedge-state"), exports);
30
+ __exportStar(require("./hedge-instructions"), exports);
31
+ __exportStar(require("./fluid-view"), exports);
32
+ __exportStar(require("./hedge-derived"), exports);
33
+ __exportStar(require("./live-jlp-price"), exports);