@airgap/icp 0.13.15-beta.1 → 0.13.15-beta.11

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 (93) hide show
  1. package/package.json +8 -6
  2. package/v1/block-explorer/ICPBlockExplorer.d.ts +1 -1
  3. package/v1/block-explorer/ICPBlockExplorer.js +16 -49
  4. package/v1/block-explorer/ICPBlockExplorer.js.map +1 -1
  5. package/v1/index.d.ts +3 -2
  6. package/v1/index.js +9 -5
  7. package/v1/index.js.map +1 -1
  8. package/v1/module/ICPModule.d.ts +2 -4
  9. package/v1/module/ICPModule.js +53 -94
  10. package/v1/module/ICPModule.js.map +1 -1
  11. package/v1/module.js +1 -1
  12. package/v1/module.js.map +1 -1
  13. package/v1/protocol/ICPGovernance.d.ts +39 -0
  14. package/v1/protocol/ICPGovernance.js +1177 -0
  15. package/v1/protocol/ICPGovernance.js.map +1 -0
  16. package/v1/protocol/ICPImplementation.d.ts +30 -5
  17. package/v1/protocol/ICPImplementation.js +317 -252
  18. package/v1/protocol/ICPImplementation.js.map +1 -1
  19. package/v1/protocol/ICPProtocol.d.ts +60 -8
  20. package/v1/protocol/ICPProtocol.js +765 -320
  21. package/v1/protocol/ICPProtocol.js.map +1 -1
  22. package/v1/protocol/icrc/CkBTCProtocol.js +138 -225
  23. package/v1/protocol/icrc/CkBTCProtocol.js.map +1 -1
  24. package/v1/protocol/icrc/ICRC1Protocol.d.ts +4 -4
  25. package/v1/protocol/icrc/ICRC1Protocol.js +338 -553
  26. package/v1/protocol/icrc/ICRC1Protocol.js.map +1 -1
  27. package/v1/serializer/v3/schemas/converter/transaction-converter.js +48 -5
  28. package/v1/serializer/v3/schemas/converter/transaction-converter.js.map +1 -1
  29. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-icp.d.ts +8 -2
  30. package/v1/serializer/v3/schemas/generated/transaction-sign-request-icp.json +31 -1
  31. package/v1/serializer/v3/serializer-companion.js +85 -144
  32. package/v1/serializer/v3/serializer-companion.js.map +1 -1
  33. package/v1/serializer/v3/validators/transaction-validator.js +22 -60
  34. package/v1/serializer/v3/validators/transaction-validator.js.map +1 -1
  35. package/v1/serializer/v3/validators/validators.js +19 -58
  36. package/v1/serializer/v3/validators/validators.js.map +1 -1
  37. package/v1/types/governance.d.ts +29 -0
  38. package/v1/types/governance.js +279 -210
  39. package/v1/types/governance.js.map +1 -1
  40. package/v1/types/icrc/ledger.js +22 -23
  41. package/v1/types/icrc/ledger.js.map +1 -1
  42. package/v1/types/ledger.d.ts +1 -0
  43. package/v1/types/ledger.js +37 -38
  44. package/v1/types/ledger.js.map +1 -1
  45. package/v1/types/management_idl.js +6 -7
  46. package/v1/types/management_idl.js.map +1 -1
  47. package/v1/types/protocol.d.ts +2 -1
  48. package/v1/types/transaction.d.ts +22 -3
  49. package/v1/types/transaction.js +38 -0
  50. package/v1/types/transaction.js.map +1 -1
  51. package/v1/utils/account.js +42 -70
  52. package/v1/utils/account.js.map +1 -1
  53. package/v1/utils/actor.js +139 -322
  54. package/v1/utils/actor.js.map +1 -1
  55. package/v1/utils/auth.js +44 -134
  56. package/v1/utils/auth.js.map +1 -1
  57. package/v1/utils/bls.js +41 -109
  58. package/v1/utils/bls.js.map +1 -1
  59. package/v1/utils/buffer.js +47 -111
  60. package/v1/utils/buffer.js.map +1 -1
  61. package/v1/utils/cbor.js +50 -85
  62. package/v1/utils/cbor.js.map +1 -1
  63. package/v1/utils/certificate.js +116 -238
  64. package/v1/utils/certificate.js.map +1 -1
  65. package/v1/utils/convert.d.ts +1 -1
  66. package/v1/utils/convert.js +29 -49
  67. package/v1/utils/convert.js.map +1 -1
  68. package/v1/utils/der.js +37 -35
  69. package/v1/utils/der.js.map +1 -1
  70. package/v1/utils/errors.js +10 -30
  71. package/v1/utils/errors.js.map +1 -1
  72. package/v1/utils/hdkey.js +33 -33
  73. package/v1/utils/hdkey.js.map +1 -1
  74. package/v1/utils/http.d.ts +1 -1
  75. package/v1/utils/http.js +202 -426
  76. package/v1/utils/http.js.map +1 -1
  77. package/v1/utils/icrc1.js +24 -41
  78. package/v1/utils/icrc1.js.map +1 -1
  79. package/v1/utils/idl.js +780 -1159
  80. package/v1/utils/idl.js.map +1 -1
  81. package/v1/utils/json.d.ts +1 -0
  82. package/v1/utils/json.js +19 -0
  83. package/v1/utils/json.js.map +1 -0
  84. package/v1/utils/leb128.js +29 -30
  85. package/v1/utils/leb128.js.map +1 -1
  86. package/v1/utils/polling.js +84 -234
  87. package/v1/utils/polling.js.map +1 -1
  88. package/v1/utils/principal.js +78 -126
  89. package/v1/utils/principal.js.map +1 -1
  90. package/v1/utils/secp256k1.js +68 -134
  91. package/v1/utils/secp256k1.js.map +1 -1
  92. package/v1/utils/transaction.js +7 -7
  93. package/v1/utils/transaction.js.map +1 -1
@@ -1,14 +1,26 @@
1
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);
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
12
24
  };
13
25
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
26
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -19,48 +31,29 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
19
31
  step((generator = generator.apply(thisArg, _arguments || [])).next());
20
32
  });
21
33
  };
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
34
  var __importDefault = (this && this.__importDefault) || function (mod) {
50
35
  return (mod && mod.__esModule) ? mod : { "default": mod };
51
36
  };
52
37
  Object.defineProperty(exports, "__esModule", { value: true });
53
38
  exports.createICPProtocolOptions = exports.ICP_MAINNET_PROTOCOL_NETWORK = exports.createICPProtocol = exports.ICPProtocolImpl = exports.ICP_TRANSACTION_METADATA = exports.ICP_ACCOUNT_METADATA = exports.ICP_DERIVATION_PATH = void 0;
54
- var coinlib_core_1 = require("@airgap/coinlib-core");
55
- var index_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/axios-0.19.0/index"));
56
- var bignumber_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/bignumber.js-9.0.0/bignumber"));
57
- var errors_1 = require("@airgap/coinlib-core/errors");
58
- var crypto_1 = require("@airgap/crypto");
59
- var module_kit_1 = require("@airgap/module-kit");
60
- var convert_1 = require("../utils/convert");
61
- var ICPImplementation_1 = require("./ICPImplementation");
39
+ const coinlib_core_1 = require("@airgap/coinlib-core");
40
+ const index_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/axios-0.19.0/index"));
41
+ const bignumber_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/bignumber.js-9.0.0/bignumber"));
42
+ const errors_1 = require("@airgap/coinlib-core/errors");
43
+ const array_1 = require("@airgap/coinlib-core/utils/array");
44
+ const assert_1 = require("@airgap/coinlib-core/utils/assert");
45
+ const crypto_1 = require("@airgap/crypto");
46
+ const module_kit_1 = require("@airgap/module-kit");
47
+ const governance_1 = require("../types/governance");
48
+ const transaction_1 = require("../types/transaction");
49
+ const account_1 = require("../utils/account");
50
+ const Cbor = __importStar(require("../utils/cbor"));
51
+ const IDL = __importStar(require("../utils/idl"));
52
+ const principal_1 = require("../utils/principal");
53
+ const ICPGovernance_1 = require("./ICPGovernance");
54
+ const ICPImplementation_1 = require("./ICPImplementation");
62
55
  // Implementation
