@portal-hq/utils 0.2.11 → 0.2.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/lib/commonjs/currency/countries/country-codes.js +250 -0
  2. package/lib/commonjs/currency/countries/currency-codes.js +247 -0
  3. package/lib/commonjs/currency/countries/index.js +10 -0
  4. package/lib/commonjs/currency/index.js +29 -0
  5. package/lib/commonjs/definitions/index.js +33 -0
  6. package/lib/commonjs/errors/http-error.js +10 -0
  7. package/lib/commonjs/errors/index.js +23 -0
  8. package/lib/commonjs/errors/invalid-api-key-error.js +10 -0
  9. package/lib/commonjs/errors/invalid-chain-id-error.js +10 -0
  10. package/lib/commonjs/errors/invalid-gateway-config-error.js +10 -0
  11. package/lib/commonjs/errors/missing-option-error.js +10 -0
  12. package/lib/commonjs/errors/mpc-signing-error.js +10 -0
  13. package/lib/commonjs/errors/no-address-error.js +10 -0
  14. package/lib/commonjs/errors/provider-rpc-error.js +52 -0
  15. package/lib/commonjs/eth-requests/index.js +93 -0
  16. package/lib/commonjs/http-request/index.js +72 -0
  17. package/lib/commonjs/index.js +28 -0
  18. package/lib/commonjs/requesters/http.js +52 -0
  19. package/lib/commonjs/requesters/index.js +8 -0
  20. package/lib/esm/currency/countries/country-codes.js +248 -0
  21. package/lib/esm/currency/countries/currency-codes.js +245 -0
  22. package/lib/esm/currency/countries/index.js +2 -0
  23. package/lib/esm/currency/index.js +25 -0
  24. package/lib/esm/definitions/index.js +28 -0
  25. package/lib/esm/errors/http-error.js +8 -0
  26. package/lib/esm/errors/index.js +8 -0
  27. package/lib/esm/errors/invalid-api-key-error.js +8 -0
  28. package/lib/esm/errors/invalid-chain-id-error.js +8 -0
  29. package/lib/esm/errors/invalid-gateway-config-error.js +8 -0
  30. package/lib/esm/errors/missing-option-error.js +8 -0
  31. package/lib/esm/errors/mpc-signing-error.js +8 -0
  32. package/lib/esm/errors/no-address-error.js +8 -0
  33. package/lib/esm/errors/provider-rpc-error.js +49 -0
  34. package/lib/esm/eth-requests/index.js +89 -0
  35. package/lib/esm/http-request/index.js +70 -0
  36. package/lib/esm/index.js +6 -0
  37. package/lib/esm/requesters/http.js +50 -0
  38. package/lib/esm/requesters/index.js +1 -0
  39. package/package.json +1 -1
