@evaafi/sdk 0.6.1 → 0.6.2-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 (71) hide show
  1. package/LICENSE.md +7 -0
  2. package/dist/api/liquidation.js +1 -3
  3. package/dist/api/math.js +0 -2
  4. package/dist/api/parser.js +11 -11
  5. package/dist/api/prices.d.ts +5 -2
  6. package/dist/api/prices.js +35 -13
  7. package/dist/constants/assets.d.ts +8 -0
  8. package/dist/constants/assets.js +31 -1
  9. package/dist/constants/general.d.ts +5 -2
  10. package/dist/constants/general.js +12 -22
  11. package/dist/constants/pools.d.ts +1 -0
  12. package/dist/constants/pools.js +19 -3
  13. package/dist/contracts/MasterContract.d.ts +5 -0
  14. package/dist/contracts/MasterContract.js +6 -0
  15. package/dist/index.d.ts +3 -3
  16. package/dist/index.js +7 -1
  17. package/dist/prices/Prices.d.ts +9 -0
  18. package/dist/prices/Prices.js +43 -0
  19. package/dist/prices/PricesCollector.d.ts +12 -0
  20. package/dist/prices/PricesCollector.js +123 -0
  21. package/dist/prices/Types.d.ts +33 -0
  22. package/dist/prices/Types.js +11 -0
  23. package/dist/prices/constants.d.ts +1 -0
  24. package/dist/prices/constants.js +4 -0
  25. package/dist/prices/index.d.ts +6 -0
  26. package/dist/prices/index.js +22 -0
  27. package/dist/prices/sources/Backend.d.ts +13 -0
  28. package/dist/prices/sources/Backend.js +52 -0
  29. package/dist/prices/sources/Icp.d.ts +10 -0
  30. package/dist/prices/sources/Icp.js +23 -0
  31. package/dist/prices/sources/Iota.d.ts +39 -0
  32. package/dist/prices/sources/Iota.js +49 -0
  33. package/dist/prices/sources/PriceSource.d.ts +14 -0
  34. package/dist/prices/sources/PriceSource.js +26 -0
  35. package/dist/prices/sources/index.d.ts +4 -0
  36. package/dist/prices/sources/index.js +20 -0
  37. package/dist/prices/utils.d.ts +23 -0
  38. package/dist/prices/utils.js +148 -0
  39. package/dist/types/Master.d.ts +2 -1
  40. package/dist/types/User.d.ts +1 -0
  41. package/dist/utils/userJettonWallet.js +42 -43
  42. package/dist/utils/utils.d.ts +1 -0
  43. package/dist/utils/utils.js +5 -1
  44. package/package.json +4 -2
  45. package/src/api/liquidation.ts +0 -1
  46. package/src/api/math.ts +1 -2
  47. package/src/api/parser.ts +10 -13
  48. package/src/api/prices.ts +20 -7
  49. package/src/constants/assets.ts +57 -0
  50. package/src/constants/general.ts +11 -23
  51. package/src/constants/pools.ts +21 -5
  52. package/src/contracts/MasterContract.ts +8 -1
  53. package/src/index.ts +7 -2
  54. package/src/prices/Prices.ts +32 -0
  55. package/src/prices/PricesCollector.ts +139 -0
  56. package/src/prices/Types.ts +44 -0
  57. package/src/prices/constants.ts +1 -0
  58. package/src/prices/index.ts +6 -0
  59. package/src/prices/sources/Backend.ts +62 -0
  60. package/src/prices/sources/Icp.ts +27 -0
  61. package/src/prices/sources/Iota.ts +90 -0
  62. package/src/prices/sources/PriceSource.ts +35 -0
  63. package/src/prices/sources/index.ts +4 -0
  64. package/src/prices/utils.ts +170 -0
  65. package/src/types/Master.ts +3 -2
  66. package/src/types/User.ts +2 -2
  67. package/src/utils/userJettonWallet.ts +43 -53
  68. package/src/utils/utils.ts +5 -1
  69. package/src/config.ts +0 -1
  70. package/src/types/Common.ts +0 -16
  71. package/src/utils/priceUtils.ts +0 -177
@@ -2,66 +2,56 @@ import { Address, beginCell, Cell, storeStateInit } from '@ton/core';
2
2
  import { PoolAssetConfig } from '../types/Master';
3
3
  import { UNDEFINED_ASSET } from '../constants/assets';
4
4
 
