hedge-web3 0.1.27 → 0.1.31

Sign up to get free protection for your applications and to get access to all the features.
Files changed (80) hide show
  1. package/declarations/Constants.d.ts +1 -1
  2. package/declarations/idl/vault.d.ts +277 -126
  3. package/declarations/index.d.ts +3 -0
  4. package/declarations/instructions/claimLiquidationPoolPosition.d.ts +3 -2
  5. package/declarations/instructions/claimStakingPoolPosition.d.ts +3 -2
  6. package/declarations/instructions/closeLiquidationPoolPosition.d.ts +3 -2
  7. package/declarations/instructions/createStakingPool.d.ts +3 -2
  8. package/declarations/instructions/createVault.d.ts +6 -5
  9. package/declarations/instructions/depositLiquidationPool.d.ts +3 -2
  10. package/declarations/instructions/depositStakingPool.d.ts +3 -2
  11. package/declarations/instructions/depositVault.d.ts +3 -2
  12. package/declarations/instructions/initHedgeFoundation.d.ts +3 -2
  13. package/declarations/instructions/liquidateVault.d.ts +3 -2
  14. package/declarations/instructions/loanVault.d.ts +3 -2
  15. package/declarations/instructions/redeemVault.d.ts +3 -2
  16. package/declarations/instructions/refreshOraclePrice.d.ts +3 -2
  17. package/declarations/instructions/repayVault.d.ts +3 -2
  18. package/declarations/instructions/setHalted.d.ts +3 -2
  19. package/declarations/instructions/setVaultTypeStatus.d.ts +5 -0
  20. package/declarations/instructions/withdrawStakingPool.d.ts +3 -2
  21. package/declarations/instructions/withdrawVault.d.ts +3 -2
  22. package/declarations/state/VaultAccount.d.ts +8 -0
  23. package/declarations/utils/getLinkedListAccounts.d.ts +5 -0
  24. package/lib/Constants.js +1 -1
  25. package/lib/idl/vault.js +277 -126
  26. package/lib/index.js +3 -0
  27. package/lib/instructions/claimLiquidationPoolPosition.js +19 -22
  28. package/lib/instructions/claimStakingPoolPosition.js +19 -19
  29. package/lib/instructions/closeLiquidationPoolPosition.js +22 -22
  30. package/lib/instructions/createStakingPool.js +18 -19
  31. package/lib/instructions/createVault.js +28 -31
  32. package/lib/instructions/depositLiquidationPool.js +17 -18
  33. package/lib/instructions/depositStakingPool.js +16 -18
  34. package/lib/instructions/depositVault.js +31 -26
  35. package/lib/instructions/initHedgeFoundation.js +17 -19
  36. package/lib/instructions/initHedgeFoundationTokens.js +15 -15
  37. package/lib/instructions/liquidateVault.js +36 -32
  38. package/lib/instructions/loanVault.js +27 -22
  39. package/lib/instructions/redeemVault.js +28 -23
  40. package/lib/instructions/refreshOraclePrice.js +17 -17
  41. package/lib/instructions/repayVault.js +27 -22
  42. package/lib/instructions/setHalted.js +8 -9
  43. package/lib/instructions/setVaultTypeStatus.js +37 -0
  44. package/lib/instructions/withdrawStakingPool.js +22 -24
  45. package/lib/instructions/withdrawVault.js +30 -25
  46. package/lib/state/LiquidationPoolEra.js +3 -1
  47. package/lib/state/LiquidationPosition.js +0 -7
  48. package/lib/state/StakingPool.js +3 -4
  49. package/lib/state/VaultAccount.js +51 -1
  50. package/lib/utils/getLinkedListAccounts.js +139 -0
  51. package/package.json +4 -2
  52. package/src/Constants.ts +1 -1
  53. package/src/idl/vault.ts +554 -252
  54. package/src/index.ts +4 -0
  55. package/src/instructions/claimLiquidationPoolPosition.ts +39 -29
  56. package/src/instructions/claimStakingPoolPosition.ts +45 -25
  57. package/src/instructions/closeLiquidationPoolPosition.ts +62 -32
  58. package/src/instructions/createStakingPool.ts +38 -37
  59. package/src/instructions/createVault.ts +81 -125
  60. package/src/instructions/depositLiquidationPool.ts +45 -26
  61. package/src/instructions/depositStakingPool.ts +32 -24
  62. package/src/instructions/depositVault.ts +77 -31
  63. package/src/instructions/initHedgeFoundation.ts +42 -43
  64. package/src/instructions/initHedgeFoundationTokens.ts +38 -39
  65. package/src/instructions/liquidateVault.ts +96 -22
  66. package/src/instructions/loanVault.ts +84 -30
  67. package/src/instructions/redeemVault.ts +91 -32
  68. package/src/instructions/refreshOraclePrice.ts +41 -32
  69. package/src/instructions/repayVault.ts +74 -29
  70. package/src/instructions/setHalted.ts +32 -24
  71. package/src/instructions/setVaultTypeStatus.ts +58 -0
  72. package/src/instructions/withdrawStakingPool.ts +44 -30
  73. package/src/instructions/withdrawVault.ts +87 -33
  74. package/src/state/LiquidationPoolEra.ts +4 -3
  75. package/src/state/LiquidationPosition.ts +0 -27
  76. package/src/state/StakingPool.ts +4 -7
  77. package/src/state/StakingPoolPosition.ts +2 -3
  78. package/src/state/VaultAccount.ts +65 -8
  79. package/src/state/VaultHistoryEvent.ts +1 -2
  80. package/src/utils/getLinkedListAccounts.ts +157 -0
