@pioneer-platform/pioneer 8.1.41 → 8.2.1

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 CHANGED
@@ -1,30 +1,43 @@
1
1
  "use strict";
2
2
  /*
3
3
 
4
- Pioneer Wallet v2
4
+ Pioneer API
5
+ A High Availability blockchain api
5
6
 
6
- Class based wallet development
7
+ Goals:
8
+ v1 compatibility with watchtower with 0 change
9
+ Multi-asset support
7
10
 
8
- */
9
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
12
- }) : (function(o, m, k, k2) {
13
- if (k2 === undefined) k2 = k;
14
- o[k2] = m[k];
15
- }));
16
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17
- Object.defineProperty(o, "default", { enumerable: true, value: v });
18
- }) : function(o, v) {
19
- o["default"] = v;
20
- });
21
- var __importStar = (this && this.__importStar) || function (mod) {
22
- if (mod && mod.__esModule) return mod;
23
- var result = {};
24
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
25
- __setModuleDefault(result, mod);
26
- return result;
27
- };
11
+ V2 goals:
12
+ Treat Xpubs as passwords
13
+ encrypt long term data storage
14
+ maintain hash table to detect and cache payments
15
+
16
+
17
+
18
+ getTransactions:
19
+
20
+ Data: example
21
+
22
+ { success: true,
23
+ pagination: { page: 1, total_objects: 88, total_pages: 9 },
24
+ data:
25
+ [ { txid:
26
+ '',
27
+ status: 'confirmed',
28
+ type: 'send',
29
+ amount: -78602,
30
+ date: '2019-05-10T21:01:23Z',
31
+ confirmations: 1055,
32
+ network: 'BTC',
33
+ xpub:
34
+ '' },
35
+ }
36
+ ]
37
+ }
38
+ }
39
+
40
+ */
28
41
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
29
42
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
30
43
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -40,7 +53,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
40
53
  function verb(n) { return function (v) { return step([n, v]); }; }
