@airgap/icp 0.13.15-beta.0 → 0.13.15-beta.10

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 (90) hide show
  1. package/package.json +8 -6
  2. package/v1/block-explorer/ICPBlockExplorer.js +16 -51
  3. package/v1/block-explorer/ICPBlockExplorer.js.map +1 -1
  4. package/v1/index.d.ts +3 -2
  5. package/v1/index.js +9 -5
  6. package/v1/index.js.map +1 -1
  7. package/v1/module/ICPModule.js +53 -94
  8. package/v1/module/ICPModule.js.map +1 -1
  9. package/v1/module.js +1 -1
  10. package/v1/module.js.map +1 -1
  11. package/v1/protocol/ICPGovernance.d.ts +39 -0
  12. package/v1/protocol/ICPGovernance.js +1177 -0
  13. package/v1/protocol/ICPGovernance.js.map +1 -0
  14. package/v1/protocol/ICPImplementation.d.ts +30 -5
  15. package/v1/protocol/ICPImplementation.js +317 -252
  16. package/v1/protocol/ICPImplementation.js.map +1 -1
  17. package/v1/protocol/ICPProtocol.d.ts +58 -6
  18. package/v1/protocol/ICPProtocol.js +764 -318
  19. package/v1/protocol/ICPProtocol.js.map +1 -1
  20. package/v1/protocol/icrc/CkBTCProtocol.js +137 -223
  21. package/v1/protocol/icrc/CkBTCProtocol.js.map +1 -1
  22. package/v1/protocol/icrc/ICRC1Protocol.js +338 -553
  23. package/v1/protocol/icrc/ICRC1Protocol.js.map +1 -1
  24. package/v1/serializer/v3/schemas/converter/transaction-converter.js +48 -5
  25. package/v1/serializer/v3/schemas/converter/transaction-converter.js.map +1 -1
  26. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-icp.d.ts +8 -2
  27. package/v1/serializer/v3/schemas/generated/transaction-sign-request-icp.json +31 -1
  28. package/v1/serializer/v3/serializer-companion.js +85 -144
  29. package/v1/serializer/v3/serializer-companion.js.map +1 -1
  30. package/v1/serializer/v3/validators/transaction-validator.js +22 -60
  31. package/v1/serializer/v3/validators/transaction-validator.js.map +1 -1
  32. package/v1/serializer/v3/validators/validators.js +19 -58
  33. package/v1/serializer/v3/validators/validators.js.map +1 -1
  34. package/v1/types/governance.d.ts +29 -0
  35. package/v1/types/governance.js +279 -210
  36. package/v1/types/governance.js.map +1 -1
  37. package/v1/types/icrc/ledger.js +22 -23
  38. package/v1/types/icrc/ledger.js.map +1 -1
  39. package/v1/types/ledger.d.ts +1 -0
  40. package/v1/types/ledger.js +37 -38
  41. package/v1/types/ledger.js.map +1 -1
  42. package/v1/types/management_idl.js +6 -7
  43. package/v1/types/management_idl.js.map +1 -1
  44. package/v1/types/protocol.d.ts +1 -0
  45. package/v1/types/transaction.d.ts +22 -3
  46. package/v1/types/transaction.js +38 -0
  47. package/v1/types/transaction.js.map +1 -1
  48. package/v1/utils/account.js +42 -70
  49. package/v1/utils/account.js.map +1 -1
  50. package/v1/utils/actor.js +139 -322
  51. package/v1/utils/actor.js.map +1 -1
  52. package/v1/utils/auth.js +44 -134
  53. package/v1/utils/auth.js.map +1 -1
  54. package/v1/utils/bls.js +41 -109
  55. package/v1/utils/bls.js.map +1 -1
  56. package/v1/utils/buffer.js +47 -111
  57. package/v1/utils/buffer.js.map +1 -1
  58. package/v1/utils/cbor.js +50 -85
  59. package/v1/utils/cbor.js.map +1 -1
  60. package/v1/utils/certificate.js +116 -238
  61. package/v1/utils/certificate.js.map +1 -1
  62. package/v1/utils/convert.d.ts +1 -1
  63. package/v1/utils/convert.js +29 -49
  64. package/v1/utils/convert.js.map +1 -1
  65. package/v1/utils/der.js +37 -35
  66. package/v1/utils/der.js.map +1 -1
  67. package/v1/utils/errors.js +10 -30
  68. package/v1/utils/errors.js.map +1 -1
  69. package/v1/utils/hdkey.js +33 -33
  70. package/v1/utils/hdkey.js.map +1 -1
  71. package/v1/utils/http.d.ts +1 -1
  72. package/v1/utils/http.js +202 -426
  73. package/v1/utils/http.js.map +1 -1
  74. package/v1/utils/icrc1.js +24 -41
  75. package/v1/utils/icrc1.js.map +1 -1
  76. package/v1/utils/idl.js +780 -1159
  77. package/v1/utils/idl.js.map +1 -1
  78. package/v1/utils/json.d.ts +1 -0
  79. package/v1/utils/json.js +19 -0
  80. package/v1/utils/json.js.map +1 -0
  81. package/v1/utils/leb128.js +29 -30
  82. package/v1/utils/leb128.js.map +1 -1
  83. package/v1/utils/polling.js +84 -234
  84. package/v1/utils/polling.js.map +1 -1
  85. package/v1/utils/principal.js +78 -126
  86. package/v1/utils/principal.js.map +1 -1
  87. package/v1/utils/secp256k1.js +68 -134
  88. package/v1/utils/secp256k1.js.map +1 -1
  89. package/v1/utils/transaction.js +7 -7
  90. package/v1/utils/transaction.js.map +1 -1