63
- exports.ICP_DERIVATION_PATH = "m/44'/223'/0'/0/0";
56
+ exports.ICP_DERIVATION_PATH = `m/44'/223'/0'/0/0`;
64
57
  exports.ICP_ACCOUNT_METADATA = {
65
58
  standardDerivationPath: exports.ICP_DERIVATION_PATH,
66
59
  address: {
@@ -77,9 +70,8 @@ function ICP_TRANSACTION_METADATA() {
77
70
  };
78
71
  }
79
72
  exports.ICP_TRANSACTION_METADATA = ICP_TRANSACTION_METADATA;
80
- var ICPProtocolImpl = /** @class */ (function () {
81
- function ICPProtocolImpl(options) {
82
- if (options === void 0) { options = {}; }
73
+ class ICPProtocolImpl {
74
+ constructor(options = {}) {
83
75
  // Common
84
76
  this.units = {
85
77
  ICP: {
@@ -108,316 +100,769 @@ var ICPProtocolImpl = /** @class */ (function () {
108
100
  algorithm: 'secp256k1'
109
101
  };
110
102
  this.options = createICPProtocolOptions(options.network);
103
+ this.canisterId = {
104
+ ledger: this.options.network.ledgerCanisterId,
105
+ governance: this.options.network.governanceCanisterId
106
+ };
111
107
  }
112
- ICPProtocolImpl.prototype.getMetadata = function () {
113
- return __awaiter(this, void 0, void 0, function () {
114
- return __generator(this, function (_a) {
115
- return [2 /*return*/, this.metadata];
116
- });
108
+ getMetadata() {
109
+ return __awaiter(this, void 0, void 0, function* () {
110
+ return this.metadata;
117
111
  });
118
- };
119
- ICPProtocolImpl.prototype.getAddressFromPublicKey = function (publicKey) {
120
- return __awaiter(this, void 0, void 0, function () {
121
- return __generator(this, function (_a) {
122
- return [2 /*return*/, (0, ICPImplementation_1.getAddressFromPublicKey)(publicKey.value)];
123
- });
112
+ }
113
+ getAddressFromPublicKey(publicKey) {
114
+ return __awaiter(this, void 0, void 0, function* () {
115
+ return (0, ICPImplementation_1.getAddressFromPublicKey)(publicKey.value);
124
116
  });
125
- };
126
- ICPProtocolImpl.prototype.getDetailsFromTransaction = function (transaction, _publicKey) {
127
- return __awaiter(this, void 0, void 0, function () {
128
- var signedTransactionInfo, args, unsignedTransactionInfo;
129
- return __generator(this, function (_a) {
130
- switch (transaction.type) {
131
- case 'signed':
132
- signedTransactionInfo = (0, ICPImplementation_1.getInfoFromSignedTransaction)(transaction.transaction);
133
- args = (0, ICPImplementation_1.decodeArguments)(signedTransactionInfo.content.arg)[0];
134
- return [2 /*return*/, [
135
- {
136
- from: [(0, ICPImplementation_1.getAddressFromPublicKey)(_publicKey.value)],
137
- to: [(0, convert_1.uint8ArrayToHexString)(args.to)],
138
- isInbound: false,
139
- amount: (0, module_kit_1.newAmount)(args.amount.e8s.toString(), 'blockchain'),
140
- fee: (0, module_kit_1.newAmount)(args.fee.e8s.toString(), 'blockchain'),
141
- network: this.options.network
142
- }
143
- ]];
144
- case 'unsigned':
145
- unsignedTransactionInfo = (0, ICPImplementation_1.getInfoFromUnsignedTransaction)(transaction.transaction);
146
- return [2 /*return*/, [
147
- {
148
- from: [(0, ICPImplementation_1.getAddressFromPublicKey)(_publicKey.value)],
149
- to: [unsignedTransactionInfo.to],
150
- isInbound: false,
151
- amount: (0, module_kit_1.newAmount)(unsignedTransactionInfo.amount.toString(), 'blockchain'),
152
- fee: (0, module_kit_1.newAmount)(unsignedTransactionInfo.fee.toString(), 'blockchain'),
153
- network: this.options.network
154
- }
155
- ]];
156
- default:
157
- (0, coinlib_core_1.assertNever)(transaction);
158
- throw new errors_1.UnsupportedError(coinlib_core_1.Domain.ICP, 'Unsupported transaction type.');
159
- }
160
- return [2 /*return*/];
161
- });
117
+ }
118
+ getDetailsFromTransaction(transaction, publicKey) {
119
+ return __awaiter(this, void 0, void 0, function* () {
120
+ switch (transaction.type) {
121
+ case 'signed':
122
+ return this.getDetailsFromSignedTransaction(transaction, publicKey);
123
+ case 'unsigned':
124
+ return this.getDetailsFromUnsignedTransaction(transaction, publicKey);
125
+ default:
126
+ (0, coinlib_core_1.assertNever)(transaction);
127
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.ICP, 'Unsupported transaction type.');
128
+ }
162
129
  });
163
- };
164
- ICPProtocolImpl.prototype.getCryptoConfiguration = function () {
165
- return __awaiter(this, void 0, void 0, function () {
166
- return __generator(this, function (_a) {
167
- return [2 /*return*/, this.cryptoConfiguration];
168
- });
130
+ }
131
+ getDetailsFromSignedTransaction(transaction, publicKey) {
132
+ const transactions = transaction.transactions.map(({ actionType, encoded }) => {
133
+ switch (actionType) {
134
+ case transaction_1.ICPActionType.TRANSFER:
135
+ return (0, ICPImplementation_1.getDetailsFromSignedTransactionTransfer)(encoded, publicKey.value, this.options.network);
136
+ case transaction_1.ICPActionType.GET_NEURON_INFO:
137
+ return (0, ICPGovernance_1.getDetailsFromSignedGetNeuronInfo)(encoded, publicKey.value, this.options.network);
138
+ case transaction_1.ICPActionType.TRANSFER_TO_SUBACCOUNT:
139
+ return (0, ICPGovernance_1.getDetailsFromSignedTransferToSubaccount)(encoded, publicKey.value, this.options.network);
140
+ case transaction_1.ICPActionType.CLAIM_GOVERNANCE:
141
+ return (0, ICPGovernance_1.getDetailsFromSignedClaimGovernance)(encoded, publicKey.value, this.options.network);
142
+ case transaction_1.ICPActionType.FOLLOW_NEURON:
143
+ return (0, ICPGovernance_1.getDetailsFromSignedFollowNeuron)(encoded, publicKey.value, this.options.network);
144
+ case transaction_1.ICPActionType.DISBURSE:
145
+ return (0, ICPGovernance_1.getDetailsFromSignedDisburse)(encoded, publicKey.value, this.options.network);
146
+ case transaction_1.ICPActionType.INCREASE_DISSOLVE_DELAY:
147
+ return (0, ICPGovernance_1.getDetailsFromSignedIncreaseDissolveDelay)(encoded, publicKey.value, this.options.network);
148
+ case transaction_1.ICPActionType.START_DISSOLVING:
149
+ return (0, ICPGovernance_1.getDetailsFromSignedStartDissolving)(encoded, publicKey.value, this.options.network);
150
+ case transaction_1.ICPActionType.STOP_DISSOLVING:
151
+ return (0, ICPGovernance_1.getDetailsFromSignedStopDissolving)(encoded, publicKey.value, this.options.network);
152
+ case transaction_1.ICPActionType.AUTO_STAKE_MATURITY:
153
+ return (0, ICPGovernance_1.getDetailsFromSignedAutoStakeMaturity)(encoded, publicKey.value, this.options.network);
154
+ default:
155
+ (0, coinlib_core_1.assertNever)(actionType);
156
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.ICP, 'Unsupported ICP action type');
157
+ }
169
158
  });
170
- };
171
- ICPProtocolImpl.prototype.getKeyPairFromDerivative = function (derivative) {
172
- return __awaiter(this, void 0, void 0, function () {
173
- var bip32Node, _a, publicKey, privateKey;
174
- return __generator(this, function (_b) {
175
- bip32Node = (0, crypto_1.encodeDerivative)('bip32', derivative);
176
- _a = (0, ICPImplementation_1.getKeyPairFromExtendedSecretKey)(bip32Node.secretKey), publicKey = _a.publicKey, privateKey = _a.privateKey;
177
- return [2 /*return*/, {
178
- secretKey: (0, module_kit_1.newSecretKey)(privateKey, 'hex'),
179
- publicKey: (0, module_kit_1.newPublicKey)(publicKey, 'hex')
180
- }];
181
- });
159
+ return (0, array_1.flattenArray)(transactions);
160
+ }
161
+ getDetailsFromUnsignedTransaction(transaction, publicKey) {
162
+ const transactions = transaction.transactions.map(({ actionType, encoded }) => {
163
+ switch (actionType) {
164
+ case transaction_1.ICPActionType.TRANSFER:
165
+ return (0, ICPImplementation_1.getDetailsFromUnsignedTransactionTransfer)(encoded, publicKey.value, this.options.network);
166
+ case transaction_1.ICPActionType.GET_NEURON_INFO:
167
+ return (0, ICPGovernance_1.getDetailsFromUnsignedGetNeuronInfo)(publicKey.value, this.options.network);
168
+ case transaction_1.ICPActionType.TRANSFER_TO_SUBACCOUNT:
169
+ return (0, ICPGovernance_1.getDetailsFromUnsignedTransferToSubaccount)(encoded, publicKey.value, this.options.network);
170
+ case transaction_1.ICPActionType.CLAIM_GOVERNANCE:
171
+ return (0, ICPGovernance_1.getDetailsFromUnsignedClaimGovernance)(encoded, publicKey.value, this.options.network);
172
+ case transaction_1.ICPActionType.DISBURSE:
173
+ return (0, ICPGovernance_1.getDetailsFromUnsignedDisburse)(encoded, publicKey.value, this.options.network);
174
+ case transaction_1.ICPActionType.INCREASE_DISSOLVE_DELAY:
175
+ return (0, ICPGovernance_1.getDetailsFromUnsignedIncreaseDissolveDelay)(encoded, publicKey.value, this.options.network);
176
+ case transaction_1.ICPActionType.START_DISSOLVING:
177
+ return (0, ICPGovernance_1.getDetailsFromUnsignedStartDissolving)(encoded, publicKey.value, this.options.network);
178
+ case transaction_1.ICPActionType.STOP_DISSOLVING:
179
+ return (0, ICPGovernance_1.getDetailsFromUnsignedStopDissolving)(encoded, publicKey.value, this.options.network);
180
+ case transaction_1.ICPActionType.FOLLOW_NEURON:
181
+ return (0, ICPGovernance_1.getDetailsFromUnsignedFollowNeuron)(encoded, publicKey.value, this.options.network);
182
+ case transaction_1.ICPActionType.AUTO_STAKE_MATURITY:
183
+ return (0, ICPGovernance_1.getDetailsFromUnsignedAutoStakeMaturity)(encoded, publicKey.value, this.options.network);
184
+ default:
185
+ (0, coinlib_core_1.assertNever)(actionType);
186
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.ICP, 'Unsupported ICP action type');
187
+ }
182
188
  });
183
- };
184
- ICPProtocolImpl.prototype.signTransactionWithSecretKey = function (transaction, secretKey) {
185
- return __awaiter(this, void 0, void 0, function () {
186
- var signedTransaction;
187
- return __generator(this, function (_a) {
188
- switch (_a.label) {
189
- case 0:
190
- if (secretKey.format !== 'hex') {
191
- throw new errors_1.ConditionViolationError(coinlib_core_1.Domain.ICP, 'Secret key is of an unexpected format.');
192
- }
193
- return [4 /*yield*/, (0, ICPImplementation_1.signICPTransaction)(transaction.transaction, secretKey.value, this.options.network.ledgerCanisterId)];
194
- case 1:
195
- signedTransaction = _a.sent();
196
- return [2 /*return*/, (0, module_kit_1.newSignedTransaction)({ transaction: signedTransaction })];
189
+ return (0, array_1.flattenArray)(transactions);
190
+ }
191
+ getCryptoConfiguration() {
192
+ return __awaiter(this, void 0, void 0, function* () {
193
+ return this.cryptoConfiguration;
194
+ });
195
+ }
196
+ getKeyPairFromDerivative(derivative) {
197
+ return __awaiter(this, void 0, void 0, function* () {
198
+ const bip32Node = (0, crypto_1.encodeDerivative)('bip32', derivative);
199
+ const { publicKey, privateKey } = (0, ICPImplementation_1.getKeyPairFromExtendedSecretKey)(bip32Node.secretKey);
200
+ return {
201
+ secretKey: (0, module_kit_1.newSecretKey)(privateKey, 'hex'),
202
+ publicKey: (0, module_kit_1.newPublicKey)(publicKey, 'hex')
203
+ };
204
+ });
205
+ }
206
+ signTransactionWithSecretKey(transaction, secretKey) {
207
+ return __awaiter(this, void 0, void 0, function* () {
208
+ if (secretKey.format !== 'hex') {
209
+ throw new errors_1.ConditionViolationError(coinlib_core_1.Domain.ICP, 'Secret key is of an unexpected format.');
210
+ }
211
+ const transactions = yield Promise.all(transaction.transactions.map(({ encoded, actionType }) => __awaiter(this, void 0, void 0, function* () {
212
+ switch (actionType) {
213
+ case transaction_1.ICPActionType.TRANSFER:
214
+ return {
215
+ actionType,
216
+ encoded: yield (0, ICPImplementation_1.signTransactionTransfer)(encoded, secretKey.value, this.options.network.ledgerCanisterId)
217
+ };
218
+ case transaction_1.ICPActionType.GET_NEURON_INFO:
219
+ return {
220
+ actionType,
221
+ encoded: yield (0, ICPGovernance_1.signGetNeuronInfo)(encoded, secretKey.value, this.options.network.governanceCanisterId)
222
+ };
223
+ case transaction_1.ICPActionType.TRANSFER_TO_SUBACCOUNT:
224
+ return {
225
+ actionType,
226
+ encoded: yield (0, ICPGovernance_1.signTransferToSubaccount)(encoded, secretKey.value, this.options.network.ledgerCanisterId)
227
+ };
228
+ case transaction_1.ICPActionType.CLAIM_GOVERNANCE:
229
+ return {
230
+ actionType,
231
+ encoded: yield (0, ICPGovernance_1.signClaimGovernance)(encoded, secretKey.value, this.options.network.governanceCanisterId)
232
+ };
233
+ case transaction_1.ICPActionType.DISBURSE:
234
+ return {
235
+ actionType,
236
+ encoded: yield (0, ICPGovernance_1.signDisburse)(encoded, secretKey.value, this.options.network.governanceCanisterId)
237
+ };
238
+ case transaction_1.ICPActionType.INCREASE_DISSOLVE_DELAY:
239
+ return {
240
+ actionType,
241
+ encoded: yield (0, ICPGovernance_1.signIncreaseDissolveDelay)(encoded, secretKey.value, this.options.network.governanceCanisterId)
242
+ };
243
+ case transaction_1.ICPActionType.START_DISSOLVING:
244
+ return {
245
+ actionType,
246
+ encoded: yield (0, ICPGovernance_1.signStartDissolving)(encoded, secretKey.value, this.options.network.governanceCanisterId)
247
+ };
248
+ case transaction_1.ICPActionType.STOP_DISSOLVING:
249
+ return {
250
+ actionType,
251
+ encoded: yield (0, ICPGovernance_1.signStopDissolving)(encoded, secretKey.value, this.options.network.governanceCanisterId)
252
+ };
253
+ case transaction_1.ICPActionType.FOLLOW_NEURON:
254
+ return {
255
+ actionType,
256
+ encoded: yield (0, ICPGovernance_1.signFollowNeuron)(encoded, secretKey.value, this.options.network.governanceCanisterId)
257
+ };
258
+ case transaction_1.ICPActionType.AUTO_STAKE_MATURITY:
259
+ return {
260
+ actionType,
261
+ encoded: yield (0, ICPGovernance_1.signAutoStakeMaturity)(encoded, secretKey.value, this.options.network.governanceCanisterId)
262
+ };
263
+ default:
264
+ (0, coinlib_core_1.assertNever)(actionType);
265
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.ICP, `ICP action type ${actionType} is not supported.`);
197
266
  }
198
- });
267
+ })));
268
+ return (0, module_kit_1.newSignedTransaction)({ transactions });
199
269
  });
200
- };
270
+ }
201
271
  // Online
202
- ICPProtocolImpl.prototype.getNetwork = function () {
203
- return __awaiter(this, void 0, void 0, function () {
204
- return __generator(this, function (_a) {
205
- return [2 /*return*/, this.options.network];
206
- });
272
+ getNetwork() {
273
+ return __awaiter(this, void 0, void 0, function* () {
274
+ return this.options.network;
207
275
  });
208
- };
209
- ICPProtocolImpl.prototype.getTransactionsForPublicKey = function (publicKey, limit, cursor) {
210
- return __awaiter(this, void 0, void 0, function () {
211
- var address;
212
- return __generator(this, function (_a) {
213
- switch (_a.label) {
214
- case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
215
- case 1:
216
- address = _a.sent();
217
- return [2 /*return*/, this.getTransactionsForAddress(address, limit, cursor)];
218
- }
219
- });
276
+ }
277
+ getTransactionsForPublicKey(publicKey, limit, cursor) {
278
+ return __awaiter(this, void 0, void 0, function* () {
279
+ const address = yield this.getAddressFromPublicKey(publicKey);
280
+ return this.getTransactionsForAddress(address, limit, cursor);
220
281
  });
221
- };
222
- ICPProtocolImpl.prototype.getTransactionsForAddress = function (address, limit, cursor) {
282
+ }
283
+ getTransactionsForAddress(address, limit, cursor) {
223
284
  var _a;
224
- return __awaiter(this, void 0, void 0, function () {
225
- var endpoint, url, response, _b, nodeTransactions, tokens, offset, next, transactions;
226
- var _this = this;
227
- return __generator(this, function (_c) {
228
- switch (_c.label) {
229
- case 0:
230
- endpoint = cursor === undefined ? "/accounts/".concat(address, "/transactions?limit=").concat(limit, "&offset=0") : cursor.next;
231
- url = endpoint !== undefined ? "".concat(this.options.network.blockExplorerApi).concat(endpoint) : undefined;
232
- if (!(url !== undefined)) return [3 /*break*/, 2];
233
- return [4 /*yield*/, index_1.default.get(url)];
234
- case 1:
235
- _b = _c.sent();
236
- return [3 /*break*/, 3];
237
- case 2:
238
- _b = undefined;
239
- _c.label = 3;
240
- case 3:
241
- response = _b;
242
- nodeTransactions = ((_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.blocks) || [];
243
- tokens = endpoint.split('=');
244
- offset = parseInt(tokens[tokens.length - 1]);
245
- tokens[tokens.length - 1] = (offset + limit).toString();
246
- next = tokens.join('=');
247
- transactions = nodeTransactions.map(function (obj) {
248
- return {
249
- from: [obj.from_account_identifier],
250
- to: [obj.to_account_identifier],
251
- isInbound: address === obj.to_account_identifier,
252
- amount: (0, module_kit_1.newAmount)(obj.amount, 'blockchain'),
253
- fee: (0, module_kit_1.newAmount)(obj.fee, 'blockchain'),
254
- network: _this.options.network,
255
- timestamp: obj.created_at,
256
- status: {
257
- type: obj.transfer_type,
258
- hash: obj.transaction_hash,
259
- block: obj.block_height
260
- }
261
- };
262
- });
263
- return [2 /*return*/, {
264
- transactions: transactions,
265
- cursor: {
266
- hasNext: next !== undefined,
267
- next: next
268
- }
269
- }];
270
- }
285
+ return __awaiter(this, void 0, void 0, function* () {
286
+ const endpoint = cursor === undefined ? `/accounts/${address}/transactions?limit=${limit}&offset=0` : cursor.next;
287
+ const url = endpoint !== undefined ? `${this.options.network.explorerUrl}${endpoint}` : undefined;
288
+ const response = url !== undefined ? yield index_1.default.get(url) : undefined;
289
+ const nodeTransactions = ((_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.blocks) || [];
290
+ const tokens = endpoint.split('=');
291
+ const offset = parseInt(tokens[tokens.length - 1]);
292
+ tokens[tokens.length - 1] = (offset + limit).toString();
293
+ const next = tokens.join('=');
294
+ const transactions = nodeTransactions.map((obj) => {
295
+ return {
296
+ from: [obj.from_account_identifier],
297
+ to: [obj.to_account_identifier],
298
+ isInbound: address === obj.to_account_identifier,
299
+ amount: (0, module_kit_1.newAmount)(obj.amount, 'blockchain'),
300
+ fee: (0, module_kit_1.newAmount)(obj.fee, 'blockchain'),
301
+ network: this.options.network,
302
+ timestamp: obj.created_at,
303
+ status: {
304
+ type: obj.transfer_type,
305
+ hash: obj.transaction_hash,
306
+ block: obj.block_height
307
+ }
308
+ };
271
309
  });
310
+ return {
311
+ transactions,
312
+ cursor: {
313
+ hasNext: next !== undefined,
314
+ next
315
+ }
316
+ };
272
317
  });
273
- };
274
- ICPProtocolImpl.prototype.getBalanceOfPublicKey = function (publicKey) {
275
- return __awaiter(this, void 0, void 0, function () {
276
- var address;
277
- return __generator(this, function (_a) {
278
- address = (0, ICPImplementation_1.getAddressFromPublicKey)(publicKey.value);
279
- return [2 /*return*/, this.getBalanceOfAddress(address)];
280
- });
318
+ }
319
+ getBalanceOfPublicKey(publicKey) {
320
+ return __awaiter(this, void 0, void 0, function* () {
321
+ const address = (0, ICPImplementation_1.getAddressFromPublicKey)(publicKey.value);
322
+ const mainBalance = yield this.getBalanceOfAddress(address);
323
+ const neuronBalance = yield this.getNeuronBalance(publicKey);
324
+ const totalBalance = (0, module_kit_1.newAmount)(mainBalance.total)
325
+ .blockchain(this.units)
326
+ .toBigNumber()
327
+ .plus((0, module_kit_1.newAmount)(neuronBalance).blockchain(this.units).toBigNumber());
328
+ return {
329
+ total: (0, module_kit_1.newAmount)(totalBalance, 'blockchain'),
330
+ transferable: mainBalance.total
331
+ };
281
332
  });
282
- };
283
- ICPProtocolImpl.prototype.getBalanceOfAddress = function (address) {
284
- return __awaiter(this, void 0, void 0, function () {
285
- var balance;
286
- return __generator(this, function (_a) {
287
- switch (_a.label) {
288
- case 0:
289
- if (!address)
290
- return [2 /*return*/, { total: (0, module_kit_1.newAmount)(0, 'blockchain') }];
291
- return [4 /*yield*/, (0, ICPImplementation_1.getBalanceFromAddress)(address, this.options.network.rpcUrl, this.options.network.ledgerCanisterId)];
292
- case 1:
293
- balance = _a.sent();
294
- return [2 /*return*/, { total: (0, module_kit_1.newAmount)(balance.toString(10), 'blockchain') }];
295
- }
296
- });
333
+ }
334
+ getBalanceOfAddress(address) {
335
+ return __awaiter(this, void 0, void 0, function* () {
336
+ if (!address)
337
+ return { total: (0, module_kit_1.newAmount)(0, 'blockchain') };
338
+ const balance = yield (0, ICPImplementation_1.getBalanceFromAddress)(address, this.options.network.rpcUrl, this.options.network.ledgerCanisterId);
339
+ return { total: (0, module_kit_1.newAmount)(balance.toString(10), 'blockchain') };
297
340
  });
298
- };
299
- ICPProtocolImpl.prototype.getTransactionMaxAmountWithPublicKey = function (publicKey, to, configuration) {
300
- return __awaiter(this, void 0, void 0, function () {
301
- var balance, balanceBn, fee, feeEstimation, amountWithoutFees;
302
- return __generator(this, function (_a) {
303
- switch (_a.label) {
304
- case 0: return [4 /*yield*/, this.getBalanceOfPublicKey(publicKey)];
305
- case 1:
306
- balance = _a.sent();
307
- balanceBn = new bignumber_1.default((0, module_kit_1.newAmount)(balance.total).value);
308
- if (!((configuration === null || configuration === void 0 ? void 0 : configuration.fee) !== undefined)) return [3 /*break*/, 2];
309
- fee = new bignumber_1.default((0, module_kit_1.newAmount)(configuration.fee).value);
310
- return [3 /*break*/, 4];
311
- case 2: return [4 /*yield*/, this.getTransactionFeeWithPublicKey(publicKey, [])];
312
- case 3:
313
- feeEstimation = _a.sent();
314
- fee = new bignumber_1.default((0, module_kit_1.newAmount)(feeEstimation.medium).value);
315
- if (fee.gte(balanceBn)) {
316
- fee = new bignumber_1.default(0);
317
- }
318
- _a.label = 4;
319
- case 4:
320
- amountWithoutFees = balanceBn.minus(fee);
321
- if (amountWithoutFees.isNegative()) {
322
- amountWithoutFees = new bignumber_1.default(0);
323
- }
324
- return [2 /*return*/, (0, module_kit_1.newAmount)(amountWithoutFees.toFixed(), 'blockchain')];
341
+ }
342
+ getTransactionMaxAmountWithPublicKey(publicKey, to, configuration) {
343
+ return __awaiter(this, void 0, void 0, function* () {
344
+ const balance = yield this.getBalanceOfPublicKey(publicKey);
345
+ const balanceBn = new bignumber_1.default((0, module_kit_1.newAmount)(balance.total).value);
346
+ let fee;
347
+ if ((configuration === null || configuration === void 0 ? void 0 : configuration.fee) !== undefined) {
348
+ fee = new bignumber_1.default((0, module_kit_1.newAmount)(configuration.fee).value);
349
+ }
350
+ else {
351
+ const feeEstimation = yield this.getTransactionFeeWithPublicKey(publicKey, []);
352
+ fee = new bignumber_1.default((0, module_kit_1.newAmount)(feeEstimation).value);
353
+ if (fee.gte(balanceBn)) {
354
+ fee = new bignumber_1.default(0);
325
355
  }
326
- });
356
+ }
357
+ let amountWithoutFees = balanceBn.minus(fee);
358
+ if (amountWithoutFees.isNegative()) {
359
+ amountWithoutFees = new bignumber_1.default(0);
360
+ }
361
+ return (0, module_kit_1.newAmount)(amountWithoutFees.toFixed(), 'blockchain');
327
362
  });
328
- };
363
+ }
329
364
  // TODO : Get default from chain
330
- ICPProtocolImpl.prototype.getTransactionFeeWithPublicKey = function (_publicKey, _details, _configuration) {
331
- return __awaiter(this, void 0, void 0, function () {
332
- return __generator(this, function (_a) {
333
- // const ledger = LedgerCanister.create()
334
- // const feeDefault = await ledger.transactionFee()
335
- // return {
336
- // low: newAmount(feeDefault.toString(10), 'ICP'),
337
- // medium: newAmount(feeDefault.toString(10), 'ICP'),
338
- // high: newAmount(feeDefault.toString(10), 'ICP')
339
- // }
340
- return [2 /*return*/, this.feeDefaults];
341
- });
365
+ getTransactionFeeWithPublicKey(_publicKey, _details) {
366
+ return __awaiter(this, void 0, void 0, function* () {
367
+ // const ledger = LedgerCanister.create()
368
+ // const feeDefault = await ledger.transactionFee()
369
+ // return {
370
+ // low: newAmount(feeDefault.toString(10), 'ICP'),
371
+ // medium: newAmount(feeDefault.toString(10), 'ICP'),
372
+ // high: newAmount(feeDefault.toString(10), 'ICP')
373
+ // }
374
+ return this.feeDefaults.medium;
342
375
  });
343
- };
344
- ICPProtocolImpl.prototype.prepareTransactionWithPublicKey = function (publicKey, details, configuration) {
345
- return __awaiter(this, void 0, void 0, function () {
346
- var balance, _a, balanceBn, feeBn, amountBn, transaction, unsignedTransaction;
347
- return __generator(this, function (_b) {
348
- switch (_b.label) {
349
- case 0:
350
- _a = module_kit_1.newAmount;
351
- return [4 /*yield*/, this.getBalanceOfPublicKey(publicKey)];
352
- case 1:
353
- balance = _a.apply(void 0, [(_b.sent()).total]).blockchain(this.units);
354
- balanceBn = BigInt(balance.value);
355
- feeBn = (configuration === null || configuration === void 0 ? void 0 : configuration.fee) !== undefined
356
- ? BigInt((0, module_kit_1.newAmount)(configuration.fee).blockchain(this.units).value)
357
- : BigInt((0, module_kit_1.newAmount)(this.feeDefaults.medium).blockchain(this.units).value);
358
- // Throw if not enough balance for fee
359
- if (balanceBn < feeBn) {
360
- throw new errors_1.BalanceError(coinlib_core_1.Domain.ICP, 'not enough balance');
361
- }
362
- amountBn = BigInt((0, module_kit_1.newAmount)(details[0].amount).blockchain(this.units).value);
363
- transaction = {
364
- from: (0, ICPImplementation_1.getAddressFromPublicKey)(publicKey.value),
365
- to: details[0].to,
366
- amount: amountBn,
367
- fee: feeBn
368
- };
369
- unsignedTransaction = (0, ICPImplementation_1.createUnsignedTransaction)(transaction);
370
- return [2 /*return*/, (0, module_kit_1.newUnsignedTransaction)({
371
- transaction: unsignedTransaction,
372
- networkId: this.networkId()
373
- })];
374
- }
376
+ }
377
+ prepareTransactionWithPublicKey(publicKey, details, configuration) {
378
+ return __awaiter(this, void 0, void 0, function* () {
379
+ // Check balance
380
+ const balance = (0, module_kit_1.newAmount)((yield this.getBalanceOfPublicKey(publicKey)).total).blockchain(this.units);
381
+ const balanceBn = BigInt(balance.value);
382
+ const feeBn = (configuration === null || configuration === void 0 ? void 0 : configuration.fee) !== undefined
383
+ ? BigInt((0, module_kit_1.newAmount)(configuration.fee).blockchain(this.units).value)
384
+ : BigInt((0, module_kit_1.newAmount)(this.feeDefaults.medium).blockchain(this.units).value);
385
+ // Throw if not enough balance for fee
386
+ if (balanceBn < feeBn) {
387
+ throw new errors_1.BalanceError(coinlib_core_1.Domain.ICP, 'not enough balance');
388
+ }
389
+ const amountBn = BigInt((0, module_kit_1.newAmount)(details[0].amount).blockchain(this.units).value);
390
+ // Create unsigned
391
+ const unsignedTransaction = (0, ICPImplementation_1.createUnsignedTransaction)({
392
+ to: details[0].to,
393
+ amount: amountBn,
394
+ fee: feeBn
395
+ });
396
+ return (0, module_kit_1.newUnsignedTransaction)({
397
+ transactions: [
398
+ {
399
+ actionType: transaction_1.ICPActionType.TRANSFER,
400
+ encoded: unsignedTransaction
401
+ }
402
+ ]
375
403
  });
376
404
  });
377
- };
378
- ICPProtocolImpl.prototype.networkId = function () {
379
- switch (this.options.network.type) {
380
- case 'mainnet':
381
- return 'icp_mainnet';
382
- default:
383
- throw new errors_1.ConditionViolationError(coinlib_core_1.Domain.ICP, 'Network type not supported.');
384
- }
385
- };
405
+ }
386
406
  // TODO : discover how to get transaction hash after broadcast
387
407
  // https://github.com/dfinity/ic-js/tree/main/packages/nns
388
408
  // Search for : Transfer ICP from the caller to the destination accountIdentifier. Returns the index of the block containing the tx if it was successful.
389
- ICPProtocolImpl.prototype.broadcastTransaction = function (transaction) {
390
- return __awaiter(this, void 0, void 0, function () {
391
- return __generator(this, function (_a) {
392
- switch (_a.label) {
393
- case 0: return [4 /*yield*/, (0, ICPImplementation_1.broadcastTransaction)(transaction.transaction, this.options.network.rpcUrl, this.options.network.ledgerCanisterId)];
394
- case 1: return [2 /*return*/, _a.sent()];
409
+ broadcastTransaction(transaction) {
410
+ return __awaiter(this, void 0, void 0, function* () {
411
+ for (const { actionType, encoded } of transaction.transactions) {
412
+ const requestType = transaction_1.ICP_REQUEST_TYPE_PER_ACTION[actionType];
413
+ if (requestType !== 'call')
414
+ continue;
415
+ yield (0, ICPImplementation_1.broadcastTransaction)(encoded, this.options.network.rpcUrl, this.canisterId[transaction_1.ICP_CANISTER_TYPE_PER_ACTION[actionType]], transaction_1.ICP_REQUEST_TYPE_PER_ACTION[actionType]);
416
+ }
417
+ return '';
418
+ });
419
+ }
420
+ sendQuery(transaction) {
421
+ return __awaiter(this, void 0, void 0, function* () {
422
+ return Promise.all(transaction.transactions
423
+ .filter(({ actionType }) => transaction_1.ICP_REQUEST_TYPE_PER_ACTION[actionType] === 'query')
424
+ .map(({ actionType, encoded }) => __awaiter(this, void 0, void 0, function* () {
425
+ const response = yield (0, ICPImplementation_1.broadcastTransaction)(encoded, this.options.network.rpcUrl, this.canisterId[transaction_1.ICP_CANISTER_TYPE_PER_ACTION[actionType]], transaction_1.ICP_REQUEST_TYPE_PER_ACTION[actionType]);
426
+ const queryResponse = Cbor.decode(response);
427
+ if (queryResponse.status == "rejected" /* QueryResponseStatus.Rejected */) {
428
+ throw new errors_1.NetworkError(coinlib_core_1.Domain.ICP, {}, `Error (${queryResponse.reject_code}) ${queryResponse.reject_message}`);
395
429
  }
430
+ return this.decodeQueryResponse(actionType, queryResponse.reply.arg);
431
+ })));
432
+ });
433
+ }
434
+ decodeQueryResponse(actionType, response) {
435
+ switch (actionType) {
436
+ case transaction_1.ICPActionType.GET_NEURON_INFO:
437
+ const NeuronId = IDL.Record({ id: IDL.Nat64 });
438
+ const BallotInfo = IDL.Record({
439
+ vote: IDL.Int32,
440
+ proposal_id: IDL.Opt(NeuronId)
441
+ });
442
+ const DissolveState = IDL.Variant({
443
+ DissolveDelaySeconds: IDL.Nat64,
444
+ WhenDissolvedTimestampSeconds: IDL.Nat64
445
+ });
446
+ const Followees = IDL.Record({ followees: IDL.Vec(NeuronId) });
447
+ const NeuronStakeTransfer = IDL.Record({
448
+ to_subaccount: IDL.Vec(IDL.Nat8),
449
+ neuron_stake_e8s: IDL.Nat64,
450
+ from: IDL.Opt(IDL.Principal),
451
+ memo: IDL.Nat64,
452
+ from_subaccount: IDL.Vec(IDL.Nat8),
453
+ transfer_timestamp: IDL.Nat64,
454
+ block_height: IDL.Nat64
455
+ });
456
+ const KnownNeuronData = IDL.Record({
457
+ name: IDL.Text,
458
+ description: IDL.Opt(IDL.Text)
459
+ });
460
+ const Neuron = IDL.Record({
461
+ id: IDL.Opt(NeuronId),
462
+ staked_maturity_e8s_equivalent: IDL.Opt(IDL.Nat64),
463
+ controller: IDL.Opt(IDL.Principal),
464
+ recent_ballots: IDL.Vec(BallotInfo),
465
+ kyc_verified: IDL.Bool,
466
+ not_for_profit: IDL.Bool,
467
+ maturity_e8s_equivalent: IDL.Nat64,
468
+ cached_neuron_stake_e8s: IDL.Nat64,
469
+ created_timestamp_seconds: IDL.Nat64,
470
+ auto_stake_maturity: IDL.Opt(IDL.Bool),
471
+ aging_since_timestamp_seconds: IDL.Nat64,
472
+ hot_keys: IDL.Vec(IDL.Principal),
473
+ account: IDL.Vec(IDL.Nat8),
474
+ joined_community_fund_timestamp_seconds: IDL.Opt(IDL.Nat64),
475
+ dissolve_state: IDL.Opt(DissolveState),
476
+ followees: IDL.Vec(IDL.Tuple(IDL.Int32, Followees)),
477
+ neuron_fees_e8s: IDL.Nat64,
478
+ transfer: IDL.Opt(NeuronStakeTransfer),
479
+ known_neuron_data: IDL.Opt(KnownNeuronData),
480
+ spawn_at_timestamp_seconds: IDL.Opt(IDL.Nat64)
481
+ });
482
+ const GovernanceError = IDL.Record({
483
+ error_message: IDL.Text,
484
+ error_type: IDL.Int32
485
+ });
486
+ const Result = IDL.Variant({ Ok: Neuron, Err: GovernanceError });
487
+ return IDL.decode([Result], response)[0];
488
+ default:
489
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.ICP, `Decode response for action type ${actionType} is not supported`);
490
+ }
491
+ }
492
+ // DELEGATION
493
+ getDefaultDelegatee() {
494
+ var _a, _b, _c;
495
+ return __awaiter(this, void 0, void 0, function* () {
496
+ const knownNeurons = yield (0, ICPImplementation_1.listKnownNeurons)(this.options.network.rpcUrl, this.options.network.governanceCanisterId);
497
+ const id = (_c = (_b = (_a = knownNeurons[0]) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.id;
498
+ return (id === null || id === void 0 ? void 0 : id.toString()) || '';
499
+ });
500
+ }
501
+ getCurrentDelegateesForPublicKey(_publicKey, data) {
502
+ return __awaiter(this, void 0, void 0, function* () {
503
+ // Fetch neurons of address from governance canister (listNeurons)
504
+ // Fetch followees from each neuron (get_full_neuron_by_id_or_subaccount)
505
+ // Each of the functions needs a identity (signed user)
506
+ return (data === null || data === void 0 ? void 0 : data.neuron) ? this.getNeuronFollowees(data.neuron) : [];
507
+ });
508
+ }
509
+ getCurrentDelegateesForAddress(_address, _data) {
510
+ return __awaiter(this, void 0, void 0, function* () {
511
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.ICP, '`getCurrentDelegateesForAddress` is not supported');
512
+ });
513
+ }
514
+ getDelegateeDetails(address, data) {
515
+ var _a, _b, _c, _d;
516
+ return __awaiter(this, void 0, void 0, function* () {
517
+ const partialNeuron = yield (0, ICPImplementation_1.getNeuronInfo)(address, this.options.network.rpcUrl, this.options.network.governanceCanisterId);
518
+ const neuronFolowees = (data === null || data === void 0 ? void 0 : data.neuron) ? this.getNeuronFollowees(data.neuron) : undefined;
519
+ return {
520
+ name: ((_b = (_a = partialNeuron === null || partialNeuron === void 0 ? void 0 : partialNeuron.known_neuron_data) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.name) || '',
521
+ address: address,
522
+ status: neuronFolowees ? (neuronFolowees.includes(address) ? 'followed' : 'not-followed') : 'unknown',
523
+ votingPower: (_d = (_c = partialNeuron === null || partialNeuron === void 0 ? void 0 : partialNeuron.voting_power) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '0'
524
+ };
525
+ });
526
+ }
527
+ isPublicKeyDelegating(publicKey, data) {
528
+ var _a, _b;
529
+ return __awaiter(this, void 0, void 0, function* () {
530
+ const partialNeuron = yield this.getNeuron(publicKey);
531
+ if (partialNeuron === undefined || partialNeuron.stake_e8s <= BigInt(0)) {
532
+ return false;
533
+ }
534
+ const neuron = data === null || data === void 0 ? void 0 : data.neuron;
535
+ // Without full neuron data we can't be sure if we're actually delegating,
536
+ // i.e. the neuron has followees. We assume, however, that if the neuron
537
+ // has a stake, the public key is delegating.
538
+ if (neuron === undefined) {
539
+ return true;
540
+ }
541
+ // We should check if partial and full neuron data describe the same neuron
542
+ // but there's no neuron ID in partial neuron data
543
+ if (((_a = partialNeuron.known_neuron_data[0]) === null || _a === void 0 ? void 0 : _a.name) !== ((_b = neuron.known_neuron_data[0]) === null || _b === void 0 ? void 0 : _b.name)) {
544
+ return true;
545
+ }
546
+ return this.getNeuronFollowees(neuron).length > 0;
547
+ });
548
+ }
549
+ isAddressDelegating(_address, data) {
550
+ return __awaiter(this, void 0, void 0, function* () {
551
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.ICP, '`isAddressDelegating` is not supported');
552
+ });
553
+ }
554
+ getDelegatorDetailsFromPublicKey(publicKey, data) {
555
+ var _a, _b, _c, _d, _e;
556
+ return __awaiter(this, void 0, void 0, function* () {
557
+ const fullNeuron = data === null || data === void 0 ? void 0 : data.neuron;
558
+ const address = yield this.getAddressFromPublicKey(publicKey);
559
+ const totalBalance = yield this.getBalanceOfPublicKey(publicKey);
560
+ const followees = fullNeuron ? this.getNeuronFollowees(fullNeuron) : [];
561
+ const availableActions = yield this.getAvailableDelegatorActions(publicKey, data === null || data === void 0 ? void 0 : data.followee, fullNeuron);
562
+ const neuronBalance = yield this.getNeuronBalance(publicKey);
563
+ const partialNeuron = yield this.getNeuron(publicKey);
564
+ const balance = (0, module_kit_1.newAmount)(totalBalance.total).blockchain(this.units);
565
+ const subaccountBalance = (0, module_kit_1.newAmount)(neuronBalance).blockchain(this.units);
566
+ return {
567
+ address,
568
+ balance: balance.value,
569
+ delegatees: followees,
570
+ availableActions: availableActions,
571
+ subaccountBalance: subaccountBalance.value,
572
+ stake: (_a = partialNeuron === null || partialNeuron === void 0 ? void 0 : partialNeuron.stake_e8s) === null || _a === void 0 ? void 0 : _a.toString(),
573
+ votingPower: (_b = partialNeuron === null || partialNeuron === void 0 ? void 0 : partialNeuron.voting_power) === null || _b === void 0 ? void 0 : _b.toString(),
574
+ age: (_c = partialNeuron === null || partialNeuron === void 0 ? void 0 : partialNeuron.age_seconds) === null || _c === void 0 ? void 0 : _c.toString(),
575
+ dissolveDelay: (_d = partialNeuron === null || partialNeuron === void 0 ? void 0 : partialNeuron.dissolve_delay_seconds) === null || _d === void 0 ? void 0 : _d.toString(),
576
+ maturity: (_e = fullNeuron === null || fullNeuron === void 0 ? void 0 : fullNeuron.maturity_e8s_equivalent) === null || _e === void 0 ? void 0 : _e.toString()
577
+ };
578
+ });
579
+ }
580
+ getDelegatorDetailsFromAddress(_address, data) {
581
+ return __awaiter(this, void 0, void 0, function* () {
582
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.ICP, '`getDelegatorDetailsFromAddress` is not supported');
583
+ });
584
+ }
585
+ getDelegationDetailsFromPublicKey(publicKey, delegatees, data) {
586
+ return __awaiter(this, void 0, void 0, function* () {
587
+ if (delegatees.length > 1) {
588
+ return Promise.reject('Multiple followees for a single delegation are not supported.');
589
+ }
590
+ const followee = delegatees[0];
591
+ const results = yield Promise.all([
592
+ this.getDelegatorDetailsFromPublicKey(publicKey, Object.assign(Object.assign({}, data), { followee })),
593
+ this.getDelegateeDetails(followee, data)
594
+ ]);
595
+ const delegatorDetails = results[0];
596
+ const validatorDetails = results[1];
597
+ return {
598
+ delegator: delegatorDetails,
599
+ delegatees: [validatorDetails]
600
+ };
601
+ });
602
+ }
603
+ getDelegationDetailsFromAddress(_address, _delegatees, _data) {
604
+ return __awaiter(this, void 0, void 0, function* () {
605
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.ICP, '`getDelegationDetailsFromAddress` is not supported');
606
+ });
607
+ }
608
+ getAvailableDelegatorActions(publicKey, followee, fullNeuron) {
609
+ var _a;
610
+ return __awaiter(this, void 0, void 0, function* () {
611
+ const actions = [];
612
+ const results = yield Promise.all([this.getBalanceOfPublicKey(publicKey), this.getNeuronBalance(publicKey), this.getNeuron(publicKey)]);
613
+ const transferableBalance = (_a = results[0].transferable) !== null && _a !== void 0 ? _a : results[0].total;
614
+ const neuronBalance = results[1];
615
+ const partialNeuron = results[2];
616
+ const canStake = new bignumber_1.default(transferableBalance.value).gt(0);
617
+ const isStaking = new bignumber_1.default(neuronBalance.value).gt(0);
618
+ const hasNeuron = partialNeuron !== undefined;
619
+ const isNeuronUpToDate = !isStaking || (hasNeuron && partialNeuron.stake_e8s.toString() === (0, module_kit_1.newAmount)(neuronBalance).blockchain(this.units).value);
620
+ const canFollow = fullNeuron && followee ? !this.getNeuronFollowees(fullNeuron).includes(followee) : false;
621
+ const isDissolving = fullNeuron ? this.isNeuronDissolving(fullNeuron) : false;
622
+ const canDisburse = partialNeuron ? this.canNeuronDisburse(partialNeuron) : false;
623
+ if (canStake && isNeuronUpToDate) {
624
+ actions.push({
625
+ type: governance_1.ICPStakingActionType.STAKE_AND_FOLLOW,
626
+ args: ['followee', 'amount', 'delay']
627
+ });
628
+ }
629
+ if (!canStake && isStaking && canFollow && isNeuronUpToDate) {
630
+ actions.push({
631
+ type: governance_1.ICPStakingActionType.FOLLOW,
632
+ args: ['followee']
633
+ });
634
+ }
635
+ if (isStaking && isNeuronUpToDate) {
636
+ actions.push({
637
+ type: governance_1.ICPStakingActionType.INCREASE_DISSOLVE_DELAY,
638
+ args: ['delay']
639
+ });
640
+ }
641
+ if (!isNeuronUpToDate) {
642
+ actions.push({
643
+ type: governance_1.ICPStakingActionType.REFRESH_NEURON
644
+ });
645
+ }
646
+ if (hasNeuron) {
647
+ actions.push({
648
+ type: governance_1.ICPStakingActionType.GET_STAKING_DETAILS
649
+ });
650
+ }
651
+ if (isStaking && hasNeuron && !isDissolving && fullNeuron !== undefined) {
652
+ actions.push({
653
+ type: governance_1.ICPStakingActionType.START_DISSOLVING
654
+ });
655
+ }
656
+ if (isDissolving) {
657
+ actions.push({
658
+ type: governance_1.ICPStakingActionType.STOP_DISSOLVING
659
+ });
660
+ }
661
+ if (canDisburse) {
662
+ actions.push({
663
+ type: governance_1.ICPStakingActionType.DISBURSE_AND_UNFOLLOW
664
+ });
665
+ }
666
+ return actions;
667
+ });
668
+ }
669
+ prepareDelegatorActionFromPublicKey(publicKey, type, data) {
670
+ return __awaiter(this, void 0, void 0, function* () {
671
+ switch (type) {
672
+ case governance_1.ICPStakingActionType.GET_STAKING_DETAILS:
673
+ return this.prepareGetStakingDetails();
674
+ case governance_1.ICPStakingActionType.STAKE_AND_FOLLOW:
675
+ (0, assert_1.assertFields)(`${type} action`, data, 'followee', 'amount', 'dissolveDelay');
676
+ return this.prepareTransferToNeuronAndManage(publicKey, data.followee, data.amount, data.dissolveDelay);
677
+ case governance_1.ICPStakingActionType.FOLLOW:
678
+ (0, assert_1.assertFields)(`${type} action`, data, 'followee');
679
+ return this.prepareFollowNeuron(publicKey, data.followee);
680
+ case governance_1.ICPStakingActionType.REFRESH_NEURON:
681
+ return this.prepareClaimOrRefreshNeuron(publicKey);
682
+ case governance_1.ICPStakingActionType.INCREASE_DISSOLVE_DELAY:
683
+ (0, assert_1.assertFields)(`${type} action`, data, 'dissolveDelay');
684
+ return this.prepareIncreaseDissolveDelay(publicKey, data.dissolveDelay);
685
+ case governance_1.ICPStakingActionType.START_DISSOLVING:
686
+ return this.prepareStartDissolving(publicKey);
687
+ case governance_1.ICPStakingActionType.STOP_DISSOLVING:
688
+ return this.prepareStopDissolving(publicKey);
689
+ case governance_1.ICPStakingActionType.DISBURSE_AND_UNFOLLOW:
690
+ return this.prepareDisburseAndUnfollow(publicKey);
691
+ default:
692
+ return Promise.reject(`Delegator action type ${type} is not supported.`);
693
+ }
694
+ });
695
+ }
696
+ prepareGetStakingDetails() {
697
+ return __awaiter(this, void 0, void 0, function* () {
698
+ return [
699
+ (0, module_kit_1.newUnsignedTransaction)({
700
+ transactions: yield (0, ICPGovernance_1.prepareGetNeuronInfo)()
701
+ })
702
+ ];
703
+ });
704
+ }
705
+ prepareTransferToNeuronAndManage(publicKey, followee, amount, dissolveDelay) {
706
+ var _a, _b;
707
+ return __awaiter(this, void 0, void 0, function* () {
708
+ const amountBigInt = BigInt(amount);
709
+ const feeBigInt = BigInt((0, module_kit_1.newAmount)(this.feeDefaults.medium).blockchain(this.units).value);
710
+ const partialNeuron = yield this.getNeuron(publicKey);
711
+ const currentDissolveDelay = (_b = (_a = partialNeuron === null || partialNeuron === void 0 ? void 0 : partialNeuron.dissolve_delay_seconds) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '0';
712
+ const differenceInDissolveDelay = new bignumber_1.default(dissolveDelay).minus(currentDissolveDelay);
713
+ return [
714
+ (0, module_kit_1.newUnsignedTransaction)({
715
+ transactions: (0, array_1.flattenArray)(yield Promise.all([
716
+ ...(amountBigInt > BigInt(0)
717
+ ? [
718
+ (0, ICPGovernance_1.prepareTransferToSubaccount)(publicKey.value, this.options.network.governanceCanisterId, amountBigInt, feeBigInt),
719
+ (0, ICPGovernance_1.prepareClaimOrRefreshNeuron)(publicKey.value)
720
+ ]
721
+ : []),
722
+ (0, ICPGovernance_1.prepareFollowNeuron)(publicKey.value, BigInt(followee)),
723
+ differenceInDissolveDelay.gt(0)
724
+ ? (0, ICPGovernance_1.prepareIncreaseDissolveDelay)(publicKey.value, BigInt(differenceInDissolveDelay.toFixed()))
725
+ : Promise.resolve([]),
726
+ (0, ICPGovernance_1.prepareAutoStakeMaturity)(publicKey.value)
727
+ ]))
728
+ })
729
+ ];
730
+ });
731
+ }
732
+ prepareFollowNeuron(publicKey, followee) {
733
+ return __awaiter(this, void 0, void 0, function* () {
734
+ return [
735
+ (0, module_kit_1.newUnsignedTransaction)({
736
+ transactions: yield (0, ICPGovernance_1.prepareFollowNeuron)(publicKey.value, BigInt(followee))
737
+ })
738
+ ];
739
+ });
740
+ }
741
+ prepareClaimOrRefreshNeuron(publicKey) {
742
+ return __awaiter(this, void 0, void 0, function* () {
743
+ return [
744
+ (0, module_kit_1.newUnsignedTransaction)({
745
+ transactions: yield (0, ICPGovernance_1.prepareClaimOrRefreshNeuron)(publicKey.value)
746
+ })
747
+ ];
748
+ });
749
+ }
750
+ prepareIncreaseDissolveDelay(publicKey, dissolveDelay) {
751
+ var _a, _b;
752
+ return __awaiter(this, void 0, void 0, function* () {
753
+ const partialNeuron = yield this.getNeuron(publicKey);
754
+ const currentDissolveDelay = (_b = (_a = partialNeuron === null || partialNeuron === void 0 ? void 0 : partialNeuron.dissolve_delay_seconds) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '0';
755
+ const differenceInDissolveDelay = new bignumber_1.default(dissolveDelay).minus(currentDissolveDelay);
756
+ return [
757
+ (0, module_kit_1.newUnsignedTransaction)({
758
+ transactions: yield (0, ICPGovernance_1.prepareIncreaseDissolveDelay)(publicKey.value, BigInt(differenceInDissolveDelay.toFixed()))
759
+ })
760
+ ];
761
+ });
762
+ }
763
+ prepareStartDissolving(publicKey) {
764
+ return __awaiter(this, void 0, void 0, function* () {
765
+ return [
766
+ (0, module_kit_1.newUnsignedTransaction)({
767
+ transactions: yield (0, ICPGovernance_1.prepareStartDissolving)(publicKey.value)
768
+ })
769
+ ];
770
+ });
771
+ }
772
+ prepareStopDissolving(publicKey) {
773
+ return __awaiter(this, void 0, void 0, function* () {
774
+ return [
775
+ (0, module_kit_1.newUnsignedTransaction)({
776
+ transactions: yield (0, ICPGovernance_1.prepareStopDissolving)(publicKey.value)
777
+ })
778
+ ];
779
+ });
780
+ }
781
+ prepareDisburseAndUnfollow(publicKey) {
782
+ return __awaiter(this, void 0, void 0, function* () {
783
+ return [
784
+ (0, module_kit_1.newUnsignedTransaction)({
785
+ transactions: (0, array_1.flattenArray)(yield Promise.all([(0, ICPGovernance_1.prepareDisburse)(publicKey.value), (0, ICPGovernance_1.prepareFollowNeuron)(publicKey.value, undefined)]))
786
+ })
787
+ ];
788
+ });
789
+ }
790
+ getMaxStakingAmount(publicKey) {
791
+ var _a, _b;
792
+ return __awaiter(this, void 0, void 0, function* () {
793
+ const balance = yield this.getBalanceOfPublicKey(publicKey);
794
+ const { subAccount } = (0, ICPImplementation_1.getFixedSubaccountFromPublicKey)(publicKey.value);
795
+ const accountIdentifier = account_1.AccountIdentifier.fromPrincipal({
796
+ principal: principal_1.Principal.from(this.options.network.ledgerCanisterId),
797
+ subAccount: subAccount
396
798
  });
799
+ const fee = yield this.getTransactionFeeWithPublicKey(publicKey, [
800
+ {
801
+ to: accountIdentifier.toHex(),
802
+ amount: (_a = balance.transferable) !== null && _a !== void 0 ? _a : balance.total
803
+ }
804
+ ]);
805
+ const maxAmount = (0, module_kit_1.newAmount)((_b = balance.transferable) !== null && _b !== void 0 ? _b : balance.total)
806
+ .blockchain(this.units)
807
+ .toBigNumber()
808
+ .minus((0, module_kit_1.newAmount)(fee).blockchain(this.units).value);
809
+ return (0, module_kit_1.newAmount)(maxAmount, 'blockchain');
397
810
  });
398
- };
399
- return ICPProtocolImpl;
400
- }());
811
+ }
812
+ getKnownNeurons() {
813
+ return __awaiter(this, void 0, void 0, function* () {
814
+ return (0, ICPImplementation_1.listKnownNeurons)(this.options.network.rpcUrl, this.options.network.governanceCanisterId);
815
+ });
816
+ }
817
+ getNeuron(publicKey) {
818
+ return __awaiter(this, void 0, void 0, function* () {
819
+ const neuron = yield (0, ICPImplementation_1.getNeuronInfoBySubAccount)(publicKey.value, this.options.network.rpcUrl, this.options.network.governanceCanisterId);
820
+ return neuron;
821
+ });
822
+ }
823
+ getNeuronBalance(publicKey) {
824
+ return __awaiter(this, void 0, void 0, function* () {
825
+ // Create subaccount from publicKey
826
+ const { subAccount, nonce: _ } = (0, ICPImplementation_1.getFixedSubaccountFromPublicKey)(publicKey.value);
827
+ const accountIdentifier = account_1.AccountIdentifier.fromPrincipal({
828
+ principal: principal_1.Principal.from(this.options.network.governanceCanisterId),
829
+ subAccount: subAccount
830
+ });
831
+ return this.getBalanceOfAddress(accountIdentifier.toHex()).then((balance) => balance.total);
832
+ });
833
+ }
834
+ getNeuronFollowees(neuron) {
835
+ const followees = (0, array_1.flattenArray)(neuron.followees.map(([_, { followees }]) => followees.map(({ id }) => id.toString())));
836
+ return Array.from(new Set(followees));
837
+ }
838
+ isNeuronDissolving(neuron) {
839
+ const dissolveState = neuron.dissolve_state[0];
840
+ return (dissolveState !== undefined &&
841
+ 'WhenDissolvedTimestampSeconds' in dissolveState &&
842
+ dissolveState.WhenDissolvedTimestampSeconds > BigInt(0));
843
+ }
844
+ canNeuronDisburse(neuron) {
845
+ return neuron.dissolve_delay_seconds === BigInt(0) && neuron.stake_e8s > BigInt(0);
846
+ }
847
+ }
401
848
  exports.ICPProtocolImpl = ICPProtocolImpl;
402
849
  // Factory
403
- function createICPProtocol(options) {
404
- if (options === void 0) { options = {}; }
850
+ function createICPProtocol(options = {}) {
405
851
  return new ICPProtocolImpl(options);
406
852
  }
407
853
  exports.createICPProtocol = createICPProtocol;
408
854
  exports.ICP_MAINNET_PROTOCOL_NETWORK = {
409
855
  name: 'Mainnet',
410
856
  type: 'mainnet',
411
- rpcUrl: 'https://boundary.ic0.app/',
412
- blockExplorerUrl: 'https://dashboard.internetcomputer.org/',
857
+ rpcUrl: 'https://ic0.app/',
413
858
  ledgerCanisterId: 'ryjl3-tyaaa-aaaaa-aaaba-cai',
414
- blockExplorerApi: 'https://ledger-api.internetcomputer.org'
859
+ governanceCanisterId: 'rrkah-fqaaa-aaaaa-aaaaq-cai',
860
+ explorerUrl: 'https://ledger-api.internetcomputer.org'
415
861
  };
416
- var DEFAULT_ICP_PROTOCOL_NETWORK = exports.ICP_MAINNET_PROTOCOL_NETWORK;
417
- function createICPProtocolOptions(network) {
418
- if (network === void 0) { network = {}; }
862
+ const DEFAULT_ICP_PROTOCOL_NETWORK = exports.ICP_MAINNET_PROTOCOL_NETWORK;
863
+ function createICPProtocolOptions(network = {}) {
419
864
  return {
420
- network: __assign(__assign({}, DEFAULT_ICP_PROTOCOL_NETWORK), network)
865
+ network: Object.assign(Object.assign({}, DEFAULT_ICP_PROTOCOL_NETWORK), network)
421
866
  };
422
867
  }
423
868
  exports.createICPProtocolOptions = createICPProtocolOptions;