41
54
  function step(op) {
42
55
  if (f) throw new TypeError("Generator is already executing.");
43
- while (_) try {
56
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
44
57
  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;
45
58
  if (y = 0, t) op = [op[0] & 2, t.value];
46
59
  switch (op[0]) {
@@ -61,2862 +74,1143 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
61
74
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
62
75
  }
63
76
  };
64
- Object.defineProperty(exports, "__esModule", { value: true });
65
- var TAG = " | pioneer | ";
66
- var log = require("@pioneer-platform/loggerdog")();
67
- var cryptoTools = require('crypto');
68
- var ripemd160 = require("crypto-js/ripemd160");
69
- var CryptoJS = require("crypto-js");
70
- var sha256 = require("crypto-js/sha256");
71
- var bech32 = require("bech32");
72
- var bitcoin = require("bitcoinjs-lib");
73
- var ethUtils = require('ethereumjs-util');
74
- var prettyjson = require('prettyjson');
75
- var coinSelect = require('coinselect');
76
- var keccak256 = require('keccak256');
77
- var bchaddr = require('bchaddrjs');
78
- var ethCrypto = require("@pioneer-platform/eth-crypto");
79
- var coincap = require("@pioneer-platform/coincap");
80
- var _a = require('@pioneer-platform/pioneer-coins'), getPaths = _a.getPaths, nativeToBaseAmount = _a.nativeToBaseAmount, baseAmountToNative = _a.baseAmountToNative, UTXO_COINS = _a.UTXO_COINS, COIN_MAP_KEEPKEY_LONG = _a.COIN_MAP_KEEPKEY_LONG, COIN_MAP_LONG = _a.COIN_MAP_LONG, getNativeAssetForBlockchain = _a.getNativeAssetForBlockchain, addressNListToBIP32 = _a.addressNListToBIP32, bip32ToAddressNList = _a.bip32ToAddressNList, get_address_from_xpub = _a.get_address_from_xpub;
81
- //support
82
- var ethers_1 = require("ethers");
83
- var support = __importStar(require("./support"));
84
- var web3_utils_1 = require("web3-utils");
85
- var fiosdk_offline_1 = require("fiosdk-offline");
86
- var pioneer_types_1 = require("@pioneer-platform/pioneer-types");
87
- //Pioneer follows OpenAPI spec
88
- var network = require("@pioneer-platform/pioneer-client");
89
- //Highlander fork
90
- var hdwallet = require("@bithighlander/hdwallet-core");
91
- var pioneer = require("@bithighlander/hdwallet-native");
92
- // SS public TODO catch up public repo
93
- // const hdwallet = require("@shapeshiftoss/hdwallet-core")
94
- // const pioneer = require("@shapeshiftoss/hdwallet-native")
95
- //global
96
- var keyring = new hdwallet.Keyring();
97
- var HD_RUNE_KEYPATH = "m/44'/931'/0'/0/0";
98
- var RUNE_CHAIN = "thorchain";
99
- var RUNE_BASE = 100000000;
100
- var HD_ATOM_KEYPATH = "m/44'/118'/0'/0/0";
101
- var ATOM_CHAIN = "cosmoshub-4";
102
- var ATOM_BASE = 1000000;
103
- var GIG = 1000000000;
104
- var OSMO_CHAIN = "osmosis-1";
105
- function bech32ify(address, prefix) {
106
- var words = bech32.toWords(address);
107
- return bech32.encode(prefix, words);
77
+ var TAG = " | Pioneer | ";
78
+ var queue = require('@pioneer-platform/redis-queue');
79
+ var uuid = require('short-uuid');
80
+ var blocknative = require("@pioneer-platform/blocknative-client");
81
+ blocknative.init();
82
+ var blockbook = require('@pioneer-platform/blockbook');
83
+ // const foxitar = require("@pioneer-platform/foxitar-client")
84
+ var zapper = require("@pioneer-platform/zapper-client");
85
+ //@ts-ignore
86
+ var _a = require("@pioneer-platform/pioneer-caip"), shortListSymbolToCaip = _a.shortListSymbolToCaip, evmCaips = _a.evmCaips;
87
+ var networks = {
88
+ 'ETH': require('@pioneer-platform/eth-network'),
89
+ 'ATOM': require('@pioneer-platform/cosmos-network'),
90
+ 'OSMO': require('@pioneer-platform/osmosis-network'),
91
+ 'BNB': require('@pioneer-platform/binance-network'),
92
+ // 'EOS' : require('@pioneer-platform/eos-network'),
93
+ 'FIO': require('@pioneer-platform/fio-network'),
94
+ 'ANY': require('@pioneer-platform/utxo-network'),
95
+ 'RUNE': require('@pioneer-platform/thor-network'),
96
+ };
97
+ var _b = require('@pioneer-platform/cointools'), supportedBlockchains = _b.supportedBlockchains, supportedAssets = _b.supportedAssets, getPaths = _b.getPaths, get_address_from_xpub = _b.get_address_from_xpub, getNativeAssetForBlockchain = _b.getNativeAssetForBlockchain;
98
+ //const bcrypt = require('bcryptjs');
99
+ var numbro = require("numbro");
100
+ var log = require('@pioneer-platform/loggerdog')();
101
+ var _c = require('@pioneer-platform/default-redis'), subscriber = _c.subscriber, publisher = _c.publisher, redis = _c.redis, redisQueue = _c.redisQueue;
102
+ var connection = require("@pioneer-platform/default-mongo");
103
+ var wait = require('wait-promise');
104
+ var sleep = wait.sleep;
105
+ var usersDB = connection.get('users');
106
+ var txsDB = connection.get('transactions');
107
+ var pubkeysDB = connection.get('pubkeys');
108
+ var inputsDB = connection.get('unspent');
109
+ var assetsDB = connection.get('assets');
110
+ var nodesDB = connection.get('nodes');
111
+ usersDB.createIndex({ id: 1 }, { unique: true });
112
+ txsDB.createIndex({ txid: 1 }, { unique: true });
113
+ inputsDB.createIndex({ txid: 1 }, { unique: true });
114
+ pubkeysDB.createIndex({ pubkey: 1 }, { unique: true });
115
+ pubkeysDB.createIndex({ tags: 1 });
116
+ var BALANCE_ON_REGISTER = true;
117
+ var onStart = function () {
118
+ return __awaiter(this, void 0, void 0, function () {
119
+ var tag, servers, e_1;
120
+ return __generator(this, function (_a) {
121
+ switch (_a.label) {
122
+ case 0:
123
+ tag = TAG + " | onStart | ";
124
+ _a.label = 1;
125
+ case 1:
126
+ _a.trys.push([1, 5, , 6]);
127
+ log.info(tag, "starting...");
128
+ return [4 /*yield*/, nodesDB.find({ type: 'blockbook' })];
129
+ case 2:
130
+ servers = _a.sent();
131
+ log.info(tag, "servers: ", servers.length);
132
+ return [4 /*yield*/, blockbook.init(servers)
133
+ // networks.ANY.init('full')
134
+ ];
135
+ case 3:
136
+ _a.sent();
137
+ // networks.ANY.init('full')
138
+ return [4 /*yield*/, networks.ETH.init()];
139
+ case 4:
140
+ // networks.ANY.init('full')
141
+ _a.sent();
142
+ return [2 /*return*/, true];
143
+ case 5:
144
+ e_1 = _a.sent();
145
+ log.error(e_1);
146
+ return [3 /*break*/, 6];
147
+ case 6: return [2 /*return*/];
148
+ }
149
+ });
150
+ });
151
+ };
152
+ //onStart()
153
+ module.exports = {
154
+ init: function () {
155
+ return __awaiter(this, void 0, void 0, function () {
156
+ return __generator(this, function (_a) {
157
+ return [2 /*return*/, onStart()];
158
+ });
159
+ });
160
+ },
161
+ refresh: function (username) {
162
+ return __awaiter(this, void 0, void 0, function () {
163
+ return __generator(this, function (_a) {
164
+ return [2 /*return*/, get_and_rescan_pubkeys(username)];
165
+ });
166
+ });
167
+ },
168
+ register: function (username, pubkeys, context) {
169
+ return __awaiter(this, void 0, void 0, function () {
170
+ return __generator(this, function (_a) {
171
+ return [2 /*return*/, register_pubkeys(username, pubkeys, context)];
172
+ });
173
+ });
174
+ },
175
+ getPubkeys: function (username, context) {
176
+ return __awaiter(this, void 0, void 0, function () {
177
+ return __generator(this, function (_a) {
178
+ return [2 /*return*/, get_and_verify_pubkeys(username, context)];
179
+ });
180
+ });
181
+ },
182
+ update: function (username, xpubs, context) {
183
+ return __awaiter(this, void 0, void 0, function () {
184
+ return __generator(this, function (_a) {
185
+ return [2 /*return*/, update_pubkeys(username, xpubs, context)];
186
+ });
187
+ });
188
+ },
189
+ balances: function (pubkey) {
190
+ return __awaiter(this, void 0, void 0, function () {
191
+ return __generator(this, function (_a) {
192
+ return [2 /*return*/, get_pubkey_balances(pubkey)];
193
+ });
194
+ });
195
+ },
196
+ };
197
+ function getFromCache(key) {
198
+ return __awaiter(this, void 0, void 0, function () {
199
+ var data, err_1;
200
+ return __generator(this, function (_a) {
201
+ switch (_a.label) {
202
+ case 0:
203
+ _a.trys.push([0, 2, , 3]);
204
+ return [4 /*yield*/, redis.get(key)];
205
+ case 1:
206
+ data = _a.sent();
207
+ return [2 /*return*/, data];
208
+ case 2:
209
+ err_1 = _a.sent();
210
+ throw err_1;
211
+ case 3: return [2 /*return*/];
212
+ }
213
+ });
214
+ });
108
215
  }
109
- function createBech32Address(publicKey, prefix) {
110
- var message = CryptoJS.enc.Hex.parse(publicKey.toString("hex"));
111
- var hash = ripemd160(sha256(message)).toString();
112
- var address = Buffer.from(hash, "hex");
113
- var cosmosAddress = bech32ify(address, prefix);
114
- return cosmosAddress;
216
+ function setInCache(key, data, expiration) {
217
+ return __awaiter(this, void 0, void 0, function () {
218
+ var err_2;
219
+ return __generator(this, function (_a) {
220
+ switch (_a.label) {
221
+ case 0:
222
+ _a.trys.push([0, 2, , 3]);
223
+ return [4 /*yield*/, redis.setex(key, expiration, data)];
224
+ case 1:
225
+ _a.sent();
226
+ return [3 /*break*/, 3];
227
+ case 2:
228
+ err_2 = _a.sent();
229
+ throw err_2;
230
+ case 3: return [2 /*return*/];
231
+ }
232
+ });
233
+ });
115
234
  }
116
- module.exports = /** @class */ (function () {
117
- function wallet(type, config, isTestnet) {
118
- this.PUBLIC_WALLET = {};
119
- //if(config.isTestnet) isTestnet = true
120
- this.APPROVE_QUEUE = [];
121
- this.PENDING_QUEUE = [];
122
- this.isTestnet = false;
123
- if (config.pioneerApi) {
124
- this.offline = false;
125
- }
126
- else {
127
- this.offline = true;
128
- }
129
- this.mode = config.mode;
130
- this.context = config.context;
131
- this.queryKey = config.queryKey;
132
- this.username = config.username;
133
- this.pioneerApi = config.pioneerApi;
134
- this.blockchains = config.blockchains;
135
- this.WALLET_BALANCES = {};
136
- this.type = type;
137
- this.spec = config.spec;
138
- this.mnemonic = config.mnemonic;
139
- this.auth = config.auth;
140
- this.bip32ToAddressNList = function (path) {
141
- return bip32ToAddressNList(path);
142
- };
143
- this.setMnemonic = function () {
144
- return this.mnemonic;
145
- };
146
- this.init = function (wallet) {
147
- return __awaiter(this, void 0, void 0, function () {
148
- var tag, paths, _a, walletEth, pioneerAdapter, _b, _loop_1, this_1, i, _c, _loop_2, this_2, i, i, pubkey, nativeAsset, i, pubkey, _d, _e, _f, _g, userInfo, register, regsiterResponse, output, walletInfo, coins, i, coin, balance, e_1;
149
- return __generator(this, function (_h) {
150
- switch (_h.label) {
151
- case 0:
152
- tag = TAG + " | init_wallet | ";
153
- _h.label = 1;
154
- case 1:
155
- _h.trys.push([1, 21, , 22]);
156
- if (!this.blockchains && !wallet.blockchains)
157
- throw Error("102: Must Specify blockchain support! ");
158
- log.debug(tag, "checkpoint");
159
- paths = getPaths(this.blockchains);
160
- _a = +pioneer_types_1.HDWALLETS[this.type];
161
- switch (_a) {
162
- case pioneer_types_1.HDWALLETS.pioneer: return [3 /*break*/, 2];
163
- case pioneer_types_1.HDWALLETS.keepkey: return [3 /*break*/, 8];
164
- case pioneer_types_1.HDWALLETS.metamask: return [3 /*break*/, 9];
235
+ var get_pubkey_balances = function (pubkey) {
236
+ var _a, _b;
237
+ return __awaiter(this, void 0, void 0, function () {
238
+ var tag, output, balances_1, nfts, positions, cacheKey, cachedData, balance, _c, cacheKeyZapper, cachedDataZapper, zapperInfo, cacheKeyAllPioneers, cachedAllPioneers, allPioneers, isPioneer, updatedUsername, pioneerImage, updatedUsername2, cacheKeyBlockbookInfo, cachedBlockbookInfo, blockbookInfo, cacheKeyNetwork, cachedDataNetwork, balanceNetwork, pubkeyInfo, saveActions, _loop_1, i, _loop_2, i, updateSuccess, e_2;
239
+ return __generator(this, function (_d) {
240
+ switch (_d.label) {
241
+ case 0:
242
+ tag = TAG + " | get_pubkey_balances | ";
243
+ _d.label = 1;
244
+ case 1:
245
+ _d.trys.push([1, 41, , 42]);
246
+ output = {};
247
+ if (!pubkey.symbol && pubkey.asset)
248
+ pubkey.symbol = pubkey.asset;
249
+ if (!pubkey.type && pubkey.address)
250
+ pubkey.type = "address";
251
+ if (!pubkey.context)
252
+ throw Error("100: invalid pubkey! missing context");
253
+ if (!pubkey.symbol)
254
+ throw Error("101: invalid pubkey! missing symbol");
255
+ if (!pubkey.username)
256
+ throw Error("102: invalid pubkey! missing username");
257
+ if (!pubkey.pubkey)
258
+ throw Error("103: invalid pubkey! missing pubkey");
259
+ if (!pubkey.type)
260
+ throw Error("105: invalid pubkey! missing type");
261
+ // if(!pubkey.queueId) throw Error("106: invalid pubkey! missing queueId");
262
+ if (pubkey.type !== 'address' && pubkey.type !== 'xpub' && pubkey.type !== 'zpub' && pubkey.type !== 'contract')
263
+ throw Error("Unknown type! " + pubkey.type);
264
+ balances_1 = [];
265
+ nfts = [];
266
+ positions = [];
267
+ log.info(tag, " scanning pubkey: ", pubkey.pubkey);
268
+ if (!(pubkey.type === "xpub" || pubkey.type === "zpub")) return [3 /*break*/, 7];
269
+ cacheKey = "balances:blockbook:getBalanceByXpub:".concat(pubkey.symbol, ":").concat(pubkey.pubkey);
270
+ return [4 /*yield*/, getFromCache(cacheKey)];
271
+ case 2:
272
+ cachedData = _d.sent();
273
+ balance = void 0;
274
+ if (!cachedData) return [3 /*break*/, 3];
275
+ balance = JSON.parse(cachedData);
276
+ return [3 /*break*/, 6];
277
+ case 3: return [4 /*yield*/, blockbook.getBalanceByXpub(pubkey.symbol, pubkey.pubkey)];
278
+ case 4:
279
+ balance = _d.sent();
280
+ log.debug(tag, pubkey.username + " Balance (" + pubkey.symbol + "): ", balance);
281
+ return [4 /*yield*/, setInCache(cacheKey, JSON.stringify(balance), 60 * 60 * 1)];
282
+ case 5:
283
+ _d.sent();
284
+ _d.label = 6;
285
+ case 6:
286
+ //
287
+ // Update balance
288
+ balances_1.push({
289
+ network: pubkey.symbol,
290
+ blockchainCaip: shortListSymbolToCaip(pubkey.symbol),
291
+ assetCaip: shortListSymbolToCaip(pubkey.symbol),
292
+ asset: pubkey.symbol,
293
+ symbol: pubkey.symbol,
294
+ pubkey: pubkey.pubkey,
295
+ context: pubkey.context,
296
+ isToken: false,
297
+ lastUpdated: new Date().getTime(),
298
+ balance: balance
299
+ });
300
+ return [3 /*break*/, 33];
301
+ case 7:
302
+ if (!(pubkey.type === "address")) return [3 /*break*/, 33];
303
+ _c = pubkey.symbol;
304
+ switch (_c) {
305
+ case "ETH": return [3 /*break*/, 8];
306
+ }
307
+ return [3 /*break*/, 27];
308
+ case 8:
309
+ cacheKeyZapper = "balances:zapperInfo:getPortfolio:".concat(pubkey.pubkey);
310
+ return [4 /*yield*/, getFromCache(cacheKeyZapper)];
311
+ case 9:
312
+ cachedDataZapper = _d.sent();
313
+ zapperInfo = void 0;
314
+ if (!cachedDataZapper) return [3 /*break*/, 10];
315
+ zapperInfo = JSON.parse(cachedDataZapper);
316
+ return [3 /*break*/, 13];
317
+ case 10: return [4 /*yield*/, zapper.getPortfolio(pubkey.pubkey)];
318
+ case 11:
319
+ zapperInfo = _d.sent();
320
+ log.debug(tag, "zapperInfo: ", zapperInfo);
321
+ return [4 /*yield*/, setInCache(cacheKeyZapper, JSON.stringify(zapperInfo), 60 * 60 * 1)];
322
+ case 12:
323
+ _d.sent();
324
+ _d.label = 13;
325
+ case 13:
326
+ if (((_a = zapperInfo === null || zapperInfo === void 0 ? void 0 : zapperInfo.tokens) === null || _a === void 0 ? void 0 : _a.length) > 0) {
327
+ zapperInfo.tokens.forEach(function (token) {
328
+ var balanceInfo = token.token;
329
+ balanceInfo.network = token.network;
330
+ //get caip for network
331
+ balanceInfo.blockchainCaip = token.caip || 'caip:placeholder:' + token.network;
332
+ balanceInfo.asset = token.token.symbol;
333
+ balanceInfo.symbol = token.token.symbol;
334
+ balanceInfo.pubkey = pubkey.pubkey;
335
+ balanceInfo.context = pubkey.context;
336
+ balanceInfo.contract = token.token.address;
337
+ balanceInfo.source = 'zapper';
338
+ if (token.token.address !== '0x0000000000000000000000000000000000000000') {
339
+ balanceInfo.isToken = true;
340
+ balanceInfo.protocal = 'erc20';
165
341
  }
166
- return [3 /*break*/, 10];
167
- case 2:
168
- if (!config.mnemonic)
169
- throw Error("103: mnemonic required!");
170
- if (!config.username)
171
- throw Error("104: username required!");
172
- if (!(!this.context && config.mnemonic)) return [3 /*break*/, 4];
173
- return [4 /*yield*/, ethCrypto.generateWalletFromSeed(config.mnemonic)];
174
- case 3:
175
- walletEth = _h.sent();
176
- this.context = walletEth.masterAddress + ".wallet.json";
177
- _h.label = 4;
178
- case 4:
179
- if (!this.context)
180
- throw Error("102: unable to determine correct context!");
181
- pioneerAdapter = pioneer.NativeAdapter.useKeyring(keyring);
182
- if (!config.mnemonic && !wallet && !config.context)
183
- throw Error("102: mnemonic or wallet file or context required! ");
184
- if (config.mnemonic && config.wallet)
185
- throw Error("103: wallet collision! invalid config! ");
186
- _b = this;
187
- return [4 /*yield*/, pioneerAdapter.pairDevice(config.username)];
188
- case 5:
189
- _b.WALLET = _h.sent();
190
- if (!this.WALLET)
191
- throw Error("Failed to init wallet!");
192
- return [4 /*yield*/, this.WALLET.loadDevice({ mnemonic: config.mnemonic })
193
- //verify paths for each enabled blockchain
194
- ];
195
- case 6:
196
- _h.sent();
197
- _loop_1 = function (i) {
198
- var blockchain = this_1.blockchains[i];
199
- log.debug(tag, "blockchain: ", blockchain);
200
- //find blockchain in path
201
- var isFound = paths.find(function (path) {
202
- return path.blockchain === blockchain;
203
- });
204
- if (!isFound) {
205
- throw Error("Failed to find path for blockchain: " + blockchain);
342
+ balanceInfo.lastUpdated = new Date().getTime();
343
+ balanceInfo.balance = token.token.balance.toString();
344
+ balances_1.push(balanceInfo);
345
+ });
346
+ }
347
+ if (((_b = zapperInfo === null || zapperInfo === void 0 ? void 0 : zapperInfo.nfts) === null || _b === void 0 ? void 0 : _b.length) > 0) {
348
+ nfts = zapperInfo.nfts;
349
+ }
350
+ cacheKeyAllPioneers = 'balances:getAllPioneers:ETH';
351
+ return [4 /*yield*/, getFromCache(cacheKeyAllPioneers)];
352
+ case 14:
353
+ cachedAllPioneers = _d.sent();
354
+ allPioneers = void 0;
355
+ if (!cachedAllPioneers) return [3 /*break*/, 15];
356
+ allPioneers = JSON.parse(cachedAllPioneers);
357
+ return [3 /*break*/, 18];
358
+ case 15: return [4 /*yield*/, networks['ETH'].getAllPioneers()];
359
+ case 16:
360
+ allPioneers = _d.sent();
361
+ return [4 /*yield*/, setInCache(cacheKeyAllPioneers, JSON.stringify(allPioneers), 60 * 60 * 1)];
362
+ case 17:
363
+ _d.sent();
364
+ _d.label = 18;
365
+ case 18:
366
+ log.debug(tag, "allPioneers: ", allPioneers);
367
+ if (!allPioneers || allPioneers.owners)
368
+ allPioneers = { owners: [], images: [] };
369
+ isPioneer = allPioneers.owners.includes(pubkey.pubkey.toLowerCase());
370
+ if (!isPioneer) return [3 /*break*/, 21];
371
+ log.debug("Pioneer detected!");
372
+ return [4 /*yield*/, usersDB.update({ username: pubkey.username }, { $set: { isPioneer: true } }, { multi: true })];
373
+ case 19:
374
+ updatedUsername = _d.sent();
375
+ log.debug("Updated username PIONEER: ", updatedUsername);
376
+ pioneerImage = allPioneers.images.find(function (image) { return image.address.toLowerCase() === pubkey.pubkey.toLowerCase(); });
377
+ if (!pioneerImage) return [3 /*break*/, 21];
378
+ return [4 /*yield*/, usersDB.update({ username: pubkey.username }, { $set: { pioneerImage: pioneerImage.image } }, { multi: true })];
379
+ case 20:
380
+ updatedUsername2 = _d.sent();
381
+ log.debug("updatedUsername2 PIONEER: ", updatedUsername2);
382
+ nfts.push({
383
+ name: "Pioneer",
384
+ description: "Pioneer",
385
+ source: "pioneer",
386
+ blockchainCaip: 'eip155:1/slip44:60',
387
+ pubkey: pubkey.pubkey,
388
+ context: pubkey.context,
389
+ number: allPioneers.owners.indexOf(pubkey.pubkey.toLowerCase()),
390
+ image: pioneerImage.image
391
+ });
392
+ _d.label = 21;
393
+ case 21:
394
+ cacheKeyBlockbookInfo = "balances:blockbook:getAddressInfo:ETH:".concat(pubkey.pubkey);
395
+ return [4 /*yield*/, getFromCache(cacheKeyBlockbookInfo)];
396
+ case 22:
397
+ cachedBlockbookInfo = _d.sent();
398
+ blockbookInfo = void 0;
399
+ if (!cachedBlockbookInfo) return [3 /*break*/, 23];
400
+ blockbookInfo = JSON.parse(cachedBlockbookInfo);
401
+ return [3 /*break*/, 26];
402
+ case 23: return [4 /*yield*/, blockbook.getAddressInfo('ETH', pubkey.pubkey)];
403
+ case 24:
404
+ blockbookInfo = _d.sent();
405
+ return [4 /*yield*/, setInCache(cacheKeyBlockbookInfo, JSON.stringify(blockbookInfo), 60 * 60 * 1)];
406
+ case 25:
407
+ _d.sent();
408
+ _d.label = 26;
409
+ case 26:
410
+ log.debug(tag, 'blockbookInfo: ', blockbookInfo);
411
+ if (blockbookInfo === null || blockbookInfo === void 0 ? void 0 : blockbookInfo.tokens) {
412
+ blockbookInfo.tokens.forEach(function (tokenInfo) {
413
+ if (tokenInfo.symbol && tokenInfo.symbol !== 'ETH') {
414
+ var balanceInfo = {
415
+ network: "ETH",
416
+ blockchainCaip: 'eip155:1/slip44:60',
417
+ assetCaip: 'eip155:1/slip44:60:' + tokenInfo.contract,
418
+ type: tokenInfo.type,
419
+ asset: tokenInfo.symbol,
420
+ symbol: tokenInfo.symbol,
421
+ name: tokenInfo.name,
422
+ contract: tokenInfo.contract,
423
+ pubkey: pubkey.pubkey,
424
+ context: pubkey.context,
425
+ image: "https://pioneers.dev/coins/ethereum.png",
426
+ isToken: true,
427
+ protocal: 'erc20',
428
+ lastUpdated: new Date().getTime(),
429
+ decimals: tokenInfo.decimals,
430
+ balance: tokenInfo.balance / Math.pow(10, Number(tokenInfo.decimals)),
431
+ balanceNative: tokenInfo.balance / Math.pow(10, Number(tokenInfo.decimals)),
432
+ source: "blockbook"
433
+ };
434
+ if (tokenInfo.holdersCount === 1) {
435
+ balanceInfo.nft = true;
206
436
  }
207
- };
208
- this_1 = this;
209
- //verify paths for each enabled blockchain
210
- for (i = 0; i < this.blockchains.length; i++) {
211
- _loop_1(i);
212
- }
213
- log.debug(tag, "Checkpoint valid paths ** ");
214
- _c = this;
215
- return [4 /*yield*/, this.WALLET.getPublicKeys(paths)];
216
- case 7:
217
- _c.pubkeys = _h.sent();
218
- log.debug("pubkeys ", JSON.stringify(this.pubkeys));
219
- _loop_2 = function (i) {
220
- var blockchain = this_2.blockchains[i];
221
- //find blockchain in path
222
- var isFound = this_2.pubkeys.find(function (pubkey) {
223
- return pubkey.blockchain == blockchain;
224
- });
225
- if (!isFound) {
226
- throw Error("Failed to find path for blockchain: " + blockchain);
437
+ if (balanceInfo.balance > 0) {
438
+ balances_1.push(balanceInfo);
227
439
  }
228
- };
229
- this_2 = this;
230
- //verify pubkey for each blockchain
231
- for (i = 0; i < this.blockchains.length; i++) {
232
- _loop_2(i);
233
440
  }
234
- for (i = 0; i < this.pubkeys.length; i++) {
235
- pubkey = this.pubkeys[i];
236
- log.debug(tag, "pubkey: ", pubkey);
237
- if (!pubkey)
238
- throw Error("empty pubkey!");
239
- if (!pubkey.symbol) {
240
- nativeAsset = getNativeAssetForBlockchain(pubkey.blockchain);
241
- if (!nativeAsset)
242
- throw Error("102: blockchain not supported by coins module! " + pubkey.blockchain);
243
- pubkey.symbol = nativeAsset;
244
- }
245
- this.PUBLIC_WALLET[pubkey.symbol] = pubkey;
246
- if (!this.masters)
247
- this.masters = {};
248
- this.masters[pubkey.symbol] = pubkey.master;
441
+ });
442
+ }
443
+ return [3 /*break*/, 33];
444
+ case 27:
445
+ cacheKeyNetwork = "balances:".concat(pubkey.symbol, ":getBalance:").concat(pubkey.pubkey);
446
+ return [4 /*yield*/, getFromCache(cacheKeyNetwork)];
447
+ case 28:
448
+ cachedDataNetwork = _d.sent();
449
+ balanceNetwork = void 0;
450
+ if (!cachedDataNetwork) return [3 /*break*/, 29];
451
+ balanceNetwork = JSON.parse(cachedDataNetwork);
452
+ return [3 /*break*/, 32];
453
+ case 29: return [4 /*yield*/, networks[pubkey.symbol].getBalance(pubkey.pubkey)];
454
+ case 30:
455
+ balanceNetwork = _d.sent();
456
+ log.debug(tag, "balance: ", balanceNetwork);
457
+ return [4 /*yield*/, setInCache(cacheKeyNetwork, JSON.stringify(balanceNetwork), 60 * 60 * 1)];
458
+ case 31:
459
+ _d.sent();
460
+ _d.label = 32;
461
+ case 32:
462
+ if (!balanceNetwork)
463
+ balanceNetwork = 0;
464
+ balances_1.push({
465
+ network: pubkey.symbol,
466
+ asset: pubkey.symbol,
467
+ symbol: pubkey.symbol,
468
+ blockchainCaip: shortListSymbolToCaip[pubkey.symbol],
469
+ assetCaip: shortListSymbolToCaip[pubkey.symbol],
470
+ isToken: false,
471
+ lastUpdated: new Date().getTime(),
472
+ balance: balanceNetwork,
473
+ source: "pioneer-network-" + pubkey.symbol
474
+ });
475
+ return [3 /*break*/, 33];
476
+ case 33: return [4 /*yield*/, pubkeysDB.findOne({ pubkey: pubkey.pubkey })];
477
+ case 34:
478
+ pubkeyInfo = _d.sent();
479
+ if (!pubkeyInfo || !pubkeyInfo.balances) {
480
+ pubkeyInfo = {
481
+ balances: []
482
+ };
483
+ }
484
+ if (!pubkeyInfo.nfts)
485
+ pubkeyInfo.nfts = [];
486
+ log.debug(tag, "pubkeyInfo: ", pubkeyInfo);
487
+ log.debug(tag, "pubkeyInfo.balances: ", pubkeyInfo.balances.length);
488
+ log.debug(tag, "nfts: ", pubkeyInfo.nfts.length);
489
+ log.debug(tag, "balances: ", balances_1);
490
+ log.debug(tag, "balances: ", balances_1.length);
491
+ saveActions = [];
492
+ _loop_1 = function (i) {
493
+ var balance, balanceIndex, assetInfo;
494
+ var _e;
495
+ return __generator(this, function (_f) {
496
+ switch (_f.label) {
497
+ case 0:
498
+ balance = balances_1[i];
499
+ balanceIndex = pubkeyInfo.balances.findIndex(function (e) { return e.symbol === balance.symbol; });
500
+ return [4 /*yield*/, assetsDB.findOne({ symbol: balance.symbol })];
501
+ case 1:
502
+ assetInfo = _f.sent();
503
+ log.debug(tag, "assetInfo: ", assetInfo);
504
+ if (assetInfo) {
505
+ balance.caip = assetInfo.caip;
506
+ balance.image = assetInfo.image;
507
+ balance.assetCaip = assetInfo.caip;
508
+ balance.description = assetInfo.description;
509
+ balance.website = assetInfo.website;
510
+ balance.explorer = assetInfo.explorer;
511
+ }
512
+ if (balanceIndex !== -1 && pubkeyInfo.balances[balanceIndex].balance !== balance.balance) {
513
+ saveActions.push({
514
+ updateOne: {
515
+ filter: { pubkey: pubkey.pubkey },
516
+ update: {
517
+ $set: (_e = {}, _e["balances.".concat(balanceIndex)] = balance, _e),
518
+ },
519
+ },
520
+ });
521
+ }
522
+ else {
523
+ log.debug(tag, pubkey.context + ": balance not changed! ", balance.symbol);
524
+ }
525
+ return [2 /*return*/];
249
526
  }
250
- return [3 /*break*/, 11];
251
- case 8:
252
- log.debug(tag, " Keepkey mode! ");
253
- log.debug(tag, "**** wallet: ", wallet);
254
- if (!config.wallet)
255
- throw Error("102: Config is missing watch wallet!");
256
- if (!config.wallet.WALLET_PUBLIC)
257
- throw Error("103: Config watch wallet missing WALLET_PUBLIC!");
258
- if (!config.wallet.pubkeys)
259
- throw Error("104: Config watch wallet missing pubkeys!");
260
- if (!wallet.features.deviceId)
261
- throw Error("105: invalid wallet! missing wallet.features.deviceId");
262
- this.context = wallet.features.deviceId + ".wallet.json";
263
- //load wallet from keepkey
264
- this.WALLET = wallet;
265
- log.debug(tag, "IN paths: ", paths);
266
- //TODO why this no worky
267
- // this.pubkeys = await this.WALLET.getPublicKeys(paths)
268
- this.pubkeys = config.wallet.pubkeys;
269
- log.debug("pubkeys ", JSON.stringify(this.pubkeys));
270
- log.debug("pubkeys.length ", this.pubkeys.length);
271
- log.debug("paths.length ", paths.length);
272
- //if paths !== pubkeys throw? missing symbol?
273
- for (i = 0; i < this.pubkeys.length; i++) {
274
- pubkey = this.pubkeys[i];
275
- log.debug(tag, "pubkey: ", pubkey);
276
- if (!pubkey)
277
- throw Error("empty pubkey!");
278
- if (!pubkey.symbol) {
279
- log.debug("pubkey: ", pubkey);
280
- throw Error("Invalid pubkey!");
527
+ });
528
+ };
529
+ i = 0;
530
+ _d.label = 35;
531
+ case 35:
532
+ if (!(i < balances_1.length)) return [3 /*break*/, 38];
533
+ return [5 /*yield**/, _loop_1(i)];
534
+ case 36:
535
+ _d.sent();
536
+ _d.label = 37;
537
+ case 37:
538
+ i++;
539
+ return [3 /*break*/, 35];
540
+ case 38:
541
+ _loop_2 = function (i) {
542
+ var nft = nfts[i];
543
+ log.debug(tag, "pubkeyInfo.nfts: ", pubkeyInfo.nfts.length);
544
+ var existingNft = pubkeyInfo.nfts.find(function (e) { return e.name === nft.name; });
545
+ if (!existingNft) {
546
+ saveActions.push({
547
+ updateOne: {
548
+ filter: { pubkey: pubkey.pubkey },
549
+ update: {
550
+ $addToSet: { nfts: nft }
551
+ }
281
552
  }
282
- this.PUBLIC_WALLET[pubkey.symbol] = pubkey;
283
- }
284
- log.debug("this.PUBLIC_WALLET", this.PUBLIC_WALLET);
285
- return [3 /*break*/, 11];
286
- case 9:
287
- log.debug(tag, " metamask mode! ");
288
- if (!config.wallet)
289
- throw Error("Config is missing watch wallet!");
290
- if (!config.wallet.WALLET_PUBLIC)
291
- throw Error("Config watch wallet missing WALLET_PUBLIC!");
292
- this.PUBLIC_WALLET = config.wallet.WALLET_PUBLIC;
293
- if (!config.pubkeys)
294
- throw Error("Config watch wallet missing pubkeys!");
295
- this.pubkeys = config.pubkeys;
296
- return [3 /*break*/, 11];
297
- case 10: throw Error("108: WALLET not yet supported! " + type + " valid: " + pioneer_types_1.HDWALLETS);
298
- case 11:
299
- if (!this.pubkeys)
300
- throw Error("103: failed to init wallet! missing pubkeys!");
301
- if (!this.pioneerApi) return [3 /*break*/, 19];
302
- if (!this.spec)
303
- throw Error("102: Api spec required! ");
304
- if (!this.queryKey)
305
- throw Error("102: queryKey required! ");
306
- this.pioneer = new network(config.spec, {
307
- queryKey: config.queryKey
308
553
  });
309
- _d = this;
310
- return [4 /*yield*/, this.pioneer.init(config.spec, {
311
- queryKey: config.queryKey
312
- })];
313
- case 12:
314
- _d.pioneerClient = _h.sent();
315
- _f = (_e = log).debug;
316
- _g = ["baseUrl: "];
317
- return [4 /*yield*/, this.pioneerClient.getBaseURL()];
318
- case 13:
319
- _f.apply(_e, _g.concat([_h.sent()]));
320
- return [4 /*yield*/, this.pioneerClient.instance.User()];
321
- case 14:
322
- userInfo = _h.sent();
323
- userInfo = userInfo.data;
324
- log.debug(tag, "userInfo: ", userInfo);
325
- if (!(!userInfo || !userInfo.success)) return [3 /*break*/, 16];
326
- log.debug(tag, "registering new user! ");
327
- register = {
328
- username: this.username,
329
- blockchains: this.blockchains,
330
- context: this.context,
331
- walletDescription: {
332
- context: this.context,
333
- type: this.type
334
- },
335
- data: {
336
- pubkeys: this.pubkeys
337
- },
338
- queryKey: this.queryKey,
339
- auth: this.auth,
340
- provider: 'bitcoin'
341
- };
342
- log.debug("registerBody: ", register);
343
- log.debug("this.pioneerClient: ", this.pioneerClient);
344
- if (!register.context)
345
- throw Error("102: missing context Can not register!");
346
- return [4 /*yield*/, this.pioneerClient.instance.Register(null, register)];
347
- case 15:
348
- regsiterResponse = _h.sent();
349
- if (regsiterResponse.code === 104) {
350
- //TODO request change of queryKey
554
+ }
555
+ };
556
+ for (i = 0; i < nfts.length; i++) {
557
+ _loop_2(i);
558
+ }
559
+ if (!(saveActions.length > 0)) return [3 /*break*/, 40];
560
+ return [4 /*yield*/, pubkeysDB.bulkWrite(saveActions, { ordered: false })];
561
+ case 39:
562
+ updateSuccess = _d.sent();
563
+ log.info(tag, "updateSuccess: ", updateSuccess);
564
+ output.dbUpdate = updateSuccess;
565
+ _d.label = 40;
566
+ case 40:
567
+ //@TODO save transactions
568
+ // Build output
569
+ output.pubkeys = [pubkeyInfo];
570
+ output.balances = balances_1;
571
+ output.nfts = nfts;
572
+ output.success = true;
573
+ return [2 /*return*/, output];
574
+ case 41:
575
+ e_2 = _d.sent();
576
+ console.error(tag, "e: ", e_2);
577
+ throw e_2;
578
+ case 42: return [2 /*return*/];
579
+ }
580
+ });
581
+ });
582
+ };
583
+ var get_and_rescan_pubkeys = function (username) {
584
+ return __awaiter(this, void 0, void 0, function () {
585
+ var tag, pubkeysMongo, userInfo, blockchains, pubkeys, masters, i, pubkeyInfo, _loop_3, j, e_3;
586
+ return __generator(this, function (_a) {
587
+ switch (_a.label) {
588
+ case 0:
589
+ tag = TAG + " | get_and_rescan_pubkeys | ";
590
+ _a.label = 1;
591
+ case 1:
592
+ _a.trys.push([1, 4, , 5]);
593
+ return [4 /*yield*/, pubkeysDB.find({ tags: { $all: [username] } })];
594
+ case 2:
595
+ pubkeysMongo = _a.sent();
596
+ log.debug(tag, "pubkeysMongo: ", pubkeysMongo.length);
597
+ return [4 /*yield*/, usersDB.findOne({ username: username })];
598
+ case 3:
599
+ userInfo = _a.sent();
600
+ if (!userInfo)
601
+ throw Error("get_and_rescan_pubkeys user not found!");
602
+ log.debug(tag, "userInfo: ", userInfo);
603
+ blockchains = userInfo.blockchains;
604
+ if (!blockchains)
605
+ blockchains = [];
606
+ pubkeys = [];
607
+ masters = {};
608
+ for (i = 0; i < pubkeysMongo.length; i++) {
609
+ pubkeyInfo = pubkeysMongo[i];
610
+ delete pubkeyInfo._id;
611
+ _loop_3 = function (j) {
612
+ var context = userInfo.wallets[i];
613
+ if (pubkeyInfo.type === 'zpub') {
614
+ //if context found in tags
615
+ var match = pubkeyInfo.tags.filter(function (e) { return e === context; });
616
+ if (match.length > 0) {
617
+ register_zpub(username, pubkeyInfo, context);
618
+ }
351
619
  }
352
- log.debug("registerResponse: ", regsiterResponse);
353
- return [3 /*break*/, 17];
354
- case 16:
355
- //user found! syncronize
356
- if (!userInfo.blockchains)
357
- throw Error("104: invalid user!");
358
- log.debug(tag, "userInfo: ", userInfo);
359
- log.debug(tag, "userInfo: ", userInfo.blockchains);
360
- log.debug(tag, "userInfo: ", userInfo.blockchains.length);
361
- log.debug(tag, "blockchains: ", this.blockchains);
362
- log.debug(tag, "blockchains: ", this.blockchains.length);
363
- //count blockchains
364
- //count pubkeys
365
- //if missing register key
366
- //if incomplete
367
- //register missing pubkeys
368
- if (userInfo.blockchains.length !== this.blockchains.length) {
369
- log.error(tag, "Pubkeys OUT OF SYNC!");
370
- log.error(tag, "blockchains remote: ", userInfo.blockchains);
371
- log.error(tag, "blockchains configured: ", this.blockchains);
372
- //TODO register pubkey 1 by 1 with async on
373
- //if failure give reason
620
+ else if (pubkeyInfo.type === 'xpub') {
621
+ var match = pubkeyInfo.tags.filter(function (e) { return e === context; });
622
+ if (match.length > 0) {
623
+ register_xpub(username, pubkeyInfo, context);
624
+ }
374
625
  }
375
- _h.label = 17;
376
- case 17:
377
- output = {};
378
- log.debug(tag, "getting info on context: ", this.context);
379
- return [4 /*yield*/, this.getInfo(this.context)];
380
- case 18:
381
- walletInfo = _h.sent();
382
- log.debug(tag, "walletInfo: ", walletInfo);
383
- //validate info
384
- log.debug("walletInfo: ", walletInfo);
385
- if (walletInfo && walletInfo.balances) {
386
- coins = Object.keys(walletInfo.balances);
387
- for (i = 0; i < coins.length; i++) {
388
- coin = coins[i];
389
- balance = walletInfo.balances[coin];
390
- this.WALLET_BALANCES[coin] = balance;
626
+ else if (pubkeyInfo.type === 'address') {
627
+ var match = pubkeyInfo.tags.filter(function (e) { return e === context; });
628
+ if (match.length > 0) {
629
+ register_address(username, pubkeyInfo, context);
391
630
  }
392
631
  }
393
- if (walletInfo && walletInfo.balances)
394
- this.WALLET_BALANCES = walletInfo.balances;
395
- return [2 /*return*/, walletInfo];
396
- case 19:
397
- log.debug(tag, "Offline mode!");
398
- //log.debug(tag,"this: ",this)
399
- return [2 /*return*/, {
400
- isTestnet: this.isTestnet,
401
- context: this.context,
402
- username: this.username,
403
- blockchains: this.blockchains,
404
- wallet: this.PUBLIC_WALLET,
405
- paths: this.paths
406
- }];
407
- case 20: return [3 /*break*/, 22];
408
- case 21:
409
- e_1 = _h.sent();
410
- log.error(tag, e_1);
411
- throw e_1;
412
- case 22: return [2 /*return*/];
413
- }
414
- });
415
- });
416
- };
417
- this.paths = function (format) {
418
- var tag = TAG + " | get_paths | ";
419
- try {
420
- var output = [];
421
- if (format === 'keepkey') {
422
- var paths = getPaths(this.blockchains);
423
- for (var i = 0; i < paths.length; i++) {
424
- var path = paths[i];
425
- var pathForKeepkey = {};
426
- //send coin as bitcoin
427
- pathForKeepkey.symbol = path.symbol;
428
- pathForKeepkey.addressNList = path.addressNList;
429
- //why
430
- pathForKeepkey.coin = 'Bitcoin';
431
- pathForKeepkey.script_type = 'p2pkh';
432
- output.push(pathForKeepkey);
632
+ };
633
+ //for each wallet by user
634
+ for (j = 0; j < userInfo.wallets.length; j++) {
635
+ _loop_3(j);
636
+ }
433
637
  }
434
- }
435
- else {
436
- var paths = getPaths(this.blockchains);
437
- output = paths;
438
- }
439
- return output;
440
- }
441
- catch (e) {
442
- log.error(tag, "e: ", e);
638
+ return [2 /*return*/, { pubkeys: pubkeys, masters: masters }];
639
+ case 4:
640
+ e_3 = _a.sent();
641
+ console.error(tag, "e: ", e_3);
642
+ throw e_3;
643
+ case 5: return [2 /*return*/];
443
644
  }
444
- };
445
- this.forget = function () {
446
- return __awaiter(this, void 0, void 0, function () {
447
- var resp;
448
- return __generator(this, function (_a) {
449
- switch (_a.label) {
450
- case 0: return [4 /*yield*/, this.pioneerClient.instance.Forget()];
451
- case 1:
452
- resp = _a.sent();
453
- return [2 /*return*/, resp.data];
454
- }
455
- });
456
- });
457
- };
458
- this.getInfo = function (context) {
459
- return __awaiter(this, void 0, void 0, function () {
460
- var tag, walletInfo, e_2;
461
- return __generator(this, function (_a) {
462
- switch (_a.label) {
463
- case 0:
464
- tag = TAG + " | getInfo | ";
465
- _a.label = 1;
466
- case 1:
467
- _a.trys.push([1, 5, , 6]);
468
- walletInfo = {};
469
- if (!!this.offline) return [3 /*break*/, 3];
470
- return [4 /*yield*/, this.pioneerClient.instance.Info(context)];
471
- case 2:
472
- //query api
473
- walletInfo = _a.sent();
474
- log.debug(tag, "walletInfo: ", walletInfo);
475
- walletInfo = walletInfo.data;
476
- walletInfo.pioneerApi = true;
477
- return [3 /*break*/, 4];
478
- case 3:
479
- walletInfo.pioneerApi = false;
480
- walletInfo.pubkeys = this.pubkeys;
481
- walletInfo.wallet = this.PUBLIC_WALLET;
482
- walletInfo.paths = this.paths;
483
- walletInfo.masters = this.masters;
484
- _a.label = 4;
485
- case 4: return [2 /*return*/, walletInfo];
486
- case 5:
487
- e_2 = _a.sent();
488
- log.error(tag, "e: ", e_2);
489
- return [3 /*break*/, 6];
490
- case 6: return [2 /*return*/];
645
+ });
646
+ });
647
+ };
648
+ var get_and_verify_pubkeys = function (username, context) {
649
+ return __awaiter(this, void 0, void 0, function () {
650
+ var tag, pubkeysMongo, userInfo, blockchains, pubkeys, allBalances, synced, i, pubkeyInfo, balances, isSynced, i, blockchain, e_4;
651
+ return __generator(this, function (_a) {
652
+ switch (_a.label) {
653
+ case 0:
654
+ tag = TAG + " | get_and_verify_pubkeys | ";
655
+ _a.label = 1;
656
+ case 1:
657
+ _a.trys.push([1, 10, , 11]);
658
+ //get pubkeys from mongo with context tagged
659
+ if (!context)
660
+ context = username;
661
+ return [4 /*yield*/, pubkeysDB.find({ tags: { $all: [context] } })];
662
+ case 2:
663
+ pubkeysMongo = _a.sent();
664
+ log.debug(tag, "pubkeysMongo: ", pubkeysMongo.length);
665
+ return [4 /*yield*/, usersDB.findOne({ username: username })];
666
+ case 3:
667
+ userInfo = _a.sent();
668
+ if (!userInfo)
669
+ throw Error("get_and_verify_pubkeys User not found!");
670
+ log.debug(tag, "userInfo: ", userInfo);
671
+ blockchains = userInfo.blockchains;
672
+ log.debug(tag, "userInfo: ", userInfo);
673
+ if (!blockchains)
674
+ blockchains = [];
675
+ pubkeys = [];
676
+ allBalances = [];
677
+ synced = [];
678
+ i = 0;
679
+ _a.label = 4;
680
+ case 4:
681
+ if (!(i < userInfo.pubkeys.length)) return [3 /*break*/, 9];
682
+ pubkeyInfo = userInfo.pubkeys[i];
683
+ delete pubkeyInfo._id;
684
+ //TODO validate pubkeys?
685
+ pubkeyInfo.username = username;
686
+ if (!(!pubkeyInfo.balances || pubkeyInfo.balances.length === 0)) return [3 /*break*/, 6];
687
+ log.debug(tag, "no balances, getting balances...");
688
+ return [4 /*yield*/, get_pubkey_balances(pubkeyInfo)];
689
+ case 5:
690
+ balances = _a.sent();
691
+ if (balances.success)
692
+ synced.push(pubkeyInfo.blockchain);
693
+ // log.debug(tag,"balances: ",balances)
694
+ log.debug(tag, pubkeyInfo.symbol + " balances: ", balances);
695
+ log.info(tag, context + ": " + pubkeyInfo.symbol + " balances: ", balances.balances.length);
696
+ if (balances && balances.balances) {
697
+ pubkeyInfo.balances = balances.balances;
698
+ allBalances = allBalances.concat(balances.balances);
699
+ log.info(tag, context + ": " + pubkeyInfo.symbol + " allBalances: ", allBalances.length);
491
700
  }
492
- });
493
- });
494
- };
495
- this.getBalance = function (coin) {
496
- return this.WALLET_BALANCES[coin] || 0;
497
- };
498
- this.getMasterOfSeed = function (mnemonic, coin) {
499
- return __awaiter(this, void 0, void 0, function () {
500
- var wallet;
501
- return __generator(this, function (_a) {
502
- switch (_a.label) {
503
- case 0: return [4 /*yield*/, ethCrypto.generateWalletFromSeed(mnemonic)];
504
- case 1:
505
- wallet = _a.sent();
506
- return [2 /*return*/, wallet.masterAddress];
701
+ if (balances && balances.nfts)
702
+ pubkeys.nfts = balances.nfts;
703
+ return [3 /*break*/, 7];
704
+ case 6:
705
+ log.debug(tag, "balances already exist! count: ", pubkeyInfo.balances.length);
706
+ _a.label = 7;
707
+ case 7:
708
+ // if(!masters[pubkeyInfo.symbol] && pubkeyInfo.master)masters[pubkeyInfo.symbol] = pubkeyInfo.master
709
+ pubkeyInfo.context = context;
710
+ pubkeys.push(pubkeyInfo);
711
+ _a.label = 8;
712
+ case 8:
713
+ i++;
714
+ return [3 /*break*/, 4];
715
+ case 9:
716
+ isSynced = false;
717
+ for (i = 0; i < blockchains.length; i++) {
718
+ blockchain = blockchains[i];
719
+ if (synced.indexOf(blockchain) === -1) {
720
+ log.info(tag, context + " blockchain not synced: ", blockchain);
721
+ isSynced = false;
722
+ break;
723
+ }
507
724
  }
508
- });
509
- });
510
- };
511
- this.getBalanceRemote = function (coin, address) {
512
- return __awaiter(this, void 0, void 0, function () {
513
- var tag;
514
- return __generator(this, function (_a) {
515
- tag = TAG + " | getBalance | ";
516
- try {
517
- log.debug("coin detected: ", coin);
518
- //TODO
725
+ return [2 /*return*/, { pubkeys: pubkeys, balances: allBalances }];
726
+ case 10:
727
+ e_4 = _a.sent();
728
+ console.error(tag, "e: ", e_4);
729
+ throw e_4;
730
+ case 11: return [2 /*return*/];
731
+ }
732
+ });
733
+ });
734
+ };
735
+ var register_zpub = function (username, pubkey, context) {
736
+ return __awaiter(this, void 0, void 0, function () {
737
+ var tag, queueId, account, index, address, work, result, e_5;
738
+ return __generator(this, function (_a) {
739
+ switch (_a.label) {
740
+ case 0:
741
+ tag = TAG + " | register_zpub | ";
742
+ _a.label = 1;
743
+ case 1:
744
+ _a.trys.push([1, 4, , 5]);
745
+ if (!context)
746
+ throw Error("101: context required!");
747
+ if (!pubkey.zpub)
748
+ throw Error("102: invalid pubkey! missing zpub!");
749
+ if (!pubkey.pubkey)
750
+ throw Error("103: invalid pubkey! missing pubkey!");
751
+ if (pubkey.pubkey == true)
752
+ throw Error("104:(zpub) invalid pubkey! == true wtf!");
753
+ if (!pubkey.symbol)
754
+ throw Error("105: invalid pubkey! missing pubkey!");
755
+ log.debug(tag, "pubkey: ", pubkey);
756
+ queueId = uuid.generate();
757
+ account = 0;
758
+ index = 0;
759
+ return [4 /*yield*/, get_address_from_xpub(pubkey.zpub, pubkey.scriptType, pubkey.symbol, account, index, false, false)];
760
+ case 2:
761
+ address = _a.sent();
762
+ log.debug(tag, "Master(Local): ", address);
763
+ log.debug(tag, "Master(hdwallet): ", pubkey.master);
764
+ if (address !== pubkey.master) {
765
+ log.error(tag, "Local Master NOT VALID!!");
766
+ log.error(tag, "Local Master: ", address);
767
+ log.error(tag, "hdwallet Master: ", pubkey.master);
768
+ //revert to pubkey (assume hdwallet right)
769
+ address = pubkey.master;
519
770
  }
520
- catch (e) {
521
- log.error(tag, "e: ", e);
522
- throw e;
771
+ work = {
772
+ type: 'zpub',
773
+ blockchain: pubkey.blockchain,
774
+ pubkey: pubkey.pubkey,
775
+ master: pubkey.master,
776
+ network: pubkey.blockchain,
777
+ asset: pubkey.symbol,
778
+ queueId: queueId,
779
+ username: username,
780
+ context: context,
781
+ zpub: pubkey.pubkey,
782
+ inserted: new Date().getTime()
783
+ };
784
+ log.debug(tag, "Creating work! ", work);
785
+ queue.createWork("pioneer:pubkey:ingest", work);
786
+ return [4 /*yield*/, get_pubkey_balances(work)];
787
+ case 3:
788
+ result = _a.sent();
789
+ log.debug(result);
790
+ return [2 /*return*/, queueId];
791
+ case 4:
792
+ e_5 = _a.sent();
793
+ console.error(tag, "e: ", e_5);
794
+ throw e_5;
795
+ case 5: return [2 /*return*/];
796
+ }
797
+ });
798
+ });
799
+ };
800
+ var register_xpub = function (username, pubkey, context) {
801
+ return __awaiter(this, void 0, void 0, function () {
802
+ var tag, queueId, account, index, address, work, _a, pubkeys, balances, e_6;
803
+ return __generator(this, function (_b) {
804
+ switch (_b.label) {
805
+ case 0:
806
+ tag = TAG + " | register_xpub | ";
807
+ _b.label = 1;
808
+ case 1:
809
+ _b.trys.push([1, 4, , 5]);
810
+ if (!pubkey.pubkey)
811
+ throw Error("102: invalid pubkey! missing pubkey!");
812
+ if (pubkey.pubkey == true)
813
+ throw Error("103:(xpub) invalid pubkey! === true wtf!");
814
+ if (!pubkey.symbol)
815
+ throw Error("104: invalid pubkey! missing symbol!");
816
+ queueId = uuid.generate();
817
+ account = 0;
818
+ index = 0;
819
+ return [4 /*yield*/, get_address_from_xpub(pubkey.pubkey, pubkey.scriptType, pubkey.symbol, account, index, false, false)];
820
+ case 2:
821
+ address = _b.sent();
822
+ log.debug(tag, "Master(Local): ", address);
823
+ log.debug(tag, "Master(hdwallet): ", pubkey.master);
824
+ if (address !== pubkey.master) {
825
+ log.error(tag, "Local Master NOT VALID!!");
826
+ //revert to pubkey (assume hdwallet right)
827
+ address = pubkey.master;
523
828
  }
524
- return [2 /*return*/];
525
- });
526
- });
527
- };
528
- this.getApproveQueue = function () {
529
- return this.APPROVE_QUEUE;
530
- };
531
- this.getPendingQueue = function () {
532
- return this.PENDING_QUEUE;
533
- };
534
- this.getNextReview = function () {
535
- return this.APPROVE_QUEUE.shift();
536
- };
537
- this.addUnsigned = function (unsigned) {
538
- return this.APPROVE_QUEUE.push(unsigned);
539
- };
540
- this.addBroadcasted = function (signed) {
541
- return this.PENDING_QUEUE.push(signed);
542
- };
543
- /*
544
- FIO commands
545
- */
546
- this.getFioPubkey = function () {
547
- return this.PUBLIC_WALLET['FIO'].pubkey;
548
- };
549
- this.getFioAccountInfo = function (username) {
550
- return __awaiter(this, void 0, void 0, function () {
551
- var result;
552
- return __generator(this, function (_a) {
553
- switch (_a.label) {
554
- case 0: return [4 /*yield*/, this.pioneerClient.instance.GetFioAccountInfo(username)];
555
- case 1:
556
- result = _a.sent();
557
- return [2 /*return*/, result.data];
829
+ work = {
830
+ context: context,
831
+ type: 'xpub',
832
+ blockchain: pubkey.blockchain,
833
+ pubkey: pubkey.pubkey,
834
+ master: pubkey.master,
835
+ network: pubkey.blockchain,
836
+ asset: pubkey.symbol,
837
+ queueId: queueId,
838
+ username: username,
839
+ xpub: pubkey.xpub,
840
+ inserted: new Date().getTime()
841
+ };
842
+ log.debug(tag, "Creating work! ", work);
843
+ queue.createWork("pioneer:pubkey:ingest", work);
844
+ return [4 /*yield*/, get_pubkey_balances(work)];
845
+ case 3:
846
+ _a = _b.sent(), pubkeys = _a.pubkeys, balances = _a.balances;
847
+ log.debug(tag, "pubkeys: ", pubkeys.length);
848
+ log.debug(tag, "balances: ", balances.length);
849
+ return [2 /*return*/, { pubkeys: pubkeys, balances: balances }];
850
+ case 4:
851
+ e_6 = _b.sent();
852
+ console.error(tag, "e: ", e_6);
853
+ throw e_6;
854
+ case 5: return [2 /*return*/];
855
+ }
856
+ });
857
+ });
858
+ };
859
+ var register_address = function (username, pubkey, context) {
860
+ return __awaiter(this, void 0, void 0, function () {
861
+ var tag, address, queueId, work, result, e_7;
862
+ return __generator(this, function (_a) {
863
+ switch (_a.label) {
864
+ case 0:
865
+ tag = TAG + " | register_address | ";
866
+ _a.label = 1;
867
+ case 1:
868
+ _a.trys.push([1, 3, , 4]);
869
+ address = pubkey.pubkey;
870
+ queueId = uuid.generate();
871
+ work = {
872
+ type: 'address',
873
+ pubkey: address,
874
+ symbol: pubkey.symbol,
875
+ blockchain: pubkey.blockchain,
876
+ network: pubkey.network,
877
+ asset: pubkey.symbol,
878
+ context: context,
879
+ queueId: queueId,
880
+ username: username,
881
+ address: address,
882
+ master: address,
883
+ inserted: new Date().getTime()
884
+ };
885
+ log.debug("adding work: ", work);
886
+ queue.createWork("pioneer:pubkey:ingest", work);
887
+ return [4 /*yield*/, get_pubkey_balances(work)];
888
+ case 2:
889
+ result = _a.sent();
890
+ log.info(tag, "result: ", result);
891
+ return [2 /*return*/, queueId];
892
+ case 3:
893
+ e_7 = _a.sent();
894
+ console.error(tag, "e: ", e_7);
895
+ throw e_7;
896
+ case 4: return [2 /*return*/];
897
+ }
898
+ });
899
+ });
900
+ };
901
+ var update_pubkeys = function (username, pubkeys, context) {
902
+ return __awaiter(this, void 0, void 0, function () {
903
+ var tag, saveActions, output, allPubkeys, PubkeyMap, i, pubkeyInfo, allBalances, allKnownPubkeys, knownPubkeys_1, i, unknown, i, pubkey, pubkeyInfo, nativeAsset, entryMongo, result, result, result, keyExists, pushTagMongo, resultSave, e_8;
904
+ var _a, _b, _c;
905
+ return __generator(this, function (_d) {
906
+ switch (_d.label) {
907
+ case 0:
908
+ tag = TAG + " | update_pubkeys | ";
909
+ _d.label = 1;
910
+ case 1:
911
+ _d.trys.push([1, 20, , 21]);
912
+ log.debug(tag, "input: ", { username: username, pubkeys: pubkeys, context: context });
913
+ saveActions = [];
914
+ output = {};
915
+ output.pubkeys = [];
916
+ allPubkeys = [];
917
+ PubkeyMap = {};
918
+ for (i = 0; i < pubkeys.length; i++) {
919
+ pubkeyInfo = pubkeys[i];
920
+ allPubkeys.push(pubkeyInfo.pubkey);
921
+ PubkeyMap[pubkeyInfo.pubkey] = pubkeyInfo;
558
922
  }
559
- });
560
- });
561
- };
562
- this.getFioAccountsByPubkey = function (pubkey) {
563
- return __awaiter(this, void 0, void 0, function () {
564
- var accounts;
565
- return __generator(this, function (_a) {
566
- switch (_a.label) {
567
- case 0: return [4 /*yield*/, this.pioneerClient.instance.AccountsFromFioPubkey(pubkey)];
568
- case 1:
569
- accounts = _a.sent();
570
- return [2 /*return*/, accounts.data];
923
+ //remove duplicates
924
+ allPubkeys = Array.from(new Set(allPubkeys));
925
+ allBalances = [];
926
+ //get pubkeys from mongo
927
+ log.debug(tag, "allPubkeys: ", allPubkeys);
928
+ return [4 /*yield*/, pubkeysDB.find({ "pubkey": { "$in": allPubkeys } })];
929
+ case 2:
930
+ allKnownPubkeys = _d.sent();
931
+ log.debug(tag, "allKnownPubkeys: ", allKnownPubkeys.length);
932
+ knownPubkeys_1 = [];
933
+ for (i = 0; i < allKnownPubkeys.length; i++) {
934
+ knownPubkeys_1.push(allKnownPubkeys[i].pubkey);
571
935
  }
572
- });
573
- });
574
- };
575
- //getPaymentRequests
576
- this.getPaymentRequests = function () {
577
- return __awaiter(this, void 0, void 0, function () {
578
- var accounts;
579
- return __generator(this, function (_a) {
580
- switch (_a.label) {
581
- case 0: return [4 /*yield*/, this.pioneerClient.instance.GetPaymentRequests(this.PUBLIC_WALLET['FIO'].pubkey)];
582
- case 1:
583
- accounts = _a.sent();
584
- return [2 /*return*/, accounts.data];
936
+ log.debug(tag, "allKnownPubkeys: ", allKnownPubkeys.length);
937
+ log.debug(tag, "allPubkeys: ", allPubkeys.length);
938
+ if (!(allPubkeys.length > allKnownPubkeys.length)) return [3 /*break*/, 18];
939
+ unknown = allPubkeys.filter(function (x) { return !knownPubkeys_1.includes(x); });
940
+ log.debug(tag, "unknown: ", unknown);
941
+ log.debug(tag, "Registering pubkeys : ", unknown.length);
942
+ i = 0;
943
+ _d.label = 3;
944
+ case 3:
945
+ if (!(i < unknown.length)) return [3 /*break*/, 17];
946
+ pubkey = unknown[i];
947
+ pubkeyInfo = PubkeyMap[pubkey];
948
+ log.debug(tag, "pubkeyInfo: ", pubkeyInfo);
949
+ if (!pubkeyInfo.pubkey)
950
+ throw Error("102: invalid pubkey! missing pubkey");
951
+ if (!pubkeyInfo.master)
952
+ throw Error("102: invalid pubkey! missing master");
953
+ if (!pubkeyInfo.blockchain)
954
+ throw Error("103: invalid pubkey! missing blockchain");
955
+ if (pubkey.pubkey === true)
956
+ throw Error("104: invalid pubkey! === true wtf!");
957
+ nativeAsset = getNativeAssetForBlockchain(pubkeyInfo.blockchain);
958
+ if (!nativeAsset)
959
+ throw Error("105: invalid pubkey! unsupported by coins module!");
960
+ //hack
961
+ if (!pubkeyInfo.symbol)
962
+ pubkeyInfo.symbol = nativeAsset;
963
+ //hack clean up tags
964
+ if (typeof (context) !== 'string') {
965
+ //
966
+ log.error("invalid context!", context);
967
+ throw Error("Bad walletID!");
585
968
  }
586
- });
587
- });
588
- };
589
- this.fioEncryptRequestContent = function (content) {
590
- return __awaiter(this, void 0, void 0, function () {
591
- var result;
592
- return __generator(this, function (_a) {
593
- switch (_a.label) {
594
- case 0: return [4 /*yield*/, this.WALLET.fioEncryptRequestContent(content)];
595
- case 1:
596
- result = _a.sent();
597
- return [2 /*return*/, result];
969
+ entryMongo = {
970
+ blockchain: pubkeyInfo.blockchain,
971
+ symbol: nativeAsset,
972
+ asset: nativeAsset,
973
+ path: pubkeyInfo.path,
974
+ pathMaster: pubkeyInfo.pathMaster,
975
+ master: pubkeyInfo.master,
976
+ pubkey: pubkeyInfo.pubkey,
977
+ script_type: pubkeyInfo.script_type,
978
+ network: pubkeyInfo.network,
979
+ created: new Date().getTime(),
980
+ tags: [username, pubkeyInfo.blockchain, pubkeyInfo.network, context],
981
+ };
982
+ if (!(pubkeyInfo.type === "xpub" || pubkeyInfo.xpub)) return [3 /*break*/, 5];
983
+ if (pubkeyInfo.xpub) {
984
+ entryMongo.pubkey = pubkeyInfo.pubkey;
598
985
  }
599
- });
600
- });
601
- };
602
- //fioDecryptRequestContent
603
- this.fioDecryptRequestContent = function (content) {
604
- return __awaiter(this, void 0, void 0, function () {
605
- var result;
606
- return __generator(this, function (_a) {
607
- switch (_a.label) {
608
- case 0: return [4 /*yield*/, this.WALLET.fioDecryptRequestContent(content)];
609
- case 1:
610
- result = _a.sent();
611
- return [2 /*return*/, result];
986
+ else {
987
+ log.errro(tag, "pubkey: ", pubkeyInfo);
988
+ throw Error("102: Invalid xpub pubkey!");
612
989
  }
613
- });
614
- });
615
- };
616
- this.getMaster = function (network) {
617
- return __awaiter(this, void 0, void 0, function () {
618
- var tag, output, address, paths, pathInfo, masterPath, _a, e_3;
619
- return __generator(this, function (_b) {
620
- switch (_b.label) {
621
- case 0:
622
- tag = TAG + " | get_address_master | ";
623
- _b.label = 1;
624
- case 1:
625
- _b.trys.push([1, 24, , 25]);
626
- if (!network)
627
- throw Error("101: must pass network!");
628
- if (!this.PUBLIC_WALLET[network]) return [3 /*break*/, 22];
629
- output = this.PUBLIC_WALLET[network].address;
630
- address = void 0;
631
- paths = this.paths();
632
- pathInfo = paths.filter(function (e) { return e.network === network; });
633
- log.debug(tag, "pathInfo: ", pathInfo);
634
- if (!pathInfo[0])
635
- throw Error("103: unable to get path info! ");
636
- masterPath = addressNListToBIP32(pathInfo[0].addressNListMaster);
637
- _a = network;
638
- switch (_a) {
639
- case 'BCH': return [3 /*break*/, 2];
640
- case 'LTC': return [3 /*break*/, 4];
641
- case 'DOGE': return [3 /*break*/, 6];
642
- case 'BTC': return [3 /*break*/, 8];
643
- case 'ETH': return [3 /*break*/, 10];
644
- case 'RUNE': return [3 /*break*/, 12];
645
- case 'OSMO': return [3 /*break*/, 14];
646
- case 'ATOM': return [3 /*break*/, 16];
647
- case 'BNB': return [3 /*break*/, 18];
648
- }
649
- return [3 /*break*/, 20];
650
- case 2: return [4 /*yield*/, this.WALLET.btcGetAddress({
651
- addressNList: bip32ToAddressNList(masterPath),
652
- coin: "BitcoinCash",
653
- //script types
654
- //p2pkh/cashaddr
655
- scriptType: 'p2pkh',
656
- showDisplay: false,
657
- })];
658
- case 3:
659
- address = _b.sent();
660
- address = bchaddr.toCashAddress(address);
661
- //convert
662
- return [3 /*break*/, 21];
663
- case 4: return [4 /*yield*/, this.WALLET.btcGetAddress({
664
- addressNList: bip32ToAddressNList(masterPath),
665
- coin: "Litecoin",
666
- //script types
667
- //p2wpkh/p2pkh/cashaddr
668
- scriptType: 'p2pkh',
669
- showDisplay: false,
670
- })];
671
- case 5:
672
- address = _b.sent();
673
- return [3 /*break*/, 21];
674
- case 6: return [4 /*yield*/, this.WALLET.btcGetAddress({
675
- addressNList: bip32ToAddressNList(masterPath),
676
- coin: "Dogecoin",
677
- //script types
678
- //p2wpkh/p2pkh/cashaddr
679
- scriptType: 'p2pkh',
680
- showDisplay: false,
681
- })];
682
- case 7:
683
- address = _b.sent();
684
- return [3 /*break*/, 21];
685
- case 8: return [4 /*yield*/, this.WALLET.btcGetAddress({
686
- addressNList: bip32ToAddressNList(masterPath),
687
- coin: "Bitcoin",
688
- //script types
689
- //p2wpkh/p2pkh/cashaddr
690
- scriptType: 'p2wpkh',
691
- showDisplay: false,
692
- })];
693
- case 9:
694
- address = _b.sent();
695
- return [3 /*break*/, 21];
696
- case 10: return [4 /*yield*/, this.WALLET.ethGetAddress({
697
- addressNList: bip32ToAddressNList(masterPath),
698
- showDisplay: false,
699
- })];
700
- case 11:
701
- address = _b.sent();
702
- return [3 /*break*/, 21];
703
- case 12: return [4 /*yield*/, this.WALLET.thorchainGetAddress({
704
- addressNList: bip32ToAddressNList(masterPath),
705
- showDisplay: false,
706
- })];
707
- case 13:
708
- address = _b.sent();
709
- return [3 /*break*/, 21];
710
- case 14: return [4 /*yield*/, this.WALLET.osmosisGetAddress({
711
- addressNList: bip32ToAddressNList(masterPath),
712
- showDisplay: false,
713
- })];
714
- case 15:
715
- address = _b.sent();
716
- return [3 /*break*/, 21];
717
- case 16: return [4 /*yield*/, this.WALLET.cosmosGetAddress({
718
- addressNList: bip32ToAddressNList(masterPath),
719
- showDisplay: false,
720
- })];
721
- case 17:
722
- address = _b.sent();
723
- return [3 /*break*/, 21];
724
- case 18: return [4 /*yield*/, this.WALLET.binanceGetAddress({
725
- addressNList: bip32ToAddressNList(masterPath),
726
- showDisplay: false,
727
- })];
728
- case 19:
729
- address = _b.sent();
730
- return [3 /*break*/, 21];
731
- case 20: throw Error("coin not yet implemented ! ");
732
- case 21:
733
- log.debug(tag, "address (HDwallet): ", address);
734
- log.debug(tag, "address (private): ", output);
735
- if (address !== output) {
736
- throw Error("unable to verify address in HDwallet!");
737
- }
738
- return [2 /*return*/, output];
739
- case 22:
740
- log.error(tag, "PUBLIC_WALLET: ", this.PUBLIC_WALLET);
741
- log.error(tag, "network: ", network);
742
- throw Error("master Not Found!");
743
- case 23: return [3 /*break*/, 25];
744
- case 24:
745
- e_3 = _b.sent();
746
- log.error(tag, "e: ", e_3);
747
- return [3 /*break*/, 25];
748
- case 25: return [2 /*return*/];
990
+ saveActions.push({ insertOne: entryMongo });
991
+ return [4 /*yield*/, register_xpub(username, pubkeyInfo, context)];
992
+ case 4:
993
+ result = _d.sent();
994
+ entryMongo.balances = result.balances;
995
+ allBalances.push.apply(allBalances, result.balances);
996
+ (_a = output.pubkeys).push.apply(_a, result.pubkeys);
997
+ return [3 /*break*/, 10];
998
+ case 5:
999
+ if (!(pubkeyInfo.type === "zpub" || pubkeyInfo.zpub)) return [3 /*break*/, 7];
1000
+ if (pubkeyInfo.zpub) {
1001
+ entryMongo.pubkey = pubkeyInfo.pubkey;
749
1002
  }
750
- });
751
- });
752
- };
753
- this.getAddress = function (coin, account, index, isChange) {
754
- var tag = TAG + " | get_address | ";
755
- try {
756
- var output
757
- //TODO do this with coin.js?
758
- //from xpub?
759
- //if token use ETH pubkey
760
- //TODO
761
- // if(tokenData.tokens.indexOf(coin) >=0 && coin !== 'EOS'){
762
- // coin = 'ETH'
763
- // }
764
- //if xpub get next unused
765
- = void 0;
766
- //TODO do this with coin.js?
767
- //from xpub?
768
- //if token use ETH pubkey
769
- //TODO
770
- // if(tokenData.tokens.indexOf(coin) >=0 && coin !== 'EOS'){
771
- // coin = 'ETH'
772
- // }
773
- //if xpub get next unused
774
- if (!this.PUBLIC_WALLET[coin]) {
775
- log.error(tag, "PUBLIC_WALLET: ", this.PUBLIC_WALLET);
776
- throw Error("102: coin not in this.PUBLIC_WALLET! coin:" + coin);
777
- }
778
- if (this.PUBLIC_WALLET[coin].type === 'xpub') {
779
- //get pubkey at path
780
- var publicKey = bitcoin.bip32.fromBase58(this.PUBLIC_WALLET[coin].pubkey).derive(account).derive(index).publicKey;
781
- log.debug("publicKey: ********* ", publicKey);
782
- switch (coin) {
783
- case 'ETH':
784
- output = ethUtils.bufferToHex(ethUtils.pubToAddress(publicKey, true));
785
- break;
786
- case 'RUNE':
787
- // code block
788
- if (this.isTestnet) {
789
- output = createBech32Address(publicKey, 'tthor');
790
- }
791
- else {
792
- output = createBech32Address(publicKey, 'thor');
793
- }
794
- break;
795
- case 'OSMO':
796
- // code block
797
- output = createBech32Address(publicKey, 'osmosis');
798
- break;
799
- case 'ATOM':
800
- // code block
801
- output = createBech32Address(publicKey, 'cosmos');
802
- break;
803
- case 'BNB':
804
- // code block
805
- output = createBech32Address(publicKey, 'bnb');
806
- break;
807
- case 'EOS':
808
- // log.debug(tag,"pubkey: ",publicKey)
809
- //
810
- // let account = this.pioneerClient.instance.Balance(null,publicKey)
811
- // log.debug(tag,"account: ",account)
812
- // //get accounts for pubkey
813
- // output = 'fixmebro'
814
- // break;
815
- case 'FIO':
816
- log.debug(tag, "pubkey: ", publicKey);
817
- var accountFio = this.pioneerClient.instance.GetFioAccount(publicKey);
818
- log.debug(tag, "accountFio: ", accountFio);
819
- //get accounts for pubkey
820
- output = accountFio;
821
- break;
822
- default:
823
- throw Error("coin not yet implemented ! ");
824
- // code block
1003
+ else {
1004
+ log.errro(tag, "pubkey: ", pubkeyInfo);
1005
+ throw Error("102: Invalid zpub pubkey!");
825
1006
  }
1007
+ saveActions.push({ insertOne: entryMongo });
1008
+ return [4 /*yield*/, register_zpub(username, pubkeyInfo, context)];
1009
+ case 6:
1010
+ result = _d.sent();
1011
+ entryMongo.balances = result.balances;
1012
+ allBalances.push.apply(allBalances, result.balances);
1013
+ (_b = output.pubkeys).push.apply(_b, result.pubkeys);
1014
+ return [3 /*break*/, 10];
1015
+ case 7:
1016
+ if (!(pubkeyInfo.type === "address")) return [3 /*break*/, 9];
1017
+ entryMongo.pubkey = pubkeyInfo.pubkey;
1018
+ return [4 /*yield*/, register_address(username, pubkeyInfo, context)];
1019
+ case 8:
1020
+ result = _d.sent();
1021
+ entryMongo.balances = result.balances;
1022
+ allBalances.push.apply(allBalances, result.balances);
1023
+ (_c = output.pubkeys).push.apply(_c, result.pubkeys);
1024
+ return [3 /*break*/, 10];
1025
+ case 9:
1026
+ log.error("Unhandled type: ", pubkeyInfo.type);
1027
+ _d.label = 10;
1028
+ case 10:
1029
+ //verify write
1030
+ log.debug(tag, "entryMongo: ", entryMongo);
1031
+ return [4 /*yield*/, pubkeysDB.findOne({ pubkey: entryMongo.pubkey })];
1032
+ case 11:
1033
+ keyExists = _d.sent();
1034
+ if (!keyExists) return [3 /*break*/, 13];
1035
+ log.debug(tag, "Key already registered! key: ", entryMongo);
1036
+ return [4 /*yield*/, pubkeysDB.update({ pubkey: entryMongo.pubkey }, { $addToSet: { tags: { $each: [context, username] } } })];
1037
+ case 12:
1038
+ pushTagMongo = _d.sent();
1039
+ log.debug(tag, "pushTagMongo: ", pushTagMongo);
1040
+ return [3 /*break*/, 16];
1041
+ case 13:
1042
+ if (!(!entryMongo.pubkey || entryMongo.pubkey == true)) return [3 /*break*/, 14];
1043
+ log.error(" **** ERROR INVALID PUBKEY ENTRY! ***** pubkeyInfo: ", pubkeyInfo);
1044
+ log.error(" **** ERROR INVALID PUBKEY ENTRY! ***** entryMongo: ", entryMongo);
1045
+ throw Error("105: unable to save invalid pubkey!");
1046
+ case 14: return [4 /*yield*/, pubkeysDB.insert(entryMongo)];
1047
+ case 15:
1048
+ resultSave = _d.sent();
1049
+ log.debug(tag, "resultSave: ", resultSave);
1050
+ _d.label = 16;
1051
+ case 16:
1052
+ i++;
1053
+ return [3 /*break*/, 3];
1054
+ case 17: return [3 /*break*/, 19];
1055
+ case 18:
1056
+ log.debug(tag, " No new pubkeys! ");
1057
+ _d.label = 19;
1058
+ case 19:
826
1059
  log.debug(tag, "output: ", output);
827
- }
828
- else {
829
- output = this.PUBLIC_WALLET[coin].master || this.PUBLIC_WALLET[coin].pubkey;
830
- }
831
- return output;
1060
+ if (allBalances.length === 0) {
1061
+ log.error(tag, "No balances found! allBalances: ", allBalances);
1062
+ // throw Error("No balances found!")
1063
+ }
1064
+ output.balances = allBalances;
1065
+ log.debug(tag, " return object: ", output);
1066
+ return [2 /*return*/, output];
1067
+ case 20:
1068
+ e_8 = _d.sent();
1069
+ console.error(tag, "e: ", e_8);
1070
+ throw e_8;
1071
+ case 21: return [2 /*return*/];
832
1072
  }
833
- catch (e) {
834
- log.error(tag, "e: ", e);
1073
+ });
1074
+ });
1075
+ };
1076
+ var register_pubkeys = function (username, pubkeys, context) {
1077
+ return __awaiter(this, void 0, void 0, function () {
1078
+ var tag, saveActions, allBalances, output, i, pubkeyInfo, nativeAsset, entryMongo, xpub, result, zpub, result, result, keyExists, pushTagMongo, saveMongo, e_9;
1079
+ var _a, _b, _c;
1080
+ return __generator(this, function (_d) {
1081
+ switch (_d.label) {
1082
+ case 0:
1083
+ tag = TAG + " | register_pubkeys | ";
1084
+ _d.label = 1;
1085
+ case 1:
1086
+ _d.trys.push([1, 17, , 18]);
1087
+ log.debug(tag, "input: ", { username: username, pubkeys: pubkeys, context: context });
1088
+ saveActions = [];
1089
+ allBalances = [];
1090
+ output = {};
1091
+ output.pubkeys = [];
1092
+ output.balances = [];
1093
+ i = 0;
1094
+ _d.label = 2;
1095
+ case 2:
1096
+ if (!(i < pubkeys.length)) return [3 /*break*/, 16];
1097
+ pubkeyInfo = pubkeys[i];
1098
+ log.info(tag, "pubkeyInfo: ", pubkeyInfo);
1099
+ nativeAsset = getNativeAssetForBlockchain(pubkeyInfo.blockchain);
1100
+ if (!nativeAsset)
1101
+ throw Error("104: invalid pubkey! unsupported by coins module!");
1102
+ if (!pubkeyInfo.pubkey)
1103
+ throw Error("104: invalid pubkey! missing pubkey!");
1104
+ if (!pubkeyInfo.type)
1105
+ throw Error("104: invalid pubkey! missing type!");
1106
+ //TODO verify type is in enums
1107
+ //hack
1108
+ if (!pubkeyInfo.symbol)
1109
+ pubkeyInfo.symbol = nativeAsset;
1110
+ log.debug(tag, "pubkeyInfo: ", pubkeyInfo);
1111
+ if (!pubkeyInfo.blockchain)
1112
+ throw Error("Invalid pubkey required field: blockchain");
1113
+ if (!pubkeyInfo.script_type)
1114
+ throw Error("Invalid pubkey required field: script_type coin:" + pubkeyInfo.blockchain);
1115
+ if (!pubkeyInfo.network)
1116
+ throw Error("Invalid pubkey required field: network coin:" + pubkeyInfo.blockchain);
1117
+ if (!pubkeyInfo.master)
1118
+ throw Error("Invalid pubkey required field: master coin:" + pubkeyInfo.blockchain);
1119
+ entryMongo = {
1120
+ pubkey: pubkeyInfo.pubkey,
1121
+ type: pubkeyInfo.type,
1122
+ blockchain: pubkeyInfo.blockchain,
1123
+ symbol: nativeAsset,
1124
+ asset: pubkeyInfo.blockchain,
1125
+ path: pubkeyInfo.path,
1126
+ pathMaster: pubkeyInfo.pathMaster,
1127
+ script_type: pubkeyInfo.script_type,
1128
+ network: pubkeyInfo.blockchain,
1129
+ created: new Date().getTime(),
1130
+ tags: [username, pubkeyInfo.blockchain, pubkeyInfo.symbol, pubkeyInfo.network, context],
1131
+ };
1132
+ if (!(pubkeyInfo.type === "xpub")) return [3 /*break*/, 4];
1133
+ log.debug(tag, "pubkeyInfo: ", pubkeyInfo);
1134
+ xpub = pubkeyInfo.pubkey;
1135
+ log.debug(tag, "xpub: ", xpub);
1136
+ entryMongo.pubkey = xpub;
1137
+ entryMongo.xpub = xpub;
1138
+ entryMongo.type = 'xpub';
1139
+ entryMongo.master = pubkeyInfo.address;
1140
+ entryMongo.address = pubkeyInfo.address;
1141
+ return [4 /*yield*/, register_xpub(username, pubkeyInfo, context)];
1142
+ case 3:
1143
+ result = _d.sent();
1144
+ allBalances.push.apply(allBalances, result.balances);
1145
+ (_a = output.pubkeys).push.apply(_a, result.pubkeys);
1146
+ return [3 /*break*/, 9];
1147
+ case 4:
1148
+ if (!(pubkeyInfo.type === "zpub")) return [3 /*break*/, 6];
1149
+ zpub = pubkeyInfo.pubkey;
1150
+ entryMongo.pubkey = zpub;
1151
+ entryMongo.zpub = zpub;
1152
+ entryMongo.type = 'zpub';
1153
+ entryMongo.master = pubkeyInfo.address;
1154
+ entryMongo.address = pubkeyInfo.address;
1155
+ return [4 /*yield*/, register_xpub(username, pubkeyInfo, context)];
1156
+ case 5:
1157
+ result = _d.sent();
1158
+ allBalances.push.apply(allBalances, result.balances);
1159
+ (_b = output.pubkeys).push.apply(_b, result.pubkeys);
1160
+ return [3 /*break*/, 9];
1161
+ case 6:
1162
+ if (!(pubkeyInfo.type === "address")) return [3 /*break*/, 8];
1163
+ entryMongo.pubkey = pubkeyInfo.pubkey;
1164
+ entryMongo.master = pubkeyInfo.pubkey;
1165
+ entryMongo.type = pubkeyInfo.type;
1166
+ entryMongo.address = pubkeyInfo.address;
1167
+ return [4 /*yield*/, register_address(username, pubkeyInfo, context)];
1168
+ case 7:
1169
+ result = _d.sent();
1170
+ allBalances.push.apply(allBalances, result.balances);
1171
+ (_c = output.pubkeys).push.apply(_c, result.pubkeys);
1172
+ return [3 /*break*/, 9];
1173
+ case 8:
1174
+ log.error("Unhandled type: ", pubkeyInfo.type);
1175
+ _d.label = 9;
1176
+ case 9:
1177
+ //verify write
1178
+ log.debug(tag, "entryMongo: ", entryMongo);
1179
+ if (!entryMongo.pubkey)
1180
+ throw Error("103: Invalid pubkey! can not save!");
1181
+ return [4 /*yield*/, pubkeysDB.findOne({ pubkey: entryMongo.pubkey })];
1182
+ case 10:
1183
+ keyExists = _d.sent();
1184
+ if (!keyExists) return [3 /*break*/, 12];
1185
+ log.debug(tag, "Key already registered! key: ", entryMongo);
1186
+ return [4 /*yield*/, pubkeysDB.update({ pubkey: entryMongo.pubkey }, { $addToSet: { tags: { $each: [context, username] } } })];
1187
+ case 11:
1188
+ pushTagMongo = _d.sent();
1189
+ log.debug(tag, "pushTagMongo: ", pushTagMongo);
1190
+ return [3 /*break*/, 15];
1191
+ case 12:
1192
+ if (!(!entryMongo.pubkey || entryMongo.pubkey == true)) return [3 /*break*/, 13];
1193
+ log.error(" **** ERROR INVALID PUBKEY ENTRY! ***** pubkeyInfo: ", pubkeyInfo);
1194
+ log.error(" **** ERROR INVALID PUBKEY ENTRY! ***** entryMongo: ", entryMongo);
1195
+ throw Error("105: unable to save invalid pubkey!");
1196
+ case 13: return [4 /*yield*/, pubkeysDB.insert(entryMongo)];
1197
+ case 14:
1198
+ saveMongo = _d.sent();
1199
+ log.debug(tag, "saveMongo: ", saveMongo);
1200
+ _d.label = 15;
1201
+ case 15:
1202
+ i++;
1203
+ return [3 /*break*/, 2];
1204
+ case 16:
1205
+ output.balances = allBalances;
1206
+ log.debug(tag, "return object: ", output);
1207
+ return [2 /*return*/, output];
1208
+ case 17:
1209
+ e_9 = _d.sent();
1210
+ console.error(tag, "e: ", e_9);
1211
+ throw e_9;
1212
+ case 18: return [2 /*return*/];
835
1213
  }
836
- };
837
- /*
838
- let swap = {
839
- inboundAddress: {
840
- chain: 'ETH',
841
- pub_key: 'tthorpub1addwnpepqvuy8vh6yj4h28xp6gfpjsztpj6p46y2rs0763t6uw9f6lkky0ly5uvwla6',
842
- address: '0x36286e570c412531aad366154eea9867b0e71755',
843
- router: '0x9d496De78837f5a2bA64Cb40E62c19FBcB67f55a',
844
- halted: false
845
- },
846
- asset: {
847
- chain: 'ETH',
848
- symbol: 'ETH',
849
- ticker: 'ETH',
850
- iconPath: 'https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/binance/assets/ETH-1C9/logo.png'
851
- },
852
- memo: '=:THOR.RUNE:tthor1veu9u5h4mtdq34fjgu982s8pympp6w87ag58nh',
853
- amount: "0.1"
854
- }
855
- */
856
- // @ts-ignore
857
- this.addLiquidity = function (addLiquidity) {
858
- return __awaiter(this, void 0, void 0, function () {
859
- var tag, rawTx, UTXOcoins, addressFrom, data, nonceRemote, nonce, gas_limit, gas_price, masterPathEth, amountNative, ethTx, txid, coin, addressFrom, transfer, e_4;
860
- return __generator(this, function (_a) {
861
- switch (_a.label) {
862
- case 0:
863
- tag = TAG + " | addLiquidity | ";
864
- _a.label = 1;
865
- case 1:
866
- _a.trys.push([1, 14, , 15]);
867
- rawTx = void 0;
868
- UTXOcoins = [
869
- 'BTC',
870
- 'BCH',
871
- 'LTC'
872
- ];
873
- if (!(addLiquidity.inboundAddress.chain === 'ETH')) return [3 /*break*/, 9];
874
- addressFrom = void 0;
875
- if (!addLiquidity.addressFrom) return [3 /*break*/, 2];
876
- addressFrom = addLiquidity.addressFrom;
877
- return [3 /*break*/, 4];
878
- case 2: return [4 /*yield*/, this.getMaster('ETH')];
879
- case 3:
880
- addressFrom = _a.sent();
881
- _a.label = 4;
882
- case 4:
883
- if (!addressFrom)
884
- throw Error("102: unable to get master address! ");
885
- return [4 /*yield*/, this.pioneerClient.instance.GetThorchainMemoEncoded(null, addLiquidity)];
886
- case 5:
887
- data = _a.sent();
888
- data = data.data;
889
- log.debug(tag, "txData: ", data);
890
- return [4 /*yield*/, this.pioneerClient.instance.GetNonce(addressFrom)];
891
- case 6:
892
- nonceRemote = _a.sent();
893
- nonceRemote = nonceRemote.data;
894
- nonce = addLiquidity.nonce || nonceRemote;
895
- gas_limit = 80000 //TODO dynamic gas limit?
896
- ;
897
- return [4 /*yield*/, this.pioneerClient.instance.GetGasPrice()];
898
- case 7:
899
- gas_price = _a.sent();
900
- gas_price = gas_price.data;
901
- log.debug(tag, "gas_price: ", gas_price);
902
- gas_price = parseInt(gas_price);
903
- gas_price = gas_price + 1000000000;
904
- masterPathEth = "m/44'/60'/0'/0/0" //TODO moveme to support
905
- ;
906
- amountNative = parseFloat(addLiquidity.amount) * support.getBase('ETH');
907
- amountNative = Number(parseInt(String(amountNative)));
908
- log.debug("amountNative: ", amountNative);
909
- log.debug("nonce: ", nonce);
910
- ethTx = {
911
- // addressNList: support.bip32ToAddressNList(masterPathEth),
912
- "addressNList": [
913
- 2147483692,
914
- 2147483708,
915
- 2147483648,
916
- 0,
917
- 0
918
- ],
919
- nonce: web3_utils_1.numberToHex(nonce),
920
- gasPrice: web3_utils_1.numberToHex(gas_price),
921
- gasLimit: web3_utils_1.numberToHex(gas_limit),
922
- value: web3_utils_1.numberToHex(amountNative),
923
- to: addLiquidity.inboundAddress.router,
924
- data: data,
925
- };
926
- log.debug("unsignedTxETH: ", ethTx);
927
- return [4 /*yield*/, this.WALLET.ethSignTx(ethTx)];
928
- case 8:
929
- //send to hdwallet
930
- rawTx = _a.sent();
931
- rawTx.params = ethTx;
932
- txid = keccak256(rawTx.serialized).toString('hex');
933
- log.debug(tag, "txid: ", txid);
934
- rawTx.txid = txid;
935
- return [3 /*break*/, 13];
936
- case 9:
937
- if (!(UTXOcoins.indexOf(addLiquidity.inboundAddress.chain) >= 0)) return [3 /*break*/, 12];
938
- if (!addLiquidity.memo)
939
- throw Error("Memo required for swaps!");
940
- coin = addLiquidity.inboundAddress.chain;
941
- return [4 /*yield*/, this.getMaster(coin)
942
- //build transfer with memo
943
- ]; //TODO this silly in utxo
944
- case 10:
945
- addressFrom = _a.sent() //TODO this silly in utxo
946
- ;
947
- transfer = {
948
- coin: "BTC",
949
- asset: "BTC",
950
- network: "BTC",
951
- addressTo: addLiquidity.inboundAddress.address,
952
- addressFrom: addressFrom,
953
- amount: addLiquidity.amount,
954
- feeLevel: addLiquidity.feeLevel,
955
- memo: addLiquidity.memo
956
- };
957
- return [4 /*yield*/, this.buildTransfer(transfer)];
958
- case 11:
959
- rawTx = _a.sent();
960
- console.log("rawTx: ", rawTx);
961
- return [3 /*break*/, 13];
962
- case 12: throw Error("Chain not supported! " + addLiquidity.inboundAddress.chain);
963
- case 13: return [2 /*return*/, rawTx];
964
- case 14:
965
- e_4 = _a.sent();
966
- log.error(e_4);
967
- throw e_4;
968
- case 15: return [2 /*return*/];
969
- }
970
- });
971
- });
972
- },
973
- this.buildApproval = function (approval) {
974
- return __awaiter(this, void 0, void 0, function () {
975
- var tag, rawTx, addressFrom, nonceRemote, nonce, gas_limit, gas_price, data, ethTx, e_5;
976
- return __generator(this, function (_a) {
977
- switch (_a.label) {
978
- case 0:
979
- tag = TAG + " | buildApproval | ";
980
- _a.label = 1;
981
- case 1:
982
- _a.trys.push([1, 5, , 6]);
983
- rawTx = void 0;
984
- return [4 /*yield*/, this.getMaster('ETH')];
985
- case 2:
986
- addressFrom = _a.sent();
987
- return [4 /*yield*/, this.pioneerClient.instance.GetNonce(addressFrom)];
988
- case 3:
989
- nonceRemote = _a.sent();
990
- nonceRemote = nonceRemote.data;
991
- nonce = approval.nonce || nonceRemote;
992
- gas_limit = 80000 //TODO dynamic gas limit?
993
- ;
994
- return [4 /*yield*/, this.pioneerClient.instance.GetGasPrice()];
995
- case 4:
996
- gas_price = _a.sent();
997
- gas_price = gas_price.data;
998
- log.debug(tag, "gas_price: ", gas_price);
999
- gas_price = parseInt(gas_price);
1000
- gas_price = gas_price + 1000000000;
1001
- log.debug(tag, "approval.tokenAddress: ", approval.tokenAddress);
1002
- log.debug(tag, "approval.amount: ", approval.amount);
1003
- data = "0x" +
1004
- "095ea7b3" + // ERC-20 contract approve function identifier
1005
- (approval.contract).replace("0x", "").padStart(64, "0") +
1006
- (approval.amount).toString(16).padStart(64, "0");
1007
- log.debug(tag, "data: ", data);
1008
- ethTx = {
1009
- // addressNList: support.bip32ToAddressNList(masterPathEth),
1010
- "addressNList": [
1011
- 2147483692,
1012
- 2147483708,
1013
- 2147483648,
1014
- 0,
1015
- 0
1016
- ],
1017
- nonce: web3_utils_1.numberToHex(nonce),
1018
- gasPrice: web3_utils_1.numberToHex(gas_price),
1019
- gasLimit: web3_utils_1.numberToHex(gas_limit),
1020
- value: web3_utils_1.numberToHex(0),
1021
- to: approval.tokenAddress,
1022
- data: data,
1023
- };
1024
- log.debug("unsignedTxETH: ", ethTx);
1025
- return [2 /*return*/, ethTx];
1026
- case 5:
1027
- e_5 = _a.sent();
1028
- log.error(e_5);
1029
- throw e_5;
1030
- case 6: return [2 /*return*/];
1031
- }
1032
- });
1033
- });
1034
- },
1035
- this.deposit = function (deposit) {
1036
- return __awaiter(this, void 0, void 0, function () {
1037
- var tag, rawTx, amountNative, addressFrom, masterInfo, sequence, account_number, txType, gas, fee, memo, unsigned, chain_id, fromAddress, runeTx, unsignedTx, e_6;
1038
- return __generator(this, function (_a) {
1039
- switch (_a.label) {
1040
- case 0:
1041
- tag = TAG + " | deposit | ";
1042
- _a.label = 1;
1043
- case 1:
1044
- _a.trys.push([1, 8, , 9]);
1045
- rawTx = void 0;
1046
- log.debug(tag, "deposit: ", deposit);
1047
- if (!(deposit.network === 'RUNE')) return [3 /*break*/, 6];
1048
- amountNative = RUNE_BASE * parseFloat(deposit.amount);
1049
- amountNative = parseInt(amountNative.toString());
1050
- addressFrom = void 0;
1051
- if (!deposit.addressFrom) return [3 /*break*/, 2];
1052
- addressFrom = deposit.addressFrom;
1053
- return [3 /*break*/, 4];
1054
- case 2: return [4 /*yield*/, this.getMaster('RUNE')];
1055
- case 3:
1056
- addressFrom = _a.sent();
1057
- _a.label = 4;
1058
- case 4:
1059
- //get account number
1060
- log.debug(tag, "addressFrom: ", addressFrom);
1061
- return [4 /*yield*/, this.pioneerClient.instance.GetAccountInfo({ network: 'RUNE', address: addressFrom })];
1062
- case 5:
1063
- masterInfo = _a.sent();
1064
- masterInfo = masterInfo.data;
1065
- log.debug(tag, "masterInfo: ", masterInfo.data);
1066
- sequence = masterInfo.result.value.sequence || 0;
1067
- account_number = masterInfo.result.value.account_number;
1068
- sequence = parseInt(sequence);
1069
- sequence = sequence.toString();
1070
- txType = "thorchain/MsgDeposit";
1071
- gas = "250000";
1072
- fee = "2000000";
1073
- if (!deposit.memo)
1074
- throw Error("103: invalid swap! missing memo");
1075
- memo = deposit.memo;
1076
- unsigned = {
1077
- "fee": {
1078
- "amount": [
1079
- {
1080
- "amount": fee,
1081
- "denom": "rune"
1082
- }
1083
- ],
1084
- "gas": gas
1085
- },
1086
- "memo": memo,
1087
- "msg": [
1088
- {
1089
- "type": txType,
1090
- "value": {
1091
- "amount": [
1092
- {
1093
- "amount": "50994000",
1094
- "asset": "THOR.RUNE"
1095
- }
1096
- ],
1097
- "memo": memo,
1098
- "signer": addressFrom
1099
- }
1100
- }
1101
- ],
1102
- "signatures": null
1103
- };
1104
- chain_id = RUNE_CHAIN;
1105
- if (!sequence)
1106
- throw Error("112: Failed to get sequence");
1107
- if (!account_number)
1108
- account_number = 0;
1109
- fromAddress = addressFrom;
1110
- log.debug("res: ", prettyjson.render({
1111
- addressNList: bip32ToAddressNList(HD_RUNE_KEYPATH),
1112
- chain_id: chain_id,
1113
- account_number: account_number,
1114
- sequence: sequence,
1115
- tx: unsigned,
1116
- }));
1117
- if (fromAddress !== addressFrom) {
1118
- log.error(tag, "fromAddress context WALLET: ", fromAddress);
1119
- log.error(tag, "fromAddress DEPOSIT: ", addressFrom);
1120
- throw Error("Can not sign, address mismatch");
1121
- }
1122
- log.debug(tag, "******* signTx: ", JSON.stringify({
1123
- addressNList: bip32ToAddressNList(HD_RUNE_KEYPATH),
1124
- chain_id: chain_id,
1125
- account_number: account_number,
1126
- sequence: sequence,
1127
- tx: unsigned,
1128
- }));
1129
- runeTx = {
1130
- addressNList: bip32ToAddressNList(HD_RUNE_KEYPATH),
1131
- chain_id: chain_id,
1132
- account_number: account_number,
1133
- sequence: sequence,
1134
- tx: unsigned,
1135
- };
1136
- unsignedTx = {
1137
- invocationId: deposit.invocationId,
1138
- network: deposit.network,
1139
- deposit: deposit,
1140
- HDwalletPayload: runeTx,
1141
- verbal: "Thorchain transaction"
1142
- };
1143
- rawTx = unsignedTx;
1144
- return [3 /*break*/, 7];
1145
- case 6: throw Error("Chain not supported! " + deposit.inboundAddress.chain);
1146
- case 7: return [2 /*return*/, rawTx];
1147
- case 8:
1148
- e_6 = _a.sent();
1149
- log.error(e_6);
1150
- throw e_6;
1151
- case 9: return [2 /*return*/];
1152
- }
1153
- });
1154
- });
1155
- },
1156
- //@ts-ignore
1157
- this.buildSwap = function (swap) {
1158
- return __awaiter(this, void 0, void 0, function () {
1159
- var tag, rawTx, UTXOcoins, addressFrom, data, nonceRemote, nonce, gas_limit, gas_price, masterPathEth, amountNative, ethTx, amountNative, addressFrom, masterInfo, sequence, account_number, txType, gas, fee, memo, unsigned, chain_id, fromAddress, runeTx, unsignedTx, e_7;
1160
- return __generator(this, function (_a) {
1161
- switch (_a.label) {
1162
- case 0:
1163
- tag = TAG + " | buildSwap | ";
1164
- _a.label = 1;
1165
- case 1:
1166
- _a.trys.push([1, 16, , 17]);
1167
- rawTx = void 0;
1168
- log.debug(tag, "swap: ", swap);
1169
- UTXOcoins = [
1170
- 'BTC',
1171
- 'BCH',
1172
- 'LTC'
1173
- ];
1174
- if (!(swap.inboundAddress.chain === 'ETH')) return [3 /*break*/, 8];
1175
- addressFrom = void 0;
1176
- if (!swap.addressFrom) return [3 /*break*/, 2];
1177
- addressFrom = swap.addressFrom;
1178
- return [3 /*break*/, 4];
1179
- case 2: return [4 /*yield*/, this.getMaster('ETH')];
1180
- case 3:
1181
- addressFrom = _a.sent();
1182
- _a.label = 4;
1183
- case 4:
1184
- if (!addressFrom)
1185
- throw Error("102: unable to get master address! ");
1186
- return [4 /*yield*/, this.pioneerClient.instance.GetThorchainMemoEncoded(null, swap)];
1187
- case 5:
1188
- data = _a.sent();
1189
- data = data.data;
1190
- log.debug(tag, "txData: ", data);
1191
- return [4 /*yield*/, this.pioneerClient.instance.GetNonce(addressFrom)];
1192
- case 6:
1193
- nonceRemote = _a.sent();
1194
- nonceRemote = nonceRemote.data;
1195
- nonce = swap.nonce || nonceRemote;
1196
- gas_limit = 80000 //TODO dynamic gas limit?
1197
- ;
1198
- return [4 /*yield*/, this.pioneerClient.instance.GetGasPrice()];
1199
- case 7:
1200
- gas_price = _a.sent();
1201
- gas_price = gas_price.data;
1202
- log.debug(tag, "gas_price: ", gas_price);
1203
- gas_price = parseInt(gas_price);
1204
- gas_price = gas_price + 1000000000;
1205
- masterPathEth = "m/44'/60'/0'/0/0" //TODO moveme to support
1206
- ;
1207
- amountNative = parseFloat(swap.amount) * support.getBase('ETH');
1208
- amountNative = Number(parseInt(String(amountNative)));
1209
- log.debug("amountNative: ", amountNative);
1210
- log.debug("nonce: ", nonce);
1211
- ethTx = {
1212
- // addressNList: support.bip32ToAddressNList(masterPathEth),
1213
- "addressNList": [
1214
- 2147483692,
1215
- 2147483708,
1216
- 2147483648,
1217
- 0,
1218
- 0
1219
- ],
1220
- nonce: web3_utils_1.numberToHex(nonce),
1221
- gasPrice: web3_utils_1.numberToHex(gas_price),
1222
- gasLimit: web3_utils_1.numberToHex(gas_limit),
1223
- value: web3_utils_1.numberToHex(amountNative),
1224
- to: swap.inboundAddress.router,
1225
- data: data,
1226
- chainId: 1
1227
- };
1228
- log.debug("unsignedTxETH: ", ethTx);
1229
- rawTx = {
1230
- network: 'ETH',
1231
- asset: 'ETH',
1232
- swap: swap,
1233
- HDwalletPayload: ethTx,
1234
- verbal: "Ethereum transaction"
1235
- };
1236
- return [3 /*break*/, 15];
1237
- case 8:
1238
- if (!(swap.inboundAddress.chain === 'RUNE')) return [3 /*break*/, 14];
1239
- amountNative = RUNE_BASE * parseFloat(swap.amount);
1240
- amountNative = parseInt(amountNative.toString());
1241
- addressFrom = void 0;
1242
- if (!swap.addressFrom) return [3 /*break*/, 9];
1243
- addressFrom = swap.addressFrom;
1244
- return [3 /*break*/, 11];
1245
- case 9: return [4 /*yield*/, this.getMaster('ETH')];
1246
- case 10:
1247
- addressFrom = _a.sent();
1248
- _a.label = 11;
1249
- case 11:
1250
- //get account number
1251
- log.debug(tag, "addressFrom: ", addressFrom);
1252
- return [4 /*yield*/, this.pioneerClient.instance.GetAccountInfo({ network: 'RUNE', address: addressFrom })];
1253
- case 12:
1254
- masterInfo = _a.sent();
1255
- masterInfo = masterInfo.data;
1256
- log.debug(tag, "masterInfo: ", masterInfo.data);
1257
- sequence = masterInfo.result.value.sequence || 0;
1258
- account_number = masterInfo.result.value.account_number;
1259
- sequence = parseInt(sequence);
1260
- sequence = sequence.toString();
1261
- txType = "thorchain/MsgSend";
1262
- gas = "250000";
1263
- fee = "2000000";
1264
- if (!swap.memo)
1265
- throw Error("103: invalid swap! missing memo");
1266
- memo = swap.memo;
1267
- if (!swap.inboundAddress.address)
1268
- throw Error("104: invalid inboundAddress on swap");
1269
- unsigned = {
1270
- "fee": {
1271
- "amount": [
1272
- {
1273
- "amount": fee,
1274
- "denom": "rune"
1275
- }
1276
- ],
1277
- "gas": gas
1278
- },
1279
- "memo": memo,
1280
- "msg": [
1281
- {
1282
- "type": txType,
1283
- "value": {
1284
- "amount": [
1285
- {
1286
- "amount": amountNative.toString(),
1287
- "denom": "rune"
1288
- }
1289
- ],
1290
- "from_address": addressFrom,
1291
- "to_address": swap.inboundAddress.address
1292
- }
1293
- }
1294
- ],
1295
- "signatures": null
1296
- };
1297
- chain_id = RUNE_CHAIN;
1298
- if (!sequence)
1299
- throw Error("112: Failed to get sequence");
1300
- if (!account_number)
1301
- account_number = 0;
1302
- return [4 /*yield*/, this.WALLET.thorchainGetAddress({
1303
- addressNList: bip32ToAddressNList(HD_RUNE_KEYPATH),
1304
- showDisplay: false,
1305
- })];
1306
- case 13:
1307
- fromAddress = _a.sent();
1308
- log.debug(tag, "fromAddressHDwallet: ", fromAddress);
1309
- log.debug(tag, "fromAddress: ", addressFrom);
1310
- log.debug("res: ", prettyjson.render({
1311
- addressNList: bip32ToAddressNList(HD_RUNE_KEYPATH),
1312
- chain_id: chain_id,
1313
- account_number: account_number,
1314
- sequence: sequence,
1315
- tx: unsigned,
1316
- }));
1317
- if (fromAddress !== addressFrom) {
1318
- log.error(tag, "fromAddress: ", fromAddress);
1319
- log.error(tag, "addressFrom: ", addressFrom);
1320
- throw Error("Can not sign, address mismatch");
1321
- }
1322
- log.debug(tag, "******* signTx: ", JSON.stringify({
1323
- addressNList: bip32ToAddressNList(HD_RUNE_KEYPATH),
1324
- chain_id: chain_id,
1325
- account_number: account_number,
1326
- sequence: sequence,
1327
- tx: unsigned,
1328
- }));
1329
- runeTx = {
1330
- addressNList: bip32ToAddressNList(HD_RUNE_KEYPATH),
1331
- chain_id: chain_id,
1332
- account_number: account_number,
1333
- sequence: sequence,
1334
- tx: unsigned,
1335
- };
1336
- unsignedTx = {
1337
- network: 'ETH',
1338
- asset: 'ETH',
1339
- swap: swap,
1340
- HDwalletPayload: runeTx,
1341
- verbal: "Thorchain transaction"
1342
- };
1343
- rawTx = unsignedTx;
1344
- return [3 /*break*/, 15];
1345
- case 14:
1346
- if (UTXOcoins.indexOf(swap.inboundAddress.chain) >= 0) {
1347
- throw Error("NOT SUPPORTED! Use transfer with memo!");
1348
- }
1349
- else {
1350
- throw Error("Chain not supported! " + swap.inboundAddress.chain);
1351
- }
1352
- _a.label = 15;
1353
- case 15: return [2 /*return*/, rawTx];
1354
- case 16:
1355
- e_7 = _a.sent();
1356
- log.error(e_7);
1357
- throw e_7;
1358
- case 17: return [2 /*return*/];
1359
- }
1360
- });
1361
- });
1362
- },
1363
- /*
1364
- CatchAll for custom Tx's
1365
- */
1366
- this.buildTx = function (transaction) {
1367
- return __awaiter(this, void 0, void 0, function () {
1368
- var tag, rawTx, amountNative, addressFrom, masterInfo, sequence, account_number, chain_id, msg, txType, gas, fee, memo, unsigned, fromAddress, atomTx, unsignedTx, tx, signTx, res, _a, tx, signTx, res, amountNative, addressFrom, masterInfo, sequence, account_number, chain_id, msg, txType, gas, fee, memo, unsigned, fromAddress, atomTx, unsignedTx, e_8;
1369
- return __generator(this, function (_b) {
1370
- switch (_b.label) {
1371
- case 0:
1372
- tag = TAG + " | buildTx | ";
1373
- _b.label = 1;
1374
- case 1:
1375
- _b.trys.push([1, 23, , 24]);
1376
- rawTx = {};
1377
- if (!(transaction.type === 'ibcdeposit')) return [3 /*break*/, 7];
1378
- amountNative = ATOM_BASE * parseFloat(transaction.amount);
1379
- amountNative = parseInt(amountNative.toString());
1380
- log.debug(tag, "amountNative: ", amountNative);
1381
- addressFrom = void 0;
1382
- if (!transaction.addressFrom) return [3 /*break*/, 2];
1383
- addressFrom = transaction.addressFrom;
1384
- return [3 /*break*/, 4];
1385
- case 2: return [4 /*yield*/, this.getMaster('ATOM')];
1386
- case 3:
1387
- addressFrom = _b.sent();
1388
- _b.label = 4;
1389
- case 4: return [4 /*yield*/, this.pioneerClient.instance.GetAccountInfo({ network: 'ATOM', address: addressFrom })];
1390
- case 5:
1391
- masterInfo = _b.sent();
1392
- masterInfo = masterInfo.data;
1393
- log.debug(tag, "masterInfo: ", masterInfo.data);
1394
- sequence = masterInfo.result.value.sequence;
1395
- account_number = masterInfo.result.value.account_number;
1396
- sequence = parseInt(sequence);
1397
- sequence = sequence.toString();
1398
- chain_id = ATOM_CHAIN;
1399
- msg = void 0;
1400
- switch (transaction.type) {
1401
- case "ibcdeposit":
1402
- if (!transaction.source_port)
1403
- throw Error("Missing source_port !");
1404
- if (!transaction.source_channel)
1405
- throw Error("Missing source_channel!");
1406
- if (!transaction.token)
1407
- throw Error("Missing token!");
1408
- if (!transaction.timeout_height)
1409
- throw Error("Missing timeout_height!");
1410
- msg = {
1411
- "type": "cosmos-sdk/MsgTransfer",
1412
- "value": {
1413
- "sender": transaction.sender,
1414
- "receiver": transaction.receiver,
1415
- "source_port": transaction.source_port,
1416
- "source_channel": transaction.source_channel,
1417
- "token": transaction.token,
1418
- "timeout_height": transaction.timeout_height,
1419
- }
1420
- };
1421
- break;
1422
- default:
1423
- throw Error("unsupported IBC tx type: " + transaction.type);
1424
- //code block
1425
- }
1426
- txType = "cosmos-sdk/MsgSend";
1427
- gas = "100000";
1428
- fee = "1000";
1429
- memo = transaction.memo || "";
1430
- if (!msg)
1431
- throw Error('failed to make tx msg');
1432
- unsigned = {
1433
- "fee": {
1434
- "amount": [
1435
- {
1436
- "amount": fee,
1437
- "denom": "uatom"
1438
- }
1439
- ],
1440
- "gas": gas
1441
- },
1442
- "memo": memo,
1443
- "msg": [
1444
- msg
1445
- ],
1446
- "signatures": null
1447
- };
1448
- if (!sequence)
1449
- throw Error("112: Failed to get sequence");
1450
- if (!account_number)
1451
- throw Error("113: Failed to get account_number");
1452
- return [4 /*yield*/, this.WALLET.cosmosGetAddress({
1453
- addressNList: bip32ToAddressNList(HD_ATOM_KEYPATH),
1454
- showDisplay: false,
1455
- })];
1456
- case 6:
1457
- fromAddress = _b.sent();
1458
- log.debug(tag, "fromAddressHDwallet: ", fromAddress);
1459
- log.debug(tag, "fromAddress: ", addressFrom);
1460
- log.debug("res: ", prettyjson.render({
1461
- addressNList: bip32ToAddressNList(HD_ATOM_KEYPATH),
1462
- chain_id: chain_id,
1463
- account_number: account_number,
1464
- sequence: sequence,
1465
- tx: unsigned,
1466
- }));
1467
- atomTx = {
1468
- addressNList: bip32ToAddressNList(HD_ATOM_KEYPATH),
1469
- chain_id: ATOM_CHAIN,
1470
- account_number: account_number,
1471
- sequence: sequence,
1472
- tx: unsigned,
1473
- };
1474
- unsignedTx = {
1475
- network: network,
1476
- asset: network,
1477
- transaction: transaction,
1478
- HDwalletPayload: atomTx,
1479
- verbal: "ibc transaction"
1480
- };
1481
- rawTx = unsignedTx;
1482
- return [3 /*break*/, 22];
1483
- case 7:
1484
- if (!(transaction.network === 'FIO')) return [3 /*break*/, 15];
1485
- tx = void 0;
1486
- signTx = void 0;
1487
- res = void 0;
1488
- _a = transaction.type;
1489
- switch (_a) {
1490
- case "fioSignAddPubAddressTx": return [3 /*break*/, 8];
1491
- case "fioSignRegisterDomainTx": return [3 /*break*/, 10];
1492
- case "fioSignRegisterFioAddressTx": return [3 /*break*/, 11];
1493
- case "fioSignNewFundsRequestTx": return [3 /*break*/, 12];
1494
- }
1495
- return [3 /*break*/, 14];
1496
- case 8:
1497
- tx = transaction.tx;
1498
- signTx = {
1499
- addressNList: bip32ToAddressNList("m/44'/235'/0'/0/0"),
1500
- actions: [
1501
- {
1502
- account: fiosdk_offline_1.FioActionParameters.FioAddPubAddressActionAccount,
1503
- name: fiosdk_offline_1.FioActionParameters.FioAddPubAddressActionName,
1504
- data: tx,
1505
- },
1506
- ],
1507
- };
1508
- log.debug(tag, "signTx: ", JSON.stringify(signTx));
1509
- return [4 /*yield*/, this.WALLET.fioSignTx(signTx)];
1510
- case 9:
1511
- res = _b.sent();
1512
- res.coin = "FIO";
1513
- res.type = transaction.type;
1514
- rawTx = res;
1515
- // code block
1516
- return [3 /*break*/, 14];
1517
- case 10:
1518
- // code block
1519
- return [3 /*break*/, 14];
1520
- case 11:
1521
- // code block
1522
- return [3 /*break*/, 14];
1523
- case 12:
1524
- tx = transaction.tx;
1525
- signTx = {
1526
- addressNList: bip32ToAddressNList("m/44'/235'/0'/0/0"),
1527
- actions: [
1528
- {
1529
- account: fiosdk_offline_1.FioActionParameters.FioNewFundsRequestActionAccount,
1530
- name: fiosdk_offline_1.FioActionParameters.FioNewFundsRequestActionName,
1531
- data: tx,
1532
- },
1533
- ],
1534
- };
1535
- log.debug(tag, "signTx: ", JSON.stringify(signTx));
1536
- return [4 /*yield*/, this.WALLET.fioSignTx(signTx)];
1537
- case 13:
1538
- res = _b.sent();
1539
- res.coin = "FIO";
1540
- res.type = transaction.type;
1541
- rawTx = res;
1542
- return [3 /*break*/, 14];
1543
- case 14: return [3 /*break*/, 22];
1544
- case 15:
1545
- if (!(transaction.network === 'osmosis' || transaction.network === 'OSMO')) return [3 /*break*/, 21];
1546
- log.debug(tag, "transaction: ", transaction);
1547
- tx = void 0;
1548
- signTx = void 0;
1549
- res = void 0;
1550
- amountNative = ATOM_BASE * parseFloat(transaction.amount);
1551
- amountNative = parseInt(amountNative.toString());
1552
- log.debug(tag, "amountNative: ", amountNative);
1553
- addressFrom = void 0;
1554
- if (!transaction.addressFrom) return [3 /*break*/, 16];
1555
- addressFrom = transaction.addressFrom;
1556
- return [3 /*break*/, 18];
1557
- case 16: return [4 /*yield*/, this.getMaster('OSMO')];
1558
- case 17:
1559
- addressFrom = _b.sent();
1560
- _b.label = 18;
1561
- case 18: return [4 /*yield*/, this.pioneerClient.instance.GetAccountInfo({ network: 'OSMO', address: addressFrom })];
1562
- case 19:
1563
- masterInfo = _b.sent();
1564
- masterInfo = masterInfo.data;
1565
- log.debug(tag, "masterInfo: ", masterInfo.data);
1566
- sequence = masterInfo.result.value.sequence;
1567
- account_number = masterInfo.result.value.account_number;
1568
- sequence = parseInt(sequence);
1569
- if (!sequence || isNaN(sequence))
1570
- sequence = 0;
1571
- sequence = sequence.toString();
1572
- chain_id = OSMO_CHAIN;
1573
- msg = void 0;
1574
- switch (transaction.type) {
1575
- case "delegate":
1576
- if (!transaction.validator)
1577
- throw Error("Missing validator address!");
1578
- msg = {
1579
- "type": "cosmos-sdk/MsgDelegate",
1580
- "value": {
1581
- "delegator_address": addressFrom,
1582
- "validator_address": transaction.validator,
1583
- "amount": {
1584
- "denom": "uosmo",
1585
- "amount": amountNative.toString()
1586
- }
1587
- }
1588
- };
1589
- break;
1590
- case "redelegate":
1591
- if (!transaction.validatorOld)
1592
- throw Error("102: Missing validatorOld!");
1593
- if (!transaction.validator)
1594
- throw Error("103: Missing validator!");
1595
- msg = {
1596
- "type": "cosmos-sdk/MsgBeginRedelegate",
1597
- "value": {
1598
- "delegator_address": addressFrom,
1599
- "validator_src_address": transaction.validatorOld,
1600
- "validator_dst_address": transaction.validator,
1601
- "amount": {
1602
- "denom": "uosmo",
1603
- "amount": amountNative.toString()
1604
- }
1605
- }
1606
- };
1607
- break;
1608
- case "osmosislpadd":
1609
- if (!transaction.poolId)
1610
- throw Error("102: Missing poolId!");
1611
- if (!transaction.shareOutAmount)
1612
- throw Error("103: Missing shareOutAmount!");
1613
- if (!transaction.tokenInMaxs)
1614
- throw Error("104: Missing tokenInMaxs!");
1615
- msg = {
1616
- "type": "osmosis/gamm/join-pool",
1617
- "value": {
1618
- "sender": addressFrom,
1619
- "poolId": transaction.poolId,
1620
- "shareOutAmount": transaction.shareOutAmount,
1621
- "tokenInMaxs": transaction.tokenInMaxs
1622
- }
1623
- };
1624
- break;
1625
- case "osmosisswap":
1626
- if (!transaction.routes)
1627
- throw Error("102: Missing routes!");
1628
- if (!transaction.tokenIn)
1629
- throw Error("103: Missing tokenIn!");
1630
- if (!transaction.tokenOutMinAmount)
1631
- throw Error("104: Missing tokenOutMinAmount!");
1632
- msg = {
1633
- "type": "osmosis/gamm/swap-exact-amount-in",
1634
- "value": {
1635
- "sender": addressFrom,
1636
- "routes": transaction.routes,
1637
- "tokenIn": transaction.tokenIn,
1638
- "tokenOutMinAmount": transaction.tokenOutMinAmount.toString()
1639
- }
1640
- };
1641
- break;
1642
- case "ibcWithdrawal":
1643
- //TODO
1644
- throw Error("TODO");
1645
- break;
1646
- case "ibcWithdrawal":
1647
- //TODO
1648
- throw Error("TODO");
1649
- break;
1650
- default:
1651
- throw Error("unsupported osmosis tx type: " + transaction.type);
1652
- //code block
1653
- }
1654
- txType = "cosmos-sdk/MsgSend";
1655
- gas = "290000";
1656
- fee = "2800";
1657
- if (transaction.priority === 0) {
1658
- gas = "0";
1659
- fee = "0";
1660
- }
1661
- memo = transaction.memo || "";
1662
- if (!msg)
1663
- throw Error('failed to make tx msg');
1664
- unsigned = {
1665
- "fee": {
1666
- "amount": [
1667
- {
1668
- "amount": fee,
1669
- "denom": "uosmo"
1670
- }
1671
- ],
1672
- "gas": gas
1673
- },
1674
- "memo": memo,
1675
- "msg": [
1676
- msg
1677
- ],
1678
- "signatures": null
1679
- };
1680
- if (!sequence)
1681
- throw Error("112: Failed to get sequence");
1682
- if (isNaN(sequence))
1683
- throw Error("113: Failed to get valid sequence");
1684
- if (!account_number)
1685
- throw Error("114: Failed to get account_number");
1686
- return [4 /*yield*/, this.WALLET.osmosisGetAddress({
1687
- addressNList: bip32ToAddressNList(HD_ATOM_KEYPATH),
1688
- showDisplay: false,
1689
- })];
1690
- case 20:
1691
- fromAddress = _b.sent();
1692
- log.debug(tag, "fromAddressHDwallet: ", fromAddress);
1693
- log.debug(tag, "fromAddress: ", addressFrom);
1694
- log.debug("res: ", prettyjson.render({
1695
- addressNList: bip32ToAddressNList(HD_ATOM_KEYPATH),
1696
- chain_id: chain_id,
1697
- account_number: account_number,
1698
- sequence: sequence,
1699
- tx: unsigned,
1700
- }));
1701
- atomTx = {
1702
- addressNList: bip32ToAddressNList(HD_ATOM_KEYPATH),
1703
- chain_id: 'osmosis-1',
1704
- account_number: account_number,
1705
- sequence: sequence,
1706
- tx: unsigned,
1707
- };
1708
- unsignedTx = {
1709
- network: network,
1710
- asset: network,
1711
- transaction: transaction,
1712
- HDwalletPayload: atomTx,
1713
- verbal: "osmosis transaction"
1714
- };
1715
- rawTx = unsignedTx;
1716
- return [3 /*break*/, 22];
1717
- case 21:
1718
- log.error(tag, "network not supported! ", transaction.network);
1719
- _b.label = 22;
1720
- case 22: return [2 /*return*/, rawTx];
1721
- case 23:
1722
- e_8 = _b.sent();
1723
- log.error(e_8);
1724
- throw e_8;
1725
- case 24: return [2 /*return*/];
1726
- }
1727
- });
1728
- });
1729
- };
1730
- // this.encrypt = function (msg:FioActionParameters.FioRequestContent,payerPubkey:string) {
1731
- // return encrypt_message(msg,payerPubkey);
1732
- // }
1733
- this.sendApproval = function (intent) {
1734
- return __awaiter(this, void 0, void 0, function () {
1735
- var tag, invocationId, approval, signedTx_1, broadcast_hook, e_9;
1736
- var _this = this;
1737
- return __generator(this, function (_a) {
1738
- switch (_a.label) {
1739
- case 0:
1740
- tag = TAG + " | sendApproval | ";
1741
- _a.label = 1;
1742
- case 1:
1743
- _a.trys.push([1, 3, , 4]);
1744
- invocationId = void 0;
1745
- if (!intent.invocationId) {
1746
- invocationId = "notset";
1747
- }
1748
- else {
1749
- invocationId = intent.invocationId;
1750
- }
1751
- if (intent.coin && intent.coin !== 'ETH')
1752
- throw Error("approvals are ETH only!");
1753
- intent.coin = "ETH";
1754
- if (!intent.contract)
1755
- throw Error("102: contract required!");
1756
- if (!intent.tokenAddress)
1757
- throw Error("103: tokenAddress required!");
1758
- if (!intent.amount)
1759
- throw Error("104: amount required!");
1760
- approval = {
1761
- contract: intent.contract,
1762
- tokenAddress: intent.tokenAddress,
1763
- amount: intent.amount
1764
- };
1765
- return [4 /*yield*/, this.buildApproval(approval)];
1766
- case 2:
1767
- signedTx_1 = _a.sent();
1768
- log.debug(tag, "signedTx: ", signedTx_1);
1769
- if (invocationId)
1770
- signedTx_1.invocationId = invocationId;
1771
- log.debug(tag, "invocationId: ", invocationId);
1772
- signedTx_1.broadcasted = false;
1773
- broadcast_hook = function () { return __awaiter(_this, void 0, void 0, function () {
1774
- var broadcastResult, e_10;
1775
- return __generator(this, function (_a) {
1776
- switch (_a.label) {
1777
- case 0:
1778
- _a.trys.push([0, 2, , 3]);
1779
- log.debug(tag, "signedTx: ", signedTx_1);
1780
- return [4 /*yield*/, this.broadcastTransaction('ETH', signedTx_1)];
1781
- case 1:
1782
- broadcastResult = _a.sent();
1783
- log.debug(tag, "broadcastResult: ", broadcastResult);
1784
- return [3 /*break*/, 3];
1785
- case 2:
1786
- e_10 = _a.sent();
1787
- log.error(tag, "Failed to broadcast transaction!");
1788
- return [3 /*break*/, 3];
1789
- case 3: return [2 /*return*/];
1790
- }
1791
- });
1792
- }); };
1793
- //broadcast hook
1794
- if (!intent.noBroadcast) {
1795
- signedTx_1.broadcasted = true;
1796
- }
1797
- else {
1798
- signedTx_1.noBroadcast = true;
1799
- }
1800
- //if noBroadcast we MUST still release the inovation
1801
- //notice we pass noBroadcast to the broadcast post request
1802
- //also Notice NO asyc here! tx lifecycle hooks bro!
1803
- broadcast_hook();
1804
- signedTx_1.invocationId = invocationId;
1805
- //
1806
- if (!signedTx_1.txid)
1807
- throw Error("103: Pre-broadcast txid hash not implemented!");
1808
- return [2 /*return*/, signedTx_1];
1809
- case 3:
1810
- e_9 = _a.sent();
1811
- log.error(tag, e_9);
1812
- throw Error(e_9);
1813
- case 4: return [2 /*return*/];
1814
- }
1815
- });
1816
- });
1817
- };
1818
- this.sendToAddress = function (intent) {
1819
- return __awaiter(this, void 0, void 0, function () {
1820
- var tag, invocationId, addressFrom, balance, transaction, unSignedTx, e_11;
1821
- return __generator(this, function (_a) {
1822
- switch (_a.label) {
1823
- case 0:
1824
- tag = TAG + " | sendToAddress | ";
1825
- _a.label = 1;
1826
- case 1:
1827
- _a.trys.push([1, 6, , 7]);
1828
- invocationId = void 0;
1829
- if (!intent.invocationId) {
1830
- invocationId = "notset";
1831
- }
1832
- else {
1833
- invocationId = intent.invocationId;
1834
- }
1835
- intent.asset = intent.asset.toUpperCase();
1836
- log.debug(tag, "params: ", intent);
1837
- if (!intent.amount)
1838
- throw Error("Amount required!");
1839
- if (!intent.address)
1840
- throw Error("address required!");
1841
- return [4 /*yield*/, this.getMaster(intent.asset)];
1842
- case 2:
1843
- addressFrom = _a.sent();
1844
- log.debug(tag, "addressFrom: ", addressFrom);
1845
- if (!(intent.amount === 'all')) return [3 /*break*/, 4];
1846
- return [4 /*yield*/, this.getBalance(intent.asset)];
1847
- case 3:
1848
- balance = _a.sent();
1849
- log.debug(tag, "balance: ", balance);
1850
- //subtract fees
1851
- intent.amount = String(parseFloat(balance) - 0.08);
1852
- log.debug(tag, "ALL amount: ", intent.amount);
1853
- if (parseFloat(intent.amount) < 0) {
1854
- throw Error("Balance lower then expected fee!");
1855
- }
1856
- _a.label = 4;
1857
- case 4:
1858
- transaction = {
1859
- network: intent.network,
1860
- asset: intent.asset,
1861
- addressTo: intent.address,
1862
- addressFrom: addressFrom,
1863
- amount: intent.amount,
1864
- };
1865
- if (intent.memo)
1866
- transaction.memo = intent.memo;
1867
- if (intent.noBroadcast)
1868
- transaction.noBroadcast = intent.noBroadcast;
1869
- return [4 /*yield*/, this.buildTransfer(transaction)];
1870
- case 5:
1871
- unSignedTx = _a.sent();
1872
- log.debug(tag, "unSignedTx: ", unSignedTx);
1873
- if (invocationId)
1874
- unSignedTx.invocationId = invocationId;
1875
- log.debug(tag, "transaction: ", transaction);
1876
- unSignedTx.broadcasted = false;
1877
- if (!intent.noBroadcast) {
1878
- unSignedTx.broadcasted = true;
1879
- }
1880
- else {
1881
- unSignedTx.noBroadcast = true;
1882
- }
1883
- unSignedTx.invocationId = invocationId;
1884
- return [2 /*return*/, unSignedTx];
1885
- case 6:
1886
- e_11 = _a.sent();
1887
- log.error(tag, e_11);
1888
- throw Error(e_11);
1889
- case 7: return [2 /*return*/];
1890
- }
1891
- });
1892
- });
1893
- };
1894
- this.signTransaction = function (unsignedTx) {
1895
- var _a;
1896
- return __awaiter(this, void 0, void 0, function () {
1897
- var tag, signedTx, network_1, res, decoded, txid, res, txFinal, broadcastString, buffer, hash, res, txFinal, broadcastString, buffer, txid, res, txFinal, broadcastString, buffer, txid, signedTxResponse, pubkeySigHex, buffer, hash, e_12;
1898
- return __generator(this, function (_b) {
1899
- switch (_b.label) {
1900
- case 0:
1901
- tag = TAG + " | signTransaction | ";
1902
- _b.label = 1;
1903
- case 1:
1904
- _b.trys.push([1, 15, , 16]);
1905
- log.debug(tag, "unsignedTx: ", unsignedTx);
1906
- signedTx = {};
1907
- if (!unsignedTx.network && unsignedTx.transaction)
1908
- unsignedTx.network = unsignedTx.transaction.network;
1909
- network_1 = unsignedTx.network;
1910
- if (!network_1)
1911
- throw Error("102: invalid unsinged tx! missing network!");
1912
- if (!(UTXO_COINS.indexOf(network_1) >= 0)) return [3 /*break*/, 3];
1913
- log.debug(tag, "HDwalletPayload: ", unsignedTx.HDwalletPayload);
1914
- if (UTXO_COINS.indexOf(unsignedTx.HDwalletPayload.network) >= 0) {
1915
- //opps convert
1916
- unsignedTx.HDwalletPayload.network = COIN_MAP_KEEPKEY_LONG[unsignedTx.HDwalletPayload.network];
1917
- }
1918
- return [4 /*yield*/, this.WALLET.btcSignTx(unsignedTx.HDwalletPayload)];
1919
- case 2:
1920
- res = _b.sent();
1921
- log.debug(tag, "res: ", res);
1922
- //
1923
- signedTx = {
1924
- txid: res.txid,
1925
- network: network_1,
1926
- serialized: res.serializedTx
1927
- };
1928
- return [3 /*break*/, 14];
1929
- case 3:
1930
- if (!(network_1 === 'ETH')) return [3 /*break*/, 5];
1931
- //TODO fix tokens
1932
- log.debug("unsignedTxETH: ", unsignedTx);
1933
- return [4 /*yield*/, this.WALLET.ethSignTx(unsignedTx.HDwalletPayload)
1934
- //debug https://flightwallet.github.io/decode-eth-tx/
1935
- //verify from address correct
1936
- ];
1937
- case 4:
1938
- signedTx = _b.sent();
1939
- decoded = ethers_1.ethers.utils.parseTransaction(signedTx.serialized);
1940
- signedTx.decoded = decoded;
1941
- log.debug(tag, "decoded: ", decoded);
1942
- log.debug(tag, "decoded.from: ", decoded.from);
1943
- log.debug(tag, "addressFrom: ", (_a = unsignedTx === null || unsignedTx === void 0 ? void 0 : unsignedTx.transaction) === null || _a === void 0 ? void 0 : _a.addressFrom);
1944
- // let addressFromUnsignedTx
1945
- // if(unsignedTx?.swap){
1946
- // //TODO fixme (add from address to swap payload)
1947
- // addressFromUnsignedTx =
1948
- // }
1949
- // if(unsignedTx?.transaction?.addressFrom !== decoded.from){
1950
- // throw Error("Invalid transaction! from address mismatch!")
1951
- // }
1952
- //TODO verify more
1953
- //verify amounts sane
1954
- //txid
1955
- //const txHash = await web3.utils.sha3(signed.rawTransaction);
1956
- if (!signedTx.serialized)
1957
- throw Error("Failed to sign!");
1958
- txid = keccak256(signedTx.serialized).toString('hex');
1959
- txid = "0x" + txid;
1960
- log.debug(tag, "txid: ", txid);
1961
- signedTx.txid = txid;
1962
- signedTx.params = unsignedTx.transaction; //input
1963
- return [3 /*break*/, 14];
1964
- case 5:
1965
- if (!(network_1 === 'RUNE')) return [3 /*break*/, 7];
1966
- return [4 /*yield*/, this.WALLET.thorchainSignTx(unsignedTx.HDwalletPayload)];
1967
- case 6:
1968
- res = _b.sent();
1969
- log.debug("res: ", prettyjson.render(res));
1970
- log.debug("res*****: ", res);
1971
- txFinal = void 0;
1972
- txFinal = res;
1973
- txFinal.signatures = res.signatures;
1974
- log.debug("FINAL: ****** ", txFinal);
1975
- broadcastString = {
1976
- tx: txFinal,
1977
- type: "cosmos-sdk/StdTx",
1978
- mode: "sync"
1979
- };
1980
- buffer = Buffer.from(JSON.stringify(txFinal), 'base64');
1981
- hash = sha256(buffer).toString().toUpperCase();
1982
- signedTx = {
1983
- txid: hash,
1984
- network: network_1,
1985
- serialized: JSON.stringify(broadcastString)
1986
- };
1987
- return [3 /*break*/, 14];
1988
- case 7:
1989
- if (!(network_1 === 'ATOM')) return [3 /*break*/, 9];
1990
- return [4 /*yield*/, this.WALLET.cosmosSignTx(unsignedTx.HDwalletPayload)];
1991
- case 8:
1992
- res = _b.sent();
1993
- log.debug("res: ", prettyjson.render(res));
1994
- log.debug("res*****: ", res);
1995
- txFinal = void 0;
1996
- txFinal = res;
1997
- txFinal.signatures = res.signatures;
1998
- log.debug("FINAL: ****** ", txFinal);
1999
- broadcastString = {
2000
- tx: txFinal,
2001
- type: "cosmos-sdk/StdTx",
2002
- mode: "sync"
2003
- };
2004
- buffer = Buffer.from(JSON.stringify(broadcastString), 'base64');
2005
- txid = cryptoTools.createHash('sha256').update(buffer).digest('hex').toUpperCase();
2006
- signedTx = {
2007
- txid: txid,
2008
- network: network_1,
2009
- serialized: JSON.stringify(broadcastString)
2010
- };
2011
- return [3 /*break*/, 14];
2012
- case 9:
2013
- if (!(network_1 === 'OSMO')) return [3 /*break*/, 11];
2014
- return [4 /*yield*/, this.WALLET.osmosisSignTx(unsignedTx.HDwalletPayload)];
2015
- case 10:
2016
- res = _b.sent();
2017
- log.debug("res: ", prettyjson.render(res));
2018
- log.debug("res*****: ", res);
2019
- txFinal = void 0;
2020
- txFinal = res;
2021
- txFinal.signatures = res.signatures;
2022
- log.debug("FINAL: ****** ", txFinal);
2023
- broadcastString = {
2024
- tx: txFinal,
2025
- type: "cosmos-sdk/StdTx",
2026
- mode: "sync"
2027
- };
2028
- buffer = Buffer.from(JSON.stringify(broadcastString), 'base64');
2029
- txid = cryptoTools.createHash('sha256').update(buffer).digest('hex').toUpperCase();
2030
- signedTx = {
2031
- txid: txid,
2032
- network: network_1,
2033
- serialized: JSON.stringify(broadcastString)
2034
- };
2035
- return [3 /*break*/, 14];
2036
- case 11:
2037
- if (!(network_1 === 'BNB')) return [3 /*break*/, 13];
2038
- return [4 /*yield*/, this.WALLET.binanceSignTx(unsignedTx.HDwalletPayload)];
2039
- case 12:
2040
- signedTxResponse = _b.sent();
2041
- log.debug(tag, "**** signedTxResponse: ", signedTxResponse);
2042
- log.debug(tag, "**** signedTxResponse: ", JSON.stringify(signedTxResponse));
2043
- pubkeySigHex = signedTxResponse.signatures.pub_key.toString('hex');
2044
- log.debug(tag, "pubkeySigHex: ", pubkeySigHex);
2045
- buffer = Buffer.from(signedTxResponse.serialized, 'base64');
2046
- hash = cryptoTools.createHash('sha256').update(buffer).digest('hex').toUpperCase();
2047
- signedTx = {
2048
- txid: hash,
2049
- serialized: signedTxResponse.serialized
2050
- };
2051
- return [3 /*break*/, 14];
2052
- case 13:
2053
- //TODO EOS
2054
- //FIO
2055
- throw Error("network not supported! " + network_1);
2056
- case 14:
2057
- //carry over unsigned params to signed
2058
- if (unsignedTx.transaction && unsignedTx.transaction.noBroadcast)
2059
- signedTx.noBroadcast = true;
2060
- if (unsignedTx.invocationId)
2061
- signedTx.invocationId = unsignedTx.invocationId;
2062
- return [2 /*return*/, signedTx];
2063
- case 15:
2064
- e_12 = _b.sent();
2065
- log.error(tag, "e: ", e_12);
2066
- throw e_12;
2067
- case 16: return [2 /*return*/];
2068
- }
2069
- });
2070
- });
2071
- };
2072
- this.buildTransfer = function (transaction) {
2073
- return __awaiter(this, void 0, void 0, function () {
2074
- var tag, network_2, asset, address, amount, fee, paths, memo, addressFrom, rawTx, pubkeyInfo, input, unspentInputs, utxos, i, input_1, utxo, feeRateInfo, feeRate, amountSat, targets, totalInSatoshi, i, amountInSat, valueIn, valueOut, selectedResults, inputs, outputs, i, inputInfo, input_2, changeAddressIndex, xpub, scriptType, coin, account, index, isTestnet_1, changeAddress, type_1, i, outputInfo, output, output, longName, hdwalletTxDescription, unsignedTx, balanceEth, nonceRemote, nonce, gas_limit, gas_price, txParams, amountNative, ethPathInfo, masterPathEth, fromAddressHDwallet, chainId, ethTx, unsignedTx, amountNative, masterInfo, sequence, account_number, txType, gas, fee_1, memo_1, unsigned, chain_id, fromAddress, runeTx, unsignedTx, amountNative, masterInfo, sequence, account_number, txType, gas, fee_2, memo_2, unsigned, chain_id, fromAddress, atomTx, unsignedTx, amountNative, masterInfo, sequence, account_number, txType, gas, fee_3, memo_3, unsigned, chain_id, fromAddress, atomTx, unsignedTx, accountInfo, sequence, account_number, pubkey, bnbTx, binanceTx, unsignedTx, e_13;
2075
- return __generator(this, function (_a) {
2076
- switch (_a.label) {
2077
- case 0:
2078
- tag = TAG + " | build_transfer | ";
2079
- _a.label = 1;
2080
- case 1:
2081
- _a.trys.push([1, 33, , 34]);
2082
- log.debug(tag, "transaction: ", transaction);
2083
- network_2 = transaction.network.toUpperCase();
2084
- asset = transaction.asset.toUpperCase();
2085
- address = transaction.address;
2086
- if (!address)
2087
- address = transaction.addressTo;
2088
- amount = transaction.amount;
2089
- fee = transaction.fee;
2090
- paths = this.paths();
2091
- log.debug(tag, "paths: ", paths);
2092
- if (!paths)
2093
- throw Error("101: unable to get paths!");
2094
- if (!network_2)
2095
- throw Error("102: Invalid transaction missing address!");
2096
- if (!address)
2097
- throw Error("103: Invalid transaction missing address!");
2098
- if (!amount)
2099
- throw Error("104: Invalid transaction missing amount!");
2100
- if (!fee)
2101
- throw Error("105: Invalid transaction missing fee!");
2102
- memo = transaction.memo;
2103
- addressFrom = void 0;
2104
- if (!transaction.addressFrom) return [3 /*break*/, 2];
2105
- addressFrom = transaction.addressFrom;
2106
- return [3 /*break*/, 4];
2107
- case 2: return [4 /*yield*/, this.getMaster(network_2)];
2108
- case 3:
2109
- addressFrom = _a.sent();
2110
- _a.label = 4;
2111
- case 4:
2112
- if (!addressFrom)
2113
- throw Error("102: unable to get master address! ");
2114
- log.debug(tag, "addressFrom: ", addressFrom);
2115
- transaction.addressFrom = addressFrom;
2116
- rawTx = void 0;
2117
- if (!(UTXO_COINS.indexOf(network_2) >= 0)) return [3 /*break*/, 11];
2118
- log.debug(tag, "Build UTXO tx! ", network_2);
2119
- //list unspent
2120
- log.debug(tag, "network: ", network_2);
2121
- log.debug(tag, "xpub: ", this.PUBLIC_WALLET[network_2].xpub);
2122
- log.debug(tag, "zpub: ", this.PUBLIC_WALLET[network_2].zpub);
2123
- log.debug(tag, "pubkey: ", this.PUBLIC_WALLET[network_2].pubkey);
2124
- pubkeyInfo = this.PUBLIC_WALLET[network_2];
2125
- input = { network: network_2, xpub: this.PUBLIC_WALLET[network_2].pubkey };
2126
- log.debug(tag, "input: ", input);
2127
- return [4 /*yield*/, this.pioneerClient.instance.ListUnspent({ network: network_2, xpub: input.xpub })];
2128
- case 5:
2129
- unspentInputs = _a.sent();
2130
- unspentInputs = unspentInputs.data;
2131
- log.debug(tag, "unspentInputs: ", unspentInputs);
2132
- utxos = [];
2133
- for (i = 0; i < unspentInputs.length; i++) {
2134
- input_1 = unspentInputs[i];
2135
- utxo = {
2136
- txId: input_1.txid,
2137
- vout: input_1.vout,
2138
- value: parseInt(input_1.value),
2139
- nonWitnessUtxo: Buffer.from(input_1.hex, 'hex'),
2140
- hex: input_1.hex,
2141
- tx: input_1.tx,
2142
- path: input_1.path
2143
- //TODO if segwit
2144
- // witnessUtxo: {
2145
- // script: Buffer.from(input.hex, 'hex'),
2146
- // value: 10000 // 0.0001 BTC and is the exact same as the value above
2147
- // }
2148
- };
2149
- utxos.push(utxo);
2150
- }
2151
- //if no utxo's
2152
- if (utxos.length === 0) {
2153
- throw Error("101 YOUR BROKE! no UTXO's found! ");
2154
- }
2155
- return [4 /*yield*/, this.pioneerClient.instance.GetFeeInfo({ coin: network_2 })];
2156
- case 6:
2157
- feeRateInfo = _a.sent();
2158
- feeRateInfo = feeRateInfo.data;
2159
- log.debug(tag, "feeRateInfo: ", feeRateInfo);
2160
- feeRate = void 0;
2161
- //TODO dynamic all the things
2162
- if (network_2 === 'BTC') {
2163
- feeRate = feeRateInfo;
2164
- }
2165
- else if (network_2 === 'BCH') {
2166
- feeRate = 2;
2167
- }
2168
- else if (network_2 === 'LTC') {
2169
- feeRate = 4;
2170
- }
2171
- else {
2172
- throw Error("Fee's not configured for network:" + network_2);
2173
- }
2174
- log.debug(tag, "feeRate: ", feeRate);
2175
- if (!feeRate)
2176
- throw Error("Can not build TX without fee Rate!");
2177
- amountSat = parseFloat(amount) * 100000000;
2178
- amountSat = parseInt(amountSat.toString());
2179
- log.debug(tag, "amount satoshi: ", amountSat);
2180
- targets = [
2181
- {
2182
- address: address,
2183
- value: amountSat
2184
- }
2185
- ];
2186
- totalInSatoshi = 0;
2187
- for (i = 0; i < utxos.length; i++) {
2188
- amountInSat = utxos[i].value;
2189
- totalInSatoshi = totalInSatoshi + amountInSat;
2190
- }
2191
- log.debug(tag, "totalInSatoshi: ", totalInSatoshi);
2192
- log.debug(tag, "totalInBase: ", nativeToBaseAmount(network_2, totalInSatoshi));
2193
- return [4 /*yield*/, coincap.getValue(network_2, nativeToBaseAmount(network_2, totalInSatoshi))];
2194
- case 7:
2195
- valueIn = _a.sent();
2196
- log.debug(tag, "totalInValue: ", valueIn);
2197
- //amount out
2198
- log.debug(tag, "amountOutSat: ", amountSat);
2199
- log.debug(tag, "amountOutBase: ", amount);
2200
- return [4 /*yield*/, coincap.getValue(network_2, nativeToBaseAmount(network_2, amountSat))];
2201
- case 8:
2202
- valueOut = _a.sent();
2203
- log.debug(tag, "valueOut: ", valueOut);
2204
- if (valueOut < 1) {
2205
- if (network_2 === 'BCH') {
2206
- log.debug(tag, " God bless you sir's :BCH:");
2207
- }
2208
- else {
2209
- log.debug("ALERT DUST! sending less that 1usd. (hope you know what you are doing)");
2210
- }
2211
- //Expensive networks
2212
- if (["BTC", "ETH", "RUNE"].indexOf(network_2) >= 0) {
2213
- throw Error("You dont want to do this! sending < 1usd on expensive network");
2214
- }
2215
- }
2216
- if (nativeToBaseAmount(network_2, totalInSatoshi) < amount) {
2217
- throw Error("Sum of input less than output! YOUR BROKE! ");
2218
- }
2219
- log.debug(tag, "inputs coinselect algo: ", { utxos: utxos, targets: targets, feeRate: feeRate });
2220
- selectedResults = coinSelect(utxos, targets, feeRate);
2221
- log.debug(tag, "result coinselect algo: ", selectedResults);
2222
- //value of all outputs
2223
- //amount fee in USD
2224
- //if
2225
- if (!selectedResults.inputs) {
2226
- throw Error("Fee exceeded total available inputs!");
2227
- }
2228
- inputs = [];
2229
- outputs = [];
2230
- for (i = 0; i < selectedResults.inputs.length; i++) {
2231
- inputInfo = selectedResults.inputs[i];
2232
- log.debug(tag, "inputInfo: ", inputInfo);
2233
- input_2 = {
2234
- addressNList: support.bip32ToAddressNList(inputInfo.path),
2235
- scriptType: pubkeyInfo.script_type,
2236
- amount: String(inputInfo.value),
2237
- vout: inputInfo.vout,
2238
- txid: inputInfo.txId,
2239
- segwit: false,
2240
- hex: inputInfo.hex,
2241
- tx: inputInfo.tx
2242
- };
2243
- inputs.push(input_2);
2244
- }
2245
- log.debug(tag, "pubkeyInfo: change: ", pubkeyInfo);
2246
- return [4 /*yield*/, this.pioneerClient.instance.GetChangeAddress({ network: network_2, xpub: input.xpub })];
2247
- case 9:
2248
- changeAddressIndex = _a.sent();
2249
- changeAddressIndex = changeAddressIndex.data.changeIndex;
2250
- xpub = input.xpub;
2251
- scriptType = pubkeyInfo.script_type;
2252
- coin = network_2;
2253
- account = 0 //TODO adjustable by pubkey data?
2254
- ;
2255
- index = changeAddressIndex;
2256
- isTestnet_1 = false;
2257
- log.debug(tag, "input: ", { xpub: xpub, scriptType: scriptType, coin: coin, account: account, index: index, isChange: true, isTestnet: isTestnet_1 });
2258
- return [4 /*yield*/, get_address_from_xpub(xpub, scriptType, coin, account, index, true, isTestnet_1)];
2259
- case 10:
2260
- changeAddress = _a.sent();
2261
- log.debug(tag, "changeAddress: ", changeAddress);
2262
- if (!changeAddress)
2263
- throw Error("103 Failed to get new change address!");
2264
- //if bch convert format
2265
- if (network_2 === 'BCH') {
2266
- type_1 = bchaddr.detectAddressFormat(changeAddress);
2267
- log.debug(tag, "type: ", type_1);
2268
- if (type_1 === 'cashaddr') {
2269
- changeAddress = bchaddr.toLegacyAddress(changeAddress);
2270
- }
2271
- }
2272
- for (i = 0; i < selectedResults.outputs.length; i++) {
2273
- outputInfo = selectedResults.outputs[i];
2274
- if (outputInfo.address) {
2275
- output = {
2276
- address: address,
2277
- addressType: "spend",
2278
- scriptType: pubkeyInfo.stript_type,
2279
- amount: String(outputInfo.value),
2280
- isChange: false,
2281
- };
2282
- outputs.push(output);
2283
- }
2284
- else {
2285
- output = {
2286
- address: changeAddress,
2287
- addressType: "spend",
2288
- scriptType: pubkeyInfo.stript_type,
2289
- amount: String(outputInfo.value),
2290
- isChange: true,
2291
- };
2292
- outputs.push(output);
2293
- }
2294
- }
2295
- longName = void 0;
2296
- if (network_2 === 'BCH') {
2297
- longName = 'BitcoinCash';
2298
- }
2299
- else if (network_2 === 'LTC') {
2300
- longName = 'Litecoin';
2301
- if (isTestnet_1) {
2302
- longName = 'Testnet';
2303
- }
2304
- }
2305
- else if (network_2 === 'BTC') {
2306
- longName = 'Bitcoin';
2307
- if (isTestnet_1) {
2308
- longName = 'Testnet';
2309
- }
2310
- }
2311
- else {
2312
- throw Error("UTXO coin: " + network_2 + " Not supported yet! ");
2313
- }
2314
- hdwalletTxDescription = {
2315
- opReturnData: memo,
2316
- coin: longName,
2317
- inputs: inputs,
2318
- outputs: outputs,
2319
- version: 1,
2320
- locktime: 0,
2321
- };
2322
- unsignedTx = {
2323
- network: network_2,
2324
- asset: network_2,
2325
- transaction: transaction,
2326
- HDwalletPayload: hdwalletTxDescription,
2327
- verbal: "UTXO transaction"
2328
- };
2329
- rawTx = unsignedTx;
2330
- return [3 /*break*/, 32];
2331
- case 11:
2332
- if (!(network_2 === 'ETH')) return [3 /*break*/, 20];
2333
- //TODO fix tokens
2334
- log.debug(tag, "checkpoint");
2335
- return [4 /*yield*/, this.getBalance('ETH')];
2336
- case 12:
2337
- balanceEth = _a.sent();
2338
- log.debug(tag, "balanceEth: ", balanceEth);
2339
- return [4 /*yield*/, this.pioneerClient.instance.GetNonce(addressFrom)];
2340
- case 13:
2341
- nonceRemote = _a.sent();
2342
- nonceRemote = nonceRemote.data;
2343
- nonce = transaction.nonce || nonceRemote;
2344
- log.debug(tag, "nonce: ", nonce);
2345
- gas_limit = 80000;
2346
- gas_price = void 0;
2347
- //overrides
2348
- log.debug(tag, "transaction.fee: ", transaction.fee);
2349
- if (!transaction.fee) return [3 /*break*/, 16];
2350
- if (!transaction.fee.priority) return [3 /*break*/, 15];
2351
- log.debug(tag, "Selecting fee based on priority");
2352
- return [4 /*yield*/, this.pioneerClient.instance.GetGasPrice()];
2353
- case 14:
2354
- //get gas recomendations
2355
- gas_price = _a.sent();
2356
- gas_price = gas_price.data;
2357
- log.debug(tag, "gas_price: ", gas_price);
2358
- if (transaction.fee.priority === 2) {
2359
- log.debug(tag, "setting priority 2 ");
2360
- gas_price = gas_price * 0.5;
2361
- gas_price = parseInt(String(gas_price));
2362
- log.debug(tag, "gas_price: ", gas_price);
2363
- }
2364
- return [3 /*break*/, 16];
2365
- case 15:
2366
- log.debug(tag, "Selecting fee based on hard coded value");
2367
- //TODO other units?
2368
- if (transaction.fee.value && transaction.fee.units === 'gwei') {
2369
- log.debug(tag, "setting fee value: ", transaction.fee.value);
2370
- gas_price = transaction.fee.value * GIG;
2371
- }
2372
- if (transaction.fee.gasLimit) {
2373
- gas_limit = transaction.fee.gasLimit;
2374
- }
2375
- _a.label = 16;
2376
- case 16:
2377
- if (!!gas_price) return [3 /*break*/, 18];
2378
- log.debug(tag, "Getting Fee Level from remote!");
2379
- return [4 /*yield*/, this.pioneerClient.instance.GetGasPrice()];
2380
- case 17:
2381
- gas_price = _a.sent();
2382
- gas_price = gas_price.data;
2383
- _a.label = 18;
2384
- case 18:
2385
- log.debug(tag, "gas_price: ", gas_price);
2386
- gas_price = parseInt(String(gas_price));
2387
- txParams = void 0;
2388
- if (asset === "ETH") {
2389
- amountNative = parseFloat(amount) * support.getBase('ETH');
2390
- amountNative = Number(parseInt(String(amountNative)));
2391
- txParams = {
2392
- nonce: nonce,
2393
- to: address,
2394
- gasPrice: gas_price,
2395
- gasLimit: gas_limit,
2396
- value: amountNative,
2397
- data: memo
2398
- };
2399
- log.debug(tag, "txParams: ", txParams);
2400
- }
2401
- else {
2402
- throw Error("103: tokens incomplete!");
2403
- //TODO tokens
2404
- }
2405
- if (!txParams)
2406
- throw Error("tokens not supported");
2407
- ethPathInfo = paths.filter(function (e) { return e.network === 'ETH'; });
2408
- log.debug(tag, "ethPathInfo: ", ethPathInfo);
2409
- if (!ethPathInfo[0])
2410
- throw Error("103: unable to get eth path info! ");
2411
- masterPathEth = addressNListToBIP32(ethPathInfo[0].addressNListMaster);
2412
- log.debug(tag, "masterPathEth: ", masterPathEth);
2413
- log.debug(tag, "masterPathEth: ", "m/44'/60'/0'/0/0");
2414
- log.debug(tag, "txParams: ", txParams);
2415
- return [4 /*yield*/, this.WALLET.ethGetAddress({
2416
- addressNList: bip32ToAddressNList(masterPathEth),
2417
- showDisplay: false,
2418
- })];
2419
- case 19:
2420
- fromAddressHDwallet = _a.sent();
2421
- log.debug(tag, "fromAddressHDwallet: ", fromAddressHDwallet);
2422
- log.debug(tag, "fromAddress: ", addressFrom);
2423
- if (addressFrom !== fromAddressHDwallet) {
2424
- throw Error("666: Address mismatch! refusing to sign!");
2425
- }
2426
- chainId = 1;
2427
- if (this.isTestnet) {
2428
- chainId = 3; //ropsten
2429
- }
2430
- ethTx = {
2431
- addressNList: bip32ToAddressNList(masterPathEth),
2432
- nonce: web3_utils_1.numberToHex(txParams.nonce),
2433
- gasPrice: web3_utils_1.numberToHex(txParams.gasPrice),
2434
- gasLimit: web3_utils_1.numberToHex(txParams.gasLimit),
2435
- value: web3_utils_1.numberToHex(txParams.value || 0),
2436
- to: txParams.to,
2437
- data: txParams.data,
2438
- chainId: chainId
2439
- };
2440
- log.debug("TX: ", JSON.stringify(ethTx));
2441
- unsignedTx = {
2442
- network: network_2,
2443
- asset: network_2,
2444
- transaction: transaction,
2445
- HDwalletPayload: ethTx,
2446
- verbal: "Ethereum transaction"
2447
- };
2448
- rawTx = unsignedTx;
2449
- return [3 /*break*/, 32];
2450
- case 20:
2451
- if (!(network_2 === 'RUNE')) return [3 /*break*/, 23];
2452
- amountNative = RUNE_BASE * parseFloat(amount);
2453
- amountNative = parseInt(amountNative.toString());
2454
- //get account number
2455
- log.debug(tag, "addressFrom: ", addressFrom);
2456
- return [4 /*yield*/, this.pioneerClient.instance.GetAccountInfo({ network: 'RUNE', address: addressFrom })];
2457
- case 21:
2458
- masterInfo = _a.sent();
2459
- masterInfo = masterInfo.data;
2460
- log.debug(tag, "masterInfo: ", masterInfo.data);
2461
- sequence = masterInfo.result.value.sequence || 0;
2462
- account_number = masterInfo.result.value.account_number;
2463
- sequence = parseInt(sequence);
2464
- sequence = sequence.toString();
2465
- txType = "thorchain/MsgSend";
2466
- gas = "650000";
2467
- fee_1 = "0";
2468
- memo_1 = transaction.memo || "";
2469
- unsigned = {
2470
- "fee": {
2471
- "amount": [
2472
- {
2473
- "amount": fee_1,
2474
- "denom": "rune"
2475
- }
2476
- ],
2477
- "gas": gas
2478
- },
2479
- "memo": memo_1,
2480
- "msg": [
2481
- {
2482
- "type": txType,
2483
- "value": {
2484
- "amount": [
2485
- {
2486
- "amount": amountNative.toString(),
2487
- "denom": "rune"
2488
- }
2489
- ],
2490
- "from_address": addressFrom,
2491
- "to_address": address
2492
- }
2493
- }
2494
- ],
2495
- "signatures": null
2496
- };
2497
- chain_id = RUNE_CHAIN;
2498
- if (!sequence)
2499
- throw Error("112: Failed to get sequence");
2500
- if (!account_number)
2501
- account_number = 0;
2502
- return [4 /*yield*/, this.WALLET.thorchainGetAddress({
2503
- addressNList: bip32ToAddressNList(HD_RUNE_KEYPATH),
2504
- showDisplay: false,
2505
- })];
2506
- case 22:
2507
- fromAddress = _a.sent();
2508
- log.debug(tag, "fromAddressHDwallet: ", fromAddress);
2509
- log.debug(tag, "fromAddress: ", addressFrom);
2510
- log.debug("res: ", prettyjson.render({
2511
- addressNList: bip32ToAddressNList(HD_RUNE_KEYPATH),
2512
- chain_id: chain_id,
2513
- account_number: account_number,
2514
- sequence: sequence,
2515
- tx: unsigned,
2516
- }));
2517
- if (fromAddress !== addressFrom) {
2518
- log.error(tag, "fromAddress: ", fromAddress);
2519
- log.error(tag, "addressFrom: ", addressFrom);
2520
- throw Error("Can not sign, address mismatch");
2521
- }
2522
- runeTx = {
2523
- addressNList: bip32ToAddressNList(HD_RUNE_KEYPATH),
2524
- chain_id: chain_id,
2525
- account_number: account_number,
2526
- sequence: sequence,
2527
- tx: unsigned,
2528
- };
2529
- unsignedTx = {
2530
- network: network_2,
2531
- asset: network_2,
2532
- transaction: transaction,
2533
- HDwalletPayload: runeTx,
2534
- verbal: "Thorchain transaction"
2535
- };
2536
- rawTx = unsignedTx;
2537
- return [3 /*break*/, 32];
2538
- case 23:
2539
- if (!(network_2 === 'ATOM')) return [3 /*break*/, 26];
2540
- amountNative = ATOM_BASE * parseFloat(amount);
2541
- amountNative = parseInt(amountNative.toString());
2542
- //get account number
2543
- log.debug(tag, "addressFrom: ", addressFrom);
2544
- return [4 /*yield*/, this.pioneerClient.instance.GetAccountInfo({ network: 'ATOM', address: addressFrom })];
2545
- case 24:
2546
- masterInfo = _a.sent();
2547
- masterInfo = masterInfo.data;
2548
- log.debug(tag, "masterInfo: ", masterInfo.data);
2549
- sequence = masterInfo.result.value.sequence;
2550
- account_number = masterInfo.result.value.account_number;
2551
- sequence = parseInt(sequence);
2552
- sequence = sequence.toString();
2553
- txType = "cosmos-sdk/MsgSend";
2554
- gas = "100000";
2555
- fee_2 = "1000";
2556
- memo_2 = transaction.memo || "";
2557
- unsigned = {
2558
- "fee": {
2559
- "amount": [
2560
- {
2561
- "amount": fee_2,
2562
- "denom": "uatom"
2563
- }
2564
- ],
2565
- "gas": gas
2566
- },
2567
- "memo": memo_2,
2568
- "msg": [
2569
- {
2570
- "type": txType,
2571
- "value": {
2572
- "amount": [
2573
- {
2574
- "amount": amountNative.toString(),
2575
- "denom": "uatom"
2576
- }
2577
- ],
2578
- "from_address": addressFrom,
2579
- "to_address": address
2580
- }
2581
- }
2582
- ],
2583
- "signatures": null
2584
- };
2585
- chain_id = ATOM_CHAIN;
2586
- if (!sequence)
2587
- throw Error("112: Failed to get sequence");
2588
- if (!account_number)
2589
- throw Error("113: Failed to get account_number");
2590
- return [4 /*yield*/, this.WALLET.cosmosGetAddress({
2591
- addressNList: bip32ToAddressNList(HD_ATOM_KEYPATH),
2592
- showDisplay: false,
2593
- })];
2594
- case 25:
2595
- fromAddress = _a.sent();
2596
- log.debug(tag, "fromAddressHDwallet: ", fromAddress);
2597
- log.debug(tag, "fromAddress: ", addressFrom);
2598
- log.debug("res: ", prettyjson.render({
2599
- addressNList: bip32ToAddressNList(HD_ATOM_KEYPATH),
2600
- chain_id: chain_id,
2601
- account_number: account_number,
2602
- sequence: sequence,
2603
- tx: unsigned,
2604
- }));
2605
- atomTx = {
2606
- addressNList: bip32ToAddressNList(HD_ATOM_KEYPATH),
2607
- chain_id: chain_id,
2608
- account_number: account_number,
2609
- sequence: sequence,
2610
- tx: unsigned,
2611
- };
2612
- unsignedTx = {
2613
- network: network_2,
2614
- asset: network_2,
2615
- transaction: transaction,
2616
- HDwalletPayload: atomTx,
2617
- verbal: "Thorchain transaction"
2618
- };
2619
- rawTx = unsignedTx;
2620
- return [3 /*break*/, 32];
2621
- case 26:
2622
- if (!(network_2 === 'OSMO')) return [3 /*break*/, 29];
2623
- amountNative = ATOM_BASE * parseFloat(amount);
2624
- amountNative = parseInt(amountNative.toString());
2625
- //get account number
2626
- log.debug(tag, "addressFrom: ", addressFrom);
2627
- return [4 /*yield*/, this.pioneerClient.instance.GetAccountInfo({ network: 'OSMO', address: addressFrom })];
2628
- case 27:
2629
- masterInfo = _a.sent();
2630
- masterInfo = masterInfo.data;
2631
- log.debug(tag, "masterInfo: ", masterInfo.data);
2632
- sequence = masterInfo.result.value.sequence;
2633
- account_number = masterInfo.result.value.account_number;
2634
- sequence = parseInt(sequence);
2635
- if (!sequence || isNaN(sequence))
2636
- sequence = 0;
2637
- sequence = sequence.toString();
2638
- txType = "cosmos-sdk/MsgSend";
2639
- gas = "80000";
2640
- fee_3 = "2800";
2641
- memo_3 = transaction.memo || "";
2642
- unsigned = {
2643
- "fee": {
2644
- "amount": [
2645
- {
2646
- "amount": fee_3,
2647
- "denom": "uosmo"
2648
- }
2649
- ],
2650
- "gas": gas
2651
- },
2652
- "memo": memo_3,
2653
- "msg": [
2654
- {
2655
- "type": txType,
2656
- "value": {
2657
- "amount": [
2658
- {
2659
- "amount": amountNative.toString(),
2660
- "denom": "uosmo"
2661
- }
2662
- ],
2663
- "from_address": addressFrom,
2664
- "to_address": address
2665
- }
2666
- }
2667
- ],
2668
- "signatures": null
2669
- };
2670
- chain_id = OSMO_CHAIN;
2671
- if (!sequence)
2672
- throw Error("112: Failed to get sequence");
2673
- if (!account_number)
2674
- throw Error("113: Failed to get account_number");
2675
- return [4 /*yield*/, this.WALLET.osmosisGetAddress({
2676
- addressNList: bip32ToAddressNList(HD_ATOM_KEYPATH),
2677
- showDisplay: false,
2678
- })];
2679
- case 28:
2680
- fromAddress = _a.sent();
2681
- log.debug(tag, "fromAddressHDwallet: ", fromAddress);
2682
- log.debug(tag, "fromAddress: ", addressFrom);
2683
- log.debug("res: ", prettyjson.render({
2684
- addressNList: bip32ToAddressNList(HD_ATOM_KEYPATH),
2685
- chain_id: chain_id,
2686
- account_number: account_number,
2687
- sequence: sequence,
2688
- tx: unsigned,
2689
- }));
2690
- atomTx = {
2691
- addressNList: bip32ToAddressNList(HD_ATOM_KEYPATH),
2692
- chain_id: 'osmosis-1',
2693
- account_number: account_number,
2694
- sequence: sequence,
2695
- tx: unsigned,
2696
- };
2697
- unsignedTx = {
2698
- network: network_2,
2699
- asset: network_2,
2700
- transaction: transaction,
2701
- HDwalletPayload: atomTx,
2702
- verbal: "osmosis transaction"
2703
- };
2704
- rawTx = unsignedTx;
2705
- return [3 /*break*/, 32];
2706
- case 29:
2707
- if (!(network_2 === "BNB")) return [3 /*break*/, 31];
2708
- //TODO move to tx builder module
2709
- //get account info
2710
- log.debug("addressFrom: ", addressFrom);
2711
- return [4 /*yield*/, this.pioneerClient.instance.GetAccountInfo({ network: network_2, address: addressFrom })];
2712
- case 30:
2713
- accountInfo = _a.sent();
2714
- accountInfo = accountInfo.data;
2715
- log.debug("accountInfo: ", prettyjson.render(accountInfo));
2716
- sequence = void 0;
2717
- account_number = void 0;
2718
- pubkey = void 0;
2719
- if (!accountInfo.result) {
2720
- //assume new account
2721
- sequence = "0";
2722
- account_number = "0";
2723
- pubkey = null;
2724
- }
2725
- else {
2726
- sequence = transaction.nonce || accountInfo.result.sequence;
2727
- account_number = accountInfo.result.account_number;
2728
- pubkey = accountInfo.result.public_key;
2729
- }
2730
- if (!address)
2731
- throw Error("Missing TO address! ");
2732
- bnbTx = {
2733
- "account_number": account_number,
2734
- "chain_id": "Binance-Chain-Nile",
2735
- "data": null,
2736
- "memo": transaction.memo,
2737
- "msgs": [
2738
- {
2739
- "inputs": [
2740
- {
2741
- "address": addressFrom,
2742
- "coins": [
2743
- {
2744
- "amount": amount,
2745
- "denom": "BNB"
2746
- }
2747
- ]
2748
- }
2749
- ],
2750
- "outputs": [
2751
- {
2752
- "address": address,
2753
- "coins": [
2754
- {
2755
- "amount": amount,
2756
- "denom": "BNB"
2757
- }
2758
- ]
2759
- }
2760
- ]
2761
- }
2762
- ],
2763
- "sequence": sequence,
2764
- "source": "1"
2765
- };
2766
- log.debug(tag, "bnbTx: ", prettyjson.render(bnbTx));
2767
- binanceTx = {
2768
- addressNList: bip32ToAddressNList("m/44'/714'/0'/0/0"),
2769
- chain_id: "Binance-Chain-Nile",
2770
- account_number: account_number,
2771
- sequence: sequence,
2772
- tx: bnbTx,
2773
- };
2774
- unsignedTx = {
2775
- network: network_2,
2776
- asset: network_2,
2777
- transaction: transaction,
2778
- HDwalletPayload: binanceTx,
2779
- verbal: "Thorchain transaction"
2780
- };
2781
- rawTx = unsignedTx;
2782
- return [3 /*break*/, 32];
2783
- case 31:
2784
- if (network_2 === "EOS") {
2785
- throw Error("666: EOS not supported yet!");
2786
- // amount = getEosAmount(amount)
2787
- // //EOS transfer
2788
- // let unsigned_main = {
2789
- // expiration: "2020-04-30T22:00:00.000",
2790
- // ref_block_num: 54661,
2791
- // ref_block_prefix: 2118672142,
2792
- // max_net_usage_words: 0,
2793
- // max_cpu_usage_ms: 0,
2794
- // delay_sec: 0,
2795
- // context_free_actions: [],
2796
- // actions: [
2797
- // {
2798
- // account: "eosio.token",
2799
- // name: "transfer",
2800
- // authorization: [
2801
- // {
2802
- // actor: addressFrom,
2803
- // permission: "active",
2804
- // },
2805
- // ],
2806
- // data: {
2807
- // from: addressFrom,
2808
- // to: address,
2809
- // quantity: amount+" EOS",
2810
- // memo: memo,
2811
- // },
2812
- // },
2813
- // ],
2814
- // };
2815
- //
2816
- // log.debug(tag,"unsigned_main: ",JSON.stringify(unsigned_main))
2817
- //
2818
- // let chainid_main =
2819
- // "aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906";
2820
- // let res = await this.WALLET.eosSignTx({
2821
- // addressNList:[ 0x80000000 + 44, 0x80000000 + 194, 0x80000000 + 0 , 0, 0 ],
2822
- // chain_id: chainid_main,
2823
- // tx: unsigned_main,
2824
- // });
2825
- //
2826
- // log.debug(tag,"**** res: ",res)
2827
- //
2828
- // // let broadcastForm = {
2829
- // // serializedTransaction:Uint8Array.from(Buffer.from(res.serialized, 'hex')),
2830
- // // signatures: [res.eosFormSig]
2831
- // // }
2832
- //
2833
- // let broadcastForm = {
2834
- // serializedTransaction:res.serialized,
2835
- // signatures: res.eosFormSig
2836
- // }
2837
- //
2838
- // // output.serializedTransaction = Uint8Array.from(Buffer.from(res.serialized, 'hex'));
2839
- // // output.signatures = [res.eosFormSig]
2840
- // // log.debug(tag,"res: ",res)
2841
- // rawTx = {
2842
- // txid:"",
2843
- // serialized:res.serialized,
2844
- // broadcastBody:broadcastForm
2845
- // }
2846
- // log.debug(tag,"rawTx: ",rawTx)
2847
- }
2848
- else if (network_2 === "FIO") {
2849
- throw Error("666: FIO not supported yet!");
2850
- // //if name
2851
- // if(address.indexOf("@") >= 0){
2852
- // address = await network.getFioPubkeyFromUsername(address)
2853
- // }
2854
- //
2855
- // //
2856
- // log.debug(tag,"address: ",address)
2857
- //
2858
- // let amountNative = parseFloat(amount) * 100000000
2859
- // amountNative = parseInt(String(amountNative))
2860
- // //
2861
- // log.debug(tag,"fiotx: ",transaction)
2862
- // const data: FioActionParameters.FioTransferTokensPubKeyActionData = {
2863
- // payee_public_key: address,
2864
- // amount: String(amountNative),
2865
- // max_fee: 2000000000,
2866
- // tpid: "",
2867
- // };
2868
- //
2869
- // const res = await WALLET.fioSignTx({
2870
- // addressNList: bip32ToAddressNList("m/44'/235'/0'/0/0"),
2871
- // actions: [
2872
- // {
2873
- // account: FioActionParameters.FioTransferTokensPubKeyActionAccount,
2874
- // name: FioActionParameters.FioTransferTokensPubKeyActionName,
2875
- // data,
2876
- // },
2877
- // ],
2878
- // });
2879
- // log.debug(tag,"res: ",res)
2880
- //
2881
- // rawTx = res
2882
- }
2883
- else {
2884
- throw Error("109: network not yet implemented! network: " + network_2);
2885
- }
2886
- _a.label = 32;
2887
- case 32: return [2 /*return*/, rawTx];
2888
- case 33:
2889
- e_13 = _a.sent();
2890
- log.error(tag, "e: ", e_13);
2891
- throw e_13;
2892
- case 34: return [2 /*return*/];
2893
- }
2894
- });
2895
- });
2896
- };
2897
- this.broadcastTransaction = function (network, signedTx) {
2898
- return __awaiter(this, void 0, void 0, function () {
2899
- var tag, resultBroadcast;
2900
- return __generator(this, function (_a) {
2901
- switch (_a.label) {
2902
- case 0:
2903
- tag = TAG + " | broadcastTransaction | ";
2904
- if (this.isTestnet && network === 'BTC') {
2905
- signedTx.network = "TEST";
2906
- }
2907
- else {
2908
- signedTx.network = network;
2909
- }
2910
- log.debug(tag, "signedTx: ", signedTx);
2911
- return [4 /*yield*/, this.pioneerClient.instance.Broadcast(null, signedTx)];
2912
- case 1:
2913
- resultBroadcast = _a.sent();
2914
- log.debug(tag, "resultBroadcast: ", resultBroadcast.data);
2915
- return [2 /*return*/, resultBroadcast.data];
2916
- }
2917
- });
2918
- });
2919
- };
2920
- }
2921
- return wallet;
2922
- }());
1214
+ });
1215
+ });
1216
+ };