@@ -0,0 +1,245 @@
1
+ const currencyCodes = {
2
+ Afghanistan: 'AFN',
3
+ Albania: 'ALL',
4
+ Algeria: 'DZD',
5
+ 'American Samoa': 'USD',
6
+ Andorra: 'EUR',
7
+ Angola: 'AOA',
8
+ Anguilla: 'XCD',
9
+ Antarctica: 'XCD',
10
+ 'Antigua and Barbuda': 'XCD',
11
+ Argentina: 'ARS',
12
+ Armenia: 'AMD',
13
+ Aruba: 'AWG',
14
+ Australia: 'AUD',
15
+ Austria: 'EUR',
16
+ Azerbaijan: 'AZN',
17
+ Bahamas: 'BSD',
18
+ Bahrain: 'BHD',
19
+ Bangladesh: 'BDT',
20
+ Barbados: 'BBD',
21
+ Belarus: 'BYR',
22
+ Belgium: 'EUR',
23
+ Belize: 'BZD',
24
+ Benin: 'XOF',
25
+ Bermuda: 'BMD',
26
+ Bhutan: 'BTN',
27
+ Bolivia: 'BOB',
28
+ 'Bosnia and Herzegovina': 'BAM',
29
+ Botswana: 'BWP',
30
+ 'Bouvet Island': 'NOK',
31
+ Brazil: 'BRL',
32
+ 'British Indian Ocean Territory': 'USD',
33
+ Brunei: 'BND',
34
+ Bulgaria: 'BGN',
35
+ 'Burkina Faso': 'XOF',
36
+ Burundi: 'BIF',
37
+ Cambodia: 'KHR',
38
+ Cameroon: 'XAF',
39
+ Canada: 'CAD',
40
+ 'Cape Verde': 'CVE',
41
+ 'Cayman Islands': 'KYD',
42
+ 'Central African Republic': 'XAF',
43
+ Chad: 'XAF',
44
+ Chile: 'CLP',
45
+ China: 'CNY',
46
+ 'Christmas Island': 'AUD',
47
+ 'Cocos (Keeling) Islands': 'AUD',
48
+ Colombia: 'COP',
49
+ Comoros: 'KMF',
50
+ Congo: 'XAF',
51
+ 'Cook Islands': 'NZD',
52
+ 'Costa Rica': 'CRC',
53
+ Croatia: 'HRK',
54
+ Cuba: 'CUP',
55
+ Cyprus: 'EUR',
56
+ 'Czech Republic': 'CZK',
57
+ Denmark: 'DKK',
58
+ Djibouti: 'DJF',
59
+ Dominica: 'XCD',
60
+ 'Dominican Republic': 'DOP',
61
+ 'East Timor': 'USD',
62
+ Ecuador: 'ECS',
63
+ Egypt: 'EGP',
64
+ 'El Salvador': 'SVC',
65
+ England: 'GBP',
66
+ 'Equatorial Guinea': 'XAF',
67
+ Eritrea: 'ERN',
68
+ Estonia: 'EUR',
69
+ Ethiopia: 'ETB',
70
+ 'Falkland Islands': 'FKP',
71
+ 'Faroe Islands': 'DKK',
72
+ 'Fiji Islands': 'FJD',
73
+ Finland: 'EUR',
74
+ France: 'EUR',
75
+ 'French Guiana': 'EUR',
76
+ 'French Polynesia': 'XPF',
77
+ 'French Southern territories': 'EUR',
78
+ Gabon: 'XAF',
79
+ Gambia: 'GMD',
80
+ Georgia: 'GEL',
81
+ Germany: 'EUR',
82
+ Ghana: 'GHS',
83
+ Gibraltar: 'GIP',
84
+ Greece: 'EUR',
85
+ Greenland: 'DKK',
86
+ Grenada: 'XCD',
87
+ Guadeloupe: 'EUR',
88
+ Guam: 'USD',
89
+ Guatemala: 'QTQ',
90
+ Guinea: 'GNF',
91
+ 'Guinea-Bissau': 'CFA',
92
+ Guyana: 'GYD',
93
+ Haiti: 'HTG',
94
+ 'Heard Island and McDonald Islands': 'AUD',
95
+ 'Holy See (Vatican City State)': 'EUR',
96
+ Honduras: 'HNL',
97
+ 'Hong Kong': 'HKD',
98
+ Hungary: 'HUF',
99
+ Iceland: 'ISK',
100
+ India: 'INR',
101
+ Indonesia: 'IDR',
102
+ Iran: 'IRR',
103
+ Iraq: 'IQD',
104
+ Ireland: 'EUR',
105
+ Israel: 'ILS',
106
+ Italy: 'EUR',
107
+ 'Ivory Coast': 'XOF',
108
+ Jamaica: 'JMD',
109
+ Japan: 'JPY',
110
+ Jordan: 'JOD',
111
+ Kazakhstan: 'KZT',
112
+ Kenya: 'KES',
113
+ Kiribati: 'AUD',
114
+ Kuwait: 'KWD',
115
+ Kyrgyzstan: 'KGS',
116
+ Laos: 'LAK',
117
+ Latvia: 'LVL',
118
+ Lebanon: 'LBP',
119
+ Lesotho: 'LSL',
120
+ Liberia: 'LRD',
121
+ 'Libyan Arab Jamahiriya': 'LYD',
122
+ Liechtenstein: 'CHF',
123
+ Lithuania: 'LTL',
124
+ Luxembourg: 'EUR',
125
+ Macao: 'MOP',
126
+ 'North Macedonia': 'MKD',
127
+ Madagascar: 'MGF',
128
+ Malawi: 'MWK',
129
+ Malaysia: 'MYR',
130
+ Maldives: 'MVR',
131
+ Mali: 'XOF',
132
+ Malta: 'EUR',
133
+ 'Marshall Islands': 'USD',
134
+ Martinique: 'EUR',
135
+ Mauritania: 'MRO',
136
+ Mauritius: 'MUR',
137
+ Mayotte: 'EUR',
138
+ Mexico: 'MXN',
139
+ 'Micronesia, Federated States of': 'USD',
140
+ Moldova: 'MDL',
141
+ Monaco: 'EUR',
142
+ Mongolia: 'MNT',
143
+ Montserrat: 'XCD',
144
+ Morocco: 'MAD',
145
+ Mozambique: 'MZN',
146
+ Myanmar: 'MMR',
147
+ Namibia: 'NAD',
148
+ Nauru: 'AUD',
149
+ Nepal: 'NPR',
150
+ Netherlands: 'EUR',
151
+ 'Netherlands Antilles': 'ANG',
152
+ 'New Caledonia': 'XPF',
153
+ 'New Zealand': 'NZD',
154
+ Nicaragua: 'NIO',
155
+ Niger: 'XOF',
156
+ Nigeria: 'NGN',
157
+ Niue: 'NZD',
158
+ 'Norfolk Island': 'AUD',
159
+ 'North Korea': 'KPW',
160
+ 'Northern Ireland': 'GBP',
161
+ 'Northern Mariana Islands': 'USD',
162
+ Norway: 'NOK',
163
+ Oman: 'OMR',
164
+ Pakistan: 'PKR',
165
+ Palau: 'USD',
166
+ Panama: 'PAB',
167
+ 'Papua New Guinea': 'PGK',
168
+ Paraguay: 'PYG',
169
+ Peru: 'PEN',
170
+ Philippines: 'PHP',
171
+ Pitcairn: 'NZD',
172
+ Poland: 'PLN',
173
+ Portugal: 'EUR',
174
+ 'Puerto Rico': 'USD',
175
+ Qatar: 'QAR',
176
+ Reunion: 'EUR',
177
+ Romania: 'RON',
178
+ 'Russian Federation': 'RUB',
179
+ Rwanda: 'RWF',
180
+ 'Saint Helena': 'SHP',
181
+ 'Saint Kitts and Nevis': 'XCD',
182
+ 'Saint Lucia': 'XCD',
183
+ 'Saint Pierre and Miquelon': 'EUR',
184
+ 'Saint Vincent and the Grenadines': 'XCD',
185
+ Samoa: 'WST',
186
+ 'San Marino': 'EUR',
187
+ 'Sao Tome and Principe': 'STD',
188
+ 'Saudi Arabia': 'SAR',
189
+ Scotland: 'GBP',
190
+ Senegal: 'XOF',
191
+ Serbia: 'RSD',
192
+ Seychelles: 'SCR',
193
+ 'Sierra Leone': 'SLL',
194
+ Singapore: 'SGD',
195
+ Slovakia: 'EUR',
196
+ Slovenia: 'EUR',
197
+ 'Solomon Islands': 'SBD',
198
+ Somalia: 'SOS',
199
+ 'South Africa': 'ZAR',
200
+ 'South Georgia and the South Sandwich Islands': 'GBP',
201
+ 'South Korea': 'KRW',
202
+ 'South Sudan': 'SSP',
203
+ Spain: 'EUR',
204
+ 'Sri Lanka': 'LKR',
205
+ Sudan: 'SDG',
206
+ Suriname: 'SRD',
207
+ 'Svalbard and Jan Mayen': 'NOK',
208
+ Swaziland: 'SZL',
209
+ Sweden: 'SEK',
210
+ Switzerland: 'CHF',
211
+ Syria: 'SYP',
212
+ Tajikistan: 'TJS',
213
+ Tanzania: 'TZS',
214
+ Thailand: 'THB',
215
+ 'The Democratic Republic of Congo': 'CDF',
216
+ Togo: 'XOF',
217
+ Tokelau: 'NZD',
218
+ Tonga: 'TOP',
219
+ 'Trinidad and Tobago': 'TTD',
220
+ Tunisia: 'TND',
221
+ Turkey: 'TRY',
222
+ Turkmenistan: 'TMT',
223
+ 'Turks and Caicos Islands': 'USD',
224
+ Tuvalu: 'AUD',
225
+ Uganda: 'UGX',
226
+ Ukraine: 'UAH',
227
+ 'United Arab Emirates': 'AED',
228
+ 'United Kingdom': 'GBP',
229
+ 'United States': 'USD',
230
+ 'United States Minor Outlying Islands': 'USD',
231
+ Uruguay: 'UYU',
232
+ Uzbekistan: 'UZS',
233
+ Vanuatu: 'VUV',
234
+ Venezuela: 'VEF',
235
+ Vietnam: 'VND',
236
+ 'Virgin Islands, British': 'USD',
237
+ 'Virgin Islands, U.S.': 'USD',
238
+ Wales: 'GBP',
239
+ 'Wallis and Futuna': 'XPF',
240
+ 'Western Sahara': 'MAD',
241
+ Yemen: 'YER',
242
+ Zambia: 'ZMW',
243
+ Zimbabwe: 'ZWD',
244
+ };
245
+ export default currencyCodes;
@@ -0,0 +1,2 @@
1
+ export { default as countryCodes } from './country-codes';
2
+ export { default as currencyCodes } from './currency-codes';
@@ -0,0 +1,25 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { countryCodes, currencyCodes } from './countries';
11
+ export const convert = (value, from = 'ETH', countryCode) => __awaiter(void 0, void 0, void 0, function* () {
12
+ const country = countryCodes[countryCode || 'US'];
13
+ if (!country) {
14
+ throw new Error(`Unable to find country name for country code: ${countryCode}.`);
15
+ }
16
+ const to = currencyCodes[country];
17
+ if (!to) {
18
+ throw new Error(`Unable to find currency code for country: ${country}.`);
19
+ }
20
+ const url = `https://min-api.cryptocompare.com/data/price?fsym=${from}&tsyms=${from},${to}`;
21
+ const response = yield fetch(url);
22
+ const data = yield response.json();
23
+ const convertedValue = Math.round((value / (1 / data[to]) + Number.EPSILON) * 100) / 100;
24
+ return convertedValue;
25
+ });
@@ -0,0 +1,28 @@
1
+ export class KeychainAdapter {
2
+ deleteAddress() {
3
+ throw new Error('[Portal] KeychainAdapter method deleteAddress cannot be called directly. Please extend KeychainAdapter.');
4
+ }
5
+ deleteDkgResult() {
6
+ throw new Error('[Portal] KeychainAdapter method deleteDkgResult cannot be called directly. Please extend KeychainAdapter.');
7
+ }
8
+ getAddress(isSim) {
9
+ throw new Error(`[Portal] KeychainAdapter method getAddress(${isSim}) cannot be called directly. Please extend KeychainAdapter.`);
10
+ }
11
+ getDkgResult(isSim) {
12
+ throw new Error(`[Portal] KeychainAdapter method getDkgResult(${isSim}) cannot be called directly. Please extend KeychainAdapter.`);
13
+ }
14
+ storeAddress(address, isSim) {
15
+ throw new Error(`[Portal] KeychainAdapter method storeAddress(${address}, ${isSim}) cannot be called directly. Please extend KeychainAdapter.`);
16
+ }
17
+ storeDkgResult(result, isSim) {
18
+ throw new Error(`[Portal] KeychainAdapter method storeDkgResult(${result}, ${isSim}) cannot be called directly. Please extend KeychainAdapter.`);
19
+ }
20
+ }
21
+ export class Storage {
22
+ read() {
23
+ throw new Error('[Portal] Storage method read cannot be called directly. Please extend Storage.');
24
+ }
25
+ write(privateKey) {
26
+ throw new Error(`[Portal] Storage method write(${privateKey}) cannot be called directly. Please extend Storage.`);
27
+ }
28
+ }
@@ -0,0 +1,8 @@
1
+ class HttpError extends Error {
2
+ constructor({ message, status, statusText }) {
3
+ super(`${status} - ${statusText}: ${message}`);
4
+ // Set the prototype explicitly.
5
+ Object.setPrototypeOf(this, HttpError.prototype);
6
+ }
7
+ }
8
+ export default HttpError;
@@ -0,0 +1,8 @@
1
+ export { default as HttpError } from './http-error';
2
+ export { default as InvalidApiKeyError } from './invalid-api-key-error';
3
+ export { default as InvalidChainIdError } from './invalid-chain-id-error';
4
+ export { default as InvalidGatewayConfigError } from './invalid-gateway-config-error';
5
+ export { default as MissingOptionError } from './missing-option-error';
6
+ export { default as MpcSigningError } from './mpc-signing-error';
7
+ export { default as NoAddressError } from './no-address-error';
8
+ export { default as ProviderRpcError, RpcErrorCodes, } from './provider-rpc-error';
@@ -0,0 +1,8 @@
1
+ class InvalidApiKeyError extends Error {
2
+ constructor() {
3
+ super('[Portal] A valid Portal Client API Key was not provided.');
4
+ // Set the prototype explicitly.
5
+ Object.setPrototypeOf(this, InvalidApiKeyError.prototype);
6
+ }
7
+ }
8
+ export default InvalidApiKeyError;
@@ -0,0 +1,8 @@
1
+ class InvalidChainIdError extends Error {
2
+ constructor() {
3
+ super('[Portal] A valid Ethereum Chain ID was not provided.');
4
+ // Set the prototype explicitly.
5
+ Object.setPrototypeOf(this, InvalidChainIdError.prototype);
6
+ }
7
+ }
8
+ export default InvalidChainIdError;
@@ -0,0 +1,8 @@
1
+ class InvalidGatewayConfigError extends Error {
2
+ constructor() {
3
+ super('[Portal] A valid Gateway configuration was not provided.');
4
+ // Set the prototype explicitly.
5
+ Object.setPrototypeOf(this, InvalidGatewayConfigError.prototype);
6
+ }
7
+ }
8
+ export default InvalidGatewayConfigError;
@@ -0,0 +1,8 @@
1
+ class MissingOptionError extends Error {
2
+ constructor({ className, option }) {
3
+ super(`[Portal] Instance option '${option}' is required when instantiating ${className}.`);
4
+ // Set the prototype explicitly.
5
+ Object.setPrototypeOf(this, MissingOptionError.prototype);
6
+ }
7
+ }
8
+ export default MissingOptionError;
@@ -0,0 +1,8 @@
1
+ class MpcSigningError extends Error {
2
+ constructor(message) {
3
+ super(`[Portal] An error occurred in the MPC signing process: ${message}`);
4
+ // Set the prototype explicitly.
5
+ Object.setPrototypeOf(this, MpcSigningError.prototype);
6
+ }
7
+ }
8
+ export default MpcSigningError;
@@ -0,0 +1,8 @@
1
+ class NoAddressError extends Error {
2
+ constructor() {
3
+ super('[Portal] A valid wallet address was not provided.');
4
+ // Set the prototype explicitly.
5
+ Object.setPrototypeOf(this, NoAddressError.prototype);
6
+ }
7
+ }
8
+ export default NoAddressError;
@@ -0,0 +1,49 @@
1
+ export var RpcErrorCodes;
2
+ (function (RpcErrorCodes) {
3
+ RpcErrorCodes[RpcErrorCodes["UserRejectedRequest"] = 4001] = "UserRejectedRequest";
4
+ RpcErrorCodes[RpcErrorCodes["Unauthorized"] = 4100] = "Unauthorized";
5
+ RpcErrorCodes[RpcErrorCodes["UnsupportedMethod"] = 4200] = "UnsupportedMethod";
6
+ RpcErrorCodes[RpcErrorCodes["Disconnected"] = 4900] = "Disconnected";
7
+ RpcErrorCodes[RpcErrorCodes["ChainDisconnected"] = 4901] = "ChainDisconnected";
8
+ })(RpcErrorCodes || (RpcErrorCodes = {}));
9
+ const providerErrors = {
10
+ 4001: {
11
+ name: 'User Rejected Request',
12
+ description: 'The user rejected the request.',
13
+ },
14
+ 4100: {
15
+ name: 'Unauthorized',
16
+ description: 'The requested method and/or account has not been authorized by the user.',
17
+ },
18
+ 4200: {
19
+ name: 'Unsupported Method',
20
+ description: 'The Provider does not support the requested method.',
21
+ },
22
+ 4900: {
23
+ name: 'Disconnected',
24
+ description: 'The Provider is disconnected from all chains.',
25
+ },
26
+ 4901: {
27
+ name: 'Chain Disconnected',
28
+ description: 'The Provider is not connected to the requested chain.',
29
+ },
30
+ };
31
+ class ProviderRpcError extends Error {
32
+ constructor({ code, data }) {
33
+ const log = console;
34
+ const definition = providerErrors[code];
35
+ if (!definition) {
36
+ log.warn(`[Portal] ProviderRpcError instantiated with unknown error code ${code}. Attempting to continue with limited context.`);
37
+ }
38
+ const message = definition
39
+ ? `${definition.name} - ${definition.description}`
40
+ : '';
41
+ super(`[Portal] RPC Error: ${code} ${message}`);
42
+ // Set the prototype explicitly.
43
+ Object.setPrototypeOf(this, ProviderRpcError.prototype);
44
+ this.code = code;
45
+ this.data = data;
46
+ this.definition = definition;
47
+ }
48
+ }
49
+ export default ProviderRpcError;
@@ -0,0 +1,89 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { convert } from '../currency';
11
+ const hexStringToString = (hexInput) => {
12
+ // Get the proper hex string
13
+ const byteArray = Array.from(hexStringToByteArray(hexInput.replace('0x', '')));
14
+ // Create an array of characters
15
+ const stringArray = byteArray.reduce((acc, charCode) => {
16
+ // Add the character matching the charCode
17
+ acc.push(String.fromCharCode(charCode));
18
+ // Return the accumulator
19
+ return acc;
20
+ }, []);
21
+ // Join the array of characters
22
+ const string = stringArray.join('');
23
+ // Return the final string
24
+ return string;
25
+ };
26
+ const hexStringToByteArray = (hexString) => {
27
+ // Verify the length of the string
28
+ if (hexString.length % 2 !== 0) {
29
+ throw Error('[Portal] hexStringToByteArray() detected invalid input lenth for hexString.');
30
+ }
31
+ // Get the total bytes
32
+ const totalBytes = hexString.length / 2;
33
+ // Initialize a Uint8Array with a length matching totalBytes
34
+ const byteArray = new Uint8Array(totalBytes);
35
+ // Loop of the resulting array
36
+ for (let i = 0; i < totalBytes; i++) {
37
+ // Get the byte at the current index
38
+ const substring = hexString.substring(i * 2, i * 2 + 2).toLowerCase();
39
+ // Get the integer matching the current byte and push to the array
40
+ byteArray[i] = parseInt(substring, 16);
41
+ }
42
+ // Return a byte array
43
+ return byteArray;
44
+ };
45
+ const hexStringToNumber = (hexBalance) => {
46
+ const balanceNumber = Number(hexBalance);
47
+ console.log(`balanceNumber`, balanceNumber);
48
+ const balance = Math.round((balanceNumber / 1e18) * 1000000) / 1000000;
49
+ return balance;
50
+ };
51
+ export const parseRequest = (method, params) => __awaiter(void 0, void 0, void 0, function* () {
52
+ let requestData;
53
+ console.log(`Request: `, JSON.stringify({ method, params }));
54
+ const txParam0 = Array.isArray(params) ? params[0] : params;
55
+ switch (method) {
56
+ case 'eth_sendTransaction':
57
+ case 'eth_signTransaction':
58
+ const payload = txParam0;
59
+ const value = hexStringToNumber(payload.value);
60
+ requestData = {
61
+ data: payload.data,
62
+ from: payload.from,
63
+ to: payload.to,
64
+ value,
65
+ valueConverted: yield convert(value),
66
+ };
67
+ return {
68
+ method,
69
+ data: requestData,
70
+ };
71
+ case 'eth_sign':
72
+ case 'personal_sign':
73
+ requestData = {
74
+ message: hexStringToString(txParam0),
75
+ };
76
+ return {
77
+ method,
78
+ data: requestData,
79
+ };
80
+ default:
81
+ return {
82
+ method,
83
+ data: {
84
+ message: 'NO_DATA_PROVIDED',
85
+ },
86
+ };
87
+ break;
88
+ }
89
+ });
@@ -0,0 +1,70 @@
1
+ import { HttpError } from '../errors';
2
+ class HttpRequest {
3
+ constructor({ body = {}, headers = {}, method, url }) {
4
+ this.body = body;
5
+ this.headers = headers;
6
+ this.method = method;
7
+ this.url = url;
8
+ this.request = new XMLHttpRequest();
9
+ this.request.open(this.method, this.url, true);
10
+ }
11
+ send() {
12
+ return new Promise((resolve, reject) => {
13
+ // Sets headers on the request
14
+ this.prepareRequest();
15
+ // Sends the request with a formatted request body
16
+ const body = this.prepareBody();
17
+ this.request.send(body);
18
+ // Adds an event listener for when the request state changes
19
+ this.request.onreadystatechange = () => {
20
+ if (this.request.readyState === 4) {
21
+ // readyState 4 means the request has completed
22
+ if (this.request.status !== 200) {
23
+ // If we didn't get an 'OK' status, error out
24
+ reject(new HttpError({
25
+ message: this.request.responseText,
26
+ status: this.request.status,
27
+ statusText: this.request.statusText,
28
+ }));
29
+ }
30
+ else {
31
+ // Otherwise, resolve a parsed response object
32
+ resolve(this.buildResponse());
33
+ }
34
+ }
35
+ };
36
+ });
37
+ }
38
+ buildResponse() {
39
+ try {
40
+ // Try parsing the response body into a JSON object
41
+ const response = JSON.parse(this.request.response);
42
+ return response;
43
+ }
44
+ catch (_a) {
45
+ // If JSON parsing doesn't work, just return the response body however it came back
46
+ return this.request.response;
47
+ }
48
+ }
49
+ prepareBody() {
50
+ if (this.headers['Content-Type'] === 'application/json') {
51
+ // Stringify if we're declaring this request to be a JSON request
52
+ return JSON.stringify(this.body);
53
+ }
54
+ else {
55
+ // Otherwise, build a serialized string
56
+ const params = [];
57
+ for (const [key, value] of Object.entries(this.body)) {
58
+ params.push(`${key}=${value}`);
59
+ }
60
+ return params.join('&');
61
+ }
62
+ }
63
+ prepareRequest() {
64
+ // Add all of the defined headers to the request
65
+ for (const [key, value] of Object.entries(this.headers)) {
66
+ this.request.setRequestHeader(key, value);
67
+ }
68
+ }
69
+ }
70
+ export default HttpRequest;
@@ -0,0 +1,6 @@
1
+ export { convert } from './currency';
2
+ export { KeychainAdapter, PortalApi, Storage } from './definitions';
3
+ export { HttpError, InvalidApiKeyError, InvalidChainIdError, InvalidGatewayConfigError, MissingOptionError, MpcSigningError, NoAddressError, ProviderRpcError, RpcErrorCodes, } from './errors';
4
+ export { parseRequest } from './eth-requests';
5
+ export { default as HttpRequest } from './http-request';
6
+ export { HttpRequester } from './requesters';
@@ -0,0 +1,50 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { HttpRequest } from '../index';
11
+ class HttpRequester {
12
+ constructor({ baseUrl }) {
13
+ this.baseUrl = baseUrl.startsWith('https://')
14
+ ? baseUrl
15
+ : `https://${baseUrl}`;
16
+ }
17
+ get(path, options) {
18
+ return __awaiter(this, void 0, void 0, function* () {
19
+ const requestOptions = {
20
+ method: 'GET',
21
+ url: `${this.baseUrl}${path}`,
22
+ };
23
+ if (options && options.headers) {
24
+ requestOptions.headers = this.buildHeaders(options.headers);
25
+ }
26
+ const request = new HttpRequest(requestOptions);
27
+ const response = (yield request.send());
28
+ return response;
29
+ });
30
+ }
31
+ post(path, options) {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ const requestOptions = {
34
+ method: 'POST',
35
+ url: `${this.baseUrl}${path}`,
36
+ };
37
+ requestOptions.headers = this.buildHeaders(options && options.headers ? options.headers : {});
38
+ if (options && options.body) {
39
+ requestOptions.body = options.body;
40
+ }
41
+ const request = new HttpRequest(requestOptions);
42
+ const response = (yield request.send());
43
+ return response;
44
+ });
45
+ }
46
+ buildHeaders(headers) {
47
+ return Object.assign({ 'Content-Type': 'application/json' }, headers);
48
+ }
49
+ }
50
+ export default HttpRequester;
@@ -0,0 +1 @@
1
+ export { default as HttpRequester } from './http';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@portal-hq/utils",
3
- "version": "0.2.11",
3
+ "version": "0.2.12",
4
4
  "main": "lib/commonjs/index",
5
5
  "module": "lib/esm/index",
6
6
  "source": "src/index",