@elemental-stv-core/sdk 0.8.0 → 0.9.1

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.
@@ -0,0 +1,190 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createInitStrategyIx = createInitStrategyIx;
4
+ exports.createUpdateStrategyIx = createUpdateStrategyIx;
5
+ exports.createRegisterAdapterIx = createRegisterAdapterIx;
6
+ exports.createDeregisterAdapterIx = createDeregisterAdapterIx;
7
+ exports.createAddManagerIx = createAddManagerIx;
8
+ exports.createRemoveManagerIx = createRemoveManagerIx;
9
+ exports.createInitPositionIx = createInitPositionIx;
10
+ exports.createClosePositionIx = createClosePositionIx;
11
+ exports.createDepositIx = createDepositIx;
12
+ exports.createWithdrawIx = createWithdrawIx;
13
+ exports.createRouteDepositIx = createRouteDepositIx;
14
+ exports.createRouteWithdrawIx = createRouteWithdrawIx;
15
+ const web3_js_1 = require("@solana/web3.js");
16
+ const buffer_1 = require("../common/buffer");
17
+ const constants_1 = require("./constants");
18
+ function createInitStrategyIx(args, programId = constants_1.PROGRAM_ID) {
19
+ const { admin, baseMint, strategyState, authority, systemProgram = web3_js_1.SystemProgram.programId, } = args;
20
+ return new web3_js_1.TransactionInstruction({
21
+ keys: [
22
+ { pubkey: admin, isSigner: true, isWritable: true },
23
+ { pubkey: baseMint, isSigner: false, isWritable: false },
24
+ { pubkey: strategyState, isSigner: false, isWritable: true },
25
+ { pubkey: authority, isSigner: false, isWritable: false },
26
+ { pubkey: systemProgram, isSigner: false, isWritable: false },
27
+ ],
28
+ programId,
29
+ data: constants_1.IX_INIT_STRATEGY,
30
+ });
31
+ }
32
+ function createUpdateStrategyIx(args, programId = constants_1.PROGRAM_ID) {
33
+ const parts = [];
34
+ (0, buffer_1.writeOptionalPubkey)(parts, args.newAdmin ?? null);
35
+ (0, buffer_1.writeOptionalU16)(parts, args.newFlags ?? null);
36
+ return new web3_js_1.TransactionInstruction({
37
+ keys: [
38
+ { pubkey: args.admin, isSigner: true, isWritable: false },
39
+ { pubkey: args.strategyState, isSigner: false, isWritable: true },
40
+ ],
41
+ programId,
42
+ data: Buffer.concat([constants_1.IX_UPDATE_STRATEGY, Buffer.from(parts)]),
43
+ });
44
+ }
45
+ function createRegisterAdapterIx(args, programId = constants_1.PROGRAM_ID) {
46
+ const { admin, strategyState, protocolVault, adapterProgram, index, params, systemProgram = web3_js_1.SystemProgram.programId, } = args;
47
+ if (index < 0 || index > 0xff) {
48
+ throw new RangeError(`index out of range: ${index}`);
49
+ }
50
+ if (params.readAumAccountCount < 0 || params.readAumAccountCount > 0xff) {
51
+ throw new RangeError(`readAumAccountCount out of range: ${params.readAumAccountCount}`);
52
+ }
53
+ const data = Buffer.concat([
54
+ constants_1.IX_REGISTER_ADAPTER,
55
+ Buffer.from([index]),
56
+ params.protocolState.toBuffer(),
57
+ Buffer.from([params.readAumAccountCount]),
58
+ ]);
59
+ return new web3_js_1.TransactionInstruction({
60
+ keys: [
61
+ { pubkey: admin, isSigner: true, isWritable: true },
62
+ { pubkey: strategyState, isSigner: false, isWritable: true },
63
+ { pubkey: protocolVault, isSigner: false, isWritable: true },
64
+ { pubkey: adapterProgram, isSigner: false, isWritable: false },
65
+ { pubkey: systemProgram, isSigner: false, isWritable: false },
66
+ ],
67
+ programId,
68
+ data,
69
+ });
70
+ }
71
+ function createDeregisterAdapterIx(args, programId = constants_1.PROGRAM_ID) {
72
+ const { admin, strategyState, protocolVault, systemProgram = web3_js_1.SystemProgram.programId, } = args;
73
+ return new web3_js_1.TransactionInstruction({
74
+ keys: [
75
+ { pubkey: admin, isSigner: true, isWritable: true },
76
+ { pubkey: strategyState, isSigner: false, isWritable: true },
77
+ { pubkey: protocolVault, isSigner: false, isWritable: true },
78
+ { pubkey: systemProgram, isSigner: false, isWritable: false },
79
+ ],
80
+ programId,
81
+ data: constants_1.IX_DEREGISTER_ADAPTER,
82
+ });
83
+ }
84
+ function createAddManagerIx(args, programId = constants_1.PROGRAM_ID) {
85
+ const { admin, strategyState, managerRole, manager, systemProgram = web3_js_1.SystemProgram.programId, } = args;
86
+ return new web3_js_1.TransactionInstruction({
87
+ keys: [
88
+ { pubkey: admin, isSigner: true, isWritable: true },
89
+ { pubkey: strategyState, isSigner: false, isWritable: false },
90
+ { pubkey: managerRole, isSigner: false, isWritable: true },
91
+ { pubkey: manager, isSigner: false, isWritable: false },
92
+ { pubkey: systemProgram, isSigner: false, isWritable: false },
93
+ ],
94
+ programId,
95
+ data: constants_1.IX_ADD_MANAGER,
96
+ });
97
+ }
98
+ function createRemoveManagerIx(args, programId = constants_1.PROGRAM_ID) {
99
+ const { admin, strategyState, managerRole, systemProgram = web3_js_1.SystemProgram.programId, } = args;
100
+ return new web3_js_1.TransactionInstruction({
101
+ keys: [
102
+ { pubkey: admin, isSigner: true, isWritable: true },
103
+ { pubkey: strategyState, isSigner: false, isWritable: false },
104
+ { pubkey: managerRole, isSigner: false, isWritable: true },
105
+ { pubkey: systemProgram, isSigner: false, isWritable: false },
106
+ ],
107
+ programId,
108
+ data: constants_1.IX_REMOVE_MANAGER,
109
+ });
110
+ }
111
+ function createInitPositionIx(args, programId = constants_1.PROGRAM_ID) {
112
+ const { strategyState, position, stv, payer, systemProgram = web3_js_1.SystemProgram.programId, } = args;
113
+ return new web3_js_1.TransactionInstruction({
114
+ keys: [
115
+ { pubkey: strategyState, isSigner: false, isWritable: false },
116
+ { pubkey: position, isSigner: false, isWritable: true },
117
+ { pubkey: stv, isSigner: true, isWritable: false },
118
+ { pubkey: payer, isSigner: true, isWritable: true },
119
+ { pubkey: systemProgram, isSigner: false, isWritable: false },
120
+ ],
121
+ programId,
122
+ data: constants_1.IX_INIT_POSITION,
123
+ });
124
+ }
125
+ function createClosePositionIx(args, programId = constants_1.PROGRAM_ID) {
126
+ return new web3_js_1.TransactionInstruction({
127
+ keys: [
128
+ { pubkey: args.strategyState, isSigner: false, isWritable: false },
129
+ { pubkey: args.position, isSigner: false, isWritable: true },
130
+ { pubkey: args.stv, isSigner: true, isWritable: true },
131
+ ],
132
+ programId,
133
+ data: constants_1.IX_CLOSE_POSITION,
134
+ });
135
+ }
136
+ function createDepositIx(args, programId = constants_1.PROGRAM_ID) {
137
+ const data = [...constants_1.IX_DEPOSIT];
138
+ (0, buffer_1.writeU64)(data, args.amount);
139
+ return new web3_js_1.TransactionInstruction({
140
+ keys: [
141
+ { pubkey: args.strategyState, isSigner: false, isWritable: true },
142
+ { pubkey: args.position, isSigner: false, isWritable: true },
143
+ { pubkey: args.stv, isSigner: true, isWritable: false },
144
+ ],
145
+ programId,
146
+ data: Buffer.from(data),
147
+ });
148
+ }
149
+ function createWithdrawIx(args, programId = constants_1.PROGRAM_ID) {
150
+ const data = [...constants_1.IX_WITHDRAW];
151
+ (0, buffer_1.writeU64)(data, args.shares);
152
+ return new web3_js_1.TransactionInstruction({
153
+ keys: [
154
+ { pubkey: args.strategyState, isSigner: false, isWritable: true },
155
+ { pubkey: args.position, isSigner: false, isWritable: true },
156
+ { pubkey: args.stv, isSigner: true, isWritable: false },
157
+ { pubkey: args.strategyBaseAta, isSigner: false, isWritable: true },
158
+ { pubkey: args.destAta, isSigner: false, isWritable: true },
159
+ { pubkey: args.baseMint, isSigner: false, isWritable: false },
160
+ { pubkey: args.tokenProgram, isSigner: false, isWritable: false },
161
+ ],
162
+ programId,
163
+ data: Buffer.from(data),
164
+ });
165
+ }
166
+ function buildRouteIx(disc, args, programId) {
167
+ const data = [...disc];
168
+ (0, buffer_1.writeU64)(data, args.amount);
169
+ return new web3_js_1.TransactionInstruction({
170
+ keys: [
171
+ { pubkey: args.manager, isSigner: true, isWritable: false },
172
+ { pubkey: args.managerRole, isSigner: false, isWritable: false },
173
+ { pubkey: args.strategyState, isSigner: false, isWritable: false },
174
+ { pubkey: args.protocolVault, isSigner: false, isWritable: false },
175
+ { pubkey: args.strategyBaseAta, isSigner: false, isWritable: true },
176
+ { pubkey: args.baseMint, isSigner: false, isWritable: false },
177
+ { pubkey: args.tokenProgram, isSigner: false, isWritable: false },
178
+ { pubkey: args.adapterProgram, isSigner: false, isWritable: false },
179
+ ...args.remainingAccounts,
180
+ ],
181
+ programId,
182
+ data: Buffer.from(data),
183
+ });
184
+ }
185
+ function createRouteDepositIx(args, programId = constants_1.PROGRAM_ID) {
186
+ return buildRouteIx(constants_1.IX_ROUTE_DEPOSIT, args, programId);
187
+ }
188
+ function createRouteWithdrawIx(args, programId = constants_1.PROGRAM_ID) {
189
+ return buildRouteIx(constants_1.IX_ROUTE_WITHDRAW, args, programId);
190
+ }
@@ -0,0 +1,20 @@
1
+ import { PublicKey, TransactionInstruction, AddressLookupTableAccount } from "@solana/web3.js";
2
+ import type { SolanaConnection } from "../common/connection";
3
+ import type { LendStrategyState } from "./types";
4
+ import type { PerProtocolReadAumAccounts } from "./update-aum";
5
+ /**
6
+ * Build `extendLookupTable` instructions for every account touched by
7
+ * update_aum / route_* flows on a given strategy:
8
+ * - lend program ID
9
+ * - each unique adapter program (from ProtocolVault + extras)
10
+ * - each ProtocolVault PDA
11
+ * - each protocol_state
12
+ * - per-protocol adapter-specific accounts (caller-supplied — not stored on-chain in v2)
13
+ *
14
+ * Batched at ≤30 addresses per ix.
15
+ */
16
+ export declare function buildElementalLendLutExtendIxs(connection: SolanaConnection, payer: PublicKey, lutAddress: PublicKey, strategy: LendStrategyState, strategyStatePda: PublicKey, perProtocolReadAumAccounts: PerProtocolReadAumAccounts, extraAdapterPrograms?: PublicKey[], programId?: PublicKey): Promise<TransactionInstruction[]>;
17
+ /**
18
+ * Fetch an existing ALT for use in VersionedTransaction compilation.
19
+ */
20
+ export declare function resolveElementalLendLut(connection: Pick<import("@solana/web3.js").Connection, "getAddressLookupTable">, lutAddress: PublicKey): Promise<AddressLookupTableAccount>;
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildElementalLendLutExtendIxs = buildElementalLendLutExtendIxs;
4
+ exports.resolveElementalLendLut = resolveElementalLendLut;
5
+ const web3_js_1 = require("@solana/web3.js");
6
+ const constants_1 = require("./constants");
7
+ const accounts_1 = require("./accounts");
8
+ const MAX_LUT_EXTEND_PER_IX = 30;
9
+ /**
10
+ * Build `extendLookupTable` instructions for every account touched by
11
+ * update_aum / route_* flows on a given strategy:
12
+ * - lend program ID
13
+ * - each unique adapter program (from ProtocolVault + extras)
14
+ * - each ProtocolVault PDA
15
+ * - each protocol_state
16
+ * - per-protocol adapter-specific accounts (caller-supplied — not stored on-chain in v2)
17
+ *
18
+ * Batched at ≤30 addresses per ix.
19
+ */
20
+ async function buildElementalLendLutExtendIxs(connection, payer, lutAddress, strategy, strategyStatePda, perProtocolReadAumAccounts, extraAdapterPrograms = [], programId = constants_1.PROGRAM_ID) {
21
+ const keys = [programId];
22
+ if (strategy.protocolCount > 0) {
23
+ const pvs = await (0, accounts_1.fetchAllProtocolVaults)(connection, strategyStatePda, strategy.protocolCount, programId);
24
+ for (let i = 0; i < pvs.length; i++) {
25
+ const [pvPda, pv] = pvs[i];
26
+ keys.push(pvPda);
27
+ keys.push(pv.adapterProgram);
28
+ keys.push(pv.protocolState);
29
+ const reads = perProtocolReadAumAccounts[i];
30
+ if (reads)
31
+ for (const k of reads)
32
+ keys.push(k);
33
+ }
34
+ }
35
+ for (const p of extraAdapterPrograms)
36
+ keys.push(p);
37
+ const seen = new Set();
38
+ const unique = keys.filter((k) => {
39
+ const s = k.toBase58();
40
+ if (seen.has(s))
41
+ return false;
42
+ seen.add(s);
43
+ return true;
44
+ });
45
+ const ixs = [];
46
+ for (let i = 0; i < unique.length; i += MAX_LUT_EXTEND_PER_IX) {
47
+ ixs.push(web3_js_1.AddressLookupTableProgram.extendLookupTable({
48
+ payer,
49
+ authority: payer,
50
+ lookupTable: lutAddress,
51
+ addresses: unique.slice(i, i + MAX_LUT_EXTEND_PER_IX),
52
+ }));
53
+ }
54
+ return ixs;
55
+ }
56
+ /**
57
+ * Fetch an existing ALT for use in VersionedTransaction compilation.
58
+ */
59
+ async function resolveElementalLendLut(connection, lutAddress) {
60
+ const { value } = await connection.getAddressLookupTable(lutAddress);
61
+ if (!value) {
62
+ throw new Error(`LUT not found: ${lutAddress.toBase58()}`);
63
+ }
64
+ return value;
65
+ }
@@ -0,0 +1,9 @@
1
+ import { PublicKey } from "@solana/web3.js";
2
+ /** StrategyState PDA: ["strategy_state", base_mint]. */
3
+ export declare function deriveStrategyState(baseMint: PublicKey, programId?: PublicKey): [PublicKey, number];
4
+ /** ProtocolVault PDA: ["protocol", strategy_state, [index]]. */
5
+ export declare function deriveProtocolVault(strategyState: PublicKey, index: number, programId?: PublicKey): [PublicKey, number];
6
+ /** ManagerRole PDA: ["manager", strategy_state, manager]. */
7
+ export declare function deriveManagerRole(strategyState: PublicKey, manager: PublicKey, programId?: PublicKey): [PublicKey, number];
8
+ /** StvPosition PDA: ["position", stv]. */
9
+ export declare function deriveStvPosition(stv: PublicKey, programId?: PublicKey): [PublicKey, number];
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deriveStrategyState = deriveStrategyState;
4
+ exports.deriveProtocolVault = deriveProtocolVault;
5
+ exports.deriveManagerRole = deriveManagerRole;
6
+ exports.deriveStvPosition = deriveStvPosition;
7
+ const web3_js_1 = require("@solana/web3.js");
8
+ const constants_1 = require("./constants");
9
+ /** StrategyState PDA: ["strategy_state", base_mint]. */
10
+ function deriveStrategyState(baseMint, programId = constants_1.PROGRAM_ID) {
11
+ return web3_js_1.PublicKey.findProgramAddressSync([constants_1.STRATEGY_STATE_SEED, baseMint.toBuffer()], programId);
12
+ }
13
+ /** ProtocolVault PDA: ["protocol", strategy_state, [index]]. */
14
+ function deriveProtocolVault(strategyState, index, programId = constants_1.PROGRAM_ID) {
15
+ if (index < 0 || index > 0xff) {
16
+ throw new RangeError(`ProtocolVault index out of range: ${index}`);
17
+ }
18
+ return web3_js_1.PublicKey.findProgramAddressSync([constants_1.PROTOCOL_VAULT_SEED, strategyState.toBuffer(), Buffer.from([index])], programId);
19
+ }
20
+ /** ManagerRole PDA: ["manager", strategy_state, manager]. */
21
+ function deriveManagerRole(strategyState, manager, programId = constants_1.PROGRAM_ID) {
22
+ return web3_js_1.PublicKey.findProgramAddressSync([constants_1.MANAGER_SEED, strategyState.toBuffer(), manager.toBuffer()], programId);
23
+ }
24
+ /** StvPosition PDA: ["position", stv]. */
25
+ function deriveStvPosition(stv, programId = constants_1.PROGRAM_ID) {
26
+ return web3_js_1.PublicKey.findProgramAddressSync([constants_1.POSITION_SEED, stv.toBuffer()], programId);
27
+ }
@@ -0,0 +1,105 @@
1
+ import { PublicKey } from "@solana/web3.js";
2
+ import BN from "bn.js";
3
+ import type { StrategyStateHeader } from "../common/strategy-interface";
4
+ /** LendStrategyState v2 (280 bytes). */
5
+ export interface LendStrategyState extends StrategyStateHeader {
6
+ admin: PublicKey;
7
+ protocolCount: number;
8
+ }
9
+ /**
10
+ * ProtocolVault (224 bytes). Per-protocol adapter registration.
11
+ * Core pins only `protocolState`; everything else is validated adapter-side.
12
+ */
13
+ export interface ProtocolVault {
14
+ strategyState: PublicKey;
15
+ adapterProgram: PublicKey;
16
+ protocolState: PublicKey;
17
+ index: number;
18
+ bump: number;
19
+ readAumAccountCount: number;
20
+ }
21
+ export interface ManagerRole {
22
+ strategyState: PublicKey;
23
+ manager: PublicKey;
24
+ bump: number;
25
+ }
26
+ export type { StvPosition } from "../common/strategy-interface";
27
+ export interface StrategyInitializedEvent {
28
+ name: "StrategyInitialized";
29
+ baseMint: PublicKey;
30
+ authority: PublicKey;
31
+ admin: PublicKey;
32
+ }
33
+ export interface StrategyUpdatedEvent {
34
+ name: "StrategyUpdated";
35
+ baseMint: PublicKey;
36
+ newAdmin: PublicKey | null;
37
+ newFlags: number | null;
38
+ }
39
+ export interface AdapterRegisteredEvent {
40
+ name: "AdapterRegistered";
41
+ baseMint: PublicKey;
42
+ index: number;
43
+ adapterProgram: PublicKey;
44
+ protocolState: PublicKey;
45
+ }
46
+ export interface AdapterDeregisteredEvent {
47
+ name: "AdapterDeregistered";
48
+ baseMint: PublicKey;
49
+ index: number;
50
+ adapterProgram: PublicKey;
51
+ }
52
+ export interface RouteDepositedEvent {
53
+ name: "RouteDeposited";
54
+ baseMint: PublicKey;
55
+ protocolIndex: number;
56
+ amount: BN;
57
+ actualDeposited: BN;
58
+ }
59
+ export interface RouteWithdrawnEvent {
60
+ name: "RouteWithdrawn";
61
+ baseMint: PublicKey;
62
+ protocolIndex: number;
63
+ amount: BN;
64
+ actualWithdrawn: BN;
65
+ }
66
+ export interface AumUpdatedEvent {
67
+ name: "AumUpdated";
68
+ baseMint: PublicKey;
69
+ totalAum: BN;
70
+ pps: BN;
71
+ baseBalance: BN;
72
+ /** Sum of protocol AUM values computed this CPI (not a cached value). */
73
+ protocolAumSum: BN;
74
+ }
75
+ export interface DepositedEvent {
76
+ name: "Deposited";
77
+ stv: PublicKey;
78
+ amount: BN;
79
+ sharesMinted: BN;
80
+ }
81
+ export interface WithdrawnEvent {
82
+ name: "Withdrawn";
83
+ stv: PublicKey;
84
+ shares: BN;
85
+ baseAmount: BN;
86
+ }
87
+ export interface PositionInitializedEvent {
88
+ name: "PositionInitialized";
89
+ stv: PublicKey;
90
+ }
91
+ export interface PositionClosedEvent {
92
+ name: "PositionClosed";
93
+ stv: PublicKey;
94
+ }
95
+ export interface ManagerAddedEvent {
96
+ name: "ManagerAdded";
97
+ strategyState: PublicKey;
98
+ manager: PublicKey;
99
+ }
100
+ export interface ManagerRemovedEvent {
101
+ name: "ManagerRemoved";
102
+ strategyState: PublicKey;
103
+ manager: PublicKey;
104
+ }
105
+ export type LendV2Event = StrategyInitializedEvent | StrategyUpdatedEvent | AdapterRegisteredEvent | AdapterDeregisteredEvent | RouteDepositedEvent | RouteWithdrawnEvent | AumUpdatedEvent | DepositedEvent | WithdrawnEvent | PositionInitializedEvent | PositionClosedEvent | ManagerAddedEvent | ManagerRemovedEvent;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,29 @@
1
+ import { PublicKey, TransactionInstruction, AccountMeta } from "@solana/web3.js";
2
+ import type { SolanaConnection } from "../common/connection";
3
+ import type { LendStrategyState, ProtocolVault } from "./types";
4
+ /**
5
+ * Per-protocol map of adapter-specific accounts appended after
6
+ * `[protocol_vault, adapter_program]` in update_aum's remaining_accounts.
7
+ *
8
+ * Keyed by protocol index. First account MUST equal the registered
9
+ * protocol_state (enforced by core). Subsequent accounts adapter-validated.
10
+ * Length must equal `ProtocolVault.readAumAccountCount`.
11
+ */
12
+ export type PerProtocolReadAumAccounts = Record<number, PublicKey[]>;
13
+ /**
14
+ * Build the update_aum remaining_accounts tail.
15
+ *
16
+ * Layout per protocol i in 0..protocol_count:
17
+ * [protocol_vault_i, adapter_program_i, ...perProtocolReadAumAccounts[i]]
18
+ */
19
+ export declare function buildUpdateAumRemainingAccounts(connection: SolanaConnection, strategy: LendStrategyState, strategyStatePda: PublicKey, perProtocolReadAumAccounts: PerProtocolReadAumAccounts, programId?: PublicKey): Promise<AccountMeta[]>;
20
+ /** Sync variant when the caller already has ProtocolVault data cached. */
21
+ export declare function buildUpdateAumRemainingAccountsSync(strategy: LendStrategyState, strategyStatePda: PublicKey, protocolVaults: ProtocolVault[], perProtocolReadAumAccounts: PerProtocolReadAumAccounts, programId?: PublicKey): AccountMeta[];
22
+ export interface UpdateAumArgs {
23
+ strategyState: PublicKey;
24
+ stv: PublicKey;
25
+ strategyBaseAta: PublicKey;
26
+ baseMint: PublicKey;
27
+ remainingAccounts: AccountMeta[];
28
+ }
29
+ export declare function createUpdateAumIx(args: UpdateAumArgs, programId?: PublicKey): TransactionInstruction;
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildUpdateAumRemainingAccounts = buildUpdateAumRemainingAccounts;
4
+ exports.buildUpdateAumRemainingAccountsSync = buildUpdateAumRemainingAccountsSync;
5
+ exports.createUpdateAumIx = createUpdateAumIx;
6
+ const web3_js_1 = require("@solana/web3.js");
7
+ const constants_1 = require("./constants");
8
+ const accounts_1 = require("./accounts");
9
+ const pda_1 = require("./pda");
10
+ /**
11
+ * Build the update_aum remaining_accounts tail.
12
+ *
13
+ * Layout per protocol i in 0..protocol_count:
14
+ * [protocol_vault_i, adapter_program_i, ...perProtocolReadAumAccounts[i]]
15
+ */
16
+ async function buildUpdateAumRemainingAccounts(connection, strategy, strategyStatePda, perProtocolReadAumAccounts, programId = constants_1.PROGRAM_ID) {
17
+ const out = [];
18
+ if (strategy.protocolCount === 0)
19
+ return out;
20
+ const pvs = await (0, accounts_1.fetchAllProtocolVaults)(connection, strategyStatePda, strategy.protocolCount, programId);
21
+ for (let i = 0; i < pvs.length; i++) {
22
+ const [pvPda, pv] = pvs[i];
23
+ const reads = perProtocolReadAumAccounts[i];
24
+ if (!reads) {
25
+ throw new Error(`buildUpdateAumRemainingAccounts: missing read_aum accounts for protocol ${i}`);
26
+ }
27
+ if (reads.length !== pv.readAumAccountCount) {
28
+ throw new Error(`buildUpdateAumRemainingAccounts: protocol ${i} expects ` +
29
+ `${pv.readAumAccountCount} read_aum accounts, got ${reads.length}`);
30
+ }
31
+ if (!reads[0].equals(pv.protocolState)) {
32
+ throw new Error(`buildUpdateAumRemainingAccounts: protocol ${i} first read_aum account must equal ` +
33
+ `protocol_state ${pv.protocolState.toBase58()}, got ${reads[0].toBase58()}`);
34
+ }
35
+ out.push({ pubkey: pvPda, isSigner: false, isWritable: false });
36
+ out.push({ pubkey: pv.adapterProgram, isSigner: false, isWritable: false });
37
+ for (const k of reads) {
38
+ out.push({ pubkey: k, isSigner: false, isWritable: false });
39
+ }
40
+ }
41
+ return out;
42
+ }
43
+ /** Sync variant when the caller already has ProtocolVault data cached. */
44
+ function buildUpdateAumRemainingAccountsSync(strategy, strategyStatePda, protocolVaults, perProtocolReadAumAccounts, programId = constants_1.PROGRAM_ID) {
45
+ if (protocolVaults.length !== strategy.protocolCount) {
46
+ throw new Error(`protocolVaults length ${protocolVaults.length} does not match strategy.protocolCount ${strategy.protocolCount}`);
47
+ }
48
+ const out = [];
49
+ for (let i = 0; i < protocolVaults.length; i++) {
50
+ const pv = protocolVaults[i];
51
+ const [pvPda] = (0, pda_1.deriveProtocolVault)(strategyStatePda, i, programId);
52
+ const reads = perProtocolReadAumAccounts[i];
53
+ if (!reads) {
54
+ throw new Error(`missing read_aum accounts for protocol ${i}`);
55
+ }
56
+ if (reads.length !== pv.readAumAccountCount) {
57
+ throw new Error(`protocol ${i} expects ${pv.readAumAccountCount} read_aum accounts, got ${reads.length}`);
58
+ }
59
+ if (!reads[0].equals(pv.protocolState)) {
60
+ throw new Error(`protocol ${i} first read_aum account must equal protocol_state`);
61
+ }
62
+ out.push({ pubkey: pvPda, isSigner: false, isWritable: false });
63
+ out.push({ pubkey: pv.adapterProgram, isSigner: false, isWritable: false });
64
+ for (const k of reads) {
65
+ out.push({ pubkey: k, isSigner: false, isWritable: false });
66
+ }
67
+ }
68
+ return out;
69
+ }
70
+ function createUpdateAumIx(args, programId = constants_1.PROGRAM_ID) {
71
+ return new web3_js_1.TransactionInstruction({
72
+ keys: [
73
+ { pubkey: args.strategyState, isSigner: false, isWritable: true },
74
+ { pubkey: args.stv, isSigner: true, isWritable: false },
75
+ { pubkey: args.strategyBaseAta, isSigner: false, isWritable: false },
76
+ { pubkey: args.baseMint, isSigner: false, isWritable: false },
77
+ ...args.remainingAccounts,
78
+ ],
79
+ programId,
80
+ data: constants_1.IX_UPDATE_AUM,
81
+ });
82
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * as common from "./common";
2
2
  export * as pStvCore from "./p-stv-core";
3
3
  export * as elementalLend from "./elemental-lend";
4
+ export * as elementalLendV2 from "./elemental-lend-v2";
4
5
  export * as jlpdStrategy from "./jlpd-strategy";
package/dist/index.js CHANGED
@@ -33,8 +33,9 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.jlpdStrategy = exports.elementalLend = exports.pStvCore = exports.common = void 0;
36
+ exports.jlpdStrategy = exports.elementalLendV2 = exports.elementalLend = exports.pStvCore = exports.common = void 0;
37
37
  exports.common = __importStar(require("./common"));
38
38
  exports.pStvCore = __importStar(require("./p-stv-core"));
39
39
  exports.elementalLend = __importStar(require("./elemental-lend"));
40
+ exports.elementalLendV2 = __importStar(require("./elemental-lend-v2"));
40
41
  exports.jlpdStrategy = __importStar(require("./jlpd-strategy"));
@@ -71,3 +71,85 @@ export declare function computeAddLiquidityFee(args: {
71
71
  isDiscount: boolean;
72
72
  };
73
73
  export declare function fetchJlpCustodyData(connection: SolanaConnection): Promise<JlpData>;
74
+ /** Public symbol used by the effective-weights API.
75
+ *
76
+ * Note: JLP custody is internally named "WBTC" but represents BTC exposure
77
+ * for sensitivity purposes — surfaced as `'BTC'` here per spec. */
78
+ export type EffectiveWeightSymbol = "BTC" | "ETH" | "SOL" | "USDC" | "USDT";
79
+ export interface AssetEffectiveWeight {
80
+ mint: PublicKey;
81
+ symbol: EffectiveWeightSymbol;
82
+ /** Effective USD contribution, normalized to 8 decimals. */
83
+ effUsd: bigint;
84
+ /** Share of total effective USD, in basis points (0–10000). */
85
+ effShareBps: number;
86
+ /** True if `(owned − locked) < 0`. Spot term clamped to 0 in `effUsd`. */
87
+ spotClamped: boolean;
88
+ }
89
+ export interface JlpEffectiveWeights {
90
+ assets: AssetEffectiveWeight[];
91
+ /** Sum of all `effUsd` values, 8 decimals. */
92
+ totalEffUsd: bigint;
93
+ /** Total pool aumUsd (including `guaranteed_usd`), 8 decimals — context only. */
94
+ totalAumUsd: bigint;
95
+ }
96
+ /** Inputs needed to compute effective USD for one custody.
97
+ *
98
+ * Decoupled from on-chain fetching so unit tests can drive the math directly. */
99
+ export interface EffectiveWeightInput {
100
+ owned: bigint;
101
+ locked: bigint;
102
+ /** Raw debt u128 (DEBT_MULTIPLIER-scaled by 1e9 internally, then by 10^decimals). */
103
+ debt: bigint;
104
+ /** Raw borrow-lend interests accrued u128 (same scale as `debt`). */
105
+ borrowLendInterestsAccrued: bigint;
106
+ shortSizeUsd: bigint;
107
+ avgShortPriceUsd: bigint;
108
+ guaranteedUsd: bigint;
109
+ decimals: number;
110
+ /** Price scaled to 8 decimals (float price × 10^8, as bigint). */
111
+ priceScaled8: bigint;
112
+ }
113
+ export interface EffectiveWeightOutput {
114
+ /** (owned + netDebt − locked) × price, normalized to 8-decimal USD. Clamped to 0 if negative. */
115
+ spotEffUsd: bigint;
116
+ /** shortSize × price / avgShortPrice, normalized to 8-decimal USD. 0 if no shorts. */
117
+ shortEffUsd: bigint;
118
+ /** spotEffUsd + shortEffUsd. */
119
+ effUsd: bigint;
120
+ /** True if (owned + netDebt − locked) < 0 — spot term was clamped. */
121
+ spotClamped: boolean;
122
+ /** netDebt tokens applied to spot term (already converted to token-base units). */
123
+ netDebtTokens: bigint;
124
+ }
125
+ /** Compute effective USD (price-sensitivity-weighted) for a single custody.
126
+ *
127
+ * Formula (in 8-decimal USD):
128
+ * netDebtTokens = max(debt − borrowLendInterestsAccrued, 0) / DEBT_MULTIPLIER
129
+ * spot = (owned + netDebtTokens − locked) × price_8dec / 10^decimals
130
+ * short = shortSize_6dec × price_8dec / avgShortPrice_6dec (zeroed if either operand is 0)
131
+ * effUsd = max(spot, 0) + short
132
+ *
133
+ * Algebra for unit normalization:
134
+ * - owned/locked/netDebt is in 10^decimals base units; price is 10^8 USD.
135
+ * spot = (owned + netDebt − locked) × price_8dec / 10^decimals → 10^8 USD ✓
136
+ * - debt is stored as u128 scaled by DEBT_MULTIPLIER (1e9) on top of 10^decimals.
137
+ * netDebtTokens = (debt − borrowLendInterestsAccrued) / DEBT_MULTIPLIER
138
+ * (integer division — small rounding under one base unit, acceptable).
139
+ * - shortSize and avgShortPrice are both 10^6; ratio is dimensionless.
140
+ * short = shortSize × price_8dec / avgShortPrice → 10^8 USD ✓
141
+ */
142
+ export declare function computeEffectiveUsd(input: EffectiveWeightInput): EffectiveWeightOutput;
143
+ /**
144
+ * Fetch JLP pool effective-weight composition.
145
+ *
146
+ * Returns price-sensitivity-weighted shares per asset, dropping `guaranteed_usd`
147
+ * from the per-asset weight calculation. Suitable for rebalance planners that
148
+ * want to track the pool's true delta-1 composition rather than reported aumUsd.
149
+ *
150
+ * Reuses the same on-chain custody parser and Jupiter Price API source as
151
+ * `fetchJlpCustodyData` to keep numbers consistent across callers.
152
+ *
153
+ * @returns assets in fixed order: BTC, ETH, SOL, USDC, USDT.
154
+ */
155
+ export declare function fetchJlpEffectiveWeights(connection: SolanaConnection): Promise<JlpEffectiveWeights>;