@cityofzion/bs-multichain 0.0.1 → 1.0.2

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.
@@ -0,0 +1,258 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
12
+ if (kind === "m") throw new TypeError("Private method is not writable");
13
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
14
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
15
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
16
+ };
17
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
18
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
19
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
+ };
22
+ var __importDefault = (this && this.__importDefault) || function (mod) {
23
+ return (mod && mod.__esModule) ? mod : { "default": mod };
24
+ };
25
+ var _SimpleSwapApi_instances, _SimpleSwapApi_tickersBySimpleSwapBlockchain, _SimpleSwapApi_axios, _SimpleSwapApi_allCurrenciesMap, _SimpleSwapApi_createAddressTemplateUrl, _SimpleSwapApi_createTxTemplateUrl, _SimpleSwapApi_getTokenFromCurrency;
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.SimpleSwapApi = void 0;
28
+ const axios_1 = __importDefault(require("axios"));
29
+ const blockchain_service_1 = require("@cityofzion/blockchain-service");
30
+ class SimpleSwapApi {
31
+ constructor() {
32
+ _SimpleSwapApi_instances.add(this);
33
+ _SimpleSwapApi_tickersBySimpleSwapBlockchain.set(this, {
34
+ neo3: {
35
+ neo3: 'neo',
36
+ gasn3: 'gas',
37
+ },
38
+ });
39
+ _SimpleSwapApi_axios.set(this, void 0);
40
+ _SimpleSwapApi_allCurrenciesMap.set(this, new Map());
41
+ __classPrivateFieldSet(this, _SimpleSwapApi_axios, axios_1.default.create({
42
+ baseURL: `${blockchain_service_1.BSCommonConstants.DORA_URL}/api/v2/swap`,
43
+ headers: {
44
+ 'Cache-Control': 'no-cache',
45
+ Pragma: 'no-cache',
46
+ Expires: '0',
47
+ },
48
+ }), "f");
49
+ }
50
+ getCurrencies(options) {
51
+ var _a;
52
+ return __awaiter(this, void 0, void 0, function* () {
53
+ try {
54
+ if (__classPrivateFieldGet(this, _SimpleSwapApi_allCurrenciesMap, "f").size) {
55
+ return Array.from(__classPrivateFieldGet(this, _SimpleSwapApi_allCurrenciesMap, "f").values());
56
+ }
57
+ const response = yield __classPrivateFieldGet(this, _SimpleSwapApi_axios, "f").get('/currencies');
58
+ const tokens = [];
59
+ response.data.result.forEach(currency => {
60
+ const token = __classPrivateFieldGet(this, _SimpleSwapApi_instances, "m", _SimpleSwapApi_getTokenFromCurrency).call(this, currency, options);
61
+ if (!token)
62
+ return;
63
+ __classPrivateFieldGet(this, _SimpleSwapApi_allCurrenciesMap, "f").set(`${token.ticker}:${token.network}`, token);
64
+ if (!token.blockchain)
65
+ return;
66
+ tokens.push(token);
67
+ });
68
+ return tokens;
69
+ }
70
+ catch (error) {
71
+ if (axios_1.default.isAxiosError(error) && ((_a = error.response) === null || _a === void 0 ? void 0 : _a.data.message)) {
72
+ throw new Error(error.response.data.message);
73
+ }
74
+ throw error;
75
+ }
76
+ });
77
+ }
78
+ getPairs(ticker, network) {
79
+ var _a, _b;
80
+ return __awaiter(this, void 0, void 0, function* () {
81
+ try {
82
+ const response = yield __classPrivateFieldGet(this, _SimpleSwapApi_axios, "f").get(`/pairs/${ticker}/${network}`);
83
+ const pairs = (_a = response.data.result[`${ticker}:${network}`]) !== null && _a !== void 0 ? _a : [];
84
+ const tokens = [];
85
+ pairs.forEach(pair => {
86
+ const token = __classPrivateFieldGet(this, _SimpleSwapApi_allCurrenciesMap, "f").get(pair);
87
+ if (token)
88
+ tokens.push(token);
89
+ });
90
+ return tokens;
91
+ }
92
+ catch (error) {
93
+ if (axios_1.default.isAxiosError(error) && ((_b = error.response) === null || _b === void 0 ? void 0 : _b.data.message)) {
94
+ throw new Error(error.response.data.message);
95
+ }
96
+ throw error;
97
+ }
98
+ });
99
+ }
100
+ getRange(currencyFrom, currencyTo) {
101
+ var _a;
102
+ return __awaiter(this, void 0, void 0, function* () {
103
+ try {
104
+ const response = yield __classPrivateFieldGet(this, _SimpleSwapApi_axios, "f").get('/ranges', {
105
+ params: {
106
+ tickerFrom: currencyFrom.ticker,
107
+ tickerTo: currencyTo.ticker,
108
+ networkFrom: currencyFrom.network,
109
+ networkTo: currencyTo.network,
110
+ },
111
+ });
112
+ return response.data.result;
113
+ }
114
+ catch (error) {
115
+ if (axios_1.default.isAxiosError(error) && ((_a = error.response) === null || _a === void 0 ? void 0 : _a.data.message)) {
116
+ throw new Error(error.response.data.message);
117
+ }
118
+ throw error;
119
+ }
120
+ });
121
+ }
122
+ getEstimate(currencyFrom, currencyTo, amount) {
123
+ var _a;
124
+ return __awaiter(this, void 0, void 0, function* () {
125
+ try {
126
+ const response = yield __classPrivateFieldGet(this, _SimpleSwapApi_axios, "f").get('/estimates', {
127
+ params: {
128
+ tickerFrom: currencyFrom.ticker,
129
+ tickerTo: currencyTo.ticker,
130
+ networkFrom: currencyFrom.network,
131
+ networkTo: currencyTo.network,
132
+ amount,
133
+ },
134
+ });
135
+ return response.data.result.estimatedAmount;
136
+ }
137
+ catch (error) {
138
+ if (axios_1.default.isAxiosError(error) && ((_a = error.response) === null || _a === void 0 ? void 0 : _a.data.message)) {
139
+ throw new Error(error.response.data.message);
140
+ }
141
+ throw error;
142
+ }
143
+ });
144
+ }
145
+ createExchange({ currencyFrom, currencyTo, amount, refundAddress, address, extraIdToReceive, }) {
146
+ var _a, _b;
147
+ return __awaiter(this, void 0, void 0, function* () {
148
+ try {
149
+ const { data: { result }, } = yield __classPrivateFieldGet(this, _SimpleSwapApi_axios, "f").post('/exchanges', {
150
+ tickerFrom: currencyFrom.ticker,
151
+ networkFrom: currencyFrom.network,
152
+ tickerTo: currencyTo.ticker,
153
+ networkTo: currencyTo.network,
154
+ amount,
155
+ userRefundAddress: refundAddress,
156
+ addressTo: address,
157
+ extraIdTo: (_a = extraIdToReceive === null || extraIdToReceive === void 0 ? void 0 : extraIdToReceive.trim()) !== null && _a !== void 0 ? _a : null,
158
+ });
159
+ return {
160
+ id: result.id,
161
+ depositAddress: result.addressFrom,
162
+ log: JSON.stringify(result),
163
+ };
164
+ }
165
+ catch (error) {
166
+ if (axios_1.default.isAxiosError(error) && ((_b = error.response) === null || _b === void 0 ? void 0 : _b.data.message)) {
167
+ throw new Error(error.response.data.message);
168
+ }
169
+ throw error;
170
+ }
171
+ });
172
+ }
173
+ getExchange(id) {
174
+ var _a;
175
+ return __awaiter(this, void 0, void 0, function* () {
176
+ try {
177
+ const { data: { result }, } = yield __classPrivateFieldGet(this, _SimpleSwapApi_axios, "f").get(`/exchanges/${id}`);
178
+ return {
179
+ status: result.status,
180
+ txFrom: result.txFrom,
181
+ txTo: result.txTo,
182
+ log: JSON.stringify(result),
183
+ };
184
+ }
185
+ catch (error) {
186
+ if (axios_1.default.isAxiosError(error) && ((_a = error.response) === null || _a === void 0 ? void 0 : _a.data.message)) {
187
+ throw new Error(error.response.data.message);
188
+ }
189
+ throw error;
190
+ }
191
+ });
192
+ }
193
+ }
194
+ exports.SimpleSwapApi = SimpleSwapApi;
195
+ _SimpleSwapApi_tickersBySimpleSwapBlockchain = new WeakMap(), _SimpleSwapApi_axios = new WeakMap(), _SimpleSwapApi_allCurrenciesMap = new WeakMap(), _SimpleSwapApi_instances = new WeakSet(), _SimpleSwapApi_createAddressTemplateUrl = function _SimpleSwapApi_createAddressTemplateUrl(blockchainService, explorer) {
196
+ var _a;
197
+ explorer = !explorer ? undefined : explorer.replace('{}', '{address}');
198
+ if (blockchainService && (0, blockchain_service_1.hasExplorerService)(blockchainService))
199
+ return (_a = blockchainService.explorerService.getAddressTemplateUrl()) !== null && _a !== void 0 ? _a : explorer;
200
+ return explorer;
201
+ }, _SimpleSwapApi_createTxTemplateUrl = function _SimpleSwapApi_createTxTemplateUrl(blockchainService, explorer) {
202
+ var _a;
203
+ explorer = !explorer ? undefined : explorer.replace('{}', '{txId}');
204
+ if (blockchainService && (0, blockchain_service_1.hasExplorerService)(blockchainService))
205
+ return (_a = blockchainService.explorerService.getTxTemplateUrl()) !== null && _a !== void 0 ? _a : explorer;
206
+ return explorer;
207
+ }, _SimpleSwapApi_getTokenFromCurrency = function _SimpleSwapApi_getTokenFromCurrency(currency, options) {
208
+ var _a;
209
+ const { network: simpleSwapBlockchain, ticker } = currency;
210
+ let { name } = currency;
211
+ let symbol = ticker;
212
+ if (!ticker || !simpleSwapBlockchain || !currency.image || !name || !currency.validationAddress)
213
+ return;
214
+ const chainsByServiceNameEntries = Object.entries(options.chainsByServiceName);
215
+ const chainsByServiceNameEntry = chainsByServiceNameEntries.find(([_serviceName, chains]) => chains.includes(simpleSwapBlockchain));
216
+ let blockchain;
217
+ let blockchainService;
218
+ let decimals;
219
+ let hash = (_a = currency.contractAddress) !== null && _a !== void 0 ? _a : undefined;
220
+ const normalizedHash = hash ? blockchain_service_1.BSTokenHelper.normalizeHash(hash) : '';
221
+ const lowerCaseSymbol = symbol.toLowerCase();
222
+ const tickers = __classPrivateFieldGet(this, _SimpleSwapApi_tickersBySimpleSwapBlockchain, "f")[simpleSwapBlockchain];
223
+ if (chainsByServiceNameEntry) {
224
+ blockchain = chainsByServiceNameEntry[0];
225
+ blockchainService = options.blockchainServicesByName[blockchain];
226
+ const token = blockchainService.tokens.find(item => {
227
+ if (normalizedHash && blockchain_service_1.BSTokenHelper.predicateByHash(item)(normalizedHash))
228
+ return true;
229
+ const currentLowerCaseSymbol = item.symbol.toLowerCase();
230
+ if (!normalizedHash)
231
+ return (lowerCaseSymbol === currentLowerCaseSymbol ||
232
+ (!!tickers && currentLowerCaseSymbol === tickers[lowerCaseSymbol]));
233
+ return false;
234
+ });
235
+ if (token) {
236
+ hash = token.hash;
237
+ decimals = token.decimals;
238
+ name = token.name;
239
+ symbol = token.symbol;
240
+ }
241
+ }
242
+ return {
243
+ id: `${ticker}:${simpleSwapBlockchain}`,
244
+ ticker,
245
+ symbol: symbol,
246
+ network: simpleSwapBlockchain,
247
+ name,
248
+ imageUrl: currency.image,
249
+ hash,
250
+ decimals,
251
+ hasExtraId: currency.hasExtraId,
252
+ validationExtra: currency.validationExtra,
253
+ validationAddress: currency.validationAddress,
254
+ addressTemplateUrl: __classPrivateFieldGet(this, _SimpleSwapApi_instances, "m", _SimpleSwapApi_createAddressTemplateUrl).call(this, blockchainService, currency.addressExplorer),
255
+ txTemplateUrl: __classPrivateFieldGet(this, _SimpleSwapApi_instances, "m", _SimpleSwapApi_createTxTemplateUrl).call(this, blockchainService, currency.txExplorer),
256
+ blockchain,
257
+ };
258
+ };
@@ -0,0 +1,17 @@
1
+ import { Account, ISwapOrchestrator, TSwapOrchestratorEvents, TSwapResult, TSwapToken } from '@cityofzion/blockchain-service';
2
+ import TypedEmitter from 'typed-emitter';
3
+ import { TSimpleSwapOrchestratorInitParams } from './types';
4
+ export declare class SimpleSwapOrchestrator<BSName extends string = string> implements ISwapOrchestrator<BSName> {
5
+ #private;
6
+ eventEmitter: TypedEmitter<TSwapOrchestratorEvents<BSName>>;
7
+ constructor(params: TSimpleSwapOrchestratorInitParams<BSName>);
8
+ init(): Promise<void>;
9
+ setTokenToUse(token: TSwapToken<BSName> | null): Promise<void>;
10
+ setAccountToUse(account: Account<BSName> | null): Promise<void>;
11
+ setAmountToUse(amount: string | null): Promise<void>;
12
+ setTokenToReceive(token: TSwapToken<BSName> | null): Promise<void>;
13
+ setAddressToReceive(address: string | null): Promise<void>;
14
+ setExtraIdToReceive(extraIdToReceive: string | null): Promise<void>;
15
+ swap(): Promise<TSwapResult>;
16
+ calculateFee(): Promise<string>;
17
+ }