@pioneer-platform/thorchain-client 0.0.26

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/lib/index.js ADDED
@@ -0,0 +1,246 @@
1
+ "use strict";
2
+ /*
3
+ Maya Swap Integration
4
+ - Highlander
5
+ */
6
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
+ return new (P || (P = Promise))(function (resolve, reject) {
9
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
13
+ });
14
+ };
15
+ var __generator = (this && this.__generator) || function (thisArg, body) {
16
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
17
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
18
+ function verb(n) { return function (v) { return step([n, v]); }; }
19
+ function step(op) {
20
+ if (f) throw new TypeError("Generator is already executing.");
21
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
22
+ 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;
23
+ if (y = 0, t) op = [op[0] & 2, t.value];
24
+ switch (op[0]) {
25
+ case 0: case 1: t = op; break;
26
+ case 4: _.label++; return { value: op[1], done: false };
27
+ case 5: _.label++; y = op[1]; op = [0]; continue;
28
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
29
+ default:
30
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
31
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
32
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
33
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
34
+ if (t[2]) _.ops.pop();
35
+ _.trys.pop(); continue;
36
+ }
37
+ op = body.call(thisArg, _);
38
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
39
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
40
+ }
41
+ };
42
+ Object.defineProperty(exports, "__esModule", { value: true });
43
+ var TAG = " | maya | ";
44
+ var uuid = require('uuidv4').uuid;
45
+ var log = require('@pioneer-platform/loggerdog')();
46
+ var _a = require("@pioneer-platform/pioneer-caip"), caipToNetworkId = _a.caipToNetworkId, shortListSymbolToCaip = _a.shortListSymbolToCaip, ChainToNetworkId = _a.ChainToNetworkId;
47
+ var network = require("@pioneer-platform/midgard-client");
48
+ var _b = require('@pioneer-platform/pioneer-coins'), createMemo = _b.createMemo, parseMemo = _b.parseMemo;
49
+ var networkSupport = [
50
+ ChainToNetworkId["BTC"],
51
+ ChainToNetworkId["ETH"],
52
+ ChainToNetworkId["THOR"],
53
+ ];
54
+ // Function to make a request to the node
55
+ function nodeRequest(path) {
56
+ return __awaiter(this, void 0, void 0, function () {
57
+ var response, data, error_1;
58
+ return __generator(this, function (_a) {
59
+ switch (_a.label) {
60
+ case 0:
61
+ _a.trys.push([0, 3, , 4]);
62
+ return [4 /*yield*/, fetch("https://thornode.ninerealms.com".concat(path))];
63
+ case 1:
64
+ response = _a.sent();
65
+ return [4 /*yield*/, response.json()];
66
+ case 2:
67
+ data = _a.sent();
68
+ return [2 /*return*/, data];
69
+ case 3:
70
+ error_1 = _a.sent();
71
+ console.error('Error fetching from node:', error_1);
72
+ throw error_1;
73
+ case 4: return [2 /*return*/];
74
+ }
75
+ });
76
+ });
77
+ }
78
+ module.exports = {
79
+ init: function (settings) {
80
+ return true;
81
+ },
82
+ networkSupport: function () {
83
+ return networkSupport;
84
+ },
85
+ getQuote: function (quote) {
86
+ return get_quote(quote);
87
+ },
88
+ };
89
+ function quoteFromPool(sellAmount, assetPoolAmount, runePoolAmount, maxSlippage) {
90
+ // Convert string inputs to numbers and scale the sell amount
91
+ var swapAmount = parseFloat(sellAmount) * 1e8; // Assuming 1e6 is the scaling factor for Maya
92
+ var assetDepth = parseFloat(assetPoolAmount);
93
+ var runeDepth = parseFloat(runePoolAmount);
94
+ // Calculate the constant product
95
+ var k = assetDepth * runeDepth;
96
+ // New amount of the asset in the pool after the swap
97
+ var newAssetDepth = assetDepth + swapAmount;
98
+ // Calculate the amount of Rune received (or the other asset in the pool)
99
+ var newRuneDepth = k / newAssetDepth;
100
+ var runeReceived = runeDepth - newRuneDepth;
101
+ // Scale back down the amount of Rune received
102
+ var scaledRuneReceived = runeReceived / 1e6; // Adjust as per Rune's scaling factor
103
+ // Calculate the actual rate of the swap
104
+ var actualRate = scaledRuneReceived / (swapAmount / 1e6);
105
+ // Calculate the ideal rate
106
+ var idealRate = runeDepth / assetDepth;
107
+ // Calculate the slippage
108
+ var slippage = ((idealRate - actualRate) / idealRate) * 100;
109
+ // Calculate amountOutMin considering the maximum slippage
110
+ var amountOutMin = scaledRuneReceived * (1 - maxSlippage / 100);
111
+ return {
112
+ amountOutMin: amountOutMin.toFixed(6).toString(),
113
+ amountOut: scaledRuneReceived.toFixed(6),
114
+ slippage: Math.max(slippage, 0).toFixed(6)
115
+ };
116
+ }
117
+ var get_quote = function (quote) {
118
+ return __awaiter(this, void 0, void 0, function () {
119
+ var tag, output, pools, poolIn, poolOut, BaseDecimal_1, asset, DECIMALS, BASE_UNIT, sellAmountInBaseUnits, quoteFromNode, URL_1, amountOutMin, inboundAddress, amountOutEstimated, memoInput, memo, type, chain, tx, e_1;
120
+ return __generator(this, function (_a) {
121
+ switch (_a.label) {
122
+ case 0:
123
+ tag = TAG + " | get_quote | ";
124
+ _a.label = 1;
125
+ case 1:
126
+ _a.trys.push([1, 4, , 5]);
127
+ output = {};
128
+ if (!quote.sellAsset)
129
+ throw new Error("missing sellAsset");
130
+ if (!quote.buyAsset)
131
+ throw new Error("missing buyAsset");
132
+ if (!quote.sellAmount)
133
+ throw new Error("missing sellAmount");
134
+ if (!quote.senderAddress)
135
+ throw new Error("missing senderAddress");
136
+ if (!quote.recipientAddress)
137
+ throw new Error("missing recipientAddress");
138
+ if (!quote.slippage)
139
+ throw new Error("missing slippage");
140
+ return [4 /*yield*/, network.getPools()];
141
+ case 2:
142
+ pools = _a.sent();
143
+ if (!pools)
144
+ throw Error("Unable to get pools from network!");
145
+ log.info(tag, "pools: ", pools);
146
+ poolIn = pools.find(function (p) { return p.asset == quote.sellAsset; });
147
+ log.info(tag, "poolIn: ", poolIn);
148
+ poolOut = pools.find(function (p) { return p.asset == quote.buyAsset; });
149
+ output.meta = {
150
+ quoteMode: "TC_SUPPORTED_TO_TC_SUPPORTED"
151
+ };
152
+ output.steps = 1;
153
+ output.complete = true;
154
+ output.id = uuid();
155
+ BaseDecimal_1 = {
156
+ ARB: 18,
157
+ AVAX: 18,
158
+ BCH: 8,
159
+ BNB: 8,
160
+ BSC: 18,
161
+ BTC: 8,
162
+ DASH: 8,
163
+ DGB: 8,
164
+ DOGE: 8,
165
+ ETH: 18,
166
+ BASE: 18,
167
+ EOS: 6,
168
+ GAIA: 6,
169
+ KUJI: 6,
170
+ LTC: 8,
171
+ MATIC: 18,
172
+ MAYA: 10,
173
+ OP: 18,
174
+ OSMO: 6,
175
+ XRP: 6,
176
+ THOR: 8,
177
+ ZEC: 8
178
+ };
179
+ asset = quote.sellAsset.split(".")[0];
180
+ if (!asset)
181
+ throw Error("unable to pasre asset from quote.sellAsset");
182
+ DECIMALS = BaseDecimal_1[asset];
183
+ if (!DECIMALS)
184
+ throw Error("unable to get DECIMALS for asset: " + asset);
185
+ BASE_UNIT = Math.pow(10, DECIMALS);
186
+ sellAmountInBaseUnits = parseFloat(quote.sellAmount) * BASE_UNIT;
187
+ quoteFromNode = void 0;
188
+ URL_1 = "/quote/swap?from_asset=".concat(quote.sellAsset, "&to_asset=").concat(quote.buyAsset, "&amount=").concat(sellAmountInBaseUnits, "&destination=").concat(quote.recipientAddress);
189
+ log.info("URL: ", URL_1);
190
+ return [4 /*yield*/, nodeRequest(URL_1)];
191
+ case 3:
192
+ quoteFromNode = _a.sent();
193
+ log.info("quoteFromNode: ", quoteFromNode);
194
+ if (quoteFromNode.error)
195
+ throw Error(quoteFromNode.error);
196
+ amountOutMin = quoteFromNode.amount_out_min;
197
+ inboundAddress = quoteFromNode.inbound_address;
198
+ amountOutEstimated = (parseInt(quoteFromNode.expected_amount_out) / BASE_UNIT).toFixed(DECIMALS);
199
+ output.amountOut = amountOutEstimated;
200
+ memoInput = {
201
+ type: 'SWAP',
202
+ asset: quote.buyAsset,
203
+ destAddr: quote.recipientAddress,
204
+ lim: null,
205
+ interval: null,
206
+ quantity: null,
207
+ affiliate: null,
208
+ fee: null,
209
+ dexAggregatorAddr: null,
210
+ finalAssetAddr: null,
211
+ minAmountOut: null
212
+ };
213
+ memo = createMemo(memoInput);
214
+ log.info(tag, "memo: ", memo);
215
+ type = void 0;
216
+ chain = quote.sellAsset.split(".")[0];
217
+ if (chain == "MAYA") {
218
+ type = 'deposit';
219
+ }
220
+ else {
221
+ type = 'transfer';
222
+ }
223
+ tx = {
224
+ type: type,
225
+ chain: ChainToNetworkId[quote.sellAsset.split(".")[0]],
226
+ txParams: {
227
+ senderAddress: quote.senderAddress,
228
+ recipientAddress: quoteFromNode.inbound_address,
229
+ amount: quote.sellAmount,
230
+ token: quote.sellAsset.split(".")[1],
231
+ memo: quoteFromNode.memo || memo
232
+ }
233
+ };
234
+ output.txs = [
235
+ tx
236
+ ];
237
+ return [2 /*return*/, output];
238
+ case 4:
239
+ e_1 = _a.sent();
240
+ console.error(tag, "e: ", e_1);
241
+ throw e_1;
242
+ case 5: return [2 /*return*/];
243
+ }
244
+ });
245
+ });
246
+ };
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@pioneer-platform/thorchain-client",
3
+ "version": "0.0.26",
4
+ "main": "./lib/index.js",
5
+ "types": "./lib/index.d.ts",
6
+ "dependencies": {
7
+ "@pioneer-platform/loggerdog": "^8.3.1",
8
+ "@pioneer-platform/pioneer-caip": "^9.2.23",
9
+ "@pioneer-platform/pioneer-coins": "^9.2.13",
10
+ "axios": "^1.3.4",
11
+ "dotenv": "^8.2.0",
12
+ "rango-sdk": "^0.1.45",
13
+ "uuidv4": "^6.2.13"
14
+ },
15
+ "scripts": {
16
+ "npm": "npm i",
17
+ "test": "npm run build && node __tests__/test-module.js",
18
+ "build": "tsc -p .",
19
+ "prepublish": "npm run build",
20
+ "refresh": "rm -rf ./node_modules ./package-lock.json && npm install"
21
+ },
22
+ "devDependencies": {
23
+ "@types/jest": "^25.2.3",
24
+ "@types/node": "^13.13.21",
25
+ "@types/source-map-support": "^0.5.3",
26
+ "jest": "^26.4.2",
27
+ "onchange": "^7.0.2",
28
+ "serve": "^11.3.2",
29
+ "ts-jest": "^29.0.5",
30
+ "typescript": "^5.0.2"
31
+ },
32
+ "gitHead": "0de2bc2b38ab25ab7972cb963c66e37af6c82712"
33
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es5",
4
+ "module": "commonjs",
5
+ "lib": ["es6", "es2015", "dom"],
6
+ "declaration": true,
7
+ "outDir": "lib",
8
+ "rootDir": "src",
9
+ "strict": true,
10
+ "types": ["node"],
11
+ "esModuleInterop": true
12
+ }
13
+ }