@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
package/v1/utils/http.js CHANGED
@@ -1,30 +1,4 @@
1
1
  "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
- var __assign = (this && this.__assign) || function () {
18
- __assign = Object.assign || function(t) {
19
- for (var s, i = 1, n = arguments.length; i < n; i++) {
20
- s = arguments[i];
21
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
22
- t[p] = s[p];
23
- }
24
- return t;
25
- };
26
- return __assign.apply(this, arguments);
27
- };
28
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
29
3
  if (k2 === undefined) k2 = k;
30
4
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -57,80 +31,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
57
31
  step((generator = generator.apply(thisArg, _arguments || [])).next());
58
32
  });
59
33
  };
60
- var __generator = (this && this.__generator) || function (thisArg, body) {
61
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
62
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
63
- function verb(n) { return function (v) { return step([n, v]); }; }
64
- function step(op) {
65
- if (f) throw new TypeError("Generator is already executing.");
66
- while (_) try {
67
- 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;
68
- if (y = 0, t) op = [op[0] & 2, t.value];
69
- switch (op[0]) {
70
- case 0: case 1: t = op; break;
71
- case 4: _.label++; return { value: op[1], done: false };
72
- case 5: _.label++; y = op[1]; op = [0]; continue;
73
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
74
- default:
75
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
76
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
77
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
78
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
79
- if (t[2]) _.ops.pop();
80
- _.trys.pop(); continue;
81
- }
82
- op = body.call(thisArg, _);
83
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
84
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
85
- }
86
- };
87
- var __read = (this && this.__read) || function (o, n) {
88
- var m = typeof Symbol === "function" && o[Symbol.iterator];
89
- if (!m) return o;
90
- var i = m.call(o), r, ar = [], e;
91
- try {
92
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
93
- }
94
- catch (error) { e = { error: error }; }
95
- finally {
96
- try {
97
- if (r && !r.done && (m = i["return"])) m.call(i);
98
- }
99
- finally { if (e) throw e.error; }
100
- }
101
- return ar;
102
- };
103
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
104
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
105
- if (ar || !(i in from)) {
106
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
107
- ar[i] = from[i];
108
- }
109
- }
110
- return to.concat(ar || Array.prototype.slice.call(from));
111
- };
112
- var __values = (this && this.__values) || function(o) {
113
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
114
- if (m) return m.call(o);
115
- if (o && typeof o.length === "number") return {
116
- next: function () {
117
- if (o && i >= o.length) o = void 0;
118
- return { value: o && o[i++], done: !o };
119
- }
120
- };
121
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
122
- };
123
34
  Object.defineProperty(exports, "__esModule", { value: true });
124
35
  exports.HttpAgent = exports.IdentityInvalidError = exports.RequestStatusResponseStatus = exports.makeNonce = exports.SubmitRequestType = exports.Expiry = exports.ReplicaRejectCode = void 0;
125
- var principal_1 = require("./principal");
126
- var auth_1 = require("./auth");
127
- var buffer_1 = require("./buffer");
128
- var Cbor = __importStar(require("./cbor"));
129
- var cbor = __importStar(require("simple-cbor"));
130
- var leb128_1 = require("./leb128");
131
- var errors_1 = require("./errors");
132
- var NANOSECONDS_PER_MILLISECONDS = BigInt(1000000);
133
- var REPLICA_PERMITTED_DRIFT_MILLISECONDS = BigInt(60 * 1000);
36
+ const principal_1 = require("./principal");
37
+ const auth_1 = require("./auth");
38
+ const buffer_1 = require("./buffer");
39
+ const Cbor = __importStar(require("./cbor"));
40
+ const cbor = __importStar(require("simple-cbor"));
41
+ const leb128_1 = require("./leb128");
42
+ const errors_1 = require("./errors");
43
+ const NANOSECONDS_PER_MILLISECONDS = BigInt(1000000);
44
+ const REPLICA_PERMITTED_DRIFT_MILLISECONDS = BigInt(60 * 1000);
134
45
  var ReplicaRejectCode;
