@evaafi/sdk 0.5.6 → 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.
Files changed (45) hide show
  1. package/dist/api/helpers.js +3 -2
  2. package/dist/api/math.d.ts +1 -10
  3. package/dist/api/math.js +32 -76
  4. package/dist/api/parser.d.ts +2 -1
  5. package/dist/api/parser.js +46 -57
  6. package/dist/api/prices.d.ts +2 -1
  7. package/dist/api/prices.js +29 -19
  8. package/dist/config.d.ts +1 -2
  9. package/dist/config.js +2 -3
  10. package/dist/constants/general.d.ts +7 -5
  11. package/dist/constants/general.js +29 -10
  12. package/dist/constants/pools.js +6 -3
  13. package/dist/constants.d.ts +35 -6
  14. package/dist/constants.js +47 -92
  15. package/dist/contracts/MasterContract.d.ts +9 -3
  16. package/dist/contracts/MasterContract.js +13 -8
  17. package/dist/contracts/UserContract.d.ts +2 -2
  18. package/dist/contracts/UserContract.js +5 -5
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +3 -1
  21. package/dist/types/Common.d.ts +9 -0
  22. package/dist/types/Master.d.ts +23 -4
  23. package/dist/types/User.d.ts +4 -1
  24. package/dist/utils/merkleProof.js +4 -3
  25. package/dist/utils/priceUtils.d.ts +2 -2
  26. package/dist/utils/priceUtils.js +16 -16
  27. package/dist/utils/sha256BigInt.js +2 -1
  28. package/dist/utils/tonConnectSender.js +3 -2
  29. package/dist/utils/userJettonWallet.js +2 -1
  30. package/dist/utils/utils.js +2 -1
  31. package/package.json +2 -2
  32. package/src/api/math.ts +22 -84
  33. package/src/api/parser.ts +37 -52
  34. package/src/api/prices.ts +33 -57
  35. package/src/config.ts +1 -0
  36. package/src/constants/general.ts +32 -9
  37. package/src/constants/pools.ts +7 -4
  38. package/src/contracts/MasterContract.ts +23 -17
  39. package/src/contracts/UserContract.ts +7 -3
  40. package/src/index.ts +4 -0
  41. package/src/types/Common.ts +10 -0
  42. package/src/types/Master.ts +23 -9
  43. package/src/types/User.ts +2 -3
  44. package/src/utils/merkleProof.ts +141 -0
  45. package/src/utils/priceUtils.ts +177 -0