@@ -1,15 +1,4 @@
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);
12
- };
13
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
3
  if (k2 === undefined) k2 = k;
15
4
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -42,94 +31,44 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
42
31
  step((generator = generator.apply(thisArg, _arguments || [])).next());
43
32
  });
44
33
  };
45
- var __generator = (this && this.__generator) || function (thisArg, body) {
46
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
47
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
48
- function verb(n) { return function (v) { return step([n, v]); }; }
49
- function step(op) {
50
- if (f) throw new TypeError("Generator is already executing.");
51
- while (_) try {
52
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
53
- if (y = 0, t) op = [op[0] & 2, t.value];
54
- switch (op[0]) {
55
- case 0: case 1: t = op; break;
56
- case 4: _.label++; return { value: op[1], done: false };
57
- case 5: _.label++; y = op[1]; op = [0]; continue;
58
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
59
- default:
60
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
61
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
62
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
63
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
64
- if (t[2]) _.ops.pop();
65
- _.trys.pop(); continue;
66
- }
67
- op = body.call(thisArg, _);
68
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
69
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
70
- }
71
- };
72
- var __read = (this && this.__read) || function (o, n) {
73
- var m = typeof Symbol === "function" && o[Symbol.iterator];
74
- if (!m) return o;
75
- var i = m.call(o), r, ar = [], e;
76
- try {
77
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
78
- }
79
- catch (error) { e = { error: error }; }
80
- finally {
81
- try {
82
- if (r && !r.done && (m = i["return"])) m.call(i);
83
- }
84
- finally { if (e) throw e.error; }
85
- }
86
- return ar;
87
- };
88
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
89
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
90
- if (ar || !(i in from)) {
91
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
92
- ar[i] = from[i];
93
- }
94
- }
95
- return to.concat(ar || Array.prototype.slice.call(from));
96
- };
97
34
  var __importDefault = (this && this.__importDefault) || function (mod) {
98
35
  return (mod && mod.__esModule) ? mod : { "default": mod };
99
36
  };
100
37
  Object.defineProperty(exports, "__esModule", { value: true });
101
- exports.broadcastTransaction = exports.getBalanceFromAddress = exports.decodeArguments = exports.getInfoFromSignedTransaction = exports.signTransaction = exports.signICPTransaction = exports.getInfoFromUnsignedTransaction = exports.createUnsignedTransaction = exports.getAddressFromPrincipal = exports.getAddressFromPublicKey = exports.getPrincipalFromPublicKey = exports.getKeyPairFromExtendedSecretKey = exports.createHttpAgent = void 0;
102
- var index_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/axios-0.19.0/index"));
103
- var hex_1 = require("@airgap/coinlib-core/utils/hex");
38
+ exports.getNeuronInfoBySubAccount = exports.getNeuronInfo = exports.listKnownNeurons = exports.signListNeurons = exports.createManageNeuronUnsignedTransaction = exports.createClaimOrRefreshNeuronFromAccountUnsignedTransaction = exports.createStakeUnsignedTransactions = exports.getFixedSubaccountFromPublicKey = exports.getFixedSubaccountFromPrivateKey = exports.broadcastTransaction = exports.getBalanceFromAddress = exports.decodeArguments = exports.getDetailsFromSignedTransactionTransfer = exports.signTransaction = exports.signTransactionTransfer = exports.getDetailsFromUnsignedTransactionTransfer = exports.getInfoFromUnsignedTransaction = exports.createUnsignedTransaction = exports.getAddressFromPrincipal = exports.getAddressFromPublicKey = exports.getPrincipalFromPublicKey = exports.getKeyPairFromExtendedSecretKey = exports.createHttpAgent = void 0;
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 hex_1 = require("@airgap/coinlib-core/utils/hex");
42
+ const module_kit_1 = require("@airgap/module-kit");
104
43
  require("isomorphic-fetch");
105
- var js_sha256_1 = require("js-sha256");
106
- var ledger_1 = require("../types/ledger");
107
- var account_1 = require("../utils/account");
108
- // import { requestIdOf } from '../utils/auth'
109
- var actor_1 = require("../utils/actor");
110
- var auth_1 = require("../utils/auth");
111
- var Cbor = __importStar(require("../utils/cbor"));
112
- var convert_1 = require("../utils/convert");
113
- var hdkey_1 = __importDefault(require("../utils/hdkey"));
114
- var http_1 = require("../utils/http");
115
- var IDL = __importStar(require("../utils/idl"));
116
- var principal_1 = require("../utils/principal");
117
- var secp256k1_1 = __importDefault(require("../utils/secp256k1"));
44
+ const js_sha256_1 = require("js-sha256");
45
+ const governance_1 = require("../types/governance");
46
+ const ledger_1 = require("../types/ledger");
47
+ const account_1 = require("../utils/account");
48
+ const actor_1 = require("../utils/actor");
49
+ const auth_1 = require("../utils/auth");
50
+ const Cbor = __importStar(require("../utils/cbor"));
51
+ const convert_1 = require("../utils/convert");
52
+ const hdkey_1 = __importDefault(require("../utils/hdkey"));
53
+ const http_1 = require("../utils/http");
54
+ const IDL = __importStar(require("../utils/idl"));
55
+ const json_1 = require("../utils/json");
56
+ const principal_1 = require("../utils/principal");
57
+ const secp256k1_1 = __importDefault(require("../utils/secp256k1"));
118
58
  // Agent
