@evaafi/sdk 0.5.6 → 0.6.0

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 (42) 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 +26 -74
  4. package/dist/api/parser.d.ts +2 -1
  5. package/dist/api/parser.js +42 -56
  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 +8 -3
  16. package/dist/contracts/MasterContract.js +13 -8
  17. package/dist/index.d.ts +3 -3
  18. package/dist/index.js +3 -1
  19. package/dist/types/Common.d.ts +9 -0
  20. package/dist/types/Master.d.ts +23 -4
  21. package/dist/types/User.d.ts +4 -1
  22. package/dist/utils/merkleProof.js +4 -3
  23. package/dist/utils/priceUtils.d.ts +2 -2
  24. package/dist/utils/priceUtils.js +16 -16
  25. package/dist/utils/sha256BigInt.js +2 -1
  26. package/dist/utils/tonConnectSender.js +3 -2
  27. package/dist/utils/userJettonWallet.js +2 -1
  28. package/dist/utils/utils.js +2 -1
  29. package/package.json +2 -2
  30. package/src/api/math.ts +16 -80
  31. package/src/api/parser.ts +33 -51
  32. package/src/api/prices.ts +33 -57
  33. package/src/config.ts +1 -0
  34. package/src/constants/general.ts +32 -9
  35. package/src/constants/pools.ts +7 -4
  36. package/src/contracts/MasterContract.ts +22 -17
  37. package/src/index.ts +4 -0
  38. package/src/types/Common.ts +10 -0
  39. package/src/types/Master.ts +23 -9
  40. package/src/types/User.ts +2 -3
  41. package/src/utils/merkleProof.ts +141 -0
  42. package/src/utils/priceUtils.ts +177 -0
@@ -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
+ }