@@ -11,7 +11,9 @@ class LiquidationPoolEra {
11
11
  this.liquidyPoolEra = liquidyPoolEra;
12
12
  this.totalDeposits = liquidyPoolEra.totalDeposits.toNumber();
13
13
  this.product = (0, HedgeDecimal_1.DecimalFromU128)(liquidyPoolEra.productBytes);
14
- this.sum = liquidyPoolEra.sumBytes.map((sumBytes) => { return (0, HedgeDecimal_1.DecimalFromU128)(sumBytes); });
14
+ this.sum = liquidyPoolEra.sumBytes.map((sumBytes) => {
15
+ return (0, HedgeDecimal_1.DecimalFromU128)(sumBytes);
16
+ });
15
17
  this.hedgeRewardsAccumulator = (0, HedgeDecimal_1.DecimalFromU128)(liquidyPoolEra.hedgeRewardsAccumulatorBytes);
16
18
  this.hedgeRewardsTimestamp = liquidyPoolEra.hedgeRewardsTimestamp.toNumber();
17
19
  }
@@ -31,10 +31,3 @@ class LiquidationPosition {
31
31
  }
32
32
  }
33
33
  exports.LiquidationPosition = LiquidationPosition;
34
- // function hedgeRewardsDecay (supply: number, birthTime: number, timeIn: number, timeOut: number, halfLifeInDays: number): number {
35
- // const timeInOffsetStart = timeIn - birthTime
36
- // const timeOutOffsetStart = timeOut - birthTime
37
- // const halfLife = -1 * Math.log(2) / (halfLifeInDays * 60 * 60 * 24)
38
- // const awardedTokens = supply * (Math.pow(Math.E, halfLife * timeInOffsetStart) - Math.pow(Math.E, halfLife * timeOutOffsetStart))
39
- // return awardedTokens
40
- // }
@@ -7,16 +7,15 @@ class StakingPool {
7
7
  this.poolInfo = poolInfo;
8
8
  this.publicKey = publicKey;
9
9
  this.deposits = poolInfo.deposits.toNumber();
10
- // this.totalFeesNow = poolInfo.totalFeesNow.toNumber()
11
- // this.totalFeesPrevious = poolInfo.totalFeesPrevious.toNumber()
12
10
  this.lastTransactionTime = poolInfo.lastTransactionTime.toNumber();
13
11
  this.startTime = poolInfo.startTime.toNumber();
14
12
  this.halfLifeInDays = poolInfo.halfLifeInDays.toNumber();
15
13
  this.totalHedgeReward = poolInfo.totalHedgeReward.toNumber();
16
14
  this.hedgeRewardAccumulator = (0, HedgeDecimal_1.DecimalFromU128)(poolInfo.hedgeRewardAccumulator);
17
15
  this.ushFeeAccumulator = (0, HedgeDecimal_1.DecimalFromU128)(poolInfo.ushFeeAccumulator);
18
- this.collateralFeeAccumulator = poolInfo.collateralFeeAccumulator.map((sum) => { return (0, HedgeDecimal_1.DecimalFromU128)(sum); });
19
- // this.currentRewardsPerDay = DecimalFromU128(poolInfo.currentRewardsPerDay)
16
+ this.collateralFeeAccumulator = poolInfo.collateralFeeAccumulator.map((sum) => {
17
+ return (0, HedgeDecimal_1.DecimalFromU128)(sum);
18
+ });
20
19
  }
