wallaby-cash 2.0.1-alpha.0 → 2.0.1-alpha.1

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.
package/dist/index.cjs.js CHANGED
@@ -5,8 +5,8 @@ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toString
5
5
  const uuid = require('uuid');
6
6
  const axios = require('axios');
7
7
  const log = require('loglevel');
8
- const jwtDecode = require('jwt-decode');
9
8
  const cryptoJs = require('crypto-js');
9
+ const jwtDecode = require('jwt-decode');
10
10
 
11
11
  const _interopDefaultCompat = e => e && typeof e === 'object' && 'default' in e ? e : { default: e };
12
12
 
@@ -710,828 +710,155 @@ var PUBLIC_KEY_CREDENTIAL_PARAM = [
710
710
  { type: 'public-key', alg: exports.PublicKeyCredentialAlgorithm.ES256 },
711
711
  ];
712
712
 
713
- var StorageService = /** @class */ (function () {
714
- function StorageService(_a) {
715
- var deviceStorage = _a.deviceStorage, userId = _a.userId, environment = _a.environment;
716
- this.userId = userId;
717
- this.environment = environment !== null && environment !== void 0 ? environment : defaultEnvironment;
718
- this.deviceStorage = deviceStorage;
713
+ function getRandomBytesSync(bytes) {
714
+ return randomBytes(bytes);
715
+ }
716
+
717
+ /**
718
+ * Returns a `Boolean` on whether or not the a `String` starts with '0x'
719
+ * @param str the string input value
720
+ * @return a boolean if it is or is not hex prefixed
721
+ * @throws if the str input is not a string
722
+ */
723
+ var isHexPrefixed = function (str) {
724
+ if (typeof str !== 'string') {
725
+ throw new Error("[isHexPrefixed] input must be type 'string', received type ".concat(typeof str));
719
726
  }
720
- StorageService.prototype.fetch = function (key) {
721
- return __awaiter(this, void 0, void 0, function () {
722
- var item, _a;
723
- return __generator(this, function (_b) {
724
- switch (_b.label) {
725
- case 0:
726
- _a = key;
727
- switch (_a) {
728
- case exports.LocalStorageItems.EncryptedStandardSeedPhrase: return [3 /*break*/, 1];
729
- case exports.LocalStorageItems.EncryptedAlgorandSeedPhrase: return [3 /*break*/, 3];
730
- }
731
- return [3 /*break*/, 5];
732
- case 1: return [4 /*yield*/, this.getItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Standard, "-seedPhrase-").concat(this.userId))];
733
- case 2:
734
- item = _b.sent();
735
- return [3 /*break*/, 7];
736
- case 3: return [4 /*yield*/, this.getItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Algorand, "-seedPhrase-").concat(this.userId))];
737
- case 4:
738
- item = _b.sent();
739
- return [3 /*break*/, 7];
740
- case 5: return [4 /*yield*/, this.getItem("".concat(this.environment, "-").concat(key, "-").concat(this.userId))];
741
- case 6:
742
- item = _b.sent();
743
- return [3 /*break*/, 7];
744
- case 7:
745
- if (!item) {
746
- logger.info("Item with key ".concat(key, " was not found in storage."));
747
- return [2 /*return*/, undefined];
748
- }
749
- return [2 /*return*/, item];
750
- }
751
- });
752
- });
753
- };
754
- StorageService.prototype.save = function (key, value) {
755
- return __awaiter(this, void 0, void 0, function () {
756
- var _a;
757
- return __generator(this, function (_b) {
758
- switch (_b.label) {
759
- case 0:
760
- _a = key;
761
- switch (_a) {
762
- case exports.LocalStorageItems.EncryptedStandardSeedPhrase: return [3 /*break*/, 1];
763
- case exports.LocalStorageItems.EncryptedAlgorandSeedPhrase: return [3 /*break*/, 3];
764
- }
765
- return [3 /*break*/, 5];
766
- case 1: return [4 /*yield*/, this.setItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Standard, "-seedPhrase-").concat(this.userId), value)];
767
- case 2:
768
- _b.sent();
769
- return [3 /*break*/, 7];
770
- case 3: return [4 /*yield*/, this.setItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Algorand, "-seedPhrase-").concat(this.userId), value)];
771
- case 4:
772
- _b.sent();
773
- return [3 /*break*/, 7];
774
- case 5: return [4 /*yield*/, this.setItem("".concat(this.environment, "-").concat(key, "-").concat(this.userId), value)];
775
- case 6:
776
- _b.sent();
777
- return [3 /*break*/, 7];
778
- case 7: return [2 /*return*/];
779
- }
780
- });
781
- });
782
- };
783
- StorageService.prototype.saveInBulk = function (data) {
784
- return __awaiter(this, void 0, void 0, function () {
785
- var _this = this;
786
- return __generator(this, function (_a) {
787
- data.forEach(function (item) { return __awaiter(_this, void 0, void 0, function () {
788
- return __generator(this, function (_a) {
789
- switch (_a.label) {
790
- case 0: return [4 /*yield*/, this.save(item.key, item.value)];
791
- case 1:
792
- _a.sent();
793
- return [2 /*return*/];
794
- }
795
- });
796
- }); });
797
- return [2 /*return*/];
798
- });
799
- });
800
- };
801
- StorageService.prototype.delete = function (key) {
802
- return __awaiter(this, void 0, void 0, function () {
803
- var _a;
804
- return __generator(this, function (_b) {
805
- switch (_b.label) {
806
- case 0:
807
- _a = key;
808
- switch (_a) {
809
- case exports.LocalStorageItems.EncryptedStandardSeedPhrase: return [3 /*break*/, 1];
810
- case exports.LocalStorageItems.EncryptedAlgorandSeedPhrase: return [3 /*break*/, 3];
811
- }
812
- return [3 /*break*/, 5];
813
- case 1: return [4 /*yield*/, this.removeItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Standard, "-seedPhrase-").concat(this.userId))];
814
- case 2:
815
- _b.sent();
816
- return [3 /*break*/, 7];
817
- case 3: return [4 /*yield*/, this.removeItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Algorand, "-seedPhrase-").concat(this.userId))];
818
- case 4:
819
- _b.sent();
820
- return [3 /*break*/, 7];
821
- case 5: return [4 /*yield*/, this.removeItem("".concat(this.environment, "-").concat(key, "-").concat(this.userId))];
822
- case 6:
823
- _b.sent();
824
- return [3 /*break*/, 7];
825
- case 7: return [2 /*return*/];
826
- }
827
- });
828
- });
829
- };
830
- StorageService.prototype.setItem = function (key, value) {
831
- var _a, _b;
832
- /** check if deviceStorageSetItem is defined */
833
- if ((_a = this.deviceStorage) === null || _a === void 0 ? void 0 : _a.setItem) {
834
- return this.deviceStorage.setItem(key, value);
835
- }
836
- if ((_b = this.deviceStorage) === null || _b === void 0 ? void 0 : _b.setItemAsync) {
837
- return this.deviceStorage.setItemAsync(key, value);
727
+ return str[0] === '0' && str[1] === 'x';
728
+ };
729
+ /**
730
+ * Removes '0x' from a given `String` if present
731
+ * @param str the string value
732
+ * @returns the string without 0x prefix
733
+ */
734
+ var stripHexPrefix = function (str) {
735
+ if (typeof str !== 'string')
736
+ throw new Error("[stripHexPrefix] input must be type 'string', received ".concat(typeof str));
737
+ return isHexPrefixed(str) ? str.slice(2) : str;
738
+ };
739
+ /**
740
+ * Adds '0x' to a given `String` if not present
741
+ * @param str the string input value
742
+ * @return the string with a 0x prefix
743
+ */
744
+ var addLeading0x = function (str) {
745
+ if (!str.startsWith('0x'))
746
+ return '0x' + str;
747
+ else
748
+ return str;
749
+ };
750
+ var decompress = function (startsWith02Or03) {
751
+ var testByteArray = hexToBytes$1(startsWith02Or03);
752
+ var startsWith04 = startsWith02Or03;
753
+ if (testByteArray.length === 64) {
754
+ startsWith04 = '04' + startsWith02Or03;
755
+ }
756
+ return startsWith04.substring(2);
757
+ };
758
+ /** Helper function to concat UInt8Arrays mimicking the behaviour of the
759
+ * Buffer.concat function in Node.js
760
+ */
761
+ var concatUint8Arrays = function (uint8arrays) {
762
+ var totalLength = uint8arrays.reduce(function (total, uint8array) { return total + uint8array.byteLength; }, 0);
763
+ var result = new Uint8Array(totalLength);
764
+ var offset = 0;
765
+ uint8arrays.forEach(function (uint8array) {
766
+ result.set(uint8array, offset);
767
+ offset += uint8array.byteLength;
768
+ });
769
+ return result;
770
+ };
771
+ /**
772
+ * Converts a UTF-8 string to a Uint8Array without using TextEncoder, which is not available in mobile
773
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
774
+ */
775
+ var utf8ToBytes$1 = function (str) {
776
+ if (typeof str !== 'string')
777
+ throw new Error("utf8ToBytes expected string, got ".concat(typeof str));
778
+ var bytes = [];
779
+ for (var i = 0; i < str.length; i++) {
780
+ var codePoint = str.codePointAt(i);
781
+ if (!codePoint) {
782
+ throw new Error('Invalid code point');
838
783
  }
839
- throw new Error('setItem function is is not defined');
840
- };
841
- StorageService.prototype.getItem = function (key) {
842
- var _a, _b;
843
- if ((_a = this.deviceStorage) === null || _a === void 0 ? void 0 : _a.getItem) {
844
- return this.deviceStorage.getItem(key);
784
+ if (codePoint < 0x80) {
785
+ bytes.push(codePoint);
845
786
  }
846
- if ((_b = this.deviceStorage) === null || _b === void 0 ? void 0 : _b.getItemAsync) {
847
- return this.deviceStorage.getItemAsync(key);
787
+ else if (codePoint < 0x800) {
788
+ bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f));
848
789
  }
849
- throw new Error('getItem function is not defined');
850
- };
851
- StorageService.prototype.removeItem = function (key) {
852
- var _a, _b;
853
- if ((_a = this.deviceStorage) === null || _a === void 0 ? void 0 : _a.removeItem) {
854
- return this.deviceStorage.removeItem(key);
790
+ else if (codePoint < 0x10000) {
791
+ bytes.push(0xe0 | (codePoint >> 12), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
855
792
  }
856
- if ((_b = this.deviceStorage) === null || _b === void 0 ? void 0 : _b.deleteItemAsync) {
857
- return this.deviceStorage.deleteItemAsync(key);
793
+ else {
794
+ i++; // skip one iteration since we have a surrogate pair
795
+ bytes.push(0xf0 | (codePoint >> 18), 0x80 | ((codePoint >> 12) & 0x3f), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
858
796
  }
859
- throw new Error('removeItem function is not defined');
860
- };
861
- StorageService.prototype.clearLocalStorage = function () {
862
- return __awaiter(this, void 0, void 0, function () {
863
- return __generator(this, function (_a) {
864
- switch (_a.label) {
865
- case 0: return [4 /*yield*/, Promise.all([
866
- this.removeItem("".concat(this.environment, "-access-token-").concat(this.userId)),
867
- this.removeItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Algorand, "-seedPhrase-").concat(this.userId)),
868
- this.removeItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Standard, "-seedPhrase-").concat(this.userId)),
869
- this.removeItem("".concat(this.environment, "-client-auth-private-key-").concat(this.userId)),
870
- this.removeItem("".concat(this.environment, "-wallaby-auth-public-key-").concat(this.userId)),
871
- this.removeItem("encryptedPrivateKey_".concat(this.userId)),
872
- this.removeItem("wallabyAuthPubKey_".concat(this.userId)),
873
- this.removeItem("encryptedSeed_".concat(this.userId)),
874
- this.removeItem("encryptedAlgorandSeed_".concat(this.userId)),
875
- this.removeItem("accessToken_".concat(this.userId)),
876
- this.delete(exports.LocalStorageItems.AccessToken),
877
- this.delete(exports.LocalStorageItems.ClientAuthPublicKey),
878
- this.delete(exports.LocalStorageItems.ClientAuthToken),
879
- this.delete(exports.LocalStorageItems.EncryptedStandardSeedPhrase),
880
- this.delete(exports.LocalStorageItems.EncryptedAlgorandSeedPhrase),
881
- this.delete(exports.LocalStorageItems.EncryptedDevicePrivateKey),
882
- this.delete(exports.LocalStorageItems.WallabyAuthPubKey),
883
- ])];
884
- case 1:
885
- _a.sent();
886
- return [2 /*return*/];
887
- }
888
- });
889
- });
890
- };
891
- StorageService.prototype.loadDeviceInformation = function () {
892
- return __awaiter(this, void 0, void 0, function () {
893
- var _a, _b, _c, _d;
894
- return __generator(this, function (_e) {
895
- switch (_e.label) {
896
- case 0:
897
- _a = {};
898
- _b = {};
899
- return [4 /*yield*/, this.fetch(exports.LocalStorageItems.AccessToken)];
900
- case 1:
901
- _b.accessToken = _e.sent();
902
- return [4 /*yield*/, this.fetch(exports.LocalStorageItems.ClientAuthToken)];
903
- case 2:
904
- _a.authTokens = (_b.clientAuthToken = _e.sent(),
905
- _b);
906
- _c = {
907
- clientUserId: this.userId
908
- };
909
- return [4 /*yield*/, this.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase)];
910
- case 3:
911
- _c.encryptedStandardSeedPhrase = _e.sent();
912
- return [4 /*yield*/, this.fetch(exports.LocalStorageItems.EncryptedAlgorandSeedPhrase)];
913
- case 4:
914
- _a.user = (
915
- // encryptedKeyShare: await this.fetch(LocalStorageItems.EncryptedKeyShares),
916
- _c.encryptedAlgorandSeedPhrase = _e.sent(),
917
- _c.wallabyUserId = undefined,
918
- _c);
919
- _d = {
920
- // Initially these are undefined, because we don't have the decrypted private key yet, and for that we need the password.
921
- deviceAuthPrivateKey: undefined,
922
- deviceAuthPublicKey: undefined
923
- };
924
- return [4 /*yield*/, this.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey)];
925
- case 5:
926
- _d.deviceEncryptedPrivateKey = _e.sent();
927
- return [4 /*yield*/, this.fetch(exports.LocalStorageItems.WallabyAuthPubKey)];
928
- case 6: return [2 /*return*/, (_a.credentials = (_d.wallabyPublicKey = _e.sent(),
929
- _d),
930
- _a)];
931
- }
932
- });
933
- });
934
- };
935
- return StorageService;
936
- }());
797
+ }
798
+ return new Uint8Array(bytes);
799
+ };
937
800
 
938
801
  /**
939
- * Converts an object to query parameters string.
940
- *
941
- * @param obj - The object to convert.
942
- * @returns The query parameters string.
802
+ * Polyfill for Safari 14
943
803
  */
