@evaafi/sdk 0.5.6-a → 0.6.0-a

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.
package/src/api/prices.ts CHANGED
@@ -1,69 +1,45 @@
1
- import { beginCell, Cell, Dictionary } from '@ton/core';
2
- import { PriceData } from '../types/Common';
3
- import { MAIN_POOL_NFT_ID } from '../constants/general';
1
+ import { Dictionary } from '@ton/core';
2
+ import { PriceData, RawPriceData } from '../types/Common';
3
+ import { getMedianPrice, loadPrices, packAssetsData, packOraclesData, packPrices, parsePrices, verifyPrices } from '../utils/priceUtils';
4
+ import { OracleNFT, PoolConfig } from '../types/Master';
5
+ import { MAINNET_POOL_CONFIG } from '../constants/pools';
4
6
 
5
- type NftData = {
6
- ledgerIndex: number;
7
- pageSize: number;
8
- items: string[];
9
- };
7
+ export async function getPrices(endpoints: String[] = ["api.stardust-mainnet.iotaledger.net", "iota.evaa.finance"], poolConfig: PoolConfig = MAINNET_POOL_CONFIG): Promise<PriceData> {
8
+ if (endpoints.length == 0) {
9
+ throw new Error("Empty endpoint list");
10
+ }
11
+
12
+ const prices = await Promise.all(poolConfig.oracles.map(async x => await parsePrices(await loadPrices(x.address, endpoints), x.id)));
13
+
14
+ let acceptedPrices: RawPriceData[] = prices.filter(verifyPrices(poolConfig.poolAssetsConfig));
10
15
 
11
- type OutputData = {
12
- metadata: {
13
- blockId: string;
14
- transactionId: string;
15
- outputIndex: number;
16
- isSpent: boolean;
17
- milestoneIndexSpent: number;
18
- milestoneTimestampSpent: number;
19
- transactionIdSpent: string;
20
- milestoneIndexBooked: number;
21
- milestoneTimestampBooked: number;
22
- ledgerIndex: number;
23
- };
24
- output: {
25
- type: number;
26
- amount: string;
27
- nftId: string;
28
- unlockConditions: {
29
- type: number;
30
- address: {
31
- type: number;
32
- pubKeyHash: string;
33
- };
34
- }[];
35
- features: {
36
- type: number;
37
- data: string;
38
- }[];
39
- };
40
- }
41
16
 
42
- export async function getPrices(endpoints: string[] = ["api.stardust-mainnet.iotaledger.net"], nftId: string = MAIN_POOL_NFT_ID) {
43
- return await Promise.any(endpoints.map(x => loadPrices(nftId, x)));
44
- }
17
+ if (acceptedPrices.length < poolConfig.minimalOracles) {
18
+ throw new Error("Prices are outdated");
19
+ }
20
+
21
+ if (acceptedPrices.length > poolConfig.minimalOracles && acceptedPrices.length % 2 == 0) {
22
+ acceptedPrices = acceptedPrices.slice(0, acceptedPrices.length - 1); // to reduce fees, MINIMAL_ORACLES_NUMBER is odd
23
+ }
45
24
 
46
- async function loadPrices(nftId: string, endpoint: string = "api.stardust-mainnet.iotaledger.net"): Promise<PriceData> {
47
- let result = await fetch(`https://${endpoint}/api/indexer/v1/outputs/nft/${nftId}`, {
48
- headers: { accept: 'application/json' },
49
- });
50
- let outputId = (await result.json()) as NftData;
25
+ if (acceptedPrices.length != poolConfig.minimalOracles) {
26
+ const sortedByTimestamp = acceptedPrices.slice().sort((a, b) => b.timestamp - a.timestamp);
27
+ const newerPrices = sortedByTimestamp.slice(0, poolConfig.minimalOracles);
28
+ acceptedPrices = newerPrices.sort((a, b) => a.oracleId - b.oracleId);
29
+ }
51
30
 
52
- result = await fetch(`https://${endpoint}/api/core/v2/outputs/${outputId.items[0]}`, {
53
- headers: { accept: 'application/json' },
54
- });
55
31
 
56
- let resData = (await result.json()) as OutputData;
32
+ const medianData = poolConfig.poolAssetsConfig.map(asset => ({ assetId: asset.assetId, medianPrice: getMedianPrice(acceptedPrices, asset.assetId)}));
33
+ const packedMedianData = packAssetsData(medianData);
57
34
 
58
- const data = JSON.parse(
59
- decodeURIComponent(resData.output.features[0].data.replace('0x', '').replace(/[0-9a-f]{2}/g, '%$&')),
60
- );
35
+ const oraclesData = acceptedPrices.map(x => ({oracle: {id: x.oracleId, pubkey: x.pubkey}, data: {timestamp: x.timestamp, prices: x.dict}, signature: x.signature}));
36
+ const packedOracleData = packOraclesData(oraclesData, poolConfig.poolAssetsConfig.map(x => x.assetId));
61
37
 
62
- const pricesCell = Cell.fromBoc(Buffer.from(data['packedPrices'], 'hex'))[0];
63
- const signature = Buffer.from(data['signature'], 'hex');
38
+ const dict = Dictionary.empty<bigint, bigint>();
39
+ medianData.forEach(x => dict.set(x.assetId, x.medianPrice));
64
40
 
65
41
  return {
66
- dict: pricesCell.beginParse().loadDictDirect(Dictionary.Keys.BigUint(256), Dictionary.Values.BigUint(64)),
67
- dataCell: beginCell().storeRef(pricesCell).storeBuffer(signature).endCell(),
42
+ dict: dict,
43
+ dataCell: packPrices(packedMedianData, packedOracleData)
68
44
  };
69
45
  }
package/src/config.ts ADDED
@@ -0,0 +1 @@
1
+ export const TTL_ORACLE_DATA_SEC = 120; // todo back to 120
@@ -1,5 +1,6 @@
1
1
  import { Address, Cell, toNano } from '@ton/core';
2
2
  import { sha256Hash } from '../utils/sha256BigInt';
3
+ import { OracleNFT } from '../types/Master';
3
4
 
4
5
  export const MASTER_CONSTANTS = {
5
6
  FACTOR_SCALE: BigInt(1e12),
@@ -14,15 +15,37 @@ export const MASTER_CONSTANTS = {
14
15
 
15
16
  export const NULL_ADDRESS = Address.parse('UQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJKZ');
16
17
 
18
+
17
19
  export const EVAA_MASTER_MAINNET = Address.parse('EQC8rUZqR_pWV1BylWUlPNBzyiTYVoBEmQkMIQDZXICfnuRr');
18
- export const MAINNET_VERSION = 5;
19
- export const EVAA_MASTER_TESTNET = Address.parse('EQCoIxsE8m0Q_Ui9uM-2RPtVWXqHK0ttuW2Mccuaj4FfdkLl'); // EQBghPVKxgauOyrcyNYNwE2MRRnebaNpDGpVDQLbml_LIXnK
20
- export const TESTNET_VERSION = 5;
20
+ export const MAINNET_VERSION = 6;
21
+ export const EVAA_MASTER_TESTNET = Address.parse('EQDLsg3w-iBj26Gww7neYoJAxiT2t77Zo8ro56b0yuHsPp3C');
22
+ export const TESTNET_VERSION = 0;
21
23
  export const EVAA_LP_MAINNET = Address.parse('EQBIlZX2URWkXCSg3QF2MJZU-wC5XkBoLww-hdWk2G37Jc6N');
22
- export const EVAA_LP_MAINNET_VERSION = 0;
24
+ export const EVAA_LP_MAINNET_VERSION = 2;
25
+
26
+ export const ORACLES_MAINNET: OracleNFT[] = [
27
+ {id: 0, address: '0xd3a8c0b9fd44fd25a49289c631e3ac45689281f2f8cf0744400b4c65bed38e5d'},
28
+ {id: 1, address: '0x2c21cabdaa89739de16bde7bc44e86401fac334a3c7e55305fe5e7563043e191'},
29
+ {id: 2, address: '0x2eb258ce7b5d02466ab8a178ad8b0ba6ffa7b58ef21de3dc3b6dd359a1e16af0'},
30
+ {id: 3, address: '0xf9a0769954b4430bca95149fb3d876deb7799d8f74852e0ad4ccc5778ce68b52'},
31
+ ];
32
+
33
+ export const ORACLES_TESTNET: OracleNFT[] = [
34
+ {id: 0, address: '0x3bb147a37b7a7f874c39320440f352bddd2c9337e31a778731910f0266391650'},
35
+ {id: 1, address: '0x676767e93b05a21aec9023a65f73cffe1c725709c3c964a7c3f0fd4229089bfe'},
36
+ {id: 2, address: '0x9c9e65951b0c5920c286bdb3410babcaf21f85bc9c90c13172988630f1244e0f'},
37
+ {id: 3, address: '0x9dcf880229bfb68d7344fd294624b64f1e0b43b9d858f0fdb1bc6434616c08f5'},
38
+ {id: 4, address: '0x4d1afcf7c0426ca61c405c8cfaef0053a0f0d143740ffed04c8716beb99cd614'},
39
+ {id: 5, address: '0x11c6baa608ed10733051fd74134441d384e471722fbc496b43ea4e3c6652485f'},
40
+ {id: 6, address: '0x2b685672f38dc2fce59013bb740bf24c6037049a1c267bb3b5f6f55d5b195f5f'},
41
+ ];
23
42
 
24
- export const MAIN_POOL_NFT_ID = '0xfb9874544d76ca49c5db9cc3e5121e4c018bc8a2fb2bfe8f2a38c5b9963492f5';
25
- export const LP_POOL_NFT_ID = '0x85f0045998038bebd076987deb4d4c680a323cb04380491eaa7857b6469ba923';
43
+ export const ORACLES_LP: OracleNFT[] = [
44
+ {id: 0, address: '0xd3a8c0b9fd44fd25a49289c631e3ac45689281f2f8cf0744400b4c65bed38e5d'},
45
+ {id: 1, address: '0x2c21cabdaa89739de16bde7bc44e86401fac334a3c7e55305fe5e7563043e191'},
46
+ {id: 2, address: '0x2eb258ce7b5d02466ab8a178ad8b0ba6ffa7b58ef21de3dc3b6dd359a1e16af0'},
47
+ {id: 3, address: '0xf9a0769954b4430bca95149fb3d876deb7799d8f74852e0ad4ccc5778ce68b52'},
48
+ ];
26
49
 
27
50
  export const LENDING_CODE = Cell.fromBoc(
28
51
  Buffer.from(
@@ -47,9 +70,9 @@ export const OPCODES = {
47
70
 
48
71
  export const FEES = {
49
72
  SUPPLY: toNano('0.3'),
50
- WITHDRAW: toNano('0.5'),
51
- SUPPLY_JETTON: toNano('0.29'),
52
- SUPPLY_JETTON_FWD: toNano('0.5'),
73
+ WITHDRAW: toNano('0.35'),
74
+ SUPPLY_JETTON: toNano('0.35'),
75
+ SUPPLY_JETTON_FWD: toNano('0.3'),
53
76
  LIQUIDATION: toNano('0.8'),
54
77
  LIQUIDATION_JETTON: toNano('1'),
55
78
  LIQUIDATION_JETTON_FWD: toNano('0.8'),
@@ -1,13 +1,14 @@
1
1
  import { Address } from "@ton/core";
2
2
  import { JUSDC_MAINNET, JUSDC_TESTNET, JUSDT_MAINNET, JUSDT_TESTNET, STTON_MAINNET, STTON_TESTNET, TON_MAINNET, TON_STORM_MAINNET, TONUSDT_DEDUST_MAINNET, TSTON_MAINNET, USDT_MAINNET, USDT_STORM_MAINNET } from "./assets";
3
3
  import { PoolConfig } from "../types/Master";
4
- import { EVAA_MASTER_MAINNET, EVAA_MASTER_TESTNET, LENDING_CODE, MAINNET_VERSION, MASTER_CONSTANTS, MAIN_POOL_NFT_ID, TESTNET_VERSION, LP_POOL_NFT_ID, EVAA_LP_MAINNET, EVAA_LP_MAINNET_VERSION } from "./general";
4
+ import { EVAA_MASTER_MAINNET, EVAA_MASTER_TESTNET, LENDING_CODE, MAINNET_VERSION, MASTER_CONSTANTS, TESTNET_VERSION, EVAA_LP_MAINNET, EVAA_LP_MAINNET_VERSION, ORACLES_MAINNET, ORACLES_LP, ORACLES_TESTNET } from "./general";
5
5
 
6
6
  export const MAINNET_POOL_CONFIG: PoolConfig = {
7
7
  masterAddress: EVAA_MASTER_MAINNET,
8
8
  masterVersion: MAINNET_VERSION,
9
9
  masterConstants: MASTER_CONSTANTS,
10
- nftId: MAIN_POOL_NFT_ID,
10
+ oracles: ORACLES_MAINNET,
11
+ minimalOracles: 3,
11
12
  poolAssetsConfig: [
12
13
  TON_MAINNET,
13
14
  JUSDT_MAINNET,
@@ -23,7 +24,8 @@ export const TESTNET_POOL_CONFIG: PoolConfig = {
23
24
  masterAddress: EVAA_MASTER_TESTNET,
24
25
  masterVersion: TESTNET_VERSION,
25
26
  masterConstants: MASTER_CONSTANTS,
26
- nftId: MAIN_POOL_NFT_ID,
27
+ oracles: ORACLES_TESTNET,
28
+ minimalOracles: 5,
27
29
  poolAssetsConfig: [
28
30
  TON_MAINNET,
29
31
  JUSDT_TESTNET,
@@ -37,7 +39,8 @@ export const MAINNET_LP_POOL_CONFIG: PoolConfig = {
37
39
  masterAddress: EVAA_LP_MAINNET,
38
40
  masterVersion: EVAA_LP_MAINNET_VERSION,
39
41
  masterConstants: MASTER_CONSTANTS,
40
- nftId: LP_POOL_NFT_ID,
42
+ oracles: ORACLES_LP,
43
+ minimalOracles: 3,
41
44
  poolAssetsConfig: [
42
45
  TON_MAINNET,
43
46
  USDT_MAINNET,
@@ -8,6 +8,7 @@ import {
8
8
  Sender,
9
9
  SendMode,
10
10
  storeStateInit,
11
+ toNano,
11
12
  } from '@ton/core';
12
13
  import {
13
14
  FEES,
@@ -47,10 +48,9 @@ export type SupplyParameters = {
47
48
  userAddress: Address;
48
49
  responseAddress?: Address;
49
50
  forwardAmount?: bigint;
50
- /* Will be in v6
51
51
  amountToTransfer: bigint;
52
- payload: Cell; */
53
- }
52
+ payload: Cell;
53
+ };
54
54
 
55
55
  /**
56
56
  * Parameters for the withdraw message
@@ -67,11 +67,10 @@ export type WithdrawParameters = {
67
67
  amount: bigint;
68
68
  userAddress: Address;
69
69
  includeUserCode: boolean;
70
- priceData: Cell;
71
- asset: PoolAssetConfig;
72
- /* Will be in v6
70
+ asset: PoolAssetConfig
71
+ priceData: Cell;
73
72
  amountToTransfer: bigint;
74
- payload: Cell; */
73
+ payload: Cell;
75
74
  };
76
75
 
77
76
  /**
@@ -90,6 +89,7 @@ export type LiquidationBaseData = {
90
89
  minCollateralAmount: bigint;
91
90
  liquidationAmount: bigint;
92
91
  tonLiquidation: boolean;
92
+ forwardAmount?: bigint;
93
93
  };
94
94
 
95
95
  /**
@@ -103,10 +103,11 @@ export type LiquidationParameters = LiquidationBaseData & {
103
103
  asset: PoolAssetConfig;
104
104
  queryID: bigint;
105
105
  liquidatorAddress: Address;
106
+ responseAddress: Address;
106
107
  includeUserCode: boolean;
107
108
  priceData: Cell;
108
- responseAddress?: Address;
109
- forwardAmount?: bigint;
109
+ payload: Cell;
110
+ payloadForwardAmount: bigint;
110
111
  };
111
112
 
112
113
  /**
@@ -149,9 +150,8 @@ export class Evaa implements Contract {
149
150
  .storeUint(OPCODES.SUPPLY, 32)
150
151
  .storeInt(parameters.includeUserCode ? -1 : 0, 2)
151
152
  .storeAddress(parameters.userAddress)
152
- /* Will be in v6
153
153
  .storeUint(parameters.amountToTransfer, 64)
154
- .storeRef(parameters.payload) */
154
+ .storeRef(parameters.payload)
155
155
  .endCell(),
156
156
  )
157
157
  .endCell();
@@ -162,9 +162,8 @@ export class Evaa implements Contract {
162
162
  .storeInt(parameters.includeUserCode ? -1 : 0, 2)
163
163
  .storeUint(parameters.amount, 64)
164
164
  .storeAddress(parameters.userAddress)
165
- /* Will be in v6
166
165
  .storeUint(parameters.amountToTransfer, 64)
167
- .storeRef(parameters.payload) */
166
+ .storeRef(parameters.payload)
168
167
  .endCell();
169
168
  }
170
169
  }
@@ -181,9 +180,8 @@ export class Evaa implements Contract {
181
180
  .storeUint(parameters.amount, 64)
182
181
  .storeAddress(parameters.userAddress)
183
182
  .storeInt(parameters.includeUserCode ? -1 : 0, 2)
184
- /* Will be in v6
185
183
  .storeUint(parameters.amountToTransfer, 64)
186
- .storeRef(parameters.payload) */
184
+ .storeRef(parameters.payload)
187
185
  .storeRef(parameters.priceData)
188
186
  .endCell();
189
187
  }
@@ -214,6 +212,10 @@ export class Evaa implements Contract {
214
212
  // do not need liquidationAmount in case of jetton liquidation because
215
213
  // the exact amount of transferred jettons for liquidation is known
216
214
  .storeUint(0, 64)
215
+ .storeRef(beginCell()
216
+ .storeUint(parameters.payloadForwardAmount ?? 0, 64)
217
+ .storeRef(parameters.payload)
218
+ .endCell())
217
219
  .storeRef(parameters.priceData)
218
220
  .endCell(),
219
221
  )
@@ -228,6 +230,10 @@ export class Evaa implements Contract {
228
230
  .storeUint(parameters.minCollateralAmount, 64)
229
231
  .storeInt(parameters.includeUserCode ? -1 : 0, 2)
230
232
  .storeUint(parameters.liquidationAmount, 64)
233
+ .storeRef(beginCell()
234
+ .storeUint(parameters.payloadForwardAmount ?? 0, 64)
235
+ .storeRef(parameters.payload)
236
+ .endCell())
231
237
  .storeRef(parameters.priceData)
232
238
  .endCell();
233
239
  }
@@ -382,9 +388,9 @@ export class Evaa implements Contract {
382
388
 
383
389
  async getPrices(provider: ContractProvider, endpoints?: string[]) {
384
390
  if ((endpoints?.length ?? 0) > 0) {
385
- return await getPrices(endpoints, this.poolConfig.nftId);
391
+ return await getPrices(endpoints, this.poolConfig);
386
392
  } else {
387
- return await getPrices(undefined, this.poolConfig.nftId);
393
+ return await getPrices(undefined, this.poolConfig);
388
394
  }
389
395
  }
390
396
  }
@@ -34,6 +34,7 @@ export class EvaaUser implements Contract {
34
34
  provider: ContractProvider,
35
35
  assetsData: ExtendedAssetsData,
36
36
  assetsConfig: ExtendedAssetsConfig,
37
+ applyDust: boolean = false
37
38
  ) {
38
39
  const state = (await provider.getState()).state;
39
40
  if (state.type === 'active') {
@@ -41,7 +42,8 @@ export class EvaaUser implements Contract {
41
42
  state.data!.toString('base64'),
42
43
  assetsData,
43
44
  assetsConfig,
44
- this.poolConfig
45
+ this.poolConfig,
46
+ applyDust
45
47
  );
46
48
  this.lastSync = Math.floor(Date.now() / 1000);
47
49
  } else {
@@ -96,6 +98,7 @@ export class EvaaUser implements Contract {
96
98
  assetsData: ExtendedAssetsData,
97
99
  assetsConfig: ExtendedAssetsConfig,
98
100
  prices: Dictionary<bigint, bigint>,
101
+ applyDust: boolean = false
99
102
  ) {
100
103
  const state = (await provider.getState()).state;
101
104
  if (state.type === 'active') {
@@ -103,9 +106,10 @@ export class EvaaUser implements Contract {
103
106
  state.data!.toString('base64'),
104
107
  assetsData,
105
108
  assetsConfig,
106
- this.poolConfig
109
+ this.poolConfig,
110
+ applyDust
107
111
  );
108
- this._data = parseUserData(this._liteData, assetsData, assetsConfig, prices, this.poolConfig);
112
+ this._data = parseUserData(this._liteData, assetsData, assetsConfig, prices, this.poolConfig, applyDust);
109
113
  this.lastSync = Math.floor(Date.now() / 1000);
110
114
  } else {
111
115
  this._data = { type: 'inactive' };
package/src/index.ts CHANGED
@@ -12,6 +12,7 @@ export {
12
12
  calculateMaximumWithdrawAmount,
13
13
  presentValue,
14
14
  calculateLiquidationData,
15
+ predictHealthFactor
15
16
  } from './api/math';
16
17
 
17
18
  // Parser
@@ -26,6 +27,7 @@ export {
26
27
  EvaaParameters,
27
28
  WithdrawParameters,
28
29
  LiquidationBaseData,
30
+ LiquidationParameters,
29
31
  Evaa,
30
32
  } from './contracts/MasterContract';
31
33
  export { EvaaUser } from './contracts/UserContract';
@@ -46,7 +48,9 @@ export {
46
48
  ExtendedAssetsConfig,
47
49
  PoolAssetConfig,
48
50
  PoolAssetsConfig,
51
+ MasterConstants
49
52
  } from './types/Master';
53
+
50
54
  export {
51
55
  BalanceType,
52
56
  UserBalance,
@@ -1,5 +1,15 @@
1
1
  import { Cell, Dictionary } from '@ton/core';
2
2
 
3
+ export type RawPriceData = {
4
+ dict: Dictionary<bigint, bigint>;
5
+ dataCell: Cell;
6
+ oracleId: number;
7
+ signature: Buffer;
8
+ pubkey: Buffer;
9
+ timestamp: number;
10
+ };
11
+
12
+
3
13
  export type PriceData = {
4
14
  dict: Dictionary<bigint, bigint>;
5
15
  dataCell: Cell;
@@ -24,7 +24,8 @@ export type PoolConfig = {
24
24
  masterAddress: Address;
25
25
  masterVersion: number;
26
26
  masterConstants: MasterConstants;
27
- nftId: string;
27
+ oracles: OracleNFT[];
28
+ minimalOracles: number;
28
29
  poolAssetsConfig: PoolAssetsConfig;
29
30
  lendingCode: Cell;
30
31
  };
@@ -36,7 +37,7 @@ export type UpgradeConfig = {
36
37
  updateTime: number;
37
38
  freezeTime: number;
38
39
  userCode: Cell;
39
- blankCode: Cell;
40
+ //blankCode: Cell;
40
41
  newMasterCode: Cell | null;
41
42
  newUserCode: Cell | null;
42
43
  };
@@ -58,18 +59,22 @@ export type AssetConfig = {
58
59
  maxTotalSupply: bigint;
59
60
  reserveFactor: bigint;
60
61
  liquidationReserveFactor: bigint;
61
- /* Will be in v6
62
62
  minPrincipalForRewards: bigint;
63
63
  baseTrackingSupplySpeed: bigint;
64
- baseTrackingBorrowSpeed: bigint; */
64
+ baseTrackingBorrowSpeed: bigint;
65
65
  };
66
66
 
67
67
  export type MasterConfig = {
68
68
  ifActive: number;
69
69
  admin: Address;
70
- adminPK: bigint;
70
+ oraclesInfo: OraclesInfo
71
71
  tokenKeys: Cell | null;
72
- walletToMaster: Cell | null;
72
+ };
73
+
74
+ export type OraclesInfo = {
75
+ numOracles: number;
76
+ threshold: number;
77
+ oracles: Cell | null;
73
78
  };
74
79
 
75
80
  export type AssetData = {
@@ -79,10 +84,9 @@ export type AssetData = {
79
84
  totalBorrow: bigint;
80
85
  lastAccural: bigint;
81
86
  balance: bigint;
82
- /* Will be in v6
83
87
  trackingSupplyIndex: bigint;
84
88
  trackingBorrowIndex: bigint;
85
- lastTrackingAccural: bigint; */
89
+ awaitedSupply?: bigint;
86
90
  };
87
91
 
88
92
  export type AssetInterest = {
@@ -115,4 +119,14 @@ export type MasterData = {
115
119
  export type AgregatedBalances = {
116
120
  totalBorrow: bigint;
117
121
  totalSupply: bigint;
118
- }
122
+ }
123
+
124
+ export type OracleNFT = {
125
+ id: number,
126
+ address: string
127
+ }
128
+
129
+ export type Oracle = {
130
+ id: number,
131
+ pubkey: Buffer
132
+ }
package/src/types/User.ts CHANGED
@@ -44,10 +44,9 @@ export type UserLiteData = {
44
44
  trackingBorrowIndex: bigint;
45
45
  dutchAuctionStart: number;
46
46
  backupCell: Cell;
47
- /* Will be in v6
48
47
  rewards: Dictionary<bigint, UserRewards>;
49
48
  backupCell1: Cell | null;
50
- backupCell2: Cell | null; */
49
+ backupCell2: Cell | null;
51
50
  };
52
51
 
53
52
  export type UserDataActive = UserLiteData & {
@@ -85,7 +84,7 @@ export enum BalanceChangeType {
85
84
  export type PredictHealthFactorArgs = {
86
85
  balanceChangeType: BalanceChangeType;
87
86
  amount: bigint; // always positive
88
- tokenSymbol: string;
87
+ asset: PoolAssetConfig;
89
88
  principals: Dictionary<bigint, bigint>;
90
89
  prices: Dictionary<bigint, bigint>;
91
90
  assetsData: ExtendedAssetsData;
@@ -0,0 +1,141 @@
1
+ import { Builder, Cell, Dictionary, DictionaryKey, DictionaryKeyTypes, Slice, beginCell } from "@ton/core";
2
+
3
+ function readUnaryLength(slice: Slice) {
4
+ let res = 0;
5
+ while (slice.loadBit()) {
6
+ res++;
7
+ }
8
+ return res;
9
+ }
10
+
11
+ function endExoticCell(b: Builder): Cell {
12
+ let c = b.endCell();
13
+ return new Cell({exotic: true, bits: c.bits, refs: c.refs});
14
+ }
15
+
16
+ export function convertToMerkleProof(c: Cell): Cell {
17
+ return endExoticCell(beginCell()
18
+ .storeUint(3, 8)
19
+ .storeBuffer(c.hash(0))
20
+ .storeUint(c.depth(0), 16)
21
+ .storeRef(c));
22
+ }
23
+
24
+ function convertToPrunedBranch(c: Cell): Cell {
25
+ return endExoticCell(beginCell()
26
+ .storeUint(1, 8)
27
+ .storeUint(1, 8)
28
+ .storeBuffer(c.hash(0))
29
+ .storeUint(c.depth(0), 16));
30
+ }
31
+
32
+ function doGenerateMerkleProof(
33
+ prefix: string,
34
+ slice: Slice,
35
+ n: number,
36
+ keys: string[]
37
+ ): Cell {
38
+ // Reading label
39
+ const originalCell = slice.asCell();
40
+
41
+ if (keys.length == 0) {
42
+ // no keys to prove, prune the whole subdict
43
+ return convertToPrunedBranch(originalCell);
44
+ }
45
+
46
+ let lb0 = slice.loadBit() ? 1 : 0;
47
+ let prefixLength = 0;
48
+ let pp = prefix;
49
+
50
+ if (lb0 === 0) {
51
+ // Short label detected
52
+
53
+ // Read
54
+ prefixLength = readUnaryLength(slice);
55
+
56
+ // Read prefix
57
+ for (let i = 0; i < prefixLength; i++) {
58
+ pp += slice.loadBit() ? '1' : '0';
59
+ }
60
+ } else {
61
+ let lb1 = slice.loadBit() ? 1 : 0;
62
+ if (lb1 === 0) {
63
+ // Long label detected
64
+ prefixLength = slice.loadUint(Math.ceil(Math.log2(n + 1)));
65
+ for (let i = 0; i < prefixLength; i++) {
66
+ pp += slice.loadBit() ? '1' : '0';
67
+ }
68
+ } else {
69
+ // Same label detected
70
+ let bit = slice.loadBit() ? '1' : '0';
71
+ prefixLength = slice.loadUint(Math.ceil(Math.log2(n + 1)));
72
+ for (let i = 0; i < prefixLength; i++) {
73
+ pp += bit;
74
+ }
75
+ }
76
+ }
77
+
78
+ if (n - prefixLength === 0) {
79
+ return originalCell;
80
+ } else {
81
+ let sl = originalCell.beginParse();
82
+ let left = sl.loadRef();
83
+ let right = sl.loadRef();
84
+ // NOTE: Left and right branches are implicitly contain prefixes '0' and '1'
85
+ if (!left.isExotic) {
86
+ const leftKeys = keys.filter((key) => {
87
+ return pp + '0' === key.slice(0, pp.length + 1);
88
+ });
89
+ left = doGenerateMerkleProof(
90
+ pp + '0',
91
+ left.beginParse(),
92
+ n - prefixLength - 1,
93
+ leftKeys
94
+ );
95
+ }
96
+ if (!right.isExotic) {
97
+ const rightKeys = keys.filter((key) => {
98
+ return pp + '1' === key.slice(0, pp.length + 1);
99
+ });
100
+ right = doGenerateMerkleProof(
101
+ pp + '1',
102
+ right.beginParse(),
103
+ n - prefixLength - 1,
104
+ rightKeys
105
+ );
106
+ }
107
+
108
+ return beginCell()
109
+ .storeSlice(sl)
110
+ .storeRef(left)
111
+ .storeRef(right)
112
+ .endCell();
113
+ }
114
+ }
115
+
116
+ export function generateMerkleProofDirect<K extends DictionaryKeyTypes, V>(
117
+ dict: Dictionary<K, V>,
118
+ keys: K[],
119
+ keyObject: DictionaryKey<K>
120
+ ): Cell {
121
+ keys.forEach((key) => {
122
+ if (!dict.has(key)) {
123
+ throw new Error(`Trying to generate merkle proof for a missing key "${key}"`)
124
+ }
125
+ })
126
+ const s = beginCell().storeDictDirect(dict).asSlice();
127
+ return doGenerateMerkleProof(
128
+ '',
129
+ s,
130
+ keyObject.bits,
131
+ keys.map((key) => keyObject.serialize(key).toString(2).padStart(keyObject.bits, '0'))
132
+ );
133
+ }
134
+
135
+ export function generateMerkleProof<K extends DictionaryKeyTypes, V>(
136
+ dict: Dictionary<K, V>,
137
+ keys: K[],
138
+ keyObject: DictionaryKey<K>
139
+ ): Cell {
140
+ return convertToMerkleProof(generateMerkleProofDirect(dict, keys, keyObject));
141
+ }