135
46
  (function (ReplicaRejectCode) {
136
47
  ReplicaRejectCode[ReplicaRejectCode["SysFatal"] = 1] = "SysFatal";
@@ -139,21 +50,20 @@ var ReplicaRejectCode;
139
50
  ReplicaRejectCode[ReplicaRejectCode["CanisterReject"] = 4] = "CanisterReject";
140
51
  ReplicaRejectCode[ReplicaRejectCode["CanisterError"] = 5] = "CanisterError";
141
52
  })(ReplicaRejectCode = exports.ReplicaRejectCode || (exports.ReplicaRejectCode = {}));
142
- var Expiry = /** @class */ (function () {
143
- function Expiry(deltaInMSec) {
53
+ class Expiry {
54
+ constructor(deltaInMSec) {
144
55
  // Use bigint because it can overflow the maximum number allowed in a double float.
145
56
  this._value = (BigInt(Date.now()) + BigInt(deltaInMSec) - REPLICA_PERMITTED_DRIFT_MILLISECONDS) * NANOSECONDS_PER_MILLISECONDS;
146
57
  }
147
58
  //@ts-ignore
148
- Expiry.prototype.toCBOR = function () {
59
+ toCBOR() {
149
60
  // TODO: change this to take the minimum amount of space (it always takes 8 bytes now).
150
61
  return cbor.value.u64(this._value.toString(16), 16);
151
- };
152
- Expiry.prototype.toHash = function () {
62
+ }
63
+ toHash() {
153
64
  return (0, leb128_1.lebEncode)(this._value);
154
- };
155
- return Expiry;
156
- }());
65
+ }
66
+ }
157
67
  exports.Expiry = Expiry;
158
68
  // tslint:enable:camel-case
159
69
  // The types of values allowed in the `request_type` field for submit requests.
@@ -166,17 +76,17 @@ var SubmitRequestType;
166
76
  */
167
77
  function makeNonce() {
168
78
  // Encode 128 bits.
169
- var buffer = new ArrayBuffer(16);
170
- var view = new DataView(buffer);
171
- var now = BigInt(+Date.now());
172
- var randHi = Math.floor(Math.random() * 0xffffffff);
173
- var randLo = Math.floor(Math.random() * 0xffffffff);
79
+ const buffer = new ArrayBuffer(16);
80
+ const view = new DataView(buffer);
81
+ const now = BigInt(+Date.now());
82
+ const randHi = Math.floor(Math.random() * 0xffffffff);
83
+ const randLo = Math.floor(Math.random() * 0xffffffff);
174
84
  // Fix for IOS < 14.8 setBigUint64 absence
175
85
  if (typeof view.setBigUint64 === 'function') {
176
86
  view.setBigUint64(0, now);
177
87
  }
178
88
  else {
179
- var TWO_TO_THE_32 = BigInt(1) << BigInt(32);
89
+ const TWO_TO_THE_32 = BigInt(1) << BigInt(32);
180
90
  view.setUint32(0, Number(now >> BigInt(32)));
181
91
  view.setUint32(4, Number(now % TWO_TO_THE_32));
182
92
  }
@@ -195,36 +105,30 @@ var RequestStatusResponseStatus;
195
105
  RequestStatusResponseStatus["Done"] = "done";
196
106
  })(RequestStatusResponseStatus = exports.RequestStatusResponseStatus || (exports.RequestStatusResponseStatus = {}));
197
107
  // Default delta for ingress expiry is 5 minutes.
198
- var DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS = 5 * 60 * 1000;
108
+ const DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS = 5 * 60 * 1000;
199
109
  // Root public key for the IC, encoded as hex
200
- var IC_ROOT_KEY = '308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814' +
110
+ const IC_ROOT_KEY = '308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814' +
201
111
  'c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d968' +
202
112
  '5f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484' +
203
113
  'b01291091c5f87b98883463f98091a0baaae';
204
114
  // IC0 domain info
