@airgap/cosmos-core 0.13.11-beta.14

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 (77) hide show
  1. package/LICENSE.md +7 -0
  2. package/README.md +11 -0
  3. package/index.d.ts +1 -0
  4. package/index.js +18 -0
  5. package/index.js.map +1 -0
  6. package/package.json +59 -0
  7. package/v1/index.d.ts +18 -0
  8. package/v1/index.js +29 -0
  9. package/v1/index.js.map +1 -0
  10. package/v1/node/CosmosNodeClient.d.ts +29 -0
  11. package/v1/node/CosmosNodeClient.js +383 -0
  12. package/v1/node/CosmosNodeClient.js.map +1 -0
  13. package/v1/protocol/CosmosBaseProtocol.d.ts +109 -0
  14. package/v1/protocol/CosmosBaseProtocol.js +1005 -0
  15. package/v1/protocol/CosmosBaseProtocol.js.map +1 -0
  16. package/v1/protocol/CosmosCryptoClient.d.ts +8 -0
  17. package/v1/protocol/CosmosCryptoClient.js +90 -0
  18. package/v1/protocol/CosmosCryptoClient.js.map +1 -0
  19. package/v1/serializer/v3/schemas/converter/transaction-converter.d.ts +7 -0
  20. package/v1/serializer/v3/schemas/converter/transaction-converter.js +37 -0
  21. package/v1/serializer/v3/schemas/converter/transaction-converter.js.map +1 -0
  22. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-cosmos.d.ts +4 -0
  23. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-cosmos.js +3 -0
  24. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-cosmos.js.map +1 -0
  25. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-cosmos.d.ts +3 -0
  26. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-cosmos.js +3 -0
  27. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-cosmos.js.map +1 -0
  28. package/v1/serializer/v3/schemas/generated/transaction-sign-request-cosmos.json +100 -0
  29. package/v1/serializer/v3/schemas/generated/transaction-sign-response-cosmos.json +19 -0
  30. package/v1/serializer/v3/validators/transaction-validators.d.ts +7 -0
  31. package/v1/serializer/v3/validators/transaction-validators.js +88 -0
  32. package/v1/serializer/v3/validators/transaction-validators.js.map +1 -0
  33. package/v1/types/crypto.d.ts +2 -0
  34. package/v1/types/crypto.js +3 -0
  35. package/v1/types/crypto.js.map +1 -0
  36. package/v1/types/data/CosmosAddress.d.ts +7 -0
  37. package/v1/types/data/CosmosAddress.js +30 -0
  38. package/v1/types/data/CosmosAddress.js.map +1 -0
  39. package/v1/types/data/CosmosCoin.d.ts +18 -0
  40. package/v1/types/data/CosmosCoin.js +56 -0
  41. package/v1/types/data/CosmosCoin.js.map +1 -0
  42. package/v1/types/data/CosmosFee.d.ts +15 -0
  43. package/v1/types/data/CosmosFee.js +31 -0
  44. package/v1/types/data/CosmosFee.js.map +1 -0
  45. package/v1/types/data/transaction/CosmosTransaction.d.ts +36 -0
  46. package/v1/types/data/transaction/CosmosTransaction.js +109 -0
  47. package/v1/types/data/transaction/CosmosTransaction.js.map +1 -0
  48. package/v1/types/data/transaction/message/CosmosDelegateMessage.d.ts +19 -0
  49. package/v1/types/data/transaction/message/CosmosDelegateMessage.js +70 -0
  50. package/v1/types/data/transaction/message/CosmosDelegateMessage.js.map +1 -0
  51. package/v1/types/data/transaction/message/CosmosMessage.d.ts +38 -0
  52. package/v1/types/data/transaction/message/CosmosMessage.js +47 -0
  53. package/v1/types/data/transaction/message/CosmosMessage.js.map +1 -0
  54. package/v1/types/data/transaction/message/CosmosSendMessage.d.ts +19 -0
  55. package/v1/types/data/transaction/message/CosmosSendMessage.js +83 -0
  56. package/v1/types/data/transaction/message/CosmosSendMessage.js.map +1 -0
  57. package/v1/types/data/transaction/message/CosmosWithdrawDelegationRewardMessage.d.ts +23 -0
  58. package/v1/types/data/transaction/message/CosmosWithdrawDelegationRewardMessage.js +61 -0
  59. package/v1/types/data/transaction/message/CosmosWithdrawDelegationRewardMessage.js.map +1 -0
  60. package/v1/types/protocol.d.ts +10 -0
  61. package/v1/types/protocol.js +3 -0
  62. package/v1/types/protocol.js.map +1 -0
  63. package/v1/types/rpc.d.ts +286 -0
  64. package/v1/types/rpc.js +3 -0
  65. package/v1/types/rpc.js.map +1 -0
  66. package/v1/types/transaction.d.ts +50 -0
  67. package/v1/types/transaction.js +18 -0
  68. package/v1/types/transaction.js.map +1 -0
  69. package/v1/utils/key.d.ts +3 -0
  70. package/v1/utils/key.js +20 -0
  71. package/v1/utils/key.js.map +1 -0
  72. package/v1/utils/signature.d.ts +2 -0
  73. package/v1/utils/signature.js +13 -0
  74. package/v1/utils/signature.js.map +1 -0
  75. package/v1/utils/transaction.d.ts +1 -0
  76. package/v1/utils/transaction.js +8 -0
  77. package/v1/utils/transaction.js.map +1 -0