@@ -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
+ }
@@ -0,0 +1,177 @@
1
+ import { beginCell, Cell, Dictionary, Slice } from "@ton/core";
2
+ import { PriceData, RawPriceData } from "../types/Common";
3
+ import { TTL_ORACLE_DATA_SEC } from "../config";
4
+ import { Oracle, PoolAssetsConfig } from "../types/Master";
5
+ import { convertToMerkleProof, generateMerkleProofDirect } from "./merkleProof";
6
+
7
+ type NftData = {
8
+ ledgerIndex: number;
9
+ pageSize: number;
10
+ items: string[];
11
+ };
12
+
13
+ type OutputData = {
14
+ metadata: {
15
+ blockId: string;
16
+ transactionId: string;
17
+ outputIndex: number;
18
+ isSpent: boolean;
19
+ milestoneIndexSpent: number;
20
+ milestoneTimestampSpent: number;
21
+ transactionIdSpent: string;
22
+ milestoneIndexBooked: number;
23
+ milestoneTimestampBooked: number;
24
+ ledgerIndex: number;
25
+ };
26
+ output: {
27
+ type: number;
28
+ amount: string;
29
+ nftId: string;
30
+ unlockConditions: {
31
+ type: number;
32
+ address: {
33
+ type: number;
34
+ pubKeyHash: string;
35
+ };
36
+ }[];
37
+ features: {
38
+ type: number;
39
+ data: string;
40
+ }[];
41
+ };
42
+ };
43
+
44
+ export type OraclePricesData = {
45
+ timestamp: number,
46
+ prices: Dictionary<bigint, bigint>
47
+ }
48
+
49
+ export async function loadPrices(oracleNftId: String, endpoints: String[]): Promise<OutputData> {
50
+ return await Promise.any(endpoints.map(x => loadOracleData(oracleNftId, x)));
51
+ }
52
+
53
+
54
+ async function loadOracleData(oracleNftId: String, endpoint: String): Promise<OutputData> {
55
+ let result = await fetch(`https://${endpoint}/api/indexer/v1/outputs/nft/${oracleNftId}`, {
56
+ headers: { accept: 'application/json' },
57
+ signal: AbortSignal.timeout(5000)
58
+ });
59
+ let outputId = (await result.json()) as NftData;
60
+
61
+ result = await fetch(`https://${endpoint}/api/core/v2/outputs/${outputId.items[0]}`, {
62
+ headers: { accept: 'application/json' },
63
+ signal: AbortSignal.timeout(5000)
64
+ });
65
+ return (await result.json() as OutputData);
66
+ }
67
+
68
+ export async function parsePrices(outputData: OutputData, oracleId: number): Promise<RawPriceData>{
69
+ const data = JSON.parse(
70
+ decodeURIComponent(outputData.output.features[0].data.replace('0x', '').replace(/[0-9a-f]{2}/g, '%$&')),
71
+ );
72
+
73
+ try {
74
+ const pricesCell = Cell.fromBoc(Buffer.from(data['packedPrices'], 'hex'))[0];
75
+ const signature = Buffer.from(data['signature'], 'hex');
76
+ const publicKey = Buffer.from(data['publicKey'], 'hex');
77
+ const timestamp = Number(data['timestamp']);
78
+
79
+ return {
80
+ dict: pricesCell.beginParse().loadRef().beginParse().loadDictDirect(Dictionary.Keys.BigUint(256), Dictionary.Values.BigVarUint(4)),
81
+ dataCell: beginCell().storeRef(pricesCell).storeBuffer(signature).endCell(),
82
+ oracleId: oracleId,
83
+ signature: signature,
84
+ pubkey: publicKey,
85
+ timestamp: timestamp,
86
+ };
87
+ }
88
+ catch (error) {
89
+ console.log(oracleId, data, error);
90
+ throw Error();
91
+ }
92
+ }
93
+
94
+ export function verifyPrices(assets: PoolAssetsConfig) {
95
+ return function(priceData: RawPriceData): boolean {
96
+ const timestamp = Date.now() / 1000;
97
+ const pricesTime = priceData.timestamp;
98
+
99
+ for (const asset of assets) {
100
+ if(!priceData.dict.has(asset.assetId)) {
101
+ return false;
102
+ }
103
+ }
104
+ // console.log('timestamp', timestamp, 'pricestime', pricesTime, timestamp - pricesTime);
105
+ return timestamp - pricesTime < TTL_ORACLE_DATA_SEC;
106
+ }
107
+ }
108
+
109
+ export function getMedianPrice(pricesData: PriceData[], asset: bigint): bigint {
110
+ const sorted = pricesData.map(x => x.dict.get(asset)!).sort((a, b) => Number(a) - Number(b));
111
+ const mid = Math.floor(sorted.length / 2);
112
+ if (sorted.length % 2 === 0) {
113
+ return (sorted[mid - 1] + sorted[mid]) / 2n;
114
+ } else {
115
+ return sorted[mid];
116
+ }
117
+ }
118
+
119
+ export function packAssetsData(assetsData: {assetId: bigint, medianPrice: bigint}[]): Cell {
120
+ if (assetsData.length == 0) {
121
+ throw new Error("No assets data to pack");
122
+ }
123
+ return assetsData.reduceRight(
124
+ (acc: Cell | null, {assetId, medianPrice}) => beginCell()
125
+ .storeUint(assetId, 256)
126
+ .storeCoins(medianPrice)
127
+ .storeMaybeRef(acc)
128
+ .endCell(),
129
+ null
130
+ )!;
131
+ }
132
+
133
+ export function packPrices(assetsDataCell: Cell, oraclesDataCell: Cell): Cell {
134
+ let pricesCell = beginCell()
135
+ .storeRef(assetsDataCell)
136
+ .storeRef(oraclesDataCell)
137
+ .endCell();
138
+ return pricesCell;
139
+ }
140
+
141
+ export function createOracleDataProof(oracle: Oracle,
142
+ data: OraclePricesData,
143
+ signature: Buffer,
144
+ assets: Array<bigint>): Slice {
145
+ let prunedDict = generateMerkleProofDirect(data.prices, assets, Dictionary.Keys.BigUint(256));
146
+ let prunedData = beginCell().storeUint(data.timestamp, 32).storeMaybeRef(prunedDict).endCell();
147
+ let merkleProof = convertToMerkleProof(prunedData);
148
+ let oracleDataProof = beginCell().storeUint(oracle.id, 32).storeRef(merkleProof).storeBuffer(signature).asSlice();
149
+ return oracleDataProof;
150
+ }
151
+
152
+ export function packOraclesData(oraclesData: {oracle: Oracle, data: OraclePricesData, signature: Buffer}[],
153
+ assets: Array<bigint>): Cell {
154
+ if (oraclesData.length == 0) {
155
+ throw new Error("no oracles data to pack");
156
+ }
157
+ let proofs = oraclesData.sort((d1, d2) => d1.oracle.id - d2.oracle.id).map(
158
+ ({oracle, data, signature}) => createOracleDataProof(oracle, data, signature, assets)
159
+ );
160
+ return proofs.reduceRight((acc: Cell | null, val) => beginCell().storeSlice(val).storeMaybeRef(acc).endCell(), null)!;
161
+ }
162
+
163
+
164
+ // : String = "api.stardust-mainnet.iotaledger.net"
165
+ export function sumDicts(result: Dictionary<bigint, bigint>, addendum: Dictionary<bigint, bigint>) {
166
+ for (const key of addendum.keys()) {
167
+ const current = result.get(key)!;
168
+ const value = addendum.get(key)!;
169
+
170
+ if (current === undefined) {
171
+ result.set(key, value);
172
+ continue;
173
+ }
174
+
175
+ result.set(key, current + value);
176
+ }
177
+ }