119
- function createHttpAgent(rpcUrl, identity) {
120
- if (identity === void 0) { identity = new auth_1.AnonymousIdentity(); }
59
+ function createHttpAgent(rpcUrl, identity = new auth_1.AnonymousIdentity()) {
121
60
  return new http_1.HttpAgent({
122
- identity: identity,
61
+ identity,
123
62
  host: rpcUrl
124
63
  });
125
64
  }
126
65
  exports.createHttpAgent = createHttpAgent;
127
66
  // MNEMONIC -> KEY PAIR
128
67
  function getKeyPairFromExtendedSecretKey(extendedSecretKey) {
129
- var hdKey = hdkey_1.default.fromExtendedKey(extendedSecretKey);
130
- var identity = secp256k1_1.default.fromSecretKey(hdKey.privateKey);
131
- var publicKey = new Uint8Array(identity.getPublicKey().toDer());
132
- var privateKey = new Uint8Array(identity.getKeyPair().secretKey);
68
+ const hdKey = hdkey_1.default.fromExtendedKey(extendedSecretKey);
69
+ const identity = secp256k1_1.default.fromSecretKey(hdKey.privateKey);
70
+ const publicKey = new Uint8Array(identity.getPublicKey().toDer());
71
+ const privateKey = new Uint8Array(identity.getKeyPair().secretKey);
133
72
  return {
134
73
  publicKey: (0, convert_1.uint8ArrayToHexString)(publicKey),
135
74
  privateKey: (0, convert_1.uint8ArrayToHexString)(privateKey)
@@ -143,234 +82,360 @@ function getPrincipalFromPublicKey(publicKey) {
143
82
  exports.getPrincipalFromPublicKey = getPrincipalFromPublicKey;
144
83
  function getAddressFromPublicKey(publicKey, subAccount) {
145
84
  // Get principal from public key
146
- var principal = getPrincipalFromPublicKey(publicKey);
85
+ const principal = getPrincipalFromPublicKey(publicKey);
147
86
  return getAddressFromPrincipal(principal, subAccount);
148
87
  }
149
88
  exports.getAddressFromPublicKey = getAddressFromPublicKey;
150
89
  function getAddressFromPrincipal(principalOrText, subAccountOrUndefined) {
151
- var principal = typeof principalOrText === 'string'
90
+ const principal = typeof principalOrText === 'string'
152
91
  ? (0, hex_1.isHex)(principalOrText)
153
92
  ? principal_1.Principal.fromHex(principalOrText)
154
93
  : principal_1.Principal.from(principalOrText)
155
94
  : principalOrText;
156
- var subAccount = typeof subAccountOrUndefined === 'string'
95
+ const subAccount = typeof subAccountOrUndefined === 'string'
157
96
  ? Buffer.from(subAccountOrUndefined, 'hex')
158
97
  : typeof subAccountOrUndefined === 'undefined' || subAccountOrUndefined.length === 0
159
98
  ? Buffer.alloc(32, 0)
160
99
  : subAccountOrUndefined;
161
100
  // Hash (sha224) the principal, the subAccount and some padding
162
- var padding = (0, convert_1.asciiStringToByteArray)('\x0Aaccount-id');
163
- var shaObj = js_sha256_1.sha224.create();
164
- shaObj.update(__spreadArray(__spreadArray(__spreadArray([], __read(padding), false), __read(principal.toUint8Array()), false), __read(subAccount), false));
165
- var hash = new Uint8Array(shaObj.array());
101
+ const padding = (0, convert_1.asciiStringToByteArray)('\x0Aaccount-id');
102
+ const shaObj = js_sha256_1.sha224.create();
103
+ shaObj.update([...padding, ...principal.toUint8Array(), ...subAccount]);
104
+ const hash = new Uint8Array(shaObj.array());
166
105
  // Prepend the checksum of the hash and convert to a hex string
167
- var checksum = (0, convert_1.calculateCrc32)(hash);
168
- var bytes = new Uint8Array(__spreadArray(__spreadArray([], __read(checksum), false), __read(hash), false));
106
+ const checksum = (0, convert_1.calculateCrc32)(hash);
107
+ const bytes = new Uint8Array([...checksum, ...hash]);
169
108
  return (0, convert_1.uint8ArrayToHexString)(bytes);
170
109
  }
171
110
  exports.getAddressFromPrincipal = getAddressFromPrincipal;
172
111
  // TRANSACTION OBJECT -> UNSIGNED TRANSACTION HEX
173
112
  function createUnsignedTransaction(transaction) {
174
- var to = account_1.AccountIdentifier.fromHex(transaction.to);
113
+ const to = account_1.AccountIdentifier.fromHex(transaction.to);
175
114
  // Create raw request body
176
- var rawRequestBody = {
115
+ const rawRequestBody = {
177
116
  to: to.toNumbers(),
178
117
  fee: (0, convert_1.e8sToTokens)(transaction.fee),
179
118
  amount: (0, convert_1.e8sToTokens)(transaction.amount),
180
119
  // Always explicitly set the memo for compatibility with ledger wallet - hardware wallet
181
- memo: BigInt(0),
120
+ memo: transaction.memo || BigInt(0),
182
121
  created_at_time: [],
183
- from_subaccount: []
122
+ from_subaccount: transaction.fromSubAccount ? [transaction.fromSubAccount.toUint8Array()] : []
184
123
  };
185
124
  // Encode raw request
186
125
  //@ts-ignore
187
- var unsignedTransaction = IDL.encode(ledger_1.TransferFn.argTypes, [rawRequestBody]);
126
+ const unsignedTransaction = IDL.encode(ledger_1.TransferFn.argTypes, [rawRequestBody]);
188
127
  return (0, convert_1.arrayBufferToHexString)(unsignedTransaction);
189
128
  }
190
129
  exports.createUnsignedTransaction = createUnsignedTransaction;
191
130
  // UNSIGNED TRANSACTION -> TRANSACTION DETAILS
192
131
  function getInfoFromUnsignedTransaction(unsignedTransaction) {
193
132
  //@ts-ignore
194
- var transaction = IDL.decode(ledger_1.TransferFn.argTypes, Buffer.from(unsignedTransaction, 'hex'))[0];
133
+ const transaction = IDL.decode(ledger_1.TransferFn.argTypes, Buffer.from(unsignedTransaction, 'hex'))[0];
195
134
  return {
196
135
  to: (0, convert_1.uint8ArrayToHexString)(transaction.to),
197
136
  fee: transaction.fee.e8s,
198
137
  memo: transaction.memo,
199
138
  from_subaccount: transaction.from_subaccount,
200
139
  created_at_time: transaction.created_at_time,
201
- amount: transaction.amount.e8s
140
+ amount: transaction.amount.e8s,
141
+ json: transaction
202
142
  };
203
143
  }
204
144
  exports.getInfoFromUnsignedTransaction = getInfoFromUnsignedTransaction;
145
+ function getDetailsFromUnsignedTransactionTransfer(unsignedTransaction, publicKey, network) {
146
+ const transactionDetails = getInfoFromUnsignedTransaction(unsignedTransaction);
147
+ return [
148
+ {
149
+ from: [getAddressFromPublicKey(publicKey)],
150
+ to: [transactionDetails.to],
151
+ isInbound: false,
152
+ amount: (0, module_kit_1.newAmount)(transactionDetails.amount.toString(), 'blockchain'),
153
+ fee: (0, module_kit_1.newAmount)(transactionDetails.fee.toString(), 'blockchain'),
154
+ network,
155
+ json: (0, json_1.idlDecodedToJsonStringifiable)(transactionDetails.json)
156
+ }
157
+ ];
158
+ }
159
+ exports.getDetailsFromUnsignedTransactionTransfer = getDetailsFromUnsignedTransactionTransfer;
205
160
  // UNSIGNED TRANSACTION, PRIVATE KEY -> SIGNED TRANSACTION
206
- function signICPTransaction(unsignedTransaction, privateKey, canisterId) {
207
- return __awaiter(this, void 0, void 0, function () {
208
- var transactionDetails, Address, ICP, Memo, SubAccount, TimeStamp, TransferArgs, DEFAULT_TRANSACTION_FEE, toTransferRawRequest, rawRequestBody, args;
209
- return __generator(this, function (_a) {
210
- transactionDetails = getInfoFromUnsignedTransaction(unsignedTransaction);
211
- Address = IDL.Vec(IDL.Nat8);
212
- ICP = IDL.Record({ e8s: IDL.Nat64 });
213
- Memo = IDL.Nat64;
214
- SubAccount = IDL.Vec(IDL.Nat8);
215
- TimeStamp = IDL.Record({ timestamp_nanos: IDL.Nat64 });
216
- TransferArgs = IDL.Record({
217
- to: Address,
218
- fee: ICP,
219
- memo: Memo,
220
- from_subaccount: IDL.Opt(SubAccount),
221
- created_at_time: IDL.Opt(TimeStamp),
222
- amount: ICP
223
- });
224
- DEFAULT_TRANSACTION_FEE = BigInt(10000);
225
- toTransferRawRequest = function (_a) {
226
- var to = _a.to, amount = _a.amount, memo = _a.memo, fee = _a.fee, fromSubAccount = _a.fromSubAccount;
227
- return {
228
- to: to.toNumbers(),
229
- fee: (0, convert_1.e8sToTokens)(fee !== null && fee !== void 0 ? fee : DEFAULT_TRANSACTION_FEE),
230
- amount: (0, convert_1.e8sToTokens)(amount),
231
- // Always explicitly set the memo for compatibility with ledger wallet - hardware wallet
232
- memo: memo !== null && memo !== void 0 ? memo : BigInt(0),
233
- created_at_time: [],
234
- from_subaccount: fromSubAccount === undefined ? [] : [fromSubAccount]
235
- };
236
- };
237
- rawRequestBody = toTransferRawRequest(__assign(__assign({}, transactionDetails), { to: account_1.AccountIdentifier.fromHex(transactionDetails.to) }));
238
- args = IDL.encode([TransferArgs], [rawRequestBody]);
239
- return [2 /*return*/, signTransaction(privateKey, canisterId, args, 'transfer')];
161
+ function signTransactionTransfer(unsignedTransaction, privateKey, canisterId) {
162
+ return __awaiter(this, void 0, void 0, function* () {
163
+ // TODO : REFACTOR
164
+ const transactionDetails = getInfoFromUnsignedTransaction(unsignedTransaction);
165
+ const Address = IDL.Vec(IDL.Nat8);
166
+ const ICP = IDL.Record({ e8s: IDL.Nat64 });
167
+ const Memo = IDL.Nat64;
168
+ const SubAccount = IDL.Vec(IDL.Nat8);
169
+ const TimeStamp = IDL.Record({ timestamp_nanos: IDL.Nat64 });
170
+ const TransferArgs = IDL.Record({
171
+ to: Address,
172
+ fee: ICP,
173
+ memo: Memo,
174
+ from_subaccount: IDL.Opt(SubAccount),
175
+ created_at_time: IDL.Opt(TimeStamp),
176
+ amount: ICP
240
177
  });
178
+ const DEFAULT_TRANSACTION_FEE = BigInt(10000);
179
+ const toTransferRawRequest = ({ to, amount, memo, fee, fromSubAccount }) => {
180
+ return {
181
+ to: to.toNumbers(),
182
+ fee: (0, convert_1.e8sToTokens)(fee !== null && fee !== void 0 ? fee : DEFAULT_TRANSACTION_FEE),
183
+ amount: (0, convert_1.e8sToTokens)(amount),
184
+ // Always explicitly set the memo for compatibility with ledger wallet - hardware wallet
185
+ memo: memo !== null && memo !== void 0 ? memo : BigInt(0),
186
+ created_at_time: [],
187
+ from_subaccount: fromSubAccount === undefined ? [] : [fromSubAccount]
188
+ };
189
+ };
190
+ const rawRequestBody = toTransferRawRequest(Object.assign(Object.assign({}, transactionDetails), { to: account_1.AccountIdentifier.fromHex(transactionDetails.to) }));
191
+ const args = IDL.encode([TransferArgs], [rawRequestBody]);
192
+ return signTransaction(privateKey, canisterId, args, 'transfer', 'call');
241
193
  });
242
194
  }
243
- exports.signICPTransaction = signICPTransaction;
244
- function signTransaction(privateKey, canisterId, arg, methodName) {
245
- return __awaiter(this, void 0, void 0, function () {
246
- var identity, submit, transform, request, transformedRequest, encoded;
247
- var _this = this;
248
- return __generator(this, function (_a) {
249
- switch (_a.label) {
250
- case 0:
251
- identity = secp256k1_1.default.fromSecretKey((0, convert_1.hexStringToArrayBuffer)(privateKey));
252
- submit = {
253
- request_type: http_1.SubmitRequestType.Call,
254
- canister_id: principal_1.Principal.from(canisterId),
255
- method_name: methodName,
256
- arg: arg,
257
- sender: identity.getPrincipal(),
258
- ingress_expiry: new http_1.Expiry(5 * 60 * 1000)
259
- };
260
- transform = function (request) { return __awaiter(_this, void 0, void 0, function () {
261
- var p;
262
- return __generator(this, function (_a) {
263
- p = Promise.resolve(request);
264
- return [2 /*return*/, p];
265
- });
266
- }); };
267
- return [4 /*yield*/, transform({
268
- request: {
269
- body: null,
270
- method: 'POST',
271
- headers: {
272
- 'Content-Type': 'application/cbor'
273
- }
274
- },
275
- endpoint: "call" /* Endpoint.Call */,
276
- body: submit
277
- })];
278
- case 1:
279
- request = (_a.sent());
280
- return [4 /*yield*/, identity.transformRequest(request)];
281
- case 2:
282
- transformedRequest = (_a.sent());
283
- encoded = Cbor.encode(transformedRequest.body);
284
- return [2 /*return*/, (0, convert_1.arrayBufferToHexString)(encoded)];
285
- }
195
+ exports.signTransactionTransfer = signTransactionTransfer;
196
+ function signTransaction(privateKey, canisterId, arg, methodName, callType) {
197
+ return __awaiter(this, void 0, void 0, function* () {
198
+ const identity = secp256k1_1.default.fromSecretKey((0, convert_1.hexStringToArrayBuffer)(privateKey));
199
+ let submit;
200
+ if (callType === 'query') {
201
+ submit = {
202
+ request_type: "query" /* ReadRequestType.Query */,
203
+ canister_id: principal_1.Principal.from(canisterId),
204
+ method_name: methodName,
205
+ arg,
206
+ sender: identity.getPrincipal(),
207
+ ingress_expiry: new http_1.Expiry(5 * 60 * 1000)
208
+ };
209
+ }
210
+ else {
211
+ submit = {
212
+ request_type: http_1.SubmitRequestType.Call,
213
+ canister_id: principal_1.Principal.from(canisterId),
214
+ method_name: methodName,
215
+ arg,
216
+ sender: identity.getPrincipal(),
217
+ ingress_expiry: new http_1.Expiry(5 * 60 * 1000)
218
+ };
219
+ }
220
+ const transform = (request) => __awaiter(this, void 0, void 0, function* () {
221
+ let p = Promise.resolve(request);
222
+ return p;
286
223
  });
224
+ let request;
225
+ if (callType === 'query') {
226
+ request = (yield transform({
227
+ request: {
228
+ body: null,
229
+ method: 'POST',
230
+ headers: {
231
+ 'Content-Type': 'application/cbor'
232
+ }
233
+ },
234
+ endpoint: "read" /* Endpoint.Query */,
235
+ body: submit
236
+ }));
237
+ }
238
+ else {
239
+ request = (yield transform({
240
+ request: {
241
+ body: null,
242
+ method: 'POST',
243
+ headers: {
244
+ 'Content-Type': 'application/cbor'
245
+ }
246
+ },
247
+ endpoint: "call" /* Endpoint.Call */,
248
+ body: submit
249
+ }));
250
+ }
251
+ // Apply transform for identity.
252
+ const transformedRequest = (yield identity.transformRequest(request));
253
+ const encoded = Cbor.encode(transformedRequest.body);
254
+ return (0, convert_1.arrayBufferToHexString)(encoded);
287
255
  });
288
256
  }
289
257
  exports.signTransaction = signTransaction;
290
258
  // SIGNED TRANSACTION -> TRANSACTION DETAILS
291
- function getInfoFromSignedTransaction(signedTransaction) {
292
- return Cbor.decode((0, convert_1.hexStringToArrayBuffer)(signedTransaction));
259
+ function getDetailsFromSignedTransactionTransfer(signedTransaction, publicKey, network) {
260
+ const transactionInfo = Cbor.decode((0, convert_1.hexStringToArrayBuffer)(signedTransaction));
261
+ const args = decodeArguments(ledger_1.TransferArgs, transactionInfo.content.arg);
262
+ return [
263
+ {
264
+ from: [getAddressFromPublicKey(publicKey)],
265
+ to: [(0, convert_1.uint8ArrayToHexString)(args.to)],
266
+ isInbound: false,
267
+ amount: (0, module_kit_1.newAmount)(args.amount.e8s.toString(), 'blockchain'),
268
+ fee: (0, module_kit_1.newAmount)(args.fee.e8s.toString(), 'blockchain'),
269
+ network,
270
+ json: (0, json_1.idlDecodedToJsonStringifiable)(args)
271
+ }
272
+ ];
293
273
  }
294
- exports.getInfoFromSignedTransaction = getInfoFromSignedTransaction;
295
- function decodeArguments(args) {
296
- var Address = IDL.Vec(IDL.Nat8);
297
- var ICP = IDL.Record({ e8s: IDL.Nat64 });
298
- var Memo = IDL.Nat64;
299
- var SubAccount = IDL.Vec(IDL.Nat8);
300
- var TimeStamp = IDL.Record({ timestamp_nanos: IDL.Nat64 });
301
- var TransferArgs = IDL.Record({
302
- to: Address,
303
- fee: ICP,
304
- memo: Memo,
305
- from_subaccount: IDL.Opt(SubAccount),
306
- created_at_time: IDL.Opt(TimeStamp),
307
- amount: ICP
308
- });
309
- return IDL.decode([TransferArgs], args);
274
+ exports.getDetailsFromSignedTransactionTransfer = getDetailsFromSignedTransactionTransfer;
275
+ function decodeArguments(idlInterface, args) {
276
+ return IDL.decode([idlInterface], args)[0];
310
277
  }
311
278
  exports.decodeArguments = decodeArguments;
312
279
  // ADDRESS -> BALANCE
313
280
  function getBalanceFromAddress(address, host, canisterId) {
314
- return __awaiter(this, void 0, void 0, function () {
315
- var agent, actor, acc, b;
316
- return __generator(this, function (_a) {
317
- switch (_a.label) {
318
- case 0:
319
- agent = createHttpAgent(host, secp256k1_1.default.generate());
320
- actor = actor_1.Actor.createActor(ledger_1.idlFactory, {
321
- agent: agent,
322
- canisterId: canisterId
323
- });
324
- acc = Uint8Array.from(Buffer.from(address, 'hex'));
325
- return [4 /*yield*/, actor.account_balance({
326
- account: __spreadArray([], __read(acc), false)
327
- })];
328
- case 1:
329
- b = (_a.sent());
330
- return [2 /*return*/, b.e8s];
331
- }
281
+ return __awaiter(this, void 0, void 0, function* () {
282
+ const agent = createHttpAgent(host, secp256k1_1.default.generate());
283
+ const actor = actor_1.Actor.createActor(ledger_1.idlFactory, {
284
+ agent,
285
+ canisterId
332
286
  });
287
+ let acc = Uint8Array.from(Buffer.from(address, 'hex'));
288
+ const b = (yield actor.account_balance({
289
+ account: [...acc]
290
+ }));
291
+ return b.e8s;
333
292
  });
334
293
  }
335
294
  exports.getBalanceFromAddress = getBalanceFromAddress;
336
- function broadcastTransaction(signedTransaction, host, canisterId) {
337
- return __awaiter(this, void 0, void 0, function () {
338
- var canister, body, error_1;
339
- return __generator(this, function (_a) {
340
- switch (_a.label) {
341
- case 0:
342
- canister = principal_1.Principal.from(canisterId);
343
- body = (0, convert_1.hexStringToArrayBuffer)(signedTransaction);
344
- _a.label = 1;
345
- case 1:
346
- _a.trys.push([1, 3, , 4]);
347
- /*const request = */ return [4 /*yield*/, index_1.default.post('' + new URL("/api/v2/canister/".concat(canister.toText(), "/call"), host), body, {
348
- headers: {
349
- 'Content-Type': 'application/cbor'
350
- }
351
- })
352
- // const submit: CallRequest = {
353
- // ...signedTransactionInfo.content,
354
- // ingress_expiry: new Expiry(1000)
355
- // }
356
- // await Promise.all([request, requestIdOf(submit)])
357
- ];
358
- case 2:
359
- /*const request = */ _a.sent();
360
- // const submit: CallRequest = {
361
- // ...signedTransactionInfo.content,
362
- // ingress_expiry: new Expiry(1000)
363
- // }
364
- // await Promise.all([request, requestIdOf(submit)])
365
- return [2 /*return*/, ''];
366
- case 3:
367
- error_1 = _a.sent();
368
- console.error('Error: ', error_1);
369
- return [2 /*return*/, ''];
370
- case 4: return [2 /*return*/];
371
- }
372
- });
295
+ function broadcastTransaction(signedTransaction, host, canisterId, requestType) {
296
+ return __awaiter(this, void 0, void 0, function* () {
297
+ const canister = principal_1.Principal.from(canisterId);
298
+ const body = (0, convert_1.hexStringToArrayBuffer)(signedTransaction);
299
+ try {
300
+ const response = yield index_1.default.post('' + new URL(`/api/v2/canister/${canister.toText()}/${requestType}`, host), body, {
301
+ responseType: 'arraybuffer',
302
+ headers: {
303
+ 'Content-Type': 'application/cbor'
304
+ }
305
+ });
306
+ return response.data;
307
+ }
308
+ catch (error) {
309
+ console.error(error);
310
+ throw new coinlib_core_1.NetworkError(coinlib_core_1.Domain.ICP, error);
311
+ }
373
312
  });
374
313
  }
375
314
  exports.broadcastTransaction = broadcastTransaction;
315
+ // STAKING
316
+ function getFixedSubaccountFromPrivateKey(privateKey) {
317
+ const identity = secp256k1_1.default.fromSecretKey(Buffer.from(privateKey, 'hex'));
318
+ const publicKey = Buffer.from(identity.getPublicKey().toDer());
319
+ return getFixedSubaccountFromPublicKey(publicKey.toString('hex'));
320
+ }
321
+ exports.getFixedSubaccountFromPrivateKey = getFixedSubaccountFromPrivateKey;
322
+ function getFixedSubaccountFromPublicKey(publicKey) {
323
+ // Create subaccount from publicKey
324
+ const principal = getPrincipalFromPublicKey(publicKey);
325
+ const padding = (0, convert_1.asciiStringToByteArray)('neuron-stake');
326
+ const shaObj = js_sha256_1.sha256.create();
327
+ // Should be random?
328
+ //const nonceBytes = new Uint8Array(randomBytes(8))
329
+ // TODO: const arr = hexStringToUint8Array(publicKey)
330
+ const arr = principal.toUint8Array();
331
+ const nonceBytes = new Uint8Array(arr.buffer, arr.byteLength - 8);
332
+ const nonce = (0, convert_1.uint8ArrayToBigInt)(nonceBytes);
333
+ shaObj.update([0x0c, ...padding, ...principal.toUint8Array(), ...nonceBytes]);
334
+ const toSubAccount = account_1.SubAccount.fromBytes(new Uint8Array(shaObj.array()));
335
+ return {
336
+ subAccount: toSubAccount,
337
+ nonce
338
+ };
339
+ }
340
+ exports.getFixedSubaccountFromPublicKey = getFixedSubaccountFromPublicKey;
341
+ function createStakeUnsignedTransactions(amount, fee, publicKey, canisterId) {
342
+ const { subAccount, nonce } = getFixedSubaccountFromPublicKey(publicKey);
343
+ const accountIdentifier = account_1.AccountIdentifier.fromPrincipal({
344
+ principal: principal_1.Principal.from(canisterId),
345
+ subAccount: subAccount
346
+ });
347
+ // Send amount to the ledger.
348
+ const unsignedTransfer = createUnsignedTransaction({
349
+ memo: nonce,
350
+ amount: amount,
351
+ to: accountIdentifier.toHex(),
352
+ fee: fee
353
+ });
354
+ // Notify the governance of the transaction so that the neuron is created.
355
+ // const unsignedClaim = createClaimOrRefreshNeuronFromAccountUnsignedTransaction(principal, nonce)
356
+ return [unsignedTransfer];
357
+ }
358
+ exports.createStakeUnsignedTransactions = createStakeUnsignedTransactions;
359
+ function createClaimOrRefreshNeuronFromAccountUnsignedTransaction(principal, memo) {
360
+ const ClaimOrRefreshNeuronFromAccount = IDL.Record({
361
+ controller: IDL.Opt(IDL.Principal),
362
+ memo: IDL.Nat64
363
+ });
364
+ const unsignedTransaction = IDL.encode([ClaimOrRefreshNeuronFromAccount], [{ controller: [principal], memo: memo }]);
365
+ return (0, convert_1.arrayBufferToHexString)(unsignedTransaction);
366
+ }
367
+ exports.createClaimOrRefreshNeuronFromAccountUnsignedTransaction = createClaimOrRefreshNeuronFromAccountUnsignedTransaction;
368
+ function createManageNeuronUnsignedTransaction(principal, memo) {
369
+ const NeuronId = IDL.Record({ id: IDL.Nat64 });
370
+ const NeuronIdOrSubaccount = IDL.Variant({
371
+ Subaccount: IDL.Vec(IDL.Nat8),
372
+ NeuronId: NeuronId
373
+ });
374
+ const Follow = IDL.Record({
375
+ topic: IDL.Int32,
376
+ followees: IDL.Vec(NeuronId)
377
+ });
378
+ const Command = IDL.Variant({
379
+ Follow: Follow
380
+ });
381
+ const ManageNeuron = IDL.Record({
382
+ id: IDL.Opt(NeuronId),
383
+ command: IDL.Opt(Command),
384
+ neuron_id_or_subaccount: IDL.Opt(NeuronIdOrSubaccount)
385
+ });
386
+ const unsignedTransaction = IDL.encode([ManageNeuron], [{ controller: [principal], memo: memo }]);
387
+ return (0, convert_1.arrayBufferToHexString)(unsignedTransaction);
388
+ }
389
+ exports.createManageNeuronUnsignedTransaction = createManageNeuronUnsignedTransaction;
390
+ function signListNeurons(privateKey, canisterId) {
391
+ return __awaiter(this, void 0, void 0, function* () {
392
+ const ListNeurons = IDL.Record({
393
+ neuron_ids: IDL.Vec(IDL.Nat64),
394
+ include_neurons_readable_by_caller: IDL.Bool
395
+ });
396
+ const args = IDL.encode([ListNeurons], [{ neuron_ids: [], include_neurons_readable_by_caller: true }]);
397
+ const signedTransaction = signTransaction(privateKey, canisterId, args, 'list_neurons', 'query');
398
+ return signedTransaction;
399
+ });
400
+ }
401
+ exports.signListNeurons = signListNeurons;
402
+ function listKnownNeurons(host, canisterId) {
403
+ return __awaiter(this, void 0, void 0, function* () {
404
+ const agent = createHttpAgent(host, secp256k1_1.default.generate());
405
+ const actor = actor_1.Actor.createActor(governance_1.idlFactory, {
406
+ agent,
407
+ canisterId
408
+ });
409
+ const result = (yield actor.list_known_neurons());
410
+ return result.known_neurons;
411
+ });
412
+ }
413
+ exports.listKnownNeurons = listKnownNeurons;
414
+ function getNeuronInfo(neuronId, host, canisterId) {
415
+ return __awaiter(this, void 0, void 0, function* () {
416
+ const agent = createHttpAgent(host, secp256k1_1.default.generate());
417
+ const actor = actor_1.Actor.createActor(governance_1.idlFactory, {
418
+ agent,
419
+ canisterId
420
+ });
421
+ const result = (yield actor.get_neuron_info(BigInt(neuronId)));
422
+ return result.Ok ? result.Ok : undefined;
423
+ });
424
+ }
425
+ exports.getNeuronInfo = getNeuronInfo;
426
+ function getNeuronInfoBySubAccount(publicKey, host, canisterId) {
427
+ return __awaiter(this, void 0, void 0, function* () {
428
+ // Create subaccount from publicKey
429
+ const { subAccount } = getFixedSubaccountFromPublicKey(publicKey);
430
+ const agent = createHttpAgent(host, secp256k1_1.default.generate());
431
+ const actor = actor_1.Actor.createActor(governance_1.idlFactory, {
432
+ agent,
433
+ canisterId
434
+ });
435
+ const array = subAccount.toUint8Array();
436
+ const result = (yield actor.get_neuron_info_by_id_or_subaccount({ Subaccount: array }));
437
+ return result.Ok ? result.Ok : undefined;
438
+ });
439
+ }
440
+ exports.getNeuronInfoBySubAccount = getNeuronInfoBySubAccount;
376
441
  //# sourceMappingURL=ICPImplementation.js.map