944
- function objectToQueryParams(obj) {
945
- var params = new URLSearchParams();
946
- Object.keys(obj).forEach(function (key) {
947
- if (obj[key] !== null && obj[key] !== undefined && obj[key] !== '') {
948
- params.append(key, obj[key]);
949
- }
950
- });
951
- return params.toString();
804
+ function setBigUint64(view, byteOffset, value, isLE) {
805
+ if (typeof view.setBigUint64 === 'function')
806
+ return view.setBigUint64(byteOffset, value, isLE);
807
+ const _32n = BigInt(32);
808
+ const _u32_max = BigInt(0xffffffff);
809
+ const wh = Number((value >> _32n) & _u32_max);
810
+ const wl = Number(value & _u32_max);
811
+ const h = isLE ? 4 : 0;
812
+ const l = isLE ? 0 : 4;
813
+ view.setUint32(byteOffset + h, wh, isLE);
814
+ view.setUint32(byteOffset + l, wl, isLE);
952
815
  }
953
-
954
816
  /**
955
- * Checks if a given JWT has expired.
956
- *
957
- * @param jwt - The JWT string to check. If null, the function will return true.
958
- * @returns `true` if the JWT has expired or is null, otherwise `false`.
817
+ * Choice: a ? b : c
959
818
  */
960
- function jwtHasExpired(jwt) {
961
- if (!jwt) {
962
- return true;
963
- }
964
- return millisecondsToJWTTimeout(jwt) <= 0;
965
- }
819
+ const Chi = (a, b, c) => (a & b) ^ (~a & c);
966
820
  /**
967
- * Calculates the remaining time in milliseconds until a given JWT expires.
968
- *
969
- * @param jwt - The JWT string to decode and check.
970
- * @returns The number of milliseconds until the JWT expires. If the JWT has already expired, the returned value will be less than or equal to 0.
821
+ * Majority function, true if any two inputs is true
971
822
  */
972
- function millisecondsToJWTTimeout(jwt) {
973
- var jwtDecoded = jwtDecode.jwtDecode(jwt);
974
- var jwtExpirationTimeSeconds = jwtDecoded.exp;
975
- var jwtExpirationTimeMilliseconds = (jwtExpirationTimeSeconds !== null && jwtExpirationTimeSeconds !== void 0 ? jwtExpirationTimeSeconds : 0) * 1000;
976
- var timeNowMilliseconds = Date.now();
977
- return jwtExpirationTimeMilliseconds - timeNowMilliseconds;
978
- }
979
-
980
- var Base = /** @class */ (function () {
981
- function Base(config) {
982
- var _a;
983
- this.apiKey = config.apiKey;
984
- this.baseUrl = config.baseUrl;
985
- this.userId = config.userId;
986
- this.clientAuthToken = (_a = config.clientAuthToken) !== null && _a !== void 0 ? _a : config === null || config === void 0 ? void 0 : config.jwt;
987
- this.options = config.options;
823
+ const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
824
+ /**
825
+ * Merkle-Damgard hash construction base class.
826
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
827
+ */
828
+ class HashMD extends Hash {
829
+ constructor(blockLen, outputLen, padOffset, isLE) {
830
+ super();
831
+ this.blockLen = blockLen;
832
+ this.outputLen = outputLen;
833
+ this.padOffset = padOffset;
834
+ this.isLE = isLE;
835
+ this.finished = false;
836
+ this.length = 0;
837
+ this.pos = 0;
838
+ this.destroyed = false;
839
+ this.buffer = new Uint8Array(blockLen);
840
+ this.view = createView(this.buffer);
988
841
  }
989
- Object.defineProperty(Base.prototype, "deviceStorage", {
990
- /**
991
- * This library uses `localStorage` as the default storage.
992
- * If you want to use a different storage, you can pass it in the options object of the Wallaby config.
993
- * storage: new CustomStorage()
994
- * {
995
- * }
996
- */
997
- get: function () {
998
- var _a;
999
- if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.storage) {
1000
- return this.options.storage;
1001
- }
1002
- if (window && window.localStorage) {
1003
- return window.localStorage;
842
+ update(data) {
843
+ exists(this);
844
+ const { view, buffer, blockLen } = this;
845
+ data = toBytes(data);
846
+ const len = data.length;
847
+ for (let pos = 0; pos < len;) {
848
+ const take = Math.min(blockLen - this.pos, len - pos);
849
+ // Fast path: we have at least one block in input, cast it to view and process
850
+ if (take === blockLen) {
851
+ const dataView = createView(data);
852
+ for (; blockLen <= len - pos; pos += blockLen)
853
+ this.process(dataView, pos);
854
+ continue;
1004
855
  }
1005
- throw new Error('Your device storage is not supported natively yet, please provide a custom storage in the config options.');
1006
- },
1007
- enumerable: false,
1008
- configurable: true
1009
- });
1010
- Object.defineProperty(Base.prototype, "device", {
1011
- /**
1012
- * @protected
1013
- */
1014
- get: function () {
1015
- return this.storageService.loadDeviceInformation();
1016
- },
1017
- enumerable: false,
1018
- configurable: true
1019
- });
1020
- Object.defineProperty(Base.prototype, "settings", {
1021
- /**
1022
- * @private
1023
- */
1024
- get: function () {
1025
- var _a, _b, _c, _d;
1026
- return {
1027
- apiKey: this.apiKey,
1028
- baseUrl: this.baseUrl,
1029
- environment: (_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.environment) !== null && _b !== void 0 ? _b : defaultEnvironment,
1030
- network: (_d = (_c = this.options) === null || _c === void 0 ? void 0 : _c.network) !== null && _d !== void 0 ? _d : defaultNetwork,
1031
- };
1032
- },
1033
- enumerable: false,
1034
- configurable: true
1035
- });
1036
- Object.defineProperty(Base.prototype, "storageService", {
1037
- /**
1038
- * @protected
1039
- */
1040
- get: function () {
1041
- if (!this.clientAuthToken) {
1042
- throw new Error('A client authentication token (JWT) is required');
1043
- }
1044
- return new StorageService({
1045
- deviceStorage: this.deviceStorage,
1046
- userId: this.userId,
1047
- environment: this.settings.environment,
1048
- });
1049
- },
1050
- enumerable: false,
1051
- configurable: true
1052
- });
1053
- /**
1054
- *
1055
- * This is the main request method that is used to make requests to the Wallaby API.
1056
- * @param { RequestRoute } route full route object to the request endpoint.
1057
- * @param { RequestOptions } options Extends the `RequestInit` interface to include a payload and queryParams.
1058
- * @returns Promise of <T> where T is the type of the response.
1059
- */
1060
- Base.prototype.request = function (route, options) {
1061
- return __awaiter(this, void 0, void 0, function () {
1062
- var url, headers, http, _a, result, error_1, result, error_2, result, error_3, result, error_4, error_5;
1063
- var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
1064
- return __generator(this, function (_m) {
1065
- switch (_m.label) {
1066
- case 0:
1067
- _m.trys.push([0, 16, , 17]);
1068
- url = void 0;
1069
- if (typeof route.fullPath !== 'string') {
1070
- url = route.fullPath(options === null || options === void 0 ? void 0 : options.payload);
1071
- }
1072
- else {
1073
- url = route.fullPath;
1074
- }
1075
- if (options === null || options === void 0 ? void 0 : options.queryParams) {
1076
- url += "?".concat(objectToQueryParams(options.queryParams));
1077
- }
1078
- return [4 /*yield*/, this.getRequestHeaders(route.requiresAccessToken)];
1079
- case 1:
1080
- headers = _m.sent();
1081
- if ((_b = this.options) === null || _b === void 0 ? void 0 : _b.headers) {
1082
- headers = __assign(__assign({}, headers), this.options.headers);
1083
- }
1084
- http = axios__default.default.create({
1085
- url: url,
1086
- baseURL: this.baseUrl,
1087
- headers: headers,
1088
- });
1089
- http.interceptors.response.use(function (response) { return response; }, function (error) {
1090
- var _a, _b;
1091
- if ((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) {
1092
- return Promise.reject((_b = error === null || error === void 0 ? void 0 : error.response) === null || _b === void 0 ? void 0 : _b.data);
1093
- }
1094
- logger.error('SDK::Base::Interceptor::error', error);
1095
- return Promise.reject(error);
1096
- });
1097
- _a = route.method;
1098
- switch (_a) {
1099
- case exports.RequestMethod.Get: return [3 /*break*/, 2];
1100
- case exports.RequestMethod.Post: return [3 /*break*/, 5];
1101
- case exports.RequestMethod.Put: return [3 /*break*/, 8];
1102
- case exports.RequestMethod.Delete: return [3 /*break*/, 11];
1103
- }
1104
- return [3 /*break*/, 14];
1105
- case 2:
1106
- _m.trys.push([2, 4, , 5]);
1107
- return [4 /*yield*/, http.get(url)];
1108
- case 3:
1109
- result = _m.sent();
1110
- logger.info('SDK::Base::RequestMethod.Get::result.data', result === null || result === void 0 ? void 0 : result.data);
1111
- return [2 /*return*/, result === null || result === void 0 ? void 0 : result.data];
1112
- case 4:
1113
- error_1 = _m.sent();
1114
- if (error_1 instanceof axios.AxiosError) {
1115
- logger.error('SDK::Base::RequestMethod.Get::error', (_c = error_1 === null || error_1 === void 0 ? void 0 : error_1.response) === null || _c === void 0 ? void 0 : _c.data);
1116
- return [2 /*return*/, Promise.reject((_d = error_1 === null || error_1 === void 0 ? void 0 : error_1.response) === null || _d === void 0 ? void 0 : _d.data)];
1117
- }
1118
- return [2 /*return*/, Promise.reject(error_1 === null || error_1 === void 0 ? void 0 : error_1.message)];
1119
- case 5:
1120
- _m.trys.push([5, 7, , 8]);
1121
- return [4 /*yield*/, http.post(url, JSON.stringify(options === null || options === void 0 ? void 0 : options.payload))];
1122
- case 6:
1123
- result = _m.sent();
1124
- logger.info('SDK::Base::RequestMethod.Post::result.data', result === null || result === void 0 ? void 0 : result.data);
1125
- return [2 /*return*/, result === null || result === void 0 ? void 0 : result.data];
1126
- case 7:
1127
- error_2 = _m.sent();
1128
- if (error_2 instanceof axios.AxiosError) {
1129
- logger.error('SDK::Base::RequestMethod.Post::error', (_e = error_2 === null || error_2 === void 0 ? void 0 : error_2.response) === null || _e === void 0 ? void 0 : _e.data);
1130
- return [2 /*return*/, Promise.reject((_f = error_2 === null || error_2 === void 0 ? void 0 : error_2.response) === null || _f === void 0 ? void 0 : _f.data)];
1131
- }
1132
- return [2 /*return*/, Promise.reject(error_2 === null || error_2 === void 0 ? void 0 : error_2.message)];
1133
- case 8:
1134
- _m.trys.push([8, 10, , 11]);
1135
- return [4 /*yield*/, http.put(url, (_g = JSON.stringify(options === null || options === void 0 ? void 0 : options.payload)) !== null && _g !== void 0 ? _g : null)];
1136
- case 9:
1137
- result = _m.sent();
1138
- logger.info('SDK::Base::RequestMethod.Put::result.data', result.data);
1139
- return [2 /*return*/, result === null || result === void 0 ? void 0 : result.data];
1140
- case 10:
1141
- error_3 = _m.sent();
1142
- if (error_3 instanceof axios.AxiosError) {
1143
- logger.error('SDK::Base::RequestMethod.Put::error', (_h = error_3 === null || error_3 === void 0 ? void 0 : error_3.response) === null || _h === void 0 ? void 0 : _h.data);
1144
- return [2 /*return*/, Promise.reject((_j = error_3 === null || error_3 === void 0 ? void 0 : error_3.response) === null || _j === void 0 ? void 0 : _j.data)];
1145
- }
1146
- return [2 /*return*/, Promise.reject(error_3 === null || error_3 === void 0 ? void 0 : error_3.message)];
1147
- case 11:
1148
- _m.trys.push([11, 13, , 14]);
1149
- return [4 /*yield*/, http.delete(url)];
1150
- case 12:
1151
- result = _m.sent();
1152
- logger.info('SDK::Base::RequestMethod.Delete::result.data', result.data);
1153
- return [2 /*return*/, result === null || result === void 0 ? void 0 : result.data];
1154
- case 13:
1155
- error_4 = _m.sent();
1156
- if (error_4 instanceof axios.AxiosError) {
1157
- logger.error('SDK::Base::RequestMethod.Delete::error', (_k = error_4 === null || error_4 === void 0 ? void 0 : error_4.response) === null || _k === void 0 ? void 0 : _k.data);
1158
- return [2 /*return*/, Promise.reject((_l = error_4 === null || error_4 === void 0 ? void 0 : error_4.response) === null || _l === void 0 ? void 0 : _l.data)];
1159
- }
1160
- return [2 /*return*/, Promise.reject(error_4 === null || error_4 === void 0 ? void 0 : error_4.message)];
1161
- case 14: throw new Error('Request method is not supported');
1162
- case 15: return [3 /*break*/, 17];
1163
- case 16:
1164
- error_5 = _m.sent();
1165
- logger.error('SDK::Base::request::error', error_5);
1166
- return [2 /*return*/, Promise.reject(error_5)];
1167
- case 17: return [2 /*return*/];
1168
- }
1169
- });
1170
- });
1171
- };
1172
- Base.prototype.getRequestHeaders = function (requiresAccessToken) {
1173
- return __awaiter(this, void 0, void 0, function () {
1174
- var accessToken, headers;
1175
- return __generator(this, function (_a) {
1176
- switch (_a.label) {
1177
- case 0: return [4 /*yield*/, this.device];
1178
- case 1:
1179
- accessToken = (_a.sent()).authTokens.accessToken;
1180
- if (!isTest && jwtHasExpired(this.clientAuthToken)) {
1181
- throw new Error('Auth token has expired - blocking API call.');
1182
- }
1183
- headers = {
1184
- 'Content-Type': 'application/json',
1185
- 'x-api-key': this.settings.apiKey,
1186
- 'x-client-jwt': this.clientAuthToken,
1187
- };
1188
- if (requiresAccessToken && this.userId) {
1189
- // if (!isTest && (!accessToken || jwtHasExpired(accessToken))) {
1190
- // throw new Error('Access token has expired, please sign in to continue.');
1191
- // }
1192
- headers = __assign(__assign({}, headers), { Authorization: 'Bearer ' + accessToken });
1193
- }
1194
- return [2 /*return*/, headers];
1195
- }
1196
- });
1197
- });
1198
- };
1199
- return Base;
1200
- }());
1201
-
1202
- var WalletRoutes = {
1203
- importSeedPhraseV2: {
1204
- fullPath: '/wallets/create-shares-based-wallet-from-seed',
1205
- method: exports.RequestMethod.Post,
1206
- requiresAccessToken: true,
1207
- },
1208
- initKeyExchange: {
1209
- fullPath: '/mpc/init-key-exchange',
1210
- method: exports.RequestMethod.Post,
1211
- requiresAccessToken: true,
1212
- },
1213
- retrieveSeedPhrase: {
1214
- fullPath: '/mpc/reconstruct-seed-phrase',
1215
- method: exports.RequestMethod.Post,
1216
- requiresAccessToken: true,
1217
- },
1218
- createWithKeyShares: {
1219
- fullPath: '/wallets/create-with-shares',
1220
- method: exports.RequestMethod.Post,
1221
- requiresAccessToken: true,
1222
- },
1223
- retrieveShares: {
1224
- fullPath: '/wallets/retrieve-shares',
1225
- method: exports.RequestMethod.Post,
1226
- requiresAccessToken: true,
1227
- },
1228
- create: {
1229
- fullPath: '/wallets/create',
1230
- method: exports.RequestMethod.Post,
1231
- requiresAccessToken: true,
1232
- },
1233
- import: {
1234
- fullPath: '/wallets/import-seed-phrase',
1235
- method: exports.RequestMethod.Post,
1236
- requiresAccessToken: true,
1237
- },
1238
- initRecoveryFlow: {
1239
- fullPath: 'wallets/recover/init',
1240
- method: exports.RequestMethod.Post,
1241
- requiresAccessToken: false,
1242
- },
1243
- recover: {
1244
- fullPath: '/wallets/recover',
1245
- method: exports.RequestMethod.Post,
1246
- requiresAccessToken: false,
1247
- },
1248
- getTokenBalance: {
1249
- fullPath: function (_a) {
1250
- var address = _a.address, symbol = _a.symbol, chainName = _a.chainName, tokenStandard = _a.tokenStandard;
1251
- return ("/query/assets/balance?address=".concat(address, "&assetSymbol=").concat(symbol) +
1252
- "".concat(tokenStandard ? "&tokenType=".concat(tokenStandard) : '') +
1253
- "".concat(chainName ? "&chainName=".concat(chainName) : ''));
1254
- },
1255
- method: exports.RequestMethod.Get,
1256
- requiresAccessToken: false,
1257
- },
1258
- getMultiTokenBalances: {
1259
- fullPath: '/query/assets/bulk-balance',
1260
- method: exports.RequestMethod.Post,
1261
- requiresAccessToken: false,
1262
- },
1263
- getWalletBalances: {
1264
- fullPath: '/query/assets/wallet-bulk-balance',
1265
- method: exports.RequestMethod.Post,
1266
- requiresAccessToken: false,
1267
- },
1268
- getWalletAssets: {
1269
- fullPath: function (_a) {
1270
- var walletId = _a.walletId;
1271
- return "/wallets/".concat(walletId, "/assets");
1272
- },
1273
- method: exports.RequestMethod.Get,
1274
- requiresAccessToken: true,
1275
- },
1276
- getUserAssets: {
1277
- fullPath: function (_a) {
1278
- var userId = _a.userId;
1279
- return "/users/".concat(userId, "/assets");
1280
- },
1281
- method: exports.RequestMethod.Get,
1282
- requiresAccessToken: true,
1283
- },
1284
- addTokenToWallet: {
1285
- fullPath: '/users/assets/add',
1286
- method: exports.RequestMethod.Post,
1287
- requiresAccessToken: true,
1288
- },
1289
- updateAsset: {
1290
- fullPath: '/wallets/asset/update',
1291
- method: exports.RequestMethod.Put,
1292
- requiresAccessToken: true,
1293
- },
1294
- getUserWallets: {
1295
- fullPath: function (_a) {
1296
- var userId = _a.userId;
1297
- return "/users/".concat(userId, "/wallets");
1298
- },
1299
- method: exports.RequestMethod.Get,
1300
- requiresAccessToken: true,
1301
- },
1302
- convertMnemonicSeedPhrase: {
1303
- fullPath: '/wallets/convert-mnemonic-seed',
1304
- method: exports.RequestMethod.Post,
1305
- requiresAccessToken: false,
1306
- },
1307
- createMultisigAsset: {
1308
- fullPath: '/wallets/create-multisig-asset',
1309
- method: exports.RequestMethod.Post,
1310
- requiresAccessToken: true,
1311
- },
1312
- };
1313
-
1314
- var AuthRoutes = {
1315
- signatureMessage: {
1316
- fullPath: '/auth/signature-message',
1317
- method: exports.RequestMethod.Post,
1318
- requiresAccessToken: false,
1319
- },
1320
- signIn: {
1321
- fullPath: '/auth/sign-in',
1322
- method: exports.RequestMethod.Post,
1323
- requiresAccessToken: true,
1324
- },
1325
- signUp: {
1326
- fullPath: '/auth/sign-up',
1327
- method: exports.RequestMethod.Post,
1328
- requiresAccessToken: false,
1329
- },
1330
- refreshAccessToken: {
1331
- fullPath: '/auth/refresh-access-token',
1332
- method: exports.RequestMethod.Post,
1333
- requiresAccessToken: true,
1334
- },
1335
- clientAuthPubKey: {
1336
- fullPath: 'auth/client-auth-pubkey',
1337
- method: exports.RequestMethod.Put,
1338
- requiresAccessToken: true,
1339
- },
1340
- wallabyAuthPublicKey: {
1341
- fullPath: '/auth/wallaby-auth-pubkey',
1342
- method: exports.RequestMethod.Get,
1343
- requiresAccessToken: true,
1344
- },
1345
- getUserSalt: {
1346
- fullPath: '/users/salt',
1347
- method: exports.RequestMethod.Get,
1348
- requiresAccessToken: true,
1349
- },
1350
- };
1351
-
1352
- var SystemRoutes = {
1353
- getSupportedBlockchains: {
1354
- fullPath: '/chains',
1355
- method: exports.RequestMethod.Get,
1356
- requiresAccessToken: false,
1357
- },
1358
- getSupportedTokens: {
1359
- fullPath: '/assets/configurations',
1360
- method: exports.RequestMethod.Get,
1361
- requiresAccessToken: false,
1362
- },
1363
- getUserByExternalUserId: {
1364
- fullPath: function (_a) {
1365
- var externalUserId = _a.externalUserId;
1366
- return "/users/".concat(externalUserId, "/externalUserId");
1367
- },
1368
- method: exports.RequestMethod.Get,
1369
- requiresAccessToken: false,
1370
- },
1371
- getUserData: {
1372
- fullPath: function (_a) {
1373
- var userId = _a.userId;
1374
- return "/users/".concat(userId);
1375
- },
1376
- method: exports.RequestMethod.Get,
1377
- requiresAccessToken: false,
1378
- },
1379
- fetchTokenInfo: {
1380
- fullPath: function () { return "/query/fetch-token-info"; },
1381
- method: exports.RequestMethod.Get,
1382
- requiresAccessToken: false,
1383
- },
1384
- };
1385
-
1386
- function getRandomBytesSync(bytes) {
1387
- return randomBytes(bytes);
1388
- }
1389
-
1390
- /**
1391
- * Returns a `Boolean` on whether or not the a `String` starts with '0x'
1392
- * @param str the string input value
1393
- * @return a boolean if it is or is not hex prefixed
1394
- * @throws if the str input is not a string
1395
- */
1396
- var isHexPrefixed = function (str) {
1397
- if (typeof str !== 'string') {
1398
- throw new Error("[isHexPrefixed] input must be type 'string', received type ".concat(typeof str));
1399
- }
1400
- return str[0] === '0' && str[1] === 'x';
1401
- };
1402
- /**
1403
- * Removes '0x' from a given `String` if present
1404
- * @param str the string value
1405
- * @returns the string without 0x prefix
1406
- */
1407
- var stripHexPrefix = function (str) {
1408
- if (typeof str !== 'string')
1409
- throw new Error("[stripHexPrefix] input must be type 'string', received ".concat(typeof str));
1410
- return isHexPrefixed(str) ? str.slice(2) : str;
1411
- };
1412
- /**
1413
- * Adds '0x' to a given `String` if not present
1414
- * @param str the string input value
1415
- * @return the string with a 0x prefix
1416
- */
1417
- var addLeading0x = function (str) {
1418
- if (!str.startsWith('0x'))
1419
- return '0x' + str;
1420
- else
1421
- return str;
1422
- };
1423
- var decompress = function (startsWith02Or03) {
1424
- var testByteArray = hexToBytes$1(startsWith02Or03);
1425
- var startsWith04 = startsWith02Or03;
1426
- if (testByteArray.length === 64) {
1427
- startsWith04 = '04' + startsWith02Or03;
1428
- }
1429
- return startsWith04.substring(2);
1430
- };
1431
- /** Helper function to concat UInt8Arrays mimicking the behaviour of the
1432
- * Buffer.concat function in Node.js
1433
- */
1434
- var concatUint8Arrays = function (uint8arrays) {
1435
- var totalLength = uint8arrays.reduce(function (total, uint8array) { return total + uint8array.byteLength; }, 0);
1436
- var result = new Uint8Array(totalLength);
1437
- var offset = 0;
1438
- uint8arrays.forEach(function (uint8array) {
1439
- result.set(uint8array, offset);
1440
- offset += uint8array.byteLength;
1441
- });
1442
- return result;
1443
- };
1444
- /**
1445
- * Converts a UTF-8 string to a Uint8Array without using TextEncoder, which is not available in mobile
1446
- * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
1447
- */
1448
- var utf8ToBytes$1 = function (str) {
1449
- if (typeof str !== 'string')
1450
- throw new Error("utf8ToBytes expected string, got ".concat(typeof str));
1451
- var bytes = [];
1452
- for (var i = 0; i < str.length; i++) {
1453
- var codePoint = str.codePointAt(i);
1454
- if (!codePoint) {
1455
- throw new Error('Invalid code point');
1456
- }
1457
- if (codePoint < 0x80) {
1458
- bytes.push(codePoint);
1459
- }
1460
- else if (codePoint < 0x800) {
1461
- bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f));
1462
- }
1463
- else if (codePoint < 0x10000) {
1464
- bytes.push(0xe0 | (codePoint >> 12), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
1465
- }
1466
- else {
1467
- i++; // skip one iteration since we have a surrogate pair
1468
- bytes.push(0xf0 | (codePoint >> 18), 0x80 | ((codePoint >> 12) & 0x3f), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
1469
- }
1470
- }
1471
- return new Uint8Array(bytes);
1472
- };
1473
-
1474
- /**
1475
- * Polyfill for Safari 14
1476
- */
1477
- function setBigUint64(view, byteOffset, value, isLE) {
1478
- if (typeof view.setBigUint64 === 'function')
1479
- return view.setBigUint64(byteOffset, value, isLE);
1480
- const _32n = BigInt(32);
1481
- const _u32_max = BigInt(0xffffffff);
1482
- const wh = Number((value >> _32n) & _u32_max);
1483
- const wl = Number(value & _u32_max);
1484
- const h = isLE ? 4 : 0;
1485
- const l = isLE ? 0 : 4;
1486
- view.setUint32(byteOffset + h, wh, isLE);
1487
- view.setUint32(byteOffset + l, wl, isLE);
1488
- }
1489
- /**
1490
- * Choice: a ? b : c
1491
- */
1492
- const Chi = (a, b, c) => (a & b) ^ (~a & c);
1493
- /**
1494
- * Majority function, true if any two inputs is true
1495
- */
1496
- const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
1497
- /**
1498
- * Merkle-Damgard hash construction base class.
1499
- * Could be used to create MD5, RIPEMD, SHA1, SHA2.
1500
- */
1501
- class HashMD extends Hash {
1502
- constructor(blockLen, outputLen, padOffset, isLE) {
1503
- super();
1504
- this.blockLen = blockLen;
1505
- this.outputLen = outputLen;
1506
- this.padOffset = padOffset;
1507
- this.isLE = isLE;
1508
- this.finished = false;
1509
- this.length = 0;
1510
- this.pos = 0;
1511
- this.destroyed = false;
1512
- this.buffer = new Uint8Array(blockLen);
1513
- this.view = createView(this.buffer);
1514
- }
1515
- update(data) {
1516
- exists(this);
1517
- const { view, buffer, blockLen } = this;
1518
- data = toBytes(data);
1519
- const len = data.length;
1520
- for (let pos = 0; pos < len;) {
1521
- const take = Math.min(blockLen - this.pos, len - pos);
1522
- // Fast path: we have at least one block in input, cast it to view and process
1523
- if (take === blockLen) {
1524
- const dataView = createView(data);
1525
- for (; blockLen <= len - pos; pos += blockLen)
1526
- this.process(dataView, pos);
1527
- continue;
1528
- }
1529
- buffer.set(data.subarray(pos, pos + take), this.pos);
1530
- this.pos += take;
1531
- pos += take;
1532
- if (this.pos === blockLen) {
1533
- this.process(view, 0);
1534
- this.pos = 0;
856
+ buffer.set(data.subarray(pos, pos + take), this.pos);
857
+ this.pos += take;
858
+ pos += take;
859
+ if (this.pos === blockLen) {
860
+ this.process(view, 0);
861
+ this.pos = 0;
1535
862
  }
1536
863
  }
1537
864
  this.length += data.length;
@@ -4577,298 +3904,1308 @@ function ctrCounter(xk, nonce, src, dst) {
4577
3904
  }
4578
3905
  ({ s0, s1, s2, s3 } = encrypt$2(xk, c32[0], c32[1], c32[2], c32[3]));
4579
3906
  }
4580
- // leftovers (less than block)
4581
- // It's possible to handle > u32 fast, but is it worth it?
4582
- const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
4583
- if (start < srcLen) {
4584
- const b32 = new Uint32Array([s0, s1, s2, s3]);
4585
- const buf = u8(b32);
4586
- for (let i = start, pos = 0; i < srcLen; i++, pos++)
4587
- dst[i] = src[i] ^ buf[pos];
4588
- clean(b32);
3907
+ // leftovers (less than block)
3908
+ // It's possible to handle > u32 fast, but is it worth it?
3909
+ const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
3910
+ if (start < srcLen) {
3911
+ const b32 = new Uint32Array([s0, s1, s2, s3]);
3912
+ const buf = u8(b32);
3913
+ for (let i = start, pos = 0; i < srcLen; i++, pos++)
3914
+ dst[i] = src[i] ^ buf[pos];
3915
+ clean(b32);
3916
+ }
3917
+ return dst;
3918
+ }
3919
+ /**
3920
+ * CTR: counter mode. Creates stream cipher.
3921
+ * Requires good IV. Parallelizable. OK, but no MAC.
3922
+ */
3923
+ const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) {
3924
+ bytes(key);
3925
+ bytes(nonce, BLOCK_SIZE);
3926
+ function processCtr(buf, dst) {
3927
+ bytes(buf);
3928
+ if (dst !== undefined) {
3929
+ bytes(dst);
3930
+ if (!isAligned32(dst))
3931
+ throw new Error('unaligned destination');
3932
+ }
3933
+ const xk = expandKeyLE(key);
3934
+ const n = copyBytes(nonce); // align + avoid changing
3935
+ const toClean = [xk, n];
3936
+ if (!isAligned32(buf))
3937
+ toClean.push((buf = copyBytes(buf)));
3938
+ const out = ctrCounter(xk, n, buf, dst);
3939
+ clean(...toClean);
3940
+ return out;
3941
+ }
3942
+ return {
3943
+ encrypt: (plaintext, dst) => processCtr(plaintext, dst),
3944
+ decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),
3945
+ };
3946
+ });
3947
+ function validateBlockDecrypt(data) {
3948
+ bytes(data);
3949
+ if (data.length % BLOCK_SIZE !== 0) {
3950
+ throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`);
3951
+ }
3952
+ }
3953
+ function validateBlockEncrypt(plaintext, pcks5, dst) {
3954
+ bytes(plaintext);
3955
+ let outLen = plaintext.length;
3956
+ const remaining = outLen % BLOCK_SIZE;
3957
+ if (!pcks5 && remaining !== 0)
3958
+ throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');
3959
+ if (!isAligned32(plaintext))
3960
+ plaintext = copyBytes(plaintext);
3961
+ const b = u32(plaintext);
3962
+ if (pcks5) {
3963
+ let left = BLOCK_SIZE - remaining;
3964
+ if (!left)
3965
+ left = BLOCK_SIZE; // if no bytes left, create empty padding block
3966
+ outLen = outLen + left;
3967
+ }
3968
+ const out = getDst(outLen, dst);
3969
+ const o = u32(out);
3970
+ return { b, o, out };
3971
+ }
3972
+ function validatePCKS(data, pcks5) {
3973
+ if (!pcks5)
3974
+ return data;
3975
+ const len = data.length;
3976
+ if (!len)
3977
+ throw new Error('aes/pcks5: empty ciphertext not allowed');
3978
+ const lastByte = data[len - 1];
3979
+ if (lastByte <= 0 || lastByte > 16)
3980
+ throw new Error('aes/pcks5: wrong padding');
3981
+ const out = data.subarray(0, -lastByte);
3982
+ for (let i = 0; i < lastByte; i++)
3983
+ if (data[len - i - 1] !== lastByte)
3984
+ throw new Error('aes/pcks5: wrong padding');
3985
+ return out;
3986
+ }
3987
+ function padPCKS(left) {
3988
+ const tmp = new Uint8Array(16);
3989
+ const tmp32 = u32(tmp);
3990
+ tmp.set(left);
3991
+ const paddingByte = BLOCK_SIZE - left.length;
3992
+ for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)
3993
+ tmp[i] = paddingByte;
3994
+ return tmp32;
3995
+ }
3996
+ /**
3997
+ * CBC: Cipher-Block-Chaining. Key is previous round’s block.
3998
+ * Fragile: needs proper padding. Unauthenticated: needs MAC.
3999
+ */
4000
+ const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) {
4001
+ bytes(key);
4002
+ bytes(iv, 16);
4003
+ const pcks5 = !opts.disablePadding;
4004
+ return {
4005
+ encrypt(plaintext, dst) {
4006
+ const xk = expandKeyLE(key);
4007
+ const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);
4008
+ let _iv = iv;
4009
+ const toClean = [xk];
4010
+ if (!isAligned32(_iv))
4011
+ toClean.push((_iv = copyBytes(_iv)));
4012
+ const n32 = u32(_iv);
4013
+ // prettier-ignore
4014
+ let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
4015
+ let i = 0;
4016
+ for (; i + 4 <= b.length;) {
4017
+ (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);
4018
+ ({ s0, s1, s2, s3 } = encrypt$2(xk, s0, s1, s2, s3));
4019
+ (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
4020
+ }
4021
+ if (pcks5) {
4022
+ const tmp32 = padPCKS(plaintext.subarray(i * 4));
4023
+ (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);
4024
+ ({ s0, s1, s2, s3 } = encrypt$2(xk, s0, s1, s2, s3));
4025
+ (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
4026
+ }
4027
+ clean(...toClean);
4028
+ return _out;
4029
+ },
4030
+ decrypt(ciphertext, dst) {
4031
+ validateBlockDecrypt(ciphertext);
4032
+ const xk = expandKeyDecLE(key);
4033
+ let _iv = iv;
4034
+ const toClean = [xk];
4035
+ if (!isAligned32(_iv))
4036
+ toClean.push((_iv = copyBytes(_iv)));
4037
+ const n32 = u32(_iv);
4038
+ const out = getDst(ciphertext.length, dst);
4039
+ if (!isAligned32(ciphertext))
4040
+ toClean.push((ciphertext = copyBytes(ciphertext)));
4041
+ const b = u32(ciphertext);
4042
+ const o = u32(out);
4043
+ // prettier-ignore
4044
+ let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
4045
+ for (let i = 0; i + 4 <= b.length;) {
4046
+ // prettier-ignore
4047
+ const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;
4048
+ (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);
4049
+ const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt$2(xk, s0, s1, s2, s3);
4050
+ (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);
4051
+ }
4052
+ clean(...toClean);
4053
+ return validatePCKS(out, pcks5);
4054
+ },
4055
+ };
4056
+ });
4057
+ new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6
4058
+
4059
+ function getCipher(key, iv, mode, pkcs7PaddingEnabled = true) {
4060
+ if (!mode.startsWith("aes-")) {
4061
+ throw new Error("AES: unsupported mode");
4062
+ }
4063
+ const len = key.length;
4064
+ if ((mode.startsWith("aes-128") && len !== 16) || (mode.startsWith("aes-256") && len !== 32)) {
4065
+ throw new Error("AES: wrong key length");
4066
+ }
4067
+ if (iv.length !== 16) {
4068
+ throw new Error("AES: wrong IV length");
4069
+ }
4070
+ if (["aes-128-cbc", "aes-256-cbc"].includes(mode)) {
4071
+ return cbc(key, iv, { disablePadding: !pkcs7PaddingEnabled });
4072
+ }
4073
+ if (["aes-128-ctr", "aes-256-ctr"].includes(mode)) {
4074
+ return ctr(key, iv);
4075
+ }
4076
+ throw new Error("AES: unsupported mode");
4077
+ }
4078
+ function encrypt$1(msg, key, iv, mode = "aes-128-ctr", pkcs7PaddingEnabled = true) {
4079
+ return getCipher(key, iv, mode, pkcs7PaddingEnabled).encrypt(msg);
4080
+ }
4081
+ function decrypt$1(ciphertext, key, iv, mode = "aes-128-ctr", pkcs7PaddingEnabled = true) {
4082
+ return getCipher(key, iv, mode, pkcs7PaddingEnabled).decrypt(ciphertext);
4083
+ }
4084
+
4085
+ /**
4086
+ * See https://github.com/bitchan/eccrypto for the original implementation that eth-crypto used, it's ancient and not maintained.
4087
+ */
4088
+ /**
4089
+ * Encrypts a message using the recipient's public key.
4090
+ * @param {string} publicKeyTo - The recipient's public key.
4091
+ * @param {string} msg - The message to encrypt.
4092
+ * @returns {Encrypted} The encrypted message.
4093
+ */
4094
+ var encrypt = function (publicKeyTo, msg, options) {
4095
+ var ephemPrivateKey = (options === null || options === void 0 ? void 0 : options.ephemPrivateKey) ? hexToBytes$1(options.ephemPrivateKey) : getRandomBytesSync(32);
4096
+ var iv = (options === null || options === void 0 ? void 0 : options.iv) ? hexToBytes$1(options.iv) : getRandomBytesSync(16);
4097
+ var ephemPublicKey = secp256k1.getPublicKey(ephemPrivateKey, false);
4098
+ var sharedSecret = secp256k1.getSharedSecret(ephemPrivateKey, hexToBytes$1(publicKeyTo), true).slice(1);
4099
+ var hash = sha512(sharedSecret);
4100
+ var encryptionKey = hash.subarray(0, 32);
4101
+ var macKey = hash.subarray(32);
4102
+ var message = utf8ToBytes$1(msg);
4103
+ var data = encrypt$1(message, encryptionKey, iv, 'aes-256-cbc');
4104
+ var dataToMac = concatUint8Arrays([iv, ephemPublicKey, data]);
4105
+ var mac = hmacSha256Sign(macKey, dataToMac);
4106
+ return {
4107
+ iv: bytesToHex$1(iv),
4108
+ ephemPublicKey: bytesToHex$1(ephemPublicKey),
4109
+ ciphertext: bytesToHex$1(data),
4110
+ mac: bytesToHex$1(mac),
4111
+ };
4112
+ };
4113
+ /**
4114
+ * Decrypts an encrypted message using the recipient's private key.
4115
+ * @param {string} privateKey - The recipient's private key.
4116
+ * @param {Encrypted} opts - The encrypted message.
4117
+ * @returns {string} The decrypted message.
4118
+ */
4119
+ var decrypt = function (privateKey, opts) {
4120
+ var sharedSecret = secp256k1.getSharedSecret(hexToBytes$1(privateKey), opts.ephemPublicKey, true).slice(1);
4121
+ var hash = sha512(sharedSecret);
4122
+ var encryptionKey = hash.subarray(0, 32);
4123
+ var ciphertext = hexToBytes$1(opts.ciphertext);
4124
+ var iv = hexToBytes$1(opts.iv);
4125
+ var decrypted = decrypt$1(ciphertext, encryptionKey, iv, 'aes-256-cbc');
4126
+ return bytesToUtf8(decrypted);
4127
+ };
4128
+
4129
+ var encryptWithPublicKey = function (publicKey, message, options) {
4130
+ // ensure its an uncompressed publicKey
4131
+ var decompressedKey = decompress(publicKey);
4132
+ // re-add the compression-flag
4133
+ var pubString = '04' + decompressedKey;
4134
+ return encrypt(pubString, message, options);
4135
+ };
4136
+
4137
+ var decryptWithPrivateKey = function (privateKey, encrypted) {
4138
+ // remove '0x' from privateKey
4139
+ var twoStripped = stripHexPrefix(privateKey);
4140
+ return decrypt(twoStripped, encrypted);
4141
+ };
4142
+
4143
+ var solidityPackedKeccak256 = function (value) {
4144
+ var bytes = utf8ToBytes$1(value);
4145
+ var hex = addLeading0x(bytesToHex$1(bytes));
4146
+ var hash = keccak256$1(hexToBytes$1(hex));
4147
+ return addLeading0x(bytesToHex$1(hash));
4148
+ };
4149
+ var keccak256 = function (params) {
4150
+ return solidityPackedKeccak256(params);
4151
+ };
4152
+
4153
+ // Use `secp256k1` module directly.
4154
+ // This is a legacy compatibility layer for the npm package `secp256k1` via noble-secp256k1
4155
+ secp256k1.ProjectivePoint;
4156
+ secp256k1.CURVE.n;
4157
+ function output(out = (len) => new Uint8Array(len), length, value) {
4158
+ if (typeof out === "function") {
4159
+ out = out(length);
4160
+ }
4161
+ assertBytes(out, length);
4162
+ if (value) {
4163
+ out.set(value);
4589
4164
  }
4590
- return dst;
4165
+ return out;
4166
+ }
4167
+ function getSignature(signature) {
4168
+ assertBytes(signature, 64);
4169
+ return secp256k1.Signature.fromCompact(signature);
4170
+ }
4171
+ function ecdsaRecover(signature, recid, msgHash, compressed = true, out) {
4172
+ assertBytes(msgHash, 32);
4173
+ assertBool(compressed);
4174
+ const sign = getSignature(signature);
4175
+ const point = sign.addRecoveryBit(recid).recoverPublicKey(msgHash);
4176
+ return output(out, compressed ? 33 : 65, point.toRawBytes(compressed));
4591
4177
  }
4178
+
4592
4179
  /**
4593
- * CTR: counter mode. Creates stream cipher.
4594
- * Requires good IV. Parallelizable. OK, but no MAC.
4180
+ * returns the publicKey for the privateKey with which the messageHash was signed
4181
+ * @param {string} signature
4182
+ * @param {string} hash
4183
+ * @return {string} publicKey
4595
4184
  */
4596
- const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) {
4597
- bytes(key);
4598
- bytes(nonce, BLOCK_SIZE);
4599
- function processCtr(buf, dst) {
4600
- bytes(buf);
4601
- if (dst !== undefined) {
4602
- bytes(dst);
4603
- if (!isAligned32(dst))
4604
- throw new Error('unaligned destination');
4605
- }
4606
- const xk = expandKeyLE(key);
4607
- const n = copyBytes(nonce); // align + avoid changing
4608
- const toClean = [xk, n];
4609
- if (!isAligned32(buf))
4610
- toClean.push((buf = copyBytes(buf)));
4611
- const out = ctrCounter(xk, n, buf, dst);
4612
- clean(...toClean);
4613
- return out;
4185
+ var recoverPublicKey = function (signature, hash) {
4186
+ var noHex = stripHexPrefix(signature);
4187
+ // split into v-value and sig
4188
+ var sigOnly = noHex.substring(0, noHex.length - 2); // all but last 2 chars
4189
+ var vValue = noHex.slice(-2); // last 2 chars
4190
+ var recoveryNumber = vValue === '1c' ? 1 : 0;
4191
+ var pubKey = bytesToHex$1(ecdsaRecover(hexToBytes$1(sigOnly), recoveryNumber, hexToBytes$1(stripHexPrefix(hash)), false));
4192
+ // remove trailing '04'
4193
+ pubKey = pubKey.slice(2);
4194
+ return pubKey;
4195
+ };
4196
+
4197
+ var hash = {
4198
+ keccak256: keccak256,
4199
+ };
4200
+
4201
+ var StorageService = /** @class */ (function () {
4202
+ function StorageService(_a) {
4203
+ var deviceStorage = _a.deviceStorage, userId = _a.userId, environment = _a.environment;
4204
+ this.userId = userId;
4205
+ this.environment = environment !== null && environment !== void 0 ? environment : defaultEnvironment;
4206
+ this.deviceStorage = deviceStorage;
4614
4207
  }
4615
- return {
4616
- encrypt: (plaintext, dst) => processCtr(plaintext, dst),
4617
- decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),
4208
+ StorageService.prototype.fetch = function (key) {
4209
+ return __awaiter(this, void 0, void 0, function () {
4210
+ var item, _a;
4211
+ return __generator(this, function (_b) {
4212
+ switch (_b.label) {
4213
+ case 0:
4214
+ _a = key;
4215
+ switch (_a) {
4216
+ case exports.LocalStorageItems.EncryptedStandardSeedPhrase: return [3 /*break*/, 1];
4217
+ case exports.LocalStorageItems.EncryptedAlgorandSeedPhrase: return [3 /*break*/, 3];
4218
+ }
4219
+ return [3 /*break*/, 5];
4220
+ case 1: return [4 /*yield*/, this.getItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Standard, "-seedPhrase-").concat(this.userId))];
4221
+ case 2:
4222
+ item = _b.sent();
4223
+ return [3 /*break*/, 7];
4224
+ case 3: return [4 /*yield*/, this.getItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Algorand, "-seedPhrase-").concat(this.userId))];
4225
+ case 4:
4226
+ item = _b.sent();
4227
+ return [3 /*break*/, 7];
4228
+ case 5: return [4 /*yield*/, this.getItem("".concat(this.environment, "-").concat(key, "-").concat(this.userId))];
4229
+ case 6:
4230
+ item = _b.sent();
4231
+ return [3 /*break*/, 7];
4232
+ case 7:
4233
+ if (!item) {
4234
+ logger.info("Item with key ".concat(key, " was not found in storage."));
4235
+ return [2 /*return*/, undefined];
4236
+ }
4237
+ return [2 /*return*/, item];
4238
+ }
4239
+ });
4240
+ });
4241
+ };
4242
+ StorageService.prototype.save = function (key, value) {
4243
+ return __awaiter(this, void 0, void 0, function () {
4244
+ var _a;
4245
+ return __generator(this, function (_b) {
4246
+ switch (_b.label) {
4247
+ case 0:
4248
+ _a = key;
4249
+ switch (_a) {
4250
+ case exports.LocalStorageItems.EncryptedStandardSeedPhrase: return [3 /*break*/, 1];
4251
+ case exports.LocalStorageItems.EncryptedAlgorandSeedPhrase: return [3 /*break*/, 3];
4252
+ }
4253
+ return [3 /*break*/, 5];
4254
+ case 1: return [4 /*yield*/, this.setItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Standard, "-seedPhrase-").concat(this.userId), value)];
4255
+ case 2:
4256
+ _b.sent();
4257
+ return [3 /*break*/, 7];
4258
+ case 3: return [4 /*yield*/, this.setItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Algorand, "-seedPhrase-").concat(this.userId), value)];
4259
+ case 4:
4260
+ _b.sent();
4261
+ return [3 /*break*/, 7];
4262
+ case 5: return [4 /*yield*/, this.setItem("".concat(this.environment, "-").concat(key, "-").concat(this.userId), value)];
4263
+ case 6:
4264
+ _b.sent();
4265
+ return [3 /*break*/, 7];
4266
+ case 7: return [2 /*return*/];
4267
+ }
4268
+ });
4269
+ });
4270
+ };
4271
+ StorageService.prototype.saveInBulk = function (data) {
4272
+ return __awaiter(this, void 0, void 0, function () {
4273
+ var _this = this;
4274
+ return __generator(this, function (_a) {
4275
+ data.forEach(function (item) { return __awaiter(_this, void 0, void 0, function () {
4276
+ return __generator(this, function (_a) {
4277
+ switch (_a.label) {
4278
+ case 0: return [4 /*yield*/, this.save(item.key, item.value)];
4279
+ case 1:
4280
+ _a.sent();
4281
+ return [2 /*return*/];
4282
+ }
4283
+ });
4284
+ }); });
4285
+ return [2 /*return*/];
4286
+ });
4287
+ });
4288
+ };
4289
+ StorageService.prototype.delete = function (key) {
4290
+ return __awaiter(this, void 0, void 0, function () {
4291
+ var _a;
4292
+ return __generator(this, function (_b) {
4293
+ switch (_b.label) {
4294
+ case 0:
4295
+ _a = key;
4296
+ switch (_a) {
4297
+ case exports.LocalStorageItems.EncryptedStandardSeedPhrase: return [3 /*break*/, 1];
4298
+ case exports.LocalStorageItems.EncryptedAlgorandSeedPhrase: return [3 /*break*/, 3];
4299
+ }
4300
+ return [3 /*break*/, 5];
4301
+ case 1: return [4 /*yield*/, this.removeItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Standard, "-seedPhrase-").concat(this.userId))];
4302
+ case 2:
4303
+ _b.sent();
4304
+ return [3 /*break*/, 7];
4305
+ case 3: return [4 /*yield*/, this.removeItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Algorand, "-seedPhrase-").concat(this.userId))];
4306
+ case 4:
4307
+ _b.sent();
4308
+ return [3 /*break*/, 7];
4309
+ case 5: return [4 /*yield*/, this.removeItem("".concat(this.environment, "-").concat(key, "-").concat(this.userId))];
4310
+ case 6:
4311
+ _b.sent();
4312
+ return [3 /*break*/, 7];
4313
+ case 7: return [2 /*return*/];
4314
+ }
4315
+ });
4316
+ });
4317
+ };
4318
+ StorageService.prototype.setItem = function (key, value) {
4319
+ var _a, _b;
4320
+ /** check if deviceStorageSetItem is defined */
4321
+ if ((_a = this.deviceStorage) === null || _a === void 0 ? void 0 : _a.setItem) {
4322
+ return this.deviceStorage.setItem(key, value);
4323
+ }
4324
+ if ((_b = this.deviceStorage) === null || _b === void 0 ? void 0 : _b.setItemAsync) {
4325
+ return this.deviceStorage.setItemAsync(key, value);
4326
+ }
4327
+ throw new Error('setItem function is is not defined');
4328
+ };
4329
+ StorageService.prototype.getItem = function (key) {
4330
+ var _a, _b;
4331
+ if ((_a = this.deviceStorage) === null || _a === void 0 ? void 0 : _a.getItem) {
4332
+ return this.deviceStorage.getItem(key);
4333
+ }
4334
+ if ((_b = this.deviceStorage) === null || _b === void 0 ? void 0 : _b.getItemAsync) {
4335
+ return this.deviceStorage.getItemAsync(key);
4336
+ }
4337
+ throw new Error('getItem function is not defined');
4338
+ };
4339
+ StorageService.prototype.removeItem = function (key) {
4340
+ var _a, _b;
4341
+ if ((_a = this.deviceStorage) === null || _a === void 0 ? void 0 : _a.removeItem) {
4342
+ return this.deviceStorage.removeItem(key);
4343
+ }
4344
+ if ((_b = this.deviceStorage) === null || _b === void 0 ? void 0 : _b.deleteItemAsync) {
4345
+ return this.deviceStorage.deleteItemAsync(key);
4346
+ }
4347
+ throw new Error('removeItem function is not defined');
4348
+ };
4349
+ /**
4350
+ *
4351
+ * Stores Wallaby auth public key to local storage
4352
+ * @param wallabyAuthPubKey
4353
+ */
4354
+ StorageService.prototype.setWallabyAuthPubKey = function (wallabyAuthPubKey) {
4355
+ return __awaiter(this, void 0, void 0, function () {
4356
+ var error_1;
4357
+ return __generator(this, function (_a) {
4358
+ switch (_a.label) {
4359
+ case 0:
4360
+ _a.trys.push([0, 2, , 3]);
4361
+ return [4 /*yield*/, this.setItem("".concat(this.environment, "-wallaby-auth-public-key-").concat(this.userId), wallabyAuthPubKey)];
4362
+ case 1:
4363
+ _a.sent();
4364
+ return [2 /*return*/, true];
4365
+ case 2:
4366
+ error_1 = _a.sent();
4367
+ logger.error('SDK::StorageService::setWallabyAuthPubKey:error', error_1);
4368
+ return [2 /*return*/, false];
4369
+ case 3: return [2 /*return*/];
4370
+ }
4371
+ });
4372
+ });
4373
+ };
4374
+ /**
4375
+ *
4376
+ * Fetches Wallaby auth public key from local storage
4377
+ * @returns { string | undefined } Wallaby Auth Public key or undefined.
4378
+ */
4379
+ StorageService.prototype.getWallabyAuthPubKey = function () {
4380
+ return __awaiter(this, void 0, void 0, function () {
4381
+ var wallabyAuthPubKey, error_2;
4382
+ return __generator(this, function (_a) {
4383
+ switch (_a.label) {
4384
+ case 0:
4385
+ _a.trys.push([0, 7, , 8]);
4386
+ wallabyAuthPubKey = void 0;
4387
+ return [4 /*yield*/, this.getItem("".concat(this.environment, "-wallaby-auth-public-key-").concat(this.userId))];
4388
+ case 1:
4389
+ wallabyAuthPubKey = _a.sent();
4390
+ if (!!wallabyAuthPubKey) return [3 /*break*/, 3];
4391
+ return [4 /*yield*/, this.getItem("wallabyAuthPubKey_".concat(this.userId))];
4392
+ case 2:
4393
+ // try to get the wallabyAuthPubKey from the legacy key
4394
+ wallabyAuthPubKey = _a.sent();
4395
+ _a.label = 3;
4396
+ case 3:
4397
+ if (!wallabyAuthPubKey) return [3 /*break*/, 5];
4398
+ // updating the key to the new format
4399
+ return [4 /*yield*/, this.setItem("".concat(this.environment, "-wallaby-auth-public-key-").concat(this.userId), wallabyAuthPubKey)];
4400
+ case 4:
4401
+ // updating the key to the new format
4402
+ _a.sent();
4403
+ return [2 /*return*/, wallabyAuthPubKey];
4404
+ case 5: return [2 /*return*/, undefined];
4405
+ case 6: return [3 /*break*/, 8];
4406
+ case 7:
4407
+ error_2 = _a.sent();
4408
+ logger.error('SDK::UtilsHelpers::getWallabyAuthPubKey::error', error_2);
4409
+ return [2 /*return*/, undefined];
4410
+ case 8: return [2 /*return*/];
4411
+ }
4412
+ });
4413
+ });
4414
+ };
4415
+ /**
4416
+ *
4417
+ * Encrypts and stores device auth private key
4418
+ * @param privateKey private key
4419
+ * @param password password that is used to encrypt the private key
4420
+ */
4421
+ StorageService.prototype.setEncryptedPrivateKey = function (privateKey, password) {
4422
+ return __awaiter(this, void 0, void 0, function () {
4423
+ var encryptedClientAuthPrivKey, error_3;
4424
+ return __generator(this, function (_a) {
4425
+ switch (_a.label) {
4426
+ case 0:
4427
+ _a.trys.push([0, 2, , 3]);
4428
+ encryptedClientAuthPrivKey = cryptoJs.AES.encrypt(privateKey, password).toString();
4429
+ return [4 /*yield*/, this.setItem("".concat(this.environment, "-client-auth-private-key-").concat(this.userId), encryptedClientAuthPrivKey)];
4430
+ case 1:
4431
+ _a.sent();
4432
+ return [2 /*return*/, true];
4433
+ case 2:
4434
+ error_3 = _a.sent();
4435
+ logger.error('SDK::StorageService::setEncryptedPrivateKey', error_3);
4436
+ return [2 /*return*/, false];
4437
+ case 3: return [2 /*return*/];
4438
+ }
4439
+ });
4440
+ });
4618
4441
  };
4619
- });
4620
- function validateBlockDecrypt(data) {
4621
- bytes(data);
4622
- if (data.length % BLOCK_SIZE !== 0) {
4623
- throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`);
4624
- }
4625
- }
4626
- function validateBlockEncrypt(plaintext, pcks5, dst) {
4627
- bytes(plaintext);
4628
- let outLen = plaintext.length;
4629
- const remaining = outLen % BLOCK_SIZE;
4630
- if (!pcks5 && remaining !== 0)
4631
- throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');
4632
- if (!isAligned32(plaintext))
4633
- plaintext = copyBytes(plaintext);
4634
- const b = u32(plaintext);
4635
- if (pcks5) {
4636
- let left = BLOCK_SIZE - remaining;
4637
- if (!left)
4638
- left = BLOCK_SIZE; // if no bytes left, create empty padding block
4639
- outLen = outLen + left;
4640
- }
4641
- const out = getDst(outLen, dst);
4642
- const o = u32(out);
4643
- return { b, o, out };
4644
- }
4645
- function validatePCKS(data, pcks5) {
4646
- if (!pcks5)
4647
- return data;
4648
- const len = data.length;
4649
- if (!len)
4650
- throw new Error('aes/pcks5: empty ciphertext not allowed');
4651
- const lastByte = data[len - 1];
4652
- if (lastByte <= 0 || lastByte > 16)
4653
- throw new Error('aes/pcks5: wrong padding');
4654
- const out = data.subarray(0, -lastByte);
4655
- for (let i = 0; i < lastByte; i++)
4656
- if (data[len - i - 1] !== lastByte)
4657
- throw new Error('aes/pcks5: wrong padding');
4658
- return out;
4442
+ /**
4443
+ *
4444
+ * Fetches encrypted private key from local storage
4445
+ * @param userId
4446
+ */
4447
+ StorageService.prototype.getEncryptedPrivateKey = function () {
4448
+ return __awaiter(this, void 0, void 0, function () {
4449
+ var encryptedPrivateKey, error_4;
4450
+ return __generator(this, function (_a) {
4451
+ switch (_a.label) {
4452
+ case 0:
4453
+ _a.trys.push([0, 7, , 8]);
4454
+ encryptedPrivateKey = void 0;
4455
+ return [4 /*yield*/, this.getItem("".concat(this.environment, "-client-auth-private-key-").concat(this.userId))];
4456
+ case 1:
4457
+ encryptedPrivateKey = _a.sent();
4458
+ if (!!encryptedPrivateKey) return [3 /*break*/, 3];
4459
+ return [4 /*yield*/, this.getItem("encryptedPrivateKey_".concat(this.userId))];
4460
+ case 2:
4461
+ // try to get the encryptedPrivateKey from the legacy key
4462
+ encryptedPrivateKey = _a.sent();
4463
+ _a.label = 3;
4464
+ case 3:
4465
+ if (!encryptedPrivateKey) return [3 /*break*/, 5];
4466
+ return [4 /*yield*/, this.setItem("".concat(this.environment, "-client-auth-private-key-").concat(this.userId), encryptedPrivateKey)];
4467
+ case 4:
4468
+ _a.sent();
4469
+ return [2 /*return*/, encryptedPrivateKey];
4470
+ case 5:
4471
+ logger.error('SDK::StorageService::getEncryptedPrivateKey: private key not found');
4472
+ return [2 /*return*/, undefined];
4473
+ case 6: return [3 /*break*/, 8];
4474
+ case 7:
4475
+ error_4 = _a.sent();
4476
+ logger.error('SDK::StorageService::getEncryptedPrivateKey::error', error_4);
4477
+ return [2 /*return*/, undefined];
4478
+ case 8: return [2 /*return*/];
4479
+ }
4480
+ });
4481
+ });
4482
+ };
4483
+ /**
4484
+ *
4485
+ * Decrypts user private key
4486
+ * @param password
4487
+ * @returns { string | undefined } It returns the decrypted private key as a string or undefined if it can't decrypt it or find it
4488
+ */
4489
+ StorageService.prototype.getDecryptedPrivateKey = function (password) {
4490
+ return __awaiter(this, void 0, void 0, function () {
4491
+ var privateKey, decryptedPrivateKey, error_5;
4492
+ return __generator(this, function (_a) {
4493
+ switch (_a.label) {
4494
+ case 0:
4495
+ _a.trys.push([0, 2, , 3]);
4496
+ return [4 /*yield*/, this.getItem("".concat(this.environment, "-client-auth-private-key-").concat(this.userId))];
4497
+ case 1:
4498
+ privateKey = _a.sent();
4499
+ if (!privateKey) {
4500
+ return [2 /*return*/, undefined];
4501
+ }
4502
+ decryptedPrivateKey = cryptoJs.AES.decrypt(privateKey, password).toString(cryptoJs.enc.Utf8);
4503
+ if (decryptedPrivateKey !== '' && decryptedPrivateKey !== undefined) {
4504
+ return [2 /*return*/, decryptedPrivateKey];
4505
+ }
4506
+ else {
4507
+ return [2 /*return*/, undefined];
4508
+ }
4509
+ case 2:
4510
+ error_5 = _a.sent();
4511
+ logger.error('SDK::StorageService::getDecryptedPrivateKey::error', error_5);
4512
+ return [2 /*return*/, undefined];
4513
+ case 3: return [2 /*return*/];
4514
+ }
4515
+ });
4516
+ });
4517
+ };
4518
+ StorageService.prototype.setEncryptedSeedPhrase = function (_a) {
4519
+ return __awaiter(this, arguments, void 0, function (_b) {
4520
+ var encryptedOnceSeedPhrase, clientSalt, _c, hashKey, doubleEncryptedSeedPhrase;
4521
+ var decryptedSeedPhrase = _b.decryptedSeedPhrase, seedPhraseType = _b.seedPhraseType, password = _b.password, deviceAuthPublicKey = _b.deviceAuthPublicKey, getUserSalt = _b.getUserSalt, salt = _b.salt;
4522
+ return __generator(this, function (_d) {
4523
+ switch (_d.label) {
4524
+ case 0: return [4 /*yield*/, encryptWithPublicKey(deviceAuthPublicKey, decryptedSeedPhrase)];
4525
+ case 1:
4526
+ encryptedOnceSeedPhrase = _d.sent();
4527
+ if (!(salt !== null && salt !== void 0)) return [3 /*break*/, 2];
4528
+ _c = salt;
4529
+ return [3 /*break*/, 4];
4530
+ case 2: return [4 /*yield*/, getUserSalt()];
4531
+ case 3:
4532
+ _c = (_d.sent());
4533
+ _d.label = 4;
4534
+ case 4:
4535
+ clientSalt = _c;
4536
+ if (!clientSalt) {
4537
+ throw new Error('User salt could not be retrieved, Seed phrase could not be encrypted');
4538
+ }
4539
+ hashKey = "".concat(clientSalt).concat(password);
4540
+ return [4 /*yield*/, cryptoJs.AES.encrypt(JSON.stringify(encryptedOnceSeedPhrase), hashKey)];
4541
+ case 5:
4542
+ doubleEncryptedSeedPhrase = _d.sent();
4543
+ return [4 /*yield*/, this.setItem("".concat(this.environment, "-encrypted-").concat(seedPhraseType, "-seedPhrase-").concat(this.userId), doubleEncryptedSeedPhrase.toString())];
4544
+ case 6:
4545
+ _d.sent();
4546
+ return [2 /*return*/, true];
4547
+ }
4548
+ });
4549
+ });
4550
+ };
4551
+ /**
4552
+ *
4553
+ * @param { SeedPhraseType } seedPhraseType Standard or Mnemonic seed phrase
4554
+ * @returns { string | undefined } It returns the encrypted seed phrase as a string or undefined
4555
+ */
4556
+ StorageService.prototype.getEncryptedSeedPhrase = function (seedPhraseType) {
4557
+ return __awaiter(this, void 0, void 0, function () {
4558
+ var encryptedSeedPhrase, _a;
4559
+ return __generator(this, function (_b) {
4560
+ switch (_b.label) {
4561
+ case 0: return [4 /*yield*/, this.getItem("".concat(this.environment, "-encrypted-").concat(seedPhraseType, "-seedPhrase-").concat(this.userId))];
4562
+ case 1:
4563
+ encryptedSeedPhrase = _b.sent();
4564
+ if (!!encryptedSeedPhrase) return [3 /*break*/, 7];
4565
+ _a = seedPhraseType;
4566
+ switch (_a) {
4567
+ case exports.SeedPhraseType.Algorand: return [3 /*break*/, 2];
4568
+ case exports.SeedPhraseType.Standard: return [3 /*break*/, 4];
4569
+ }
4570
+ return [3 /*break*/, 6];
4571
+ case 2: return [4 /*yield*/, this.getItem("encryptedAlgorandSeed_".concat(this.userId))];
4572
+ case 3:
4573
+ encryptedSeedPhrase = _b.sent();
4574
+ return [3 /*break*/, 7];
4575
+ case 4: return [4 /*yield*/, this.getItem("encryptedSeed_".concat(this.userId))];
4576
+ case 5:
4577
+ encryptedSeedPhrase = _b.sent();
4578
+ return [3 /*break*/, 7];
4579
+ case 6: return [3 /*break*/, 7];
4580
+ case 7:
4581
+ if (!encryptedSeedPhrase) return [3 /*break*/, 9];
4582
+ // updating the key to the new format
4583
+ return [4 /*yield*/, this.setItem("".concat(this.environment, "-encrypted-").concat(seedPhraseType, "-seedPhrase-").concat(this.userId), encryptedSeedPhrase)];
4584
+ case 8:
4585
+ // updating the key to the new format
4586
+ _b.sent();
4587
+ return [2 /*return*/, encryptedSeedPhrase];
4588
+ case 9: return [2 /*return*/, undefined];
4589
+ }
4590
+ });
4591
+ });
4592
+ };
4593
+ /**
4594
+ *
4595
+ * @param {string} password
4596
+ * @param {SeedPhraseType} seedPhraseType
4597
+ * @returns { string | undefined } It returns the decrypted seed phrase as a string or undefined
4598
+ */
4599
+ StorageService.prototype.getDecryptedSeedPhrase = function (_a) {
4600
+ return __awaiter(this, arguments, void 0, function (_b) {
4601
+ var encryptedSeedPhrase, decryptedClientAuthPrivKey, clientSalt, _c, hashKey, decryptedOnceSeedPhrase, parsedSeed, decryptedSeedPhrase;
4602
+ var password = _b.password, seedPhraseType = _b.seedPhraseType, getUserSalt = _b.getUserSalt, salt = _b.salt;
4603
+ return __generator(this, function (_d) {
4604
+ switch (_d.label) {
4605
+ case 0: return [4 /*yield*/, this.getEncryptedSeedPhrase(seedPhraseType)];
4606
+ case 1:
4607
+ encryptedSeedPhrase = _d.sent();
4608
+ return [4 /*yield*/, this.getDecryptedPrivateKey(password)];
4609
+ case 2:
4610
+ decryptedClientAuthPrivKey = _d.sent();
4611
+ if (!encryptedSeedPhrase || !decryptedClientAuthPrivKey) {
4612
+ return [2 /*return*/, undefined];
4613
+ }
4614
+ if (!(salt !== null && salt !== void 0)) return [3 /*break*/, 3];
4615
+ _c = salt;
4616
+ return [3 /*break*/, 5];
4617
+ case 3: return [4 /*yield*/, getUserSalt()];
4618
+ case 4:
4619
+ _c = (_d.sent());
4620
+ _d.label = 5;
4621
+ case 5:
4622
+ clientSalt = _c;
4623
+ hashKey = "".concat(clientSalt).concat(password);
4624
+ decryptedOnceSeedPhrase = cryptoJs.AES.decrypt(encryptedSeedPhrase, hashKey);
4625
+ parsedSeed = JSON.parse(decryptedOnceSeedPhrase.toString(cryptoJs.enc.Utf8));
4626
+ return [4 /*yield*/, decryptWithPrivateKey(decryptedClientAuthPrivKey, parsedSeed)];
4627
+ case 6:
4628
+ decryptedSeedPhrase = _d.sent();
4629
+ return [2 /*return*/, decryptedSeedPhrase];
4630
+ }
4631
+ });
4632
+ });
4633
+ };
4634
+ StorageService.prototype.setAccessToken = function (accessToken) {
4635
+ return __awaiter(this, void 0, void 0, function () {
4636
+ var error_6;
4637
+ return __generator(this, function (_a) {
4638
+ switch (_a.label) {
4639
+ case 0:
4640
+ _a.trys.push([0, 2, , 3]);
4641
+ return [4 /*yield*/, this.setItem("".concat(this.environment, "-access-token-").concat(this.userId), accessToken)];
4642
+ case 1:
4643
+ _a.sent();
4644
+ return [2 /*return*/, true];
4645
+ case 2:
4646
+ error_6 = _a.sent();
4647
+ logger.error('SDK::StorageService::setAccessToken::error', error_6);
4648
+ return [2 /*return*/, false];
4649
+ case 3: return [2 /*return*/];
4650
+ }
4651
+ });
4652
+ });
4653
+ };
4654
+ StorageService.prototype.getAccessToken = function () {
4655
+ return __awaiter(this, void 0, void 0, function () {
4656
+ var accessToken, error_7;
4657
+ return __generator(this, function (_a) {
4658
+ switch (_a.label) {
4659
+ case 0:
4660
+ _a.trys.push([0, 4, , 5]);
4661
+ return [4 /*yield*/, this.getItem("".concat(this.environment, "-access-token-").concat(this.userId))];
4662
+ case 1:
4663
+ accessToken = _a.sent();
4664
+ if (!!accessToken) return [3 /*break*/, 3];
4665
+ return [4 /*yield*/, this.getItem("accessToken_".concat(this.userId))];
4666
+ case 2:
4667
+ // try to get the accessToken from the legacy key
4668
+ accessToken = _a.sent();
4669
+ _a.label = 3;
4670
+ case 3:
4671
+ if (accessToken) {
4672
+ return [2 /*return*/, accessToken];
4673
+ }
4674
+ else {
4675
+ return [2 /*return*/, undefined];
4676
+ }
4677
+ case 4:
4678
+ error_7 = _a.sent();
4679
+ logger.error('SDK::StorageService::getAccessToken::error', error_7);
4680
+ return [2 /*return*/, undefined];
4681
+ case 5: return [2 /*return*/];
4682
+ }
4683
+ });
4684
+ });
4685
+ };
4686
+ StorageService.prototype.clearLocalStorage = function () {
4687
+ return __awaiter(this, void 0, void 0, function () {
4688
+ return __generator(this, function (_a) {
4689
+ switch (_a.label) {
4690
+ case 0: return [4 /*yield*/, Promise.all([
4691
+ this.removeItem("".concat(this.environment, "-access-token-").concat(this.userId)),
4692
+ this.removeItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Algorand, "-seedPhrase-").concat(this.userId)),
4693
+ this.removeItem("".concat(this.environment, "-encrypted-").concat(exports.SeedPhraseType.Standard, "-seedPhrase-").concat(this.userId)),
4694
+ this.removeItem("".concat(this.environment, "-client-auth-private-key-").concat(this.userId)),
4695
+ this.removeItem("".concat(this.environment, "-wallaby-auth-public-key-").concat(this.userId)),
4696
+ this.removeItem("encryptedPrivateKey_".concat(this.userId)),
4697
+ this.removeItem("wallabyAuthPubKey_".concat(this.userId)),
4698
+ this.removeItem("encryptedSeed_".concat(this.userId)),
4699
+ this.removeItem("encryptedAlgorandSeed_".concat(this.userId)),
4700
+ this.removeItem("accessToken_".concat(this.userId)),
4701
+ this.delete(exports.LocalStorageItems.AccessToken),
4702
+ this.delete(exports.LocalStorageItems.ClientAuthPublicKey),
4703
+ this.delete(exports.LocalStorageItems.ClientAuthToken),
4704
+ this.delete(exports.LocalStorageItems.EncryptedStandardSeedPhrase),
4705
+ this.delete(exports.LocalStorageItems.EncryptedAlgorandSeedPhrase),
4706
+ this.delete(exports.LocalStorageItems.EncryptedDevicePrivateKey),
4707
+ this.delete(exports.LocalStorageItems.WallabyAuthPubKey),
4708
+ ])];
4709
+ case 1:
4710
+ _a.sent();
4711
+ return [2 /*return*/];
4712
+ }
4713
+ });
4714
+ });
4715
+ };
4716
+ StorageService.prototype.loadDeviceInformation = function () {
4717
+ return __awaiter(this, void 0, void 0, function () {
4718
+ var _a, _b, _c, _d;
4719
+ return __generator(this, function (_e) {
4720
+ switch (_e.label) {
4721
+ case 0:
4722
+ _a = {};
4723
+ _b = {};
4724
+ return [4 /*yield*/, this.fetch(exports.LocalStorageItems.AccessToken)];
4725
+ case 1:
4726
+ _b.accessToken = _e.sent();
4727
+ return [4 /*yield*/, this.fetch(exports.LocalStorageItems.ClientAuthToken)];
4728
+ case 2:
4729
+ _a.authTokens = (_b.clientAuthToken = _e.sent(),
4730
+ _b);
4731
+ _c = {
4732
+ clientUserId: this.userId
4733
+ };
4734
+ return [4 /*yield*/, this.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase)];
4735
+ case 3:
4736
+ _c.encryptedStandardSeedPhrase = _e.sent();
4737
+ return [4 /*yield*/, this.fetch(exports.LocalStorageItems.EncryptedAlgorandSeedPhrase)];
4738
+ case 4:
4739
+ _a.user = (
4740
+ // encryptedKeyShare: await this.fetch(LocalStorageItems.EncryptedKeyShares),
4741
+ _c.encryptedAlgorandSeedPhrase = _e.sent(),
4742
+ _c.wallabyUserId = undefined,
4743
+ _c);
4744
+ _d = {
4745
+ // Initially these are undefined, because we don't have the decrypted private key yet, and for that we need the password.
4746
+ deviceAuthPrivateKey: undefined,
4747
+ deviceAuthPublicKey: undefined
4748
+ };
4749
+ return [4 /*yield*/, this.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey)];
4750
+ case 5:
4751
+ _d.deviceEncryptedPrivateKey = _e.sent();
4752
+ return [4 /*yield*/, this.fetch(exports.LocalStorageItems.WallabyAuthPubKey)];
4753
+ case 6: return [2 /*return*/, (_a.credentials = (_d.wallabyPublicKey = _e.sent(),
4754
+ _d),
4755
+ _a)];
4756
+ }
4757
+ });
4758
+ });
4759
+ };
4760
+ return StorageService;
4761
+ }());
4762
+
4763
+ /**
4764
+ * Converts an object to query parameters string.
4765
+ *
4766
+ * @param obj - The object to convert.
4767
+ * @returns The query parameters string.
4768
+ */
4769
+ function objectToQueryParams(obj) {
4770
+ var params = new URLSearchParams();
4771
+ Object.keys(obj).forEach(function (key) {
4772
+ if (obj[key] !== null && obj[key] !== undefined && obj[key] !== '') {
4773
+ params.append(key, obj[key]);
4774
+ }
4775
+ });
4776
+ return params.toString();
4659
4777
  }