21
20
  }
22
21
  exports.StakingPool = StakingPool;
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.VaultAccount = void 0;
4
7
  const web3_js_1 = require("@solana/web3.js");
8
+ const decimal_js_1 = __importDefault(require("decimal.js"));
5
9
  const HedgeDecimal_1 = require("../HedgeDecimal");
6
10
  /**
7
11
  * A class that represents an on-chian vault.
@@ -10,6 +14,7 @@ class VaultAccount {
10
14
  constructor(vault, publicKey) {
11
15
  this.publicKey = publicKey;
12
16
  this.vaultOwner = vault.vaultOwner;
17
+ this.vaultNumber = vault.vaultNumber.toNumber();
13
18
  this.pdaSalt = vault.pdaSalt;
14
19
  this.deposited = vault.deposited.toNumber();
15
20
  this.denormalizedDebt = vault.denormalizedDebt.toNumber();
@@ -49,7 +54,52 @@ class VaultAccount {
49
54
  * @returns example: `1b6ca...azy71s`
50
55
  */
51
56
  toDisplayString() {
52
- return `${this.publicKey.toString().substring(0, 6)}...${this.publicKey.toString().substring(this.publicKey.toString().length - 6)}`;
57
+ return `${this.publicKey.toString().substring(0, 6)}...${this.publicKey
58
+ .toString()
59
+ .substring(this.publicKey.toString().length - 6)}`;
60
+ }
61
+ addDebt(newNormalizedDebt, vaultTypeCompoundedInterest) {
62
+ const denormalizedNewDebt = newNormalizedDebt.div(vaultTypeCompoundedInterest);
63
+ this.denormalizedDebt += denormalizedNewDebt.toNumber();
64
+ }
65
+ addDeposit(depositAmount) {
66
+ this.deposited += depositAmount;
67
+ }
68
+ redeem() {
69
+ // TODO - Calculate actual redeem amount and adust correctly
70
+ this.denormalizedDebt = 0;
71
+ this.vaultStatus = 'initialized';
72
+ }
73
+ liquidate() {
74
+ // TODO - Calculate actual liquidate amount and adust correctly
75
+ this.denormalizedDebt = 0;
76
+ this.vaultStatus = 'liquidated';
77
+ }
78
+ updateDebtAndCollateral(vaultTypeAccuntData) {
79
+ const debtProductCurrent = (0, HedgeDecimal_1.DecimalFromU128)(vaultTypeAccuntData.debtRedistributionProduct);
80
+ const collateralAccumulatorCurrent = (0, HedgeDecimal_1.DecimalFromU128)(vaultTypeAccuntData.collateralRedistributionAccumulator);
81
+ this.denormalizedDebt = debtProductCurrent
82
+ .div(this.debtProductSnapshotBytes)
83
+ .mul(new decimal_js_1.default(this.denormalizedDebt))
84
+ // .add(new Decimal(vaultTypeAccuntData.debtRedistributionError))
85
+ .toNumber();
86
+ const extraCollateralDeposited = this.denormalizedDebt * collateralAccumulatorCurrent.sub(this.collateralAccumulatorSnapshotBytes).toNumber();
87
+ this.deposited += extraCollateralDeposited;
88
+ this.collateralAccumulatorSnapshotBytes = collateralAccumulatorCurrent;
89
+ this.debtProductSnapshotBytes = debtProductCurrent;
90
+ }
91
+ toString(highlight) {
92
+ let arrow = '';
93
+ if (this.publicKey.toString() === highlight.toString()) {
94
+ arrow = ' <----';
95
+ }
96
+ let collateralRatio = 'Infinite';
97
+ if (this.denormalizedDebt > 0) {
98
+ collateralRatio = (this.deposited / this.denormalizedDebt).toFixed(8);
99
+ }
100
+ return `Vault(${this.vaultNumber}): ${this.publicKey
101
+ .toString()
102
+ .substring(0, 6)}. Debt: ${this.inUsd()} Collat: ${collateralRatio} ${arrow}`;
53
103
  }
