@airgap/bitcoin 0.13.7-beta.22 → 0.13.7-beta.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/airgap-coinlib-bitcoin.min.js +16559 -4042
  2. package/index.d.ts +1 -14
  3. package/index.js +15 -19
  4. package/index.js.map +1 -1
  5. package/package.json +4 -2
  6. package/v0/index.d.ts +14 -0
  7. package/v0/index.js +34 -0
  8. package/v0/index.js.map +1 -0
  9. package/{protocol → v0/protocol}/BitcoinAddress.d.ts +0 -0
  10. package/{protocol → v0/protocol}/BitcoinAddress.js +0 -0
  11. package/v0/protocol/BitcoinAddress.js.map +1 -0
  12. package/{protocol → v0/protocol}/BitcoinCryptoClient.d.ts +0 -0
  13. package/{protocol → v0/protocol}/BitcoinCryptoClient.js +2 -0
  14. package/v0/protocol/BitcoinCryptoClient.js.map +1 -0
  15. package/{protocol → v0/protocol}/BitcoinProtocol.d.ts +0 -0
  16. package/{protocol → v0/protocol}/BitcoinProtocol.js +29 -21
  17. package/v0/protocol/BitcoinProtocol.js.map +1 -0
  18. package/{protocol → v0/protocol}/BitcoinProtocolOptions.d.ts +0 -0
  19. package/{protocol → v0/protocol}/BitcoinProtocolOptions.js +9 -3
  20. package/v0/protocol/BitcoinProtocolOptions.js.map +1 -0
  21. package/{protocol → v0/protocol}/BitcoinSegwitAddress.d.ts +0 -0
  22. package/{protocol → v0/protocol}/BitcoinSegwitAddress.js +2 -0
  23. package/v0/protocol/BitcoinSegwitAddress.js.map +1 -0
  24. package/{protocol → v0/protocol}/BitcoinSegwitProtocol.d.ts +0 -0
  25. package/{protocol → v0/protocol}/BitcoinSegwitProtocol.js +32 -21
  26. package/v0/protocol/BitcoinSegwitProtocol.js.map +1 -0
  27. package/{protocol → v0/protocol}/BitcoinTestnetProtocol.d.ts +0 -0
  28. package/{protocol → v0/protocol}/BitcoinTestnetProtocol.js +7 -1
  29. package/v0/protocol/BitcoinTestnetProtocol.js.map +1 -0
  30. package/{protocol → v0/protocol}/BitcoinTypes.d.ts +0 -0
  31. package/{protocol → v0/protocol}/BitcoinTypes.js +0 -0
  32. package/v0/protocol/BitcoinTypes.js.map +1 -0
  33. package/v0/serializer/schemas/v2/transaction-sign-request-bitcoin-segwit.json +0 -0
  34. package/v0/serializer/schemas/v2/transaction-sign-request-bitcoin.json +73 -0
  35. package/v0/serializer/schemas/v2/transaction-sign-response-bitcoin-segwit.json +0 -0
  36. package/v0/serializer/schemas/v2/transaction-sign-response-bitcoin.json +37 -0
  37. package/v0/serializer/schemas/v3/transaction-sign-request-bitcoin-segwit.json +32 -0
  38. package/v0/serializer/schemas/v3/transaction-sign-request-bitcoin.json +73 -0
  39. package/v0/serializer/schemas/v3/transaction-sign-response-bitcoin-segwit.json +19 -0
  40. package/v0/serializer/schemas/v3/transaction-sign-response-bitcoin.json +37 -0
  41. package/v0/serializer/validators/transaction-validator.d.ts +15 -0
  42. package/v0/serializer/validators/transaction-validator.js +81 -0
  43. package/v0/serializer/validators/transaction-validator.js.map +1 -0
  44. package/v0/serializer/validators/validators.d.ts +1 -0
  45. package/v0/serializer/validators/validators.js +151 -0
  46. package/v0/serializer/validators/validators.js.map +1 -0
  47. package/v0/types/signed-transaction-bitcoin-segwit.d.ts +5 -0
  48. package/{types → v0/types}/signed-transaction-bitcoin-segwit.js +0 -0
  49. package/v0/types/signed-transaction-bitcoin-segwit.js.map +1 -0
  50. package/v0/types/signed-transaction-bitcoin.d.ts +9 -0
  51. package/{types → v0/types}/signed-transaction-bitcoin.js +0 -0
  52. package/v0/types/signed-transaction-bitcoin.js.map +1 -0
  53. package/{types → v0/types}/transaction-bitcoin.d.ts +0 -0
  54. package/{types → v0/types}/transaction-bitcoin.js +0 -0
  55. package/v0/types/transaction-bitcoin.js.map +1 -0
  56. package/v0/types/unsigned-transaction-bitcoin-segwit.d.ts +7 -0
  57. package/{types → v0/types}/unsigned-transaction-bitcoin-segwit.js +0 -0
  58. package/v0/types/unsigned-transaction-bitcoin-segwit.js.map +1 -0
  59. package/{types → v0/types}/unsigned-transaction-bitcoin.d.ts +2 -2
  60. package/{types → v0/types}/unsigned-transaction-bitcoin.js +0 -0
  61. package/v0/types/unsigned-transaction-bitcoin.js.map +1 -0
  62. package/v1/block-explorer/BlockCypherBlockExplorer.d.ts +9 -0
  63. package/v1/block-explorer/BlockCypherBlockExplorer.js +74 -0
  64. package/v1/block-explorer/BlockCypherBlockExplorer.js.map +1 -0
  65. package/v1/data/BitcoinAddress.d.ts +7 -0
  66. package/v1/data/BitcoinAddress.js +21 -0
  67. package/v1/data/BitcoinAddress.js.map +1 -0
  68. package/v1/data/BitcoinSegwitAddress.d.ts +8 -0
  69. package/v1/data/BitcoinSegwitAddress.js +26 -0
  70. package/v1/data/BitcoinSegwitAddress.js.map +1 -0
  71. package/v1/index.d.ts +20 -0
  72. package/v1/index.js +26 -0
  73. package/v1/index.js.map +1 -0
  74. package/v1/module/BitcoinModule.d.ts +8 -0
  75. package/v1/module/BitcoinModule.js +86 -0
  76. package/v1/module/BitcoinModule.js.map +1 -0
  77. package/v1/module/BitcoinSegwitModule.d.ts +8 -0
  78. package/v1/module/BitcoinSegwitModule.js +87 -0
  79. package/v1/module/BitcoinSegwitModule.js.map +1 -0
  80. package/v1/protocol/BitcoinCryptoClient.d.ts +12 -0
  81. package/v1/protocol/BitcoinCryptoClient.js +96 -0
  82. package/v1/protocol/BitcoinCryptoClient.js.map +1 -0
  83. package/v1/protocol/BitcoinProtocol.d.ts +68 -0
  84. package/v1/protocol/BitcoinProtocol.js +1198 -0
  85. package/v1/protocol/BitcoinProtocol.js.map +1 -0
  86. package/v1/protocol/BitcoinSegwitProtocol.d.ts +51 -0
  87. package/v1/protocol/BitcoinSegwitProtocol.js +734 -0
  88. package/v1/protocol/BitcoinSegwitProtocol.js.map +1 -0
  89. package/v1/protocol/BitcoinTestnetProtocol.d.ts +11 -0
  90. package/v1/protocol/BitcoinTestnetProtocol.js +67 -0
  91. package/v1/protocol/BitcoinTestnetProtocol.js.map +1 -0
  92. package/v1/serializer/v3/schemas/converter/transaction-converter.d.ts +13 -0
  93. package/v1/serializer/v3/schemas/converter/transaction-converter.js +54 -0
  94. package/v1/serializer/v3/schemas/converter/transaction-converter.js.map +1 -0
  95. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-bitcoin-segwit.d.ts +4 -0
  96. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-bitcoin-segwit.js +3 -0
  97. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-bitcoin-segwit.js.map +1 -0
  98. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-bitcoin.d.ts +4 -0
  99. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-bitcoin.js +3 -0
  100. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-bitcoin.js.map +1 -0
  101. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-bitcoin-segwit.d.ts +3 -0
  102. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-bitcoin-segwit.js +3 -0
  103. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-bitcoin-segwit.js.map +1 -0
  104. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-bitcoin.d.ts +7 -0
  105. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-bitcoin.js +3 -0
  106. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-bitcoin.js.map +1 -0
  107. package/v1/serializer/v3/schemas/generated/transaction-sign-request-bitcoin-segwit.json +36 -0
  108. package/v1/serializer/v3/schemas/generated/transaction-sign-request-bitcoin.json +86 -0
  109. package/v1/serializer/v3/schemas/generated/transaction-sign-response-bitcoin-segwit.json +19 -0
  110. package/v1/serializer/v3/schemas/generated/transaction-sign-response-bitcoin.json +37 -0
  111. package/v1/serializer/v3/validators/transaction-validators.d.ts +10 -0
  112. package/v1/serializer/v3/validators/transaction-validators.js +65 -0
  113. package/v1/serializer/v3/validators/transaction-validators.js.map +1 -0
  114. package/v1/serializer/v3/validators/validators.d.ts +7 -0
  115. package/v1/serializer/v3/validators/validators.js +254 -0
  116. package/v1/serializer/v3/validators/validators.js.map +1 -0
  117. package/v1/types/bitcoinjs.d.ts +14 -0
  118. package/v1/types/bitcoinjs.js +3 -0
  119. package/v1/types/bitcoinjs.js.map +1 -0
  120. package/v1/types/indexer.d.ts +81 -0
  121. package/v1/types/indexer.js +3 -0
  122. package/v1/types/indexer.js.map +1 -0
  123. package/v1/types/key.d.ts +6 -0
  124. package/v1/types/key.js +3 -0
  125. package/v1/types/key.js.map +1 -0
  126. package/v1/types/protocol.d.ts +17 -0
  127. package/v1/types/protocol.js +3 -0
  128. package/v1/types/protocol.js.map +1 -0
  129. package/v1/types/transaction.d.ts +39 -0
  130. package/v1/types/transaction.js +3 -0
  131. package/v1/types/transaction.js.map +1 -0
  132. package/v1/utils/common.d.ts +2 -0
  133. package/v1/utils/common.js +28 -0
  134. package/v1/utils/common.js.map +1 -0
  135. package/v1/utils/key.d.ts +12 -0
  136. package/v1/utils/key.js +157 -0
  137. package/v1/utils/key.js.map +1 -0
  138. package/v1/utils/network.d.ts +2 -0
  139. package/v1/utils/network.js +22 -0
  140. package/v1/utils/network.js.map +1 -0
  141. package/v1/utils/signature.d.ts +2 -0
  142. package/v1/utils/signature.js +34 -0
  143. package/v1/utils/signature.js.map +1 -0
  144. package/protocol/BitcoinAddress.js.map +0 -1
  145. package/protocol/BitcoinCryptoClient.js.map +0 -1
  146. package/protocol/BitcoinProtocol.js.map +0 -1
  147. package/protocol/BitcoinProtocolOptions.js.map +0 -1
  148. package/protocol/BitcoinSegwitAddress.js.map +0 -1
  149. package/protocol/BitcoinSegwitProtocol.js.map +0 -1
  150. package/protocol/BitcoinTestnetProtocol.js.map +0 -1
  151. package/protocol/BitcoinTypes.js.map +0 -1
  152. package/types/signed-transaction-bitcoin-segwit.d.ts +0 -5
  153. package/types/signed-transaction-bitcoin-segwit.js.map +0 -1
  154. package/types/signed-transaction-bitcoin.d.ts +0 -9
  155. package/types/signed-transaction-bitcoin.js.map +0 -1
  156. package/types/transaction-bitcoin.js.map +0 -1
  157. package/types/unsigned-transaction-bitcoin-segwit.d.ts +0 -7
  158. package/types/unsigned-transaction-bitcoin-segwit.js.map +0 -1
  159. package/types/unsigned-transaction-bitcoin.js.map +0 -1