205
- var IC0_DOMAIN = 'ic0.app';
206
- var IC0_SUB_DOMAIN = '.ic0.app';
207
- var HttpDefaultFetchError = /** @class */ (function (_super) {
208
- __extends(HttpDefaultFetchError, _super);
209
- function HttpDefaultFetchError(message) {
210
- var _this = _super.call(this, message) || this;
211
- _this.message = message;
212
- return _this;
115
+ const IC0_DOMAIN = 'ic0.app';
116
+ const IC0_SUB_DOMAIN = '.ic0.app';
117
+ class HttpDefaultFetchError extends errors_1.AgentError {
118
+ constructor(message) {
119
+ super(message);
120
+ this.message = message;
213
121
  }
214
- return HttpDefaultFetchError;
215
- }(errors_1.AgentError));
216
- var IdentityInvalidError = /** @class */ (function (_super) {
217
- __extends(IdentityInvalidError, _super);
218
- function IdentityInvalidError(message) {
219
- var _this = _super.call(this, message) || this;
220
- _this.message = message;
221
- return _this;
122
+ }
123
+ class IdentityInvalidError extends errors_1.AgentError {
124
+ constructor(message) {
125
+ super(message);
126
+ this.message = message;
222
127
  }
223
- return IdentityInvalidError;
224
- }(errors_1.AgentError));
128
+ }
225
129
  exports.IdentityInvalidError = IdentityInvalidError;
226
130
  function getDefaultFetch() {
227
- var defaultFetch;
131
+ let defaultFetch;
228
132
  if (typeof window !== 'undefined') {
229
133
  // Browser context
230
134
  if (window.fetch) {
@@ -262,9 +166,8 @@ function getDefaultFetch() {
262
166
  // it to the client. This is to decouple signature, nonce generation and
263
167
  // other computations so that this class can stay as simple as possible while
264
168
  // allowing extensions.
265
- var HttpAgent = /** @class */ (function () {
266
- function HttpAgent(options) {
267
- if (options === void 0) { options = {}; }
169
+ class HttpAgent {
170
+ constructor(options = {}) {
268
171
  this.rootKey = (0, buffer_1.fromHex)(IC_ROOT_KEY);
269
172
  this._pipeline = [];
270
173
  this._rootKeyFetched = false;
@@ -272,7 +175,7 @@ var HttpAgent = /** @class */ (function () {
272
175
  if (!(options.source instanceof HttpAgent)) {
273
176
  throw new Error("An Agent's source can only be another HttpAgent");
274
177
  }
275
- this._pipeline = __spreadArray([], __read(options.source._pipeline), false);
178
+ this._pipeline = [...options.source._pipeline];
276
179
  this._identity = options.source._identity;
277
180
  this._fetch = options.source._fetch;
278
181
  this._host = options.source._host;
@@ -294,321 +197,194 @@ var HttpAgent = /** @class */ (function () {
294
197
  this._host = options.source._host;
295
198
  }
296
199
  else {
297
- var location_1 = typeof window !== 'undefined' ? window.location : undefined;
298
- if (!location_1) {
200
+ const location = typeof window !== 'undefined' ? window.location : undefined;
201
+ if (!location) {
299
202
  throw new Error('Must specify a host to connect to.');
300
203
  }
301
- this._host = new URL(location_1 + '');
204
+ this._host = new URL(location + '');
302
205
  }
303
206
  // Rewrite to avoid redirects
304
207
  if (this._host.hostname.endsWith(IC0_SUB_DOMAIN)) {
305
208
  this._host.hostname = IC0_DOMAIN;
306
209
  }
307
210
  if (options.credentials) {
308
- var _a = options.credentials, name_1 = _a.name, password = _a.password;
309
- this._credentials = "".concat(name_1).concat(password ? ':' + password : '');
211
+ const { name, password } = options.credentials;
212
+ this._credentials = `${name}${password ? ':' + password : ''}`;
310
213
  }
311
214
  this._identity = Promise.resolve(options.identity || new auth_1.AnonymousIdentity());
312
215
  }
313
- HttpAgent.prototype.addTransform = function (fn, priority) {
314
- if (priority === void 0) { priority = fn.priority || 0; }
216
+ addTransform(fn, priority = fn.priority || 0) {
315
217
  // Keep the pipeline sorted at all time, by priority.
316
- var i = this._pipeline.findIndex(function (x) { return (x.priority || 0) < priority; });
317
- this._pipeline.splice(i >= 0 ? i : this._pipeline.length, 0, Object.assign(fn, { priority: priority }));
318
- };
319
- HttpAgent.prototype.getPrincipal = function () {
320
- return __awaiter(this, void 0, void 0, function () {
321
- return __generator(this, function (_a) {
322
- switch (_a.label) {
323
- case 0:
324
- if (!this._identity) {
325
- throw new IdentityInvalidError("This identity has expired due this application's security policy. Please refresh your authentication.");
326
- }
327
- return [4 /*yield*/, this._identity];
328
- case 1:
329
- //@ts-ignore
330
- return [2 /*return*/, (_a.sent()).getPrincipal()];
331
- }
332
- });
218
+ const i = this._pipeline.findIndex((x) => (x.priority || 0) < priority);
219
+ this._pipeline.splice(i >= 0 ? i : this._pipeline.length, 0, Object.assign(fn, { priority }));
220
+ }
221
+ getPrincipal() {
222
+ return __awaiter(this, void 0, void 0, function* () {
223
+ if (!this._identity) {
224
+ throw new IdentityInvalidError("This identity has expired due this application's security policy. Please refresh your authentication.");
225
+ }
226
+ //@ts-ignore
227
+ return (yield this._identity).getPrincipal();
333
228
  });
334
- };
335
- HttpAgent.prototype.call = function (canisterId, options, identity) {
336
- return __awaiter(this, void 0, void 0, function () {
337
- var id, _a, canister, ecid, sender, submit, transformedRequest, body, _b, response, requestId, _c, _d, _e;
338
- return __generator(this, function (_f) {
339
- switch (_f.label) {
340
- case 0:
341
- if (!(identity !== undefined)) return [3 /*break*/, 2];
342
- return [4 /*yield*/, identity];
343
- case 1:
344
- _a = _f.sent();
345
- return [3 /*break*/, 4];
346
- case 2: return [4 /*yield*/, this._identity];
347
- case 3:
348
- _a = _f.sent();
349
- _f.label = 4;
350
- case 4: return [4 /*yield*/, (_a)];
351
- case 5:
352
- id = _f.sent();
353
- if (!id) {
354
- throw new IdentityInvalidError("This identity has expired due this application's security policy. Please refresh your authentication.");
355
- }
356
- canister = principal_1.Principal.from(canisterId);
357
- ecid = options.effectiveCanisterId ? principal_1.Principal.from(options.effectiveCanisterId) : canister;
358
- sender = id.getPrincipal() || principal_1.Principal.anonymous();
359
- submit = {
360
- request_type: SubmitRequestType.Call,
361
- canister_id: canister,
362
- method_name: options.methodName,
363
- arg: options.arg,
364
- sender: sender,
365
- ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS)
366
- };
367
- return [4 /*yield*/, this._transform({
368
- request: {
369
- body: null,
370
- method: 'POST',
371
- headers: __assign({ 'Content-Type': 'application/cbor' }, (this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}))
372
- },
373
- endpoint: "call" /* Endpoint.Call */,
374
- body: submit
375
- })];
376
- case 6:
377
- transformedRequest = (_f.sent());
378
- return [4 /*yield*/, id.transformRequest(transformedRequest)];
379
- case 7:
380
- // Apply transform for identity.
381
- transformedRequest = _f.sent();
382
- body = Cbor.encode(transformedRequest.body);
383
- return [4 /*yield*/, Promise.all([
384
- this._fetch('' + new URL("/api/v2/canister/".concat(ecid.toText(), "/call"), this._host), __assign(__assign({}, transformedRequest.request), { body: body })),
385
- (0, auth_1.requestIdOf)(submit)
386
- ])];
387
- case 8:
388
- _b = __read.apply(void 0, [_f.sent(), 2]), response = _b[0], requestId = _b[1];
389
- if (!!response.ok) return [3 /*break*/, 10];
390
- _c = Error.bind;
391
- _d = "Server returned an error:\n" + " Code: ".concat(response.status, " (").concat(response.statusText, ")\n");
392
- _e = " Body: ".concat;
393
- return [4 /*yield*/, response.text()];
394
- case 9: throw new (_c.apply(Error, [void 0, _d + _e.apply(" Body: ", [_f.sent(), "\n"])]))();
395
- case 10: return [2 /*return*/, {
396
- requestId: requestId,
397
- response: {
398
- ok: response.ok,
399
- status: response.status,
400
- statusText: response.statusText
401
- }
402
- }];
229
+ }
230
+ call(canisterId, options, identity) {
231
+ return __awaiter(this, void 0, void 0, function* () {
232
+ const id = yield (identity !== undefined ? yield identity : yield this._identity);
233
+ if (!id) {
234
+ throw new IdentityInvalidError("This identity has expired due this application's security policy. Please refresh your authentication.");
235
+ }
236
+ const canister = principal_1.Principal.from(canisterId);
237
+ const ecid = options.effectiveCanisterId ? principal_1.Principal.from(options.effectiveCanisterId) : canister;
238
+ //@ts-ignore
239
+ const sender = id.getPrincipal() || principal_1.Principal.anonymous();
240
+ const submit = {
241
+ request_type: SubmitRequestType.Call,
242
+ canister_id: canister,
243
+ method_name: options.methodName,
244
+ arg: options.arg,
245
+ sender,
246
+ ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS)
247
+ };
248
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
249
+ let transformedRequest = (yield this._transform({
250
+ request: {
251
+ body: null,
252
+ method: 'POST',
253
+ headers: Object.assign({ 'Content-Type': 'application/cbor' }, (this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}))
254
+ },
255
+ endpoint: "call" /* Endpoint.Call */,
256
+ body: submit
257
+ }));
258
+ // Apply transform for identity.
259
+ transformedRequest = yield id.transformRequest(transformedRequest);
260
+ const body = Cbor.encode(transformedRequest.body);
261
+ // Run both in parallel. The fetch is quite expensive, so we have plenty of time to
262
+ // calculate the requestId locally.
263
+ const [response, requestId] = yield Promise.all([
264
+ this._fetch('' + new URL(`/api/v2/canister/${ecid.toText()}/call`, this._host), Object.assign(Object.assign({}, transformedRequest.request), { body })),
265
+ (0, auth_1.requestIdOf)(submit)
266
+ ]);
267
+ if (!response.ok) {
268
+ throw new Error(`Server returned an error:\n` + ` Code: ${response.status} (${response.statusText})\n` + ` Body: ${yield response.text()}\n`);
269
+ }
270
+ return {
271
+ requestId,
272
+ response: {
273
+ ok: response.ok,
274
+ status: response.status,
275
+ statusText: response.statusText
403
276
  }
404
- });
277
+ };
405
278
  });
406
- };
407
- HttpAgent.prototype.query = function (canisterId, fields, identity) {
408
- return __awaiter(this, void 0, void 0, function () {
409
- var id, _a, canister, sender, request, transformedRequest, body, response, _b, _c, _d, _e, _f;
410
- return __generator(this, function (_g) {
411
- switch (_g.label) {
412
- case 0:
413
- if (!(identity !== undefined)) return [3 /*break*/, 2];
414
- return [4 /*yield*/, identity];
415
- case 1:
416
- _a = _g.sent();
417
- return [3 /*break*/, 4];
418
- case 2: return [4 /*yield*/, this._identity];
419
- case 3:
420
- _a = _g.sent();
421
- _g.label = 4;
422
- case 4: return [4 /*yield*/, (_a)];
423
- case 5:
424
- id = _g.sent();
425
- if (!id) {
426
- throw new IdentityInvalidError("This identity has expired due this application's security policy. Please refresh your authentication.");
427
- }
428
- canister = typeof canisterId === 'string' ? principal_1.Principal.fromText(canisterId) : canisterId;
429
- sender = (id === null || id === void 0 ? void 0 : id.getPrincipal()) || principal_1.Principal.anonymous();
430
- request = {
431
- request_type: "query" /* ReadRequestType.Query */,
432
- canister_id: canister,
433
- method_name: fields.methodName,
434
- arg: fields.arg,
435
- //@ts-ignore
436
- sender: sender,
437
- ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS)
438
- };
439
- return [4 /*yield*/, this._transform({
440
- request: {
441
- method: 'POST',
442
- headers: __assign({ 'Content-Type': 'application/cbor' }, (this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}))
443
- },
444
- endpoint: "read" /* Endpoint.Query */,
445
- body: request
446
- })
447
- // Apply transform for identity.
448
- ];
449
- case 6:
450
- transformedRequest = _g.sent();
451
- return [4 /*yield*/, (id === null || id === void 0 ? void 0 : id.transformRequest(transformedRequest))];
452
- case 7:
453
- // Apply transform for identity.
454
- transformedRequest = _g.sent();
455
- body = Cbor.encode(transformedRequest.body);
456
- return [4 /*yield*/, this._fetch('' + new URL("/api/v2/canister/".concat(canister.toText(), "/query"), this._host), __assign(__assign({}, transformedRequest.request), { body: body }))];
457
- case 8:
458
- response = _g.sent();
459
- if (!!response.ok) return [3 /*break*/, 10];
460
- _b = Error.bind;
461
- _c = "Server returned an error:\n" + " Code: ".concat(response.status, " (").concat(response.statusText, ")\n");
462
- _d = " Body: ".concat;
463
- return [4 /*yield*/, response.text()];
464
- case 9: throw new (_b.apply(Error, [void 0, _c + _d.apply(" Body: ", [_g.sent(), "\n"])]))();
465
- case 10:
466
- _f = (_e = Cbor).decode;
467
- return [4 /*yield*/, response.arrayBuffer()];
468
- case 11: return [2 /*return*/, _f.apply(_e, [_g.sent()])];
469
- }
279
+ }
280
+ query(canisterId, fields, identity) {
281
+ return __awaiter(this, void 0, void 0, function* () {
282
+ const id = yield (identity !== undefined ? yield identity : yield this._identity);
283
+ if (!id) {
284
+ throw new IdentityInvalidError("This identity has expired due this application's security policy. Please refresh your authentication.");
285
+ }
286
+ const canister = typeof canisterId === 'string' ? principal_1.Principal.fromText(canisterId) : canisterId;
287
+ const sender = (id === null || id === void 0 ? void 0 : id.getPrincipal()) || principal_1.Principal.anonymous();
288
+ const request = {
289
+ request_type: "query" /* ReadRequestType.Query */,
290
+ canister_id: canister,
291
+ method_name: fields.methodName,
292
+ arg: fields.arg,
293
+ //@ts-ignore
294
+ sender,
295
+ ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS)
296
+ };
297
+ // TODO: remove this any. This can be a Signed or UnSigned request.
298
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
299
+ let transformedRequest = yield this._transform({
300
+ request: {
301
+ method: 'POST',
302
+ headers: Object.assign({ 'Content-Type': 'application/cbor' }, (this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}))
303
+ },
304
+ endpoint: "read" /* Endpoint.Query */,
305
+ body: request
470
306
  });
307
+ // Apply transform for identity.
308
+ transformedRequest = yield (id === null || id === void 0 ? void 0 : id.transformRequest(transformedRequest));
309
+ const body = Cbor.encode(transformedRequest.body);
310
+ const response = yield this._fetch('' + new URL(`/api/v2/canister/${canister.toText()}/query`, this._host), Object.assign(Object.assign({}, transformedRequest.request), { body }));
311
+ if (!response.ok) {
312
+ throw new Error(`Server returned an error:\n` + ` Code: ${response.status} (${response.statusText})\n` + ` Body: ${yield response.text()}\n`);
313
+ }
314
+ return Cbor.decode(yield response.arrayBuffer());
471
315
  });
472
- };
473
- HttpAgent.prototype.readState = function (canisterId, fields, identity) {
474
- return __awaiter(this, void 0, void 0, function () {
475
- var canister, id, _a, sender, transformedRequest, body, response, _b, _c, _d, _e, _f;
476
- return __generator(this, function (_g) {
477
- switch (_g.label) {
478
- case 0:
479
- canister = typeof canisterId === 'string' ? principal_1.Principal.fromText(canisterId) : canisterId;
480
- if (!(identity !== undefined)) return [3 /*break*/, 2];
481
- return [4 /*yield*/, identity];
482
- case 1:
483
- _a = _g.sent();
484
- return [3 /*break*/, 4];
485
- case 2: return [4 /*yield*/, this._identity];
486
- case 3:
487
- _a = _g.sent();
488
- _g.label = 4;
489
- case 4: return [4 /*yield*/, (_a)];
490
- case 5:
491
- id = _g.sent();
492
- if (!id) {
493
- throw new IdentityInvalidError("This identity has expired due this application's security policy. Please refresh your authentication.");
494
- }
495
- sender = (id === null || id === void 0 ? void 0 : id.getPrincipal()) || principal_1.Principal.anonymous();
496
- return [4 /*yield*/, this._transform({
497
- request: {
498
- method: 'POST',
499
- headers: __assign({ 'Content-Type': 'application/cbor' }, (this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}))
500
- },
501
- endpoint: "read_state" /* Endpoint.ReadState */,
502
- body: {
503
- request_type: "read_state" /* ReadRequestType.ReadState */,
504
- paths: fields.paths,
505
- //@ts-ignore
506
- sender: sender,
507
- ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS)
508
- }
509
- })
510
- // Apply transform for identity.
511
- ];
512
- case 6:
513
- transformedRequest = _g.sent();
514
- return [4 /*yield*/, (id === null || id === void 0 ? void 0 : id.transformRequest(transformedRequest))];
515
- case 7:
516
- // Apply transform for identity.
517
- transformedRequest = _g.sent();
518
- body = Cbor.encode(transformedRequest.body);
519
- return [4 /*yield*/, this._fetch('' + new URL("/api/v2/canister/".concat(canister, "/read_state"), this._host), __assign(__assign({}, transformedRequest.request), { body: body }))];
520
- case 8:
521
- response = _g.sent();
522
- if (!!response.ok) return [3 /*break*/, 10];
523
- _b = Error.bind;
524
- _c = "Server returned an error:\n" + " Code: ".concat(response.status, " (").concat(response.statusText, ")\n");
525
- _d = " Body: ".concat;
526
- return [4 /*yield*/, response.text()];
527
- case 9: throw new (_b.apply(Error, [void 0, _c + _d.apply(" Body: ", [_g.sent(), "\n"])]))();
528
- case 10:
529
- _f = (_e = Cbor).decode;
530
- return [4 /*yield*/, response.arrayBuffer()];
531
- case 11: return [2 /*return*/, _f.apply(_e, [_g.sent()])];
316
+ }
317
+ readState(canisterId, fields, identity) {
318
+ return __awaiter(this, void 0, void 0, function* () {
319
+ const canister = typeof canisterId === 'string' ? principal_1.Principal.fromText(canisterId) : canisterId;
320
+ const id = yield (identity !== undefined ? yield identity : yield this._identity);
321
+ if (!id) {
322
+ throw new IdentityInvalidError("This identity has expired due this application's security policy. Please refresh your authentication.");
323
+ }
324
+ const sender = (id === null || id === void 0 ? void 0 : id.getPrincipal()) || principal_1.Principal.anonymous();
325
+ // TODO: remove this any. This can be a Signed or UnSigned request.
326
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
327
+ let transformedRequest = yield this._transform({
328
+ request: {
329
+ method: 'POST',
330
+ headers: Object.assign({ 'Content-Type': 'application/cbor' }, (this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}))
331
+ },
332
+ endpoint: "read_state" /* Endpoint.ReadState */,
333
+ body: {
334
+ request_type: "read_state" /* ReadRequestType.ReadState */,
335
+ paths: fields.paths,
336
+ //@ts-ignore
337
+ sender,
338
+ ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS)
532
339
  }
533
340
  });
341
+ // Apply transform for identity.
342
+ transformedRequest = yield (id === null || id === void 0 ? void 0 : id.transformRequest(transformedRequest));
343
+ const body = Cbor.encode(transformedRequest.body);
344
+ const response = yield this._fetch('' + new URL(`/api/v2/canister/${canister}/read_state`, this._host), Object.assign(Object.assign({}, transformedRequest.request), { body }));
345
+ if (!response.ok) {
346
+ throw new Error(`Server returned an error:\n` + ` Code: ${response.status} (${response.statusText})\n` + ` Body: ${yield response.text()}\n`);
347
+ }
348
+ return Cbor.decode(yield response.arrayBuffer());
534
349
  });
535
- };
536
- HttpAgent.prototype.status = function () {
537
- return __awaiter(this, void 0, void 0, function () {
538
- var headers, response, _a, _b, _c, _d, _e;
539
- return __generator(this, function (_f) {
540
- switch (_f.label) {
541
- case 0:
542
- headers = this._credentials
543
- ? {
544
- Authorization: 'Basic ' + btoa(this._credentials)
545
- }
546
- : {};
547
- return [4 /*yield*/, this._fetch('' + new URL("/api/v2/status", this._host), { headers: headers })];
548
- case 1:
549
- response = _f.sent();
550
- if (!!response.ok) return [3 /*break*/, 3];
551
- _a = Error.bind;
552
- _b = "Server returned an error:\n" + " Code: ".concat(response.status, " (").concat(response.statusText, ")\n");
553
- _c = " Body: ".concat;
554
- return [4 /*yield*/, response.text()];
555
- case 2: throw new (_a.apply(Error, [void 0, _b + _c.apply(" Body: ", [_f.sent(), "\n"])]))();
556
- case 3:
557
- _e = (_d = Cbor).decode;
558
- return [4 /*yield*/, response.arrayBuffer()];
559
- case 4: return [2 /*return*/, _e.apply(_d, [_f.sent()])];
350
+ }
351
+ status() {
352
+ return __awaiter(this, void 0, void 0, function* () {
353
+ const headers = this._credentials
354
+ ? {
355
+ Authorization: 'Basic ' + btoa(this._credentials)
560
356
  }
561
- });
357
+ : {};
358
+ const response = yield this._fetch('' + new URL(`/api/v2/status`, this._host), { headers });
359
+ if (!response.ok) {
360
+ throw new Error(`Server returned an error:\n` + ` Code: ${response.status} (${response.statusText})\n` + ` Body: ${yield response.text()}\n`);
361
+ }
362
+ return Cbor.decode(yield response.arrayBuffer());
562
363
  });
563
- };
564
- HttpAgent.prototype.fetchRootKey = function () {
565
- return __awaiter(this, void 0, void 0, function () {
566
- var _a;
567
- return __generator(this, function (_b) {
568
- switch (_b.label) {
569
- case 0:
570
- if (!!this._rootKeyFetched) return [3 /*break*/, 2];
571
- // Hex-encoded version of the replica root key
572
- _a = this;
573
- return [4 /*yield*/, this.status()];
574
- case 1:
575
- // Hex-encoded version of the replica root key
576
- _a.rootKey = (_b.sent()).root_key;
577
- this._rootKeyFetched = true;
578
- _b.label = 2;
579
- case 2: return [2 /*return*/, this.rootKey];
580
- }
581
- });
364
+ }
365
+ fetchRootKey() {
366
+ return __awaiter(this, void 0, void 0, function* () {
367
+ if (!this._rootKeyFetched) {
368
+ // Hex-encoded version of the replica root key
369
+ this.rootKey = (yield this.status()).root_key;
370
+ this._rootKeyFetched = true;
371
+ }
372
+ return this.rootKey;
582
373
  });
583
- };
584
- HttpAgent.prototype.invalidateIdentity = function () {
374
+ }
375
+ invalidateIdentity() {
585
376
  this._identity = null;
586
- };
587
- HttpAgent.prototype.replaceIdentity = function (identity) {
377
+ }
378
+ replaceIdentity(identity) {
588
379
  this._identity = Promise.resolve(identity);
589
- };
590
- HttpAgent.prototype._transform = function (request) {
591
- var e_1, _a;
592
- var p = Promise.resolve(request);
593
- var _loop_1 = function (fn) {
594
- p = p.then(function (r) { return fn(r).then(function (r2) { return r2 || r; }); });
595
- };
596
- try {
597
- for (var _b = __values(this._pipeline), _c = _b.next(); !_c.done; _c = _b.next()) {
598
- var fn = _c.value;
599
- _loop_1(fn);
600
- }
601
- }
602
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
603
- finally {
604
- try {
605
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
606
- }
607
- finally { if (e_1) throw e_1.error; }
380
+ }
381
+ _transform(request) {
382
+ let p = Promise.resolve(request);
383
+ for (const fn of this._pipeline) {
384
+ p = p.then((r) => fn(r).then((r2) => r2 || r));
608
385
  }
609
386
  return p;
610
- };
611
- return HttpAgent;
612
- }());
387
+ }
388
+ }
613
389
  exports.HttpAgent = HttpAgent;
614
390
  //# sourceMappingURL=http.js.map