@typus/typus-sdk 1.2.84 → 1.2.85-tails-exp

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.
@@ -1,822 +0,0 @@
1
- "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
48
- };
49
- var __read = (this && this.__read) || function (o, n) {
50
- var m = typeof Symbol === "function" && o[Symbol.iterator];
51
- if (!m) return o;
52
- var i = m.call(o), r, ar = [], e;
53
- try {
54
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
55
- }
56
- catch (error) { e = { error: error }; }
57
- finally {
58
- try {
59
- if (r && !r.done && (m = i["return"])) m.call(i);
60
- }
61
- finally { if (e) throw e.error; }
62
- }
63
- return ar;
64
- };
65
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
66
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
67
- if (ar || !(i in from)) {
68
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
69
- ar[i] = from[i];
70
- }
71
- }
72
- return to.concat(ar || Array.prototype.slice.call(from));
73
- };
74
- var __values = (this && this.__values) || function(o) {
75
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
76
- if (m) return m.call(o);
77
- if (o && typeof o.length === "number") return {
78
- next: function () {
79
- if (o && i >= o.length) o = void 0;
80
- return { value: o && o[i++], done: !o };
81
- }
82
- };
83
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
84
- };
85
- var __importDefault = (this && this.__importDefault) || function (mod) {
86
- return (mod && mod.__esModule) ? mod : { "default": mod };
87
- };
88
- Object.defineProperty(exports, "__esModule", { value: true });
89
- exports.fetchUserBids = exports.getUserBidReceipts = exports.parseBid = exports.parseBidReceipt = exports.parseStrikes = exports.calcEstPnl = exports.calcBreakEvenPrice = exports.calcDeliveryPrice = exports.calcIncentiveRate = exports.fetchPrices = exports.parsePythOracleData = exports.IncentiveRateBp = exports.periodOrder = exports.optionTypeOrder = exports.tokenOrder = exports.ASSET_INFO = void 0;
90
- var bignumber_js_1 = __importDefault(require("bignumber.js"));
91
- var web3_js_1 = require("@solana/web3.js");
92
- var client_1 = require("@pythnetwork/client");
93
- var lodash_1 = require("lodash");
94
- var moment_1 = __importDefault(require("moment"));
95
- var view_function_1 = require("../view-function");
96
- var vault_1 = require("./vault");
97
- var token_1 = require("./token");
98
- var tools_1 = require("../../tools");
99
- var config_json_1 = __importDefault(require("../../../config.json"));
100
- var view_function_2 = require("../../auto-bid/view-function");
101
- var token_2 = require("../../token");
102
- var token_3 = require("./token");
103
- var price_1 = require("../../price");
104
- var PriceDecimal = (0, bignumber_js_1.default)(10).pow(8);
105
- exports.ASSET_INFO = {
106
- BTC: {
107
- product: new web3_js_1.PublicKey("4aDoSXJ5o3AuvL7QFeR6h44jALQfTmUUCTVGDD6aoJTM"),
108
- price: new web3_js_1.PublicKey("GVXRSBjFk6e6J3NbVPXohDJetcTjaeeuykUpbQF8UoMU"),
109
- },
110
- ETH: {
111
- product: new web3_js_1.PublicKey("EMkxjGC1CQ7JLiutDbfYb7UKb3zm9SJcUmr1YicBsdpZ"),
112
- price: new web3_js_1.PublicKey("JBu1AL4obBcCMqKBBxhpWCNUt136ijcuMZLFvTP7iWdB"),
113
- },
114
- SUI: {
115
- product: new web3_js_1.PublicKey("2F8rfBf4z4SzNpeQstFTpLXTQQ7RNKsLFqPdbpybooCc"),
116
- price: new web3_js_1.PublicKey("3Qub3HaAJaa2xNY7SUqPKd3vVwTqDfDDkEUMPjXD2c1q"),
117
- },
118
- CETUS: {
119
- product: new web3_js_1.PublicKey("JDHPsM1zxsZ6TfDwpCVzo41DAZdRi6ZmhkzWU1iXvSQ"),
120
- price: new web3_js_1.PublicKey("GTeC2JfBFrHuYkBivDQcNdLY74X5FRDLEJntnxPKRQbY"),
121
- },
122
- SEI: {
123
- product: new web3_js_1.PublicKey("24bB1mRGsrrDVawJTCVYXrxbEz6ozztukPUKvcZCDcPz"),
124
- price: new web3_js_1.PublicKey("6cUuAyAX3eXoiWkjFF77RQBEUF15AAMQ7d1hm4EPd3tv"),
125
- },
126
- USDC: {
127
- product: new web3_js_1.PublicKey("8GWTTbNiXdmyZREXbjsZBmCRuzdPrW55dnZGDkTRjWvb"),
128
- price: new web3_js_1.PublicKey("Gnt27xtC473ZT2Mw5u8wZ68Z3gULkSTb5DuxJy7eJotD"),
129
- },
130
- USDT: {
131
- product: new web3_js_1.PublicKey("Av6XyAMJnyi68FdsKSPYgzfXGjYrrt6jcAMwtvzLCqaM"),
132
- price: new web3_js_1.PublicKey("3vxLXJqLqF3JG5TCbYycbKWRBbCJQLxQmBGCkyqEEefL"),
133
- },
134
- TURBOS: {
135
- product: new web3_js_1.PublicKey("8DZUgXNQo5Um1pqo4gzv9oWPUZpyKV9nXm51gysZFMef"),
136
- price: new web3_js_1.PublicKey("HoxttzPFzcPvpZhUY8LCLkFNn9keDnBrctno4wXEhpFk"),
137
- },
138
- APT: {
139
- product: new web3_js_1.PublicKey("6bQMDtuAmRgjvymdWk9w4tTc9YyuXcjMxF8MyPHXejsx"),
140
- price: new web3_js_1.PublicKey("FNNvb1AFDnDVPkocEri8mWbJ1952HQZtFLuwPiUjSJQ"),
141
- },
142
- SOL: {
143
- product: new web3_js_1.PublicKey("ALP8SdU9oARYVLgLR7LrqMNCYBnhtnQz1cj6bwgwQmgj"),
144
- price: new web3_js_1.PublicKey("H6ARHf6YXhGYeQfUzQNGk6rDNnLBQKrenN712K4AQJEG"),
145
- },
146
- INJ: {
147
- product: new web3_js_1.PublicKey("5Q5kyCVzssrGMd2BniSdVeRwjNWrGGrFhMrgGt4zURyA"),
148
- price: new web3_js_1.PublicKey("9EdtbaivHQYA4Nh3XzGR6DwRaoorqXYnmpfsnFhvwuVj"),
149
- },
150
- JUP: {
151
- product: new web3_js_1.PublicKey("AykbyeHZbUbEtEAPVpBLoPAMHBrUrDMtXJkPWZw4TRDX"),
152
- price: new web3_js_1.PublicKey("g6eRCbboSwK4tSWngn773RCMexr1APQr4uA9bGZBYfo"),
153
- },
154
- };
155
- exports.tokenOrder = {
156
- // Basically it's a to z but put SUI at first
157
- SUI: 0,
158
- AFSUI: 1,
159
- APT: 2,
160
- WBTC: 3,
161
- BTC: 3,
162
- BUCK: 4,
163
- CETUS: 5,
164
- WETH: 6,
165
- ETH: 6,
166
- FUD: 7,
167
- INJ: 8,
168
- JUP: 9,
169
- NAVX: 10,
170
- SCA: 11,
171
- SEI: 12,
172
- WSOL: 13,
173
- SOL: 14,
174
- TURBOS: 15,
175
- USDC: 16,
176
- USDT: 17,
177
- USDY: 18,
178
- };
179
- exports.optionTypeOrder = {
180
- 0: 0,
181
- 1: 2,
182
- 2: 3,
183
- 4: 4,
184
- 6: 5,
185
- 5: 6,
186
- };
187
- exports.periodOrder = {
188
- 0: 1,
189
- 1: 2,
190
- 2: 3,
191
- 3: 0,
192
- };
193
- exports.IncentiveRateBp = 4;
194
- var DefaultOracleDecimal = {
195
- ETH: "8",
196
- SUI: "8",
197
- AFSUI: "8",
198
- BTC: "8",
199
- DOGE: "8",
200
- APT: "8",
201
- SOL: "8",
202
- USDC: "8",
203
- USDT: "8",
204
- CETUS: "8",
205
- TURBOS: "8",
206
- NAVX: "8",
207
- JUP: "8",
208
- BUCK: "8",
209
- USDY: "8",
210
- SEI: "8",
211
- FUD: "8",
212
- MFUD: "8",
213
- INJ: "8",
214
- SCA: "8",
215
- };
216
- var parsePythOracleData = function (data, decimals) {
217
- var prices = {};
218
- Object.entries(exports.ASSET_INFO).forEach(function (p) {
219
- var _a, _b;
220
- var asset = p[0].toUpperCase();
221
- var coinData = data.find(function (s) {
222
- return s.productAccountKey.equals(p[1].product);
223
- });
224
- var decimal = decimals[asset];
225
- if (decimal && coinData) {
226
- prices[asset.toLowerCase()] = {
227
- price: (0, bignumber_js_1.default)((_a = coinData.price) !== null && _a !== void 0 ? _a : 0)
228
- .multipliedBy((0, bignumber_js_1.default)(10).pow(decimal))
229
- .toString(),
230
- decimal: decimal,
231
- quote: "usd",
232
- };
233
- if (token_3.WrappedToken[asset]) {
234
- prices[token_3.WrappedToken[asset].toLowerCase()] = {
235
- price: (0, bignumber_js_1.default)((_b = coinData.price) !== null && _b !== void 0 ? _b : 0)
236
- .multipliedBy((0, bignumber_js_1.default)(10).pow(decimal))
237
- .toString(),
238
- decimal: decimal,
239
- quote: "usd",
240
- };
241
- }
242
- }
243
- });
244
- return prices;
245
- };
246
- exports.parsePythOracleData = parsePythOracleData;
247
- var fetchPrices = function (provider, network) { return __awaiter(void 0, void 0, void 0, function () {
248
- var coinObjects, oracleDecimal, PYTHNET_CLUSTER_NAME, connection, pythPublicKey, pythClient, priceData, prices, suiusd, suifud, fudusd, suiafsui, afsuiusd, suinavx, navxusd, suibuck, buckusd, usdyusdc, usdyusdcWithDecimal, scasui, scausd;
249
- var _a, _b;
250
- return __generator(this, function (_c) {
251
- switch (_c.label) {
252
- case 0: return [4 /*yield*/, provider.multiGetObjects({
253
- ids: Object.values(config_json_1.default[network.toUpperCase()].ORACLE),
254
- options: { showContent: true },
255
- })];
256
- case 1:
257
- coinObjects = _c.sent();
258
- oracleDecimal = __assign({}, DefaultOracleDecimal);
259
- coinObjects.forEach(function (c) {
260
- var _a, _b;
261
- // @ts-ignore
262
- oracleDecimal[(_a = c.data) === null || _a === void 0 ? void 0 : _a.content.fields.base_token] =
263
- // @ts-ignore
264
- (_b = c.data) === null || _b === void 0 ? void 0 : _b.content.fields.decimal;
265
- });
266
- PYTHNET_CLUSTER_NAME = "pythnet";
267
- connection = new web3_js_1.Connection((0, client_1.getPythClusterApiUrl)(PYTHNET_CLUSTER_NAME));
268
- pythPublicKey = (0, client_1.getPythProgramKeyForCluster)(PYTHNET_CLUSTER_NAME);
269
- pythClient = new client_1.PythHttpClient(connection, pythPublicKey);
270
- return [4 /*yield*/, pythClient.getAssetPricesFromAccounts(Object.values(exports.ASSET_INFO).map(function (a) { return a.price; }))];
271
- case 2:
272
- priceData = _c.sent();
273
- prices = (0, exports.parsePythOracleData)(priceData, oracleDecimal);
274
- suiusd = (0, bignumber_js_1.default)((_b = (_a = prices["sui"]) === null || _a === void 0 ? void 0 : _a.price) !== null && _b !== void 0 ? _b : 0);
275
- return [4 /*yield*/, (0, price_1.getLatestPrice)("SUIFUD")];
276
- case 3:
277
- suifud = _c.sent();
278
- fudusd = suifud == "0" ? (0, bignumber_js_1.default)(0) : suiusd.div(suifud);
279
- return [4 /*yield*/, (0, price_1.getLatestPrice)("SUIAFSUI")];
280
- case 4:
281
- suiafsui = _c.sent();
282
- afsuiusd = suiafsui == "0" ? (0, bignumber_js_1.default)(0) : suiusd.div(suiafsui);
283
- return [4 /*yield*/, (0, price_1.getLatestPrice)("SUINAVX")];
284
- case 5:
285
- suinavx = _c.sent();
286
- navxusd = suiusd.div(suinavx);
287
- return [4 /*yield*/, (0, price_1.getLatestPrice)("SUIBUCK")];
288
- case 6:
289
- suibuck = _c.sent();
290
- buckusd = (0, bignumber_js_1.default)(suibuck).lte(0) ? "0" : suiusd.div(suibuck);
291
- return [4 /*yield*/, (0, price_1.getLatestPrice)("USDYUSDC")];
292
- case 7:
293
- usdyusdc = _c.sent();
294
- usdyusdcWithDecimal = (0, bignumber_js_1.default)(usdyusdc).multipliedBy((0, bignumber_js_1.default)(10).pow(8));
295
- return [4 /*yield*/, (0, price_1.getLatestPrice)("SCASUI")];
296
- case 8:
297
- scasui = _c.sent();
298
- scausd = suiusd.eq(0) ? (0, bignumber_js_1.default)(0) : (0, bignumber_js_1.default)(scasui).multipliedBy(suiusd);
299
- return [2 /*return*/, __assign({ fud: { price: fudusd.toString(), decimal: "8", quote: "usd" }, mfud: { price: fudusd.multipliedBy(1000000).toString(), decimal: "8", quote: "usd" }, afsui: { price: afsuiusd.toString(), decimal: "8", quote: "usd" }, navx: { price: navxusd.toString(), decimal: "8", quote: "usd" }, buck: { price: buckusd.toString(), decimal: "8", quote: "usd" }, usdy: { price: usdyusdcWithDecimal.toString(), decimal: "8", quote: "usd" }, sca: { price: scausd.toString(), decimal: "8", quote: "usd" } }, prices)];
300
- }
301
- });
302
- }); };
303
- exports.fetchPrices = fetchPrices;
304
- var calcIncentiveRate = function (incentiveBp) {
305
- var incentiveRateBp = (0, bignumber_js_1.default)(incentiveBp).div((0, bignumber_js_1.default)(10).pow(exports.IncentiveRateBp));
306
- var incentiveRate = 1;
307
- if (incentiveRateBp.gt(0)) {
308
- incentiveRate = 1 - Number(incentiveRateBp);
309
- }
310
- return incentiveRate;
311
- };
312
- exports.calcIncentiveRate = calcIncentiveRate;
313
- var calcDeliveryPrice = function (bidShare, vaultInfo) {
314
- var bTokenDecimal = vaultInfo.info.bTokenDecimal;
315
- var deliveryPrice = (0, bignumber_js_1.default)("0");
316
- // check if bid has settled already
317
- if (bidShare.bidVault.u64Padding[1]) {
318
- deliveryPrice = (0, bignumber_js_1.default)(bidShare.bidVault.u64Padding[1]);
319
- }
320
- else {
321
- var deliveryInfos = vaultInfo.info.deliveryInfos.deliveryInfo;
322
- var deliveryInfo = deliveryInfos[deliveryInfos.length - 1];
323
- deliveryPrice = deliveryInfo ? (0, bignumber_js_1.default)(deliveryInfo.deliveryPrice) : (0, bignumber_js_1.default)("0");
324
- }
325
- deliveryPrice = (0, bignumber_js_1.default)(deliveryPrice).div((0, bignumber_js_1.default)(10).pow((0, bignumber_js_1.default)(bTokenDecimal)));
326
- return deliveryPrice;
327
- };
328
- exports.calcDeliveryPrice = calcDeliveryPrice;
329
- var calcBreakEvenPrice = function (optionType, period, strikes, bToken, price, incentive) {
330
- var breakEvenPrice = 0;
331
- switch (optionType) {
332
- case "0":
333
- if (token_1.StableCoin.includes(bToken)) {
334
- breakEvenPrice = Number(strikes[0]) + Number(price) * 1.1 * incentive;
335
- }
336
- else {
337
- breakEvenPrice = Number(strikes[0]) / (1 - Number(price) * 1.1 * incentive);
338
- }
339
- break;
340
- case "1":
341
- if (token_1.StableCoin.includes(bToken)) {
342
- breakEvenPrice = Number(strikes[0]) - Number(price) * 1.1 * incentive;
343
- }
344
- else {
345
- breakEvenPrice = Number(strikes[0]) / (1 + Number(price) * 1.1 * incentive);
346
- }
347
- break;
348
- case "2":
349
- // Calculate with the lower one
350
- if (token_1.StableCoin.includes(bToken)) {
351
- breakEvenPrice = Number(strikes[0]) + Number(price) * 1.1 * incentive;
352
- }
353
- else {
354
- breakEvenPrice = Number(strikes[0]) / (1 - Number(price) * 1.1 * incentive);
355
- }
356
- break;
357
- case "4":
358
- // Calculate with the lower one
359
- if (token_1.StableCoin.includes(bToken)) {
360
- breakEvenPrice = Number(strikes[0]) + Number(price) * 1.1 * incentive;
361
- }
362
- else {
363
- breakEvenPrice = Number(strikes[0]) / (1 - Number(price) * 1.1 * incentive);
364
- }
365
- break;
366
- case "5":
367
- if (token_1.StableCoin.includes(bToken)) {
368
- breakEvenPrice = Number(strikes[1]) - Number(price) * 1.1 * incentive;
369
- }
370
- else {
371
- breakEvenPrice = Number(strikes[1]) / (1 + Number(price) * 1.1 * incentive);
372
- }
373
- break;
374
- case "6":
375
- // Calculate with the lower one
376
- if (token_1.StableCoin.includes(bToken)) {
377
- breakEvenPrice = Number(strikes[0]) + Number(price) * 1.1 * incentive;
378
- }
379
- else {
380
- breakEvenPrice = Number(strikes[0]) / (1 + Number(price) * 1.1 * incentive);
381
- }
382
- break;
383
- }
384
- return breakEvenPrice;
385
- };
386
- exports.calcBreakEvenPrice = calcBreakEvenPrice;
387
- var calcEstPnl = function (live, incentive, bidSize, optionType, assets, strikes, bidShare, deliveryPrice, oTokenPrice) {
388
- var profit = "0";
389
- var cost = "0";
390
- var _a = __read((0, token_2.typeArgsToAssets)(assets), 3), dToken = _a[0], bToken = _a[1], oToken = _a[2];
391
- var dTokenWrappedName = (0, token_1.getTokenName)({ token: dToken, wrapped: true });
392
- var bTokenWrappedName = (0, token_1.getTokenName)({ token: bToken, wrapped: true });
393
- var estPnls = [];
394
- var referencePrice = bidShare.bidVault.u64Padding.length > 0 ? (0, bignumber_js_1.default)(bidShare.bidVault.u64Padding[0]).div(PriceDecimal) : (0, bignumber_js_1.default)(oTokenPrice);
395
- if (optionType === "0") {
396
- profit = bignumber_js_1.default.max(0, (0, bignumber_js_1.default)(referencePrice.minus((0, bignumber_js_1.default)(strikes[0])))
397
- .div(referencePrice)
398
- .multipliedBy(bidSize)).toString();
399
- }
400
- else if (optionType === "1") {
401
- profit = bignumber_js_1.default.max(0, (0, bignumber_js_1.default)(strikes[0]).minus(referencePrice).multipliedBy(bidSize)).toString();
402
- }
403
- else if (optionType === "2" || optionType === "4") {
404
- profit = bignumber_js_1.default.max(0, (0, bignumber_js_1.default)(referencePrice.minus((0, bignumber_js_1.default)(strikes[0])))
405
- .div(referencePrice)
406
- .multipliedBy(bidSize))
407
- .minus(bignumber_js_1.default.max(0, (0, bignumber_js_1.default)(referencePrice.minus((0, bignumber_js_1.default)(strikes[1])))
408
- .div(referencePrice)
409
- .multipliedBy(bidSize)))
410
- .toString();
411
- }
412
- else if (optionType === "5") {
413
- profit = bignumber_js_1.default.max(0, (0, bignumber_js_1.default)((0, bignumber_js_1.default)(strikes[1]).minus(referencePrice)).multipliedBy(bidSize))
414
- .minus(bignumber_js_1.default.max(0, (0, bignumber_js_1.default)((0, bignumber_js_1.default)(strikes[0]).minus((0, bignumber_js_1.default)(referencePrice))).multipliedBy(bidSize)))
415
- .toString();
416
- }
417
- else if (optionType === "6") {
418
- profit = bignumber_js_1.default.max(0, (0, bignumber_js_1.default)(referencePrice.minus(strikes[0])).multipliedBy(bidSize))
419
- .minus(bignumber_js_1.default.max(0, (0, bignumber_js_1.default)(referencePrice.minus(strikes[1])).multipliedBy(bidSize)))
420
- .toString();
421
- }
422
- cost = (0, bignumber_js_1.default)(deliveryPrice).multipliedBy(bidSize).multipliedBy(1.1).multipliedBy(incentive).toString();
423
- if (dToken === bToken) {
424
- profit = (0, bignumber_js_1.default)(profit).minus(cost).toString();
425
- }
426
- if (!live) {
427
- estPnls.push({
428
- value: profit,
429
- token: assets[0],
430
- });
431
- if (dToken !== bToken) {
432
- estPnls.push({ value: "-" + cost, token: assets[1] });
433
- }
434
- }
435
- return estPnls;
436
- };
437
- exports.calcEstPnl = calcEstPnl;
438
- var parseStrikes = function (period, optionType, metadata) {
439
- var strikes = [period === "3" ? metadata.split("-")[3] : metadata.split("-")[2]];
440
- switch (optionType) {
441
- case "0":
442
- break;
443
- case "1":
444
- break;
445
- case "2":
446
- strikes = [metadata.split("-")[2], metadata.split("-")[3]];
447
- break;
448
- case "4":
449
- strikes = [metadata.split("-")[2], metadata.split("-")[3]];
450
- if (period == "3") {
451
- strikes = [metadata.split("-")[3], metadata.split("-")[4]];
452
- }
453
- strikes = strikes.sort(function (a, b) { return Number(a) - Number(b); });
454
- break;
455
- case "5":
456
- strikes = [metadata.split("-")[2], metadata.split("-")[3]];
457
- if (period == "3") {
458
- strikes = [metadata.split("-")[3], metadata.split("-")[4]];
459
- }
460
- strikes = strikes.sort(function (a, b) { return Number(a) - Number(b); });
461
- break;
462
- case "6":
463
- strikes = [metadata.split("-")[2], metadata.split("-")[3]];
464
- if (period == "3") {
465
- strikes = [metadata.split("-")[3], metadata.split("-")[4]];
466
- }
467
- strikes = strikes.sort(function (a, b) { return Number(a) - Number(b); });
468
- break;
469
- }
470
- strikes = (0, tools_1.checkNumber)(strikes[0]) ? strikes : [];
471
- strikes = strikes.sort(function (a, b) { return Number(a) - Number(b); });
472
- return strikes;
473
- };
474
- exports.parseStrikes = parseStrikes;
475
- var parseBidReceipt = function (vaults, bidReceipts) {
476
- var sortedBidReceipts = [];
477
- var bidVaultsInfo = [];
478
- var vidMap = new Map();
479
- vaults.forEach(function (v) {
480
- var curReceipts = bidReceipts[v.info.index];
481
- if (curReceipts) {
482
- curReceipts.map(function (receipt) {
483
- // ###### NOTE: #####
484
- // Bid receipts need to be sorted and put together
485
- // BY vid for SDK getMyBids to fetch the correct data.
486
- // ###########
487
- // Filer out autoBidReceiptsData receipts cuz it's wrapped in strategy and
488
- // SDK getMyBids can't retrieve it!
489
- var data = vidMap.get(receipt.vid);
490
- if (!data) {
491
- vidMap.set(receipt.vid, [receipt.id]);
492
- }
493
- else {
494
- data.push(receipt.id);
495
- vidMap.set(receipt.vid, data);
496
- }
497
- bidVaultsInfo.push({ vaultInfo: v, receipt: receipt });
498
- });
499
- var values = Array.from(vidMap.values());
500
- sortedBidReceipts = values.reduce(function (previousValue, currentValue, currentIndex, array) {
501
- return previousValue.concat(currentValue);
502
- }, []);
503
- }
504
- });
505
- return { sortedBidReceipts: sortedBidReceipts, bidVaultsInfo: bidVaultsInfo };
506
- };
507
- exports.parseBidReceipt = parseBidReceipt;
508
- var parseBid = function (bidVaultInfo, bidShare, auction, oTokenPrice, isAutoBid) {
509
- var _a, _b;
510
- var vaultInfo = bidVaultInfo.vaultInfo, _c = bidVaultInfo.vaultInfo, info = _c.info, _d = _c.info, index = _d.index, bTokenDecimal = _d.bTokenDecimal, oTokenDecimal = _d.oTokenDecimal, optionType = _d.optionType, period = _d.period, depositToken = _d.depositToken, bidToken = _d.bidToken, settlementBase = _d.settlementBase, _e = _c.config, lotSize = _e.bidLotSize, bidIncentiveBp = _e.bidIncentiveBp, u64Padding = _e.u64Padding, receipt = bidVaultInfo.receipt;
511
- var incentiveRate = (0, exports.calcIncentiveRate)(bidIncentiveBp);
512
- var _f = __read((0, vault_1.parseAssets)(info), 3), dToken = _f[0], bToken = _f[1], oToken = _f[2];
513
- var oTokenName = (0, token_1.getTokenName)({ token: oToken });
514
- var dTokenWrappedName = (0, token_1.getTokenName)({ token: dToken, wrapped: true });
515
- var bTokenWrappedName = (0, token_1.getTokenName)({ token: bToken, wrapped: true });
516
- var metadata = bidShare.bidVault.metadata;
517
- var tokenLabel = metadata.split("-")[0];
518
- var periodLabel = vault_1.Period[Number(period)].charAt(0).toUpperCase() + vault_1.Period[Number(period)].slice(1);
519
- var optionTypeLabel = vault_1.AbbrStrategyName[optionType];
520
- var bidsSize = Number(bidShare.share) / Math.pow(10, Number(oTokenDecimal));
521
- var expirationDate = (0, moment_1.default)(metadata.split("-")[1], "DDMMMYY").format("yyyy-MM-DD");
522
- expirationDate = moment_1.default
523
- .utc(period === "3" ? "".concat(expirationDate, " ").concat((0, tools_1.insertAt)(metadata.split("-")[2], ":", 2)) : "".concat(expirationDate, " 08:00"))
524
- .local()
525
- .format("DD MMM YY, HH:mm");
526
- var live = !auction
527
- ? false
528
- : moment_1.default.unix(Number(auction.endTsMs) / 1000).isAfter((0, moment_1.default)()) &&
529
- moment_1.default.unix(Number(auction.startTsMs) / 1000).isBefore((0, moment_1.default)()) &&
530
- (0, moment_1.default)(expirationDate, "DD MMM YY, HH:mm").isAfter(moment_1.default.unix(Number(auction.endTsMs) / 1000));
531
- var deliveryPrice = (0, exports.calcDeliveryPrice)(bidShare, vaultInfo);
532
- var initialPrice = (_a = auction === null || auction === void 0 ? void 0 : auction.initialPrice) !== null && _a !== void 0 ? _a : 0;
533
- initialPrice = (0, bignumber_js_1.default)(initialPrice).div((0, bignumber_js_1.default)(10).pow((0, bignumber_js_1.default)(bTokenDecimal)));
534
- var strikes = (0, exports.parseStrikes)(period, optionType, metadata);
535
- var breakEvenPriceReference = live ? initialPrice : deliveryPrice;
536
- var breakEvenPrice = (0, exports.calcBreakEvenPrice)(optionType, period, strikes, bToken, breakEvenPriceReference, incentiveRate);
537
- var defaultMinBidSize = (0, bignumber_js_1.default)(lotSize).div((0, bignumber_js_1.default)(10).pow(oTokenDecimal));
538
- var bidSize = bidsSize.toFixed((0, tools_1.countFloating)(defaultMinBidSize.toNumber()));
539
- var settlePrice = (0, bignumber_js_1.default)((_b = bidShare.bidVault.u64Padding[0]) !== null && _b !== void 0 ? _b : "0").div(PriceDecimal);
540
- var estPnls = (0, exports.calcEstPnl)(live, incentiveRate, bidSize, optionType, [depositToken, bidToken, settlementBase], strikes, bidShare, deliveryPrice.toString(), oTokenPrice);
541
- return {
542
- vaultIndex: index,
543
- auctionName: "".concat(tokenLabel, " ").concat(periodLabel, " ").concat(optionTypeLabel),
544
- expiry: expirationDate,
545
- strikes: strikes.map(function (s) {
546
- if (tokenLabel === "MFUD") {
547
- return (0, bignumber_js_1.default)(s).div(1000000).toString();
548
- }
549
- return s;
550
- }),
551
- bidSize: {
552
- value: (0, bignumber_js_1.default)(bidSize)
553
- .div((0, bignumber_js_1.default)(10).pow(oToken === "MFUD" ? 6 : 0))
554
- .toString(),
555
- token: settlementBase,
556
- },
557
- breakEvenPrice: (0, bignumber_js_1.default)(breakEvenPrice)
558
- .div((0, bignumber_js_1.default)(10).pow(oToken === "MFUD" ? 6 : 0))
559
- .toString(),
560
- settlePrice: (0, bignumber_js_1.default)(settlePrice)
561
- .div((0, bignumber_js_1.default)(10).pow(oToken === "MFUD" ? 6 : 0))
562
- .toString(),
563
- estPnls: estPnls,
564
- isAutoBid: isAutoBid,
565
- receiptsId: [receipt.id],
566
- receiptsVid: [receipt.vid],
567
- optionTypeOrder: exports.optionTypeOrder[optionType],
568
- periodOrder: exports.periodOrder[period],
569
- tokenOrder: exports.tokenOrder[oToken.toUpperCase()],
570
- };
571
- };
572
- exports.parseBid = parseBid;
573
- var getUserBidReceipts = function (provider, network, originFramworkAddress, userAddress) { return __awaiter(void 0, void 0, void 0, function () {
574
- var bidReceipts, result, hasNextPage, data, nextCursor, data_1, data_1_1, object, content, typeStringComponents, subtype, typeComponents, type, typePackage, vaultIndex, receipt;
575
- var e_1, _a;
576
- return __generator(this, function (_b) {
577
- switch (_b.label) {
578
- case 0:
579
- bidReceipts = {};
580
- return [4 /*yield*/, provider.getOwnedObjects({ owner: userAddress, options: { showType: true, showContent: true } })];
581
- case 1:
582
- result = _b.sent();
583
- hasNextPage = result.hasNextPage;
584
- data = result.data;
585
- nextCursor = result.nextCursor;
586
- _b.label = 2;
587
- case 2:
588
- if (!hasNextPage) return [3 /*break*/, 4];
589
- return [4 /*yield*/, provider.getOwnedObjects({ owner: userAddress, cursor: nextCursor, options: { showType: true, showContent: true } })];
590
- case 3:
591
- result = _b.sent();
592
- data = __spreadArray(__spreadArray([], __read(data), false), __read(result.data), false);
593
- hasNextPage = result.hasNextPage;
594
- nextCursor = result.nextCursor;
595
- return [3 /*break*/, 2];
596
- case 4:
597
- if (data.length === 0) {
598
- return [2 /*return*/, bidReceipts];
599
- }
600
- try {
601
- for (data_1 = __values(data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) {
602
- object = data_1_1.value;
603
- try {
604
- content = (object.data || {}).content;
605
- if (!content)
606
- continue;
607
- typeStringComponents = (content.type || "").split("<");
608
- subtype = (typeStringComponents[1] || "").replace(/>/, "");
609
- typeComponents = typeStringComponents[0].split("::");
610
- type = typeComponents[typeComponents.length - 1];
611
- typePackage = typeComponents[0];
612
- if (type === "TypusBidReceipt" && originFramworkAddress == typePackage) {
613
- vaultIndex = content.fields.index;
614
- receipt = {
615
- // @ts-ignore
616
- id: content.fields.id.id,
617
- // @ts-ignore
618
- index: vaultIndex,
619
- // @ts-ignore
620
- name: content.fields.name,
621
- // @ts-ignore
622
- description: content.fields.description,
623
- // @ts-ignore
624
- vid: content.fields.vid,
625
- // @ts-ignore
626
- metadata: content.fields.metadata,
627
- };
628
- bidReceipts[vaultIndex] || (bidReceipts[vaultIndex] = []);
629
- bidReceipts[vaultIndex].push(receipt);
630
- }
631
- }
632
- catch (e) {
633
- console.log("Error retrieving object", object, e);
634
- }
635
- }
636
- }
637
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
638
- finally {
639
- try {
640
- if (data_1_1 && !data_1_1.done && (_a = data_1.return)) _a.call(data_1);
641
- }
642
- finally { if (e_1) throw e_1.error; }
643
- }
644
- return [2 /*return*/, bidReceipts];
645
- }
646
- });
647
- }); };
648
- exports.getUserBidReceipts = getUserBidReceipts;
649
- /**
650
- * Fetch user's bids info
651
- *
652
- * @param provider - Sui Client instance.
653
- * @param network - network type in lowercase.
654
- * @param packageAddress - Typus main package address.
655
- * @param framworkAddress - Typus framwork package address.
656
- * @param originFramworkAddress - Typus intial framwork package address.
657
- * @param registryAddress - Typus registry package address.
658
- * @param strategyPoolAddress - strategy pool package address.
659
- * @param userAddress - user's wallet address.
660
- * @param prices - tokens prices (usd pair on Pyth)
661
- * @return User Bids.
662
- */
663
- var fetchUserBids = function (provider, network, packageAddress, framworkAddress, originFramworkAddress, registryAddress, strategyPoolAddress, userAddress, prices) { return __awaiter(void 0, void 0, void 0, function () {
664
- var vaultsInfo, userReceipts, userStrategies, auctions, _a, sortedBidReceipts, bidVaultsInfo, bidShares, bidsFromBidShares, _loop_1, bidVaultsInfo_1, bidVaultsInfo_1_1, bidVaultInfo, autoBidsShares, vaultAutoBidReceipts, userStrategies_1, userStrategies_1_1, strategy, receipts, receipts_1, receipts_1_1, receiptItem, vaultIndex, receipt, autoBidVaultInfos, bidsFromStrategies, _loop_2, autoBidVaultInfos_1, autoBidVaultInfos_1_1, autoBidVaultInfo, byOrdered;
665
- var e_2, _b, e_3, _c, e_4, _d, e_5, _e;
666
- return __generator(this, function (_f) {
667
- switch (_f.label) {
668
- case 0: return [4 /*yield*/, (0, view_function_1.getVaults)(provider, packageAddress, registryAddress, [])];
669
- case 1:
670
- vaultsInfo = _f.sent();
671
- return [4 /*yield*/, (0, exports.getUserBidReceipts)(provider, network, originFramworkAddress, userAddress)];
672
- case 2:
673
- userReceipts = _f.sent();
674
- return [4 /*yield*/, (0, view_function_2.getUserStrategies)(provider, packageAddress, registryAddress, strategyPoolAddress, userAddress)];
675
- case 3:
676
- userStrategies = _f.sent();
677
- return [4 /*yield*/, (0, view_function_1.getAuctions)(provider, packageAddress, registryAddress, [])];
678
- case 4:
679
- auctions = _f.sent();
680
- if (!(typeof prices === "undefined")) return [3 /*break*/, 6];
681
- return [4 /*yield*/, (0, exports.fetchPrices)(provider, "testnet")];
682
- case 5:
683
- prices = _f.sent();
684
- _f.label = 6;
685
- case 6:
686
- _a = (0, exports.parseBidReceipt)(Object.values(vaultsInfo), userReceipts), sortedBidReceipts = _a.sortedBidReceipts, bidVaultsInfo = _a.bidVaultsInfo;
687
- return [4 /*yield*/, (0, view_function_1.getMyBids)(provider, framworkAddress, packageAddress, registryAddress, sortedBidReceipts)];
688
- case 7:
689
- bidShares = _f.sent();
690
- bidsFromBidShares = [];
691
- _loop_1 = function (bidVaultInfo) {
692
- var bidShare = bidShares["".concat(bidVaultInfo.receipt.index, "-").concat(bidVaultInfo.receipt.vid)];
693
- var auction = auctions ? auctions[bidVaultInfo.vaultInfo.info.index] : null;
694
- var _g = __read((0, vault_1.parseAssets)(bidVaultInfo.vaultInfo.info), 3), dToken = _g[0], bToken = _g[1], oToken = _g[2];
695
- if (bidShare) {
696
- var price = (0, bignumber_js_1.default)(prices[oToken.toLowerCase()].price)
697
- .div((0, bignumber_js_1.default)(10).pow(prices[oToken.toLowerCase()].decimal))
698
- .toString();
699
- var data = (0, exports.parseBid)(bidVaultInfo, bidShare, auction, price, false);
700
- var checkExistVault = bidsFromBidShares.find(function (p) { return p.vaultIndex === bidVaultInfo.vaultInfo.info.index && p.receiptsVid.includes(bidVaultInfo.receipt.vid); });
701
- if (checkExistVault) {
702
- // Merge the bid receipts into the same vault
703
- checkExistVault.receiptsId = __spreadArray(__spreadArray([], __read(checkExistVault.receiptsId), false), __read(data.receiptsId), false);
704
- }
705
- else {
706
- bidsFromBidShares.push(data);
707
- }
708
- }
709
- };
710
- try {
711
- for (bidVaultsInfo_1 = __values(bidVaultsInfo), bidVaultsInfo_1_1 = bidVaultsInfo_1.next(); !bidVaultsInfo_1_1.done; bidVaultsInfo_1_1 = bidVaultsInfo_1.next()) {
712
- bidVaultInfo = bidVaultsInfo_1_1.value;
713
- _loop_1(bidVaultInfo);
714
- }
715
- }
716
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
717
- finally {
718
- try {
719
- if (bidVaultsInfo_1_1 && !bidVaultsInfo_1_1.done && (_b = bidVaultsInfo_1.return)) _b.call(bidVaultsInfo_1);
720
- }
721
- finally { if (e_2) throw e_2.error; }
722
- }
723
- autoBidsShares = {};
724
- vaultAutoBidReceipts = {};
725
- try {
726
- for (userStrategies_1 = __values(userStrategies), userStrategies_1_1 = userStrategies_1.next(); !userStrategies_1_1.done; userStrategies_1_1 = userStrategies_1.next()) {
727
- strategy = userStrategies_1_1.value;
728
- receipts = strategy.receipts;
729
- try {
730
- for (receipts_1 = (e_4 = void 0, __values(receipts)), receipts_1_1 = receipts_1.next(); !receipts_1_1.done; receipts_1_1 = receipts_1.next()) {
731
- receiptItem = receipts_1_1.value;
732
- vaultIndex = receiptItem.index;
733
- receipt = {
734
- id: receiptItem.id,
735
- index: vaultIndex,
736
- name: "",
737
- description: "",
738
- vid: receiptItem.vid,
739
- metadata: receiptItem.metadata,
740
- };
741
- if (vaultAutoBidReceipts[vaultIndex]) {
742
- vaultAutoBidReceipts[vaultIndex] = __spreadArray(__spreadArray([], __read(vaultAutoBidReceipts[vaultIndex]), false), [receipt], false);
743
- }
744
- else {
745
- vaultAutoBidReceipts[vaultIndex] = [receipt];
746
- }
747
- if (autoBidsShares["".concat(vaultIndex, "-").concat(receiptItem.vid)]) {
748
- autoBidsShares["".concat(vaultIndex, "-").concat(receiptItem.vid)].share = (Number(autoBidsShares["".concat(vaultIndex, "-").concat(receiptItem.vid)].share) +
749
- Number(strategy.my_bids["".concat(vaultIndex, "-").concat(receiptItem.vid)].share)).toString();
750
- }
751
- else {
752
- autoBidsShares["".concat(vaultIndex, "-").concat(receiptItem.vid)] = {
753
- bidVault: strategy.my_bids["".concat(vaultIndex, "-").concat(receiptItem.vid)].bidVault,
754
- share: strategy.my_bids["".concat(vaultIndex, "-").concat(receiptItem.vid)].share,
755
- };
756
- }
757
- }
758
- }
759
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
760
- finally {
761
- try {
762
- if (receipts_1_1 && !receipts_1_1.done && (_d = receipts_1.return)) _d.call(receipts_1);
763
- }
764
- finally { if (e_4) throw e_4.error; }
765
- }
766
- }
767
- }
768
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
769
- finally {
770
- try {
771
- if (userStrategies_1_1 && !userStrategies_1_1.done && (_c = userStrategies_1.return)) _c.call(userStrategies_1);
772
- }
773
- finally { if (e_3) throw e_3.error; }
774
- }
775
- autoBidVaultInfos = [];
776
- Object.values(vaultsInfo).forEach(function (v) {
777
- var curReceipts = vaultAutoBidReceipts[v.info.index];
778
- if (curReceipts) {
779
- curReceipts.map(function (item) {
780
- autoBidVaultInfos.push({ vaultInfo: v, receipt: item });
781
- });
782
- }
783
- });
784
- bidsFromStrategies = [];
785
- _loop_2 = function (autoBidVaultInfo) {
786
- var bidShare = autoBidsShares["".concat(autoBidVaultInfo.receipt.index, "-").concat(autoBidVaultInfo.receipt.vid)];
787
- var auction = auctions ? auctions[autoBidVaultInfo.vaultInfo.info.index] : null;
788
- var _h = __read((0, vault_1.parseAssets)(autoBidVaultInfo.vaultInfo.info), 3), dToken = _h[0], bToken = _h[1], oToken = _h[2];
789
- if (bidShare) {
790
- var price = (0, bignumber_js_1.default)(prices[oToken.toLowerCase()].price)
791
- .div((0, bignumber_js_1.default)(10).pow(prices[oToken.toLowerCase()].decimal))
792
- .toString();
793
- var data = (0, exports.parseBid)(autoBidVaultInfo, bidShare, auction, price, false);
794
- var checkExistVault = bidsFromStrategies.find(function (p) { return p.vaultIndex === autoBidVaultInfo.vaultInfo.info.index && p.receiptsVid.includes(autoBidVaultInfo.receipt.vid); });
795
- if (checkExistVault) {
796
- // Merge the bid receipts into the same vault
797
- checkExistVault.receiptsId = __spreadArray(__spreadArray([], __read(checkExistVault.receiptsId), false), __read(data.receiptsId), false);
798
- }
799
- else {
800
- bidsFromStrategies.push(data);
801
- }
802
- }
803
- };
804
- try {
805
- for (autoBidVaultInfos_1 = __values(autoBidVaultInfos), autoBidVaultInfos_1_1 = autoBidVaultInfos_1.next(); !autoBidVaultInfos_1_1.done; autoBidVaultInfos_1_1 = autoBidVaultInfos_1.next()) {
806
- autoBidVaultInfo = autoBidVaultInfos_1_1.value;
807
- _loop_2(autoBidVaultInfo);
808
- }
809
- }
810
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
811
- finally {
812
- try {
813
- if (autoBidVaultInfos_1_1 && !autoBidVaultInfos_1_1.done && (_e = autoBidVaultInfos_1.return)) _e.call(autoBidVaultInfos_1);
814
- }
815
- finally { if (e_5) throw e_5.error; }
816
- }
817
- byOrdered = (0, lodash_1.orderBy)(__spreadArray(__spreadArray([], __read(bidsFromBidShares), false), __read(bidsFromStrategies), false), ["expiry", "tokenOrder", "periodOrder", "optionTypeOrder"], ["asc", "asc", "asc", "asc"]);
818
- return [2 /*return*/, byOrdered];
819
- }
820
- });
821
- }); };
822
- exports.fetchUserBids = fetchUserBids;