@@ -0,0 +1,1198 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17
+ desc = { enumerable: true, get: function() { return m[k]; } };
18
+ }
19
+ Object.defineProperty(o, k2, desc);
20
+ }) : (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ }));
24
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
25
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
26
+ }) : function(o, v) {
27
+ o["default"] = v;
28
+ });
29
+ var __importStar = (this && this.__importStar) || function (mod) {
30
+ if (mod && mod.__esModule) return mod;
31
+ var result = {};
32
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
33
+ __setModuleDefault(result, mod);
34
+ return result;
35
+ };
36
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
37
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
38
+ return new (P || (P = Promise))(function (resolve, reject) {
39
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
40
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
41
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
42
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
43
+ });
44
+ };
45
+ var __generator = (this && this.__generator) || function (thisArg, body) {
46
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
47
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
48
+ function verb(n) { return function (v) { return step([n, v]); }; }
49
+ function step(op) {
50
+ if (f) throw new TypeError("Generator is already executing.");
51
+ while (_) try {
52
+ 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;
53
+ if (y = 0, t) op = [op[0] & 2, t.value];
54
+ switch (op[0]) {
55
+ case 0: case 1: t = op; break;
56
+ case 4: _.label++; return { value: op[1], done: false };
57
+ case 5: _.label++; y = op[1]; op = [0]; continue;
58
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
59
+ default:
60
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
61
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
62
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
63
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
64
+ if (t[2]) _.ops.pop();
65
+ _.trys.pop(); continue;
66
+ }
67
+ op = body.call(thisArg, _);
68
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
69
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
70
+ }
71
+ };
72
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
73
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
74
+ if (ar || !(i in from)) {
75
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
76
+ ar[i] = from[i];
77
+ }
78
+ }
79
+ return to.concat(ar || Array.prototype.slice.call(from));
80
+ };
81
+ var __importDefault = (this && this.__importDefault) || function (mod) {
82
+ return (mod && mod.__esModule) ? mod : { "default": mod };
83
+ };
84
+ Object.defineProperty(exports, "__esModule", { value: true });
85
+ exports.createBitcoinProtocolOptions = exports.BITCOIN_MAINNET_PROTOCOL_NETWORK = exports.createBitcoinProtocol = exports.BitcoinProtocolImpl = void 0;
86
+ var coinlib_core_1 = require("@airgap/coinlib-core");
87
+ var index_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/axios-0.19.0/index"));
88
+ var BigInteger = __importStar(require("@airgap/coinlib-core/dependencies/src/bigi-1.4.2"));
89
+ var bignumber_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/bignumber.js-9.0.0/bignumber"));
90
+ var index_2 = require("@airgap/coinlib-core/dependencies/src/bip39-2.5.0/index");
91
+ var bitcoinMessage = __importStar(require("@airgap/coinlib-core/dependencies/src/bitcoinjs-message-2.1.1/index"));
92
+ var BitGo = __importStar(require("@airgap/coinlib-core/dependencies/src/bitgo-utxo-lib-5d91049fd7a988382df81c8260e244ee56d57aac/src/index"));
93
+ var errors_1 = require("@airgap/coinlib-core/errors");
94
+ var module_kit_1 = require("@airgap/module-kit");
95
+ var BitcoinAddress_1 = require("../data/BitcoinAddress");
96
+ var common_1 = require("../utils/common");
97
+ var key_1 = require("../utils/key");
98
+ var network_1 = require("../utils/network");
99
+ var signature_1 = require("../utils/signature");
100
+ var BitcoinCryptoClient_1 = require("./BitcoinCryptoClient");
101
+ // Implementation
102
+ var DUST_AMOUNT = 50;
103
+ var BitcoinProtocolImpl = /** @class */ (function () {
104
+ function BitcoinProtocolImpl(options, bitcoinJS, bitcoinJSMessage) {
105
+ if (options === void 0) { options = {}; }
106
+ if (bitcoinJS === void 0) { bitcoinJS = BitGo; }
107
+ if (bitcoinJSMessage === void 0) { bitcoinJSMessage = bitcoinMessage; }
108
+ // Common
109
+ this.units = {
110
+ BTC: {
111
+ symbol: { value: 'BTC', market: 'btc' },
112
+ decimals: 8
113
+ },
114
+ mBTC: {
115
+ symbol: { value: 'mBTC' },
116
+ decimals: 4
117
+ },
118
+ Satoshi: {
119
+ symbol: { value: 'Satoshi' },
120
+ decimals: 0
121
+ }
122
+ };
123
+ this.feeDefaults = {
124
+ low: (0, module_kit_1.newAmount)(0.00002, 'BTC').blockchain(this.units),
125
+ medium: (0, module_kit_1.newAmount)(0.00004, 'BTC').blockchain(this.units),
126
+ high: (0, module_kit_1.newAmount)(0.00005, 'BTC').blockchain(this.units)
127
+ };
128
+ this.metadata = {
129
+ identifier: coinlib_core_1.MainProtocolSymbols.BTC,
130
+ name: 'Bitcoin (Legacy)',
131
+ units: this.units,
132
+ mainUnit: 'BTC',
133
+ fee: {
134
+ defaults: this.feeDefaults
135
+ },
136
+ account: {
137
+ standardDerivationPath: "m/44'/0'/0'",
138
+ address: {
139
+ isCaseSensitive: true,
140
+ placeholder: '1ABC...',
141
+ regex: '^(?:[13]{1}[a-km-zA-HJ-NP-Z1-9]{25,34}|bc1[a-z0-9]{39,59})$'
142
+ }
143
+ }
144
+ };
145
+ this.options = createBitcoinProtocolOptions(options.network);
146
+ this.bitcoinJS = {
147
+ lib: bitcoinJS,
148
+ message: bitcoinJSMessage,
149
+ config: {
150
+ network: (0, network_1.getBitcoinJSNetwork)(this.options.network, bitcoinJS)
151
+ }
152
+ };
153
+ this.cryptoClient = new BitcoinCryptoClient_1.BitcoinCryptoClient(this, this.bitcoinJS);
154
+ }
155
+ BitcoinProtocolImpl.prototype.getMetadata = function () {
156
+ return __awaiter(this, void 0, void 0, function () {
157
+ return __generator(this, function (_a) {
158
+ return [2 /*return*/, this.metadata];
159
+ });
160
+ });
161
+ };
162
+ BitcoinProtocolImpl.prototype.getAddressFromPublicKey = function (publicKey) {
163
+ return __awaiter(this, void 0, void 0, function () {
164
+ return __generator(this, function (_a) {
165
+ switch (publicKey.type) {
166
+ case 'pub':
167
+ return [2 /*return*/, this.getAddressFromNonExtendedPublicKey(publicKey)];
168
+ case 'xpub':
169
+ return [2 /*return*/, this.getAddressFromExtendedPublicKey(publicKey)];
170
+ default:
171
+ (0, coinlib_core_1.assertNever)(publicKey);
172
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.BITCOIN, 'Public key type is not supported.');
173
+ }
174
+ return [2 /*return*/];
175
+ });
176
+ });
177
+ };
178
+ BitcoinProtocolImpl.prototype.getAddressFromNonExtendedPublicKey = function (publicKey) {
179
+ return __awaiter(this, void 0, void 0, function () {
180
+ var hexPublicKey, keyPair;
181
+ return __generator(this, function (_a) {
182
+ hexPublicKey = (0, key_1.convertPublicKey)(publicKey, 'hex');
183
+ keyPair = this.bitcoinJS.lib.ECPair.fromPublicKeyBuffer(Buffer.from(hexPublicKey.value, 'hex'), this.bitcoinJS.config.network);
184
+ return [2 /*return*/, BitcoinAddress_1.BitcoinAddress.fromECPair(keyPair).asString()];
185
+ });
186
+ });
187
+ };
188
+ BitcoinProtocolImpl.prototype.getAddressFromExtendedPublicKey = function (extendedPublicKey) {
189
+ return __awaiter(this, void 0, void 0, function () {
190
+ var encodedExtendedPublicKey, node;
191
+ return __generator(this, function (_a) {
192
+ encodedExtendedPublicKey = this.convertExtendedPublicKey(extendedPublicKey, 'encoded');
193
+ node = this.bitcoinJS.lib.HDNode.fromBase58(encodedExtendedPublicKey.value, this.bitcoinJS.config.network);
194
+ return [2 /*return*/, BitcoinAddress_1.BitcoinAddress.fromHDNode(node).asString()];
195
+ });
196
+ });
197
+ };
198
+ BitcoinProtocolImpl.prototype.deriveFromExtendedPublicKey = function (extendedPublicKey, visibilityIndex, addressIndex) {
199
+ return __awaiter(this, void 0, void 0, function () {
200
+ var encodedExtendedPublicKey, childPublicKey;
201
+ return __generator(this, function (_a) {
202
+ encodedExtendedPublicKey = this.convertExtendedPublicKey(extendedPublicKey, 'encoded');
203
+ childPublicKey = this.bitcoinJS.lib.HDNode.fromBase58(encodedExtendedPublicKey.value, this.bitcoinJS.config.network)
204
+ .derive(visibilityIndex)
205
+ .derive(addressIndex)
206
+ .getPublicKeyBuffer();
207
+ return [2 /*return*/, (0, module_kit_1.newPublicKey)(childPublicKey.toString('hex'), 'hex')];
208
+ });
209
+ });
210
+ };
211
+ BitcoinProtocolImpl.prototype.getDetailsFromTransaction = function (transaction, _publicKey) {
212
+ return __awaiter(this, void 0, void 0, function () {
213
+ return __generator(this, function (_a) {
214
+ switch (transaction.type) {
215
+ case 'signed':
216
+ return [2 /*return*/, this.getDetailsFromSignedTransaction(transaction)];
217
+ case 'unsigned':
218
+ return [2 /*return*/, this.getDetailsFromUnsignedTransaction(transaction)];
219
+ default:
220
+ (0, coinlib_core_1.assertNever)(transaction);
221
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.BITCOIN, 'Unsupported transaction type.');
222
+ }
223
+ return [2 /*return*/];
224
+ });
225
+ });
226
+ };
227
+ BitcoinProtocolImpl.prototype.getDetailsFromSignedTransaction = function (transaction) {
228
+ return __awaiter(this, void 0, void 0, function () {
229
+ var tx, bitcoinTx;
230
+ var _this = this;
231
+ return __generator(this, function (_a) {
232
+ tx = {
233
+ from: transaction.from,
234
+ to: [],
235
+ isInbound: false,
236
+ amount: (0, module_kit_1.newAmount)(transaction.amount, 'blockchain'),
237
+ fee: (0, module_kit_1.newAmount)(transaction.fee, 'blockchain'),
238
+ network: this.options.network
239
+ };
240
+ bitcoinTx = this.bitcoinJS.lib.Transaction.fromHex(transaction.transaction);
241
+ bitcoinTx.outs.forEach(function (output) {
242
+ var address = _this.bitcoinJS.lib.address.fromOutputScript(output.script, _this.bitcoinJS.config.network);
243
+ // only works if one output is target and rest is change, but this way we can filter out change addresses
244
+ if (new bignumber_1.default(output.value).isEqualTo(transaction.amount)) {
245
+ tx.to.push(address);
246
+ }
247
+ });
248
+ return [2 /*return*/, [tx]];
249
+ });
250
+ });
251
+ };
252
+ BitcoinProtocolImpl.prototype.getDetailsFromUnsignedTransaction = function (transaction) {
253
+ return __awaiter(this, void 0, void 0, function () {
254
+ var fee, _i, _a, txIn, _b, _c, txOut;
255
+ return __generator(this, function (_d) {
256
+ fee = new bignumber_1.default(0);
257
+ for (_i = 0, _a = transaction.ins; _i < _a.length; _i++) {
258
+ txIn = _a[_i];
259
+ fee = fee.plus(new bignumber_1.default(txIn.value));
260
+ }
261
+ for (_b = 0, _c = transaction.outs; _b < _c.length; _b++) {
262
+ txOut = _c[_b];
263
+ fee = fee.minus(new bignumber_1.default(txOut.value));
264
+ }
265
+ return [2 /*return*/, [
266
+ {
267
+ from: transaction.ins.map(function (obj) { return obj.address; }),
268
+ to: transaction.outs.filter(function (obj) { return !obj.isChange; }).map(function (obj) { return obj.recipient; }),
269
+ isInbound: false,
270
+ amount: (0, module_kit_1.newAmount)(transaction.outs
271
+ .filter(function (obj) { return !obj.isChange; })
272
+ .map(function (obj) { return new bignumber_1.default(obj.value); })
273
+ .reduce(function (accumulator, currentValue) { return accumulator.plus(currentValue); }), 'blockchain'),
274
+ fee: (0, module_kit_1.newAmount)(fee, 'blockchain'),
275
+ network: this.options.network
276
+ }
277
+ ]];
278
+ });
279
+ });
280
+ };
281
+ BitcoinProtocolImpl.prototype.verifyMessageWithPublicKey = function (message, signature, publicKey) {
282
+ return __awaiter(this, void 0, void 0, function () {
283
+ var encodedSignature;
284
+ return __generator(this, function (_a) {
285
+ encodedSignature = (0, signature_1.convertSignature)(signature, 'encoded');
286
+ return [2 /*return*/, this.cryptoClient.verifyMessage(message, encodedSignature.value, publicKey.value)];
287
+ });
288
+ });
289
+ };
290
+ BitcoinProtocolImpl.prototype.encryptAsymmetricWithPublicKey = function (payload, publicKey) {
291
+ return __awaiter(this, void 0, void 0, function () {
292
+ var nonExtendedPublicKey, _a, hexNonExtendedPublicKey;
293
+ return __generator(this, function (_b) {
294
+ switch (_b.label) {
295
+ case 0:
296
+ if (!(publicKey.type === 'pub')) return [3 /*break*/, 1];
297
+ _a = publicKey;
298
+ return [3 /*break*/, 3];
299
+ case 1: return [4 /*yield*/, this.deriveFromExtendedPublicKey(publicKey, 0, 0)];
300
+ case 2:
301
+ _a = _b.sent();
302
+ _b.label = 3;
303
+ case 3:
304
+ nonExtendedPublicKey = _a;
305
+ hexNonExtendedPublicKey = (0, key_1.convertPublicKey)(nonExtendedPublicKey, 'hex');
306
+ return [2 /*return*/, this.cryptoClient.encryptAsymmetric(payload, hexNonExtendedPublicKey.value)];
307
+ }
308
+ });
309
+ });
310
+ };
311
+ // Offline
312
+ BitcoinProtocolImpl.prototype.getKeyPairFromSecret = function (secret, derivationPath) {
313
+ return __awaiter(this, void 0, void 0, function () {
314
+ return __generator(this, function (_a) {
315
+ switch (secret.type) {
316
+ case 'hex':
317
+ return [2 /*return*/, this.getKeyPairFromHexSecret(secret.value, derivationPath)];
318
+ case 'mnemonic':
319
+ return [2 /*return*/, this.getKeyPairFromMnemonic(secret.value, derivationPath, secret.password)];
320
+ default:
321
+ (0, coinlib_core_1.assertNever)(secret);
322
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.BITCOIN, 'Unsupported secret type.');
323
+ }
324
+ return [2 /*return*/];
325
+ });
326
+ });
327
+ };
328
+ BitcoinProtocolImpl.prototype.getKeyPairFromHexSecret = function (secret, derivationPath) {
329
+ return __awaiter(this, void 0, void 0, function () {
330
+ var node, derivedNode;
331
+ return __generator(this, function (_a) {
332
+ node = this.bitcoinJS.lib.HDNode.fromSeedHex(secret, this.bitcoinJS.config.network);
333
+ derivedNode = derivationPath ? node.derivePath(derivationPath) : node;
334
+ return [2 /*return*/, {
335
+ secretKey: (0, module_kit_1.newSecretKey)(derivedNode.keyPair.getPrivateKeyBuffer().toString('hex'), 'hex'),
336
+ publicKey: (0, module_kit_1.newPublicKey)(derivedNode.keyPair.getPublicKeyBuffer().toString('hex'), 'hex')
337
+ }];
338
+ });
339
+ });
340
+ };
341
+ BitcoinProtocolImpl.prototype.getKeyPairFromMnemonic = function (mnemonic, derivationPath, password) {
342
+ return __awaiter(this, void 0, void 0, function () {
343
+ var secret;
344
+ return __generator(this, function (_a) {
345
+ secret = (0, index_2.mnemonicToSeed)(mnemonic, password);
346
+ return [2 /*return*/, this.getKeyPairFromHexSecret(secret.toString('hex'), derivationPath)];
347
+ });
348
+ });
349
+ };
350
+ BitcoinProtocolImpl.prototype.getExtendedKeyPairFromSecret = function (secret, derivationPath) {
351
+ return __awaiter(this, void 0, void 0, function () {
352
+ return __generator(this, function (_a) {
353
+ switch (secret.type) {
354
+ case 'hex':
355
+ return [2 /*return*/, this.getExtendedKeyPairFromHexSecret(secret.value, derivationPath)];
356
+ case 'mnemonic':
357
+ return [2 /*return*/, this.getExtendedKeyPairFromMnemonic(secret.value, derivationPath, secret.password)];
358
+ default:
359
+ (0, coinlib_core_1.assertNever)(secret);
360
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.BITCOIN, 'Unsupported secret type.');
361
+ }
362
+ return [2 /*return*/];
363
+ });
364
+ });
365
+ };
366
+ BitcoinProtocolImpl.prototype.getExtendedKeyPairFromHexSecret = function (secret, derivationPath) {
367
+ return __awaiter(this, void 0, void 0, function () {
368
+ var node, derivedNode;
369
+ return __generator(this, function (_a) {
370
+ node = this.bitcoinJS.lib.HDNode.fromSeedHex(secret, this.bitcoinJS.config.network);
371
+ derivedNode = derivationPath ? node.derivePath(derivationPath) : undefined;
372
+ return [2 /*return*/, {
373
+ secretKey: (0, module_kit_1.newExtendedSecretKey)(derivedNode.toBase58(), 'encoded'),
374
+ publicKey: (0, module_kit_1.newExtendedPublicKey)(derivedNode.neutered().toBase58(), 'encoded')
375
+ }];
376
+ });
377
+ });
378
+ };
379
+ BitcoinProtocolImpl.prototype.getExtendedKeyPairFromMnemonic = function (mnemonic, derivationPath, password) {
380
+ return __awaiter(this, void 0, void 0, function () {
381
+ var secret;
382
+ return __generator(this, function (_a) {
383
+ secret = (0, index_2.mnemonicToSeed)(mnemonic, password);
384
+ return [2 /*return*/, this.getExtendedKeyPairFromHexSecret(secret.toString('hex'), derivationPath)];
385
+ });
386
+ });
387
+ };
388
+ BitcoinProtocolImpl.prototype.signTransactionWithSecretKey = function (transaction, secretKey) {
389
+ return __awaiter(this, void 0, void 0, function () {
390
+ return __generator(this, function (_a) {
391
+ switch (secretKey.type) {
392
+ case 'priv':
393
+ return [2 /*return*/, this.signTransactionWithNonExtendedSecretKey(transaction, secretKey)];
394
+ case 'xpriv':
395
+ return [2 /*return*/, this.signTransactionWithExtendedSecretKey(transaction, secretKey)];
396
+ default:
397
+ (0, coinlib_core_1.assertNever)(secretKey);
398
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.BITCOIN, 'Secret key type not supported.');
399
+ }
400
+ return [2 /*return*/];
401
+ });
402
+ });
403
+ };
404
+ BitcoinProtocolImpl.prototype.signTransactionWithNonExtendedSecretKey = function (transaction, secretKey) {
405
+ return __awaiter(this, void 0, void 0, function () {
406
+ var hexSecretKey, transactionBuilder, _i, _a, input, _b, _c, output, bufferSecretKey, keyPair, publicKey, generatedChangeAddress, i;
407
+ return __generator(this, function (_d) {
408
+ switch (_d.label) {
409
+ case 0:
410
+ hexSecretKey = (0, key_1.convertSecretKey)(secretKey, 'hex');
411
+ transactionBuilder = new this.bitcoinJS.lib.TransactionBuilder(this.bitcoinJS.config.network);
412
+ for (_i = 0, _a = transaction.ins; _i < _a.length; _i++) {
413
+ input = _a[_i];
414
+ transactionBuilder.addInput(input.txId, input.vout);
415
+ }
416
+ _b = 0, _c = transaction.outs;
417
+ _d.label = 1;
418
+ case 1:
419
+ if (!(_b < _c.length)) return [3 /*break*/, 5];
420
+ output = _c[_b];
421
+ if (!output.isChange) return [3 /*break*/, 3];
422
+ bufferSecretKey = Buffer.from(secretKey.value, 'hex');
423
+ keyPair = this.bitcoinJS.lib.ECPair(BigInteger.fromBuffer(bufferSecretKey), null, {
424
+ network: this.bitcoinJS.config.network
425
+ });
426
+ publicKey = (0, module_kit_1.newPublicKey)(keyPair.getPublicKeyBuffer().toString('hex'), 'hex');
427
+ return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
428
+ case 2:
429
+ generatedChangeAddress = _d.sent();
430
+ if (generatedChangeAddress !== output.recipient) {
431
+ throw new errors_1.ConditionViolationError(coinlib_core_1.Domain.BITCOIN, 'Change address could not be verified.');
432
+ }
433
+ _d.label = 3;
434
+ case 3:
435
+ transactionBuilder.addOutput(output.recipient, new bignumber_1.default(output.value).toNumber());
436
+ _d.label = 4;
437
+ case 4:
438
+ _b++;
439
+ return [3 /*break*/, 1];
440
+ case 5:
441
+ for (i = 0; i < transaction.ins.length; i++) {
442
+ transactionBuilder.sign(i, Buffer.from(hexSecretKey.value, 'hex'));
443
+ }
444
+ return [2 /*return*/, this.createSignedTransaction(transaction, transactionBuilder)];
445
+ }
446
+ });
447
+ });
448
+ };
449
+ BitcoinProtocolImpl.prototype.signTransactionWithExtendedSecretKey = function (transaction, extendedSecretKey) {
450
+ return __awaiter(this, void 0, void 0, function () {
451
+ var encodedExtendedSecretKey, transactionBuilder, node, _i, _a, input, changeAddressBatchSize, changeAddressMaxAddresses, _loop_1, this_1, _b, _c, output, i;
452
+ var _this = this;
453
+ return __generator(this, function (_d) {
454
+ switch (_d.label) {
455
+ case 0:
456
+ encodedExtendedSecretKey = (0, key_1.convertExtendedSecretKey)(extendedSecretKey, 'encoded');
457
+ transactionBuilder = new this.bitcoinJS.lib.TransactionBuilder(this.bitcoinJS.config.network);
458
+ node = this.bitcoinJS.lib.HDNode.fromBase58(encodedExtendedSecretKey.value, this.bitcoinJS.config.network);
459
+ for (_i = 0, _a = transaction.ins; _i < _a.length; _i++) {
460
+ input = _a[_i];
461
+ transactionBuilder.addInput(input.txId, input.vout);
462
+ }
463
+ changeAddressBatchSize = 10;
464
+ changeAddressMaxAddresses = 500;
465
+ _loop_1 = function (output) {
466
+ var changeAddressIsValid, extendedPublicKey_1, derivedPublicKey, generatedChangeAddress, _loop_2, out_x_1, x;
467
+ return __generator(this, function (_e) {
468
+ switch (_e.label) {
469
+ case 0:
470
+ changeAddressIsValid = false;
471
+ if (!output.isChange) return [3 /*break*/, 8];
472
+ extendedPublicKey_1 = (0, module_kit_1.newExtendedPublicKey)(node.neutered().toBase58(), 'encoded');
473
+ if (!output.derivationPath) return [3 /*break*/, 3];
474
+ return [4 /*yield*/, this_1.deriveFromExtendedPublicKey(extendedPublicKey_1, 1, parseInt(output.derivationPath, 10))];
475
+ case 1:
476
+ derivedPublicKey = _e.sent();
477
+ return [4 /*yield*/, this_1.getAddressFromPublicKey(derivedPublicKey)];
478
+ case 2:
479
+ generatedChangeAddress = _e.sent();
480
+ changeAddressIsValid = generatedChangeAddress === output.recipient;
481
+ return [3 /*break*/, 7];
482
+ case 3:
483
+ _loop_2 = function (x) {
484
+ var derivedPublicKeys, addresses;
485
+ return __generator(this, function (_f) {
486
+ switch (_f.label) {
487
+ case 0: return [4 /*yield*/, Promise.all(Array.from(new Array(changeAddressBatchSize)).map(function () { return __awaiter(_this, void 0, void 0, function () {
488
+ return __generator(this, function (_a) {
489
+ return [2 /*return*/, this.deriveFromExtendedPublicKey(extendedPublicKey_1, 1, x)];
490
+ });
491
+ }); }))];
492
+ case 1:
493
+ derivedPublicKeys = _f.sent();
494
+ return [4 /*yield*/, Promise.all(derivedPublicKeys.map(function (publicKey) {
495
+ return _this.getAddressFromPublicKey(publicKey);
496
+ }))];
497
+ case 2:
498
+ addresses = _f.sent();
499
+ if (addresses.indexOf(output.recipient) >= 0) {
500
+ changeAddressIsValid = true;
501
+ x = changeAddressMaxAddresses;
502
+ }
503
+ out_x_1 = x;
504
+ return [2 /*return*/];
505
+ }
506
+ });
507
+ };
508
+ x = 0;
509
+ _e.label = 4;
510
+ case 4:
511
+ if (!(x < changeAddressMaxAddresses)) return [3 /*break*/, 7];
512
+ return [5 /*yield**/, _loop_2(x)];
513
+ case 5:
514
+ _e.sent();
515
+ x = out_x_1;
516
+ _e.label = 6;
517
+ case 6:
518
+ x += changeAddressBatchSize;
519
+ return [3 /*break*/, 4];
520
+ case 7:
521
+ if (!changeAddressIsValid) {
522
+ throw new errors_1.InvalidValueError(coinlib_core_1.Domain.BITCOIN, 'Change address could not be verified.');
523
+ }
524
+ _e.label = 8;
525
+ case 8:
526
+ transactionBuilder.addOutput(output.recipient, new bignumber_1.default(output.value).toNumber());
527
+ return [2 /*return*/];
528
+ }
529
+ });
530
+ };
531
+ this_1 = this;
532
+ _b = 0, _c = transaction.outs;
533
+ _d.label = 1;
534
+ case 1:
535
+ if (!(_b < _c.length)) return [3 /*break*/, 4];
536
+ output = _c[_b];
537
+ return [5 /*yield**/, _loop_1(output)];
538
+ case 2:
539
+ _d.sent();
540
+ _d.label = 3;
541
+ case 3:
542
+ _b++;
543
+ return [3 /*break*/, 1];
544
+ case 4:
545
+ for (i = 0; i < transaction.ins.length; i++) {
546
+ transactionBuilder.sign(i, node.derivePath(transaction.ins[i].derivationPath));
547
+ }
548
+ return [2 /*return*/, this.createSignedTransaction(transaction, transactionBuilder)];
549
+ }
550
+ });
551
+ });
552
+ };
553
+ BitcoinProtocolImpl.prototype.createSignedTransaction = function (unsignedTransaction, transactionBuilder) {
554
+ var fee = new bignumber_1.default(0);
555
+ for (var _i = 0, _a = unsignedTransaction.ins; _i < _a.length; _i++) {
556
+ var txIn = _a[_i];
557
+ fee = fee.plus(new bignumber_1.default(txIn.value));
558
+ }
559
+ for (var _b = 0, _c = unsignedTransaction.outs; _b < _c.length; _b++) {
560
+ var txOut = _c[_b];
561
+ fee = fee.minus(new bignumber_1.default(txOut.value));
562
+ }
563
+ return (0, module_kit_1.newSignedTransaction)({
564
+ from: unsignedTransaction.ins.map(function (obj) { return obj.address; }),
565
+ to: unsignedTransaction.outs.filter(function (obj) { return !obj.isChange; }).map(function (obj) { return obj.recipient; }),
566
+ amount: unsignedTransaction.outs
567
+ .filter(function (obj) { return !obj.isChange; })
568
+ .map(function (obj) { return new bignumber_1.default(obj.value); })
569
+ .reduce(function (accumulator, currentValue) { return accumulator.plus(currentValue); })
570
+ .toString(10),
571
+ fee: fee.toString(10),
572
+ transaction: transactionBuilder.build().toHex()
573
+ });
574
+ };
575
+ BitcoinProtocolImpl.prototype.signMessageWithKeyPair = function (message, keyPair) {
576
+ return __awaiter(this, void 0, void 0, function () {
577
+ var hexSecretKey, signature;
578
+ return __generator(this, function (_a) {
579
+ switch (_a.label) {
580
+ case 0:
581
+ hexSecretKey = keyPair.secretKey.type === 'priv' ? (0, key_1.convertSecretKey)(keyPair.secretKey, 'hex') : (0, key_1.convertExtendedSecretKey)(keyPair.secretKey, 'hex');
582
+ return [4 /*yield*/, this.cryptoClient.signMessage(message, { privateKey: hexSecretKey.value })];
583
+ case 1:
584
+ signature = _a.sent();
585
+ return [2 /*return*/, (0, module_kit_1.newSignature)(signature, 'encoded')];
586
+ }
587
+ });
588
+ });
589
+ };
590
+ BitcoinProtocolImpl.prototype.decryptAsymmetricWithKeyPair = function (payload, keyPair) {
591
+ return __awaiter(this, void 0, void 0, function () {
592
+ var hexSecretKey, encodedExtendedSecretKey, node, derivedNode;
593
+ return __generator(this, function (_a) {
594
+ if (keyPair.secretKey.type === 'priv') {
595
+ hexSecretKey = (0, key_1.convertSecretKey)(keyPair.secretKey, 'hex');
596
+ }
597
+ else {
598
+ encodedExtendedSecretKey = (0, key_1.convertExtendedSecretKey)(keyPair.secretKey, 'encoded');
599
+ node = this.bitcoinJS.lib.HDNode.fromBase58(encodedExtendedSecretKey.value, this.bitcoinJS.config.network);
600
+ derivedNode = node.derive(0).derive(0);
601
+ hexSecretKey = (0, module_kit_1.newSecretKey)(derivedNode.keyPair.getPrivateKeyBuffer(), 'hex');
602
+ }
603
+ return [2 /*return*/, this.cryptoClient.decryptAsymmetric(payload, { publicKey: '', privateKey: hexSecretKey.value })];
604
+ });
605
+ });
606
+ };
607
+ BitcoinProtocolImpl.prototype.encryptAESWithSecretKey = function (payload, secretKey) {
608
+ return __awaiter(this, void 0, void 0, function () {
609
+ return __generator(this, function (_a) {
610
+ return [2 /*return*/, this.cryptoClient.encryptAES(payload, secretKey.value)];
611
+ });
612
+ });
613
+ };
614
+ BitcoinProtocolImpl.prototype.decryptAESWithSecretKey = function (payload, secretKey) {
615
+ return __awaiter(this, void 0, void 0, function () {
616
+ return __generator(this, function (_a) {
617
+ return [2 /*return*/, this.cryptoClient.decryptAES(payload, secretKey.value)];
618
+ });
619
+ });
620
+ };
621
+ // Online
622
+ BitcoinProtocolImpl.prototype.getNetwork = function () {
623
+ return __awaiter(this, void 0, void 0, function () {
624
+ return __generator(this, function (_a) {
625
+ return [2 /*return*/, this.options.network];
626
+ });
627
+ });
628
+ };
629
+ BitcoinProtocolImpl.prototype.getTransactionsForPublicKey = function (publicKey, limit, cursor) {
630
+ return __awaiter(this, void 0, void 0, function () {
631
+ return __generator(this, function (_a) {
632
+ switch (publicKey.type) {
633
+ case 'pub':
634
+ return [2 /*return*/, this.getTransactionsForNonExtendedPublicKey(publicKey, limit, cursor)];
635
+ case 'xpub':
636
+ return [2 /*return*/, this.getTransactionsForExtendedPublicKey(publicKey, limit, cursor)];
637
+ default:
638
+ (0, coinlib_core_1.assertNever)(publicKey);
639
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.BITCOIN, 'Public key type not supported');
640
+ }
641
+ return [2 /*return*/];
642
+ });
643
+ });
644
+ };
645
+ BitcoinProtocolImpl.prototype.getTransactionsForNonExtendedPublicKey = function (publicKey, limit, cursor) {
646
+ return __awaiter(this, void 0, void 0, function () {
647
+ var address;
648
+ return __generator(this, function (_a) {
649
+ switch (_a.label) {
650
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
651
+ case 1:
652
+ address = _a.sent();
653
+ return [2 /*return*/, this.getTransactionsForAddresses([address], limit, cursor)];
654
+ }
655
+ });
656
+ });
657
+ };
658
+ BitcoinProtocolImpl.prototype.getTransactionsForExtendedPublicKey = function (extendedPublicKey, limit, cursor) {
659
+ var _a;
660
+ return __awaiter(this, void 0, void 0, function () {
661
+ var encodedExtendedPublicKey, page, url, data, ourAddresses, airGapTransactions, _i, _b, transaction, tempAirGapTransactionFrom, tempAirGapTransactionTo, tempAirGapTransactionIsInbound, amount, _c, _d, vin, _e, _f, vout, airGapTransaction, hasNext;
662
+ return __generator(this, function (_g) {
663
+ switch (_g.label) {
664
+ case 0:
665
+ encodedExtendedPublicKey = this.convertExtendedPublicKey(extendedPublicKey, 'encoded');
666
+ page = (_a = cursor === null || cursor === void 0 ? void 0 : cursor.page) !== null && _a !== void 0 ? _a : 1;
667
+ url = "".concat(this.options.network.indexerApi, "/api/v2/xpub/").concat(encodedExtendedPublicKey.value, "?details=txs&tokens=used&pageSize=").concat(limit, "&page=").concat(page);
668
+ return [4 /*yield*/, index_1.default.get(url, {
669
+ responseType: 'json'
670
+ })];
671
+ case 1:
672
+ data = (_g.sent()).data;
673
+ ourAddresses = (data.tokens || []).filter(function (token) { return token.type === 'XPUBAddress'; }).map(function (token) { return token.name; });
674
+ airGapTransactions = [];
675
+ if (data.page === page) {
676
+ for (_i = 0, _b = data.transactions || []; _i < _b.length; _i++) {
677
+ transaction = _b[_i];
678
+ tempAirGapTransactionFrom = [];
679
+ tempAirGapTransactionTo = [];
680
+ tempAirGapTransactionIsInbound = true;
681
+ amount = new bignumber_1.default(0);
682
+ for (_c = 0, _d = transaction.vin; _c < _d.length; _c++) {
683
+ vin = _d[_c];
684
+ if ((0, common_1.containsSome)(vin.addresses, ourAddresses)) {
685
+ tempAirGapTransactionIsInbound = false;
686
+ }
687
+ tempAirGapTransactionFrom.push.apply(tempAirGapTransactionFrom, vin.addresses);
688
+ amount = amount.plus(vin.value);
689
+ }
690
+ for (_e = 0, _f = transaction.vout; _e < _f.length; _e++) {
691
+ vout = _f[_e];
692
+ if (vout.addresses) {
693
+ tempAirGapTransactionTo.push.apply(tempAirGapTransactionTo, vout.addresses);
694
+ // If receiving address is our address, and transaction is outbound => our change
695
+ if ((0, common_1.containsSome)(vout.addresses, ourAddresses) && !tempAirGapTransactionIsInbound) {
696
+ // remove only if related to this address
697
+ amount = amount.minus(vout.value);
698
+ }
699
+ // If receiving address is not ours, and transaction isbound => senders change
700
+ if (!(0, common_1.containsSome)(vout.addresses, ourAddresses) && tempAirGapTransactionIsInbound) {
701
+ amount = amount.minus(vout.value);
702
+ }
703
+ }
704
+ }
705
+ // deduct fee from amount
706
+ amount = amount.minus(transaction.fees);
707
+ airGapTransaction = {
708
+ from: tempAirGapTransactionFrom,
709
+ to: tempAirGapTransactionTo,
710
+ isInbound: tempAirGapTransactionIsInbound,
711
+ amount: (0, module_kit_1.newAmount)(amount, 'blockchain'),
712
+ fee: (0, module_kit_1.newAmount)(transaction.fees, 'blockchain'),
713
+ status: {
714
+ type: 'applied',
715
+ hash: transaction.txid,
716
+ block: transaction.blockHeight.toString()
717
+ },
718
+ network: this.options.network,
719
+ timestamp: transaction.blockTime
720
+ };
721
+ airGapTransactions.push(airGapTransaction);
722
+ }
723
+ }
724
+ hasNext = page < data.totalPages;
725
+ return [2 /*return*/, {
726
+ transactions: airGapTransactions,
727
+ cursor: {
728
+ hasNext: hasNext,
729
+ page: hasNext ? page + 1 : undefined
730
+ }
731
+ }];
732
+ }
733
+ });
734
+ });
735
+ };
736
+ BitcoinProtocolImpl.prototype.getTransactionsForAddress = function (address, limit, cursor) {
737
+ return __awaiter(this, void 0, void 0, function () {
738
+ return __generator(this, function (_a) {
739
+ return [2 /*return*/, this.getTransactionsForAddresses([address], limit, cursor)];
740
+ });
741
+ });
742
+ };
743
+ BitcoinProtocolImpl.prototype.getTransactionsForAddresses = function (addresses, limit, cursor) {
744
+ var _a;
745
+ return __awaiter(this, void 0, void 0, function () {
746
+ var airGapTransactions, page, url, data, _i, _b, transaction, tempAirGapTransactionFrom, tempAirGapTransactionTo, tempAirGapTransactionIsInbound, amount, _c, _d, vin, _e, _f, vout, airGapTransaction, hasNext;
747
+ return __generator(this, function (_g) {
748
+ switch (_g.label) {
749
+ case 0:
750
+ airGapTransactions = [];
751
+ page = (_a = cursor === null || cursor === void 0 ? void 0 : cursor.page) !== null && _a !== void 0 ? _a : 1;
752
+ url = "".concat(this.options.network.indexerApi, "/api/v2/address/").concat(addresses[0], "?page=").concat(page, "&pageSize=").concat(limit, "&details=txs");
753
+ return [4 /*yield*/, index_1.default.get(url, {
754
+ responseType: 'json'
755
+ })];
756
+ case 1:
757
+ data = (_g.sent()).data;
758
+ if (data.page == page) {
759
+ for (_i = 0, _b = data.transactions || []; _i < _b.length; _i++) {
760
+ transaction = _b[_i];
761
+ tempAirGapTransactionFrom = [];
762
+ tempAirGapTransactionTo = [];
763
+ tempAirGapTransactionIsInbound = true;
764
+ amount = new bignumber_1.default(0);
765
+ for (_c = 0, _d = transaction.vin; _c < _d.length; _c++) {
766
+ vin = _d[_c];
767
+ if (vin.addresses && (0, common_1.containsSome)(vin.addresses, addresses)) {
768
+ tempAirGapTransactionIsInbound = false;
769
+ }
770
+ tempAirGapTransactionFrom.push.apply(tempAirGapTransactionFrom, vin.addresses);
771
+ amount = vin.value ? amount.plus(vin.value) : amount;
772
+ }
773
+ for (_e = 0, _f = transaction.vout; _e < _f.length; _e++) {
774
+ vout = _f[_e];
775
+ if (vout.addresses) {
776
+ tempAirGapTransactionTo.push.apply(tempAirGapTransactionTo, vout.addresses);
777
+ // If receiving address is our address, and transaction is outbound => our change
778
+ if ((0, common_1.containsSome)(vout.addresses, addresses) && !tempAirGapTransactionIsInbound) {
779
+ // remove only if related to this address
780
+ amount = amount.minus(new bignumber_1.default(vout.value));
781
+ }
782
+ // If receiving address is not ours, and transaction isbound => senders change
783
+ if (!(0, common_1.containsSome)(vout.addresses, addresses) && tempAirGapTransactionIsInbound) {
784
+ amount = amount.minus(new bignumber_1.default(vout.value));
785
+ }
786
+ }
787
+ }
788
+ // deduct fee from amount
789
+ amount = amount.minus(new bignumber_1.default(transaction.fees));
790
+ airGapTransaction = {
791
+ from: tempAirGapTransactionFrom,
792
+ to: tempAirGapTransactionTo,
793
+ isInbound: tempAirGapTransactionIsInbound,
794
+ amount: (0, module_kit_1.newAmount)(amount, 'blockchain'),
795
+ fee: (0, module_kit_1.newAmount)(transaction.fees, 'blockchain'),
796
+ status: {
797
+ type: 'applied',
798
+ hash: transaction.txid,
799
+ block: transaction.blockHeight.toString()
800
+ },
801
+ network: this.options.network,
802
+ timestamp: transaction.blockTime
803
+ };
804
+ airGapTransactions.push(airGapTransaction);
805
+ }
806
+ }
807
+ hasNext = page < data.totalPages;
808
+ return [2 /*return*/, {
809
+ transactions: airGapTransactions,
810
+ cursor: {
811
+ hasNext: hasNext,
812
+ page: hasNext ? page + 1 : undefined
813
+ }
814
+ }];
815
+ }
816
+ });
817
+ });
818
+ };
819
+ BitcoinProtocolImpl.prototype.getBalanceOfPublicKey = function (publicKey) {
820
+ return __awaiter(this, void 0, void 0, function () {
821
+ return __generator(this, function (_a) {
822
+ switch (publicKey.type) {
823
+ case 'pub':
824
+ return [2 /*return*/, this.getBalanceOfNonExtendedPublicKey(publicKey)];
825
+ case 'xpub':
826
+ return [2 /*return*/, this.getBalanceOfExtendedPublicKey(publicKey)];
827
+ default:
828
+ (0, coinlib_core_1.assertNever)(publicKey);
829
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.BITCOIN, 'Unsupported public key type.');
830
+ }
831
+ return [2 /*return*/];
832
+ });
833
+ });
834
+ };
835
+ BitcoinProtocolImpl.prototype.getBalanceOfNonExtendedPublicKey = function (publicKey) {
836
+ return __awaiter(this, void 0, void 0, function () {
837
+ var address;
838
+ return __generator(this, function (_a) {
839
+ switch (_a.label) {
840
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
841
+ case 1:
842
+ address = _a.sent();
843
+ return [2 /*return*/, this.getBalanceOfAddresses([address])];
844
+ }
845
+ });
846
+ });
847
+ };
848
+ BitcoinProtocolImpl.prototype.getBalanceOfExtendedPublicKey = function (extendedPublicKey) {
849
+ return __awaiter(this, void 0, void 0, function () {
850
+ var encodedExtendedPublicKey, data;
851
+ return __generator(this, function (_a) {
852
+ switch (_a.label) {
853
+ case 0:
854
+ encodedExtendedPublicKey = this.convertExtendedPublicKey(extendedPublicKey, 'encoded');
855
+ return [4 /*yield*/, index_1.default.get("".concat(this.options.network.indexerApi, "/api/v2/xpub/").concat(encodedExtendedPublicKey.value, "?pageSize=1"), {
856
+ responseType: 'json'
857
+ })];
858
+ case 1:
859
+ data = (_a.sent()).data;
860
+ return [2 /*return*/, {
861
+ total: (0, module_kit_1.newAmount)(data.balance, 'blockchain')
862
+ }];
863
+ }
864
+ });
865
+ });
866
+ };
867
+ BitcoinProtocolImpl.prototype.getBalanceOfAddress = function (address) {
868
+ return __awaiter(this, void 0, void 0, function () {
869
+ return __generator(this, function (_a) {
870
+ return [2 /*return*/, this.getBalanceOfAddresses([address])];
871
+ });
872
+ });
873
+ };
874
+ BitcoinProtocolImpl.prototype.getBalanceOfAddresses = function (addresses) {
875
+ return __awaiter(this, void 0, void 0, function () {
876
+ var valueAccumulator, _i, addresses_1, address, data;
877
+ return __generator(this, function (_a) {
878
+ switch (_a.label) {
879
+ case 0:
880
+ valueAccumulator = new bignumber_1.default(0);
881
+ _i = 0, addresses_1 = addresses;
882
+ _a.label = 1;
883
+ case 1:
884
+ if (!(_i < addresses_1.length)) return [3 /*break*/, 4];
885
+ address = addresses_1[_i];
886
+ return [4 /*yield*/, index_1.default.get("".concat(this.options.network.indexerApi, "/api/v2/address/").concat(address, "?details=basic"), {
887
+ responseType: 'json'
888
+ })];
889
+ case 2:
890
+ data = (_a.sent()).data;
891
+ valueAccumulator = valueAccumulator.plus(new bignumber_1.default(data.balance));
892
+ _a.label = 3;
893
+ case 3:
894
+ _i++;
895
+ return [3 /*break*/, 1];
896
+ case 4: return [2 /*return*/, {
897
+ total: (0, module_kit_1.newAmount)(valueAccumulator, 'blockchain')
898
+ }];
899
+ }
900
+ });
901
+ });
902
+ };
903
+ BitcoinProtocolImpl.prototype.getTransactionMaxAmountWithPublicKey = function (publicKey, to, configuration) {
904
+ return __awaiter(this, void 0, void 0, function () {
905
+ return __generator(this, function (_a) {
906
+ switch (_a.label) {
907
+ case 0: return [4 /*yield*/, this.getBalanceOfPublicKey(publicKey)];
908
+ case 1: return [2 /*return*/, (_a.sent()).total];
909
+ }
910
+ });
911
+ });
912
+ };
913
+ BitcoinProtocolImpl.prototype.getTransactionFeeWithPublicKey = function (publicKey, details) {
914
+ return __awaiter(this, void 0, void 0, function () {
915
+ var result, estimatedFee, feeStepFactor, mediumFee, lowFee, highFee;
916
+ return __generator(this, function (_a) {
917
+ switch (_a.label) {
918
+ case 0: return [4 /*yield*/, index_1.default.get("".concat(this.options.network.indexerApi, "/api/v2/estimatefee/5"))];
919
+ case 1:
920
+ result = (_a.sent()).data.result;
921
+ estimatedFee = new bignumber_1.default((0, module_kit_1.newAmount)(result, 'BTC').blockchain(this.units).value);
922
+ if (estimatedFee.isZero()) {
923
+ return [2 /*return*/, this.feeDefaults];
924
+ }
925
+ feeStepFactor = new bignumber_1.default(0.5);
926
+ mediumFee = estimatedFee;
927
+ lowFee = mediumFee.minus(mediumFee.times(feeStepFactor)).integerValue(bignumber_1.default.ROUND_FLOOR);
928
+ highFee = mediumFee.plus(mediumFee.times(feeStepFactor)).integerValue(bignumber_1.default.ROUND_FLOOR);
929
+ return [2 /*return*/, {
930
+ low: (0, module_kit_1.newAmount)(lowFee, 'blockchain'),
931
+ medium: (0, module_kit_1.newAmount)(mediumFee, 'blockchain'),
932
+ high: (0, module_kit_1.newAmount)(highFee, 'blockchain')
933
+ }];
934
+ }
935
+ });
936
+ });
937
+ };
938
+ BitcoinProtocolImpl.prototype.prepareTransactionWithPublicKey = function (publicKey, details, configuration) {
939
+ return __awaiter(this, void 0, void 0, function () {
940
+ return __generator(this, function (_a) {
941
+ switch (publicKey.type) {
942
+ case 'pub':
943
+ return [2 /*return*/, this.prepareTransactionWithNonExtendedPublicKey(publicKey, details, configuration)];
944
+ case 'xpub':
945
+ return [2 /*return*/, this.prepareTransactionWithExtendedPublicKey(publicKey, details, configuration)];
946
+ default:
947
+ (0, coinlib_core_1.assertNever)(publicKey);
948
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.BITCOIN, 'Unuspported public key type.');
949
+ }
950
+ return [2 /*return*/];
951
+ });
952
+ });
953
+ };
954
+ BitcoinProtocolImpl.prototype.prepareTransactionWithNonExtendedPublicKey = function (publicKey, details, configuration) {
955
+ return __awaiter(this, void 0, void 0, function () {
956
+ var fee, estimatedFee, wrappedFee, transaction, address, utxos, totalRequiredBalance, valueAccumulator, _i, utxos_1, utxo, i, value, changeValue;
957
+ var _this = this;
958
+ return __generator(this, function (_a) {
959
+ switch (_a.label) {
960
+ case 0:
961
+ if (!((configuration === null || configuration === void 0 ? void 0 : configuration.fee) !== undefined)) return [3 /*break*/, 1];
962
+ fee = configuration.fee;
963
+ return [3 /*break*/, 3];
964
+ case 1: return [4 /*yield*/, this.getTransactionFeeWithPublicKey(publicKey, details)];
965
+ case 2:
966
+ estimatedFee = _a.sent();
967
+ fee = estimatedFee.medium;
968
+ _a.label = 3;
969
+ case 3:
970
+ wrappedFee = new bignumber_1.default((0, module_kit_1.newAmount)(fee).blockchain(this.units).value);
971
+ transaction = (0, module_kit_1.newUnsignedTransaction)({
972
+ ins: [],
973
+ outs: []
974
+ });
975
+ return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
976
+ case 4:
977
+ address = _a.sent();
978
+ return [4 /*yield*/, index_1.default.get("".concat(this.options.network.indexerApi, "/api/v2/utxo/").concat(address), {
979
+ responseType: 'json'
980
+ })];
981
+ case 5:
982
+ utxos = (_a.sent()).data;
983
+ totalRequiredBalance = details
984
+ .map(function (_a) {
985
+ var amount = _a.amount;
986
+ return new bignumber_1.default((0, module_kit_1.newAmount)(amount).blockchain(_this.units).value);
987
+ })
988
+ .reduce(function (accumulator, currentValue) { return accumulator.plus(currentValue); })
989
+ .plus(wrappedFee);
990
+ valueAccumulator = new bignumber_1.default(0);
991
+ for (_i = 0, utxos_1 = utxos; _i < utxos_1.length; _i++) {
992
+ utxo = utxos_1[_i];
993
+ valueAccumulator = valueAccumulator.plus(new bignumber_1.default(utxo.value));
994
+ transaction.ins.push({
995
+ txId: utxo.txid,
996
+ value: new bignumber_1.default(utxo.value).toString(10),
997
+ vout: utxo.vout,
998
+ address: address
999
+ });
1000
+ if (valueAccumulator.isGreaterThanOrEqualTo(totalRequiredBalance)) {
1001
+ break;
1002
+ }
1003
+ }
1004
+ if (valueAccumulator.isLessThan(totalRequiredBalance)) {
1005
+ throw new errors_1.BalanceError(coinlib_core_1.Domain.BITCOIN, "not enough balance, having ".concat(valueAccumulator.toFixed(), " of ").concat(totalRequiredBalance.toFixed()));
1006
+ }
1007
+ // tx.addInput(utxo.txid, utxo.vout)
1008
+ for (i = 0; i < details.length; i++) {
1009
+ value = (0, module_kit_1.newAmount)(details[i].amount).blockchain(this.units).value;
1010
+ transaction.outs.push({
1011
+ recipient: details[i].to,
1012
+ isChange: false,
1013
+ value: value
1014
+ });
1015
+ valueAccumulator = valueAccumulator.minus(value);
1016
+ // tx.addOutput(details[i].to, details[i].amount)
1017
+ }
1018
+ changeValue = valueAccumulator.minus(wrappedFee);
1019
+ if (changeValue.isGreaterThan(new bignumber_1.default(DUST_AMOUNT))) {
1020
+ transaction.outs.push({
1021
+ recipient: address,
1022
+ isChange: true,
1023
+ value: changeValue.toString(10)
1024
+ });
1025
+ }
1026
+ return [2 /*return*/, transaction];
1027
+ }
1028
+ });
1029
+ });
1030
+ };
1031
+ BitcoinProtocolImpl.prototype.prepareTransactionWithExtendedPublicKey = function (extendedPublicKey, details, configuration) {
1032
+ return __awaiter(this, void 0, void 0, function () {
1033
+ var targetFee, estimatedFee, wrappedFee, transaction, utxos, totalRequiredBalance, valueAccumulator, getPathIndexes, _i, utxos_2, utxo, indexes, derivedPublicKey, derivedAddress, i, value, lastUsedInternalAddress, changeValue, changeAddressIndex, derivedPublicKey, derivedAddress;
1034
+ var _this = this;
1035
+ return __generator(this, function (_a) {
1036
+ switch (_a.label) {
1037
+ case 0:
1038
+ if (!((configuration === null || configuration === void 0 ? void 0 : configuration.fee) !== undefined)) return [3 /*break*/, 1];
1039
+ targetFee = configuration.fee;
1040
+ return [3 /*break*/, 3];
1041
+ case 1: return [4 /*yield*/, this.getTransactionFeeWithPublicKey(extendedPublicKey, details)];
1042
+ case 2:
1043
+ estimatedFee = _a.sent();
1044
+ targetFee = estimatedFee.medium;
1045
+ _a.label = 3;
1046
+ case 3:
1047
+ wrappedFee = new bignumber_1.default((0, module_kit_1.newAmount)(targetFee).blockchain(this.units).value);
1048
+ transaction = (0, module_kit_1.newUnsignedTransaction)({
1049
+ ins: [],
1050
+ outs: []
1051
+ });
1052
+ return [4 /*yield*/, index_1.default
1053
+ .get("".concat(this.options.network.indexerApi, "/api/v2/utxo/").concat(extendedPublicKey.value, "?confirmed=true"), {
1054
+ responseType: 'json'
1055
+ })
1056
+ .catch(function (error) {
1057
+ throw new errors_1.NetworkError(coinlib_core_1.Domain.BITCOIN, error);
1058
+ })];
1059
+ case 4:
1060
+ utxos = (_a.sent()).data;
1061
+ if (utxos.length <= 0) {
1062
+ throw new errors_1.BalanceError(coinlib_core_1.Domain.BITCOIN, 'not enough balance'); // no transactions found on those addresses, probably won't find anything in the next ones
1063
+ }
1064
+ totalRequiredBalance = details
1065
+ .map(function (_a) {
1066
+ var amount = _a.amount;
1067
+ return new bignumber_1.default((0, module_kit_1.newAmount)(amount).blockchain(_this.units).value);
1068
+ })
1069
+ .reduce(function (accumulator, currentValue) { return accumulator.plus(currentValue); })
1070
+ .plus(wrappedFee);
1071
+ valueAccumulator = new bignumber_1.default(0);
1072
+ getPathIndexes = function (path) {
1073
+ var result = path
1074
+ .split('/')
1075
+ .slice(-2)
1076
+ .map(function (item) { return parseInt(item, 10); })
1077
+ .filter(function (item) { return !isNaN(item); });
1078
+ if (result.length !== 2) {
1079
+ throw new errors_1.ConditionViolationError(coinlib_core_1.Domain.BITCOIN, 'Unexpected path format');
1080
+ }
1081
+ return [result[0], result[1]];
1082
+ };
1083
+ _i = 0, utxos_2 = utxos;
1084
+ _a.label = 5;
1085
+ case 5:
1086
+ if (!(_i < utxos_2.length)) return [3 /*break*/, 9];
1087
+ utxo = utxos_2[_i];
1088
+ valueAccumulator = valueAccumulator.plus(utxo.value);
1089
+ indexes = getPathIndexes(utxo.path);
1090
+ return [4 /*yield*/, this.deriveFromExtendedPublicKey(extendedPublicKey, indexes[0], indexes[1])];
1091
+ case 6:
1092
+ derivedPublicKey = _a.sent();
1093
+ return [4 /*yield*/, this.getAddressFromPublicKey(derivedPublicKey)];
1094
+ case 7:
1095
+ derivedAddress = _a.sent();
1096
+ if (derivedAddress === utxo.address) {
1097
+ transaction.ins.push({
1098
+ txId: utxo.txid,
1099
+ value: new bignumber_1.default(utxo.value).toString(10),
1100
+ vout: utxo.vout,
1101
+ address: utxo.address,
1102
+ derivationPath: indexes.join('/')
1103
+ });
1104
+ }
1105
+ else {
1106
+ throw new errors_1.InvalidValueError(coinlib_core_1.Domain.BITCOIN, "Invalid address ".concat(JSON.stringify(utxo.address), " returned from API"));
1107
+ }
1108
+ if (valueAccumulator.isGreaterThanOrEqualTo(totalRequiredBalance)) {
1109
+ return [3 /*break*/, 9];
1110
+ }
1111
+ _a.label = 8;
1112
+ case 8:
1113
+ _i++;
1114
+ return [3 /*break*/, 5];
1115
+ case 9:
1116
+ if (valueAccumulator.isLessThan(totalRequiredBalance)) {
1117
+ throw new errors_1.BalanceError(coinlib_core_1.Domain.BITCOIN, 'not enough balance');
1118
+ }
1119
+ for (i = 0; i < details.length; i++) {
1120
+ value = (0, module_kit_1.newAmount)(details[i].amount).blockchain(this.units).value;
1121
+ transaction.outs.push({
1122
+ recipient: details[i].to,
1123
+ isChange: false,
1124
+ value: value,
1125
+ derivationPath: '' // TODO: Remove this as soon as our serializer supports optional properties
1126
+ });
1127
+ valueAccumulator = valueAccumulator.minus(value);
1128
+ }
1129
+ lastUsedInternalAddress = Math.max.apply(Math, __spreadArray([-1], utxos
1130
+ .map(function (utxo) { return getPathIndexes(utxo.path); })
1131
+ .filter(function (indexes) { return indexes[0] === 1; })
1132
+ .map(function (indexes) { return indexes[1]; }), false));
1133
+ changeValue = valueAccumulator.minus(wrappedFee);
1134
+ if (!changeValue.isGreaterThan(new bignumber_1.default(DUST_AMOUNT))) return [3 /*break*/, 12];
1135
+ changeAddressIndex = lastUsedInternalAddress + 1;
1136
+ return [4 /*yield*/, this.deriveFromExtendedPublicKey(extendedPublicKey, 1, changeAddressIndex)];
1137
+ case 10:
1138
+ derivedPublicKey = _a.sent();
1139
+ return [4 /*yield*/, this.getAddressFromPublicKey(derivedPublicKey)];
1140
+ case 11:
1141
+ derivedAddress = _a.sent();
1142
+ transaction.outs.push({
1143
+ recipient: derivedAddress,
1144
+ isChange: true,
1145
+ value: changeValue.toString(10),
1146
+ derivationPath: changeAddressIndex.toString()
1147
+ });
1148
+ _a.label = 12;
1149
+ case 12: return [2 /*return*/, transaction];
1150
+ }
1151
+ });
1152
+ });
1153
+ };
1154
+ BitcoinProtocolImpl.prototype.broadcastTransaction = function (transaction) {
1155
+ return __awaiter(this, void 0, void 0, function () {
1156
+ var data;
1157
+ return __generator(this, function (_a) {
1158
+ switch (_a.label) {
1159
+ case 0: return [4 /*yield*/, index_1.default.post("".concat(this.options.network.indexerApi, "/api/v2/sendtx/"), transaction.transaction)];
1160
+ case 1:
1161
+ data = (_a.sent()).data;
1162
+ return [2 /*return*/, data.result];
1163
+ }
1164
+ });
1165
+ });
1166
+ };
1167
+ // Custom
1168
+ BitcoinProtocolImpl.prototype.convertExtendedPublicKey = function (extendedPublicKey, targetFormat) {
1169
+ return (0, key_1.convertExtendedPublicKey)(extendedPublicKey, {
1170
+ format: targetFormat,
1171
+ type: 'xpub'
1172
+ });
1173
+ };
1174
+ return BitcoinProtocolImpl;
1175
+ }());
1176
+ exports.BitcoinProtocolImpl = BitcoinProtocolImpl;
1177
+ // Factory
1178
+ function createBitcoinProtocol(options) {
1179
+ if (options === void 0) { options = {}; }
1180
+ return new BitcoinProtocolImpl(options);
1181
+ }
1182
+ exports.createBitcoinProtocol = createBitcoinProtocol;
1183
+ exports.BITCOIN_MAINNET_PROTOCOL_NETWORK = {
1184
+ name: 'Mainnet',
1185
+ type: 'mainnet',
1186
+ rpcUrl: '',
1187
+ indexerApi: 'https://bitcoin.prod.gke.papers.tech'
1188
+ };
1189
+ var DEFAULT_BITCOIN_PROTOCOL_NETWORK = exports.BITCOIN_MAINNET_PROTOCOL_NETWORK;
1190
+ function createBitcoinProtocolOptions(network) {
1191
+ if (network === void 0) { network = {}; }
1192
+ return {
1193
+ network: network.type === 'custom'
1194
+ ? __assign(__assign(__assign({}, DEFAULT_BITCOIN_PROTOCOL_NETWORK), { bitcoinjsNetworkName: 'bitcoin' }), network) : __assign(__assign({}, DEFAULT_BITCOIN_PROTOCOL_NETWORK), network)
1195
+ };
1196
+ }
1197
+ exports.createBitcoinProtocolOptions = createBitcoinProtocolOptions;
1198
+ //# sourceMappingURL=BitcoinProtocol.js.map