@airgap/cosmos 0.13.45-beta.1 → 0.13.45-beta.3

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 (46) hide show
  1. package/package.json +6 -6
  2. package/v0/index.js +8 -8
  3. package/v0/index.js.map +1 -1
  4. package/v0/protocol/CosmosAddress.js +15 -16
  5. package/v0/protocol/CosmosAddress.js.map +1 -1
  6. package/v0/protocol/CosmosCoin.js +23 -24
  7. package/v0/protocol/CosmosCoin.js.map +1 -1
  8. package/v0/protocol/CosmosCryptoClient.js +19 -82
  9. package/v0/protocol/CosmosCryptoClient.js.map +1 -1
  10. package/v0/protocol/CosmosFee.js +16 -17
  11. package/v0/protocol/CosmosFee.js.map +1 -1
  12. package/v0/protocol/CosmosNodeClient.js +173 -365
  13. package/v0/protocol/CosmosNodeClient.js.map +1 -1
  14. package/v0/protocol/CosmosProtocol.d.ts +0 -1
  15. package/v0/protocol/CosmosProtocol.js +577 -1094
  16. package/v0/protocol/CosmosProtocol.js.map +1 -1
  17. package/v0/protocol/CosmosProtocolOptions.js +25 -98
  18. package/v0/protocol/CosmosProtocolOptions.js.map +1 -1
  19. package/v0/protocol/CosmosTransaction.js +37 -39
  20. package/v0/protocol/CosmosTransaction.js.map +1 -1
  21. package/v0/protocol/CosmosTypes.js +1 -1
  22. package/v0/protocol/CosmosTypes.js.map +1 -1
  23. package/v0/protocol/cosmos-message/CosmosDelegateMessage.js +24 -27
  24. package/v0/protocol/cosmos-message/CosmosDelegateMessage.js.map +1 -1
  25. package/v0/protocol/cosmos-message/CosmosMessage.js +11 -12
  26. package/v0/protocol/cosmos-message/CosmosMessage.js.map +1 -1
  27. package/v0/protocol/cosmos-message/CosmosSendMessage.js +31 -41
  28. package/v0/protocol/cosmos-message/CosmosSendMessage.js.map +1 -1
  29. package/v0/protocol/cosmos-message/CosmosWithdrawDelegationRewardMessage.js +20 -21
  30. package/v0/protocol/cosmos-message/CosmosWithdrawDelegationRewardMessage.js.map +1 -1
  31. package/v0/serializer/validators/transaction-validator.js +25 -77
  32. package/v0/serializer/validators/transaction-validator.js.map +1 -1
  33. package/v1/block-explorer/MintscanBlockExplorer.js +12 -61
  34. package/v1/block-explorer/MintscanBlockExplorer.js.map +1 -1
  35. package/v1/index.js +3 -3
  36. package/v1/index.js.map +1 -1
  37. package/v1/module/CosmosModule.d.ts +1 -1
  38. package/v1/module/CosmosModule.js +37 -95
  39. package/v1/module/CosmosModule.js.map +1 -1
  40. package/v1/module.js +2 -3
  41. package/v1/module.js.map +1 -1
  42. package/v1/protocol/CosmosProtocol.d.ts +1 -1
  43. package/v1/protocol/CosmosProtocol.js +35 -113
  44. package/v1/protocol/CosmosProtocol.js.map +1 -1
  45. package/v1/serializer/v3/serializer-companion.js +57 -124
  46. package/v1/serializer/v3/serializer-companion.js.map +1 -1
@@ -1,123 +1,62 @@
1
1
  "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
- var __assign = (this && this.__assign) || function () {
18
- __assign = Object.assign || function(t) {
19
- for (var s, i = 1, n = arguments.length; i < n; i++) {
20
- s = arguments[i];
21
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
22
- t[p] = s[p];
23
- }
24
- return t;
25
- };
26
- return __assign.apply(this, arguments);
27
- };
28
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
29
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
30
- return new (P || (P = Promise))(function (resolve, reject) {
31
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
32
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
33
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
34
- step((generator = generator.apply(thisArg, _arguments || [])).next());
35
- });
36
- };
37
- var __generator = (this && this.__generator) || function (thisArg, body) {
38
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
39
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
40
- function verb(n) { return function (v) { return step([n, v]); }; }
41
- function step(op) {
42
- if (f) throw new TypeError("Generator is already executing.");
43
- while (_) try {
44
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
45
- if (y = 0, t) op = [op[0] & 2, t.value];
46
- switch (op[0]) {
47
- case 0: case 1: t = op; break;
48
- case 4: _.label++; return { value: op[1], done: false };
49
- case 5: _.label++; y = op[1]; op = [0]; continue;
50
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
51
- default:
52
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
53
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
54
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
55
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
56
- if (t[2]) _.ops.pop();
57
- _.trys.pop(); continue;
58
- }
59
- op = body.call(thisArg, _);
60
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
61
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
62
- }
63
- };
64
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
65
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
66
4
  };
67
5
  Object.defineProperty(exports, "__esModule", { value: true });
68
6
  exports.CosmosProtocol = exports.CosmosDelegationActionType = void 0;
69
- var bignumber_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/bignumber.js-9.0.0/bignumber"));
7
+ const bignumber_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/bignumber.js-9.0.0/bignumber"));
70
8
  // @ts-ignore
71
- var index_1 = require("@airgap/coinlib-core/dependencies/src/bip32-2.0.4/src/index");
9
+ const index_1 = require("@airgap/coinlib-core/dependencies/src/bip32-2.0.4/src/index");
72
10
  // @ts-ignore
73
- var index_2 = require("@airgap/coinlib-core/dependencies/src/bip39-2.5.0/index");
74
- var cosmjs_1 = require("@airgap/coinlib-core/dependencies/src/cosmjs");
11
+ const index_2 = require("@airgap/coinlib-core/dependencies/src/bip39-2.5.0/index");
12
+ const cosmjs_1 = require("@airgap/coinlib-core/dependencies/src/cosmjs");
75
13
  // @ts-ignore
76
- var SECP256K1 = require("@airgap/coinlib-core/dependencies/src/secp256k1-3.7.1/elliptic");
14
+ const SECP256K1 = require("@airgap/coinlib-core/dependencies/src/secp256k1-3.7.1/elliptic");
77
15
  // @ts-ignore
78
- var sha = require("@airgap/coinlib-core/dependencies/src/sha.js-2.4.11/index");
79
- var errors_1 = require("@airgap/coinlib-core/errors");
80
- var coinlib_error_1 = require("@airgap/coinlib-core/errors/coinlib-error");
81
- var NonExtendedProtocol_1 = require("@airgap/coinlib-core/protocols/NonExtendedProtocol");
82
- var assert_1 = require("@airgap/coinlib-core/utils/assert");
83
- var ProtocolSymbols_1 = require("@airgap/coinlib-core/utils/ProtocolSymbols");
84
- var CosmosDelegateMessage_1 = require("./cosmos-message/CosmosDelegateMessage");
85
- var CosmosMessage_1 = require("./cosmos-message/CosmosMessage");
86
- var CosmosSendMessage_1 = require("./cosmos-message/CosmosSendMessage");
87
- var CosmosWithdrawDelegationRewardMessage_1 = require("./cosmos-message/CosmosWithdrawDelegationRewardMessage");
88
- var CosmosAddress_1 = require("./CosmosAddress");
89
- var CosmosCoin_1 = require("./CosmosCoin");
90
- var CosmosCryptoClient_1 = require("./CosmosCryptoClient");
91
- var CosmosFee_1 = require("./CosmosFee");
92
- var CosmosTypes_1 = require("./CosmosTypes");
93
- var CosmosProtocolOptions_1 = require("./CosmosProtocolOptions");
94
- var CosmosTransaction_1 = require("./CosmosTransaction");
16
+ const sha = require("@airgap/coinlib-core/dependencies/src/sha.js-2.4.11/index");
17
+ const errors_1 = require("@airgap/coinlib-core/errors");
18
+ const coinlib_error_1 = require("@airgap/coinlib-core/errors/coinlib-error");
19
+ const NonExtendedProtocol_1 = require("@airgap/coinlib-core/protocols/NonExtendedProtocol");
20
+ const assert_1 = require("@airgap/coinlib-core/utils/assert");
21
+ const ProtocolSymbols_1 = require("@airgap/coinlib-core/utils/ProtocolSymbols");
22
+ const CosmosDelegateMessage_1 = require("./cosmos-message/CosmosDelegateMessage");
23
+ const CosmosMessage_1 = require("./cosmos-message/CosmosMessage");
24
+ const CosmosSendMessage_1 = require("./cosmos-message/CosmosSendMessage");
25
+ const CosmosWithdrawDelegationRewardMessage_1 = require("./cosmos-message/CosmosWithdrawDelegationRewardMessage");
26
+ const CosmosAddress_1 = require("./CosmosAddress");
27
+ const CosmosCoin_1 = require("./CosmosCoin");
28
+ const CosmosCryptoClient_1 = require("./CosmosCryptoClient");
29
+ const CosmosFee_1 = require("./CosmosFee");
30
+ const CosmosTypes_1 = require("./CosmosTypes");
31
+ const CosmosProtocolOptions_1 = require("./CosmosProtocolOptions");
32
+ const CosmosTransaction_1 = require("./CosmosTransaction");
95
33
  var CosmosDelegationActionType;
