hedge-web3 0.1.46 → 0.1.50

Sign up to get free protection for your applications and to get access to all the features.
@@ -17,13 +17,8 @@ import {
17
17
  getVaultTypeAccountPublicKey,
18
18
  getUshMintPublicKey,
19
19
  getVaultSystemStatePublicKey,
20
- HEDGE_PROGRAM_PUBLICKEY,
21
20
  } from '../Constants'
22
21
  import { Vault } from 'idl/vault'
23
- import { parseAnchorErrors } from '../utils/Errors'
24
- import { VaultAccount } from '../state/VaultAccount'
25
-
26
- const fs = require('fs');
27
22
 
28
23
  export async function loanVault(
29
24
  program: Program<Vault>,
@@ -41,14 +36,15 @@ export async function loanVault(
41
36
  ushMintPublickey,
42
37
  payer.publicKey
43
38
  )
44
- const vaultAccount = await program.account.vault.fetch(vaultPublicKey)
45
- const vaultTypeAccount = await program.account.vaultType.fetch(vaultAccount.vaultType)
46
39
 
40
+ const vaultAccount = await program.account.vault.fetch(vaultPublicKey)
41
+ const vaultTypeAccountPublicKey = await getVaultTypeAccountPublicKey(vaultAccount.collateralType)
42
+ const vaultTypeAccount = await program.account.vaultType.fetch(vaultTypeAccountPublicKey)
47
43
  const vaultTypeAssociatedTokenAccount = await getOrCreateAssociatedTokenAccount(
48
44
  provider.connection,
49
45
  payer,
50
46
  vaultTypeAccount.collateralMint,
51
- vaultAccount.vaultType,
47
+ vaultTypeAccountPublicKey,
52
48
  true
53
49
  )
54
50
  const vaultAssociatedTokenAccount = await getOrCreateAssociatedTokenAccount(
@@ -58,10 +54,11 @@ export async function loanVault(
58
54
  vaultPublicKey,
59
55
  true
60
56
  )
57
+
61
58
  const [oldSmallerPublicKey, newSmallerPublicKey, newLargerPublicKey] = await getLinkedListAccounts(
62
59
  program,
63
60
  provider,
64
- vaultAccount.vaultType,
61
+ vaultTypeAccountPublicKey,
65
62
  vaultPublicKey,
66
63
  0,
67
64
  loanAmount,
@@ -78,7 +75,7 @@ export async function loanVault(
78
75
  vaultPublicKey,
79
76
  vaultAssociatedTokenAccount.address,
80
77
  history.publicKey,
81
- vaultAccount.vaultType,
78
+ vaultTypeAccountPublicKey,
82
79
  vaultTypeAssociatedTokenAccount.address,
83
80
  oldSmallerPublicKey,
84
81
  newSmallerPublicKey,
@@ -87,7 +84,7 @@ export async function loanVault(
87
84
  overrideTime
88
85
  )
89
86
  )
90
- await sendAndConfirmTransaction(provider.connection, transaction, [payer, history]).catch(parseAnchorErrors)
87
+ await sendAndConfirmTransaction(provider.connection, transaction, [payer, history])
91
88
  return vaultPublicKey
92
89
  }
93
90
 
@@ -40,12 +40,13 @@ export async function redeemVault(
40
40
  )
41
41
 
42
42
  const vaultAccount = await program.account.vault.fetch(vaultPublicKey)
43
- const vaultTypeAccountInfo = await program.account.vaultType.fetch(vaultAccount.vaultType)
43
+ const vaultTypeAccountPublicKey = await getVaultTypeAccountPublicKey(vaultAccount.collateralType)
44
+ const vaultTypeAccountInfo = await program.account.vaultType.fetch(vaultTypeAccountPublicKey)
44
45
  const vaultTypeAssociatedTokenAccount = await getOrCreateAssociatedTokenAccount(
45
46
  provider.connection,
46
47
  payer,
47
48
  vaultTypeAccountInfo.collateralMint,
48
- vaultAccount.vaultType,
49
+ vaultTypeAccountPublicKey,
49
50
  true
50
51
  )
51
52
 
@@ -67,7 +68,7 @@ export async function redeemVault(
67
68
  const [oldSmallerPublicKey, newSmallerPublicKey, newLargerPublicKey] = await getLinkedListAccounts(
68
69
  program,
69
70
  provider,
70
- vaultAccount.vaultType,
71
+ vaultTypeAccountPublicKey,
71
72
  vaultPublicKey,
72
73
  0,
73
74
  0,
@@ -85,7 +86,7 @@ export async function redeemVault(
85
86
  vaultPublicKey,
86
87
  vaultAssociatedTokenAccount.address,
87
88
  history.publicKey,
88
- vaultAccount.vaultType,
89
+ vaultTypeAccountPublicKey,
89
90
  vaultTypeAssociatedTokenAccount.address,
90
91
  oldSmallerPublicKey,
91
92
  newSmallerPublicKey,
@@ -51,7 +51,7 @@ export async function refreshOraclePriceInstruction(
51
51
  .accounts({
52
52
  oracleInfoAccount: oracleInfoAccount,
53
53
  vaultTypeAccount: vaultTypeAccount,
54
- oracleChainlink: chainlinkAccounts[network],
54
+ oracleChainlink: chainlinkAccunts[network],
55
55
  oraclePyth: pythAccounts[network],
56
56
  oracleSwitchboard: switchboardAccounts[network],
57
57
  systemProgram: SystemProgram.programId,
@@ -70,7 +70,7 @@ const pythAccounts = {
70
70
  Devnet: new PublicKey('J83w4HKfqxwcq3BEMMkPFSppX3gqekLyLJBexebFVkix'),
71
71
  MainnetBeta: new PublicKey('H6ARHf6YXhGYeQfUzQNGk6rDNnLBQKrenN712K4AQJEG'),
72
72
  }
73
- const chainlinkAccounts = {
73
+ const chainlinkAccunts = {
74
74
  Testing: SystemProgram.programId,
75
75
  Devnet: new PublicKey('FmAmfoyPXiA8Vhhe6MZTr3U6rZfEZ1ctEHay1ysqCqcf'),
76
76
  MainnetBeta: SystemProgram.programId, // CHAINLINK NOT ON MAINNET YET
@@ -39,9 +39,10 @@ export async function repayVault(
39
39
  )
40
40
  const vaultAccount = await program.account.vault.fetch(vaultPublicKey)
41
41
 
42
- const vaultTypeAccount = await program.account.vaultType.fetch(vaultAccount.vaultType)
42
+ const vaultTypeAccountPublicKey = await getVaultTypeAccountPublicKey(vaultAccount.collateralType)
43
+ const vaultTypeAccount = await program.account.vaultType.fetch(vaultTypeAccountPublicKey)
43
44
  const vaultTypeAssociatedTokenAccount = await findAssociatedTokenAddress(
44
- vaultAccount.vaultType,
45
+ vaultTypeAccountPublicKey,
45
46
  vaultTypeAccount.collateralMint
46
47
  )
47
48
  const vaultAssociatedTokenAccount = await findAssociatedTokenAddress(vaultPublicKey, vaultTypeAccount.collateralMint)
@@ -49,7 +50,7 @@ export async function repayVault(
49
50
  const [oldSmallerPublicKey, newSmallerPublicKey, newLargerPublicKey] = await getLinkedListAccounts(
50
51
  program,
51
52
  provider,
52
- vaultAccount.vaultType,
53
+ vaultTypeAccountPublicKey,
53
54
  vaultPublicKey,
54
55
  0,
55
56
  repayAmount * -1,
@@ -66,7 +67,7 @@ export async function repayVault(
66
67
  vaultPublicKey,
67
68
  vaultAssociatedTokenAccount,
68
69
  history.publicKey,
69
- vaultAccount.vaultType,
70
+ vaultTypeAccountPublicKey,
70
71
  vaultTypeAssociatedTokenAccount,
71
72
  oldSmallerPublicKey,
72
73
  newSmallerPublicKey,
@@ -37,6 +37,7 @@ export async function withdrawVault(
37
37
  const history = Keypair.generate()
38
38
  const vaultSystemStatePublicKey = await getVaultSystemStatePublicKey()
39
39
  const vaultAccount = await program.account.vault.fetch(vaultPublicKey)
40
+ const vaultTypeAccountPublicKey = await getVaultTypeAccountPublicKey(vaultAccount.collateralType)
40
41
  const vaultAssociatedCollateralAccount = await getOrCreateAssociatedTokenAccount(
41
42
  provider.connection,
42
43
  payer,
@@ -45,12 +46,12 @@ export async function withdrawVault(
45
46
  true
46
47
  )
47
48
 
48
- const vaultTypeAccountInfo = await program.account.vaultType.fetch(vaultAccount.vaultType)
49
+ const vaultTypeAccountInfo = await program.account.vaultType.fetch(vaultTypeAccountPublicKey)
49
50
  const vaultTypeAssociatedTokenAccount = await getOrCreateAssociatedTokenAccount(
50
51
  provider.connection,
51
52
  payer,
52
53
  vaultTypeAccountInfo.collateralMint,
53
- vaultAccount.vaultType,
54
+ vaultTypeAccountPublicKey,
54
55
  true
55
56
  )
56
57
 
@@ -69,7 +70,7 @@ export async function withdrawVault(
69
70
  const [oldSmallerPublicKey, newSmallerPublicKey, newLargerPublicKey] = await getLinkedListAccounts(
70
71
  program,
71
72
  provider,
72
- vaultAccount.vaultType,
73
+ vaultTypeAccountPublicKey,
73
74
  vaultPublicKey,
74
75
  withdrawAmount * -1,
75
76
  0,
@@ -85,7 +86,7 @@ export async function withdrawVault(
85
86
  destinationTokenAccount.address,
86
87
  vaultPublicKey,
87
88
  vaultAssociatedCollateralAccount.address,
88
- vaultAccount.vaultType,
89
+ vaultTypeAccountPublicKey,
89
90
  vaultTypeAssociatedTokenAccount.address,
90
91
  hedgeStakingPoolPublicKey,
91
92
  hedgeStakingPoolAssociatedUshTokenAccount,
@@ -18,10 +18,10 @@ export class VaultAccount {
18
18
  pdaSalt: string
19
19
 
20
20
  /** The deposited collateral of the vault (in SOL Lamports). */
21
- deposited: number
21
+ deposited = new Decimal(0)
22
22
 
23
23
  /** The outstanding debt of the vault (in USH Lamports). Denormalized to time 0. */
24
- denormalizedDebt: number
24
+ denormalizedDebt = new Decimal(0)
25
25
 
26
26
  /** The ordered number of when this vault was created. */
27
27
  vaultNumber: number
@@ -32,8 +32,8 @@ export class VaultAccount {
32
32
  /** Collateral redistribution snapshot' */
33
33
  collateralAccumulatorSnapshotBytes = new Decimal(0)
34
34
 
35
- /** The vault type eg '2-SOL-150-0' */
36
- vaultTypeName: string
35
+ /** The vault type eg 'SOL-150' */
36
+ collateralType: string
37
37
 
38
38
  /** Current State of the vault ("Open", "Closed", "Liquidated") */
39
39
  vaultStatus = ''
@@ -41,29 +41,29 @@ export class VaultAccount {
41
41
  /** The public key of the next vault to redeem. */
42
42
  nextVaultToRedeem: PublicKey
43
43
 
44
- /** The public key of the vault type. */
45
- vaultType: PublicKey
46
-
47
44
  constructor(vault: any, publicKey: PublicKey) {
48
45
  this.publicKey = publicKey
49
46
  this.vaultOwner = vault.vaultOwner
50
47
  this.vaultNumber = vault.vaultNumber?.toNumber()
51
48
  this.pdaSalt = vault.pdaSalt
52
- this.deposited = vault.deposited?.toNumber()
53
- this.denormalizedDebt = vault.denormalizedDebt?.toNumber()
49
+ if (vault.deposited){
50
+ this.deposited = new Decimal(vault.deposited.toString())
51
+ }
52
+ if (vault.denormalizedDebt){
53
+ this.denormalizedDebt = new Decimal(vault.denormalizedDebt.toString())
54
+ }
54
55
  if (vault.debtProductSnapshotBytes) {
55
56
  this.debtProductSnapshotBytes = DecimalFromU128(vault.debtProductSnapshotBytes.toString())
56
57
  }
57
58
  if (vault.collateralAccumulatorSnapshotBytes) {
58
59
  this.collateralAccumulatorSnapshotBytes = DecimalFromU128(vault.collateralAccumulatorSnapshotBytes.toString())
59
60
  }
60
- this.vaultTypeName = vault.vaultTypeName
61
+ this.collateralType = vault.collateralType
61
62
  this.nextVaultToRedeem = vault.nextVaultToRedeem
62
63
 
63
64
  if (vault.vaultStatus) {
64
65
  this.vaultStatus = Object.keys(vault.vaultStatus)[0]
65
66
  }
66
- this.vaultType = vault.vaultType
67
67
  }
68
68
 
69
69
  /**
@@ -82,7 +82,7 @@ export class VaultAccount {
82
82
  * @returns collateral value in SOL
83
83
  */
84
84
  public inSol(): number {
85
- return this.deposited / LAMPORTS_PER_SOL
85
+ return this.deposited.div(LAMPORTS_PER_SOL).toNumber()
86
86
  }
87
87
 
88
88
  /**
@@ -91,7 +91,7 @@ export class VaultAccount {
91
91
  * @returns debt value in USH
92
92
  */
93
93
  public inUsd(): number {
94
- return this.denormalizedDebt / LAMPORTS_PER_SOL
94
+ return this.denormalizedDebt.div(LAMPORTS_PER_SOL).toNumber()
95
95
  }
96
96
 
97
97
  /**
@@ -107,37 +107,37 @@ export class VaultAccount {
107
107
 
108
108
  public addDebt(newNormalizedDebt: Decimal, vaultTypeCompoundedInterest: Decimal) {
109
109
  const denormalizedNewDebt = newNormalizedDebt.div(vaultTypeCompoundedInterest)
110
- this.denormalizedDebt = denormalizedNewDebt.add(new Decimal(this.denormalizedDebt)).floor().toNumber()
110
+ this.denormalizedDebt = denormalizedNewDebt.add(new Decimal(this.denormalizedDebt)).floor()
111
111
  // this.denormalizedDebt = parseFloat(this.denormalizedDebt.toFixed(0))
112
112
  }
113
113
  public addDeposit(depositAmount: number) {
114
- this.deposited += depositAmount
114
+ this.deposited = this.deposited.add(depositAmount)
115
115
  }
116
116
 
117
117
  public redeem() {
118
118
  // TODO - Calculate actual redeem amount and adust correctly
119
- this.denormalizedDebt = 0
119
+ this.denormalizedDebt = new Decimal(0)
120
120
  this.vaultStatus = 'initialized'
121
121
  }
122
122
  public liquidate() {
123
123
  // TODO - Calculate actual liquidate amount and adust correctly
124
- this.denormalizedDebt = 0
124
+ this.denormalizedDebt = new Decimal(0)
125
125
  this.vaultStatus = 'liquidated'
126
126
  }
127
127
 
128
- public updateDebtAndCollateral(vaultTypeAccountData: any) {
129
- const debtProductCurrent = DecimalFromU128(vaultTypeAccountData.debtRedistributionProduct)
128
+ public updateDebtAndCollateral(vaultTypeAccuntData: any) {
129
+ const debtProductCurrent = DecimalFromU128(vaultTypeAccuntData.debtRedistributionProduct)
130
130
 
131
- const collateralAccumulatorCurrent = DecimalFromU128(vaultTypeAccountData.collateralRedistributionAccumulator)
131
+ const collateralAccumulatorCurrent = DecimalFromU128(vaultTypeAccuntData.collateralRedistributionAccumulator)
132
132
 
133
133
  this.denormalizedDebt = debtProductCurrent
134
134
  .div(this.debtProductSnapshotBytes)
135
135
  .mul(new Decimal(this.denormalizedDebt))
136
- .toNumber()
137
136
 
138
137
  const extraCollateralDeposited =
139
- this.denormalizedDebt * collateralAccumulatorCurrent.sub(this.collateralAccumulatorSnapshotBytes).toNumber()
140
- this.deposited += extraCollateralDeposited
138
+ this.denormalizedDebt.mul(collateralAccumulatorCurrent.sub(this.collateralAccumulatorSnapshotBytes))
139
+
140
+ this.deposited = this.deposited.add(extraCollateralDeposited)
141
141
 
142
142
  this.collateralAccumulatorSnapshotBytes = collateralAccumulatorCurrent
143
143
  this.debtProductSnapshotBytes = debtProductCurrent
@@ -149,7 +149,7 @@ export class VaultAccount {
149
149
  arrow = ' <----!!'
150
150
  }
151
151
  let collateralRatio = 'Infinite'
152
- if (this.denormalizedDebt > 0) {
152
+ if (this.denormalizedDebt.greaterThan(0)) {
153
153
  collateralRatio = new Decimal(this.deposited).div(new Decimal(this.denormalizedDebt)).toString()
154
154
  }
155
155
 
@@ -160,7 +160,7 @@ export class VaultAccount {
160
160
 
161
161
  return `Vault(${this.vaultNumber}): ${this.publicKey.toString().substring(0, 6)}. Debt: ${
162
162
  this.denormalizedDebt
163
- } Collat: ${this.deposited} Ratio: ${collateralRatio} ${arrow} `
163
+ } Collat: ${this.deposited} Ratio: ${collateralRatio} NextVault: ${nextVault} ${arrow} `
164
164
  }
165
165
  /**
166
166
  * Creates a VaultAccount from a slice of data
@@ -22,7 +22,7 @@ export async function getLinkedListAccounts(
22
22
  liquidate: boolean,
23
23
  cachedVaults?: VaultAccount[]
24
24
  ): Promise<[PublicKey, PublicKey, PublicKey, VaultAccount[]]> {
25
- // console.log('Getting getLinkedListAccounts')
25
+ console.log('Getting getLinkedListAccounts')
26
26
  const vaultTypeAccount = await program.account.vaultType.fetch(vaultTypeAccountPublicKey)
27
27
 
28
28
  // Default for null is the vault itself, so set them all to this vault
@@ -31,7 +31,6 @@ export async function getLinkedListAccounts(
31
31
  let newLargerPublicKey = vaultPublicKey
32
32
 
33
33
  const thisVaultData = await program.account.vault.fetch(vaultPublicKey)
34
- const accountInfo = await program.provider.connection.getAccountInfo(vaultPublicKey)
35
34
  const thisVault = new VaultAccount(thisVaultData, vaultPublicKey)
36
35
 
37
36
  // Load all the vaults
@@ -55,11 +54,11 @@ export async function getLinkedListAccounts(
55
54
  // vaults = allVaults.map((vault) => {
56
55
  // return new VaultAccount(vault.account, vault.publicKey)
57
56
  // })
58
- vaults = await getMiniVaults(program, vaultTypeAccount.vaultTypeName)
57
+ vaults = await getMiniVaults(program, vaultTypeAccount.collateralType)
59
58
  }
60
59
 
61
- // console.log('Vault count found:', vaults.length)
62
- // console.log('First Vault', vaults[0])
60
+ console.log('Vault count found:', vaults.length)
61
+ console.log('First Vault', vaults[0])
63
62
 
64
63
  // Filter out the accounts that are not open
65
64
  // TODO filter on vault status. Or we enable people to "close out" empty vaults
@@ -69,7 +68,7 @@ export async function getLinkedListAccounts(
69
68
 
70
69
  // Remove any vaults with no debt or collateral
71
70
  vaults = _.filter(vaults, (vault) => {
72
- return vault.denormalizedDebt > 0 && vault.deposited > 0
71
+ return vault.denormalizedDebt.greaterThan(0) && vault.deposited.greaterThan(0)
73
72
  })
74
73
 
75
74
  // Sort them
@@ -88,12 +87,6 @@ export async function getLinkedListAccounts(
88
87
  oldSmallerPublicKey = vaults[indexBefore - 1].publicKey
89
88
  }
90
89
 
91
- // Pretty print the list again
92
- // console.log('Sorted open vaults. Index Before: ', indexBefore)
93
- // console.log(vaults.map((vault) => {
94
- // return vault.toString(vaultPublicKey)
95
- // }))
96
-
97
90
  // Pretty print all the vaults before the operation
98
91
  // console.log('Sorted open vaults BEFORE at index:', indexBefore)
99
92
  // let correctOrderBefore = true
@@ -137,13 +130,19 @@ export async function getLinkedListAccounts(
137
130
  vaults[indexBefore].redeem()
138
131
  }
139
132
 
140
- if (vaults[indexBefore].denormalizedDebt === 0) {
133
+ if (vaults[indexBefore].denormalizedDebt.isZero()) {
141
134
  vaults.splice(indexBefore, 1)
142
135
  }
143
136
 
144
137
  // Sort it again since we've changed one vault
145
138
  vaults = vaults.sort(sortVaults)
146
139
 
140
+ // Pretty print the list again
141
+ // console.log('Sorted open vaults with new debt added at index: ', indexAfter)
142
+ // console.log(vaults.map((vault) => {
143
+ // return vault.toString(vaultPublicKey)
144
+ // }))
145
+
147
146
  // Search for the vaults new position
148
147
  let indexAfter = -1
149
148
  vaults.forEach((vault, index) => {
@@ -161,7 +160,8 @@ export async function getLinkedListAccounts(
161
160
  // )
162
161
 
163
162
  // Print where it moved from / to
164
- // console.log('Index After', indexAfter)
163
+ console.log('Index Before', indexBefore)
164
+ console.log('Index After', indexAfter)
165
165
 
166
166
  // Save references to the new left and right
167
167
  if (indexAfter > 0) {
@@ -182,15 +182,19 @@ export async function getLinkedListAccounts(
182
182
  // Sort function we can use to sort the vaults
183
183
  // Sorted by collateral ratio. If two are the same, newer vault first
184
184
  function sortVaults(a: VaultAccount, b: VaultAccount) {
185
- const aRatio = a.deposited / a.denormalizedDebt
186
- const bRatio = b.deposited / b.denormalizedDebt
187
- if (aRatio === bRatio) {
185
+ const aRatio = a.deposited.floor().div(a.denormalizedDebt.floor())
186
+ const bRatio = b.deposited.floor().div(b.denormalizedDebt.floor())
187
+ if (aRatio.equals(bRatio)) {
188
188
  return b.vaultNumber - a.vaultNumber
189
189
  }
190
- return aRatio - bRatio
190
+ if (aRatio.greaterThan(bRatio)){
191
+ return 1
192
+ }
193
+
194
+ return -1
191
195
  }
192
196
 
193
- async function getMiniVaults(program: Program<Vault>, vaultTypeName: string ) {
197
+ async function getMiniVaults(program: Program<Vault>, collateralType: string) {
194
198
  const filters = [
195
199
  // Filter for Vault Accounts
196
200
  {
@@ -200,7 +204,7 @@ async function getMiniVaults(program: Program<Vault>, vaultTypeName: string ) {
200
204
  // Filter for Vaults with this collateral type
201
205
  {
202
206
  memcmp: {
203
- bytes: base58.encode(VaultAccount.getBufferForString(vaultTypeName)),
207
+ bytes: base58.encode(VaultAccount.getBufferForString(collateralType)),
204
208
  offset: 8 + 32 + 24,
205
209
  },
206
210
  },