@haven-fi/solauto-sdk 1.0.32 → 1.0.34

Sign up to get free protection for your applications and to get access to all the features.
@@ -6,16 +6,15 @@ import { DCASettingsInpArgs, PositionState, SolautoActionArgs, SolautoRebalanceT
6
6
  import { MarginfiAccount } from "../marginfi-sdk";
7
7
  import { JupSwapDetails } from "../utils/jupiterUtils";
8
8
  import { FlashLoanDetails } from "../utils/solauto/rebalanceUtils";
9
- import { WalletAdapter } from "@metaplex-foundation/umi-signer-wallet-adapters";
10
9
  export interface SolautoMarginfiClientArgs extends SolautoClientArgs {
11
10
  marginfiAccount?: PublicKey | Signer;
12
11
  marginfiAccountSeedIdx?: bigint;
13
12
  marginfiGroup?: PublicKey;
14
13
  }
15
- export declare function newSolautoMarginfiPositionArgs(positionId: number, signer: Signer | undefined, wallet: WalletAdapter | undefined, supplyMint: PublicKey, debtMint: PublicKey, referredByAuthority?: PublicKey): SolautoMarginfiClientArgs;
16
14
  export declare class SolautoMarginfiClient extends SolautoClient {
15
+ private initialized;
17
16
  marginfiProgram: PublicKey;
18
- marginfiAccountSeedIdx?: bigint;
17
+ marginfiAccountSeedIdx: bigint;
19
18
  marginfiAccount: PublicKey | Signer;
20
19
  marginfiAccountPk: PublicKey;
21
20
  marginfiGroup: PublicKey;
@@ -25,6 +24,7 @@ export declare class SolautoMarginfiClient extends SolautoClient {
25
24
  intermediaryMarginfiAccountPk: PublicKey;
26
25
  intermediaryMarginfiAccount?: MarginfiAccount;
27
26
  initialize(args: SolautoMarginfiClientArgs): Promise<void>;
27
+ setIntermediaryMarginfiDetails(): Promise<void>;
28
28
  defaultLookupTables(): string[];
29
29
  lutAccountsToAdd(): PublicKey[];
30
30
  marginfiAccountInitialize(): TransactionBuilder;
@@ -1 +1 @@
1
- {"version":3,"file":"solautoMarginfiClient.d.ts","sourceRoot":"","sources":["../../src/clients/solautoMarginfiClient.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,MAAM,EACN,kBAAkB,EAMnB,MAAM,0BAA0B,CAAC;AAElC,OAAO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aAAa,EAAE,GAAG,GAAG,GAAG,EACxB,WAAW,EAAE,cAAc,EAC3B,aAAa,EAAE,wBAAwB,EACvC,2BAA2B,CAAC,EAAE,MAAM,EACpC,WAAW,CAAC,EAAE,MAAM,GACnB,kBAAkB;IAgDrB,WAAW,CACT,gBAAgB,EAAE,gBAAgB,EAClC,uBAAuB,EAAE,SAAS,GACjC,kBAAkB;IA2BrB,UAAU,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,kBAAkB;IA8ElE,iCAAiC,IAAI,kBAAkB;IASjD,qBAAqB,IAAI,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC;CAiBlE"}
@@ -1,9 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SolautoMarginfiClient = exports.newSolautoMarginfiPositionArgs = void 0;
3
+ exports.SolautoMarginfiClient = void 0;
4
4
  const umi_web3js_adapters_1 = require("@metaplex-foundation/umi-web3js-adapters");
5
5
  const umi_1 = require("@metaplex-foundation/umi");
6
- const umi_bundle_defaults_1 = require("@metaplex-foundation/umi-bundle-defaults");
7
6
  const web3_js_1 = require("@solana/web3.js");
8
7
  const solautoClient_1 = require("./solautoClient");
9
8
  const marginfiAccounts_1 = require("../constants/marginfiAccounts");
@@ -13,31 +12,25 @@ const generalUtils_1 = require("../utils/generalUtils");
13
12
  const marginfi_sdk_1 = require("../marginfi-sdk");
14
13
  const marginfiUtils_1 = require("../utils/marginfiUtils");
15
14
  const numberUtils_1 = require("../utils/numberUtils");
16
- function newSolautoMarginfiPositionArgs(positionId, signer, wallet, supplyMint, debtMint, referredByAuthority) {
17
- const umi = (0, umi_bundle_defaults_1.createUmi)((0, web3_js_1.clusterApiUrl)("mainnet-beta"));
18
- return {
19
- positionId,
20
- signer,
21
- wallet,
22
- marginfiAccount: positionId === 0
23
- ? (0, umi_1.createSignerFromKeypair)(umi, umi.eddsa.generateKeypair())
24
- : undefined,
25
- marginfiAccountSeedIdx: positionId > 0 ? (0, generalUtils_1.generateRandomU64)() : undefined,
26
- supplyMint: supplyMint,
27
- debtMint: debtMint,
28
- referredByAuthority,
29
- };
30
- }
31
- exports.newSolautoMarginfiPositionArgs = newSolautoMarginfiPositionArgs;
32
15
  class SolautoMarginfiClient extends solautoClient_1.SolautoClient {
16
+ constructor() {
17
+ super(...arguments);
18
+ this.initialized = false;
19
+ this.marginfiAccountSeedIdx = BigInt(0);
20
+ }
33
21
  async initialize(args) {
34
22
  await super.initialize(args, generated_1.LendingPlatform.Marginfi);
35
- this.marginfiAccountSeedIdx = args.marginfiAccountSeedIdx;
36
- this.marginfiAccount =
37
- this.marginfiAccountSeedIdx !== undefined
38
- ? await (0, accountUtils_1.getMarginfiAccountPDA)(this.solautoPosition, this.marginfiAccountSeedIdx)
39
- : args.marginfiAccount ??
40
- (0, umi_web3js_adapters_1.toWeb3JsPublicKey)(this.solautoPositionData.position.protocolAccount);
23
+ if (this.selfManaged) {
24
+ this.marginfiAccount =
25
+ args.marginfiAccount ??
26
+ (0, umi_1.createSignerFromKeypair)(this.umi, this.umi.eddsa.generateKeypair());
27
+ }
28
+ else {
29
+ this.marginfiAccountSeedIdx = (0, generalUtils_1.generateRandomU64)();
30
+ this.marginfiAccount = this.solautoPositionData
31
+ ? (0, umi_web3js_adapters_1.toWeb3JsPublicKey)(this.solautoPositionData.position.protocolAccount)
32
+ : await (0, accountUtils_1.getMarginfiAccountPDA)(this.solautoPosition, this.marginfiAccountSeedIdx);
33
+ }
41
34
  this.marginfiAccountPk =
42
35
  "publicKey" in this.marginfiAccount
43
36
  ? (0, umi_web3js_adapters_1.toWeb3JsPublicKey)(this.marginfiAccount.publicKey)
@@ -52,10 +45,18 @@ class SolautoMarginfiClient extends solautoClient_1.SolautoClient {
52
45
  this.marginfiDebtBankAccounts = (0, marginfiUtils_1.findMarginfiBankAccounts)({
53
46
  mint: this.debtMint.toString(),
54
47
  });
55
- const existingMarginfiAccounts = (await (0, marginfiUtils_1.getAllMarginfiAccountsByAuthority)(this.umi, (0, umi_web3js_adapters_1.toWeb3JsPublicKey)(this.signer.publicKey), false)).filter((x) => x.marginfiAccount.equals(this.marginfiAccountPk));
56
- const emptyMarginfiAccounts = (await (0, marginfi_sdk_1.safeFetchAllMarginfiAccount)(this.umi, existingMarginfiAccounts.map((x) => (0, umi_1.publicKey)(x.marginfiAccount)))).filter((x) => x.lendingAccount.balances.find((y) => y.bankPk.toString() !== web3_js_1.PublicKey.default.toString() &&
57
- (Math.round((0, numberUtils_1.bytesToI80F48)(y.assetShares.value)) != 0 ||
58
- Math.round((0, numberUtils_1.bytesToI80F48)(y.liabilityShares.value)) != 0)) === undefined);
48
+ if (!this.initialized) {
49
+ await this.setIntermediaryMarginfiDetails();
50
+ }
51
+ this.initialized = true;
52
+ }
53
+ async setIntermediaryMarginfiDetails() {
54
+ const existingMarginfiAccounts = (await (0, marginfiUtils_1.getAllMarginfiAccountsByAuthority)(this.umi, (0, umi_web3js_adapters_1.toWeb3JsPublicKey)(this.signer.publicKey), false)).filter((x) => !x.marginfiAccount.equals(this.marginfiAccountPk));
55
+ const emptyMarginfiAccounts = existingMarginfiAccounts.length > 0
56
+ ? (await (0, marginfi_sdk_1.safeFetchAllMarginfiAccount)(this.umi, existingMarginfiAccounts.map((x) => (0, umi_1.publicKey)(x.marginfiAccount)))).filter((x) => x.lendingAccount.balances.find((y) => y.bankPk.toString() !== web3_js_1.PublicKey.default.toString() &&
57
+ (Math.round((0, numberUtils_1.bytesToI80F48)(y.assetShares.value)) != 0 ||
58
+ Math.round((0, numberUtils_1.bytesToI80F48)(y.liabilityShares.value)) != 0)) === undefined)
59
+ : [];
59
60
  this.intermediaryMarginfiAccountSigner =
60
61
  emptyMarginfiAccounts.length > 0
61
62
  ? undefined
@@ -152,7 +153,6 @@ class SolautoMarginfiClient extends solautoClient_1.SolautoClient {
152
153
  marginfiProtocolInteractionIx(args) {
153
154
  switch (args.__kind) {
154
155
  case "Deposit": {
155
- console.log(args.fields[0]);
156
156
  return (0, marginfi_sdk_1.lendingAccountDeposit)(this.umi, {
157
157
  amount: args.fields[0],
158
158
  signer: this.signer,
@@ -2,7 +2,7 @@ import { TransactionBuilder, Umi } from "@metaplex-foundation/umi";
2
2
  import { Account as SplTokenAccount } from "@solana/spl-token";
3
3
  import { ReferralState } from "../generated";
4
4
  import { SolautoClient } from "../clients/solautoClient";
5
- export declare function rebalanceChoresBefore(client: SolautoClient, tx: TransactionBuilder): Promise<TransactionBuilder>;
5
+ export declare function rebalanceChoresBefore(client: SolautoClient, tx: TransactionBuilder, accountsGettingCreated: string[]): Promise<TransactionBuilder>;
6
6
  export declare function getTransactionChores(client: SolautoClient, tx: TransactionBuilder): Promise<[TransactionBuilder, TransactionBuilder]>;
7
7
  export declare function buildSolautoRebalanceTransaction(client: SolautoClient, targetLiqUtilizationRateBps?: number, attemptNum?: number): Promise<{
8
8
  tx: TransactionBuilder;
@@ -1 +1 @@
1
- {"version":3,"file":"transactionUtils.d.ts","sourceRoot":"","sources":["../../src/transactions/transactionUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,kBAAkB,EAClB,GAAG,EAGJ,MAAM,0BAA0B,CAAC;AAGlC,OAAO,EAGL,OAAO,IAAI,eAAe,EAC3B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAEL,aAAa,EAQd,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAqMzD,wBAAsB,qBAAqB,CACzC,MAAM,EAAE,aAAa,EACrB,EAAE,EAAE,kBAAkB,GACrB,OAAO,CAAC,kBAAkB,CAAC,CAgE7B;AAgKD,wBAAsB,oBAAoB,CACxC,MAAM,EAAE,aAAa,EACrB,EAAE,EAAE,kBAAkB,GACrB,OAAO,CAAC,CAAC,kBAAkB,EAAE,kBAAkB,CAAC,CAAC,CA0BnD;AAED,wBAAsB,gCAAgC,CACpD,MAAM,EAAE,aAAa,EACrB,2BAA2B,CAAC,EAAE,MAAM,EACpC,UAAU,CAAC,EAAE,MAAM,GAClB,OAAO,CACN;IACE,EAAE,EAAE,kBAAkB,CAAC;IACvB,oBAAoB,EAAE,MAAM,EAAE,CAAC;CAChC,GACD,SAAS,CACZ,CA2GA;AAED,wBAAsB,gCAAgC,CACpD,GAAG,EAAE,GAAG,EACR,aAAa,EAAE,aAAa,EAC5B,YAAY,EAAE,eAAe,GAC5B,OAAO,CAAC,CAAC,kBAAkB,EAAE,MAAM,EAAE,CAAC,CAAC,CA8BzC"}
1
+ {"version":3,"file":"transactionUtils.d.ts","sourceRoot":"","sources":["../../src/transactions/transactionUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,kBAAkB,EAClB,GAAG,EAGJ,MAAM,0BAA0B,CAAC;AAGlC,OAAO,EAGL,OAAO,IAAI,eAAe,EAC3B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAEL,aAAa,EASd,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAqMzD,wBAAsB,qBAAqB,CACzC,MAAM,EAAE,aAAa,EACrB,EAAE,EAAE,kBAAkB,EACtB,sBAAsB,EAAE,MAAM,EAAE,GAC/B,OAAO,CAAC,kBAAkB,CAAC,CAgG7B;AAmLD,wBAAsB,oBAAoB,CACxC,MAAM,EAAE,aAAa,EACrB,EAAE,EAAE,kBAAkB,GACrB,OAAO,CAAC,CAAC,kBAAkB,EAAE,kBAAkB,CAAC,CAAC,CA4BnD;AAED,wBAAsB,gCAAgC,CACpD,MAAM,EAAE,aAAa,EACrB,2BAA2B,CAAC,EAAE,MAAM,EACpC,UAAU,CAAC,EAAE,MAAM,GAClB,OAAO,CACN;IACE,EAAE,EAAE,kBAAkB,CAAC;IACvB,oBAAoB,EAAE,MAAM,EAAE,CAAC;CAChC,GACD,SAAS,CACZ,CA4GA;AAED,wBAAsB,gCAAgC,CACpD,GAAG,EAAE,GAAG,EACR,aAAa,EAAE,aAAa,EAC5B,YAAY,EAAE,eAAe,GAC5B,OAAO,CAAC,CAAC,kBAAkB,EAAE,MAAM,EAAE,CAAC,CAAC,CA8BzC"}
@@ -41,8 +41,7 @@ function getWSolUsage(client, solautoActions, initiatingDcaIn, cancellingDcaIn)
41
41
  return undefined;
42
42
  }
43
43
  }
44
- async function transactionChoresBefore(client, solautoActions, initiatingDcaIn) {
45
- const accountsGettingCreated = [];
44
+ async function transactionChoresBefore(client, accountsGettingCreated, solautoActions, initiatingDcaIn) {
46
45
  let chores = (0, umi_1.transactionBuilder)();
47
46
  if (client.authorityReferralStateData === null ||
48
47
  (client.referredByState !== undefined &&
@@ -54,7 +53,7 @@ async function transactionChoresBefore(client, solautoActions, initiatingDcaIn)
54
53
  chores = chores.add(client.updateReferralStatesIx());
55
54
  }
56
55
  if (client.selfManaged) {
57
- if (client.solautoPositionData === undefined) {
56
+ if (client.solautoPositionData === null) {
58
57
  chores = chores.add(client.openPosition());
59
58
  }
60
59
  else if (client.lendingPlatform === generated_1.LendingPlatform.Marginfi &&
@@ -111,14 +110,19 @@ async function transactionChoresBefore(client, solautoActions, initiatingDcaIn)
111
110
  }
112
111
  return chores;
113
112
  }
114
- async function rebalanceChoresBefore(client, tx) {
115
- const usesAccount = (key) => tx
116
- .getInstructions()
113
+ async function rebalanceChoresBefore(client, tx, accountsGettingCreated) {
114
+ const rebalanceInstructions = getRebalanceInstructions(tx);
115
+ if (rebalanceInstructions.length === 0) {
116
+ return (0, umi_1.transactionBuilder)();
117
+ }
118
+ const usesAccount = (key) => rebalanceInstructions
117
119
  .some((t) => t.keys.some((k) => (0, umi_web3js_adapters_1.toWeb3JsPublicKey)(k.pubkey).equals(key)));
118
120
  const checkReferralSupplyTa = client.referredBySupplyTa && usesAccount(client.referredBySupplyTa);
119
121
  const checkSolautoFeesTa = usesAccount(client.solautoFeesSupplyTa);
120
122
  const checkIntermediaryMfiAccount = client.lendingPlatform === generated_1.LendingPlatform.Marginfi &&
121
123
  usesAccount(client.intermediaryMarginfiAccountPk);
124
+ const checkSignerSupplyTa = client.selfManaged && usesAccount(client.signerSupplyTa);
125
+ const checkSignerDebtTa = client.selfManaged && usesAccount(client.signerSupplyTa);
122
126
  const accountsNeeded = [
123
127
  ...[checkReferralSupplyTa ? client.referredBySupplyTa : web3_js_1.PublicKey.default],
124
128
  ...[checkSolautoFeesTa ? client.solautoFeesSupplyTa : web3_js_1.PublicKey.default],
@@ -127,8 +131,10 @@ async function rebalanceChoresBefore(client, tx) {
127
131
  ? client.intermediaryMarginfiAccountPk
128
132
  : web3_js_1.PublicKey.default,
129
133
  ],
134
+ ...[checkSignerSupplyTa ? client.signerSupplyTa : web3_js_1.PublicKey.default],
135
+ ...[checkSignerDebtTa ? client.signerDebtTa : web3_js_1.PublicKey.default],
130
136
  ];
131
- const [referredBySupplyTa, solautoFeesSupplyTa, intermediaryMarginfiAccount] = await client.umi.rpc.getAccounts(accountsNeeded.map((x) => (0, umi_1.publicKey)(x ?? web3_js_1.PublicKey.default)));
137
+ const [referredBySupplyTa, solautoFeesSupplyTa, intermediaryMarginfiAccount, signerSupplyTa, signerDebtTa] = await client.umi.rpc.getAccounts(accountsNeeded.map((x) => (0, umi_1.publicKey)(x ?? web3_js_1.PublicKey.default)));
132
138
  let chores = (0, umi_1.transactionBuilder)();
133
139
  if (checkReferralSupplyTa && !(0, generalUtils_1.rpcAccountCreated)(referredBySupplyTa)) {
134
140
  client.log("Creating referred-by TA for ", client.supplyMint.toString());
@@ -142,6 +148,16 @@ async function rebalanceChoresBefore(client, tx) {
142
148
  !(0, generalUtils_1.rpcAccountCreated)(intermediaryMarginfiAccount)) {
143
149
  chores = chores.add(client.createIntermediaryMarginfiAccount());
144
150
  }
151
+ if (checkSignerSupplyTa && !(0, generalUtils_1.rpcAccountCreated)(signerSupplyTa) && !accountsGettingCreated.includes(signerSupplyTa.publicKey.toString())) {
152
+ client.log("Creating signer supply token account");
153
+ chores = chores.add((0, solanaUtils_1.createAssociatedTokenAccountUmiIx)(client.signer, (0, umi_web3js_adapters_1.toWeb3JsPublicKey)(client.signer.publicKey), client.supplyMint));
154
+ accountsGettingCreated.push(signerSupplyTa.publicKey.toString());
155
+ }
156
+ if (checkSignerDebtTa && !(0, generalUtils_1.rpcAccountCreated)(signerDebtTa) && !accountsGettingCreated.includes(signerDebtTa.publicKey.toString())) {
157
+ client.log("Creating signer debt token account");
158
+ chores = chores.add((0, solanaUtils_1.createAssociatedTokenAccountUmiIx)(client.signer, (0, umi_web3js_adapters_1.toWeb3JsPublicKey)(client.signer.publicKey), client.debtMint));
159
+ accountsGettingCreated.push(signerDebtTa.publicKey.toString());
160
+ }
145
161
  return chores;
146
162
  }
147
163
  exports.rebalanceChoresBefore = rebalanceChoresBefore;
@@ -153,6 +169,26 @@ function transactionChoresAfter(client, solautoActions, cancellingDcaIn) {
153
169
  }
154
170
  return chores;
155
171
  }
172
+ function getRebalanceInstructions(tx) {
173
+ return tx.getInstructions().filter((x) => {
174
+ if (x.programId === generated_1.SOLAUTO_PROGRAM_ID) {
175
+ try {
176
+ const serializer = (0, generated_1.getMarginfiRebalanceInstructionDataSerializer)();
177
+ const discriminator = serializer.serialize({
178
+ limitGapBps: 0,
179
+ rebalanceType: generated_1.SolautoRebalanceType.None,
180
+ targetLiqUtilizationRateBps: 0
181
+ })[0];
182
+ const [data, _] = serializer.deserialize(x.data);
183
+ if (data.discriminator === discriminator) {
184
+ return true;
185
+ }
186
+ }
187
+ catch { }
188
+ return false;
189
+ }
190
+ });
191
+ }
156
192
  function getSolautoActions(tx) {
157
193
  let solautoActions = [];
158
194
  tx.getInstructions().forEach((x) => {
@@ -162,8 +198,7 @@ function getSolautoActions(tx) {
162
198
  const discriminator = serializer
163
199
  .serialize({
164
200
  solautoAction: (0, generated_1.solautoAction)("Deposit", [BigInt(0)]),
165
- })
166
- .slice(0, 1)[0];
201
+ })[0];
167
202
  const [data, _] = serializer.deserialize(x.data);
168
203
  if (data.discriminator === discriminator) {
169
204
  solautoActions?.push(data.solautoAction);
@@ -268,12 +303,13 @@ function getSolautoActions(tx) {
268
303
  async function getTransactionChores(client, tx) {
269
304
  let choresBefore = (0, umi_1.transactionBuilder)();
270
305
  let choresAfter = (0, umi_1.transactionBuilder)();
306
+ const accountsGettingCreated = [];
271
307
  const solautoActions = getSolautoActions(tx);
272
308
  choresBefore = choresBefore.add([
273
- await transactionChoresBefore(client, solautoActions, client.livePositionUpdates.debtTaBalanceAdjustment > 0
309
+ await transactionChoresBefore(client, accountsGettingCreated, solautoActions, client.livePositionUpdates.debtTaBalanceAdjustment > 0
274
310
  ? client.livePositionUpdates.debtTaBalanceAdjustment
275
311
  : undefined),
276
- await rebalanceChoresBefore(client, tx),
312
+ await rebalanceChoresBefore(client, tx, accountsGettingCreated),
277
313
  ]);
278
314
  choresAfter = choresAfter.add(transactionChoresAfter(client, solautoActions, client.livePositionUpdates.debtTaBalanceAdjustment < 0));
279
315
  return [choresBefore, choresAfter];
@@ -281,10 +317,11 @@ async function getTransactionChores(client, tx) {
281
317
  exports.getTransactionChores = getTransactionChores;
282
318
  async function buildSolautoRebalanceTransaction(client, targetLiqUtilizationRateBps, attemptNum) {
283
319
  client.solautoPositionState = await client.getFreshPositionState();
284
- if (targetLiqUtilizationRateBps === undefined &&
285
- !(0, generalUtils_2.eligibileForRebalance)(client.solautoPositionState, client.livePositionUpdates.settings ??
286
- client.solautoPositionData?.position.settingParams, client.livePositionUpdates.activeDca ??
287
- client.solautoPositionData?.position.dca)) {
320
+ if (client.solautoPositionState?.supply.amountUsed.baseUnit === BigInt(0) ||
321
+ (targetLiqUtilizationRateBps === undefined &&
322
+ !(0, generalUtils_2.eligibileForRebalance)(client.solautoPositionState, client.livePositionUpdates.settings ??
323
+ client.solautoPositionData?.position.settingParams, client.livePositionUpdates.activeDca ??
324
+ client.solautoPositionData?.position.dca))) {
288
325
  client.log("Not eligible for a rebalance");
289
326
  return undefined;
290
327
  }
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const numberUtils_1 = require("./numberUtils");
4
4
  // TODO delete this file
5
- function check() {
5
+ async function check() {
6
6
  let supply = 458948;
7
7
  let debt = 212846;
8
8
  let supply_weight = 0.899999976158142;
@@ -8,7 +8,7 @@ export declare function findMarginfiBankAccounts({ mint, bank, }: {
8
8
  mint?: string;
9
9
  bank?: string;
10
10
  }): MarginfiTokenAccounts;
11
- export declare function getMaxLtvAndLiqThreshold(supplyBank: Bank, debtBank: Bank, supplyPrice?: number): Promise<[number, number]>;
11
+ export declare function getMaxLtvAndLiqThreshold(supplyBank: Bank, debtBank: Bank | null, supplyPrice?: number): Promise<[number, number]>;
12
12
  export declare function getAllMarginfiAccountsByAuthority(umi: Umi, authority: PublicKey, compatibleWithSolauto?: boolean): Promise<{
13
13
  marginfiAccount: PublicKey;
14
14
  supplyMint?: PublicKey;
@@ -1 +1 @@
1
- {"version":3,"file":"marginfiUtils.d.ts","sourceRoot":"","sources":["../../src/utils/marginfiUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAa,GAAG,EAAE,MAAM,0BAA0B,CAAC;AAE1D,OAAO,EACL,IAAI,EAKL,MAAM,iBAAiB,CAAC;AAUzB,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAsB,MAAM,cAAc,CAAC;AAEjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAG7D,wBAAgB,wBAAwB,CAAC,EACvC,IAAI,EACJ,IAAI,GACL,EAAE;IACD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,GAAG,qBAAqB,CAWxB;AAED,wBAAsB,wBAAwB,CAC5C,UAAU,EAAE,IAAI,EAChB,QAAQ,EAAE,IAAI,EACd,WAAW,CAAC,EAAE,MAAM,GACnB,OAAO,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAkC3B;AAED,wBAAsB,iCAAiC,C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AAW,CAAC,EAAE,MAAM,GACnB,OAAO,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAsC3B;AAED,wBAAsB,iCAAiC,CACrD,GAAG,EAAE,GAAG,EACR,SAAS,EAAE,SAAS,EACpB,qBAAqB,CAAC,EAAE,OAAO,GAC9B,OAAO,CACR;IAAE,eAAe,EAAE,SAAS,CAAC;IAAC,UAAU,CAAC,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,EAAE,SAAS,CAAA;CAAE,EAAE,CAC/E,CA6CA;AA0DD,wBAAsB,+BAA+B,CACnD,GAAG,EAAE,GAAG,EACR,iBAAiB,EAAE,SAAS,EAC5B,UAAU,CAAC,EAAE,SAAS,EACtB,QAAQ,CAAC,EAAE,SAAS,EACpB,mBAAmB,CAAC,EAAE,mBAAmB,GACxC,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CA4IpC;AA+DD,wBAAsB,sBAAsB,CAC1C,GAAG,EAAE,GAAG,EACR,IAAI,EAAE,IAAI,GACT,OAAO,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CA0B3B"}
@@ -29,6 +29,9 @@ async function getMaxLtvAndLiqThreshold(supplyBank, debtBank, supplyPrice) {
29
29
  const [price] = await (0, generalUtils_1.getTokenPrices)([(0, umi_web3js_adapters_1.toWeb3JsPublicKey)(supplyBank.mint)]);
30
30
  supplyPrice = price;
31
31
  }
32
+ if (debtBank === null) {
33
+ return [0, 0];
34
+ }
32
35
  let maxLtv = (0, numberUtils_1.bytesToI80F48)(supplyBank.config.assetWeightInit.value) /
33
36
  (0, numberUtils_1.bytesToI80F48)(debtBank.config.liabilityWeightInit.value);
34
37
  const liqThreshold = (0, numberUtils_1.bytesToI80F48)(supplyBank.config.assetWeightMaint.value) /
@@ -84,27 +87,32 @@ async function getAllMarginfiAccountsByAuthority(umi, authority, compatibleWithS
84
87
  }
85
88
  exports.getAllMarginfiAccountsByAuthority = getAllMarginfiAccountsByAuthority;
86
89
  async function getTokenUsage(umi, bank, isAsset, shares, amountUsedAdjustment) {
87
- let [marketPrice] = await (0, generalUtils_1.getTokenPrices)([(0, umi_web3js_adapters_1.toWeb3JsPublicKey)(bank.mint)]);
88
- const [assetShareValue, liabilityShareValue] = await getUpToDateShareValues(umi, bank);
89
- const shareValue = isAsset ? assetShareValue : liabilityShareValue;
90
- const amountUsed = shares * shareValue + Number(amountUsedAdjustment ?? 0);
91
- const totalDeposited = (0, numberUtils_1.bytesToI80F48)(bank.totalAssetShares.value) * assetShareValue;
92
- const amountCanBeUsd = isAsset
93
- ? Number(bank.config.depositLimit) - totalDeposited
94
- : totalDeposited -
95
- (0, numberUtils_1.bytesToI80F48)(bank.totalLiabilityShares.value) * liabilityShareValue;
90
+ let amountUsed = 0;
91
+ let amountCanBeUsed = 0;
92
+ let marketPrice = 0;
93
+ if (bank !== null) {
94
+ [marketPrice] = await (0, generalUtils_1.getTokenPrices)([(0, umi_web3js_adapters_1.toWeb3JsPublicKey)(bank.mint)]);
95
+ const [assetShareValue, liabilityShareValue] = await getUpToDateShareValues(umi, bank);
96
+ const shareValue = isAsset ? assetShareValue : liabilityShareValue;
97
+ amountUsed = shares * shareValue + Number(amountUsedAdjustment ?? 0);
98
+ const totalDeposited = (0, numberUtils_1.bytesToI80F48)(bank.totalAssetShares.value) * assetShareValue;
99
+ amountCanBeUsed = isAsset
100
+ ? Number(bank.config.depositLimit) - totalDeposited
101
+ : totalDeposited -
102
+ (0, numberUtils_1.bytesToI80F48)(bank.totalLiabilityShares.value) * liabilityShareValue;
103
+ }
96
104
  return {
97
- mint: bank.mint,
98
- decimals: bank.mintDecimals,
105
+ mint: bank?.mint ?? (0, umi_1.publicKey)(web3_js_1.PublicKey.default),
106
+ decimals: bank?.mintDecimals ?? 0,
99
107
  amountUsed: {
100
108
  baseUnit: BigInt(Math.round(amountUsed)),
101
- baseAmountUsdValue: (0, numberUtils_1.toBaseUnit)((0, numberUtils_1.fromBaseUnit)(BigInt(Math.round(amountUsed)), bank.mintDecimals) *
102
- marketPrice, generalAccounts_1.USD_DECIMALS),
109
+ baseAmountUsdValue: bank ? (0, numberUtils_1.toBaseUnit)((0, numberUtils_1.fromBaseUnit)(BigInt(Math.round(amountUsed)), bank.mintDecimals) *
110
+ marketPrice, generalAccounts_1.USD_DECIMALS) : BigInt(0),
103
111
  },
104
112
  amountCanBeUsed: {
105
- baseUnit: BigInt(Math.round(amountCanBeUsd)),
106
- baseAmountUsdValue: (0, numberUtils_1.toBaseUnit)((0, numberUtils_1.fromBaseUnit)(BigInt(Math.round(amountCanBeUsd)), bank.mintDecimals) *
107
- marketPrice, generalAccounts_1.USD_DECIMALS),
113
+ baseUnit: BigInt(Math.round(amountCanBeUsed)),
114
+ baseAmountUsdValue: bank ? (0, numberUtils_1.toBaseUnit)((0, numberUtils_1.fromBaseUnit)(BigInt(Math.round(amountCanBeUsed)), bank.mintDecimals) *
115
+ marketPrice, generalAccounts_1.USD_DECIMALS) : BigInt(0),
108
116
  },
109
117
  baseAmountMarketPriceUsd: (0, numberUtils_1.toBaseUnit)(marketPrice, generalAccounts_1.USD_DECIMALS),
110
118
  flashLoanFeeBps: 0,
@@ -151,15 +159,15 @@ async function getMarginfiAccountPositionState(umi, marginfiAccountPk, supplyMin
151
159
  debtUsage = await getTokenUsage(umi, debtBank, false, (0, numberUtils_1.bytesToI80F48)(debtBalances[0].liabilityShares.value), livePositionUpdates?.debtAdjustment);
152
160
  }
153
161
  }
154
- if (supplyBank !== null && !supplyUsage) {
162
+ if (supplyBank === null) {
163
+ return undefined;
164
+ }
165
+ if (!supplyUsage) {
155
166
  supplyUsage = await getTokenUsage(umi, supplyBank, true, 0, livePositionUpdates?.supplyAdjustment);
156
167
  }
157
- if (debtBank !== null && !debtUsage) {
168
+ if (!debtUsage) {
158
169
  debtUsage = await getTokenUsage(umi, debtBank, false, 0, livePositionUpdates?.debtAdjustment);
159
170
  }
160
- if (supplyBank === null || debtBank === null) {
161
- return undefined;
162
- }
163
171
  const supplyPrice = solautoConstants_1.PRICES[supplyMint.toString()].price;
164
172
  let [maxLtv, liqThreshold] = await getMaxLtvAndLiqThreshold(supplyBank, debtBank, supplyPrice);
165
173
  const supplyUsd = (0, numberUtils_1.fromBaseUnit)(supplyUsage.amountUsed.baseAmountUsdValue, generalAccounts_1.USD_DECIMALS);
@@ -1 +1 @@
1
- {"version":3,"file":"generalUtils.d.ts","sourceRoot":"","sources":["../../../src/utils/solauto/generalUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAoB,GAAG,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EACL,kBAAkB,EAClB,WAAW,EACX,kBAAkB,EAClB,OAAO,EACP,eAAe,EACf,aAAa,EAEb,yBAAyB,EACzB,gCAAgC,EAIjC,MAAM,iBAAiB,CAAC;AAczB,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAgB7D,wBAAgB,6BAA6B,CAC3C,UAAU,EAAE,kBAAkB,GAC7B,MAAM,CAKR;AAED,wBAAgB,+BAA+B,CAC7C,UAAU,EAAE,kBAAkB,GAC7B,OAAO,CAET;AAED,wBAAgB,6BAA6B,CAC3C,SAAS,EAAE,MAAM,EACjB,WAAW,EAAE,MAAM,EACnB,UAAU,EAAE,kBAAkB,EAC9B,oBAAoB,EAAE,MAAM,UAY7B;AAED,wBAAgB,iCAAiC,CAC/C,QAAQ,EAAE,yBAAyB,EACnC,kBAAkB,EAAE,MAAM,GACzB,yBAAyB,CAgB3B;AAED,wBAAgB,iBAAiB,CAC/B,UAAU,EAAE,OAAO,EACnB,OAAO,EAAE,OAAO,GACf;IACD,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;CACf,CAYA;AAED,wBAAgB,qBAAqB,CACnC,aAAa,EAAE,aAAa,EAC5B,gBAAgB,EAAE,yBAAyB,EAC3C,WAAW,EAAE,W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 -63,6 +63,9 @@ function eligibileForRebalance(positionState, positionSettings, positionDca) {
63
63
  eligibleForNextAutomationPeriod(positionDca.automation)) {
64
64
  return true;
65
65
  }
66
+ if (positionState.supply.amountUsed.baseUnit === BigInt(0)) {
67
+ return false;
68
+ }
66
69
  const boostToBps = eligibleForRefresh(positionState, positionSettings) &&
67
70
  positionSettings.automation.targetPeriods > 0
68
71
  ? getUpdatedValueFromAutomation(positionSettings.boostToBps, positionSettings.targetBoostToBps, positionSettings.automation, (0, generalUtils_1.currentUnixSeconds)())
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@haven-fi/solauto-sdk",
3
- "version": "1.0.32",
3
+ "version": "1.0.34",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "description": "Typescript SDK for the Solauto program on the Solana blockchain",
@@ -1,5 +1,4 @@
1
1
  import {
2
- fromWeb3JsKeypair,
3
2
  fromWeb3JsPublicKey,
4
3
  toWeb3JsPublicKey,
5
4
  } from "@metaplex-foundation/umi-web3js-adapters";
@@ -12,10 +11,7 @@ import {
12
11
  createSignerFromKeypair,
13
12
  AccountMeta,
14
13
  } from "@metaplex-foundation/umi";
15
- import { createUmi } from "@metaplex-foundation/umi-bundle-defaults";
16
14
  import {
17
- clusterApiUrl,
18
- Keypair,
19
15
  PublicKey,
20
16
  SYSVAR_INSTRUCTIONS_PUBKEY,
21
17
  } from "@solana/web3.js";
@@ -60,7 +56,6 @@ import {
60
56
  getMarginfiAccountPositionState,
61
57
  } from "../utils/marginfiUtils";
62
58
  import { bytesToI80F48 } from "../utils/numberUtils";
63
- import { WalletAdapter } from "@metaplex-foundation/umi-signer-wallet-adapters";
64
59
 
65
60
  export interface SolautoMarginfiClientArgs extends SolautoClientArgs {
66
61
  marginfiAccount?: PublicKey | Signer;
@@ -68,34 +63,12 @@ export interface SolautoMarginfiClientArgs extends SolautoClientArgs {
68
63
  marginfiGroup?: PublicKey;
69
64
  }
70
65
 
71
- export function newSolautoMarginfiPositionArgs(
72
- positionId: number,
73
- signer: Signer | undefined,
74
- wallet: WalletAdapter | undefined,
75
- supplyMint: PublicKey,
76
- debtMint: PublicKey,
77
- referredByAuthority?: PublicKey
78
- ): SolautoMarginfiClientArgs {
79
- const umi = createUmi(clusterApiUrl("mainnet-beta"));
80
- return {
81
- positionId,
82
- signer,
83
- wallet,
84
- marginfiAccount:
85
- positionId === 0
86
- ? createSignerFromKeypair(umi, umi.eddsa.generateKeypair())
87
- : undefined,
88
- marginfiAccountSeedIdx: positionId > 0 ? generateRandomU64() : undefined,
89
- supplyMint: supplyMint,
90
- debtMint: debtMint,
91
- referredByAuthority,
92
- };
93
- }
94
-
95
66
  export class SolautoMarginfiClient extends SolautoClient {
67
+ private initialized: boolean = false;
68
+
96
69
  public marginfiProgram!: PublicKey;
97
70
 
98
- public marginfiAccountSeedIdx?: bigint;
71
+ public marginfiAccountSeedIdx: bigint = BigInt(0);
99
72
  public marginfiAccount!: PublicKey | Signer;
100
73
  public marginfiAccountPk!: PublicKey;
101
74
  public marginfiGroup!: PublicKey;
@@ -111,15 +84,19 @@ export class SolautoMarginfiClient extends SolautoClient {
111
84
  async initialize(args: SolautoMarginfiClientArgs) {
112
85
  await super.initialize(args, LendingPlatform.Marginfi);
113
86
 
114
- this.marginfiAccountSeedIdx = args.marginfiAccountSeedIdx;
115
- this.marginfiAccount =
116
- this.marginfiAccountSeedIdx !== undefined
117
- ? await getMarginfiAccountPDA(
87
+ if (this.selfManaged) {
88
+ this.marginfiAccount =
89
+ args.marginfiAccount ??
90
+ createSignerFromKeypair(this.umi, this.umi.eddsa.generateKeypair());
91
+ } else {
92
+ this.marginfiAccountSeedIdx = generateRandomU64();
93
+ this.marginfiAccount = this.solautoPositionData
94
+ ? toWeb3JsPublicKey(this.solautoPositionData.position.protocolAccount)
95
+ : await getMarginfiAccountPDA(
118
96
  this.solautoPosition,
119
97
  this.marginfiAccountSeedIdx
120
- )
121
- : args.marginfiAccount ??
122
- toWeb3JsPublicKey(this.solautoPositionData!.position.protocolAccount);
98
+ );
99
+ }
123
100
  this.marginfiAccountPk =
124
101
  "publicKey" in this.marginfiAccount
125
102
  ? toWeb3JsPublicKey(this.marginfiAccount.publicKey)
@@ -140,27 +117,37 @@ export class SolautoMarginfiClient extends SolautoClient {
140
117
  mint: this.debtMint.toString(),
141
118
  })!;
142
119
 
120
+ if (!this.initialized) {
121
+ await this.setIntermediaryMarginfiDetails();
122
+ }
123
+ this.initialized = true;
124
+ }
125
+
126
+ async setIntermediaryMarginfiDetails() {
143
127
  const existingMarginfiAccounts = (
144
128
  await getAllMarginfiAccountsByAuthority(
145
129
  this.umi,
146
130
  toWeb3JsPublicKey(this.signer.publicKey),
147
131
  false
148
132
  )
149
- ).filter((x) => x.marginfiAccount.equals(this.marginfiAccountPk));
150
- const emptyMarginfiAccounts = (
151
- await safeFetchAllMarginfiAccount(
152
- this.umi,
153
- existingMarginfiAccounts.map((x) => publicKey(x.marginfiAccount))
154
- )
155
- ).filter(
156
- (x) =>
157
- x.lendingAccount.balances.find(
158
- (y) =>
159
- y.bankPk.toString() !== PublicKey.default.toString() &&
160
- (Math.round(bytesToI80F48(y.assetShares.value)) != 0 ||
161
- Math.round(bytesToI80F48(y.liabilityShares.value)) != 0)
162
- ) === undefined
163
- );
133
+ ).filter((x) => !x.marginfiAccount.equals(this.marginfiAccountPk));
134
+ const emptyMarginfiAccounts =
135
+ existingMarginfiAccounts.length > 0
136
+ ? (
137
+ await safeFetchAllMarginfiAccount(
138
+ this.umi,
139
+ existingMarginfiAccounts.map((x) => publicKey(x.marginfiAccount))
140
+ )
141
+ ).filter(
142
+ (x) =>
143
+ x.lendingAccount.balances.find(
144
+ (y) =>
145
+ y.bankPk.toString() !== PublicKey.default.toString() &&
146
+ (Math.round(bytesToI80F48(y.assetShares.value)) != 0 ||
147
+ Math.round(bytesToI80F48(y.liabilityShares.value)) != 0)
148
+ ) === undefined
149
+ )
150
+ : [];
164
151
 
165
152
  this.intermediaryMarginfiAccountSigner =
166
153
  emptyMarginfiAccounts.length > 0
@@ -274,7 +261,6 @@ export class SolautoMarginfiClient extends SolautoClient {
274
261
  private marginfiProtocolInteractionIx(args: SolautoActionArgs) {
275
262
  switch (args.__kind) {
276
263
  case "Deposit": {
277
- console.log(args.fields[0]);
278
264
  return lendingAccountDeposit(this.umi, {
279
265
  amount: args.fields[0],
280
266
  signer: this.signer,
@@ -1,4 +1,5 @@
1
1
  import {
2
+ Instruction,
2
3
  Signer,
3
4
  TransactionBuilder,
4
5
  Umi,
@@ -20,6 +21,7 @@ import {
20
21
  SolautoRebalanceType,
21
22
  convertReferralFees,
22
23
  getMarginfiProtocolInteractionInstructionDataSerializer,
24
+ getMarginfiRebalanceInstructionDataSerializer,
23
25
  isSolautoAction,
24
26
  solautoAction,
25
27
  } from "../generated";
@@ -99,10 +101,10 @@ function getWSolUsage(
99
101
 
100
102
  async function transactionChoresBefore(
101
103
  client: SolautoClient,
104
+ accountsGettingCreated: string[],
102
105
  solautoActions?: SolautoAction[],
103
- initiatingDcaIn?: bigint
106
+ initiatingDcaIn?: bigint,
104
107
  ): Promise<TransactionBuilder> {
105
- const accountsGettingCreated: string[] = [];
106
108
  let chores = transactionBuilder();
107
109
 
108
110
  if (
@@ -118,7 +120,7 @@ async function transactionChoresBefore(
118
120
  }
119
121
 
120
122
  if (client.selfManaged) {
121
- if (client.solautoPositionData === undefined) {
123
+ if (client.solautoPositionData === null) {
122
124
  chores = chores.add(client.openPosition());
123
125
  } else if (
124
126
  client.lendingPlatform === LendingPlatform.Marginfi &&
@@ -222,11 +224,16 @@ async function transactionChoresBefore(
222
224
 
223
225
  export async function rebalanceChoresBefore(
224
226
  client: SolautoClient,
225
- tx: TransactionBuilder
227
+ tx: TransactionBuilder,
228
+ accountsGettingCreated: string[]
226
229
  ): Promise<TransactionBuilder> {
230
+ const rebalanceInstructions = getRebalanceInstructions(tx);
231
+ if (rebalanceInstructions.length === 0) {
232
+ return transactionBuilder();
233
+ }
234
+
227
235
  const usesAccount = (key: PublicKey) =>
228
- tx
229
- .getInstructions()
236
+ rebalanceInstructions
230
237
  .some((t) => t.keys.some((k) => toWeb3JsPublicKey(k.pubkey).equals(key)));
231
238
 
232
239
  const checkReferralSupplyTa =
@@ -237,6 +244,8 @@ export async function rebalanceChoresBefore(
237
244
  usesAccount(
238
245
  (client as SolautoMarginfiClient).intermediaryMarginfiAccountPk
239
246
  );
247
+ const checkSignerSupplyTa = client.selfManaged && usesAccount(client.signerSupplyTa);
248
+ const checkSignerDebtTa = client.selfManaged && usesAccount(client.signerSupplyTa);
240
249
 
241
250
  const accountsNeeded = [
242
251
  ...[checkReferralSupplyTa ? client.referredBySupplyTa : PublicKey.default],
@@ -246,9 +255,11 @@ export async function rebalanceChoresBefore(
246
255
  ? (client as SolautoMarginfiClient).intermediaryMarginfiAccountPk
247
256
  : PublicKey.default,
248
257
  ],
258
+ ...[checkSignerSupplyTa ? client.signerSupplyTa : PublicKey.default],
259
+ ...[checkSignerDebtTa ? client.signerDebtTa : PublicKey.default],
249
260
  ];
250
261
 
251
- const [referredBySupplyTa, solautoFeesSupplyTa, intermediaryMarginfiAccount] =
262
+ const [referredBySupplyTa, solautoFeesSupplyTa, intermediaryMarginfiAccount, signerSupplyTa, signerDebtTa] =
252
263
  await client.umi.rpc.getAccounts(
253
264
  accountsNeeded.map((x) => publicKey(x ?? PublicKey.default))
254
265
  );
@@ -286,6 +297,30 @@ export async function rebalanceChoresBefore(
286
297
  );
287
298
  }
288
299
 
300
+ if (checkSignerSupplyTa && !rpcAccountCreated(signerSupplyTa) && !accountsGettingCreated.includes(signerSupplyTa.publicKey.toString())) {
301
+ client.log("Creating signer supply token account");
302
+ chores = chores.add(
303
+ createAssociatedTokenAccountUmiIx(
304
+ client.signer,
305
+ toWeb3JsPublicKey(client.signer.publicKey),
306
+ client.supplyMint
307
+ )
308
+ );
309
+ accountsGettingCreated.push(signerSupplyTa.publicKey.toString());
310
+ }
311
+
312
+ if (checkSignerDebtTa && !rpcAccountCreated(signerDebtTa) && !accountsGettingCreated.includes(signerDebtTa.publicKey.toString())) {
313
+ client.log("Creating signer debt token account");
314
+ chores = chores.add(
315
+ createAssociatedTokenAccountUmiIx(
316
+ client.signer,
317
+ toWeb3JsPublicKey(client.signer.publicKey),
318
+ client.debtMint
319
+ )
320
+ );
321
+ accountsGettingCreated.push(signerDebtTa.publicKey.toString());
322
+ }
323
+
289
324
  return chores;
290
325
  }
291
326
 
@@ -315,6 +350,26 @@ function transactionChoresAfter(
315
350
  return chores;
316
351
  }
317
352
 
353
+ function getRebalanceInstructions(tx: TransactionBuilder): Instruction[] {
354
+ return tx.getInstructions().filter((x) => {
355
+ if (x.programId === SOLAUTO_PROGRAM_ID) {
356
+ try {
357
+ const serializer = getMarginfiRebalanceInstructionDataSerializer();
358
+ const discriminator = serializer.serialize({
359
+ limitGapBps: 0,
360
+ rebalanceType: SolautoRebalanceType.None,
361
+ targetLiqUtilizationRateBps: 0
362
+ })[0];
363
+ const [data, _] = serializer.deserialize(x.data);
364
+ if (data.discriminator === discriminator) {
365
+ return true;
366
+ }
367
+ } catch {}
368
+ return false;
369
+ }
370
+ });
371
+ }
372
+
318
373
  function getSolautoActions(tx: TransactionBuilder): SolautoAction[] {
319
374
  let solautoActions: SolautoAction[] = [];
320
375
 
@@ -326,8 +381,7 @@ function getSolautoActions(tx: TransactionBuilder): SolautoAction[] {
326
381
  const discriminator = serializer
327
382
  .serialize({
328
383
  solautoAction: solautoAction("Deposit", [BigInt(0)]),
329
- })
330
- .slice(0, 1)[0];
384
+ })[0];
331
385
  const [data, _] = serializer.deserialize(x.data);
332
386
  if (data.discriminator === discriminator) {
333
387
  solautoActions?.push(data.solautoAction);
@@ -453,18 +507,20 @@ export async function getTransactionChores(
453
507
  ): Promise<[TransactionBuilder, TransactionBuilder]> {
454
508
  let choresBefore = transactionBuilder();
455
509
  let choresAfter = transactionBuilder();
510
+ const accountsGettingCreated: string[] = [];
456
511
 
457
512
  const solautoActions = getSolautoActions(tx);
458
513
 
459
514
  choresBefore = choresBefore.add([
460
515
  await transactionChoresBefore(
461
516
  client,
517
+ accountsGettingCreated,
462
518
  solautoActions,
463
519
  client.livePositionUpdates.debtTaBalanceAdjustment > 0
464
520
  ? client.livePositionUpdates.debtTaBalanceAdjustment
465
- : undefined
521
+ : undefined,
466
522
  ),
467
- await rebalanceChoresBefore(client, tx),
523
+ await rebalanceChoresBefore(client, tx, accountsGettingCreated),
468
524
  ]);
469
525
 
470
526
  choresAfter = choresAfter.add(
@@ -491,14 +547,15 @@ export async function buildSolautoRebalanceTransaction(
491
547
  > {
492
548
  client.solautoPositionState = await client.getFreshPositionState();
493
549
  if (
494
- targetLiqUtilizationRateBps === undefined &&
495
- !eligibileForRebalance(
496
- client.solautoPositionState!,
497
- client.livePositionUpdates.settings ??
498
- client.solautoPositionData?.position.settingParams!,
499
- client.livePositionUpdates.activeDca ??
500
- client.solautoPositionData?.position.dca!
501
- )
550
+ client.solautoPositionState?.supply.amountUsed.baseUnit === BigInt(0) ||
551
+ (targetLiqUtilizationRateBps === undefined &&
552
+ !eligibileForRebalance(
553
+ client.solautoPositionState!,
554
+ client.livePositionUpdates.settings ??
555
+ client.solautoPositionData?.position.settingParams!,
556
+ client.livePositionUpdates.activeDca ??
557
+ client.solautoPositionData?.position.dca!
558
+ ))
502
559
  ) {
503
560
  client.log("Not eligible for a rebalance");
504
561
  return undefined;
@@ -1,7 +1,7 @@
1
1
  import { getDebtAdjustmentUsd, getLiqUtilzationRateBps } from "./numberUtils";
2
2
 
3
3
  // TODO delete this file
4
- function check() {
4
+ async function check() {
5
5
  let supply = 458948;
6
6
  let debt = 212846;
7
7
  let supply_weight = 0.899999976158142;
@@ -37,4 +37,4 @@ function check() {
37
37
  console.log!(liq_utilization_rate);
38
38
  }
39
39
 
40
- check();
40
+ check();
@@ -44,7 +44,7 @@ export function findMarginfiBankAccounts({
44
44
 
45
45
  export async function getMaxLtvAndLiqThreshold(
46
46
  supplyBank: Bank,
47
- debtBank: Bank,
47
+ debtBank: Bank | null,
48
48
  supplyPrice?: number
49
49
  ): Promise<[number, number]> {
50
50
  if (!supplyPrice) {
@@ -52,6 +52,10 @@ export async function getMaxLtvAndLiqThreshold(
52
52
  supplyPrice = price;
53
53
  }
54
54
 
55
+ if (debtBank === null) {
56
+ return [0, 0];
57
+ }
58
+
55
59
  let maxLtv =
56
60
  bytesToI80F48(supplyBank.config.assetWeightInit.value) /
57
61
  bytesToI80F48(debtBank.config.liabilityWeightInit.value);
@@ -137,44 +141,50 @@ export async function getAllMarginfiAccountsByAuthority(
137
141
 
138
142
  async function getTokenUsage(
139
143
  umi: Umi,
140
- bank: Bank,
144
+ bank: Bank | null,
141
145
  isAsset: boolean,
142
146
  shares: number,
143
147
  amountUsedAdjustment?: bigint
144
148
  ): Promise<PositionTokenUsage> {
145
- let [marketPrice] = await getTokenPrices([toWeb3JsPublicKey(bank.mint)]);
146
- const [assetShareValue, liabilityShareValue] = await getUpToDateShareValues(
147
- umi,
148
- bank
149
- );
150
- const shareValue = isAsset ? assetShareValue : liabilityShareValue;
151
- const amountUsed = shares * shareValue + Number(amountUsedAdjustment ?? 0);
149
+ let amountUsed = 0;
150
+ let amountCanBeUsed = 0;
151
+ let marketPrice = 0;
152
152
 
153
- const totalDeposited =
154
- bytesToI80F48(bank.totalAssetShares.value) * assetShareValue;
155
- const amountCanBeUsd = isAsset
156
- ? Number(bank.config.depositLimit) - totalDeposited
157
- : totalDeposited -
158
- bytesToI80F48(bank.totalLiabilityShares.value) * liabilityShareValue;
153
+ if (bank !== null) {
154
+ [marketPrice] = await getTokenPrices([toWeb3JsPublicKey(bank.mint)]);
155
+ const [assetShareValue, liabilityShareValue] = await getUpToDateShareValues(
156
+ umi,
157
+ bank
158
+ );
159
+ const shareValue = isAsset ? assetShareValue : liabilityShareValue;
160
+ amountUsed = shares * shareValue + Number(amountUsedAdjustment ?? 0);
161
+
162
+ const totalDeposited =
163
+ bytesToI80F48(bank.totalAssetShares.value) * assetShareValue;
164
+ amountCanBeUsed = isAsset
165
+ ? Number(bank.config.depositLimit) - totalDeposited
166
+ : totalDeposited -
167
+ bytesToI80F48(bank.totalLiabilityShares.value) * liabilityShareValue;
168
+ }
159
169
 
160
170
  return {
161
- mint: bank.mint,
162
- decimals: bank.mintDecimals,
171
+ mint: bank?.mint ?? publicKey(PublicKey.default),
172
+ decimals: bank?.mintDecimals ?? 0,
163
173
  amountUsed: {
164
174
  baseUnit: BigInt(Math.round(amountUsed)),
165
- baseAmountUsdValue: toBaseUnit(
175
+ baseAmountUsdValue: bank ? toBaseUnit(
166
176
  fromBaseUnit(BigInt(Math.round(amountUsed)), bank.mintDecimals) *
167
177
  marketPrice,
168
178
  USD_DECIMALS
169
- ),
179
+ ) : BigInt(0),
170
180
  },
171
181
  amountCanBeUsed: {
172
- baseUnit: BigInt(Math.round(amountCanBeUsd)),
173
- baseAmountUsdValue: toBaseUnit(
174
- fromBaseUnit(BigInt(Math.round(amountCanBeUsd)), bank.mintDecimals) *
182
+ baseUnit: BigInt(Math.round(amountCanBeUsed)),
183
+ baseAmountUsdValue: bank ? toBaseUnit(
184
+ fromBaseUnit(BigInt(Math.round(amountCanBeUsed)), bank.mintDecimals) *
175
185
  marketPrice,
176
186
  USD_DECIMALS
177
- ),
187
+ ) : BigInt(0),
178
188
  },
179
189
  baseAmountMarketPriceUsd: toBaseUnit(marketPrice, USD_DECIMALS),
180
190
  flashLoanFeeBps: 0,
@@ -270,7 +280,11 @@ export async function getMarginfiAccountPositionState(
270
280
  }
271
281
  }
272
282
 
273
- if (supplyBank !== null && !supplyUsage) {
283
+ if (supplyBank === null) {
284
+ return undefined;
285
+ }
286
+
287
+ if (!supplyUsage) {
274
288
  supplyUsage = await getTokenUsage(
275
289
  umi,
276
290
  supplyBank,
@@ -280,7 +294,7 @@ export async function getMarginfiAccountPositionState(
280
294
  );
281
295
  }
282
296
 
283
- if (debtBank !== null && !debtUsage) {
297
+ if (!debtUsage) {
284
298
  debtUsage = await getTokenUsage(
285
299
  umi,
286
300
  debtBank,
@@ -290,10 +304,6 @@ export async function getMarginfiAccountPositionState(
290
304
  );
291
305
  }
292
306
 
293
- if (supplyBank === null || debtBank === null) {
294
- return undefined;
295
- }
296
-
297
307
  const supplyPrice = PRICES[supplyMint!.toString()].price;
298
308
  let [maxLtv, liqThreshold] = await getMaxLtvAndLiqThreshold(
299
309
  supplyBank,
@@ -130,6 +130,10 @@ export function eligibileForRebalance(
130
130
  return true;
131
131
  }
132
132
 
133
+ if (positionState.supply.amountUsed.baseUnit === BigInt(0)) {
134
+ return false;
135
+ }
136
+
133
137
  const boostToBps =
134
138
  eligibleForRefresh(positionState, positionSettings) &&
135
139
  positionSettings.automation.targetPeriods > 0
@@ -3,7 +3,6 @@ import { none, some } from "@metaplex-foundation/umi";
3
3
  import { setupTest } from "../shared";
4
4
  import {
5
5
  SolautoMarginfiClient,
6
- newSolautoMarginfiPositionArgs,
7
6
  } from "../../src/clients/solautoMarginfiClient";
8
7
  import {
9
8
  solautoAction,
@@ -35,13 +34,6 @@ describe("Solauto Marginfi tests", async () => {
35
34
  const debtDecimals = 6;
36
35
 
37
36
  await client.initialize(
38
- // newSolautoMarginfiPositionArgs(
39
- // positionId,
40
- // signer,
41
- // undefined,
42
- // supply,
43
- // new PublicKey(USDC_MINT)
44
- // )
45
37
  {
46
38
  signer,
47
39
  positionId,
@@ -1,11 +1,8 @@
1
- import { describe, it, before } from 'mocha';
1
+ import { describe, it, before } from "mocha";
2
2
  import { PublicKey } from "@solana/web3.js";
3
3
  import { NATIVE_MINT } from "@solana/spl-token";
4
4
  import { assert } from "chai";
5
- import {
6
- newSolautoMarginfiPositionArgs,
7
- SolautoMarginfiClient,
8
- } from "../../src/clients/solautoMarginfiClient";
5
+ import { SolautoMarginfiClient } from "../../src/clients/solautoMarginfiClient";
9
6
  import { setupTest } from "../shared";
10
7
  import { MARGINFI_ACCOUNTS } from "../../src/constants/marginfiAccounts";
11
8
  import { getRebalanceValues } from "../../src/utils/solauto/rebalanceUtils";
@@ -92,16 +89,16 @@ async function getFakePosition(
92
89
  settings: SolautoSettingsParameters,
93
90
  dca?: DCASettings
94
91
  ): Promise<SolautoClient> {
95
- const client = new SolautoMarginfiClient(process.env.HELIUS_API_KEY ?? "", true);
96
- await client.initialize(
97
- newSolautoMarginfiPositionArgs(
98
- 1,
99
- signer,
100
- undefined,
101
- new PublicKey(NATIVE_MINT),
102
- new PublicKey(MARGINFI_ACCOUNTS.USDC.mint)
103
- )
92
+ const client = new SolautoMarginfiClient(
93
+ process.env.HELIUS_API_KEY ?? "",
94
+ true
104
95
  );
96
+ await client.initialize({
97
+ positionId: 1,
98
+ signer,
99
+ supplyMint: new PublicKey(NATIVE_MINT),
100
+ debtMint: new PublicKey(MARGINFI_ACCOUNTS.USDC.mint),
101
+ });
105
102
 
106
103
  const state = await client.getFreshPositionState();
107
104
  client.solautoPositionData = {
@@ -268,16 +265,16 @@ describe("Rebalance tests", async () => {
268
265
  });
269
266
 
270
267
  it("Standard rebalance with target rate", async () => {
271
- const client = new SolautoMarginfiClient(process.env.HELIUS_API_KEY ?? "", true);
272
- await client.initialize(
273
- newSolautoMarginfiPositionArgs(
274
- 1,
275
- signer,
276
- undefined,
277
- new PublicKey(NATIVE_MINT),
278
- new PublicKey(MARGINFI_ACCOUNTS.USDC.mint)
279
- )
268
+ const client = new SolautoMarginfiClient(
269
+ process.env.HELIUS_API_KEY ?? "",
270
+ true
280
271
  );
272
+ await client.initialize({
273
+ positionId: 1,
274
+ signer,
275
+ supplyMint: new PublicKey(NATIVE_MINT),
276
+ debtMint: new PublicKey(MARGINFI_ACCOUNTS.USDC.mint),
277
+ });
281
278
 
282
279
  client.livePositionUpdates.new({
283
280
  type: "supply",