5
+ function getUserJettonData(ownerAddress: Address, assetName: string, jettonWalletCode: Cell, jettonMasterAddress: Address) {
6
+ switch (assetName) {
7
+ case 'uTON':
8
+ return beginCell()
9
+ .storeCoins(0)
10
+ .storeUint(0, 64)
11
+ .storeAddress(ownerAddress)
12
+ .storeAddress(jettonMasterAddress)
13
+ .storeRef(jettonWalletCode)
14
+ .endCell();
15
+ case 'DOGS':
16
+ case 'NOT':
17
+ case 'USDT':
18
+ return beginCell()
19
+ .storeUint(0, 4)
20
+ .storeCoins(0)
21
+ .storeAddress(ownerAddress)
22
+ .storeAddress(jettonMasterAddress)
23
+ .endCell();
24
+ case 'tsTON':
25
+ return beginCell()
26
+ .storeCoins(0)
27
+ .storeAddress(ownerAddress)
28
+ .storeAddress(jettonMasterAddress)
29
+ .storeRef(jettonWalletCode)
30
+ .storeCoins(0)
31
+ .storeUint(0, 48)
32
+ .endCell();
33
+ default:
34
+ return beginCell().storeCoins(0)
35
+ .storeAddress(ownerAddress)
36
+ .storeAddress(jettonMasterAddress)
37
+ .storeRef(jettonWalletCode)
38
+ .endCell();
39
+
40
+ }
41
+ }
5
42
  export function getUserJettonWallet(ownerAddress: Address, poolAssetConfig: PoolAssetConfig) {
6
- if (poolAssetConfig.name == 'TON' || poolAssetConfig.assetId === UNDEFINED_ASSET.assetId) {
43
+ const assetName = poolAssetConfig.name;
44
+ if (assetName == 'TON' || poolAssetConfig.assetId === UNDEFINED_ASSET.assetId) {
7
45
  throw new Error(`Cant getUserJettonWallet for ${poolAssetConfig.name} asset`)
8
46
  }
9
- const jettonMasterAddress = poolAssetConfig.jettonMasterAddress;
10
- const jettonWalletCode = poolAssetConfig.jettonWalletCode;
11
-
12
- if (poolAssetConfig.name === 'USDT') {
13
- const lib_prep = beginCell().storeUint(2, 8).storeBuffer(jettonWalletCode.hash()).endCell();
14
- const jwallet_code = new Cell({ exotic: true, bits: lib_prep.bits, refs: lib_prep.refs });
15
-
16
- const jettonData = beginCell()
17
- .storeUint(0, 4)
18
- .storeCoins(0)
19
- .storeAddress(ownerAddress)
20
- .storeAddress(jettonMasterAddress)
21
- .endCell();
22
-
23
- const stateInit = beginCell()
24
- .store(
25
- storeStateInit({
26
- code: jwallet_code,
27
- data: jettonData
28
- })
29
- )
30
- .endCell();
31
- return new Address(0, stateInit.hash());
32
- }
47
+ let jettonWalletCode = poolAssetConfig.jettonWalletCode;
33
48
 
34
- if (poolAssetConfig.name === 'tsTON') {
49
+ if (assetName === 'USDT' || assetName === 'tsTON') {
35
50
  const lib_prep = beginCell().storeUint(2, 8).storeBuffer(jettonWalletCode.hash()).endCell();
36
- const jwallet_code = new Cell({ exotic: true, bits: lib_prep.bits, refs: lib_prep.refs });
37
-
38
- const jettonData = beginCell()
39
- .storeCoins(0)
40
- .storeAddress(ownerAddress)
41
- .storeAddress(jettonMasterAddress)
42
- .storeRef(jwallet_code)
43
- .storeCoins(0)
44
- .storeUint(0, 48)
45
- .endCell();
46
-
47
- const stateInit = beginCell()
48
- .store(
49
- storeStateInit({
50
- code: jwallet_code,
51
- data: jettonData
52
- })
53
- )
54
- .endCell();
55
-
56
- return new Address(0, stateInit.hash());
51
+ jettonWalletCode = new Cell({ exotic: true, bits: lib_prep.bits, refs: lib_prep.refs });
57
52
  }
58
53
 
59
- const jettonData = beginCell()
60
- .storeCoins(0)
61
- .storeAddress(ownerAddress)
62
- .storeAddress(jettonMasterAddress)
63
- .storeRef(jettonWalletCode)
64
- .endCell();
54
+ const jettonData = getUserJettonData(ownerAddress, assetName, jettonWalletCode, poolAssetConfig.jettonMasterAddress);
65
55
 
66
56
  const stateInit = beginCell()
67
57
  .store(
@@ -7,4 +7,8 @@ export function isTonAsset(asset: PoolAssetConfig) {
7
7
 
8
8
  export function isTonAssetId(assetId: bigint) {
9
9
  return assetId === ASSET_ID.TON;
10
- }
10
+ }
11
+
12
+ export function delay(ms: number) {
13
+ return new Promise(resolve => setTimeout(resolve, ms));
14
+ }
package/src/config.ts DELETED
@@ -1 +0,0 @@
1
- export const TTL_ORACLE_DATA_SEC = 120; // todo back to 120
@@ -1,16 +0,0 @@
1
- import { Cell, Dictionary } from '@ton/core';
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
-
13
- export type PriceData = {
14
- dict: Dictionary<bigint, bigint>;
15
- dataCell: Cell;
16
- };
@@ -1,177 +0,0 @@
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
- }