4660
- function padPCKS(left) {
4661
- const tmp = new Uint8Array(16);
4662
- const tmp32 = u32(tmp);
4663
- tmp.set(left);
4664
- const paddingByte = BLOCK_SIZE - left.length;
4665
- for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)
4666
- tmp[i] = paddingByte;
4667
- return tmp32;
4778
+
4779
+ /**
4780
+ * Checks if a given JWT has expired.
4781
+ *
4782
+ * @param jwt - The JWT string to check. If null, the function will return true.
4783
+ * @returns `true` if the JWT has expired or is null, otherwise `false`.
4784
+ */
4785
+ function jwtHasExpired(jwt) {
4786
+ if (!jwt) {
4787
+ return true;
4788
+ }
4789
+ return millisecondsToJWTTimeout(jwt) <= 0;
4668
4790
  }
4669
4791
  /**
4670
- * CBC: Cipher-Block-Chaining. Key is previous round’s block.
4671
- * Fragile: needs proper padding. Unauthenticated: needs MAC.
4792
+ * Calculates the remaining time in milliseconds until a given JWT expires.
4793
+ *
4794
+ * @param jwt - The JWT string to decode and check.
4795
+ * @returns The number of milliseconds until the JWT expires. If the JWT has already expired, the returned value will be less than or equal to 0.
4672
4796
  */