96
34
  (function (CosmosDelegationActionType) {
97
35
  CosmosDelegationActionType["DELEGATE"] = "delegate";
98
36
  CosmosDelegationActionType["UNDELEGATE"] = "undelegate";
99
37
  CosmosDelegationActionType["WITHDRAW_ALL_REWARDS"] = "withdraw_all_rewards";
100
38
  CosmosDelegationActionType["WITHDRAW_VALIDATOR_REWARDS"] = "withdraw_validator_rewards";
101
- })(CosmosDelegationActionType = exports.CosmosDelegationActionType || (exports.CosmosDelegationActionType = {}));
102
- var CosmosProtocol = /** @class */ (function (_super) {
103
- __extends(CosmosProtocol, _super);
104
- function CosmosProtocol(options) {
105
- if (options === void 0) { options = new CosmosProtocolOptions_1.CosmosProtocolOptions(); }
106
- var _this = _super.call(this) || this;
107
- _this.options = options;
108
- _this.symbol = 'ATOM';
109
- _this.name = 'Cosmos';
110
- _this.marketSymbol = 'atom';
111
- _this.feeSymbol = 'atom';
112
- _this.feeDefaults = {
39
+ })(CosmosDelegationActionType || (exports.CosmosDelegationActionType = CosmosDelegationActionType = {}));
40
+ class CosmosProtocol extends NonExtendedProtocol_1.NonExtendedProtocol {
41
+ get nodeClient() {
42
+ return this.options.config.nodeClient;
43
+ }
44
+ constructor(options = new CosmosProtocolOptions_1.CosmosProtocolOptions()) {
45
+ super();
46
+ this.options = options;
47
+ this.symbol = 'ATOM';
48
+ this.name = 'Cosmos';
49
+ this.marketSymbol = 'atom';
50
+ this.feeSymbol = 'atom';
51
+ this.feeDefaults = {
113
52
  low: '0.0005',
114
53
  medium: '0.005',
115
54
  high: '0.0075'
116
55
  };
117
- _this.decimals = 6;
118
- _this.feeDecimals = 6;
119
- _this.identifier = ProtocolSymbols_1.MainProtocolSymbols.COSMOS;
120
- _this.units = [
56
+ this.decimals = 6;
57
+ this.feeDecimals = 6;
58
+ this.identifier = ProtocolSymbols_1.MainProtocolSymbols.COSMOS;
59
+ this.units = [
121
60
  {
122
61
  unitSymbol: 'atom',
123
62
  factor: '1'
@@ -127,961 +66,534 @@ var CosmosProtocol = /** @class */ (function (_super) {
127
66
  factor: '0.000001'
128
67
  }
129
68
  ];
130
- _this.supportsHD = false;
131
- _this.standardDerivationPath = "m/44'/118'/0'/0/0";
132
- _this.addressIsCaseSensitive = false;
133
- _this.addressValidationPattern = '^(cosmos|cosmosvaloper)[a-zA-Z0-9]{39}$';
134
- _this.addressPlaceholder = 'cosmos...';
135
- _this.defaultGas = new bignumber_1.default('310000');
136
- _this.cryptoClient = new CosmosCryptoClient_1.CosmosCryptoClient();
137
- return _this;
138
- }
139
- Object.defineProperty(CosmosProtocol.prototype, "nodeClient", {
140
- get: function () {
141
- return this.options.config.nodeClient;
142
- },
143
- enumerable: false,
144
- configurable: true
145
- });
146
- CosmosProtocol.prototype.getSymbol = function () {
147
- return __awaiter(this, void 0, void 0, function () {
148
- return __generator(this, function (_a) {
149
- return [2 /*return*/, this.symbol];
150
- });
151
- });
152
- };
153
- CosmosProtocol.prototype.getName = function () {
154
- return __awaiter(this, void 0, void 0, function () {
155
- return __generator(this, function (_a) {
156
- return [2 /*return*/, this.name];
157
- });
158
- });
159
- };
160
- CosmosProtocol.prototype.getMarketSymbol = function () {
161
- return __awaiter(this, void 0, void 0, function () {
162
- return __generator(this, function (_a) {
163
- return [2 /*return*/, this.marketSymbol];
164
- });
165
- });
166
- };
167
- CosmosProtocol.prototype.getAssetSymbol = function () {
168
- return __awaiter(this, void 0, void 0, function () {
169
- return __generator(this, function (_a) {
170
- return [2 /*return*/, undefined];
171
- });
172
- });
173
- };
174
- CosmosProtocol.prototype.getFeeSymbol = function () {
175
- return __awaiter(this, void 0, void 0, function () {
176
- return __generator(this, function (_a) {
177
- return [2 /*return*/, this.feeSymbol];
178
- });
179
- });
180
- };
181
- CosmosProtocol.prototype.getFeeDefaults = function () {
182
- return __awaiter(this, void 0, void 0, function () {
183
- return __generator(this, function (_a) {
184
- return [2 /*return*/, this.feeDefaults];
185
- });
186
- });
187
- };
188
- CosmosProtocol.prototype.getDecimals = function () {
189
- return __awaiter(this, void 0, void 0, function () {
190
- return __generator(this, function (_a) {
191
- return [2 /*return*/, this.decimals];
192
- });
193
- });
194
- };
195
- CosmosProtocol.prototype.getFeeDecimals = function () {
196
- return __awaiter(this, void 0, void 0, function () {
197
- return __generator(this, function (_a) {
198
- return [2 /*return*/, this.feeDecimals];
199
- });
200
- });
201
- };
202
- CosmosProtocol.prototype.getIdentifier = function () {
203
- return __awaiter(this, void 0, void 0, function () {
204
- return __generator(this, function (_a) {
205
- return [2 /*return*/, this.identifier];
206
- });
207
- });
208
- };
209
- CosmosProtocol.prototype.getUnits = function () {
210
- return __awaiter(this, void 0, void 0, function () {
211
- return __generator(this, function (_a) {
212
- return [2 /*return*/, this.units];
213
- });
214
- });
215
- };
216
- CosmosProtocol.prototype.getSupportsHD = function () {
217
- return __awaiter(this, void 0, void 0, function () {
218
- return __generator(this, function (_a) {
219
- return [2 /*return*/, this.supportsHD];
220
- });
221
- });
222
- };
223
- CosmosProtocol.prototype.getStandardDerivationPath = function () {
224
- return __awaiter(this, void 0, void 0, function () {
225
- return __generator(this, function (_a) {
226
- return [2 /*return*/, this.standardDerivationPath];
227
- });
228
- });
229
- };
230
- CosmosProtocol.prototype.getAddressIsCaseSensitive = function () {
231
- return __awaiter(this, void 0, void 0, function () {
232
- return __generator(this, function (_a) {
233
- return [2 /*return*/, this.addressIsCaseSensitive];
234
- });
235
- });
236
- };
237
- CosmosProtocol.prototype.getAddressValidationPattern = function () {
238
- return __awaiter(this, void 0, void 0, function () {
239
- return __generator(this, function (_a) {
240
- return [2 /*return*/, this.addressValidationPattern];
241
- });
242
- });
243
- };
244
- CosmosProtocol.prototype.getAddressPlaceholder = function () {
245
- return __awaiter(this, void 0, void 0, function () {
246
- return __generator(this, function (_a) {
247
- return [2 /*return*/, this.addressPlaceholder];
248
- });
249
- });
250
- };
251
- CosmosProtocol.prototype.getOptions = function () {
252
- return __awaiter(this, void 0, void 0, function () {
253
- return __generator(this, function (_a) {
254
- return [2 /*return*/, this.options];
255
- });
256
- });
257
- };
258
- CosmosProtocol.prototype.getBlockExplorerLinkForAddress = function (address) {
259
- return __awaiter(this, void 0, void 0, function () {
260
- return __generator(this, function (_a) {
261
- return [2 /*return*/, this.options.network.blockExplorer.getAddressLink(address)];
262
- });
263
- });
264
- };
265
- CosmosProtocol.prototype.getBlockExplorerLinkForTxId = function (txId) {
266
- return __awaiter(this, void 0, void 0, function () {
267
- return __generator(this, function (_a) {
268
- return [2 /*return*/, this.options.network.blockExplorer.getTransactionLink(txId)];
269
- });
270
- });
271
- };
272
- CosmosProtocol.prototype.generateKeyPair = function (mnemonic, derivationPath, password) {
273
- if (derivationPath === void 0) { derivationPath = this.standardDerivationPath; }
69
+ this.supportsHD = false;
70
+ this.standardDerivationPath = `m/44'/118'/0'/0/0`;
71
+ this.addressIsCaseSensitive = false;
72
+ this.addressValidationPattern = '^(cosmos|cosmosvaloper)[a-zA-Z0-9]{39}$';
73
+ this.addressPlaceholder = 'cosmos...';
74
+ this.defaultGas = new bignumber_1.default('310000');
75
+ this.cryptoClient = new CosmosCryptoClient_1.CosmosCryptoClient();
76
+ }
77
+ async getSymbol() {
78
+ return this.symbol;
79
+ }
80
+ async getName() {
81
+ return this.name;
82
+ }
83
+ async getMarketSymbol() {
84
+ return this.marketSymbol;
85
+ }
86
+ async getAssetSymbol() {
87
+ return undefined;
88
+ }
89
+ async getFeeSymbol() {
90
+ return this.feeSymbol;
91
+ }
92
+ async getFeeDefaults() {
93
+ return this.feeDefaults;
94
+ }
95
+ async getDecimals() {
96
+ return this.decimals;
97
+ }
98
+ async getFeeDecimals() {
99
+ return this.feeDecimals;
100
+ }
101
+ async getIdentifier() {
102
+ return this.identifier;
103
+ }
104
+ async getUnits() {
105
+ return this.units;
106
+ }
107
+ async getSupportsHD() {
108
+ return this.supportsHD;
109
+ }
110
+ async getStandardDerivationPath() {
111
+ return this.standardDerivationPath;
112
+ }
113
+ async getAddressIsCaseSensitive() {
114
+ return this.addressIsCaseSensitive;
115
+ }
116
+ async getAddressValidationPattern() {
117
+ return this.addressValidationPattern;
118
+ }
119
+ async getAddressPlaceholder() {
120
+ return this.addressPlaceholder;
121
+ }
122
+ async getOptions() {
123
+ return this.options;
124
+ }
125
+ async getBlockExplorerLinkForAddress(address) {
126
+ return this.options.network.blockExplorer.getAddressLink(address);
127
+ }
128
+ async getBlockExplorerLinkForTxId(txId) {
129
+ return this.options.network.blockExplorer.getTransactionLink(txId);
130
+ }
131
+ generateKeyPair(mnemonic, derivationPath = this.standardDerivationPath, password) {
274
132
  (0, index_2.validateMnemonic)(mnemonic);
275
- var seed = (0, index_2.mnemonicToSeed)(mnemonic, password);
276
- var node = (0, index_1.fromSeed)(seed);
133
+ const seed = (0, index_2.mnemonicToSeed)(mnemonic, password);
134
+ const node = (0, index_1.fromSeed)(seed);
277
135
  return this.generateKeyPairFromNode(node, derivationPath);
278
- };
279
- CosmosProtocol.prototype.generateKeyPairFromNode = function (node, derivationPath) {
280
- var keys = node.derivePath(derivationPath);
281
- var privateKey = keys.privateKey;
136
+ }
137
+ generateKeyPairFromNode(node, derivationPath) {
138
+ const keys = node.derivePath(derivationPath);
139
+ const privateKey = keys.privateKey;
282
140
  if (privateKey === undefined) {
283
141
  throw new errors_1.InvalidValueError(coinlib_error_1.Domain.COSMOS, 'Cannot generate private key');
284
142
  }
285
143
  return {
286
144
  publicKey: keys.publicKey,
287
- privateKey: privateKey
145
+ privateKey
288
146
  };
289
- };
290
- CosmosProtocol.prototype.getPublicKeyFromMnemonic = function (mnemonic, derivationPath, password) {
291
- return __awaiter(this, void 0, void 0, function () {
292
- return __generator(this, function (_a) {
293
- return [2 /*return*/, this.generateKeyPair(mnemonic, derivationPath, password).publicKey.toString('hex')];
294
- });
295
- });
296
- };
297
- CosmosProtocol.prototype.getPrivateKeyFromMnemonic = function (mnemonic, derivationPath, password) {
298
- return __awaiter(this, void 0, void 0, function () {
299
- return __generator(this, function (_a) {
300
- return [2 /*return*/, this.generateKeyPair(mnemonic, derivationPath, password).privateKey.toString('hex')];
301
- });
302
- });
303
- };
304
- CosmosProtocol.prototype.getPublicKeyFromHexSecret = function (secret, derivationPath) {
305
- return __awaiter(this, void 0, void 0, function () {
306
- var node;
307
- return __generator(this, function (_a) {
308
- node = (0, index_1.fromSeed)(Buffer.from(secret, 'hex'));
309
- return [2 /*return*/, this.generateKeyPairFromNode(node, derivationPath).publicKey.toString('hex')];
310
- });
311
- });
312
- };
313
- CosmosProtocol.prototype.getPublicKeyFromPrivateKey = function (privateKey) {
314
- var publicKey = SECP256K1.publicKeyCreate(privateKey);
147
+ }
148
+ async getPublicKeyFromMnemonic(mnemonic, derivationPath, password) {
149
+ return this.generateKeyPair(mnemonic, derivationPath, password).publicKey.toString('hex');
150
+ }
151
+ async getPrivateKeyFromMnemonic(mnemonic, derivationPath, password) {
152
+ return this.generateKeyPair(mnemonic, derivationPath, password).privateKey.toString('hex');
153
+ }
154
+ async getPublicKeyFromHexSecret(secret, derivationPath) {
155
+ const node = (0, index_1.fromSeed)(Buffer.from(secret, 'hex'));
156
+ return this.generateKeyPairFromNode(node, derivationPath).publicKey.toString('hex');
157
+ }
158
+ getPublicKeyFromPrivateKey(privateKey) {
159
+ const publicKey = SECP256K1.publicKeyCreate(privateKey);
315
160
  return Buffer.from(publicKey, 'binary');
316
- };
317
- CosmosProtocol.prototype.getPrivateKeyFromHexSecret = function (secret, derivationPath) {
318
- return __awaiter(this, void 0, void 0, function () {
319
- var node;
320
- return __generator(this, function (_a) {
321
- node = (0, index_1.fromSeed)(Buffer.from(secret, 'hex'));
322
- return [2 /*return*/, this.generateKeyPairFromNode(node, derivationPath).privateKey.toString('hex')];
323
- });
324
- });
325
- };
326
- CosmosProtocol.prototype.getAddressFromPublicKey = function (publicKey, cursor) {
327
- return __awaiter(this, void 0, void 0, function () {
328
- var address;
329
- return __generator(this, function (_a) {
330
- address = CosmosAddress_1.CosmosAddress.from(publicKey);
331
- return [2 /*return*/, {
332
- address: address.asString(),
333
- cursor: { hasNext: false }
334
- }];
335
- });
336
- });
337
- };
338
- CosmosProtocol.prototype.getAddressesFromPublicKey = function (publicKey, cursor) {
339
- return __awaiter(this, void 0, void 0, function () {
340
- return __generator(this, function (_a) {
341
- switch (_a.label) {
342
- case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey, cursor)];
343
- case 1: return [2 /*return*/, [_a.sent()]];
344
- }
345
- });
346
- });
347
- };
348
- CosmosProtocol.prototype.getTransactionsFromPublicKey = function (publicKey, limit, cursor) {
349
- return __awaiter(this, void 0, void 0, function () {
350
- var address;
351
- return __generator(this, function (_a) {
352
- switch (_a.label) {
353
- case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
354
- case 1:
355
- address = _a.sent();
356
- return [2 /*return*/, this.getTransactionsFromAddresses([address.address], limit, cursor)];
357
- }
358
- });
359
- });
360
- };
361
- CosmosProtocol.prototype.getTransactionsFromAddresses = function (addresses, limit, cursor) {
362
- var _a;
363
- return __awaiter(this, void 0, void 0, function () {
364
- var address, promises, senderOffset, recipientOffset, senderTotal, recipientTotal, senderLimit, recipientLimit, transactions, sentTransactions, receivedTransactions, allTransactions, result, _loop_1, _i, allTransactions_1, transaction;
365
- var _b;
366
- var _this = this;
367
- return __generator(this, function (_c) {
368
- switch (_c.label) {
369
- case 0:
370
- address = (_a = cursor === null || cursor === void 0 ? void 0 : cursor.address) !== null && _a !== void 0 ? _a : addresses[0];
371
- promises = [];
372
- senderOffset = 0;
373
- recipientOffset = 0;
374
- senderTotal = 0;
375
- recipientTotal = 0;
376
- senderLimit = 0;
377
- recipientLimit = 0;
378
- if (!cursor) return [3 /*break*/, 1];
379
- senderOffset = cursor.sender.offset;
380
- recipientOffset = cursor.recipient.offset;
381
- senderTotal = cursor.sender.total;
382
- recipientTotal = cursor.recipient.total;
383
- senderLimit = (0, CosmosTypes_1.calculateTransactionLimit)(limit, senderTotal, recipientTotal, senderOffset, recipientOffset);
384
- if (senderOffset <= Math.floor(senderTotal / senderLimit) * senderLimit) {
385
- promises.push(this.nodeClient.fetchSendTransactionsFor(address, senderLimit, senderOffset, true));
386
- }
387
- else {
388
- promises.push(new Promise(function (resolve) {
389
- resolve({ txs: [], tx_responses: [], pagination: { total: String(senderTotal) } });
390
- }));
391
- }
392
- recipientLimit = (0, CosmosTypes_1.calculateTransactionLimit)(limit, recipientTotal, senderTotal, recipientOffset, senderOffset);
393
- if (recipientOffset <= Math.floor(recipientTotal / recipientLimit) * recipientLimit) {
394
- promises.push(this.nodeClient.fetchSendTransactionsFor(address, recipientLimit, recipientOffset, false));
395
- }
396
- else {
397
- promises.push(new Promise(function (resolve) {
398
- resolve({ txs: [], tx_responses: [], pagination: { total: String(recipientTotal) } });
399
- }));
400
- }
401
- return [3 /*break*/, 3];
402
- case 1:
403
- ;
404
- return [4 /*yield*/, Promise.all([
405
- this.nodeClient
406
- .fetchSendTransactionsFor(address, 1, 0, true)
407
- .then(function (response) { return new bignumber_1.default(response.pagination.total).toNumber(); }),
408
- this.nodeClient
409
- .fetchSendTransactionsFor(address, 1, 0, false)
410
- .then(function (response) { return new bignumber_1.default(response.pagination.total).toNumber(); })
411
- ])];
412
- case 2:
413
- _b = _c.sent(), senderTotal = _b[0], recipientTotal = _b[1];
414
- senderLimit = (0, CosmosTypes_1.calculateTransactionLimit)(limit, senderTotal, recipientTotal, senderOffset, recipientOffset);
415
- recipientLimit = (0, CosmosTypes_1.calculateTransactionLimit)(limit, recipientTotal, senderTotal, recipientOffset, senderOffset);
416
- promises.push(this.nodeClient.fetchSendTransactionsFor(address, senderLimit, senderOffset, true), this.nodeClient.fetchSendTransactionsFor(address, recipientLimit, recipientOffset, false));
417
- _c.label = 3;
418
- case 3: return [4 /*yield*/, Promise.all(promises)];
419
- case 4:
420
- transactions = _c.sent();
421
- sentTransactions = transactions[0];
422
- receivedTransactions = transactions[1];
423
- allTransactions = sentTransactions === null || sentTransactions === void 0 ? void 0 : sentTransactions.tx_responses.concat(receivedTransactions === null || receivedTransactions === void 0 ? void 0 : receivedTransactions.tx_responses);
424
- result = [];
425
- _loop_1 = function (transaction) {
426
- var timestamp = new Date(transaction.timestamp).getTime() / 1000;
427
- var fee = transaction.tx.auth_info.fee.amount
428
- .filter(function (coin) { return coin.denom === 'uatom'; })
429
- .map(function (coin) { return new bignumber_1.default(coin.amount); })
430
- .reduce(function (current, next) { return current.plus(next); });
431
- result = result.concat(transaction.tx.body.messages.map(function (msg) {
432
- var tx = {
433
- fee: fee.toFixed(),
434
- protocolIdentifier: _this.identifier,
435
- network: _this.options.network,
436
- hash: transaction.txhash,
437
- timestamp: timestamp,
438
- isInbound: false,
439
- amount: '0'
440
- };
441
- switch (msg['@type']) {
442
- case CosmosMessage_1.CosmosMessageTypeValue.UNDELEGATE:
443
- return __assign(__assign({}, tx), { from: [msg.validator_address], to: [msg.delegator_address] });
444
- case CosmosMessage_1.CosmosMessageTypeValue.WITHDRAW_DELEGATION_REWARD:
445
- return __assign(__assign({}, tx), { from: [msg.delegator_address], to: [msg.validator_address] });
446
- case CosmosMessage_1.CosmosMessageTypeValue.DELEGATE:
447
- return __assign(__assign({}, tx), { from: [msg.delegator_address], to: [msg.validator_address] });
448
- default:
449
- return __assign(__assign({}, tx), { from: [msg.from_address], to: [msg.to_address], isInbound: msg.to_address === address, amount: msg.amount[0].amount });
450
- }
451
- }));
161
+ }
162
+ async getPrivateKeyFromHexSecret(secret, derivationPath) {
163
+ const node = (0, index_1.fromSeed)(Buffer.from(secret, 'hex'));
164
+ return this.generateKeyPairFromNode(node, derivationPath).privateKey.toString('hex');
165
+ }
166
+ async getAddressFromPublicKey(publicKey, cursor) {
167
+ const address = CosmosAddress_1.CosmosAddress.from(publicKey);
168
+ return {
169
+ address: address.asString(),
170
+ cursor: { hasNext: false }
171
+ };
172
+ }
173
+ async getAddressesFromPublicKey(publicKey, cursor) {
174
+ return [await this.getAddressFromPublicKey(publicKey, cursor)];
175
+ }
176
+ async getTransactionsFromPublicKey(publicKey, limit, cursor) {
177
+ const address = await this.getAddressFromPublicKey(publicKey);
178
+ return this.getTransactionsFromAddresses([address.address], limit, cursor);
179
+ }
180
+ async getTransactionsFromAddresses(addresses, limit, cursor) {
181
+ const address = cursor?.address ?? addresses[0];
182
+ const promises = [];
183
+ let senderOffset = 0;
184
+ let recipientOffset = 0;
185
+ let senderTotal = 0;
186
+ let recipientTotal = 0;
187
+ let senderLimit = 0;
188
+ let recipientLimit = 0;
189
+ if (cursor) {
190
+ senderOffset = cursor.sender.offset;
191
+ recipientOffset = cursor.recipient.offset;
192
+ senderTotal = cursor.sender.total;
193
+ recipientTotal = cursor.recipient.total;
194
+ senderLimit = (0, CosmosTypes_1.calculateTransactionLimit)(limit, senderTotal, recipientTotal, senderOffset, recipientOffset);
195
+ if (senderOffset <= Math.floor(senderTotal / senderLimit) * senderLimit) {
196
+ promises.push(this.nodeClient.fetchSendTransactionsFor(address, senderLimit, senderOffset, true));
197
+ }
198
+ else {
199
+ promises.push(new Promise((resolve) => {
200
+ resolve({ txs: [], tx_responses: [], pagination: { total: String(senderTotal) } });
201
+ }));
202
+ }
203
+ recipientLimit = (0, CosmosTypes_1.calculateTransactionLimit)(limit, recipientTotal, senderTotal, recipientOffset, senderOffset);
204
+ if (recipientOffset <= Math.floor(recipientTotal / recipientLimit) * recipientLimit) {
205
+ promises.push(this.nodeClient.fetchSendTransactionsFor(address, recipientLimit, recipientOffset, false));
206
+ }
207
+ else {
208
+ promises.push(new Promise((resolve) => {
209
+ resolve({ txs: [], tx_responses: [], pagination: { total: String(recipientTotal) } });
210
+ }));
211
+ }
212
+ }
213
+ else {
214
+ ;
215
+ [senderTotal, recipientTotal] = await Promise.all([
216
+ this.nodeClient
217
+ .fetchSendTransactionsFor(address, 1, 0, true)
218
+ .then((response) => new bignumber_1.default(response.pagination.total).toNumber()),
219
+ this.nodeClient
220
+ .fetchSendTransactionsFor(address, 1, 0, false)
221
+ .then((response) => new bignumber_1.default(response.pagination.total).toNumber())
222
+ ]);
223
+ senderLimit = (0, CosmosTypes_1.calculateTransactionLimit)(limit, senderTotal, recipientTotal, senderOffset, recipientOffset);
224
+ recipientLimit = (0, CosmosTypes_1.calculateTransactionLimit)(limit, recipientTotal, senderTotal, recipientOffset, senderOffset);
225
+ promises.push(this.nodeClient.fetchSendTransactionsFor(address, senderLimit, senderOffset, true), this.nodeClient.fetchSendTransactionsFor(address, recipientLimit, recipientOffset, false));
226
+ }
227
+ const transactions = await Promise.all(promises);
228
+ const sentTransactions = transactions[0];
229
+ const receivedTransactions = transactions[1];
230
+ const allTransactions = sentTransactions?.tx_responses.concat(receivedTransactions?.tx_responses);
231
+ let result = [];
232
+ for (const transaction of allTransactions) {
233
+ const timestamp = new Date(transaction.timestamp).getTime() / 1000;
234
+ const fee = transaction.tx.auth_info.fee.amount
235
+ .filter((coin) => coin.denom === 'uatom')
236
+ .map((coin) => new bignumber_1.default(coin.amount))
237
+ .reduce((current, next) => current.plus(next));
238
+ result = result.concat(transaction.tx.body.messages.map((msg) => {
239
+ const tx = {
240
+ fee: fee.toFixed(),
241
+ protocolIdentifier: this.identifier,
242
+ network: this.options.network,
243
+ hash: transaction.txhash,
244
+ timestamp,
245
+ isInbound: false,
246
+ amount: '0'
247
+ };
248
+ switch (msg['@type']) {
249
+ case CosmosMessage_1.CosmosMessageTypeValue.UNDELEGATE:
250
+ return {
251
+ ...tx,
252
+ from: [msg.validator_address],
253
+ to: [msg.delegator_address]
254
+ };
255
+ case CosmosMessage_1.CosmosMessageTypeValue.WITHDRAW_DELEGATION_REWARD:
256
+ return {
257
+ ...tx,
258
+ from: [msg.delegator_address],
259
+ to: [msg.validator_address]
260
+ };
261
+ case CosmosMessage_1.CosmosMessageTypeValue.DELEGATE:
262
+ return {
263
+ ...tx,
264
+ from: [msg.delegator_address],
265
+ to: [msg.validator_address]
266
+ };
267
+ default:
268
+ return {
269
+ ...tx,
270
+ from: [msg.from_address],
271
+ to: [msg.to_address],
272
+ isInbound: msg.to_address === address,
273
+ amount: msg.amount[0].amount
452
274
  };
453
- for (_i = 0, allTransactions_1 = allTransactions; _i < allTransactions_1.length; _i++) {
454
- transaction = allTransactions_1[_i];
455
- _loop_1(transaction);
456
- }
457
- return [2 /*return*/, {
458
- transactions: result,
459
- cursor: {
460
- address: address,
461
- limit: limit,
462
- sender: {
463
- total: senderTotal,
464
- offset: senderOffset + senderLimit
465
- },
466
- recipient: {
467
- total: recipientTotal,
468
- offset: recipientOffset + recipientLimit
469
- }
470
- }
471
- }];
472
- }
473
- });
474
- });
475
- };
476
- CosmosProtocol.prototype.signWithPrivateKey = function (privateKey, transaction) {
477
- return __awaiter(this, void 0, void 0, function () {
478
- var privateKeyBuffer, publicKey, encodedObject, signBytes, sha256Hash, hash, signed, sigBase64, txBytes;
479
- return __generator(this, function (_a) {
480
- switch (_a.label) {
481
- case 0:
482
- privateKeyBuffer = Buffer.from(privateKey, 'hex');
483
- publicKey = this.getPublicKeyFromPrivateKey(privateKeyBuffer);
484
- encodedObject = transaction.toEncodeObject();
485
- return [4 /*yield*/, (0, cosmjs_1.prepareSignBytes)(encodedObject, transaction.fee, Uint8Array.from(publicKey), new bignumber_1.default(transaction.sequence).toNumber(), transaction.chainID, new bignumber_1.default(transaction.accountNumber).toNumber())];
486
- case 1:
487
- signBytes = _a.sent();
488
- sha256Hash = sha('sha256').update(signBytes).digest();
489
- hash = Buffer.from(sha256Hash);
490
- signed = SECP256K1.sign(hash, privateKeyBuffer);
491
- sigBase64 = Buffer.from(signed.signature, 'binary').toString('base64');
492
- return [4 /*yield*/, (0, cosmjs_1.encodeTxBytes)(encodedObject, transaction.fee, Uint8Array.from(publicKey), new bignumber_1.default(transaction.sequence).toNumber(), {
493
- signature: sigBase64,
494
- pub_key: {
495
- type: 'tendermint/PubKeySecp256k1',
496
- value: publicKey.toString('base64')
497
- }
498
- }, transaction.chainID, new bignumber_1.default(transaction.accountNumber).toNumber())];
499
- case 2:
500
- txBytes = _a.sent();
501
- return [2 /*return*/, Buffer.from(txBytes).toString('base64')];
502
- }
503
- });
504
- });
505
- };
506
- CosmosProtocol.prototype.getTransactionDetails = function (transaction) {
507
- return __awaiter(this, void 0, void 0, function () {
508
- var result;
509
- return __generator(this, function (_a) {
510
- result = transaction.transaction.toAirGapTransactions(this.identifier, this.options.network);
511
- return [2 /*return*/, result];
512
- });
513
- });
514
- };
515
- CosmosProtocol.prototype.getTransactionDetailsFromSigned = function (transaction) {
516
- var _a;
517
- return __awaiter(this, void 0, void 0, function () {
518
- var bytes, decoded, fee, result;
519
- var _this = this;
520
- return __generator(this, function (_b) {
521
- switch (_b.label) {
522
- case 0:
523
- bytes = Uint8Array.from(Buffer.from(transaction.transaction, 'base64'));
524
- return [4 /*yield*/, (0, cosmjs_1.decodeTxBytes)(bytes)];
525
- case 1:
526
- decoded = _b.sent();
527
- fee = ((_a = decoded.fee) === null || _a === void 0 ? void 0 : _a.amount)
528
- .map(function (_a) {
529
- var amount = _a.amount;
530
- return new bignumber_1.default(amount);
531
- })
532
- .reduce(function (current, next) { return current.plus(next); })
533
- .toString(10);
534
- result = decoded.messages
535
- .map(function (message) {
536
- var type = message.typeUrl;
537
- switch (type) {
538
- case CosmosMessage_1.CosmosMessageType.Send.value:
539
- var sendMessage = CosmosSendMessage_1.CosmosSendMessage.fromEncodeObject(message);
540
- return sendMessage.toAirGapTransaction(_this.identifier, _this.options.network, fee);
541
- case CosmosMessage_1.CosmosMessageType.Undelegate.value:
542
- case CosmosMessage_1.CosmosMessageType.Delegate.value:
543
- var delegateMessage = CosmosDelegateMessage_1.CosmosDelegateMessage.fromEncodeObject(message);
544
- return delegateMessage.toAirGapTransaction(_this.identifier, _this.options.network, fee);
545
- case CosmosMessage_1.CosmosMessageType.WithdrawDelegationReward.value:
546
- var withdrawMessage = CosmosWithdrawDelegationRewardMessage_1.CosmosWithdrawDelegationRewardMessage.fromEncodeObject(message);
547
- return withdrawMessage.toAirGapTransaction(_this.identifier, _this.options.network, fee);
548
- default:
549
- throw new errors_1.InvalidValueError(coinlib_error_1.Domain.COSMOS, 'Unknown transaction');
550
- }
551
- })
552
- .map(function (tx) {
553
- if (!tx.transactionDetails) {
554
- tx.transactionDetails = {};
555
- }
556
- tx.transactionDetails.memo = decoded.memo;
557
- if (decoded.signerInfos.length > 0) {
558
- tx.transactionDetails.sequence = decoded.signerInfos[0].sequence.toString(10);
559
- }
560
- return tx;
561
- });
562
- return [2 /*return*/, result];
563
- }
564
- });
565
- });
566
- };
567
- CosmosProtocol.prototype.getBalanceOfAddresses = function (addresses) {
568
- return __awaiter(this, void 0, void 0, function () {
569
- return __generator(this, function (_a) {
570
- return [2 /*return*/, this.getBalance(addresses)];
571
- });
572
- });
573
- };
574
- CosmosProtocol.prototype.getBalanceOfPublicKey = function (publicKey) {
575
- return __awaiter(this, void 0, void 0, function () {
576
- var address;
577
- return __generator(this, function (_a) {
578
- switch (_a.label) {
579
- case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
580
- case 1:
581
- address = _a.sent();
582
- return [2 /*return*/, this.getBalanceOfAddresses([address.address])];
583
- }
584
- });
585
- });
586
- };
587
- CosmosProtocol.prototype.getAvailableBalanceOfAddresses = function (addresses) {
588
- return __awaiter(this, void 0, void 0, function () {
589
- return __generator(this, function (_a) {
590
- return [2 /*return*/, this.getBalance(addresses, false)];
591
- });
592
- });
593
- };
594
- CosmosProtocol.prototype.getBalanceOfPublicKeyForSubProtocols = function (publicKey, subProtocols) {
595
- return __awaiter(this, void 0, void 0, function () {
596
- return __generator(this, function (_a) {
597
- throw Promise.reject('get balance of sub protocols not supported');
598
- });
599
- });
600
- };
601
- CosmosProtocol.prototype.getBalance = function (addresses, totalBalance) {
602
- if (totalBalance === void 0) { totalBalance = true; }
603
- return __awaiter(this, void 0, void 0, function () {
604
- var promises, _i, addresses_1, address;
605
- return __generator(this, function (_a) {
606
- switch (_a.label) {
607
- case 0:
608
- promises = [];
609
- for (_i = 0, addresses_1 = addresses; _i < addresses_1.length; _i++) {
610
- address = addresses_1[_i];
611
- promises.push(this.nodeClient.fetchBalance(address, totalBalance));
612
- }
613
- return [4 /*yield*/, Promise.all(promises).then(function (balances) {
614
- return balances.reduce(function (current, next) {
615
- return current.plus(next);
616
- });
617
- })];
618
- case 1: return [2 /*return*/, (_a.sent()).toString(10)];
619
- }
620
- });
621
- });
622
- };
623
- CosmosProtocol.prototype.estimateMaxTransactionValueFromPublicKey = function (publicKey, recipients, fee) {
624
- return __awaiter(this, void 0, void 0, function () {
625
- var address, balance, balanceWrapper, maxFee, estimatedFeeDefaults, amountWithoutFees;
626
- return __generator(this, function (_a) {
627
- switch (_a.label) {
628
- case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
629
- case 1:
630
- address = (_a.sent()).address;
631
- return [4 /*yield*/, this.getAvailableBalanceOfAddresses([address])];
632
- case 2:
633
- balance = _a.sent();
634
- balanceWrapper = new bignumber_1.default(balance);
635
- if (!(fee !== undefined)) return [3 /*break*/, 3];
636
- maxFee = new bignumber_1.default(fee);
637
- return [3 /*break*/, 5];
638
- case 3: return [4 /*yield*/, this.estimateFeeDefaultsFromPublicKey(publicKey, recipients, [balance])];
639
- case 4:
640
- estimatedFeeDefaults = _a.sent();
641
- maxFee = new bignumber_1.default(estimatedFeeDefaults.medium).shiftedBy(this.decimals);
642
- if (maxFee.gte(balanceWrapper)) {
643
- maxFee = new bignumber_1.default(0);
644
- }
645
- _a.label = 5;
646
- case 5:
647
- amountWithoutFees = balanceWrapper.minus(maxFee);
648
- if (amountWithoutFees.isNegative()) {
649
- amountWithoutFees = new bignumber_1.default(0);
650
- }
651
- return [2 /*return*/, amountWithoutFees.toFixed()];
652
- }
653
- });
654
- });
655
- };
656
- CosmosProtocol.prototype.estimateFeeDefaultsFromPublicKey = function (publicKey, recipients, values, data) {
657
- return __awaiter(this, void 0, void 0, function () {
658
- return __generator(this, function (_a) {
659
- return [2 /*return*/, this.feeDefaults];
660
- });
661
- });
662
- };
663
- CosmosProtocol.prototype.prepareTransactionFromPublicKey = function (publicKey, recipients, values, fee, data) {
664
- var _a, _b;
665
- return __awaiter(this, void 0, void 0, function () {
666
- var wrappedValues, wrappedFee, address, nodeInfo, account, balance, _c, messages, i, message, memo, transaction;
667
- return __generator(this, function (_d) {
668
- switch (_d.label) {
669
- case 0:
670
- wrappedValues = values.map(function (value) { return new bignumber_1.default(value); });
671
- wrappedFee = new bignumber_1.default(fee);
672
- if (recipients.length !== wrappedValues.length) {
673
- return [2 /*return*/, Promise.reject('recipients length does not match with values')];
674
- }
675
- return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
676
- case 1:
677
- address = (_d.sent()).address;
678
- return [4 /*yield*/, this.nodeClient.fetchNodeInfo()];
679
- case 2:
680
- nodeInfo = _d.sent();
681
- return [4 /*yield*/, this.nodeClient.fetchAccount(address)];
682
- case 3:
683
- account = _d.sent();
684
- _c = bignumber_1.default.bind;
685
- return [4 /*yield*/, this.getAvailableBalanceOfAddresses([address])];
686
- case 4:
687
- balance = new (_c.apply(bignumber_1.default, [void 0, _d.sent()]))();
688
- if (balance.lt(values.reduce(function (pv, cv) { return pv.plus(cv); }, wrappedFee))) {
689
- throw new errors_1.BalanceError(coinlib_error_1.Domain.COSMOS, 'not enough balance');
690
- }
691
- messages = [];
692
- for (i = 0; i < recipients.length; ++i) {
693
- message = new CosmosSendMessage_1.CosmosSendMessage(address, recipients[i], [
694
- new CosmosCoin_1.CosmosCoin('uatom', wrappedValues[i].toString(10))
695
- ]);
696
- messages.push(message);
697
- }
698
- memo = (_a = data === null || data === void 0 ? void 0 : data.memo) !== null && _a !== void 0 ? _a : '';
699
- transaction = new CosmosTransaction_1.CosmosTransaction(messages, new CosmosFee_1.CosmosFee([new CosmosCoin_1.CosmosCoin('uatom', wrappedFee.toString(10))], this.defaultGas.toString(10)), memo, nodeInfo.network, account.value.account_number, (_b = account.value.sequence) !== null && _b !== void 0 ? _b : '0');
700
- return [2 /*return*/, transaction];
701
- }
702
- });
703
- });
704
- };
705
- CosmosProtocol.prototype.getDefaultDelegatee = function () {
706
- return __awaiter(this, void 0, void 0, function () {
707
- var validators;
708
- return __generator(this, function (_a) {
709
- switch (_a.label) {
710
- case 0: return [4 /*yield*/, this.nodeClient.fetchValidators()];
711
- case 1:
712
- validators = _a.sent();
713
- return [2 /*return*/, validators.length > 0 ? validators[0].operator_address : ''];
714
- }
715
- });
716
- });
717
- };
718
- CosmosProtocol.prototype.getCurrentDelegateesForPublicKey = function (publicKey) {
719
- return __awaiter(this, void 0, void 0, function () {
720
- var address;
721
- return __generator(this, function (_a) {
722
- switch (_a.label) {
723
- case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
724
- case 1:
725
- address = _a.sent();
726
- return [2 /*return*/, this.getCurrentDelegateesForAddress(address.address)];
727
- }
728
- });
729
- });
730
- };
731
- CosmosProtocol.prototype.getCurrentDelegateesForAddress = function (address) {
732
- return __awaiter(this, void 0, void 0, function () {
733
- var delegations;
734
- return __generator(this, function (_a) {
735
- switch (_a.label) {
736
- case 0: return [4 /*yield*/, this.nodeClient.fetchDelegations(address)];
737
- case 1:
738
- delegations = _a.sent();
739
- return [2 /*return*/, delegations.map(function (delegation) { return delegation.delegation.validator_address; })];
740
- }
741
- });
742
- });
743
- };
744
- CosmosProtocol.prototype.getDelegateeDetails = function (address) {
745
- return __awaiter(this, void 0, void 0, function () {
746
- var validator, statusCodes;
747
- return __generator(this, function (_a) {
748
- switch (_a.label) {
749
- case 0: return [4 /*yield*/, this.nodeClient.fetchValidator(address)];
750
- case 1:
751
- validator = _a.sent();
752
- statusCodes = { 0: 'jailed', 1: 'inactive', 2: 'active' };
753
- return [2 /*return*/, {
754
- name: validator.description.moniker,
755
- status: statusCodes[validator.status],
756
- address: validator.operator_address
757
- }];
758
- }
759
- });
760
- });
761
- };
762
- CosmosProtocol.prototype.isPublicKeyDelegating = function (publicKey) {
763
- return __awaiter(this, void 0, void 0, function () {
764
- var address;
765
- return __generator(this, function (_a) {
766
- switch (_a.label) {
767
- case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
768
- case 1:
769
- address = _a.sent();
770
- return [2 /*return*/, this.isAddressDelegating(address.address)];
771
- }
772
- });
773
- });
774
- };
775
- CosmosProtocol.prototype.isAddressDelegating = function (address) {
776
- return __awaiter(this, void 0, void 0, function () {
777
- var delegations;
778
- return __generator(this, function (_a) {
779
- switch (_a.label) {
780
- case 0: return [4 /*yield*/, this.nodeClient.fetchDelegations(address)];
781
- case 1:
782
- delegations = _a.sent();
783
- return [2 /*return*/, delegations.length > 0];
784
- }
785
- });
786
- });
787
- };
788
- CosmosProtocol.prototype.getDelegatorDetailsFromPublicKey = function (publicKey) {
789
- return __awaiter(this, void 0, void 0, function () {
790
- var address;
791
- return __generator(this, function (_a) {
792
- switch (_a.label) {
793
- case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
794
- case 1:
795
- address = _a.sent();
796
- return [2 /*return*/, this.getDelegatorDetailsFromAddress(address.address)];
797
- }
798
- });
799
- });
800
- };
801
- CosmosProtocol.prototype.getDelegatorDetailsFromAddress = function (address) {
802
- return __awaiter(this, void 0, void 0, function () {
803
- return __generator(this, function (_a) {
804
- return [2 /*return*/, this.getDelegatorDetails(address)];
805
- });
806
- });
807
- };
808
- CosmosProtocol.prototype.getDelegationDetailsFromPublicKey = function (publicKey, delegatees) {
809
- return __awaiter(this, void 0, void 0, function () {
810
- var address;
811
- return __generator(this, function (_a) {
812
- switch (_a.label) {
813
- case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
814
- case 1:
815
- address = _a.sent();
816
- return [2 /*return*/, this.getDelegationDetailsFromAddress(address.address, delegatees)];
817
- }
818
- });
819
- });
820
- };
821
- CosmosProtocol.prototype.getDelegationDetailsFromAddress = function (address, delegatees) {
822
- return __awaiter(this, void 0, void 0, function () {
823
- var validator, results, delegatorDetails, validatorDetails;
824
- return __generator(this, function (_a) {
825
- switch (_a.label) {
826
- case 0:
827
- if (delegatees.length > 1) {
828
- return [2 /*return*/, Promise.reject('Multiple validators for a single delegation are not supported.')];
829
- }
830
- validator = delegatees[0];
831
- return [4 /*yield*/, Promise.all([this.getDelegatorDetails(address, validator), this.getDelegateeDetails(validator)])];
832
- case 1:
833
- results = _a.sent();
834
- delegatorDetails = results[0];
835
- validatorDetails = results[1];
836
- return [2 /*return*/, {
837
- delegator: delegatorDetails,
838
- delegatees: [validatorDetails]
839
- }];
840
- }
841
- });
842
- });
843
- };
844
- CosmosProtocol.prototype.prepareDelegatorActionFromPublicKey = function (publicKey, type, data) {
845
- return __awaiter(this, void 0, void 0, function () {
846
- var _a;
847
- return __generator(this, function (_b) {
848
- switch (_b.label) {
849
- case 0:
850
- _a = type;
851
- switch (_a) {
852
- case CosmosDelegationActionType.DELEGATE: return [3 /*break*/, 1];
853
- case CosmosDelegationActionType.UNDELEGATE: return [3 /*break*/, 3];
854
- case CosmosDelegationActionType.WITHDRAW_ALL_REWARDS: return [3 /*break*/, 5];
855
- case CosmosDelegationActionType.WITHDRAW_VALIDATOR_REWARDS: return [3 /*break*/, 7];
856
- }
857
- return [3 /*break*/, 9];
858
- case 1:
859
- (0, assert_1.assertFields)("".concat(type, " action"), data, 'validator', 'amount');
860
- return [4 /*yield*/, this.delegate(publicKey, data.validator, data.amount)];
861
- case 2: return [2 /*return*/, [_b.sent()]];
862
- case 3:
863
- (0, assert_1.assertFields)("".concat(type, " action"), data, 'validator', 'amount');
864
- return [4 /*yield*/, this.undelegate(publicKey, data.validator, data.amount)];
865
- case 4: return [2 /*return*/, [_b.sent()]];
866
- case 5: return [4 /*yield*/, this.withdrawDelegationRewards(publicKey)];
867
- case 6: return [2 /*return*/, [_b.sent()]];
868
- case 7:
869
- (0, assert_1.assertFields)("".concat(type, " action"), data, 'validator');
870
- return [4 /*yield*/, this.withdrawDelegationRewards(publicKey, [data.validator])];
871
- case 8: return [2 /*return*/, [_b.sent()]];
872
- case 9: return [2 /*return*/, Promise.reject("Delegator action type ".concat(type, " is not supported."))];
873
- }
874
- });
875
- });
876
- };
877
- CosmosProtocol.prototype.undelegate = function (publicKey, validatorAddress, amount, memo) {
878
- return __awaiter(this, void 0, void 0, function () {
879
- return __generator(this, function (_a) {
880
- return [2 /*return*/, this.delegate(publicKey, validatorAddress, amount, true, memo)];
881
- });
882
- });
883
- };
884
- CosmosProtocol.prototype.delegate = function (publicKey, validatorAddress, amount, undelegate, memo) {
885
- var _a;
886
- if (undelegate === void 0) { undelegate = false; }
887
- return __awaiter(this, void 0, void 0, function () {
888
- var address, nodeInfo, account, message;
889
- return __generator(this, function (_b) {
890
- switch (_b.label) {
891
- case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
892
- case 1:
893
- address = (_b.sent()).address;
894
- return [4 /*yield*/, this.nodeClient.fetchNodeInfo()];
895
- case 2:
896
- nodeInfo = _b.sent();
897
- return [4 /*yield*/, this.nodeClient.fetchAccount(address)];
898
- case 3:
899
- account = _b.sent();
900
- message = new CosmosDelegateMessage_1.CosmosDelegateMessage(address, Array.isArray(validatorAddress) ? validatorAddress[0] : validatorAddress, new CosmosCoin_1.CosmosCoin('uatom', amount), undelegate);
901
- return [2 /*return*/, new CosmosTransaction_1.CosmosTransaction([message], new CosmosFee_1.CosmosFee([new CosmosCoin_1.CosmosCoin('uatom', new bignumber_1.default(this.feeDefaults.low).shiftedBy(this.feeDecimals).toString(10))], this.defaultGas.toString(10)), memo !== undefined ? memo : '', nodeInfo.network, account.value.account_number, (_a = account.value.sequence) !== null && _a !== void 0 ? _a : '0')];
902
- }
903
- });
904
- });
905
- };
906
- CosmosProtocol.prototype.withdrawDelegationRewards = function (publicKey, _validatorAddresses, memo) {
907
- var _a;
908
- if (_validatorAddresses === void 0) { _validatorAddresses = []; }
909
- return __awaiter(this, void 0, void 0, function () {
910
- var validatorAddresses, address_1, rewards, filteredRewards, address, nodeInfo, account, messages;
911
- return __generator(this, function (_b) {
912
- switch (_b.label) {
913
- case 0:
914
- if (!(_validatorAddresses.length > 0)) return [3 /*break*/, 1];
915
- validatorAddresses = _validatorAddresses;
916
- return [3 /*break*/, 4];
917
- case 1: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
918
- case 2:
919
- address_1 = (_b.sent()).address;
920
- return [4 /*yield*/, this.nodeClient.fetchRewardDetails(address_1)];
921
- case 3:
922
- rewards = _b.sent();
923
- filteredRewards = rewards.filter(function (reward) {
924
- return reward.reward
925
- ? reward.reward
926
- .reduce(function (total, next) { return total.plus(new bignumber_1.default(next.amount)); }, new bignumber_1.default(0))
927
- .decimalPlaces(0, bignumber_1.default.ROUND_FLOOR)
928
- .gt(0)
929
- : false;
930
- });
931
- validatorAddresses = filteredRewards.map(function (reward) { return reward.validator_address; });
932
- _b.label = 4;
933
- case 4: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
934
- case 5:
935
- address = (_b.sent()).address;
936
- return [4 /*yield*/, this.nodeClient.fetchNodeInfo()];
937
- case 6:
938
- nodeInfo = _b.sent();
939
- return [4 /*yield*/, this.nodeClient.fetchAccount(address)];
940
- case 7:
941
- account = _b.sent();
942
- messages = validatorAddresses.map(function (validatorAddress) { return new CosmosWithdrawDelegationRewardMessage_1.CosmosWithdrawDelegationRewardMessage(address, validatorAddress); });
943
- return [2 /*return*/, new CosmosTransaction_1.CosmosTransaction(messages, new CosmosFee_1.CosmosFee([new CosmosCoin_1.CosmosCoin('uatom', new bignumber_1.default(this.feeDefaults.low).shiftedBy(this.feeDecimals).toString(10))], this.defaultGas.toString(10)), memo !== undefined ? memo : '', nodeInfo.network, account.value.account_number, (_a = account.value.sequence) !== null && _a !== void 0 ? _a : '0')];
944
275
  }
945
- });
946
- });
947
- };
948
- CosmosProtocol.prototype.withdrawAllDelegationRewards = function (delegatorAddress, fee, memo) {
949
- var _a;
950
- return __awaiter(this, void 0, void 0, function () {
951
- var nodeInfo, account;
952
- return __generator(this, function (_b) {
953
- switch (_b.label) {
954
- case 0: return [4 /*yield*/, this.nodeClient.fetchNodeInfo()];
955
- case 1:
956
- nodeInfo = _b.sent();
957
- return [4 /*yield*/, this.nodeClient.fetchAccount(delegatorAddress)];
958
- case 2:
959
- account = _b.sent();
960
- return [2 /*return*/, this.nodeClient.withdrawAllDelegationRewards(delegatorAddress, nodeInfo.network, account.value.account_number, (_a = account.value.sequence) !== null && _a !== void 0 ? _a : '0', this.defaultGas, fee, memo !== undefined ? memo : '')];
276
+ }));
277
+ }
278
+ return {
279
+ transactions: result,
280
+ cursor: {
281
+ address,
282
+ limit,
283
+ sender: {
284
+ total: senderTotal,
285
+ offset: senderOffset + senderLimit
286
+ },
287
+ recipient: {
288
+ total: recipientTotal,
289
+ offset: recipientOffset + recipientLimit
961
290
  }
962
- });
963
- });
964
- };
965
- CosmosProtocol.prototype.fetchTotalReward = function (delegatorAddress) {
966
- return __awaiter(this, void 0, void 0, function () {
967
- return __generator(this, function (_a) {
968
- return [2 /*return*/, this.nodeClient.fetchTotalReward(delegatorAddress)];
969
- });
970
- });
971
- };
972
- CosmosProtocol.prototype.fetchRewardForDelegation = function (delegatorAddress, validatorAddress) {
973
- return __awaiter(this, void 0, void 0, function () {
974
- return __generator(this, function (_a) {
975
- return [2 /*return*/, this.nodeClient.fetchRewardForDelegation(delegatorAddress, validatorAddress)];
976
- });
977
- });
978
- };
979
- CosmosProtocol.prototype.fetchDelegations = function (address) {
980
- return __awaiter(this, void 0, void 0, function () {
981
- return __generator(this, function (_a) {
982
- return [2 /*return*/, this.nodeClient.fetchDelegations(address)];
983
- });
984
- });
985
- };
986
- CosmosProtocol.prototype.fetchTotalDelegatedAmount = function (address) {
987
- return __awaiter(this, void 0, void 0, function () {
988
- return __generator(this, function (_a) {
989
- return [2 /*return*/, this.nodeClient.fetchTotalDelegatedAmount(address)];
990
- });
991
- });
992
- };
993
- CosmosProtocol.prototype.fetchValidator = function (address) {
994
- return __awaiter(this, void 0, void 0, function () {
995
- return __generator(this, function (_a) {
996
- return [2 /*return*/, this.nodeClient.fetchValidator(address)];
997
- });
998
- });
999
- };
1000
- CosmosProtocol.prototype.fetchUnbondingDelegations = function (delegatorAddress) {
1001
- return __awaiter(this, void 0, void 0, function () {
1002
- return __generator(this, function (_a) {
1003
- return [2 /*return*/, this.nodeClient.fetchUnbondingDelegations(delegatorAddress)];
1004
- });
1005
- });
1006
- };
1007
- CosmosProtocol.prototype.fetchTotalUnbondingAmount = function (address) {
1008
- return __awaiter(this, void 0, void 0, function () {
1009
- return __generator(this, function (_a) {
1010
- return [2 /*return*/, this.nodeClient.fetchTotalUnbondingAmount(address)];
1011
- });
1012
- });
1013
- };
1014
- CosmosProtocol.prototype.fetchValidators = function () {
1015
- return __awaiter(this, void 0, void 0, function () {
1016
- return __generator(this, function (_a) {
1017
- return [2 /*return*/, this.nodeClient.fetchValidators()];
1018
- });
1019
- });
1020
- };
1021
- CosmosProtocol.prototype.fetchSelfDelegation = function (address) {
1022
- return __awaiter(this, void 0, void 0, function () {
1023
- return __generator(this, function (_a) {
1024
- return [2 /*return*/, this.nodeClient.fetchSelfDelegation(address)];
1025
- });
1026
- });
1027
- };
1028
- CosmosProtocol.prototype.broadcastTransaction = function (rawTransaction) {
1029
- return __awaiter(this, void 0, void 0, function () {
1030
- return __generator(this, function (_a) {
1031
- return [2 /*return*/, this.nodeClient.broadcastSignedTransaction(rawTransaction)];
1032
- });
291
+ }
292
+ };
293
+ }
294
+ async signWithPrivateKey(privateKey, transaction) {
295
+ const privateKeyBuffer = Buffer.from(privateKey, 'hex');
296
+ const publicKey = this.getPublicKeyFromPrivateKey(privateKeyBuffer);
297
+ const encodedObject = transaction.toEncodeObject();
298
+ const signBytes = await (0, cosmjs_1.prepareSignBytes)(encodedObject, transaction.fee, Uint8Array.from(publicKey), new bignumber_1.default(transaction.sequence).toNumber(), transaction.chainID, new bignumber_1.default(transaction.accountNumber).toNumber());
299
+ const sha256Hash = sha('sha256').update(signBytes).digest();
300
+ const hash = Buffer.from(sha256Hash);
301
+ const signed = SECP256K1.sign(hash, privateKeyBuffer);
302
+ const sigBase64 = Buffer.from(signed.signature, 'binary').toString('base64');
303
+ const txBytes = await (0, cosmjs_1.encodeTxBytes)(encodedObject, transaction.fee, Uint8Array.from(publicKey), new bignumber_1.default(transaction.sequence).toNumber(), {
304
+ signature: sigBase64,
305
+ pub_key: {
306
+ type: 'tendermint/PubKeySecp256k1',
307
+ value: publicKey.toString('base64')
308
+ }
309
+ }, transaction.chainID, new bignumber_1.default(transaction.accountNumber).toNumber());
310
+ return Buffer.from(txBytes).toString('base64');
311
+ }
312
+ async getTransactionDetails(transaction) {
313
+ const result = transaction.transaction.toAirGapTransactions(this.identifier, this.options.network);
314
+ return result;
315
+ }
316
+ async getTransactionDetailsFromSigned(transaction) {
317
+ const bytes = Uint8Array.from(Buffer.from(transaction.transaction, 'base64'));
318
+ const decoded = await (0, cosmjs_1.decodeTxBytes)(bytes);
319
+ const fee = (decoded.fee?.amount)
320
+ .map(({ amount }) => new bignumber_1.default(amount))
321
+ .reduce((current, next) => current.plus(next))
322
+ .toString(10);
323
+ const result = decoded.messages
324
+ .map((message) => {
325
+ const type = message.typeUrl;
326
+ switch (type) {
327
+ case CosmosMessage_1.CosmosMessageType.Send.value:
328
+ const sendMessage = CosmosSendMessage_1.CosmosSendMessage.fromEncodeObject(message);
329
+ return sendMessage.toAirGapTransaction(this.identifier, this.options.network, fee);
330
+ case CosmosMessage_1.CosmosMessageType.Undelegate.value:
331
+ case CosmosMessage_1.CosmosMessageType.Delegate.value:
332
+ const delegateMessage = CosmosDelegateMessage_1.CosmosDelegateMessage.fromEncodeObject(message);
333
+ return delegateMessage.toAirGapTransaction(this.identifier, this.options.network, fee);
334
+ case CosmosMessage_1.CosmosMessageType.WithdrawDelegationReward.value:
335
+ const withdrawMessage = CosmosWithdrawDelegationRewardMessage_1.CosmosWithdrawDelegationRewardMessage.fromEncodeObject(message);
336
+ return withdrawMessage.toAirGapTransaction(this.identifier, this.options.network, fee);
337
+ default:
338
+ throw new errors_1.InvalidValueError(coinlib_error_1.Domain.COSMOS, 'Unknown transaction');
339
+ }
340
+ })
341
+ .map((tx) => {
342
+ if (!tx.transactionDetails) {
343
+ tx.transactionDetails = {};
344
+ }
345
+ tx.transactionDetails.memo = decoded.memo;
346
+ if (decoded.signerInfos.length > 0) {
347
+ tx.transactionDetails.sequence = decoded.signerInfos[0].sequence.toString(10);
348
+ }
349
+ return tx;
1033
350
  });
1034
- };
1035
- CosmosProtocol.prototype.getDelegatorDetails = function (address, validator) {
1036
- var _a;
1037
- return __awaiter(this, void 0, void 0, function () {
1038
- var results, totalBalance, availableBalance, delegations, rewardDetails, unclaimedRewards, unclaimedTotalRewards, unclaimedValidatorRewards, isDelegating, availableActions;
1039
- return __generator(this, function (_b) {
1040
- switch (_b.label) {
1041
- case 0: return [4 /*yield*/, Promise.all([
1042
- this.getBalanceOfAddresses([address]),
1043
- this.getAvailableBalanceOfAddresses([address]),
1044
- this.nodeClient.fetchDelegations(address).catch(function () { return []; }),
1045
- this.nodeClient.fetchRewardDetails(address).catch(function () { return []; })
1046
- ])];
1047
- case 1:
1048
- results = _b.sent();
1049
- totalBalance = results[0];
1050
- availableBalance = new bignumber_1.default(results[1]);
1051
- delegations = results[2];
1052
- rewardDetails = results[3];
1053
- unclaimedRewards = rewardDetails.map(function (details) {
1054
- var _a, _b;
1055
- return [
1056
- details.validator_address,
1057
- (_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)
1058
- ];
1059
- });
1060
- unclaimedTotalRewards = unclaimedRewards.reduce(function (total, next) { return total.plus(next[1]); }, new bignumber_1.default(0));
1061
- unclaimedValidatorRewards = validator
1062
- ? ((_a = unclaimedRewards.find(function (_a) {
1063
- var validatorAddress = _a[0], _ = _a[1];
1064
- return validatorAddress === validator;
1065
- })) === null || _a === void 0 ? void 0 : _a[1]) || new bignumber_1.default(0)
1066
- : undefined;
1067
- isDelegating = validator
1068
- ? delegations.some(function (delegation) { return delegation.delegation.validator_address === validator; })
1069
- : delegations.length > 0;
1070
- availableActions = this.getAvailableDelegatorActions(isDelegating, availableBalance, unclaimedTotalRewards, unclaimedValidatorRewards);
1071
- return [2 /*return*/, {
1072
- address: address,
1073
- balance: totalBalance,
1074
- delegatees: delegations.map(function (delegation) { return delegation.delegation.validator_address; }),
1075
- availableActions: availableActions
1076
- }];
1077
- }
351
+ return result;
352
+ }
353
+ async getBalanceOfAddresses(addresses) {
354
+ return this.getBalance(addresses);
355
+ }
356
+ async getBalanceOfPublicKey(publicKey) {
357
+ const address = await this.getAddressFromPublicKey(publicKey);
358
+ return this.getBalanceOfAddresses([address.address]);
359
+ }
360
+ async getAvailableBalanceOfAddresses(addresses) {
361
+ return this.getBalance(addresses, false);
362
+ }
363
+ async getBalanceOfPublicKeyForSubProtocols(publicKey, subProtocols) {
364
+ throw Promise.reject('get balance of sub protocols not supported');
365
+ }
366
+ async getBalance(addresses, totalBalance = true) {
367
+ const promises = [];
368
+ for (const address of addresses) {
369
+ promises.push(this.nodeClient.fetchBalance(address, totalBalance));
370
+ }
371
+ return (await Promise.all(promises).then((balances) => {
372
+ return balances.reduce((current, next) => {
373
+ return current.plus(next);
1078
374
  });
1079
- });
1080
- };
1081
- CosmosProtocol.prototype.getAvailableDelegatorActions = function (isDelegating, availableBalance, unclaimedTotalRewards, unclaimedDelegationRewards) {
1082
- var actions = [];
1083
- var requiredFee = new bignumber_1.default(this.feeDefaults.low).shiftedBy(this.feeDecimals);
1084
- var hasSufficientBalance = availableBalance.gt(requiredFee);
375
+ })).toString(10);
376
+ }
377
+ async estimateMaxTransactionValueFromPublicKey(publicKey, recipients, fee) {
378
+ const address = (await this.getAddressFromPublicKey(publicKey)).address;
379
+ const balance = await this.getAvailableBalanceOfAddresses([address]);
380
+ const balanceWrapper = new bignumber_1.default(balance);
381
+ let maxFee;
382
+ if (fee !== undefined) {
383
+ maxFee = new bignumber_1.default(fee);
384
+ }
385
+ else {
386
+ const estimatedFeeDefaults = await this.estimateFeeDefaultsFromPublicKey(publicKey, recipients, [balance]);
387
+ maxFee = new bignumber_1.default(estimatedFeeDefaults.medium).shiftedBy(this.decimals);
388
+ if (maxFee.gte(balanceWrapper)) {
389
+ maxFee = new bignumber_1.default(0);
390
+ }
391
+ }
392
+ let amountWithoutFees = balanceWrapper.minus(maxFee);
393
+ if (amountWithoutFees.isNegative()) {
394
+ amountWithoutFees = new bignumber_1.default(0);
395
+ }
396
+ return amountWithoutFees.toFixed();
397
+ }
398
+ async estimateFeeDefaultsFromPublicKey(publicKey, recipients, values, data) {
399
+ return this.feeDefaults;
400
+ }
401
+ async prepareTransactionFromPublicKey(publicKey, recipients, values, fee, data) {
402
+ const wrappedValues = values.map((value) => new bignumber_1.default(value));
403
+ const wrappedFee = new bignumber_1.default(fee);
404
+ if (recipients.length !== wrappedValues.length) {
405
+ return Promise.reject('recipients length does not match with values');
406
+ }
407
+ const address = (await this.getAddressFromPublicKey(publicKey)).address;
408
+ const nodeInfo = await this.nodeClient.fetchNodeInfo();
409
+ const account = await this.nodeClient.fetchAccount(address);
410
+ const balance = new bignumber_1.default(await this.getAvailableBalanceOfAddresses([address]));
411
+ if (balance.lt(values.reduce((pv, cv) => pv.plus(cv), wrappedFee))) {
412
+ throw new errors_1.BalanceError(coinlib_error_1.Domain.COSMOS, 'not enough balance');
413
+ }
414
+ const messages = [];
415
+ for (let i = 0; i < recipients.length; ++i) {
416
+ const message = new CosmosSendMessage_1.CosmosSendMessage(address, recipients[i], [
417
+ new CosmosCoin_1.CosmosCoin('uatom', wrappedValues[i].toString(10))
418
+ ]);
419
+ messages.push(message);
420
+ }
421
+ const memo = data?.memo ?? '';
422
+ const transaction = new CosmosTransaction_1.CosmosTransaction(messages, new CosmosFee_1.CosmosFee([new CosmosCoin_1.CosmosCoin('uatom', wrappedFee.toString(10))], this.defaultGas.toString(10)), memo, nodeInfo.network, account.value.account_number, account.value.sequence ?? '0');
423
+ return transaction;
424
+ }
425
+ async getDefaultDelegatee() {
426
+ const validators = await this.nodeClient.fetchValidators();
427
+ return validators.length > 0 ? validators[0].operator_address : '';
428
+ }
429
+ async getCurrentDelegateesForPublicKey(publicKey) {
430
+ const address = await this.getAddressFromPublicKey(publicKey);
431
+ return this.getCurrentDelegateesForAddress(address.address);
432
+ }
433
+ async getCurrentDelegateesForAddress(address) {
434
+ const delegations = await this.nodeClient.fetchDelegations(address);
435
+ return delegations.map((delegation) => delegation.delegation.validator_address);
436
+ }
437
+ async getDelegateeDetails(address) {
438
+ const validator = await this.nodeClient.fetchValidator(address);
439
+ const statusCodes = { 0: 'jailed', 1: 'inactive', 2: 'active' };
440
+ return {
441
+ name: validator.description.moniker,
442
+ status: statusCodes[validator.status],
443
+ address: validator.operator_address
444
+ };
445
+ }
446
+ async isPublicKeyDelegating(publicKey) {
447
+ const address = await this.getAddressFromPublicKey(publicKey);
448
+ return this.isAddressDelegating(address.address);
449
+ }
450
+ async isAddressDelegating(address) {
451
+ const delegations = await this.nodeClient.fetchDelegations(address);
452
+ return delegations.length > 0;
453
+ }
454
+ async getDelegatorDetailsFromPublicKey(publicKey) {
455
+ const address = await this.getAddressFromPublicKey(publicKey);
456
+ return this.getDelegatorDetailsFromAddress(address.address);
457
+ }
458
+ async getDelegatorDetailsFromAddress(address) {
459
+ return this.getDelegatorDetails(address);
460
+ }
461
+ async getDelegationDetailsFromPublicKey(publicKey, delegatees) {
462
+ const address = await this.getAddressFromPublicKey(publicKey);
463
+ return this.getDelegationDetailsFromAddress(address.address, delegatees);
464
+ }
465
+ async getDelegationDetailsFromAddress(address, delegatees) {
466
+ if (delegatees.length > 1) {
467
+ return Promise.reject('Multiple validators for a single delegation are not supported.');
468
+ }
469
+ const validator = delegatees[0];
470
+ const results = await Promise.all([this.getDelegatorDetails(address, validator), this.getDelegateeDetails(validator)]);
471
+ const delegatorDetails = results[0];
472
+ const validatorDetails = results[1];
473
+ return {
474
+ delegator: delegatorDetails,
475
+ delegatees: [validatorDetails]
476
+ };
477
+ }
478
+ async prepareDelegatorActionFromPublicKey(publicKey, type, data) {
479
+ switch (type) {
480
+ case CosmosDelegationActionType.DELEGATE:
481
+ (0, assert_1.assertFields)(`${type} action`, data, 'validator', 'amount');
482
+ return [await this.delegate(publicKey, data.validator, data.amount)];
483
+ case CosmosDelegationActionType.UNDELEGATE:
484
+ (0, assert_1.assertFields)(`${type} action`, data, 'validator', 'amount');
485
+ return [await this.undelegate(publicKey, data.validator, data.amount)];
486
+ case CosmosDelegationActionType.WITHDRAW_ALL_REWARDS:
487
+ return [await this.withdrawDelegationRewards(publicKey)];
488
+ case CosmosDelegationActionType.WITHDRAW_VALIDATOR_REWARDS:
489
+ (0, assert_1.assertFields)(`${type} action`, data, 'validator');
490
+ return [await this.withdrawDelegationRewards(publicKey, [data.validator])];
491
+ default:
492
+ return Promise.reject(`Delegator action type ${type} is not supported.`);
493
+ }
494
+ }
495
+ async undelegate(publicKey, validatorAddress, amount, memo) {
496
+ return this.delegate(publicKey, validatorAddress, amount, true, memo);
497
+ }
498
+ async delegate(publicKey, validatorAddress, amount, undelegate = false, memo) {
499
+ const address = (await this.getAddressFromPublicKey(publicKey)).address;
500
+ const nodeInfo = await this.nodeClient.fetchNodeInfo();
501
+ const account = await this.nodeClient.fetchAccount(address);
502
+ const message = new CosmosDelegateMessage_1.CosmosDelegateMessage(address, Array.isArray(validatorAddress) ? validatorAddress[0] : validatorAddress, new CosmosCoin_1.CosmosCoin('uatom', amount), undelegate);
503
+ return new CosmosTransaction_1.CosmosTransaction([message], new CosmosFee_1.CosmosFee([new CosmosCoin_1.CosmosCoin('uatom', new bignumber_1.default(this.feeDefaults.low).shiftedBy(this.feeDecimals).toString(10))], this.defaultGas.toString(10)), memo !== undefined ? memo : '', nodeInfo.network, account.value.account_number, account.value.sequence ?? '0');
504
+ }
505
+ async withdrawDelegationRewards(publicKey, _validatorAddresses = [], memo) {
506
+ let validatorAddresses;
507
+ if (_validatorAddresses.length > 0) {
508
+ validatorAddresses = _validatorAddresses;
509
+ }
510
+ else {
511
+ const address = (await this.getAddressFromPublicKey(publicKey)).address;
512
+ const rewards = await this.nodeClient.fetchRewardDetails(address);
513
+ const filteredRewards = rewards.filter((reward) => reward.reward
514
+ ? reward.reward
515
+ .reduce((total, next) => total.plus(new bignumber_1.default(next.amount)), new bignumber_1.default(0))
516
+ .decimalPlaces(0, bignumber_1.default.ROUND_FLOOR)
517
+ .gt(0)
518
+ : false);
519
+ validatorAddresses = filteredRewards.map((reward) => reward.validator_address);
520
+ }
521
+ const address = (await this.getAddressFromPublicKey(publicKey)).address;
522
+ const nodeInfo = await this.nodeClient.fetchNodeInfo();
523
+ const account = await this.nodeClient.fetchAccount(address);
524
+ const messages = validatorAddresses.map((validatorAddress) => new CosmosWithdrawDelegationRewardMessage_1.CosmosWithdrawDelegationRewardMessage(address, validatorAddress));
525
+ return new CosmosTransaction_1.CosmosTransaction(messages, new CosmosFee_1.CosmosFee([new CosmosCoin_1.CosmosCoin('uatom', new bignumber_1.default(this.feeDefaults.low).shiftedBy(this.feeDecimals).toString(10))], this.defaultGas.toString(10)), memo !== undefined ? memo : '', nodeInfo.network, account.value.account_number, account.value.sequence ?? '0');
526
+ }
527
+ async withdrawAllDelegationRewards(delegatorAddress, fee, memo) {
528
+ const nodeInfo = await this.nodeClient.fetchNodeInfo();
529
+ const account = await this.nodeClient.fetchAccount(delegatorAddress);
530
+ return this.nodeClient.withdrawAllDelegationRewards(delegatorAddress, nodeInfo.network, account.value.account_number, account.value.sequence ?? '0', this.defaultGas, fee, memo !== undefined ? memo : '');
531
+ }
532
+ async fetchTotalReward(delegatorAddress) {
533
+ return this.nodeClient.fetchTotalReward(delegatorAddress);
534
+ }
535
+ async fetchRewardForDelegation(delegatorAddress, validatorAddress) {
536
+ return this.nodeClient.fetchRewardForDelegation(delegatorAddress, validatorAddress);
537
+ }
538
+ async fetchDelegations(address) {
539
+ return this.nodeClient.fetchDelegations(address);
540
+ }
541
+ async fetchTotalDelegatedAmount(address) {
542
+ return this.nodeClient.fetchTotalDelegatedAmount(address);
543
+ }
544
+ async fetchValidator(address) {
545
+ return this.nodeClient.fetchValidator(address);
546
+ }
547
+ async fetchUnbondingDelegations(delegatorAddress) {
548
+ return this.nodeClient.fetchUnbondingDelegations(delegatorAddress);
549
+ }
550
+ async fetchTotalUnbondingAmount(address) {
551
+ return this.nodeClient.fetchTotalUnbondingAmount(address);
552
+ }
553
+ async fetchValidators() {
554
+ return this.nodeClient.fetchValidators();
555
+ }
556
+ async fetchSelfDelegation(address) {
557
+ return this.nodeClient.fetchSelfDelegation(address);
558
+ }
559
+ async broadcastTransaction(rawTransaction) {
560
+ return this.nodeClient.broadcastSignedTransaction(rawTransaction);
561
+ }
562
+ async getDelegatorDetails(address, validator) {
563
+ const results = await Promise.all([
564
+ this.getBalanceOfAddresses([address]),
565
+ this.getAvailableBalanceOfAddresses([address]),
566
+ this.nodeClient.fetchDelegations(address).catch(() => []),
567
+ this.nodeClient.fetchRewardDetails(address).catch(() => [])
568
+ ]);
569
+ const totalBalance = results[0];
570
+ const availableBalance = new bignumber_1.default(results[1]);
571
+ const delegations = results[2];
572
+ const rewardDetails = results[3];
573
+ const unclaimedRewards = rewardDetails.map((details) => [
574
+ details.validator_address,
575
+ details.reward?.reduce((total, next) => total.plus(next.amount), new bignumber_1.default(0)).decimalPlaces(0, bignumber_1.default.ROUND_FLOOR) ??
576
+ new bignumber_1.default(0)
577
+ ]);
578
+ const unclaimedTotalRewards = unclaimedRewards.reduce((total, next) => total.plus(next[1]), new bignumber_1.default(0));
579
+ const unclaimedValidatorRewards = validator
580
+ ? unclaimedRewards.find(([validatorAddress, _]) => validatorAddress === validator)?.[1] || new bignumber_1.default(0)
581
+ : undefined;
582
+ const isDelegating = validator
583
+ ? delegations.some((delegation) => delegation.delegation.validator_address === validator)
584
+ : delegations.length > 0;
585
+ const availableActions = this.getAvailableDelegatorActions(isDelegating, availableBalance, unclaimedTotalRewards, unclaimedValidatorRewards);
586
+ return {
587
+ address,
588
+ balance: totalBalance,
589
+ delegatees: delegations.map((delegation) => delegation.delegation.validator_address),
590
+ availableActions
591
+ };
592
+ }
593
+ getAvailableDelegatorActions(isDelegating, availableBalance, unclaimedTotalRewards, unclaimedDelegationRewards) {
594
+ const actions = [];
595
+ const requiredFee = new bignumber_1.default(this.feeDefaults.low).shiftedBy(this.feeDecimals);
596
+ const hasSufficientBalance = availableBalance.gt(requiredFee);
1085
597
  if (hasSufficientBalance) {
1086
598
  actions.push({
1087
599
  type: CosmosDelegationActionType.DELEGATE,
@@ -1099,64 +611,35 @@ var CosmosProtocol = /** @class */ (function (_super) {
1099
611
  type: CosmosDelegationActionType.WITHDRAW_ALL_REWARDS
1100
612
  });
1101
613
  }
1102
- if (unclaimedDelegationRewards === null || unclaimedDelegationRewards === void 0 ? void 0 : unclaimedDelegationRewards.gt(0)) {
614
+ if (unclaimedDelegationRewards?.gt(0)) {
1103
615
  actions.push({
1104
616
  type: CosmosDelegationActionType.WITHDRAW_VALIDATOR_REWARDS,
1105
617
  args: ['validator']
1106
618
  });
1107
619
  }
1108
620
  return actions;
1109
- };
1110
- CosmosProtocol.prototype.signMessage = function (message, keypair) {
1111
- return __awaiter(this, void 0, void 0, function () {
1112
- return __generator(this, function (_a) {
1113
- return [2 /*return*/, this.cryptoClient.signMessage(message, keypair)];
1114
- });
1115
- });
1116
- };
1117
- CosmosProtocol.prototype.verifyMessage = function (message, signature, publicKey) {
1118
- return __awaiter(this, void 0, void 0, function () {
1119
- return __generator(this, function (_a) {
1120
- return [2 /*return*/, this.cryptoClient.verifyMessage(message, signature, publicKey)];
1121
- });
1122
- });
1123
- };
1124
- CosmosProtocol.prototype.encryptAsymmetric = function (message, publicKey) {
1125
- return __awaiter(this, void 0, void 0, function () {
1126
- return __generator(this, function (_a) {
1127
- return [2 /*return*/, this.cryptoClient.encryptAsymmetric(message, publicKey)];
1128
- });
1129
- });
1130
- };
1131
- CosmosProtocol.prototype.decryptAsymmetric = function (message, keypair) {
1132
- return __awaiter(this, void 0, void 0, function () {
1133
- return __generator(this, function (_a) {
1134
- return [2 /*return*/, this.cryptoClient.decryptAsymmetric(message, keypair)];
1135
- });
1136
- });
1137
- };
1138
- CosmosProtocol.prototype.encryptAES = function (message, privateKey) {
1139
- return __awaiter(this, void 0, void 0, function () {
1140
- return __generator(this, function (_a) {
1141
- return [2 /*return*/, this.cryptoClient.encryptAES(message, privateKey)];
1142
- });
1143
- });
1144
- };
1145
- CosmosProtocol.prototype.decryptAES = function (message, privateKey) {
1146
- return __awaiter(this, void 0, void 0, function () {
1147
- return __generator(this, function (_a) {
1148
- return [2 /*return*/, this.cryptoClient.decryptAES(message, privateKey)];
1149
- });
1150
- });
1151
- };
1152
- CosmosProtocol.prototype.getTransactionStatuses = function (transactionHashes) {
1153
- return __awaiter(this, void 0, void 0, function () {
1154
- return __generator(this, function (_a) {
1155
- return [2 /*return*/, Promise.reject('Transaction status not implemented')];
1156
- });
1157
- });
1158
- };
1159
- return CosmosProtocol;
1160
- }(NonExtendedProtocol_1.NonExtendedProtocol));
621
+ }
622
+ async signMessage(message, keypair) {
623
+ return this.cryptoClient.signMessage(message, keypair);
624
+ }
625
+ async verifyMessage(message, signature, publicKey) {
626
+ return this.cryptoClient.verifyMessage(message, signature, publicKey);
627
+ }
628
+ async encryptAsymmetric(message, publicKey) {
629
+ return this.cryptoClient.encryptAsymmetric(message, publicKey);
630
+ }
631
+ async decryptAsymmetric(message, keypair) {
632
+ return this.cryptoClient.decryptAsymmetric(message, keypair);
633
+ }
634
+ async encryptAES(message, privateKey) {
635
+ return this.cryptoClient.encryptAES(message, privateKey);
636
+ }
637
+ async decryptAES(message, privateKey) {
638
+ return this.cryptoClient.decryptAES(message, privateKey);
639
+ }
640
+ async getTransactionStatuses(transactionHashes) {
641
+ return Promise.reject('Transaction status not implemented');
642
+ }
643
+ }
1161
644
  exports.CosmosProtocol = CosmosProtocol;
1162
645
  //# sourceMappingURL=CosmosProtocol.js.map