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

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