4673
- const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) {
4674
- bytes(key);
4675
- bytes(iv, 16);
4676
- const pcks5 = !opts.disablePadding;
4677
- return {
4678
- encrypt(plaintext, dst) {
4679
- const xk = expandKeyLE(key);
4680
- const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);
4681
- let _iv = iv;
4682
- const toClean = [xk];
4683
- if (!isAligned32(_iv))
4684
- toClean.push((_iv = copyBytes(_iv)));
4685
- const n32 = u32(_iv);
4686
- // prettier-ignore
4687
- let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
4688
- let i = 0;
4689
- for (; i + 4 <= b.length;) {
4690
- (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);
4691
- ({ s0, s1, s2, s3 } = encrypt$2(xk, s0, s1, s2, s3));
4692
- (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
4797
+ function millisecondsToJWTTimeout(jwt) {
4798
+ var jwtDecoded = jwtDecode.jwtDecode(jwt);
4799
+ var jwtExpirationTimeSeconds = jwtDecoded.exp;
4800
+ var jwtExpirationTimeMilliseconds = (jwtExpirationTimeSeconds !== null && jwtExpirationTimeSeconds !== void 0 ? jwtExpirationTimeSeconds : 0) * 1000;
4801
+ var timeNowMilliseconds = Date.now();
4802
+ return jwtExpirationTimeMilliseconds - timeNowMilliseconds;
4803
+ }
4804
+
4805
+ var Base = /** @class */ (function () {
4806
+ function Base(config) {
4807
+ var _a;
4808
+ this.apiKey = config.apiKey;
4809
+ this.baseUrl = config.baseUrl;
4810
+ this.userId = config.userId;
4811
+ this.clientAuthToken = (_a = config.clientAuthToken) !== null && _a !== void 0 ? _a : config === null || config === void 0 ? void 0 : config.jwt;
4812
+ this.options = config.options;
4813
+ }
4814
+ Object.defineProperty(Base.prototype, "deviceStorage", {
4815
+ /**
4816
+ * This library uses `localStorage` as the default storage.
4817
+ * If you want to use a different storage, you can pass it in the options object of the Wallaby config.
4818
+ * storage: new CustomStorage()
4819
+ * {
4820
+ * }
4821
+ */
4822
+ get: function () {
4823
+ var _a;
4824
+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.storage) {
4825
+ return this.options.storage;
4693
4826
  }
4694
- if (pcks5) {
4695
- const tmp32 = padPCKS(plaintext.subarray(i * 4));
4696
- (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);
4697
- ({ s0, s1, s2, s3 } = encrypt$2(xk, s0, s1, s2, s3));
4698
- (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
4827
+ if (window && window.localStorage) {
4828
+ return window.localStorage;
4699
4829
  }
4700
- clean(...toClean);
4701
- return _out;
4830
+ throw new Error('Your device storage is not supported natively yet, please provide a custom storage in the config options.');
4702
4831
  },
4703
- decrypt(ciphertext, dst) {
4704
- validateBlockDecrypt(ciphertext);
4705
- const xk = expandKeyDecLE(key);
4706
- let _iv = iv;
4707
- const toClean = [xk];
4708
- if (!isAligned32(_iv))
4709
- toClean.push((_iv = copyBytes(_iv)));
4710
- const n32 = u32(_iv);
4711
- const out = getDst(ciphertext.length, dst);
4712
- if (!isAligned32(ciphertext))
4713
- toClean.push((ciphertext = copyBytes(ciphertext)));
4714
- const b = u32(ciphertext);
4715
- const o = u32(out);
4716
- // prettier-ignore
4717
- let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
4718
- for (let i = 0; i + 4 <= b.length;) {
4719
- // prettier-ignore
4720
- const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;
4721
- (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);
4722
- const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt$2(xk, s0, s1, s2, s3);
4723
- (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);
4832
+ enumerable: false,
4833
+ configurable: true
4834
+ });
4835
+ Object.defineProperty(Base.prototype, "device", {
4836
+ /**
4837
+ * @protected
4838
+ */
4839
+ get: function () {
4840
+ return this.storageService.loadDeviceInformation();
4841
+ },
4842
+ enumerable: false,
4843
+ configurable: true
4844
+ });
4845
+ Object.defineProperty(Base.prototype, "settings", {
4846
+ /**
4847
+ * @private
4848
+ */
4849
+ get: function () {
4850
+ var _a, _b, _c, _d;
4851
+ return {
4852
+ apiKey: this.apiKey,
4853
+ baseUrl: this.baseUrl,
4854
+ environment: (_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.environment) !== null && _b !== void 0 ? _b : defaultEnvironment,
4855
+ network: (_d = (_c = this.options) === null || _c === void 0 ? void 0 : _c.network) !== null && _d !== void 0 ? _d : defaultNetwork,
4856
+ };
4857
+ },
4858
+ enumerable: false,
4859
+ configurable: true
4860
+ });
4861
+ Object.defineProperty(Base.prototype, "storageService", {
4862
+ /**
4863
+ * @protected
4864
+ */
4865
+ get: function () {
4866
+ if (!this.clientAuthToken) {
4867
+ throw new Error('A client authentication token (JWT) is required');
4724
4868
  }
4725
- clean(...toClean);
4726
- return validatePCKS(out, pcks5);
4869
+ return new StorageService({
4870
+ deviceStorage: this.deviceStorage,
4871
+ userId: this.userId,
4872
+ environment: this.settings.environment,
4873
+ });
4727
4874
  },
4875
+ enumerable: false,
4876
+ configurable: true
4877
+ });
4878
+ /**
4879
+ *
4880
+ * This is the main request method that is used to make requests to the Wallaby API.
4881
+ * @param { RequestRoute } route full route object to the request endpoint.
4882
+ * @param { RequestOptions } options Extends the `RequestInit` interface to include a payload and queryParams.
4883
+ * @returns Promise of <T> where T is the type of the response.
4884
+ */
4885
+ Base.prototype.request = function (route, options) {
4886
+ return __awaiter(this, void 0, void 0, function () {
4887
+ var url, headers, http, _a, result, error_1, result, error_2, result, error_3, result, error_4, error_5;
4888
+ var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
4889
+ return __generator(this, function (_m) {
4890
+ switch (_m.label) {
4891
+ case 0:
4892
+ _m.trys.push([0, 16, , 17]);
4893
+ url = void 0;
4894
+ if (typeof route.fullPath !== 'string') {
4895
+ url = route.fullPath(options === null || options === void 0 ? void 0 : options.payload);
4896
+ }
4897
+ else {
4898
+ url = route.fullPath;
4899
+ }
4900
+ if (options === null || options === void 0 ? void 0 : options.queryParams) {
4901
+ url += "?".concat(objectToQueryParams(options.queryParams));
4902
+ }
4903
+ return [4 /*yield*/, this.getRequestHeaders(route.requiresAccessToken)];
4904
+ case 1:
4905
+ headers = _m.sent();
4906
+ if ((_b = this.options) === null || _b === void 0 ? void 0 : _b.headers) {
4907
+ headers = __assign(__assign({}, headers), this.options.headers);
4908
+ }
4909
+ http = axios__default.default.create({
4910
+ url: url,
4911
+ baseURL: this.baseUrl,
4912
+ headers: headers,
4913
+ });
4914
+ http.interceptors.response.use(function (response) { return response; }, function (error) {
4915
+ var _a, _b;
4916
+ if ((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) {
4917
+ return Promise.reject((_b = error === null || error === void 0 ? void 0 : error.response) === null || _b === void 0 ? void 0 : _b.data);
4918
+ }
4919
+ logger.error('SDK::Base::Interceptor::error', error);
4920
+ return Promise.reject(error);
4921
+ });
4922
+ _a = route.method;
4923
+ switch (_a) {
4924
+ case exports.RequestMethod.Get: return [3 /*break*/, 2];
4925
+ case exports.RequestMethod.Post: return [3 /*break*/, 5];
4926
+ case exports.RequestMethod.Put: return [3 /*break*/, 8];
4927
+ case exports.RequestMethod.Delete: return [3 /*break*/, 11];
4928
+ }
4929
+ return [3 /*break*/, 14];
4930
+ case 2:
4931
+ _m.trys.push([2, 4, , 5]);
4932
+ return [4 /*yield*/, http.get(url)];
4933
+ case 3:
4934
+ result = _m.sent();
4935
+ logger.info('SDK::Base::RequestMethod.Get::result.data', result === null || result === void 0 ? void 0 : result.data);
4936
+ return [2 /*return*/, result === null || result === void 0 ? void 0 : result.data];
4937
+ case 4:
4938
+ error_1 = _m.sent();
4939
+ if (error_1 instanceof axios.AxiosError) {
4940
+ logger.error('SDK::Base::RequestMethod.Get::error', (_c = error_1 === null || error_1 === void 0 ? void 0 : error_1.response) === null || _c === void 0 ? void 0 : _c.data);
4941
+ return [2 /*return*/, Promise.reject((_d = error_1 === null || error_1 === void 0 ? void 0 : error_1.response) === null || _d === void 0 ? void 0 : _d.data)];
4942
+ }
4943
+ return [2 /*return*/, Promise.reject(error_1 === null || error_1 === void 0 ? void 0 : error_1.message)];
4944
+ case 5:
4945
+ _m.trys.push([5, 7, , 8]);
4946
+ return [4 /*yield*/, http.post(url, JSON.stringify(options === null || options === void 0 ? void 0 : options.payload))];
4947
+ case 6:
4948
+ result = _m.sent();
4949
+ logger.info('SDK::Base::RequestMethod.Post::result.data', result === null || result === void 0 ? void 0 : result.data);
4950
+ return [2 /*return*/, result === null || result === void 0 ? void 0 : result.data];
4951
+ case 7:
4952
+ error_2 = _m.sent();
4953
+ if (error_2 instanceof axios.AxiosError) {
4954
+ logger.error('SDK::Base::RequestMethod.Post::error', (_e = error_2 === null || error_2 === void 0 ? void 0 : error_2.response) === null || _e === void 0 ? void 0 : _e.data);
4955
+ return [2 /*return*/, Promise.reject((_f = error_2 === null || error_2 === void 0 ? void 0 : error_2.response) === null || _f === void 0 ? void 0 : _f.data)];
4956
+ }
4957
+ return [2 /*return*/, Promise.reject(error_2 === null || error_2 === void 0 ? void 0 : error_2.message)];
4958
+ case 8:
4959
+ _m.trys.push([8, 10, , 11]);
4960
+ return [4 /*yield*/, http.put(url, (_g = JSON.stringify(options === null || options === void 0 ? void 0 : options.payload)) !== null && _g !== void 0 ? _g : null)];
4961
+ case 9:
4962
+ result = _m.sent();
4963
+ logger.info('SDK::Base::RequestMethod.Put::result.data', result.data);
4964
+ return [2 /*return*/, result === null || result === void 0 ? void 0 : result.data];
4965
+ case 10:
4966
+ error_3 = _m.sent();
4967
+ if (error_3 instanceof axios.AxiosError) {
4968
+ logger.error('SDK::Base::RequestMethod.Put::error', (_h = error_3 === null || error_3 === void 0 ? void 0 : error_3.response) === null || _h === void 0 ? void 0 : _h.data);
4969
+ return [2 /*return*/, Promise.reject((_j = error_3 === null || error_3 === void 0 ? void 0 : error_3.response) === null || _j === void 0 ? void 0 : _j.data)];
4970
+ }
4971
+ return [2 /*return*/, Promise.reject(error_3 === null || error_3 === void 0 ? void 0 : error_3.message)];
4972
+ case 11:
4973
+ _m.trys.push([11, 13, , 14]);
4974
+ return [4 /*yield*/, http.delete(url)];
4975
+ case 12:
4976
+ result = _m.sent();
4977
+ logger.info('SDK::Base::RequestMethod.Delete::result.data', result.data);
4978
+ return [2 /*return*/, result === null || result === void 0 ? void 0 : result.data];
4979
+ case 13:
4980
+ error_4 = _m.sent();
4981
+ if (error_4 instanceof axios.AxiosError) {
4982
+ logger.error('SDK::Base::RequestMethod.Delete::error', (_k = error_4 === null || error_4 === void 0 ? void 0 : error_4.response) === null || _k === void 0 ? void 0 : _k.data);
4983
+ return [2 /*return*/, Promise.reject((_l = error_4 === null || error_4 === void 0 ? void 0 : error_4.response) === null || _l === void 0 ? void 0 : _l.data)];
4984
+ }
4985
+ return [2 /*return*/, Promise.reject(error_4 === null || error_4 === void 0 ? void 0 : error_4.message)];
4986
+ case 14: throw new Error('Request method is not supported');
4987
+ case 15: return [3 /*break*/, 17];
4988
+ case 16:
4989
+ error_5 = _m.sent();
4990
+ logger.error('SDK::Base::request::error', error_5);
4991
+ return [2 /*return*/, Promise.reject(error_5)];
4992
+ case 17: return [2 /*return*/];
4993
+ }
4994
+ });
4995
+ });
4728
4996
  };
4729
- });
4730
- new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6
4731
-
4732
- function getCipher(key, iv, mode, pkcs7PaddingEnabled = true) {
4733
- if (!mode.startsWith("aes-")) {
4734
- throw new Error("AES: unsupported mode");
4735
- }
4736
- const len = key.length;
4737
- if ((mode.startsWith("aes-128") && len !== 16) || (mode.startsWith("aes-256") && len !== 32)) {
4738
- throw new Error("AES: wrong key length");
4739
- }
4740
- if (iv.length !== 16) {
4741
- throw new Error("AES: wrong IV length");
4742
- }
4743
- if (["aes-128-cbc", "aes-256-cbc"].includes(mode)) {
4744
- return cbc(key, iv, { disablePadding: !pkcs7PaddingEnabled });
4745
- }
4746
- if (["aes-128-ctr", "aes-256-ctr"].includes(mode)) {
4747
- return ctr(key, iv);
4748
- }
4749
- throw new Error("AES: unsupported mode");
4750
- }
4751
- function encrypt$1(msg, key, iv, mode = "aes-128-ctr", pkcs7PaddingEnabled = true) {
4752
- return getCipher(key, iv, mode, pkcs7PaddingEnabled).encrypt(msg);
4753
- }
4754
- function decrypt$1(ciphertext, key, iv, mode = "aes-128-ctr", pkcs7PaddingEnabled = true) {
4755
- return getCipher(key, iv, mode, pkcs7PaddingEnabled).decrypt(ciphertext);
4756
- }
4757
-
4758
- /**
4759
- * See https://github.com/bitchan/eccrypto for the original implementation that eth-crypto used, it's ancient and not maintained.
4760
- */
4761
- /**
4762
- * Encrypts a message using the recipient's public key.
4763
- * @param {string} publicKeyTo - The recipient's public key.
4764
- * @param {string} msg - The message to encrypt.
4765
- * @returns {Encrypted} The encrypted message.
4766
- */
4767
- var encrypt = function (publicKeyTo, msg, options) {
4768
- var ephemPrivateKey = (options === null || options === void 0 ? void 0 : options.ephemPrivateKey) ? hexToBytes$1(options.ephemPrivateKey) : getRandomBytesSync(32);
4769
- var iv = (options === null || options === void 0 ? void 0 : options.iv) ? hexToBytes$1(options.iv) : getRandomBytesSync(16);
4770
- var ephemPublicKey = secp256k1.getPublicKey(ephemPrivateKey, false);
4771
- var sharedSecret = secp256k1.getSharedSecret(ephemPrivateKey, hexToBytes$1(publicKeyTo), true).slice(1);
4772
- var hash = sha512(sharedSecret);
4773
- var encryptionKey = hash.subarray(0, 32);
4774
- var macKey = hash.subarray(32);
4775
- var message = utf8ToBytes$1(msg);
4776
- var data = encrypt$1(message, encryptionKey, iv, 'aes-256-cbc');
4777
- var dataToMac = concatUint8Arrays([iv, ephemPublicKey, data]);
4778
- var mac = hmacSha256Sign(macKey, dataToMac);
4779
- return {
4780
- iv: bytesToHex$1(iv),
4781
- ephemPublicKey: bytesToHex$1(ephemPublicKey),
4782
- ciphertext: bytesToHex$1(data),
4783
- mac: bytesToHex$1(mac),
4997
+ Base.prototype.getRequestHeaders = function (requiresAccessToken) {
4998
+ return __awaiter(this, void 0, void 0, function () {
4999
+ var accessToken, headers;
5000
+ return __generator(this, function (_a) {
5001
+ switch (_a.label) {
5002
+ case 0: return [4 /*yield*/, this.device];
5003
+ case 1:
5004
+ accessToken = (_a.sent()).authTokens.accessToken;
5005
+ if (!isTest && jwtHasExpired(this.clientAuthToken)) {
5006
+ throw new Error('Auth token has expired - blocking API call.');
5007
+ }
5008
+ headers = {
5009
+ 'Content-Type': 'application/json',
5010
+ 'x-api-key': this.settings.apiKey,
5011
+ 'x-client-jwt': this.clientAuthToken,
5012
+ };
5013
+ if (requiresAccessToken && this.userId) {
5014
+ // if (!isTest && (!accessToken || jwtHasExpired(accessToken))) {
5015
+ // throw new Error('Access token has expired, please sign in to continue.');
5016
+ // }
5017
+ headers = __assign(__assign({}, headers), { Authorization: 'Bearer ' + accessToken });
5018
+ }
5019
+ return [2 /*return*/, headers];
5020
+ }
5021
+ });
5022
+ });
4784
5023
  };
4785
- };
4786
- /**
4787
- * Decrypts an encrypted message using the recipient's private key.
4788
- * @param {string} privateKey - The recipient's private key.
4789
- * @param {Encrypted} opts - The encrypted message.
4790
- * @returns {string} The decrypted message.
4791
- */
4792
- var decrypt = function (privateKey, opts) {
4793
- var sharedSecret = secp256k1.getSharedSecret(hexToBytes$1(privateKey), opts.ephemPublicKey, true).slice(1);
4794
- var hash = sha512(sharedSecret);
4795
- var encryptionKey = hash.subarray(0, 32);
4796
- var ciphertext = hexToBytes$1(opts.ciphertext);
4797
- var iv = hexToBytes$1(opts.iv);
4798
- var decrypted = decrypt$1(ciphertext, encryptionKey, iv, 'aes-256-cbc');
4799
- return bytesToUtf8(decrypted);
4800
- };
4801
-
4802
- var encryptWithPublicKey = function (publicKey, message, options) {
4803
- // ensure its an uncompressed publicKey
4804
- var decompressedKey = decompress(publicKey);
4805
- // re-add the compression-flag
4806
- var pubString = '04' + decompressedKey;
4807
- return encrypt(pubString, message, options);
4808
- };
4809
-
4810
- var decryptWithPrivateKey = function (privateKey, encrypted) {
4811
- // remove '0x' from privateKey
4812
- var twoStripped = stripHexPrefix(privateKey);
4813
- return decrypt(twoStripped, encrypted);
4814
- };
5024
+ return Base;
5025
+ }());
4815
5026
 
4816
- var solidityPackedKeccak256 = function (value) {
4817
- var bytes = utf8ToBytes$1(value);
4818
- var hex = addLeading0x(bytesToHex$1(bytes));
4819
- var hash = keccak256$1(hexToBytes$1(hex));
4820
- return addLeading0x(bytesToHex$1(hash));
4821
- };
4822
- var keccak256 = function (params) {
4823
- return solidityPackedKeccak256(params);
5027
+ var WalletRoutes = {
5028
+ importSeedPhraseV2: {
5029
+ fullPath: '/wallets/create-shares-based-wallet-from-seed',
5030
+ method: exports.RequestMethod.Post,
5031
+ requiresAccessToken: true,
5032
+ },
5033
+ initKeyExchange: {
5034
+ fullPath: '/mpc/init-key-exchange',
5035
+ method: exports.RequestMethod.Post,
5036
+ requiresAccessToken: true,
5037
+ },
5038
+ retrieveSeedPhrase: {
5039
+ fullPath: '/mpc/reconstruct-seed-phrase',
5040
+ method: exports.RequestMethod.Post,
5041
+ requiresAccessToken: true,
5042
+ },
5043
+ createWithKeyShares: {
5044
+ fullPath: '/wallets/create-with-shares',
5045
+ method: exports.RequestMethod.Post,
5046
+ requiresAccessToken: true,
5047
+ },
5048
+ retrieveShares: {
5049
+ fullPath: '/wallets/retrieve-shares',
5050
+ method: exports.RequestMethod.Post,
5051
+ requiresAccessToken: true,
5052
+ },
5053
+ create: {
5054
+ fullPath: '/wallets/create',
5055
+ method: exports.RequestMethod.Post,
5056
+ requiresAccessToken: true,
5057
+ },
5058
+ import: {
5059
+ fullPath: '/wallets/import-seed-phrase',
5060
+ method: exports.RequestMethod.Post,
5061
+ requiresAccessToken: true,
5062
+ },
5063
+ initRecoveryFlow: {
5064
+ fullPath: 'wallets/recover/init',
5065
+ method: exports.RequestMethod.Post,
5066
+ requiresAccessToken: false,
5067
+ },
5068
+ recover: {
5069
+ fullPath: '/wallets/recover',
5070
+ method: exports.RequestMethod.Post,
5071
+ requiresAccessToken: false,
5072
+ },
5073
+ getTokenBalance: {
5074
+ fullPath: function (_a) {
5075
+ var address = _a.address, symbol = _a.symbol, chainName = _a.chainName, tokenStandard = _a.tokenStandard;
5076
+ return ("/query/assets/balance?address=".concat(address, "&assetSymbol=").concat(symbol) +
5077
+ "".concat(tokenStandard ? "&tokenType=".concat(tokenStandard) : '') +
5078
+ "".concat(chainName ? "&chainName=".concat(chainName) : ''));
5079
+ },
5080
+ method: exports.RequestMethod.Get,
5081
+ requiresAccessToken: false,
5082
+ },
5083
+ getMultiTokenBalances: {
5084
+ fullPath: '/query/assets/bulk-balance',
5085
+ method: exports.RequestMethod.Post,
5086
+ requiresAccessToken: false,
5087
+ },
5088
+ getWalletBalances: {
5089
+ fullPath: '/query/assets/wallet-bulk-balance',
5090
+ method: exports.RequestMethod.Post,
5091
+ requiresAccessToken: false,
5092
+ },
5093
+ getWalletAssets: {
5094
+ fullPath: function (_a) {
5095
+ var walletId = _a.walletId;
5096
+ return "/wallets/".concat(walletId, "/assets");
5097
+ },
5098
+ method: exports.RequestMethod.Get,
5099
+ requiresAccessToken: true,
5100
+ },
5101
+ getUserAssets: {
5102
+ fullPath: function (_a) {
5103
+ var userId = _a.userId;
5104
+ return "/users/".concat(userId, "/assets");
5105
+ },
5106
+ method: exports.RequestMethod.Get,
5107
+ requiresAccessToken: true,
5108
+ },
5109
+ addTokenToWallet: {
5110
+ fullPath: '/users/assets/add',
5111
+ method: exports.RequestMethod.Post,
5112
+ requiresAccessToken: true,
5113
+ },
5114
+ updateAsset: {
5115
+ fullPath: '/wallets/asset/update',
5116
+ method: exports.RequestMethod.Put,
5117
+ requiresAccessToken: true,
5118
+ },
5119
+ getUserWallets: {
5120
+ fullPath: function (_a) {
5121
+ var userId = _a.userId;
5122
+ return "/users/".concat(userId, "/wallets");
5123
+ },
5124
+ method: exports.RequestMethod.Get,
5125
+ requiresAccessToken: true,
5126
+ },
5127
+ convertMnemonicSeedPhrase: {
5128
+ fullPath: '/wallets/convert-mnemonic-seed',
5129
+ method: exports.RequestMethod.Post,
5130
+ requiresAccessToken: false,
5131
+ },
5132
+ createMultisigAsset: {
5133
+ fullPath: '/wallets/create-multisig-asset',
5134
+ method: exports.RequestMethod.Post,
5135
+ requiresAccessToken: true,
5136
+ },
4824
5137
  };
4825
5138
 
4826
- // Use `secp256k1` module directly.
4827
- // This is a legacy compatibility layer for the npm package `secp256k1` via noble-secp256k1
4828
- secp256k1.ProjectivePoint;
4829
- secp256k1.CURVE.n;
4830
- function output(out = (len) => new Uint8Array(len), length, value) {
4831
- if (typeof out === "function") {
4832
- out = out(length);
4833
- }
4834
- assertBytes(out, length);
4835
- if (value) {
4836
- out.set(value);
4837
- }
4838
- return out;
4839
- }
4840
- function getSignature(signature) {
4841
- assertBytes(signature, 64);
4842
- return secp256k1.Signature.fromCompact(signature);
4843
- }
4844
- function ecdsaRecover(signature, recid, msgHash, compressed = true, out) {
4845
- assertBytes(msgHash, 32);
4846
- assertBool(compressed);
4847
- const sign = getSignature(signature);
4848
- const point = sign.addRecoveryBit(recid).recoverPublicKey(msgHash);
4849
- return output(out, compressed ? 33 : 65, point.toRawBytes(compressed));
4850
- }
4851
-
4852
- /**
4853
- * returns the publicKey for the privateKey with which the messageHash was signed
4854
- * @param {string} signature
4855
- * @param {string} hash
4856
- * @return {string} publicKey
4857
- */
4858
- var recoverPublicKey = function (signature, hash) {
4859
- var noHex = stripHexPrefix(signature);
4860
- // split into v-value and sig
4861
- var sigOnly = noHex.substring(0, noHex.length - 2); // all but last 2 chars
4862
- var vValue = noHex.slice(-2); // last 2 chars
4863
- var recoveryNumber = vValue === '1c' ? 1 : 0;
4864
- var pubKey = bytesToHex$1(ecdsaRecover(hexToBytes$1(sigOnly), recoveryNumber, hexToBytes$1(stripHexPrefix(hash)), false));
4865
- // remove trailing '04'
4866
- pubKey = pubKey.slice(2);
4867
- return pubKey;
5139
+ var AuthRoutes = {
5140
+ signatureMessage: {
5141
+ fullPath: '/auth/signature-message',
5142
+ method: exports.RequestMethod.Post,
5143
+ requiresAccessToken: false,
5144
+ },
5145
+ signIn: {
5146
+ fullPath: '/auth/sign-in',
5147
+ method: exports.RequestMethod.Post,
5148
+ requiresAccessToken: true,
5149
+ },
5150
+ signUp: {
5151
+ fullPath: '/auth/sign-up',
5152
+ method: exports.RequestMethod.Post,
5153
+ requiresAccessToken: false,
5154
+ },
5155
+ refreshAccessToken: {
5156
+ fullPath: '/auth/refresh-access-token',
5157
+ method: exports.RequestMethod.Post,
5158
+ requiresAccessToken: true,
5159
+ },
5160
+ clientAuthPubKey: {
5161
+ fullPath: 'auth/client-auth-pubkey',
5162
+ method: exports.RequestMethod.Put,
5163
+ requiresAccessToken: true,
5164
+ },
5165
+ wallabyAuthPublicKey: {
5166
+ fullPath: '/auth/wallaby-auth-pubkey',
5167
+ method: exports.RequestMethod.Get,
5168
+ requiresAccessToken: true,
5169
+ },
5170
+ getUserSalt: {
5171
+ fullPath: '/users/salt',
5172
+ method: exports.RequestMethod.Get,
5173
+ requiresAccessToken: true,
5174
+ },
4868
5175
  };
4869
5176
 
4870
- var hash = {
4871
- keccak256: keccak256,
5177
+ var SystemRoutes = {
5178
+ getSupportedBlockchains: {
5179
+ fullPath: '/chains',
5180
+ method: exports.RequestMethod.Get,
5181
+ requiresAccessToken: false,
5182
+ },
5183
+ getSupportedTokens: {
5184
+ fullPath: '/assets/configurations',
5185
+ method: exports.RequestMethod.Get,
5186
+ requiresAccessToken: false,
5187
+ },
5188
+ getUserByExternalUserId: {
5189
+ fullPath: function (_a) {
5190
+ var externalUserId = _a.externalUserId;
5191
+ return "/users/".concat(externalUserId, "/externalUserId");
5192
+ },
5193
+ method: exports.RequestMethod.Get,
5194
+ requiresAccessToken: false,
5195
+ },
5196
+ getUserData: {
5197
+ fullPath: function (_a) {
5198
+ var userId = _a.userId;
5199
+ return "/users/".concat(userId);
5200
+ },
5201
+ method: exports.RequestMethod.Get,
5202
+ requiresAccessToken: false,
5203
+ },
5204
+ fetchTokenInfo: {
5205
+ fullPath: function () { return "/query/fetch-token-info"; },
5206
+ method: exports.RequestMethod.Get,
5207
+ requiresAccessToken: false,
5208
+ },
4872
5209
  };
4873
5210
 
4874
5211
  var Cipher = /** @class */ (function () {
@@ -5257,6 +5594,7 @@ var AuthService = /** @class */ (function (_super) {
5257
5594
  })];
5258
5595
  case 1:
5259
5596
  response = _b.sent();
5597
+ console.log('signature_message_response', { response: response, deviceAuthKeys: deviceAuthKeys });
5260
5598
  if (!response)
5261
5599
  throw new Error('Signature message could not be retrieved, please try again later.');
5262
5600
  if (response.error)
@@ -5267,6 +5605,7 @@ var AuthService = /** @class */ (function (_super) {
5267
5605
  })];
5268
5606
  case 2:
5269
5607
  _a = _b.sent(), signature = _a.signature, hashedMessage = _a.hashedMessage, message = _a.message;
5608
+ console.log('signature', { signature: signature, hashedMessage: hashedMessage, message: message });
5270
5609
  return [2 /*return*/, {
5271
5610
  signature: signature,
5272
5611
  hashedMessage: hashedMessage,
@@ -5345,7 +5684,6 @@ var AuthService = /** @class */ (function (_super) {
5345
5684
  }
5346
5685
  return [3 /*break*/, 6];
5347
5686
  case 1: return [4 /*yield*/, this.handleSignInWithPasskey({
5348
- deviceAuthKeys: { publicKey: '', privateKey: '' },
5349
5687
  input: input,
5350
5688
  })];
5351
5689
  case 2:
@@ -5451,14 +5789,14 @@ var AuthService = /** @class */ (function (_super) {
5451
5789
  AuthService.prototype.handlePasskeyRegistration = function (input) {
5452
5790
  return __awaiter(this, void 0, void 0, function () {
5453
5791
  var userSalt, firstSalt, registrationCredentials, regCred, clientExtensions, authenticationResponse, authenticationExtensions, clientDataJSON, clientDataObj, inputKeyMaterial, encryptedDevicePrivKey, error_4;
5454
- var _a, _b, _c, _d, _e;
5455
- return __generator(this, function (_f) {
5456
- switch (_f.label) {
5792
+ var _a, _b, _c, _d, _e, _f, _g;
5793
+ return __generator(this, function (_h) {
5794
+ switch (_h.label) {
5457
5795
  case 0:
5458
- _f.trys.push([0, 7, , 8]);
5796
+ _h.trys.push([0, 7, , 8]);
5459
5797
  return [4 /*yield*/, this.getUserSalt()];
5460
5798
  case 1:
5461
- userSalt = _f.sent();
5799
+ userSalt = _h.sent();
5462
5800
  firstSalt = utf8ToBytes$2(userSalt);
5463
5801
  // const signatureMessage = await this.getSignature(input.deviceAuthKeys);
5464
5802
  if (!input.nickname || !input.displayName) {
@@ -5467,16 +5805,16 @@ var AuthService = /** @class */ (function (_super) {
5467
5805
  return [4 /*yield*/, navigator.credentials.create({
5468
5806
  publicKey: this.constructPasskeyRegistrationPublicKey({
5469
5807
  nickname: input.nickname,
5470
- displayName: input.displayName,
5471
- randomSignatureMessage: input.message,
5808
+ displayName: (_a = input.displayName) !== null && _a !== void 0 ? _a : '',
5809
+ randomSignatureMessage: (_b = input.message) !== null && _b !== void 0 ? _b : '',
5472
5810
  firstSalt: firstSalt,
5473
5811
  }),
5474
5812
  })];
5475
5813
  case 2:
5476
- registrationCredentials = _f.sent();
5814
+ registrationCredentials = _h.sent();
5477
5815
  regCred = registrationCredentials;
5478
5816
  clientExtensions = regCred.getClientExtensionResults();
5479
- if (!((_a = clientExtensions === null || clientExtensions === void 0 ? void 0 : clientExtensions.prf) === null || _a === void 0 ? void 0 : _a.enabled)) {
5817
+ if (!((_c = clientExtensions === null || clientExtensions === void 0 ? void 0 : clientExtensions.prf) === null || _c === void 0 ? void 0 : _c.enabled)) {
5480
5818
  throw new Error('Encrypting with your passkey is not supported on this device, please try from another device or contact customer support for additional help.');
5481
5819
  }
5482
5820
  authenticationResponse = regCred === null || regCred === void 0 ? void 0 : regCred.response;
@@ -5486,19 +5824,19 @@ var AuthService = /** @class */ (function (_super) {
5486
5824
  clientDataObj = JSON.parse(clientDataJSON);
5487
5825
  return [4 /*yield*/, this.storageService.save(exports.LocalStorageItems.PasskeyClientDataObject, JSON.stringify(clientDataObj))];
5488
5826
  case 3:
5489
- _f.sent();
5490
- _f.label = 4;
5827
+ _h.sent();
5828
+ _h.label = 4;
5491
5829
  case 4:
5492
- if (!((_c = (_b = authenticationExtensions.prf) === null || _b === void 0 ? void 0 : _b.results) === null || _c === void 0 ? void 0 : _c.first)) {
5830
+ if (!((_e = (_d = authenticationExtensions.prf) === null || _d === void 0 ? void 0 : _d.results) === null || _e === void 0 ? void 0 : _e.first)) {
5493
5831
  throw new Error('Error encrypting with your passkey, please try again later.');
5494
5832
  }
5495
- inputKeyMaterial = new Uint8Array((_e = (_d = authenticationExtensions.prf) === null || _d === void 0 ? void 0 : _d.results) === null || _e === void 0 ? void 0 : _e.first);
5833
+ inputKeyMaterial = new Uint8Array((_g = (_f = authenticationExtensions.prf) === null || _f === void 0 ? void 0 : _f.results) === null || _g === void 0 ? void 0 : _g.first);
5496
5834
  return [4 /*yield*/, this.cipher.encrypt({
5497
5835
  data: input.deviceAuthKeys.privateKey,
5498
5836
  inputKeyMaterial: inputKeyMaterial,
5499
5837
  })];
5500
5838
  case 5:
5501
- encryptedDevicePrivKey = _f.sent();
5839
+ encryptedDevicePrivKey = _h.sent();
5502
5840
  return [4 /*yield*/, this.storageService.saveInBulk([
5503
5841
  {
5504
5842
  key: exports.LocalStorageItems.EncryptedDevicePrivateKey,
@@ -5523,10 +5861,10 @@ var AuthService = /** @class */ (function (_super) {
5523
5861
  },
5524
5862
  ])];
5525
5863
  case 6:
5526
- _f.sent();
5864
+ _h.sent();
5527
5865
  return [2 /*return*/, regCred];
5528
5866
  case 7:
5529
- error_4 = _f.sent();
5867
+ error_4 = _h.sent();
5530
5868
  logger.error('SDK::AuthService::handlePasskeyRegistration::error', error_4);
5531
5869
  return [2 /*return*/, Promise.reject(error_4)];
5532
5870
  case 8: return [2 /*return*/];
@@ -5536,34 +5874,36 @@ var AuthService = /** @class */ (function (_super) {
5536
5874
  };
5537
5875
  AuthService.prototype.handleSignInWithPasskey = function (_a) {
5538
5876
  return __awaiter(this, arguments, void 0, function (_b) {
5539
- var authentication, firstSalt, signatureMessage, storedCredentials, storedCredentialId, storedClientAuthPublicKey, passkeyRegistration, response, passkeyClientDataObject, parsedClientDataChallenge, pubKeyPayload, authenticationCredentials, authCred, clientExtensions, inputKeyMaterial, encryptedDevicePrivateKey, decryptedClientAuthPrivKey, newIdentity, clientAuthPubKey, signInAuthMessage, encryptedNewDevicePrivateKey, error_5;
5877
+ var authentication, firstSalt, storedCredentials, storedCredentialId, storedClientAuthPublicKey, passkeyRegistration, newIdentity, signatureMessage, response, passkeyClientDataObject, parsedClientDataChallenge, pubKeyPayload, authenticationCredentials, authCred, clientExtensions, inputKeyMaterial, encryptedDevicePrivateKey, decryptedClientAuthPrivKey, newIdentity, clientAuthPubKey, signInAuthMessage, encryptedNewDevicePrivateKey, error_5;
5540
5878
  var _c, _d, _e, _f, _g;
5541
- var deviceAuthKeys = _b.deviceAuthKeys, input = _b.input;
5879
+ var input = _b.input;
5542
5880
  return __generator(this, function (_h) {
5543
5881
  switch (_h.label) {
5544
5882
  case 0: return [4 /*yield*/, this.getUserSalt()];
5545
5883
  case 1:
5546
5884
  firstSalt = _h.sent();
5547
- return [4 /*yield*/, this.getSignature(deviceAuthKeys)];
5885
+ _h.label = 2;
5548
5886
  case 2:
5549
- signatureMessage = _h.sent();
5550
- _h.label = 3;
5551
- case 3:
5552
- _h.trys.push([3, 21, , 22]);
5887
+ _h.trys.push([2, 21, , 22]);
5553
5888
  return [4 /*yield*/, this.storageService.fetch(exports.LocalStorageItems.PasskeyCredential)];
5554
- case 4:
5889
+ case 3:
5555
5890
  storedCredentials = _h.sent();
5556
5891
  return [4 /*yield*/, this.storageService.fetch(exports.LocalStorageItems.PasskeyCredentialId)];
5557
- case 5:
5892
+ case 4:
5558
5893
  storedCredentialId = _h.sent();
5559
5894
  return [4 /*yield*/, this.storageService.fetch(exports.LocalStorageItems.ClientAuthPublicKey)];
5560
- case 6:
5895
+ case 5:
5561
5896
  storedClientAuthPublicKey = _h.sent();
5562
5897
  passkeyRegistration = void 0;
5563
5898
  if (!(!storedCredentials || !storedCredentialId || !storedClientAuthPublicKey)) return [3 /*break*/, 8];
5564
- return [4 /*yield*/, this.handlePasskeyRegistration(__assign(__assign({ deviceAuthKeys: deviceAuthKeys }, signatureMessage), input))];
5899
+ newIdentity = createIdentity();
5900
+ return [4 /*yield*/, this.getSignature(newIdentity)];
5901
+ case 6:
5902
+ signatureMessage = _h.sent();
5903
+ return [4 /*yield*/, this.handlePasskeyRegistration(__assign(__assign({ deviceAuthKeys: newIdentity }, signatureMessage), input))];
5565
5904
  case 7:
5566
5905
  passkeyRegistration = _h.sent();
5906
+ console.log('SDK::AuthService::handleSignInWithPasskey::error', 'Passkey credentials could not be found');
5567
5907
  return [3 /*break*/, 9];
5568
5908
  case 8:
5569
5909
  passkeyRegistration = JSON.parse(storedCredentials);
@@ -6311,7 +6651,7 @@ var WalletService = /** @class */ (function (_super) {
6311
6651
  logger.info('SDK::WalletService::export::readyForTransportKeyShares', readyForTransportKeyShares);
6312
6652
  deviceAuthPublicKey = publicKeyByPrivateKey(decryptedDevicePrivateKey_1);
6313
6653
  return [4 /*yield*/, this.handleConstructingSeedPhraseFromShares({
6314
- encryptedKeyShares: [readyForTransportKeyShares[0]],
6654
+ encryptedKeyShares: readyForTransportKeyShares,
6315
6655
  walletId: walletId,
6316
6656
  deviceAuthPublicKey: deviceAuthPublicKey,
6317
6657
  })];
@@ -6531,12 +6871,12 @@ var WalletService = /** @class */ (function (_super) {
6531
6871
  };
6532
6872
  WalletService.prototype.recover = function (input) {
6533
6873
  return __awaiter(this, void 0, void 0, function () {
6534
- var deviceAuthKeyPair, inputKeyMaterial, encryptedSeed, recoverWithSeedPhraseResponse, encryptedShares, encryptedSeed, error_4;
6874
+ var deviceAuthKeyPair, inputKeyMaterial, recoverWithSeedPhraseResponse, encryptedShares, encryptedSeed, error_4;
6535
6875
  var _a;
6536
6876
  return __generator(this, function (_b) {
6537
6877
  switch (_b.label) {
6538
6878
  case 0:
6539
- _b.trys.push([0, 8, , 9]);
6879
+ _b.trys.push([0, 11, , 12]);
6540
6880
  deviceAuthKeyPair = createIdentity();
6541
6881
  inputKeyMaterial = void 0;
6542
6882
  switch (input.authenticationOptions.encryptionMechanism) {
@@ -6553,20 +6893,21 @@ var WalletService = /** @class */ (function (_super) {
6553
6893
  inputKeyMaterial = input.authenticationOptions.prfValue;
6554
6894
  break;
6555
6895
  }
6556
- if (!input.decryptedSeedPhrase) return [3 /*break*/, 3];
6557
- encryptedSeed = encryptWithPublicKey(input.wallabyAuthPubKey, input.decryptedSeedPhrase);
6558
- if (!encryptedSeed) {
6559
- throw new Error('Encrypted seed phrase is required');
6560
- }
6896
+ if (!input.decryptedSeedPhrase) return [3 /*break*/, 6];
6897
+ console.log('SDK::WalletService::recover:: seed phrase was found in input', {
6898
+ seed: input.decryptedSeedPhrase,
6899
+ wallabyPub: input.wallabyAuthPubKey,
6900
+ });
6561
6901
  return [4 /*yield*/, this.handleRecoverFromSeedPhrase({
6562
- encryptedSeedPhrase: encryptedSeed,
6902
+ decryptedSeedPhrase: input.decryptedSeedPhrase,
6563
6903
  deviceAuthKeys: { publicKey: deviceAuthKeyPair.publicKey, privateKey: deviceAuthKeyPair.privateKey },
6564
6904
  })];
6565
6905
  case 1:
6566
6906
  recoverWithSeedPhraseResponse = _b.sent();
6907
+ if (!recoverWithSeedPhraseResponse.encryptedSeed) return [3 /*break*/, 3];
6567
6908
  // will take care of storing the seed phrase if needed.
6568
6909
  return [4 /*yield*/, this.handleSeedPhraseFromResponse({
6569
- encryptedSeed: encryptedSeed,
6910
+ encryptedSeed: recoverWithSeedPhraseResponse.encryptedSeed,
6570
6911
  decryptedClientAuthPrivKey: deviceAuthKeyPair.privateKey,
6571
6912
  inputKeyMaterial: inputKeyMaterial,
6572
6913
  storeSeedPhrase: input.storeSeedPhrase,
@@ -6574,6 +6915,18 @@ var WalletService = /** @class */ (function (_super) {
6574
6915
  case 2:
6575
6916
  // will take care of storing the seed phrase if needed.
6576
6917
  _b.sent();
6918
+ _b.label = 3;
6919
+ case 3:
6920
+ if (!recoverWithSeedPhraseResponse.shares) return [3 /*break*/, 5];
6921
+ return [4 /*yield*/, this.handleKeySharesFromResponse({
6922
+ keyShares: recoverWithSeedPhraseResponse.shares,
6923
+ decryptedClientAuthPrivKey: deviceAuthKeyPair.privateKey,
6924
+ inputKeyMaterial: inputKeyMaterial,
6925
+ })];
6926
+ case 4:
6927
+ _b.sent();
6928
+ _b.label = 5;
6929
+ case 5:
6577
6930
  this.storageService.saveInBulk([
6578
6931
  {
6579
6932
  key: exports.LocalStorageItems.EncryptedDevicePrivateKey,
@@ -6585,8 +6938,8 @@ var WalletService = /** @class */ (function (_super) {
6585
6938
  },
6586
6939
  ]);
6587
6940
  return [2 /*return*/, recoverWithSeedPhraseResponse];
6588
- case 3:
6589
- if (!input.decryptedShares) return [3 /*break*/, 6];
6941
+ case 6:
6942
+ if (!input.decryptedShares) return [3 /*break*/, 9];
6590
6943
  encryptedShares = (_a = input.decryptedShares) === null || _a === void 0 ? void 0 : _a.map(function (decryptedShare) {
6591
6944
  return encryptWithPublicKey(input.wallabyAuthPubKey, decryptedShare);
6592
6945
  });
@@ -6598,7 +6951,7 @@ var WalletService = /** @class */ (function (_super) {
6598
6951
  deviceAuthPublicKey: deviceAuthKeyPair.publicKey,
6599
6952
  walletId: input.walletId,
6600
6953
  })];
6601
- case 4:
6954
+ case 7:
6602
6955
  encryptedSeed = _b.sent();
6603
6956
  return [4 /*yield*/, this.handleSeedPhraseFromResponse({
6604
6957
  encryptedSeed: encryptedSeed,
@@ -6606,16 +6959,16 @@ var WalletService = /** @class */ (function (_super) {
6606
6959
  inputKeyMaterial: inputKeyMaterial,
6607
6960
  storeSeedPhrase: input.storeSeedPhrase,
6608
6961
  })];
6609
- case 5:
6610
- _b.sent();
6611
- return [3 /*break*/, 7];
6612
- case 6: throw new Error('Decrypted seed phrase or shares are required to recover the wallet.');
6613
- case 7: return [2 /*return*/, { standardSeedPhrase: input.decryptedSeedPhrase }];
6614
6962
  case 8:
6963
+ _b.sent();
6964
+ return [3 /*break*/, 10];
6965
+ case 9: throw new Error('Decrypted seed phrase or shares are required to recover the wallet.');
6966
+ case 10: return [2 /*return*/, { standardSeedPhrase: input.decryptedSeedPhrase }];
6967
+ case 11:
6615
6968
  error_4 = _b.sent();
6616
6969
  logger.error('SDK::Wallet::recover::error', error_4);
6617
6970
  return [2 /*return*/, Promise.reject(error_4)];
6618
- case 9: return [2 /*return*/];
6971
+ case 12: return [2 /*return*/];
6619
6972
  }
6620
6973
  });
6621
6974
  });
@@ -6717,6 +7070,66 @@ var WalletService = /** @class */ (function (_super) {
6717
7070
  });
6718
7071
  });
6719
7072
  };
7073
+ /**
7074
+ * @public
7075
+ * Updates the wallet password.
7076
+ *
7077
+ * @param {string} oldPassword - The Wallaby wallet ID.
7078
+ * @param {string} newPassword - The Wallaby asset ID.
7079
+ *
7080
+ * @returns {Promise<boolean>} True/False.
7081
+ */
7082
+ WalletService.prototype.changePassword = function (_a) {
7083
+ return __awaiter(this, arguments, void 0, function (_b) {
7084
+ var decryptedDevicePrivateKey, clientSalt, decryptedSeedPhrase, error_6;
7085
+ var oldPassword = _b.oldPassword, newPassword = _b.newPassword;
7086
+ return __generator(this, function (_c) {
7087
+ switch (_c.label) {
7088
+ case 0:
7089
+ _c.trys.push([0, 6, , 7]);
7090
+ return [4 /*yield*/, this.storageService.getDecryptedPrivateKey(oldPassword)];
7091
+ case 1:
7092
+ decryptedDevicePrivateKey = _c.sent();
7093
+ if (!decryptedDevicePrivateKey) {
7094
+ throw new Error('Password is not valid, device private key could not be decrypted.');
7095
+ }
7096
+ return [4 /*yield*/, this.authService.getUserSalt()];
7097
+ case 2:
7098
+ clientSalt = _c.sent();
7099
+ return [4 /*yield*/, this.storageService.getDecryptedSeedPhrase({
7100
+ password: oldPassword,
7101
+ seedPhraseType: exports.SeedPhraseType.Standard,
7102
+ getUserSalt: this.authService.getUserSalt,
7103
+ salt: clientSalt,
7104
+ })];
7105
+ case 3:
7106
+ decryptedSeedPhrase = _c.sent();
7107
+ if (!decryptedSeedPhrase) {
7108
+ throw new Error('Password is not valid, seed phrase could not be decrypted, please recover the wallet.');
7109
+ }
7110
+ return [4 /*yield*/, this.storageService.setEncryptedPrivateKey(decryptedDevicePrivateKey, newPassword)];
7111
+ case 4:
7112
+ _c.sent();
7113
+ return [4 /*yield*/, this.storageService.setEncryptedSeedPhrase({
7114
+ decryptedSeedPhrase: decryptedSeedPhrase,
7115
+ seedPhraseType: exports.SeedPhraseType.Standard,
7116
+ password: newPassword,
7117
+ deviceAuthPublicKey: publicKeyByPrivateKey(decryptedDevicePrivateKey),
7118
+ getUserSalt: this.authService.getUserSalt,
7119
+ salt: clientSalt,
7120
+ })];
7121
+ case 5:
7122
+ _c.sent();
7123
+ return [2 /*return*/, true];
7124
+ case 6:
7125
+ error_6 = _c.sent();
7126
+ logger.error('SDK::Wallet::changePassword::error', error_6);
7127
+ return [2 /*return*/, Promise.reject(false)];
7128
+ case 7: return [2 /*return*/];
7129
+ }
7130
+ });
7131
+ });
7132
+ };
6720
7133
  /**
6721
7134
  *
6722
7135
  * @public
@@ -6728,7 +7141,7 @@ var WalletService = /** @class */ (function (_super) {
6728
7141
  */
6729
7142
  WalletService.prototype.getTokenBalance = function (_a) {
6730
7143
  return __awaiter(this, arguments, void 0, function (_b) {
6731
- var response, error_6;
7144
+ var response, error_7;
6732
7145
  var address = _b.address, symbol = _b.symbol, tokenStandard = _b.tokenStandard, chainName = _b.chainName;
6733
7146
  return __generator(this, function (_c) {
6734
7147
  switch (_c.label) {
@@ -6745,9 +7158,9 @@ var WalletService = /** @class */ (function (_super) {
6745
7158
  }
6746
7159
  return [2 /*return*/, response];
6747
7160
  case 2:
6748
- error_6 = _c.sent();
6749
- logger.error('SDK::Wallet::getTokenBalance::error', error_6);
6750
- return [2 /*return*/, Promise.reject(error_6)];
7161
+ error_7 = _c.sent();
7162
+ logger.error('SDK::Wallet::getTokenBalance::error', error_7);
7163
+ return [2 /*return*/, Promise.reject(error_7)];
6751
7164
  case 3: return [2 /*return*/];
6752
7165
  }
6753
7166
  });
@@ -6765,7 +7178,7 @@ var WalletService = /** @class */ (function (_super) {
6765
7178
  */
6766
7179
  WalletService.prototype.getMultiTokenBalances = function (tokensAndAddressesList) {
6767
7180
  return __awaiter(this, void 0, void 0, function () {
6768
- var response, error_7;
7181
+ var response, error_8;
6769
7182
  return __generator(this, function (_a) {
6770
7183
  switch (_a.label) {
6771
7184
  case 0:
@@ -6781,9 +7194,9 @@ var WalletService = /** @class */ (function (_super) {
6781
7194
  }
6782
7195
  return [2 /*return*/, response];
6783
7196
  case 2:
6784
- error_7 = _a.sent();
6785
- logger.error('SDK::Wallet::getTokenBalance::error', error_7);
6786
- return [2 /*return*/, Promise.reject(error_7)];
7197
+ error_8 = _a.sent();
7198
+ logger.error('SDK::Wallet::getTokenBalance::error', error_8);
7199
+ return [2 /*return*/, Promise.reject(error_8)];
6787
7200
  case 3: return [2 /*return*/];
6788
7201
  }
6789
7202
  });
@@ -6798,7 +7211,7 @@ var WalletService = /** @class */ (function (_super) {
6798
7211
  */
6799
7212
  WalletService.prototype.getWalletBalances = function (_a) {
6800
7213
  return __awaiter(this, arguments, void 0, function (_b) {
6801
- var response, error_8;
7214
+ var response, error_9;
6802
7215
  var walletId = _b.walletId;
6803
7216
  return __generator(this, function (_c) {
6804
7217
  switch (_c.label) {
@@ -6815,9 +7228,9 @@ var WalletService = /** @class */ (function (_super) {
6815
7228
  }
6816
7229
  return [2 /*return*/, response];
6817
7230
  case 2:
6818
- error_8 = _c.sent();
6819
- logger.error('SDK::Wallet::getTokenBalance::error', error_8);
6820
- return [2 /*return*/, Promise.reject(error_8)];
7231
+ error_9 = _c.sent();
7232
+ logger.error('SDK::Wallet::getTokenBalance::error', error_9);
7233
+ return [2 /*return*/, Promise.reject(error_9)];
6821
7234
  case 3: return [2 /*return*/];
6822
7235
  }
6823
7236
  });
@@ -6832,7 +7245,7 @@ var WalletService = /** @class */ (function (_super) {
6832
7245
  */
6833
7246
  WalletService.prototype.getUserAssets = function (_a) {
6834
7247
  return __awaiter(this, arguments, void 0, function (_b) {
6835
- var response, error_9;
7248
+ var response, error_10;
6836
7249
  var userId = _b.userId, queryOptions = _b.queryOptions;
6837
7250
  return __generator(this, function (_c) {
6838
7251
  switch (_c.label) {
@@ -6852,9 +7265,9 @@ var WalletService = /** @class */ (function (_super) {
6852
7265
  }
6853
7266
  return [2 /*return*/, response];
6854
7267
  case 2:
6855
- error_9 = _c.sent();
6856
- logger.error('SDK::Wallet::getUserAssets::error', error_9);
6857
- return [2 /*return*/, Promise.reject(error_9)];
7268
+ error_10 = _c.sent();
7269
+ logger.error('SDK::Wallet::getUserAssets::error', error_10);
7270
+ return [2 /*return*/, Promise.reject(error_10)];
6858
7271
  case 3: return [2 /*return*/];
6859
7272
  }
6860
7273
  });
@@ -6868,7 +7281,7 @@ var WalletService = /** @class */ (function (_super) {
6868
7281
  */
6869
7282
  WalletService.prototype.getUserWallets = function (_a) {
6870
7283
  return __awaiter(this, arguments, void 0, function (_b) {
6871
- var response, error_10;
7284
+ var response, error_11;
6872
7285
  var userId = _b.userId, queryOptions = _b.queryOptions;
6873
7286
  return __generator(this, function (_c) {
6874
7287
  switch (_c.label) {
@@ -6888,9 +7301,9 @@ var WalletService = /** @class */ (function (_super) {
6888
7301
  }
6889
7302
  return [2 /*return*/, response];
6890
7303
  case 2:
6891
- error_10 = _c.sent();
6892
- logger.error('SDK::Wallet::getUserWallets::error', error_10);
6893
- return [2 /*return*/, Promise.reject(error_10)];
7304
+ error_11 = _c.sent();
7305
+ logger.error('SDK::Wallet::getUserWallets::error', error_11);
7306
+ return [2 /*return*/, Promise.reject(error_11)];
6894
7307
  case 3: return [2 /*return*/];
6895
7308
  }
6896
7309
  });
@@ -6905,7 +7318,7 @@ var WalletService = /** @class */ (function (_super) {
6905
7318
  */
6906
7319
  WalletService.prototype.getWalletAssets = function (_a) {
6907
7320
  return __awaiter(this, arguments, void 0, function (_b) {
6908
- var response, error_11;
7321
+ var response, error_12;
6909
7322
  var walletId = _b.walletId, queryOptions = _b.queryOptions;
6910
7323
  return __generator(this, function (_c) {
6911
7324
  switch (_c.label) {
@@ -6925,9 +7338,9 @@ var WalletService = /** @class */ (function (_super) {
6925
7338
  }
6926
7339
  return [2 /*return*/, response];
6927
7340
  case 2:
6928
- error_11 = _c.sent();
6929
- logger.error('SDK::Wallet::getWalletAssets::error', error_11);
6930
- return [2 /*return*/, Promise.reject(error_11)];
7341
+ error_12 = _c.sent();
7342
+ logger.error('SDK::Wallet::getWalletAssets::error', error_12);
7343
+ return [2 /*return*/, Promise.reject(error_12)];
6931
7344
  case 3: return [2 /*return*/];
6932
7345
  }
6933
7346
  });
@@ -6950,7 +7363,7 @@ var WalletService = /** @class */ (function (_super) {
6950
7363
  */
6951
7364
  WalletService.prototype.addTokenToWallet = function (_a) {
6952
7365
  return __awaiter(this, arguments, void 0, function (_b) {
6953
- var response, error_12;
7366
+ var response, error_13;
6954
7367
  var assetConfigId = _b.assetConfigId, walletId = _b.walletId, userId = _b.userId, config = _b.config;
6955
7368
  return __generator(this, function (_c) {
6956
7369
  switch (_c.label) {
@@ -6984,9 +7397,9 @@ var WalletService = /** @class */ (function (_super) {
6984
7397
  }
6985
7398
  return [2 /*return*/, response];
6986
7399
  case 2:
6987
- error_12 = _c.sent();
6988
- logger.error('SDK::Wallet::addTokenToWallet::error', error_12);
6989
- return [2 /*return*/, Promise.reject(error_12)];
7400
+ error_13 = _c.sent();
7401
+ logger.error('SDK::Wallet::addTokenToWallet::error', error_13);
7402
+ return [2 /*return*/, Promise.reject(error_13)];
6990
7403
  case 3: return [2 /*return*/];
6991
7404
  }
6992
7405
  });
@@ -7007,7 +7420,7 @@ var WalletService = /** @class */ (function (_super) {
7007
7420
  */
7008
7421
  WalletService.prototype.updateAsset = function (_a) {
7009
7422
  return __awaiter(this, void 0, void 0, function () {
7010
- var response, error_13;
7423
+ var response, error_14;
7011
7424
  var assetConfigId = _a.assetConfigId, walletId = _a.walletId, assetConfig = __rest(_a, ["assetConfigId", "walletId"]);
7012
7425
  return __generator(this, function (_b) {
7013
7426
  switch (_b.label) {
@@ -7027,9 +7440,9 @@ var WalletService = /** @class */ (function (_super) {
7027
7440
  }
7028
7441
  return [2 /*return*/, response];
7029
7442
  case 2:
7030
- error_13 = _b.sent();
7031
- logger.error('SDK::Wallet::updateAsset::error', error_13);
7032
- return [2 /*return*/, Promise.reject(error_13)];
7443
+ error_14 = _b.sent();
7444
+ logger.error('SDK::Wallet::updateAsset::error', error_14);
7445
+ return [2 /*return*/, Promise.reject(error_14)];
7033
7446
  case 3: return [2 /*return*/];
7034
7447
  }
7035
7448
  });
@@ -7044,7 +7457,7 @@ var WalletService = /** @class */ (function (_super) {
7044
7457
  */
7045
7458
  WalletService.prototype.getAlgorandSeedPhrase = function (input) {
7046
7459
  return __awaiter(this, void 0, void 0, function () {
7047
- var encryptedDevicePrivateKey, encryptedStandardSeedPhrase, _a, decryptedDevicePrivateKey, _b, _c, _d, _e, _f, clientAuthPubKey, reference, signatureMessage, message, signature, seedPhraseEncryptedWithWallabyPubKey, response, error_14;
7460
+ var encryptedDevicePrivateKey, encryptedStandardSeedPhrase, _a, decryptedDevicePrivateKey, _b, _c, _d, _e, _f, clientAuthPubKey, reference, signatureMessage, message, signature, seedPhraseEncryptedWithWallabyPubKey, response, error_15;
7048
7461
  var _g;
7049
7462
  var _h;
7050
7463
  return __generator(this, function (_j) {
@@ -7140,9 +7553,9 @@ var WalletService = /** @class */ (function (_super) {
7140
7553
  }
7141
7554
  return [2 /*return*/, response];
7142
7555
  case 14:
7143
- error_14 = _j.sent();
7144
- logger.error('SDK::Wallet::getAlgorandSeedPhrase::error', error_14);
7145
- return [2 /*return*/, Promise.reject(error_14)];
7556
+ error_15 = _j.sent();
7557
+ logger.error('SDK::Wallet::getAlgorandSeedPhrase::error', error_15);
7558
+ return [2 /*return*/, Promise.reject(error_15)];
7146
7559
  case 15: return [2 /*return*/];
7147
7560
  }
7148
7561
  });
@@ -7150,7 +7563,7 @@ var WalletService = /** @class */ (function (_super) {
7150
7563
  };
7151
7564
  WalletService.prototype.handleImportWallet = function (deviceAuthKeys, importWalletInput) {
7152
7565
  return __awaiter(this, void 0, void 0, function () {
7153
- var _a, signature, message, _b, numberOfKeyShares, threshold, readyForTransportSeedPhrase, importWalletPayload, importWalletRequest, decryptedSeedPhrase, inputKeyMaterial, decryptedShares;
7566
+ var _a, signature, message, _b, numberOfKeyShares, threshold, readyForTransportSeedPhrase, importWalletPayload, importWalletResponse, decryptedSeedPhrase, inputKeyMaterial, decryptedShares;
7154
7567
  var _c, _d, _e;
7155
7568
  return __generator(this, function (_f) {
7156
7569
  switch (_f.label) {
@@ -7187,11 +7600,11 @@ var WalletService = /** @class */ (function (_super) {
7187
7600
  payload: importWalletPayload,
7188
7601
  })];
7189
7602
  case 2:
7190
- importWalletRequest = _f.sent();
7191
- if (!importWalletRequest || importWalletRequest.error) {
7192
- throw new Error(importWalletRequest.error);
7603
+ importWalletResponse = _f.sent();
7604
+ if (!importWalletResponse || importWalletResponse.error) {
7605
+ throw new Error(importWalletResponse.error);
7193
7606
  }
7194
- logger.info('SDK::WalletService::import::importWalletRequest', importWalletRequest);
7607
+ logger.info('SDK::WalletService::import::importWalletResponse', importWalletResponse);
7195
7608
  logger.info('SDK::WalletService::import::inputKeyMaterialPayload', {
7196
7609
  encryptionMechanism: importWalletInput.authenticationOptions.encryptionMechanism,
7197
7610
  salt: importWalletInput.authenticationOptions.salt,
@@ -7202,10 +7615,10 @@ var WalletService = /** @class */ (function (_super) {
7202
7615
  ? utf8ToBytes$2("".concat(importWalletInput.authenticationOptions.salt).concat(importWalletInput.authenticationOptions.password))
7203
7616
  : importWalletInput.authenticationOptions.prfValue;
7204
7617
  logger.info('SDK::WalletService::import::inputKeyMaterial', inputKeyMaterial);
7205
- if (!importWalletRequest.encryptedSeed) return [3 /*break*/, 4];
7618
+ if (!importWalletResponse.encryptedSeed) return [3 /*break*/, 4];
7206
7619
  logger.info('SDK::WalletService::import::import does have an encrypted seed phrase');
7207
7620
  return [4 /*yield*/, this.handleSeedPhraseFromResponse({
7208
- encryptedSeed: importWalletRequest.encryptedSeed,
7621
+ encryptedSeed: importWalletResponse.encryptedSeed,
7209
7622
  decryptedClientAuthPrivKey: deviceAuthKeys.privateKey,
7210
7623
  storeSeedPhrase: importWalletInput.storeSeedPhrase,
7211
7624
  inputKeyMaterial: inputKeyMaterial,
@@ -7215,10 +7628,10 @@ var WalletService = /** @class */ (function (_super) {
7215
7628
  logger.info('SDK::WalletService::import::decryptedSeedPhrase', decryptedSeedPhrase);
7216
7629
  _f.label = 4;
7217
7630
  case 4:
7218
- if (!importWalletRequest.shares) return [3 /*break*/, 6];
7631
+ if (!importWalletResponse.shares) return [3 /*break*/, 6];
7219
7632
  logger.info('SDK::WalletService::import::import does have key shares');
7220
7633
  return [4 /*yield*/, this.handleKeySharesFromResponse({
7221
- keyShares: importWalletRequest.shares,
7634
+ keyShares: importWalletResponse.shares,
7222
7635
  decryptedClientAuthPrivKey: deviceAuthKeys.privateKey,
7223
7636
  inputKeyMaterial: inputKeyMaterial,
7224
7637
  })];
@@ -7226,7 +7639,7 @@ var WalletService = /** @class */ (function (_super) {
7226
7639
  decryptedShares = _f.sent();
7227
7640
  logger.info('SDK::WalletService::import::decryptedShares', decryptedShares);
7228
7641
  _f.label = 6;
7229
- case 6: return [2 /*return*/, __assign(__assign({}, importWalletRequest), { standardSeedPhrase: decryptedSeedPhrase })];
7642
+ case 6: return [2 /*return*/, __assign(__assign({}, importWalletResponse), { standardSeedPhrase: decryptedSeedPhrase })];
7230
7643
  }
7231
7644
  });
7232
7645
  });
@@ -7314,7 +7727,7 @@ var WalletService = /** @class */ (function (_super) {
7314
7727
  };
7315
7728
  WalletService.prototype.handleKeySharesFromResponse = function (_a) {
7316
7729
  return __awaiter(this, arguments, void 0, function (_b) {
7317
- var deviceAuthPublicKey_1, encryptedKeyShares, error_15;
7730
+ var deviceAuthPublicKey_1, encryptedKeyShares, error_16;
7318
7731
  var _this = this;
7319
7732
  var keyShares = _b.keyShares, decryptedClientAuthPrivKey = _b.decryptedClientAuthPrivKey, inputKeyMaterial = _b.inputKeyMaterial;
7320
7733
  return __generator(this, function (_c) {
@@ -7362,9 +7775,9 @@ var WalletService = /** @class */ (function (_super) {
7362
7775
  _c.sent();
7363
7776
  return [3 /*break*/, 4];
7364
7777
  case 3:
7365
- error_15 = _c.sent();
7366
- logger.error('SDK::handleKeySharesFromResponse::error', error_15);
7367
- throw error_15;
7778
+ error_16 = _c.sent();
7779
+ logger.error('SDK::handleKeySharesFromResponse::error', error_16);
7780
+ throw error_16;
7368
7781
  case 4: return [2 /*return*/];
7369
7782
  }
7370
7783
  });
@@ -7401,8 +7814,8 @@ var WalletService = /** @class */ (function (_super) {
7401
7814
  };
7402
7815
  WalletService.prototype.handleRecoverFromSeedPhrase = function (_a) {
7403
7816
  return __awaiter(this, arguments, void 0, function (_b) {
7404
- var initRecoveryFlowResponse, _c, signature, message, recoverResponse;
7405
- var encryptedSeedPhrase = _b.encryptedSeedPhrase, deviceAuthKeys = _b.deviceAuthKeys;
7817
+ var initRecoveryFlowResponse, encryptedSeed, _c, signature, message, recoverResponse;
7818
+ var decryptedSeedPhrase = _b.decryptedSeedPhrase, deviceAuthKeys = _b.deviceAuthKeys;
7406
7819
  return __generator(this, function (_d) {
7407
7820
  switch (_d.label) {
7408
7821
  case 0: return [4 /*yield*/, this.request(WalletRoutes.initRecoveryFlow, {
@@ -7417,17 +7830,22 @@ var WalletService = /** @class */ (function (_super) {
7417
7830
  if (!initRecoveryFlowResponse || initRecoveryFlowResponse.error) {
7418
7831
  throw new Error('Failed to recover wallet from seed phrase');
7419
7832
  }
7833
+ encryptedSeed = encryptWithPublicKey(initRecoveryFlowResponse.wallabyAuthPubKey, decryptedSeedPhrase);
7834
+ console.log('SDK::WalletService::recover:: encryptedSeed', encryptedSeed);
7835
+ if (!encryptedSeed) {
7836
+ throw new Error('Seed phrase could not be encrypted');
7837
+ }
7420
7838
  return [4 /*yield*/, this.authService.getSignature(deviceAuthKeys)];
7421
7839
  case 2:
7422
7840
  _c = _d.sent(), signature = _c.signature, message = _c.message;
7423
- return [4 /*yield*/, this.request(WalletRoutes.initRecoveryFlow, {
7841
+ return [4 /*yield*/, this.request(WalletRoutes.recover, {
7424
7842
  method: WalletRoutes.recover.method,
7425
7843
  payload: {
7426
7844
  externalUserId: this.userId,
7427
7845
  signature: signature,
7428
7846
  message: message,
7429
7847
  clientAuthPubKey: deviceAuthKeys.publicKey,
7430
- encryptedSeed: encryptedSeedPhrase,
7848
+ encryptedSeed: encryptedSeed,
7431
7849
  },
7432
7850
  })];
7433
7851
  case 3:
@@ -7442,7 +7860,7 @@ var WalletService = /** @class */ (function (_super) {
7442
7860
  };
7443
7861
  WalletService.prototype.handleConstructingSeedPhraseFromShares = function (_a) {
7444
7862
  return __awaiter(this, arguments, void 0, function (_b) {
7445
- var retrieveSeedPhraseResponse, error_16;
7863
+ var retrieveSeedPhraseResponse, error_17;
7446
7864
  var encryptedKeyShares = _b.encryptedKeyShares, walletId = _b.walletId, deviceAuthPublicKey = _b.deviceAuthPublicKey;
7447
7865
  return __generator(this, function (_c) {
7448
7866
  switch (_c.label) {
@@ -7468,9 +7886,9 @@ var WalletService = /** @class */ (function (_super) {
7468
7886
  }
7469
7887
  return [2 /*return*/, retrieveSeedPhraseResponse.encryptedSeed];
7470
7888
  case 2:
7471
- error_16 = _c.sent();
7472
- logger.error('SDK::handleConstructingSeedPhraseFromShares::error', error_16);
7473
- return [2 /*return*/, Promise.reject(error_16)];
7889
+ error_17 = _c.sent();
7890
+ logger.error('SDK::handleConstructingSeedPhraseFromShares::error', error_17);
7891
+ return [2 /*return*/, Promise.reject(error_17)];
7474
7892
  case 3: return [2 /*return*/];
7475
7893
  }
7476
7894
  });