@@ -0,0 +1,1005 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (_) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ var __importDefault = (this && this.__importDefault) || function (mod) {
50
+ return (mod && mod.__esModule) ? mod : { "default": mod };
51
+ };
52
+ Object.defineProperty(exports, "__esModule", { value: true });
53
+ exports.CosmosBaseProtocolImpl = void 0;
54
+ var coinlib_core_1 = require("@airgap/coinlib-core");
55
+ var module_kit_1 = require("@airgap/module-kit");
56
+ var crypto_1 = require("@airgap/crypto");
57
+ var cosmjs_1 = require("@airgap/coinlib-core/dependencies/src/cosmjs");
58
+ var bignumber_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/bignumber.js-9.0.0/bignumber"));
59
+ var errors_1 = require("@airgap/coinlib-core/src/errors");
60
+ var CosmosNodeClient_1 = require("../node/CosmosNodeClient");
61
+ var CosmosTransaction_1 = require("../types/data/transaction/CosmosTransaction");
62
+ var transaction_1 = require("../types/transaction");
63
+ var key_1 = require("../utils/key");
64
+ var CosmosCryptoClient_1 = require("./CosmosCryptoClient");
65
+ // @ts-ignore
66
+ var SECP256K1 = require("@airgap/coinlib-core/dependencies/src/secp256k1-3.7.1/elliptic");
67
+ // @ts-ignore
68
+ var index_1 = require("@airgap/coinlib-core/dependencies/src/bip32-2.0.4/src/index");
69
+ // @ts-ignore
70
+ var sha = require("@airgap/coinlib-core/dependencies/src/sha.js-2.4.11/index");
71
+ var CosmosAddress_1 = require("../types/data/CosmosAddress");
72
+ var CosmosMessage_1 = require("../types/data/transaction/message/CosmosMessage");
73
+ var CosmosSendMessage_1 = require("../types/data/transaction/message/CosmosSendMessage");
74
+ var CosmosDelegateMessage_1 = require("../types/data/transaction/message/CosmosDelegateMessage");
75
+ var CosmosWithdrawDelegationRewardMessage_1 = require("../types/data/transaction/message/CosmosWithdrawDelegationRewardMessage");
76
+ var CosmosCoin_1 = require("../types/data/CosmosCoin");
77
+ var CosmosFee_1 = require("../types/data/CosmosFee");
78
+ var signature_1 = require("../utils/signature");
79
+ var transaction_2 = require("../utils/transaction");
80
+ var assert_1 = require("@airgap/coinlib-core/src/utils/assert");
81
+ var CosmosBaseProtocolImpl = /** @class */ (function () {
82
+ function CosmosBaseProtocolImpl(options) {
83
+ this.cryptoConfiguration = {
84
+ algorithm: 'secp256k1'
85
+ };
86
+ this.options = options;
87
+ this.nodeClient = new CosmosNodeClient_1.CosmosNodeClient(this.options.network.rpcUrl, this.options.network.useCORSProxy);
88
+ this.cryptoClient = new CosmosCryptoClient_1.CosmosCryptoClient();
89
+ }
90
+ CosmosBaseProtocolImpl.prototype.getKeyPairFromSecretKey = function (secretKey) {
91
+ return __awaiter(this, void 0, void 0, function () {
92
+ var hexSecretKey, publicKey;
93
+ return __generator(this, function (_a) {
94
+ hexSecretKey = (0, key_1.convertSecretKey)(secretKey, 'hex');
95
+ publicKey = SECP256K1.publicKeyCreate(Buffer.from(secretKey.value, 'hex'));
96
+ return [2 /*return*/, {
97
+ secretKey: hexSecretKey,
98
+ publicKey: (0, module_kit_1.newPublicKey)(Buffer.from(publicKey, 'binary').toString('hex'), 'hex')
99
+ }];
100
+ });
101
+ });
102
+ };
103
+ CosmosBaseProtocolImpl.prototype.getCryptoConfiguration = function () {
104
+ return __awaiter(this, void 0, void 0, function () {
105
+ return __generator(this, function (_a) {
106
+ return [2 /*return*/, this.cryptoConfiguration];
107
+ });
108
+ });
109
+ };
110
+ CosmosBaseProtocolImpl.prototype.getKeyPairFromDerivative = function (derivative) {
111
+ return __awaiter(this, void 0, void 0, function () {
112
+ var bip32Node, bip32, secretKey, publicKey;
113
+ return __generator(this, function (_a) {
114
+ bip32Node = (0, crypto_1.encodeDerivative)('bip32', derivative);
115
+ bip32 = (0, index_1.fromBase58)(bip32Node.secretKey);
116
+ secretKey = bip32.privateKey;
117
+ if (secretKey === undefined) {
118
+ throw new errors_1.InvalidValueError(coinlib_core_1.Domain.COSMOS, 'Cannot generate secret key');
119
+ }
120
+ publicKey = bip32.publicKey;
121
+ return [2 /*return*/, {
122
+ secretKey: (0, module_kit_1.newSecretKey)(secretKey.toString('hex'), 'hex'),
123
+ publicKey: (0, module_kit_1.newPublicKey)(publicKey.toString('hex'), 'hex')
124
+ }];
125
+ });
126
+ });
127
+ };
128
+ CosmosBaseProtocolImpl.prototype.signTransactionWithSecretKey = function (transaction, secretKey) {
129
+ return __awaiter(this, void 0, void 0, function () {
130
+ var hexSecretKey, privateKeyBuffer, publicKey, hexPublicKey, publicKeyBuffer, encodedObject, signBytes, sha256Hash, hash, signed, sigBase64, txBytes;
131
+ return __generator(this, function (_a) {
132
+ switch (_a.label) {
133
+ case 0:
134
+ hexSecretKey = (0, key_1.convertSecretKey)(secretKey, 'hex');
135
+ privateKeyBuffer = Buffer.from(hexSecretKey.value, 'hex');
136
+ return [4 /*yield*/, this.getKeyPairFromSecretKey(secretKey)];
137
+ case 1:
138
+ publicKey = (_a.sent()).publicKey;
139
+ hexPublicKey = (0, key_1.convertPublicKey)(publicKey, 'hex');
140
+ publicKeyBuffer = Buffer.from(hexPublicKey.value, 'hex');
141
+ encodedObject = CosmosTransaction_1.CosmosTransaction.fromJSON(transaction).toEncodeObject();
142
+ return [4 /*yield*/, (0, cosmjs_1.prepareSignBytes)(encodedObject, transaction.fee, Uint8Array.from(publicKeyBuffer), new bignumber_1.default(transaction.sequence).toNumber(), transaction.chainID, new bignumber_1.default(transaction.accountNumber).toNumber())];
143
+ case 2:
144
+ signBytes = _a.sent();
145
+ sha256Hash = sha('sha256').update(signBytes).digest();
146
+ hash = Buffer.from(sha256Hash);
147
+ signed = SECP256K1.sign(hash, privateKeyBuffer);
148
+ sigBase64 = Buffer.from(signed.signature, 'binary').toString('base64');
149
+ return [4 /*yield*/, (0, cosmjs_1.encodeTxBytes)(encodedObject, transaction.fee, Uint8Array.from(publicKeyBuffer), new bignumber_1.default(transaction.sequence).toNumber(), {
150
+ signature: sigBase64,
151
+ pub_key: {
152
+ type: 'tendermint/PubKeySecp256k1',
153
+ value: publicKeyBuffer.toString('base64')
154
+ }
155
+ }, transaction.chainID, new bignumber_1.default(transaction.accountNumber).toNumber())];
156
+ case 3:
157
+ txBytes = _a.sent();
158
+ return [2 /*return*/, (0, module_kit_1.newSignedTransaction)({
159
+ encoded: Buffer.from(txBytes).toString('base64')
160
+ })];
161
+ }
162
+ });
163
+ });
164
+ };
165
+ CosmosBaseProtocolImpl.prototype.getAddressFromPublicKey = function (publicKey) {
166
+ return __awaiter(this, void 0, void 0, function () {
167
+ return __generator(this, function (_a) {
168
+ return [2 /*return*/, CosmosAddress_1.CosmosAddress.from(publicKey, this.options.addressPrefix).asString()];
169
+ });
170
+ });
171
+ };
172
+ CosmosBaseProtocolImpl.prototype.getDetailsFromTransaction = function (transaction, publicKey) {
173
+ return __awaiter(this, void 0, void 0, function () {
174
+ return __generator(this, function (_a) {
175
+ switch (transaction.type) {
176
+ case 'signed':
177
+ return [2 /*return*/, this.getDetailsFromSignedTransaction(transaction)];
178
+ case 'unsigned':
179
+ return [2 /*return*/, this.getDetailsFromUnsignedTransaction(transaction)];
180
+ default:
181
+ (0, coinlib_core_1.assertNever)(transaction);
182
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.COSMOS, 'Unsupported transaction type.');
183
+ }
184
+ return [2 /*return*/];
185
+ });
186
+ });
187
+ };
188
+ CosmosBaseProtocolImpl.prototype.getDetailsFromSignedTransaction = function (transaction) {
189
+ var _a;
190
+ return __awaiter(this, void 0, void 0, function () {
191
+ var bytes, decoded, fee, result;
192
+ var _this = this;
193
+ return __generator(this, function (_b) {
194
+ switch (_b.label) {
195
+ case 0:
196
+ bytes = Uint8Array.from(Buffer.from(transaction.encoded, 'base64'));
197
+ return [4 /*yield*/, (0, cosmjs_1.decodeTxBytes)(bytes)];
198
+ case 1:
199
+ decoded = _b.sent();
200
+ fee = ((_a = decoded.fee) === null || _a === void 0 ? void 0 : _a.amount)
201
+ .map(function (_a) {
202
+ var amount = _a.amount;
203
+ return new bignumber_1.default(amount);
204
+ })
205
+ .reduce(function (current, next) { return current.plus(next); })
206
+ .toString(10);
207
+ result = decoded.messages
208
+ .map(function (message) {
209
+ var type = message.typeUrl;
210
+ switch (type) {
211
+ case CosmosMessage_1.CosmosMessageType.Send.value:
212
+ var sendMessage = CosmosSendMessage_1.CosmosSendMessage.fromEncodeObject(message);
213
+ return sendMessage.toAirGapTransaction(_this.options.network, fee);
214
+ case CosmosMessage_1.CosmosMessageType.Undelegate.value:
215
+ case CosmosMessage_1.CosmosMessageType.Delegate.value:
216
+ var delegateMessage = CosmosDelegateMessage_1.CosmosDelegateMessage.fromEncodeObject(message);
217
+ return delegateMessage.toAirGapTransaction(_this.options.network, fee);
218
+ case CosmosMessage_1.CosmosMessageType.WithdrawDelegationReward.value:
219
+ var withdrawMessage = CosmosWithdrawDelegationRewardMessage_1.CosmosWithdrawDelegationRewardMessage.fromEncodeObject(message);
220
+ return withdrawMessage.toAirGapTransaction(_this.options.network, fee);
221
+ default:
222
+ throw new errors_1.InvalidValueError(coinlib_core_1.Domain.COSMOS, 'Unknown transaction');
223
+ }
224
+ })
225
+ .map(function (tx) {
226
+ if (!tx.json) {
227
+ tx.json = {};
228
+ }
229
+ tx.json.memo = decoded.memo;
230
+ if (decoded.signerInfos.length > 0) {
231
+ tx.json.sequence = decoded.signerInfos[0].sequence.toString(10);
232
+ }
233
+ tx.arbitraryData = decoded.memo;
234
+ return tx;
235
+ });
236
+ return [2 /*return*/, result];
237
+ }
238
+ });
239
+ });
240
+ };
241
+ CosmosBaseProtocolImpl.prototype.getDetailsFromUnsignedTransaction = function (transaction) {
242
+ return __awaiter(this, void 0, void 0, function () {
243
+ return __generator(this, function (_a) {
244
+ return [2 /*return*/, CosmosTransaction_1.CosmosTransaction.fromJSON(transaction).toAirGapTransactions(this.options.network)];
245
+ });
246
+ });
247
+ };
248
+ CosmosBaseProtocolImpl.prototype.getNetwork = function () {
249
+ return __awaiter(this, void 0, void 0, function () {
250
+ return __generator(this, function (_a) {
251
+ return [2 /*return*/, this.options.network];
252
+ });
253
+ });
254
+ };
255
+ CosmosBaseProtocolImpl.prototype.getTransactionsForPublicKey = function (publicKey, limit, cursor) {
256
+ return __awaiter(this, void 0, void 0, function () {
257
+ var address;
258
+ return __generator(this, function (_a) {
259
+ switch (_a.label) {
260
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
261
+ case 1:
262
+ address = _a.sent();
263
+ return [2 /*return*/, this.getTransactionsForAddress(address, limit, cursor)];
264
+ }
265
+ });
266
+ });
267
+ };
268
+ CosmosBaseProtocolImpl.prototype.getBalanceOfPublicKey = function (publicKey, configuration) {
269
+ return __awaiter(this, void 0, void 0, function () {
270
+ var address;
271
+ return __generator(this, function (_a) {
272
+ switch (_a.label) {
273
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
274
+ case 1:
275
+ address = _a.sent();
276
+ return [2 /*return*/, this.getBalanceOfAddress(address)];
277
+ }
278
+ });
279
+ });
280
+ };
281
+ CosmosBaseProtocolImpl.prototype.getTransactionMaxAmountWithPublicKey = function (publicKey, to, configuration) {
282
+ return __awaiter(this, void 0, void 0, function () {
283
+ var units, _a, total, transferable, balance, fee, estimatedFee, amountWithoutFees;
284
+ return __generator(this, function (_b) {
285
+ switch (_b.label) {
286
+ case 0: return [4 /*yield*/, this.getMetadata()];
287
+ case 1:
288
+ units = (_b.sent()).units;
289
+ return [4 /*yield*/, this.getBalanceOfPublicKey(publicKey)];
290
+ case 2:
291
+ _a = _b.sent(), total = _a.total, transferable = _a.transferable;
292
+ balance = new bignumber_1.default((0, module_kit_1.newAmount)(transferable !== null && transferable !== void 0 ? transferable : total).blockchain(units).value);
293
+ if (!((configuration === null || configuration === void 0 ? void 0 : configuration.fee) !== undefined)) return [3 /*break*/, 3];
294
+ fee = configuration.fee;
295
+ return [3 /*break*/, 5];
296
+ case 3: return [4 /*yield*/, this.getTransactionFeeWithPublicKey(publicKey, to.map(function (recipient) { return ({
297
+ to: recipient,
298
+ amount: (0, module_kit_1.newAmount)(balance.div(to.length).decimalPlaces(0, bignumber_1.default.ROUND_CEIL), 'blockchain')
299
+ }); }))];
300
+ case 4:
301
+ estimatedFee = _b.sent();
302
+ fee = (0, module_kit_1.newAmount)(estimatedFee.medium).blockchain(units);
303
+ if (balance.lte(fee.value)) {
304
+ fee = (0, module_kit_1.newAmount)(0, 'blockchain');
305
+ }
306
+ _b.label = 5;
307
+ case 5:
308
+ fee = (0, module_kit_1.newAmount)(fee).blockchain(units);
309
+ amountWithoutFees = balance.minus(fee.value);
310
+ if (amountWithoutFees.isNegative()) {
311
+ amountWithoutFees = new bignumber_1.default(0);
312
+ }
313
+ return [2 /*return*/, (0, module_kit_1.newAmount)(amountWithoutFees, 'blockchain')];
314
+ }
315
+ });
316
+ });
317
+ };
318
+ CosmosBaseProtocolImpl.prototype.prepareTransactionWithPublicKey = function (publicKey, details, configuration) {
319
+ var _a, _b;
320
+ return __awaiter(this, void 0, void 0, function () {
321
+ var fee, estimatedFee, units, wrappedFee, address, nodeInfo, account, _c, total, transferable, balance, messages, i, message, memo, transaction;
322
+ return __generator(this, function (_d) {
323
+ switch (_d.label) {
324
+ case 0:
325
+ if (!((configuration === null || configuration === void 0 ? void 0 : configuration.fee) !== undefined)) return [3 /*break*/, 1];
326
+ fee = configuration.fee;
327
+ return [3 /*break*/, 3];
328
+ case 1: return [4 /*yield*/, this.getTransactionFeeWithPublicKey(publicKey, details)];
329
+ case 2:
330
+ estimatedFee = _d.sent();
331
+ fee = estimatedFee.medium;
332
+ _d.label = 3;
333
+ case 3: return [4 /*yield*/, this.getMetadata()];
334
+ case 4:
335
+ units = (_d.sent()).units;
336
+ wrappedFee = new bignumber_1.default((0, module_kit_1.newAmount)(fee).blockchain(units).value);
337
+ return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
338
+ case 5:
339
+ address = _d.sent();
340
+ return [4 /*yield*/, this.nodeClient.fetchNodeInfo()];
341
+ case 6:
342
+ nodeInfo = _d.sent();
343
+ return [4 /*yield*/, this.nodeClient.fetchAccount(address)];
344
+ case 7:
345
+ account = _d.sent();
346
+ return [4 /*yield*/, this.getBalanceOfPublicKey(publicKey)];
347
+ case 8:
348
+ _c = _d.sent(), total = _c.total, transferable = _c.transferable;
349
+ balance = new bignumber_1.default((0, module_kit_1.newAmount)(transferable !== null && transferable !== void 0 ? transferable : total).blockchain(units).value);
350
+ if (balance.lt(details.reduce(function (acc, next) { return acc.plus((0, module_kit_1.newAmount)(next.amount).blockchain(units).value); }, wrappedFee))) {
351
+ throw new coinlib_core_1.BalanceError(coinlib_core_1.Domain.COSMOS, 'not enough balance');
352
+ }
353
+ messages = [];
354
+ for (i = 0; i < details.length; ++i) {
355
+ message = new CosmosSendMessage_1.CosmosSendMessage(address, details[i].to, [
356
+ new CosmosCoin_1.CosmosCoin(this.options.baseUnit, (0, module_kit_1.newAmount)(details[i].amount).blockchain(units).value)
357
+ ]);
358
+ messages.push(message);
359
+ }
360
+ memo = (_a = configuration === null || configuration === void 0 ? void 0 : configuration.arbitraryData) !== null && _a !== void 0 ? _a : '';
361
+ transaction = new CosmosTransaction_1.CosmosTransaction(messages, new CosmosFee_1.CosmosFee([new CosmosCoin_1.CosmosCoin(this.options.baseUnit, wrappedFee.toString(10))], (0, module_kit_1.newAmount)(this.options.defaultGas).blockchain(units).value), memo, nodeInfo.network, account.value.account_number, (_b = account.value.sequence) !== null && _b !== void 0 ? _b : '0');
362
+ return [2 /*return*/, (0, module_kit_1.newUnsignedTransaction)({
363
+ messages: transaction.messages.map(function (message) { return message.toJSON(); }),
364
+ fee: transaction.fee.toJSON(),
365
+ memo: transaction.memo,
366
+ chainID: transaction.chainID,
367
+ accountNumber: transaction.accountNumber,
368
+ sequence: transaction.sequence
369
+ })];
370
+ }
371
+ });
372
+ });
373
+ };
374
+ CosmosBaseProtocolImpl.prototype.broadcastTransaction = function (transaction) {
375
+ return __awaiter(this, void 0, void 0, function () {
376
+ return __generator(this, function (_a) {
377
+ return [2 /*return*/, this.nodeClient.broadcastSignedTransaction(transaction.encoded)];
378
+ });
379
+ });
380
+ };
381
+ CosmosBaseProtocolImpl.prototype.signMessageWithKeyPair = function (message, keyPair) {
382
+ return __awaiter(this, void 0, void 0, function () {
383
+ var hexSecretKey, signature;
384
+ return __generator(this, function (_a) {
385
+ switch (_a.label) {
386
+ case 0:
387
+ hexSecretKey = (0, key_1.convertSecretKey)(keyPair.secretKey, 'hex');
388
+ return [4 /*yield*/, this.cryptoClient.signMessage(message, { privateKey: hexSecretKey.value })];
389
+ case 1:
390
+ signature = _a.sent();
391
+ return [2 /*return*/, (0, module_kit_1.newSignature)(signature, 'hex')];
392
+ }
393
+ });
394
+ });
395
+ };
396
+ CosmosBaseProtocolImpl.prototype.verifyMessageWithPublicKey = function (message, signature, publicKey) {
397
+ return __awaiter(this, void 0, void 0, function () {
398
+ var hexSignature, hexPublicKey;
399
+ return __generator(this, function (_a) {
400
+ hexSignature = (0, signature_1.convertSignature)(signature, 'hex');
401
+ hexPublicKey = (0, key_1.convertPublicKey)(publicKey, 'hex');
402
+ return [2 /*return*/, this.cryptoClient.verifyMessage(message, hexSignature.value, hexPublicKey.value)];
403
+ });
404
+ });
405
+ };
406
+ CosmosBaseProtocolImpl.prototype.decryptAsymmetricWithKeyPair = function (payload, keyPair) {
407
+ return __awaiter(this, void 0, void 0, function () {
408
+ var hexSecretKey, hexPublicKey;
409
+ return __generator(this, function (_a) {
410
+ hexSecretKey = (0, key_1.convertSecretKey)(keyPair.secretKey, 'hex');
411
+ hexPublicKey = (0, key_1.convertPublicKey)(keyPair.publicKey, 'hex');
412
+ return [2 /*return*/, this.cryptoClient.decryptAsymmetric(payload, {
413
+ privateKey: hexSecretKey.value,
414
+ publicKey: hexPublicKey.value
415
+ })];
416
+ });
417
+ });
418
+ };
419
+ CosmosBaseProtocolImpl.prototype.encryptAsymmetricWithPublicKey = function (payload, publicKey) {
420
+ return __awaiter(this, void 0, void 0, function () {
421
+ var hexPublicKey;
422
+ return __generator(this, function (_a) {
423
+ hexPublicKey = (0, key_1.convertPublicKey)(publicKey, 'hex');
424
+ return [2 /*return*/, this.cryptoClient.encryptAsymmetric(payload, hexPublicKey.value)];
425
+ });
426
+ });
427
+ };
428
+ CosmosBaseProtocolImpl.prototype.encryptAESWithSecretKey = function (payload, secretKey) {
429
+ return __awaiter(this, void 0, void 0, function () {
430
+ var hexSecretKey;
431
+ return __generator(this, function (_a) {
432
+ hexSecretKey = (0, key_1.convertSecretKey)(secretKey, 'hex');
433
+ return [2 /*return*/, this.cryptoClient.encryptAES(payload, hexSecretKey.value)];
434
+ });
435
+ });
436
+ };
437
+ CosmosBaseProtocolImpl.prototype.decryptAESWithSecretKey = function (payload, secretKey) {
438
+ return __awaiter(this, void 0, void 0, function () {
439
+ var hexSecretKey;
440
+ return __generator(this, function (_a) {
441
+ hexSecretKey = (0, key_1.convertSecretKey)(secretKey, 'hex');
442
+ return [2 /*return*/, this.cryptoClient.decryptAES(payload, hexSecretKey.value)];
443
+ });
444
+ });
445
+ };
446
+ CosmosBaseProtocolImpl.prototype.getTransactionsForAddress = function (address, limit, cursor) {
447
+ return __awaiter(this, void 0, void 0, function () {
448
+ var promises, senderOffset, recipientOffset, senderTotal, recipientTotal, senderLimit, recipientLimit, transactions, sentTransactions, receivedTransactions, allTransactions, result, _loop_1, _i, allTransactions_1, transaction;
449
+ var _a;
450
+ var _this = this;
451
+ return __generator(this, function (_b) {
452
+ switch (_b.label) {
453
+ case 0:
454
+ promises = [];
455
+ senderOffset = 0;
456
+ recipientOffset = 0;
457
+ senderTotal = 0;
458
+ recipientTotal = 0;
459
+ senderLimit = 0;
460
+ recipientLimit = 0;
461
+ if (!cursor) return [3 /*break*/, 1];
462
+ senderOffset = cursor.sender.offset;
463
+ recipientOffset = cursor.recipient.offset;
464
+ senderTotal = cursor.sender.total;
465
+ recipientTotal = cursor.recipient.total;
466
+ senderLimit = (0, transaction_2.calculateTransactionLimit)(limit, senderTotal, recipientTotal, senderOffset, recipientOffset);
467
+ if (senderOffset <= Math.floor(senderTotal / senderLimit) * senderLimit) {
468
+ promises.push(this.nodeClient.fetchSendTransactionsFor(address, senderLimit, senderOffset, true));
469
+ }
470
+ else {
471
+ promises.push(new Promise(function (resolve) {
472
+ resolve({ txs: [], tx_responses: [], pagination: { total: String(senderTotal) } });
473
+ }));
474
+ }
475
+ recipientLimit = (0, transaction_2.calculateTransactionLimit)(limit, recipientTotal, senderTotal, recipientOffset, senderOffset);
476
+ if (recipientOffset <= Math.floor(recipientTotal / recipientLimit) * recipientLimit) {
477
+ promises.push(this.nodeClient.fetchSendTransactionsFor(address, recipientLimit, recipientOffset, false));
478
+ }
479
+ else {
480
+ promises.push(new Promise(function (resolve) {
481
+ resolve({ txs: [], tx_responses: [], pagination: { total: String(recipientTotal) } });
482
+ }));
483
+ }
484
+ return [3 /*break*/, 3];
485
+ case 1:
486
+ ;
487
+ return [4 /*yield*/, Promise.all([
488
+ this.nodeClient
489
+ .fetchSendTransactionsFor(address, 1, 0, true)
490
+ .then(function (response) { return new bignumber_1.default(response.pagination.total).toNumber(); }),
491
+ this.nodeClient
492
+ .fetchSendTransactionsFor(address, 1, 0, false)
493
+ .then(function (response) { return new bignumber_1.default(response.pagination.total).toNumber(); })
494
+ ])];
495
+ case 2:
496
+ _a = _b.sent(), senderTotal = _a[0], recipientTotal = _a[1];
497
+ senderLimit = (0, transaction_2.calculateTransactionLimit)(limit, senderTotal, recipientTotal, senderOffset, recipientOffset);
498
+ recipientLimit = (0, transaction_2.calculateTransactionLimit)(limit, recipientTotal, senderTotal, recipientOffset, senderOffset);
499
+ promises.push(this.nodeClient.fetchSendTransactionsFor(address, senderLimit, senderOffset, true), this.nodeClient.fetchSendTransactionsFor(address, recipientLimit, recipientOffset, false));
500
+ _b.label = 3;
501
+ case 3: return [4 /*yield*/, Promise.all(promises)];
502
+ case 4:
503
+ transactions = _b.sent();
504
+ sentTransactions = transactions[0];
505
+ receivedTransactions = transactions[1];
506
+ allTransactions = sentTransactions === null || sentTransactions === void 0 ? void 0 : sentTransactions.tx_responses.concat(receivedTransactions === null || receivedTransactions === void 0 ? void 0 : receivedTransactions.tx_responses);
507
+ result = [];
508
+ _loop_1 = function (transaction) {
509
+ var timestamp = new Date(transaction.timestamp).getTime() / 1000;
510
+ var fee = transaction.tx.auth_info.fee.amount
511
+ .filter(function (coin) { return coin.denom === 'uatom'; })
512
+ .map(function (coin) { return new bignumber_1.default(coin.amount); })
513
+ .reduce(function (current, next) { return current.plus(next); });
514
+ result = result.concat(transaction.tx.body.messages.map(function (msg) {
515
+ var tx = {
516
+ isInbound: false,
517
+ amount: (0, module_kit_1.newAmount)('0', 'blockchain'),
518
+ fee: (0, module_kit_1.newAmount)(fee, 'blockchain'),
519
+ network: _this.options.network,
520
+ status: {
521
+ type: 'unknown',
522
+ hash: transaction.txhash
523
+ },
524
+ timestamp: timestamp
525
+ };
526
+ switch (msg['@type']) {
527
+ case CosmosMessage_1.CosmosMessageTypeValue.UNDELEGATE:
528
+ return __assign(__assign({}, tx), { from: [msg.validator_address], to: [msg.delegator_address] });
529
+ case CosmosMessage_1.CosmosMessageTypeValue.WITHDRAW_DELEGATION_REWARD:
530
+ return __assign(__assign({}, tx), { from: [msg.delegator_address], to: [msg.validator_address] });
531
+ case CosmosMessage_1.CosmosMessageTypeValue.DELEGATE:
532
+ return __assign(__assign({}, tx), { from: [msg.delegator_address], to: [msg.validator_address] });
533
+ default:
534
+ return __assign(__assign({}, tx), { from: [msg.from_address], to: [msg.to_address], isInbound: msg.to_address === address, amount: (0, module_kit_1.newAmount)(msg.amount[0].amount, 'blockchain') });
535
+ }
536
+ }));
537
+ };
538
+ for (_i = 0, allTransactions_1 = allTransactions; _i < allTransactions_1.length; _i++) {
539
+ transaction = allTransactions_1[_i];
540
+ _loop_1(transaction);
541
+ }
542
+ return [2 /*return*/, {
543
+ transactions: result,
544
+ cursor: {
545
+ hasNext: senderOffset + senderLimit < senderTotal || recipientOffset + recipientLimit < recipientTotal,
546
+ limit: limit,
547
+ sender: {
548
+ total: senderTotal,
549
+ offset: senderOffset + senderLimit
550
+ },
551
+ recipient: {
552
+ total: recipientTotal,
553
+ offset: recipientOffset + recipientLimit
554
+ }
555
+ }
556
+ }];
557
+ }
558
+ });
559
+ });
560
+ };
561
+ CosmosBaseProtocolImpl.prototype.getBalanceOfAddress = function (address, _configuration) {
562
+ return __awaiter(this, void 0, void 0, function () {
563
+ var metadata, _a, total, available;
564
+ return __generator(this, function (_b) {
565
+ switch (_b.label) {
566
+ case 0: return [4 /*yield*/, this.getMetadata()];
567
+ case 1:
568
+ metadata = _b.sent();
569
+ return [4 /*yield*/, this.nodeClient.fetchBalance(address, this.options.baseUnit)];
570
+ case 2:
571
+ _a = _b.sent(), total = _a.total, available = _a.available;
572
+ return [2 /*return*/, {
573
+ total: (0, module_kit_1.newAmount)(total).blockchain(metadata.units),
574
+ transferable: (0, module_kit_1.newAmount)(available).blockchain(metadata.units)
575
+ }];
576
+ }
577
+ });
578
+ });
579
+ };
580
+ // DELEGATION
581
+ CosmosBaseProtocolImpl.prototype.getDefaultDelegatee = function () {
582
+ return __awaiter(this, void 0, void 0, function () {
583
+ var validators;
584
+ return __generator(this, function (_a) {
585
+ switch (_a.label) {
586
+ case 0: return [4 /*yield*/, this.nodeClient.fetchValidators()];
587
+ case 1:
588
+ validators = _a.sent();
589
+ return [2 /*return*/, validators.length > 0 ? validators[0].operator_address : ''];
590
+ }
591
+ });
592
+ });
593
+ };
594
+ CosmosBaseProtocolImpl.prototype.getCurrentDelegateesForPublicKey = function (publicKey) {
595
+ return __awaiter(this, void 0, void 0, function () {
596
+ var address;
597
+ return __generator(this, function (_a) {
598
+ switch (_a.label) {
599
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
600
+ case 1:
601
+ address = _a.sent();
602
+ return [2 /*return*/, this.getCurrentDelegateesForAddress(address)];
603
+ }
604
+ });
605
+ });
606
+ };
607
+ CosmosBaseProtocolImpl.prototype.getCurrentDelegateesForAddress = function (address) {
608
+ return __awaiter(this, void 0, void 0, function () {
609
+ var delegations;
610
+ return __generator(this, function (_a) {
611
+ switch (_a.label) {
612
+ case 0: return [4 /*yield*/, this.nodeClient.fetchDelegations(address)];
613
+ case 1:
614
+ delegations = _a.sent();
615
+ return [2 /*return*/, delegations.map(function (delegation) { return delegation.delegation.validator_address; })];
616
+ }
617
+ });
618
+ });
619
+ };
620
+ CosmosBaseProtocolImpl.prototype.getDelegateeDetails = function (address) {
621
+ return __awaiter(this, void 0, void 0, function () {
622
+ var validator, statusCodes;
623
+ return __generator(this, function (_a) {
624
+ switch (_a.label) {
625
+ case 0: return [4 /*yield*/, this.nodeClient.fetchValidator(address)];
626
+ case 1:
627
+ validator = _a.sent();
628
+ statusCodes = { 0: 'jailed', 1: 'inactive', 2: 'active' };
629
+ return [2 /*return*/, {
630
+ name: validator.description.moniker,
631
+ status: statusCodes[validator.status],
632
+ address: validator.operator_address
633
+ }];
634
+ }
635
+ });
636
+ });
637
+ };
638
+ CosmosBaseProtocolImpl.prototype.isPublicKeyDelegating = function (publicKey) {
639
+ return __awaiter(this, void 0, void 0, function () {
640
+ var address;
641
+ return __generator(this, function (_a) {
642
+ switch (_a.label) {
643
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
644
+ case 1:
645
+ address = _a.sent();
646
+ return [2 /*return*/, this.isAddressDelegating(address)];
647
+ }
648
+ });
649
+ });
650
+ };
651
+ CosmosBaseProtocolImpl.prototype.isAddressDelegating = function (address) {
652
+ return __awaiter(this, void 0, void 0, function () {
653
+ var delegations;
654
+ return __generator(this, function (_a) {
655
+ switch (_a.label) {
656
+ case 0: return [4 /*yield*/, this.nodeClient.fetchDelegations(address)];
657
+ case 1:
658
+ delegations = _a.sent();
659
+ return [2 /*return*/, delegations.length > 0];
660
+ }
661
+ });
662
+ });
663
+ };
664
+ CosmosBaseProtocolImpl.prototype.getDelegatorDetailsFromPublicKey = function (publicKey) {
665
+ return __awaiter(this, void 0, void 0, function () {
666
+ var address;
667
+ return __generator(this, function (_a) {
668
+ switch (_a.label) {
669
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
670
+ case 1:
671
+ address = _a.sent();
672
+ return [2 /*return*/, this.getDelegatorDetailsFromAddress(address)];
673
+ }
674
+ });
675
+ });
676
+ };
677
+ CosmosBaseProtocolImpl.prototype.getDelegatorDetailsFromAddress = function (address) {
678
+ return __awaiter(this, void 0, void 0, function () {
679
+ return __generator(this, function (_a) {
680
+ return [2 /*return*/, this.getDelegatorDetails(address)];
681
+ });
682
+ });
683
+ };
684
+ CosmosBaseProtocolImpl.prototype.getDelegatorDetails = function (address, validator) {
685
+ var _a;
686
+ return __awaiter(this, void 0, void 0, function () {
687
+ var results, metadata, totalBalance, availableBalance, delegations, rewardDetails, unclaimedRewards, unclaimedTotalRewards, unclaimedValidatorRewards, isDelegating, availableActions;
688
+ return __generator(this, function (_b) {
689
+ switch (_b.label) {
690
+ case 0: return [4 /*yield*/, Promise.all([
691
+ this.getBalanceOfAddress(address),
692
+ this.nodeClient.fetchDelegations(address).catch(function () { return []; }),
693
+ this.nodeClient.fetchRewardDetails(address).catch(function () { return []; })
694
+ ])];
695
+ case 1:
696
+ results = _b.sent();
697
+ return [4 /*yield*/, this.getMetadata()];
698
+ case 2:
699
+ metadata = _b.sent();
700
+ totalBalance = (0, module_kit_1.newAmount)(results[0].total).blockchain(metadata.units);
701
+ availableBalance = results[0].transferable ? (0, module_kit_1.newAmount)(results[0].transferable).blockchain(metadata.units) : totalBalance;
702
+ delegations = results[1];
703
+ rewardDetails = results[2];
704
+ unclaimedRewards = rewardDetails.map(function (details) {
705
+ var _a, _b;
706
+ return [
707
+ details.validator_address,
708
+ (_b = (_a = details.reward) === null || _a === void 0 ? void 0 : _a.reduce(function (total, next) { return total.plus(next.amount); }, new bignumber_1.default(0)).decimalPlaces(0, bignumber_1.default.ROUND_FLOOR)) !== null && _b !== void 0 ? _b : new bignumber_1.default(0)
709
+ ];
710
+ });
711
+ unclaimedTotalRewards = unclaimedRewards.reduce(function (total, next) { return total.plus(next[1]); }, new bignumber_1.default(0));
712
+ unclaimedValidatorRewards = validator
713
+ ? ((_a = unclaimedRewards.find(function (_a) {
714
+ var validatorAddress = _a[0], _ = _a[1];
715
+ return validatorAddress === validator;
716
+ })) === null || _a === void 0 ? void 0 : _a[1]) || new bignumber_1.default(0)
717
+ : undefined;
718
+ isDelegating = validator
719
+ ? delegations.some(function (delegation) { return delegation.delegation.validator_address === validator; })
720
+ : delegations.length > 0;
721
+ return [4 /*yield*/, this.getAvailableDelegatorActions(isDelegating, new bignumber_1.default(availableBalance.value), unclaimedTotalRewards, unclaimedValidatorRewards)];
722
+ case 3:
723
+ availableActions = _b.sent();
724
+ return [2 /*return*/, {
725
+ address: address,
726
+ balance: totalBalance.value,
727
+ delegatees: delegations.map(function (delegation) { return delegation.delegation.validator_address; }),
728
+ availableActions: availableActions
729
+ }];
730
+ }
731
+ });
732
+ });
733
+ };
734
+ CosmosBaseProtocolImpl.prototype.getAvailableDelegatorActions = function (isDelegating, availableBalance, unclaimedTotalRewards, unclaimedDelegationRewards) {
735
+ var _a, _b, _c;
736
+ return __awaiter(this, void 0, void 0, function () {
737
+ var actions, metadata, requiredFee, hasSufficientBalance;
738
+ return __generator(this, function (_d) {
739
+ switch (_d.label) {
740
+ case 0:
741
+ actions = [];
742
+ return [4 /*yield*/, this.getMetadata()];
743
+ case 1:
744
+ metadata = _d.sent();
745
+ requiredFee = new bignumber_1.default((_c = (_b = (_a = metadata.fee) === null || _a === void 0 ? void 0 : _a.defaults) === null || _b === void 0 ? void 0 : _b.low.value) !== null && _c !== void 0 ? _c : '0');
746
+ hasSufficientBalance = availableBalance.gt(requiredFee);
747
+ if (hasSufficientBalance) {
748
+ actions.push({
749
+ type: transaction_1.CosmosDelegationActionType.DELEGATE,
750
+ args: ['validator', 'amount']
751
+ });
752
+ }
753
+ if (isDelegating) {
754
+ actions.push({
755
+ type: transaction_1.CosmosDelegationActionType.UNDELEGATE,
756
+ args: ['validator', 'amount']
757
+ });
758
+ }
759
+ if (unclaimedTotalRewards.gt(0)) {
760
+ actions.push({
761
+ type: transaction_1.CosmosDelegationActionType.WITHDRAW_ALL_REWARDS
762
+ });
763
+ }
764
+ if (unclaimedDelegationRewards === null || unclaimedDelegationRewards === void 0 ? void 0 : unclaimedDelegationRewards.gt(0)) {
765
+ actions.push({
766
+ type: transaction_1.CosmosDelegationActionType.WITHDRAW_VALIDATOR_REWARDS,
767
+ args: ['validator']
768
+ });
769
+ }
770
+ return [2 /*return*/, actions];
771
+ }
772
+ });
773
+ });
774
+ };
775
+ CosmosBaseProtocolImpl.prototype.getDelegationDetailsFromPublicKey = function (publicKey, delegatees) {
776
+ return __awaiter(this, void 0, void 0, function () {
777
+ var address;
778
+ return __generator(this, function (_a) {
779
+ switch (_a.label) {
780
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
781
+ case 1:
782
+ address = _a.sent();
783
+ return [2 /*return*/, this.getDelegationDetailsFromAddress(address, delegatees)];
784
+ }
785
+ });
786
+ });
787
+ };
788
+ CosmosBaseProtocolImpl.prototype.getDelegationDetailsFromAddress = function (address, delegatees) {
789
+ return __awaiter(this, void 0, void 0, function () {
790
+ var validator, results, delegatorDetails, validatorDetails;
791
+ return __generator(this, function (_a) {
792
+ switch (_a.label) {
793
+ case 0:
794
+ if (delegatees.length > 1) {
795
+ return [2 /*return*/, Promise.reject('Multiple validators for a single delegation are not supported.')];
796
+ }
797
+ validator = delegatees[0];
798
+ return [4 /*yield*/, Promise.all([this.getDelegatorDetails(address, validator), this.getDelegateeDetails(validator)])];
799
+ case 1:
800
+ results = _a.sent();
801
+ delegatorDetails = results[0];
802
+ validatorDetails = results[1];
803
+ return [2 /*return*/, {
804
+ delegator: delegatorDetails,
805
+ delegatees: [validatorDetails]
806
+ }];
807
+ }
808
+ });
809
+ });
810
+ };
811
+ CosmosBaseProtocolImpl.prototype.prepareDelegatorActionFromPublicKey = function (publicKey, type, data) {
812
+ return __awaiter(this, void 0, void 0, function () {
813
+ var _a;
814
+ return __generator(this, function (_b) {
815
+ switch (_b.label) {
816
+ case 0:
817
+ _a = type;
818
+ switch (_a) {
819
+ case transaction_1.CosmosDelegationActionType.DELEGATE: return [3 /*break*/, 1];
820
+ case transaction_1.CosmosDelegationActionType.UNDELEGATE: return [3 /*break*/, 3];
821
+ case transaction_1.CosmosDelegationActionType.WITHDRAW_ALL_REWARDS: return [3 /*break*/, 5];
822
+ case transaction_1.CosmosDelegationActionType.WITHDRAW_VALIDATOR_REWARDS: return [3 /*break*/, 7];
823
+ }
824
+ return [3 /*break*/, 9];
825
+ case 1:
826
+ (0, assert_1.assertFields)("".concat(type, " action"), data, 'validator', 'amount');
827
+ return [4 /*yield*/, this.delegate(publicKey, data.validator, data.amount, false)];
828
+ case 2: return [2 /*return*/, [_b.sent()]];
829
+ case 3:
830
+ (0, assert_1.assertFields)("".concat(type, " action"), data, 'validator', 'amount');
831
+ return [4 /*yield*/, this.undelegate(publicKey, data.validator, data.amount)];
832
+ case 4: return [2 /*return*/, [_b.sent()]];
833
+ case 5: return [4 /*yield*/, this.withdrawDelegationRewards(publicKey, [])];
834
+ case 6: return [2 /*return*/, [_b.sent()]];
835
+ case 7:
836
+ (0, assert_1.assertFields)("".concat(type, " action"), data, 'validator');
837
+ return [4 /*yield*/, this.withdrawDelegationRewards(publicKey, [data.validator])];
838
+ case 8: return [2 /*return*/, [_b.sent()]];
839
+ case 9: return [2 /*return*/, Promise.reject("Delegator action type ".concat(type, " is not supported."))];
840
+ }
841
+ });
842
+ });
843
+ };
844
+ CosmosBaseProtocolImpl.prototype.undelegate = function (publicKey, validatorAddress, amount, memo) {
845
+ return __awaiter(this, void 0, void 0, function () {
846
+ return __generator(this, function (_a) {
847
+ return [2 /*return*/, this.delegate(publicKey, validatorAddress, amount, true, memo)];
848
+ });
849
+ });
850
+ };
851
+ CosmosBaseProtocolImpl.prototype.delegate = function (publicKey, validatorAddress, amount, undelegate, memo) {
852
+ var _a;
853
+ return __awaiter(this, void 0, void 0, function () {
854
+ var address, nodeInfo, account, metadata, message;
855
+ return __generator(this, function (_b) {
856
+ switch (_b.label) {
857
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
858
+ case 1:
859
+ address = _b.sent();
860
+ return [4 /*yield*/, this.nodeClient.fetchNodeInfo()];
861
+ case 2:
862
+ nodeInfo = _b.sent();
863
+ return [4 /*yield*/, this.nodeClient.fetchAccount(address)];
864
+ case 3:
865
+ account = _b.sent();
866
+ return [4 /*yield*/, this.getMetadata()];
867
+ case 4:
868
+ metadata = _b.sent();
869
+ message = new CosmosDelegateMessage_1.CosmosDelegateMessage(address, Array.isArray(validatorAddress) ? validatorAddress[0] : validatorAddress, new CosmosCoin_1.CosmosCoin(this.options.baseUnit, (0, module_kit_1.newAmount)(amount).blockchain(metadata.units).value), undelegate);
870
+ return [2 /*return*/, new CosmosTransaction_1.CosmosTransaction([message], new CosmosFee_1.CosmosFee([new CosmosCoin_1.CosmosCoin(this.options.baseUnit, (0, module_kit_1.newAmount)(metadata.fee.defaults.low).blockchain(metadata.units).value)], (0, module_kit_1.newAmount)(this.options.defaultGas).blockchain(metadata.units).value), memo !== undefined ? memo : '', nodeInfo.network, account.value.account_number, (_a = account.value.sequence) !== null && _a !== void 0 ? _a : '0')];
871
+ }
872
+ });
873
+ });
874
+ };
875
+ CosmosBaseProtocolImpl.prototype.withdrawDelegationRewards = function (publicKey, _validatorAddresses, memo) {
876
+ var _a;
877
+ return __awaiter(this, void 0, void 0, function () {
878
+ var validatorAddresses, address_1, rewards, filteredRewards, address, nodeInfo, account, messages, metadata;
879
+ return __generator(this, function (_b) {
880
+ switch (_b.label) {
881
+ case 0:
882
+ if (!(_validatorAddresses.length > 0)) return [3 /*break*/, 1];
883
+ validatorAddresses = _validatorAddresses;
884
+ return [3 /*break*/, 4];
885
+ case 1: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
886
+ case 2:
887
+ address_1 = _b.sent();
888
+ return [4 /*yield*/, this.nodeClient.fetchRewardDetails(address_1)];
889
+ case 3:
890
+ rewards = _b.sent();
891
+ filteredRewards = rewards.filter(function (reward) {
892
+ return reward.reward
893
+ ? reward.reward
894
+ .reduce(function (total, next) { return total.plus(new bignumber_1.default(next.amount)); }, new bignumber_1.default(0))
895
+ .decimalPlaces(0, bignumber_1.default.ROUND_FLOOR)
896
+ .gt(0)
897
+ : false;
898
+ });
899
+ validatorAddresses = filteredRewards.map(function (reward) { return reward.validator_address; });
900
+ _b.label = 4;
901
+ case 4: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
902
+ case 5:
903
+ address = _b.sent();
904
+ return [4 /*yield*/, this.nodeClient.fetchNodeInfo()];
905
+ case 6:
906
+ nodeInfo = _b.sent();
907
+ return [4 /*yield*/, this.nodeClient.fetchAccount(address)];
908
+ case 7:
909
+ account = _b.sent();
910
+ messages = validatorAddresses.map(function (validatorAddress) { return new CosmosWithdrawDelegationRewardMessage_1.CosmosWithdrawDelegationRewardMessage(address, validatorAddress); });
911
+ return [4 /*yield*/, this.getMetadata()];
912
+ case 8:
913
+ metadata = _b.sent();
914
+ return [2 /*return*/, new CosmosTransaction_1.CosmosTransaction(messages, new CosmosFee_1.CosmosFee([new CosmosCoin_1.CosmosCoin(this.options.baseUnit, (0, module_kit_1.newAmount)(metadata.fee.defaults.low).blockchain(metadata.units).value)], (0, module_kit_1.newAmount)(this.options.defaultGas).blockchain(metadata.units).value), memo !== undefined ? memo : '', nodeInfo.network, account.value.account_number, (_a = account.value.sequence) !== null && _a !== void 0 ? _a : '0')];
915
+ }
916
+ });
917
+ });
918
+ };
919
+ CosmosBaseProtocolImpl.prototype.withdrawAllDelegationRewards = function (delegatorAddress, fee, memo) {
920
+ var _a;
921
+ return __awaiter(this, void 0, void 0, function () {
922
+ var nodeInfo, account, metadata;
923
+ return __generator(this, function (_b) {
924
+ switch (_b.label) {
925
+ case 0: return [4 /*yield*/, this.nodeClient.fetchNodeInfo()];
926
+ case 1:
927
+ nodeInfo = _b.sent();
928
+ return [4 /*yield*/, this.nodeClient.fetchAccount(delegatorAddress)];
929
+ case 2:
930
+ account = _b.sent();
931
+ return [4 /*yield*/, this.getMetadata()];
932
+ case 3:
933
+ metadata = _b.sent();
934
+ return [2 /*return*/, this.nodeClient.withdrawAllDelegationRewards(delegatorAddress, nodeInfo.network, account.value.account_number, (_a = account.value.sequence) !== null && _a !== void 0 ? _a : '0', new bignumber_1.default((0, module_kit_1.newAmount)(this.options.defaultGas).blockchain(metadata.units).value), new bignumber_1.default((0, module_kit_1.newAmount)(fee).blockchain(metadata.units).value), memo !== undefined ? memo : '')];
935
+ }
936
+ });
937
+ });
938
+ };
939
+ CosmosBaseProtocolImpl.prototype.fetchTotalReward = function (delegatorAddress) {
940
+ return __awaiter(this, void 0, void 0, function () {
941
+ return __generator(this, function (_a) {
942
+ return [2 /*return*/, this.nodeClient.fetchTotalReward(delegatorAddress, this.options.baseUnit)];
943
+ });
944
+ });
945
+ };
946
+ CosmosBaseProtocolImpl.prototype.fetchRewardForDelegation = function (delegatorAddress, validatorAddress) {
947
+ return __awaiter(this, void 0, void 0, function () {
948
+ return __generator(this, function (_a) {
949
+ return [2 /*return*/, this.nodeClient.fetchRewardForDelegation(delegatorAddress, validatorAddress, this.options.baseUnit)];
950
+ });
951
+ });
952
+ };
953
+ CosmosBaseProtocolImpl.prototype.fetchDelegations = function (address) {
954
+ return __awaiter(this, void 0, void 0, function () {
955
+ return __generator(this, function (_a) {
956
+ return [2 /*return*/, this.nodeClient.fetchDelegations(address)];
957
+ });
958
+ });
959
+ };
960
+ CosmosBaseProtocolImpl.prototype.fetchTotalDelegatedAmount = function (address) {
961
+ return __awaiter(this, void 0, void 0, function () {
962
+ return __generator(this, function (_a) {
963
+ return [2 /*return*/, this.nodeClient.fetchTotalDelegatedAmount(address, this.options.baseUnit)];
964
+ });
965
+ });
966
+ };
967
+ CosmosBaseProtocolImpl.prototype.fetchValidator = function (address) {
968
+ return __awaiter(this, void 0, void 0, function () {
969
+ return __generator(this, function (_a) {
970
+ return [2 /*return*/, this.nodeClient.fetchValidator(address)];
971
+ });
972
+ });
973
+ };
974
+ CosmosBaseProtocolImpl.prototype.fetchValidators = function () {
975
+ return __awaiter(this, void 0, void 0, function () {
976
+ return __generator(this, function (_a) {
977
+ return [2 /*return*/, this.nodeClient.fetchValidators()];
978
+ });
979
+ });
980
+ };
981
+ CosmosBaseProtocolImpl.prototype.fetchUnbondingDelegations = function (delegatorAddress) {
982
+ return __awaiter(this, void 0, void 0, function () {
983
+ return __generator(this, function (_a) {
984
+ return [2 /*return*/, this.nodeClient.fetchUnbondingDelegations(delegatorAddress)];
985
+ });
986
+ });
987
+ };
988
+ CosmosBaseProtocolImpl.prototype.fetchTotalUnbondingAmount = function (address) {
989
+ return __awaiter(this, void 0, void 0, function () {
990
+ return __generator(this, function (_a) {
991
+ return [2 /*return*/, this.nodeClient.fetchTotalUnbondingAmount(address, this.options.baseUnit)];
992
+ });
993
+ });
994
+ };
995
+ CosmosBaseProtocolImpl.prototype.fetchSelfDelegation = function (address) {
996
+ return __awaiter(this, void 0, void 0, function () {
997
+ return __generator(this, function (_a) {
998
+ return [2 /*return*/, this.nodeClient.fetchSelfDelegation(address)];
999
+ });
1000
+ });
1001
+ };
1002
+ return CosmosBaseProtocolImpl;
1003
+ }());
1004
+ exports.CosmosBaseProtocolImpl = CosmosBaseProtocolImpl;
1005
+ //# sourceMappingURL=CosmosBaseProtocol.js.map