54
104
  }
55
105
  exports.VaultAccount = VaultAccount;
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.getLinkedListAccounts = void 0;
16
+ const underscore_1 = __importDefault(require("underscore"));
17
+ const HedgeDecimal_1 = require("../HedgeDecimal");
18
+ const VaultAccount_1 = require("../state/VaultAccount");
19
+ const decimal_js_1 = __importDefault(require("decimal.js"));
20
+ function getLinkedListAccounts(program, provider, vaultTypeAccountPublicKey, vaultPublicKey, depositAmount, loanAmount, redeem, liquidate, cachedVaults) {
21
+ return __awaiter(this, void 0, void 0, function* () {
22
+ const vaultTypeAccount = yield program.account.vaultType.fetch(vaultTypeAccountPublicKey);
23
+ // Default for null is the vault itself, so set them all to this vault
24
+ let oldSmallerPublicKey = vaultPublicKey;
25
+ let newSmallerPublicKey = vaultPublicKey;
26
+ let newLargerPublicKey = vaultPublicKey;
27
+ const thisVaultData = yield program.account.vault.fetch(vaultPublicKey);
28
+ const thisVault = new VaultAccount_1.VaultAccount(thisVaultData, vaultPublicKey);
29
+ // Load all the vaults
30
+ let vaults;
31
+ if (cachedVaults) {
32
+ vaults = cachedVaults;
33
+ }
34
+ else {
35
+ let allVaults = cachedVaults
36
+ ? cachedVaults
37
+ : (yield program.account.vault
38
+ .all([
39
+ // {
40
+ // memcmp: { bytes: bs58.encode(inputCollateralType), offset: 8 + 32 + 8 },
41
+ // },
42
+ ])
43
+ .catch((error) => {
44
+ console.log('error', error);
45
+ })) || [];
46
+ // Load them into our account objects
47
+ vaults = allVaults.map((vault) => {
48
+ return new VaultAccount_1.VaultAccount(vault.account, vault.publicKey);
49
+ });
50
+ }
51
+ // Filter out the account that are not the same vault type
52
+ vaults = underscore_1.default.filter(vaults, (vault) => {
53
+ return vault.collateralType === vaultTypeAccount.collateralType;
54
+ });
55
+ // Filter out the accounts that are not open
56
+ vaults = underscore_1.default.filter(vaults, (vault) => {
57
+ return vault.vaultStatus === 'open';
58
+ });
59
+ // Sort them
60
+ vaults.sort(sortVaults);
61
+ // Find the location of the vault before the operation
62
+ let indexBefore = -1;
63
+ vaults.forEach((vault, index) => {
64
+ if (vault.publicKey.toString() === vaultPublicKey.toString()) {
65
+ indexBefore = index;
66
+ }
67
+ });
68
+ // If we found it before, set the old smaller vault the one to the left
69
+ if (indexBefore > 0) {
70
+ oldSmallerPublicKey = vaults[indexBefore - 1].publicKey;
71
+ }
72
+ // Pretty print all the vaults before the operation
73
+ // console.log('Sorted open vaults before')
74
+ // vaults.forEach((vault) => {
75
+ // console.log(vault.toString(vaultPublicKey))
76
+ // })
77
+ // If it wasn't in the list, add it now
78
+ if (indexBefore < 0) {
79
+ vaults.push(thisVault);
80
+ indexBefore = vaults.length - 1;
81
+ }
82
+ // Now that we know it's def in the list, iterate the list and update
83
+ // this vault with the opeation we're going to apply
84
+ const newNormalizedDebt = new decimal_js_1.default(loanAmount);
85
+ const vaultTypeCompoundedInterest = (0, HedgeDecimal_1.DecimalFromU128)(vaultTypeAccount.cumulativeRate.toString());
86
+ vaults[indexBefore].updateDebtAndCollateral(vaultTypeAccount);
87
+ vaults[indexBefore].addDebt(newNormalizedDebt, vaultTypeCompoundedInterest);
88
+ vaults[indexBefore].addDeposit(depositAmount);
89
+ if (liquidate) {
90
+ vaults[indexBefore].liquidate();
91
+ }
92
+ if (redeem) {
93
+ vaults[indexBefore].redeem();
94
+ }
95
+ if (vaults[indexBefore].denormalizedDebt === 0) {
96
+ vaults.splice(indexBefore, 1);
97
+ }
98
+ // Sort it again since we've changed one vault
99
+ vaults = vaults.sort(sortVaults);
100
+ // Pretty print the list again
101
+ // console.log('Sorted open vaults with new debt added')
102
+ // vaults.forEach((vault) => {
103
+ // console.log(vault.toString(vaultPublicKey))
104
+ // })
105
+ // Search for the vaults new position
106
+ let indexAfter = -1;
107
+ vaults.forEach((vault, index) => {
108
+ if (vault.publicKey.toString() === vaultPublicKey.toString()) {
109
+ indexAfter = index;
110
+ }
111
+ });
112
+ // Print where it moved from / to
113
+ // console.log('Index Before', indexBefore)
114
+ // console.log('Index After', indexAfter)
115
+ // Save references to the new left and right
116
+ if (indexAfter > 0) {
117
+ newSmallerPublicKey = vaults[indexAfter - 1].publicKey;
118
+ }
119
+ if (indexAfter < vaults.length - 1 && indexAfter >= 0) {
120
+ newLargerPublicKey = vaults[indexAfter + 1].publicKey;
121
+ }
122
+ // Print out the new left/right
123
+ // console.log('oldSmallerPublicKey', oldSmallerPublicKey.toString())
124
+ // console.log('newSmallerPublicKey', newSmallerPublicKey.toString())
125
+ // console.log('newLargerPublicKey', newLargerPublicKey.toString())
126
+ return [oldSmallerPublicKey, newSmallerPublicKey, newLargerPublicKey, vaults];
127
+ });
128
+ }
129
+ exports.getLinkedListAccounts = getLinkedListAccounts;
130
+ // Sort function we can use to sort the vaults
131
+ // Sorted by collateral ratio. If two are the same, newer vault first
132
+ function sortVaults(a, b) {
133
+ const aRatio = a.deposited / a.denormalizedDebt;
134
+ const bRatio = b.deposited / b.denormalizedDebt;
135
+ if (aRatio === bRatio) {
136
+ return b.vaultNumber - a.vaultNumber;
137
+ }
138
+ return aRatio - bRatio;
139
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hedge-web3",
3
- "version": "0.1.27",
3
+ "version": "0.1.31",
4
4
  "description": "Hedge Javascript Web3 API",
5
5
  "main": "lib/index.js",
6
6
  "types": "declarations/index.d.ts",
@@ -14,13 +14,14 @@
14
14
  "author": "Chris Coudron <coudron@hedge.so>",
15
15
  "license": "ISC",
16
16
  "dependencies": {
17
- "@project-serum/anchor": "^0.23.0",
17
+ "@project-serum/anchor": "^0.24.1",
18
18
  "@project-serum/serum": "^0.13.61",
19
19
  "@rollup/plugin-typescript": "^8.3.0",
20
20
  "@solana/buffer-layout": "^4.0.0",
21
21
  "@solana/spl-token": "^0.2.0",
22
22
  "@solana/web3.js": "^1.37.0",
23
23
  "@types/bn.js": "^5.1.0",
24
+ "@types/underscore": "^1.11.4",
24
25
  "@types/uuid": "^8.3.4",
25
26
  "bn.js": "^5.2.0",
26
27
  "decimal.js": "^10.3.1",
@@ -28,6 +29,7 @@
28
29
  "ts-standard": "^11.0.0",
29
30
  "typedoc": "^0.22.10",
30
31
  "typescript": "^4.5.5",
32
+ "underscore": "^1.13.2",
31
33
  "uuid": "^8.3.2"
32
34
  }
33
35
  }
package/src/Constants.ts CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  } from '@solana/spl-token'
5
5
  import { PublicKey } from '@solana/web3.js'
6
6
 
7
- export const HEDGE_PROGRAM_ID = 'HDG2DRczYGkTuYTwTYy1UUhXXucT2Ujede2j4bWEoE6p'
7
+ export const HEDGE_PROGRAM_ID = 'HDG3uyafYaKxSYRW37ZBTdxaUCoyzaqbuirYucAeaPFY'
8
8
  export const HEDGE_PROGRAM_PUBLICKEY = new PublicKey(HEDGE_PROGRAM_ID)
9
9
 
10
10
  export const CHAINLINK_SOL_USD_ID =