@elmntl/jlpd-sdk 0.1.11 → 0.13.4

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 -3552
  52. package/dist/index.js +37 -4454
  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 +210 -0
  66. package/dist/jlpd-strategy/hedge-instructions.js +300 -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 -3552
  115. package/dist/index.mjs +0 -4363
@@ -0,0 +1,300 @@
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
+ const keys = buildHedgeOpKeys(args);
71
+ // The Accounts struct inserts fluid_tick between vault_state (index 11) and
72
+ // jup_lend_borrow_program — mirror it exactly.
73
+ keys.splice(12, 0, { pubkey: args.fluidTick, isSigner: false, isWritable: false });
74
+ return new web3_js_1.TransactionInstruction({ keys, programId, data });
75
+ }
76
+ /** Build the on-chain `hedge_withdraw_collateral` instruction. */
77
+ function createHedgeWithdrawCollateralIx(args, programId = constants_1.PROGRAM_ID) {
78
+ const data = serializeSlotIndexAmountParams(constants_1.IX_HEDGE_WITHDRAW_COLLATERAL, args.slotIndex, args.amount);
79
+ return new web3_js_1.TransactionInstruction({ keys: buildHedgeOpKeys(args), programId, data });
80
+ }
81
+ // ---------------------------------------------------------------------------
82
+ // hedge_swap — the general, RISK-INCREASING hedge swap between two `HedgeState` manifest ATAs
83
+ // via Jupiter. BLOCKED while the hedge is disabled (unlike the risk-decreasing hedge ops above).
84
+ //
85
+ // Account order verified against `instructions/hedge/hedge_swap.rs`'s `#[derive(Accounts)]
86
+ // HedgeSwap` struct (post-B0): the B0 change inserted a NEW fixed account, `jupsol_rate`, at
87
+ // position 13 (0-indexed 12) between `lending_dst` and `jupiter_program` — `jupiter_program` is
88
+ // therefore now position 14 (0-indexed 13), not 13. NOTE: `target/idl/jlpd_strategy.json` has NOT
89
+ // been regenerated since B0 landed — its `hedge_swap.accounts` list is stale (13 entries, missing
90
+ // `jupsol_rate`); the discriminator and `HedgeSwapParams`/`HedgeManifestRole` type entries in that
91
+ // same IDL DO match the Rust source (params/enum are unaffected by B0 — only the account list
92
+ // changed), so this builder trusts the Rust struct for account order and the IDL for the
93
+ // discriminator + param shape.
94
+ //
95
+ // Fixed accounts (14):
96
+ // 0. manager [signer]
97
+ // 1. config [] JLPD Config PDA (read-only — this ix never writes it)
98
+ // 2. manager_role [] ManagerRole PDA
99
+ // 3. hedge_state [writable] writes swap_notional_since_settle
100
+ // 4. src_ata [writable] == manifest_role_ata(hedge_state, params.src_role)
101
+ // 5. dst_ata [writable] == manifest_role_ata(hedge_state, params.dst_role)
102
+ // 6. price_oracle_src [] Doves oracle for src_role, if Doves-priced; else unused
103
+ // 7. price_oracle_dst [] Doves oracle for dst_role; same rules
104
+ // 8. strategy_state_src [] StrategyState PDA for src_role's base asset; else unused
105
+ // 9. strategy_state_dst [] StrategyState PDA for dst_role's base asset; else unused
106
+ // 10. lending_src [] Jup-Lend Earn `lending` for src_role if an fToken role; else unused
107
+ // 11. lending_dst [] Jup-Lend Earn `lending` for dst_role; same rules
108
+ // 12. jupsol_rate [] JupSOL Sanctum stake-pool account — ONE shared account
109
+ // regardless of which leg (or both) is JupSol; unused
110
+ // otherwise. Defaults to `JUPSOL_STAKE_POOL_ACCOUNT`.
111
+ // 13. jupiter_program [] Jupiter aggregator program
112
+ //
113
+ // remaining_accounts: the caller-supplied Jupiter route accounts (source must be src_ata,
114
+ // destination must be dst_ata) — unchanged passthrough, exactly like base_to_base_swap.
115
+ //
116
+ // A JupSol leg additionally requires the `jupsol_rate` stake-pool account to be EPOCH-FRESH
117
+ // (cranked this epoch) — a stale pool reverts `StaleJupSolStakePool` even though the fixed
118
+ // address/owner/mint pin passes. See `oracle::jupsol_to_sol_native`'s module doc for the
119
+ // chain-verified rate-source spec.
120
+ // ---------------------------------------------------------------------------
121
+ /**
122
+ * Mirrors the on-chain `HedgeManifestRole` enum exactly (`instructions/hedge/hedge_swap.rs`) —
123
+ * Borsh-serializes as a single `u8` by declaration order, which coincides with each variant's
124
+ * explicit `= N` discriminant (verified by the Rust module's own
125
+ * `test_borsh_round_trip_matches_declared_discriminants`).
126
+ */
127
+ var HedgeManifestRole;
128
+ (function (HedgeManifestRole) {
129
+ HedgeManifestRole[HedgeManifestRole["JupUsd"] = 0] = "JupUsd";
130
+ HedgeManifestRole[HedgeManifestRole["JupSol"] = 1] = "JupSol";
131
+ HedgeManifestRole[HedgeManifestRole["Wbtc"] = 2] = "Wbtc";
132
+ HedgeManifestRole[HedgeManifestRole["Weth"] = 3] = "Weth";
133
+ HedgeManifestRole[HedgeManifestRole["Wsol"] = 4] = "Wsol";
134
+ HedgeManifestRole[HedgeManifestRole["JlJupUsd"] = 5] = "JlJupUsd";
135
+ HedgeManifestRole[HedgeManifestRole["JlWbtc"] = 6] = "JlWbtc";
136
+ HedgeManifestRole[HedgeManifestRole["JlWeth"] = 7] = "JlWeth";
137
+ })(HedgeManifestRole || (exports.HedgeManifestRole = HedgeManifestRole = {}));
138
+ /**
139
+ * Build the on-chain `hedge_swap` instruction — see this module's `hedge_swap` section doc
140
+ * comment above for the full account-order rationale and the JupSOL stake-pool default.
141
+ *
142
+ * Instruction data layout (Anchor Borsh, `HedgeSwapParams`):
143
+ * [8-byte disc, 1-byte src_role, 1-byte dst_role, 8-byte amount_in (LE), 8-byte min_out (LE),
144
+ * 4-byte jupiter_data_len (LE), ...jupiter_data_bytes]
145
+ *
146
+ * A JupSol leg requires a FRESH (epoch-current) `jupsolRate` stake-pool account — a stale pool
147
+ * reverts `StaleJupSolStakePool` on-chain.
148
+ */
149
+ function createHedgeSwapIx(args, programId = constants_1.PROGRAM_ID) {
150
+ 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;
151
+ const amountInBi = toBigIntAmount(amountIn);
152
+ const minOutBi = toBigIntAmount(minOut);
153
+ const jupBytes = Buffer.from(jupiterData);
154
+ const dataLen = 8 + 1 + 1 + 8 + 8 + 4 + jupBytes.length;
155
+ const data = Buffer.alloc(dataLen);
156
+ constants_1.IX_HEDGE_SWAP.copy(data, 0);
157
+ data.writeUInt8(srcRole, 8);
158
+ data.writeUInt8(dstRole, 9);
159
+ data.writeBigUInt64LE(amountInBi, 10);
160
+ data.writeBigUInt64LE(minOutBi, 18);
161
+ data.writeUInt32LE(jupBytes.length, 26);
162
+ jupBytes.copy(data, 30);
163
+ const keys = [
164
+ { pubkey: manager, isSigner: true, isWritable: false },
165
+ { pubkey: config, isSigner: false, isWritable: false },
166
+ { pubkey: managerRole, isSigner: false, isWritable: false },
167
+ { pubkey: hedgeState, isSigner: false, isWritable: true },
168
+ { pubkey: srcAta, isSigner: false, isWritable: true },
169
+ { pubkey: dstAta, isSigner: false, isWritable: true },
170
+ { pubkey: priceOracleSrc, isSigner: false, isWritable: false },
171
+ { pubkey: priceOracleDst, isSigner: false, isWritable: false },
172
+ { pubkey: strategyStateSrc, isSigner: false, isWritable: false },
173
+ { pubkey: strategyStateDst, isSigner: false, isWritable: false },
174
+ { pubkey: lendingSrc, isSigner: false, isWritable: false },
175
+ { pubkey: lendingDst, isSigner: false, isWritable: false },
176
+ { pubkey: jupsolRate, isSigner: false, isWritable: false },
177
+ { pubkey: jupiterProgram, isSigner: false, isWritable: false },
178
+ ...remainingAccounts,
179
+ ];
180
+ return new web3_js_1.TransactionInstruction({ keys, programId, data });
181
+ }
182
+ // ---------------------------------------------------------------------------
183
+ // init_or_update_hedge_state — ADMIN-gated (config.admin, NOT `require_manager`). Provisions or
184
+ // updates the singleton `HedgeState` PDA (seeds `["hedge", config]`) every manager op above reads.
185
+ // Not part of the manager-facing hedge-op family, but lives here (rather than instructions.ts) to
186
+ // keep every hedge-shaped builder + its account-order doc together in one module.
187
+ //
188
+ // Verified against `instructions/hedge/init_or_update_hedge_state.rs`:
189
+ // - `#[derive(Accounts)] pub struct InitOrUpdateHedgeState<'info>` (5 fixed accounts)
190
+ // - `InitOrUpdateHedgeStateParams` (Borsh field order)
191
+ //
192
+ // Fixed accounts (5):
193
+ // 0. payer [signer, writable] rent payer; must equal JlpdConfig.admin (both init+update)
194
+ // 1. config [] JlpdConfig PDA (already initialized; read-only — this ix
195
+ // never writes it)
196
+ // 2. hedge_state [writable] HedgeState PDA, seeds ["hedge", config] (init_if_needed)
197
+ // 3. token_program [] validates/derives every canonical manifest ATA
198
+ // 4. system_program [] account creation on init
199
+ //
200
+ // remaining_accounts: config-owned token accounts backing any manifest ATA slot set to a NEW
201
+ // value THIS call (order-independent, matched by pubkey on-chain; an unchanged slot needs none).
202
+ //
203
+ // Instruction data: [8-byte disc, Borsh(InitOrUpdateHedgeStateParams)]
204
+ // Borsh field order (Option-per-field; `None` keeps the stored value on update / a fail-closed
205
+ // default on init):
206
+ // positions: [Option<HedgePositionSlotParams>; MAX_HEDGE_POSITIONS(4)]
207
+ // each HedgePositionSlotParams (Some case) = 5 Pubkeys in order:
208
+ // borrow_position, vault_config, vault_state, fluid_oracle, debt_mint
209
+ // jupusd / jupsol / wbtc / weth / wsol: Option<Pubkey> (5) — config-owned ATA manifest
210
+ // jl_jupusd / jl_wbtc / jl_weth: Option<Pubkey> (3) — Earn fToken ATAs
211
+ // jl_jupusd_mint / jl_wbtc_mint / jl_weth_mint: Option<Pubkey> (3) — admin-set fToken mints
212
+ // jl_jupusd_lending / jl_wbtc_lending / jl_weth_lending: Option<Pubkey> (3) — Earn rate sources
213
+ // max_pledged_collateral_jlp: Option<u64>
214
+ // max_swap_notional_per_settle: Option<u64>
215
+ // max_ltv_bps: Option<u16>
216
+ // enabled: Option<bool>
217
+ // ---------------------------------------------------------------------------
218
+ // sha256("global:init_or_update_hedge_state")[..8]. Defined locally rather than re-exported from
219
+ // `constants.ts` (this SDK task's touch-scope is limited to this file/index.ts/the parity test) —
220
+ // verified by an independent Node `crypto` computation in `__tests__/abi-parity.test.ts` and
221
+ // matches the identical hardcoded constant the two jlpd-server setup scripts each carry.
222
+ const IX_INIT_OR_UPDATE_HEDGE_STATE = Buffer.from([126, 123, 249, 65, 182, 100, 250, 254]);
223
+ /** Serialize `Option<HedgePositionSlotParams>` — 1-byte tag, then 5 Pubkeys (160 bytes) if `Some`. */
224
+ function writeOptionalHedgePositionSlot(parts, slot) {
225
+ if (slot != null) {
226
+ parts.push(0x01);
227
+ parts.push(...slot.borrowPosition.toBuffer());
228
+ parts.push(...slot.vaultConfig.toBuffer());
229
+ parts.push(...slot.vaultState.toBuffer());
230
+ parts.push(...slot.fluidOracle.toBuffer());
231
+ parts.push(...slot.debtMint.toBuffer());
232
+ }
233
+ else {
234
+ parts.push(0x00);
235
+ }
236
+ }
237
+ /** Serialize `Option<bool>` — 1-byte tag, then 1 byte (0/1) if `Some`. */
238
+ function writeOptionalBool(parts, value) {
239
+ if (value != null) {
240
+ parts.push(0x01);
241
+ parts.push(value ? 1 : 0);
242
+ }
243
+ else {
244
+ parts.push(0x00);
245
+ }
246
+ }
247
+ /**
248
+ * Build the on-chain `init_or_update_hedge_state` instruction (provisions/updates the singleton
249
+ * `HedgeState` PDA). See this section's module doc comment above for the full account list and
250
+ * Borsh field order.
251
+ */
252
+ function createInitOrUpdateHedgeStateIx(args, programId = constants_1.PROGRAM_ID) {
253
+ const { payer, config, hedgeState, tokenProgram = spl_token_1.TOKEN_PROGRAM_ID, systemProgram = web3_js_1.SystemProgram.programId, positions = [], remainingAccounts = [], } = args;
254
+ if (positions.length !== 0 && positions.length !== constants_1.MAX_HEDGE_POSITIONS) {
255
+ throw new RangeError(`createInitOrUpdateHedgeStateIx: positions must have exactly ${constants_1.MAX_HEDGE_POSITIONS} entries ` +
256
+ `(or be omitted/empty to leave every slot untouched), got ${positions.length}`);
257
+ }
258
+ if (args.maxLtvBps != null &&
259
+ (!Number.isInteger(args.maxLtvBps) || args.maxLtvBps < 0 || args.maxLtvBps > constants_1.MAX_HEDGE_LTV_BPS)) {
260
+ throw new RangeError(`createInitOrUpdateHedgeStateIx: maxLtvBps must be an integer in 0..${constants_1.MAX_HEDGE_LTV_BPS}, got ${args.maxLtvBps}`);
261
+ }
262
+ const parts = [...IX_INIT_OR_UPDATE_HEDGE_STATE];
263
+ // positions: [Option<HedgePositionSlotParams>; MAX_HEDGE_POSITIONS] — a fixed-size Rust array,
264
+ // so the wire format is always exactly MAX_HEDGE_POSITIONS Option tags, no length prefix.
265
+ const slots = positions.length === constants_1.MAX_HEDGE_POSITIONS ? positions : new Array(constants_1.MAX_HEDGE_POSITIONS).fill(null);
266
+ for (const slot of slots)
267
+ writeOptionalHedgePositionSlot(parts, slot);
268
+ // Config-owned ATA manifest (5 Option<Pubkey>, Rust field order).
269
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jupusd ?? null);
270
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jupsol ?? null);
271
+ (0, buffer_1.writeOptionalPubkey)(parts, args.wbtc ?? null);
272
+ (0, buffer_1.writeOptionalPubkey)(parts, args.weth ?? null);
273
+ (0, buffer_1.writeOptionalPubkey)(parts, args.wsol ?? null);
274
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlJupusd ?? null);
275
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlWbtc ?? null);
276
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlWeth ?? null);
277
+ // Admin-set Earn fToken mints (3 Option<Pubkey>).
278
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlJupusdMint ?? null);
279
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlWbtcMint ?? null);
280
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlWethMint ?? null);
281
+ // Earn rate sources (3 Option<Pubkey>).
282
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlJupusdLending ?? null);
283
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlWbtcLending ?? null);
284
+ (0, buffer_1.writeOptionalPubkey)(parts, args.jlWethLending ?? null);
285
+ // Guards.
286
+ (0, buffer_1.writeOptionalU64)(parts, args.maxPledgedCollateralJlp != null ? new bn_js_1.default(toBigIntAmount(args.maxPledgedCollateralJlp).toString()) : null);
287
+ (0, buffer_1.writeOptionalU64)(parts, args.maxSwapNotionalPerSettle != null ? new bn_js_1.default(toBigIntAmount(args.maxSwapNotionalPerSettle).toString()) : null);
288
+ (0, buffer_1.writeOptionalU16)(parts, args.maxLtvBps ?? null);
289
+ writeOptionalBool(parts, args.enabled ?? null);
290
+ const data = Buffer.from(parts);
291
+ const keys = [
292
+ { pubkey: payer, isSigner: true, isWritable: true },
293
+ { pubkey: config, isSigner: false, isWritable: false },
294
+ { pubkey: hedgeState, isSigner: false, isWritable: true },
295
+ { pubkey: tokenProgram, isSigner: false, isWritable: false },
296
+ { pubkey: systemProgram, isSigner: false, isWritable: false },
297
+ ...remainingAccounts,
298
+ ];
299
+ return new web3_js_1.TransactionInstruction({ keys, programId, data });
300
+ }
@@ -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);