@lifi/sdk 1.7.2 → 2.0.0-beta.0

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 (76) hide show
  1. package/dist/Lifi.js +97 -85
  2. package/dist/allowance/checkAllowance.js +12 -21
  3. package/dist/allowance/tokenApproval.js +20 -29
  4. package/dist/allowance/utils.js +12 -24
  5. package/dist/balance/checkBalance.js +5 -14
  6. package/dist/balance/getTokenBalance.js +12 -21
  7. package/dist/balance/index.d.ts +11 -0
  8. package/dist/balance/index.js +8 -0
  9. package/dist/balance/utils.d.ts +1 -0
  10. package/dist/balance/utils.js +36 -38
  11. package/dist/cjs/Lifi.js +97 -85
  12. package/dist/cjs/allowance/checkAllowance.js +12 -21
  13. package/dist/cjs/allowance/tokenApproval.js +20 -29
  14. package/dist/cjs/allowance/utils.js +12 -24
  15. package/dist/cjs/balance/checkBalance.js +5 -14
  16. package/dist/cjs/balance/getTokenBalance.js +12 -21
  17. package/dist/cjs/balance/index.d.ts +11 -0
  18. package/dist/cjs/balance/index.js +8 -0
  19. package/dist/cjs/balance/utils.d.ts +1 -0
  20. package/dist/cjs/balance/utils.js +39 -39
  21. package/dist/cjs/connectors.js +17 -25
  22. package/dist/cjs/execution/ExecutionManager.js +27 -33
  23. package/dist/cjs/execution/StatusManager.js +13 -13
  24. package/dist/cjs/execution/StepExecutor.js +8 -14
  25. package/dist/cjs/execution/stepComparison.js +4 -14
  26. package/dist/cjs/execution/switchChain.js +5 -14
  27. package/dist/cjs/execution/utils.js +43 -50
  28. package/dist/cjs/helpers.d.ts +12 -1
  29. package/dist/cjs/helpers.js +68 -19
  30. package/dist/cjs/services/ApiService.d.ts +10 -9
  31. package/dist/cjs/services/ApiService.js +190 -152
  32. package/dist/cjs/services/ApiService.unit.handlers.d.ts +1 -0
  33. package/dist/cjs/services/ApiService.unit.handlers.js +50 -0
  34. package/dist/cjs/services/ChainsService.js +16 -31
  35. package/dist/cjs/services/ConfigService.js +6 -16
  36. package/dist/cjs/typeguards.js +1 -1
  37. package/dist/cjs/types/internal.types.d.ts +4 -1
  38. package/dist/cjs/utils/errors.d.ts +5 -0
  39. package/dist/cjs/utils/errors.js +14 -1
  40. package/dist/cjs/utils/multicall.js +6 -15
  41. package/dist/cjs/utils/parseError.d.ts +2 -2
  42. package/dist/cjs/utils/parseError.js +36 -38
  43. package/dist/cjs/utils/preRestart.js +5 -7
  44. package/dist/cjs/utils/utils.d.ts +0 -1
  45. package/dist/cjs/utils/utils.js +21 -28
  46. package/dist/cjs/version.d.ts +1 -1
  47. package/dist/cjs/version.js +1 -1
  48. package/dist/connectors.js +15 -23
  49. package/dist/execution/ExecutionManager.js +27 -33
  50. package/dist/execution/StatusManager.js +11 -11
  51. package/dist/execution/StepExecutor.js +8 -14
  52. package/dist/execution/stepComparison.js +4 -14
  53. package/dist/execution/switchChain.js +5 -14
  54. package/dist/execution/utils.js +43 -50
  55. package/dist/helpers.d.ts +12 -1
  56. package/dist/helpers.js +65 -18
  57. package/dist/services/ApiService.d.ts +10 -9
  58. package/dist/services/ApiService.js +190 -152
  59. package/dist/services/ApiService.unit.handlers.d.ts +1 -0
  60. package/dist/services/ApiService.unit.handlers.js +44 -0
  61. package/dist/services/ChainsService.js +16 -31
  62. package/dist/services/ConfigService.js +6 -16
  63. package/dist/typeguards.js +1 -1
  64. package/dist/types/internal.types.d.ts +4 -1
  65. package/dist/utils/errors.d.ts +5 -0
  66. package/dist/utils/errors.js +12 -0
  67. package/dist/utils/multicall.js +6 -15
  68. package/dist/utils/parseError.d.ts +2 -2
  69. package/dist/utils/parseError.js +36 -38
  70. package/dist/utils/preRestart.js +5 -7
  71. package/dist/utils/utils.d.ts +0 -1
  72. package/dist/utils/utils.js +20 -26
  73. package/dist/version.d.ts +1 -1
  74. package/dist/version.js +1 -1
  75. package/package.json +22 -24
  76. package/CHANGELOG.md +0 -492
@@ -2,8 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.StatusManager = void 0;
4
4
  const types_1 = require("../types");
5
- const utils_1 = require("../utils/utils");
6
- const utils_2 = require("./utils");
5
+ const utils_1 = require("./utils");
7
6
  /**
8
7
  * Manages status updates of a route and provides various functions for tracking processes
9
8
  * @param {Route} route The route this StatusManger belongs to.
@@ -20,7 +19,7 @@ class StatusManager {
20
19
  * @return {Execution} The initialized execution object for this step and a function to update this step
21
20
  */
22
21
  this.initExecutionObject = (step) => {
23
- const currentExecution = step.execution || (0, utils_1.deepClone)(types_1.emptyExecution);
22
+ const currentExecution = step.execution || structuredClone(types_1.emptyExecution);
24
23
  if (!step.execution) {
25
24
  step.execution = currentExecution;
26
25
  step.execution.status = 'PENDING';
@@ -41,8 +40,7 @@ class StatusManager {
41
40
  * @return {Process}
42
41
  */
43
42
  this.findOrCreateProcess = (step, type, status) => {
44
- var _a;
45
- if (!((_a = step.execution) === null || _a === void 0 ? void 0 : _a.process)) {
43
+ if (!step.execution?.process) {
46
44
  throw new Error("Execution hasn't been initialized.");
47
45
  }
48
46
  const process = step.execution.process.find((p) => p.type === type);
@@ -56,8 +54,8 @@ class StatusManager {
56
54
  const newProcess = {
57
55
  type: type,
58
56
  startedAt: Date.now(),
59
- message: (0, utils_2.getProcessMessage)(type, status !== null && status !== void 0 ? status : 'STARTED'),
60
- status: status !== null && status !== void 0 ? status : 'STARTED',
57
+ message: (0, utils_1.getProcessMessage)(type, status ?? 'STARTED'),
58
+ status: status ?? 'STARTED',
61
59
  };
62
60
  step.execution.process.push(newProcess);
63
61
  this.updateStepInRoute(step);
@@ -72,11 +70,10 @@ class StatusManager {
72
70
  * @return {Process} The update process
73
71
  */
74
72
  this.updateProcess = (step, type, status, params) => {
75
- var _a, _b, _c;
76
73
  if (!step.execution) {
77
74
  throw new Error("Can't update an empty step execution.");
78
75
  }
79
- const currentProcess = (_a = step === null || step === void 0 ? void 0 : step.execution) === null || _a === void 0 ? void 0 : _a.process.find((p) => p.type === type);
76
+ const currentProcess = step?.execution?.process.find((p) => p.type === type);
80
77
  if (!currentProcess) {
81
78
  throw new Error("Can't find a process for the given type.");
82
79
  }
@@ -101,7 +98,7 @@ class StatusManager {
101
98
  break;
102
99
  }
103
100
  currentProcess.status = status;
104
- currentProcess.message = (0, utils_2.getProcessMessage)(type, status);
101
+ currentProcess.message = (0, utils_1.getProcessMessage)(type, status);
105
102
  // set extra parameters or overwritte the standard params set in the switch statement
106
103
  if (params) {
107
104
  for (const [key, value] of Object.entries(params)) {
@@ -110,8 +107,8 @@ class StatusManager {
110
107
  }
111
108
  // Sort processes, the ones with DONE status go first
112
109
  step.execution.process = [
113
- ...(_b = step === null || step === void 0 ? void 0 : step.execution) === null || _b === void 0 ? void 0 : _b.process.filter((process) => process.status === 'DONE'),
114
- ...(_c = step === null || step === void 0 ? void 0 : step.execution) === null || _c === void 0 ? void 0 : _c.process.filter((process) => process.status !== 'DONE'),
110
+ ...step?.execution?.process.filter((process) => process.status === 'DONE'),
111
+ ...step?.execution?.process.filter((process) => process.status !== 'DONE'),
115
112
  ];
116
113
  this.updateStepInRoute(step); // updates the step in the route
117
114
  return currentProcess;
@@ -160,7 +157,10 @@ class StatusManager {
160
157
  }
161
158
  step.execution.status = status;
162
159
  if (receipt) {
163
- step.execution = Object.assign(Object.assign({}, step.execution), receipt);
160
+ step.execution = {
161
+ ...step.execution,
162
+ ...receipt,
163
+ };
164
164
  }
165
165
  this.updateStepInRoute(step);
166
166
  return step;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.StepExecutor = void 0;
13
4
  const ExecutionManager_1 = require("./ExecutionManager");
@@ -23,7 +14,10 @@ class StepExecutor {
23
14
  this.allowUserInteraction = true;
24
15
  this.executionStopped = false;
25
16
  this.setInteraction = (settings) => {
26
- const interactionSettings = Object.assign(Object.assign({}, defaultInteractionSettings), settings);
17
+ const interactionSettings = {
18
+ ...defaultInteractionSettings,
19
+ ...settings,
20
+ };
27
21
  this.allowUserInteraction = interactionSettings.allowInteraction;
28
22
  this.executionManager.allowInteraction(interactionSettings.allowInteraction);
29
23
  this.statusManager.allowUpdates(interactionSettings.allowUpdates);
@@ -35,9 +29,9 @@ class StepExecutor {
35
29
  this.checkChain = () => {
36
30
  throw new Error('checkChain is not implemented.');
37
31
  };
38
- this.executeStep = (signer, step) => __awaiter(this, void 0, void 0, function* () {
32
+ this.executeStep = async (signer, step) => {
39
33
  // Make sure that the chain is still correct
40
- const updatedSigner = yield (0, switchChain_1.switchChain)(signer, this.statusManager, step, this.settings.switchChainHook, this.allowUserInteraction);
34
+ const updatedSigner = await (0, switchChain_1.switchChain)(signer, this.statusManager, step, this.settings.switchChainHook, this.allowUserInteraction);
41
35
  if (!updatedSigner) {
42
36
  // Chain switch was not successful, stop execution here
43
37
  return step;
@@ -49,9 +43,9 @@ class StepExecutor {
49
43
  settings: this.settings,
50
44
  statusManager: this.statusManager,
51
45
  };
52
- yield this.executionManager.execute(parameters);
46
+ await this.executionManager.execute(parameters);
53
47
  return step;
54
- });
48
+ };
55
49
  this.executionManager = new ExecutionManager_1.ExecutionManager();
56
50
  this.statusManager = statusManager;
57
51
  this.settings = settings;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.stepComparison = void 0;
13
4
  const errors_1 = require("../utils/errors");
@@ -23,16 +14,15 @@ const utils_1 = require("./utils");
23
14
  * @param acceptSlippageUpdateHook
24
15
  * @param allowUserInteraction
25
16
  */
26
- const stepComparison = (statusManager, oldStep, newStep, settings, allowUserInteraction) => __awaiter(void 0, void 0, void 0, function* () {
27
- var _a;
17
+ const stepComparison = async (statusManager, oldStep, newStep, settings, allowUserInteraction) => {
28
18
  // Check if changed exchange rate is in the range of slippage threshold
29
19
  if ((0, utils_1.checkStepSlippageThreshold)(oldStep, newStep)) {
30
20
  return statusManager.updateStepInRoute(newStep);
31
21
  }
32
- const acceptExchangeRateUpdateHook = (_a = settings.acceptExchangeRateUpdateHook) !== null && _a !== void 0 ? _a : settings.acceptSlippageUpdateHook;
22
+ const acceptExchangeRateUpdateHook = settings.acceptExchangeRateUpdateHook ?? settings.acceptSlippageUpdateHook;
33
23
  let allowStepUpdate;
34
24
  if (allowUserInteraction) {
35
- allowStepUpdate = yield acceptExchangeRateUpdateHook({
25
+ allowStepUpdate = await acceptExchangeRateUpdateHook({
36
26
  oldToAmount: oldStep.estimate.toAmount,
37
27
  newToAmount: newStep.estimate.toAmount,
38
28
  toToken: newStep.action.toToken,
@@ -46,5 +36,5 @@ const stepComparison = (statusManager, oldStep, newStep, settings, allowUserInte
46
36
  The exchange rate has changed and the previous estimation can not be fulfilled due to value loss.`);
47
37
  }
48
38
  return statusManager.updateStepInRoute(newStep);
49
- });
39
+ };
50
40
  exports.stepComparison = stepComparison;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.switchChain = void 0;
13
4
  const errors_1 = require("../utils/errors");
@@ -22,9 +13,9 @@ const errors_1 = require("../utils/errors");
22
13
  * @param switchChainHook
23
14
  * @param allowUserInteraction
24
15
  */
25
- const switchChain = (signer, statusManager, step, switchChainHook, allowUserInteraction) => __awaiter(void 0, void 0, void 0, function* () {
16
+ const switchChain = async (signer, statusManager, step, switchChainHook, allowUserInteraction) => {
26
17
  // if we are already on the correct chain we can proceed directly
27
- if ((yield signer.getChainId()) === step.action.fromChainId) {
18
+ if ((await signer.getChainId()) === step.action.fromChainId) {
28
19
  return signer;
29
20
  }
30
21
  // -> set status message
@@ -35,8 +26,8 @@ const switchChain = (signer, statusManager, step, switchChainHook, allowUserInte
35
26
  return;
36
27
  }
37
28
  try {
38
- const updatedSigner = yield switchChainHook(step.action.fromChainId);
39
- const updatedChainId = yield (updatedSigner === null || updatedSigner === void 0 ? void 0 : updatedSigner.getChainId());
29
+ const updatedSigner = await switchChainHook(step.action.fromChainId);
30
+ const updatedChainId = await updatedSigner?.getChainId();
40
31
  if (updatedChainId !== step.action.fromChainId) {
41
32
  throw new errors_1.ProviderError(errors_1.LifiErrorCode.ChainSwitchError, 'Chain switch required.');
42
33
  }
@@ -54,5 +45,5 @@ const switchChain = (signer, statusManager, step, switchChainHook, allowUserInte
54
45
  statusManager.updateExecution(step, 'FAILED');
55
46
  throw error;
56
47
  }
57
- });
48
+ };
58
49
  exports.switchChain = switchChain;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -18,51 +9,53 @@ const ApiService_1 = __importDefault(require("../services/ApiService"));
18
9
  const errors_1 = require("../utils/errors");
19
10
  const utils_1 = require("../utils/utils");
20
11
  const TRANSACTION_HASH_OBSERVERS = {};
21
- function waitForReceivingTransaction(txHash, statusManager, processType, step) {
22
- return __awaiter(this, void 0, void 0, function* () {
23
- const getStatus = () => new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
24
- let statusResponse;
25
- try {
26
- statusResponse = yield ApiService_1.default.getStatus({
27
- bridge: step.tool,
28
- fromChain: step.action.fromChainId,
29
- toChain: step.action.toChainId,
30
- txHash,
31
- });
32
- }
33
- catch (e) {
34
- console.debug('Fetching status from backend failed.', e);
35
- return resolve(undefined);
36
- }
37
- switch (statusResponse.status) {
38
- case 'DONE':
39
- return resolve(statusResponse);
40
- case 'PENDING':
41
- statusManager === null || statusManager === void 0 ? void 0 : statusManager.updateProcess(step, processType, 'PENDING', Object.assign({ substatus: statusResponse.substatus, substatusMessage: statusResponse.substatusMessage ||
42
- getSubstatusMessage(statusResponse.status, statusResponse.substatus) }, (statusResponse.bridgeExplorerLink && {
43
- txLink: statusResponse.bridgeExplorerLink,
44
- })));
45
- return resolve(undefined);
46
- case 'NOT_FOUND':
47
- return resolve(undefined);
48
- case 'FAILED':
49
- default:
50
- return reject();
51
- }
52
- }));
53
- let status;
54
- if (txHash in TRANSACTION_HASH_OBSERVERS) {
55
- status = yield TRANSACTION_HASH_OBSERVERS[txHash];
12
+ async function waitForReceivingTransaction(txHash, statusManager, processType, step) {
13
+ const getStatus = () => new Promise(async (resolve, reject) => {
14
+ let statusResponse;
15
+ try {
16
+ statusResponse = await ApiService_1.default.getStatus({
17
+ bridge: step.tool,
18
+ fromChain: step.action.fromChainId,
19
+ toChain: step.action.toChainId,
20
+ txHash,
21
+ });
56
22
  }
57
- else {
58
- TRANSACTION_HASH_OBSERVERS[txHash] = (0, utils_1.repeatUntilDone)(getStatus, 5000);
59
- status = yield TRANSACTION_HASH_OBSERVERS[txHash];
23
+ catch (e) {
24
+ console.debug('Fetching status from backend failed.', e);
25
+ return resolve(undefined);
60
26
  }
61
- if (!status.receiving) {
62
- throw new errors_1.ServerError("Status doesn't contain receiving information.");
27
+ switch (statusResponse.status) {
28
+ case 'DONE':
29
+ return resolve(statusResponse);
30
+ case 'PENDING':
31
+ statusManager?.updateProcess(step, processType, 'PENDING', {
32
+ substatus: statusResponse.substatus,
33
+ substatusMessage: statusResponse.substatusMessage ||
34
+ getSubstatusMessage(statusResponse.status, statusResponse.substatus),
35
+ ...(statusResponse.bridgeExplorerLink && {
36
+ txLink: statusResponse.bridgeExplorerLink,
37
+ }),
38
+ });
39
+ return resolve(undefined);
40
+ case 'NOT_FOUND':
41
+ return resolve(undefined);
42
+ case 'FAILED':
43
+ default:
44
+ return reject();
63
45
  }
64
- return status;
65
46
  });
47
+ let status;
48
+ if (txHash in TRANSACTION_HASH_OBSERVERS) {
49
+ status = await TRANSACTION_HASH_OBSERVERS[txHash];
50
+ }
51
+ else {
52
+ TRANSACTION_HASH_OBSERVERS[txHash] = (0, utils_1.repeatUntilDone)(getStatus, 5000);
53
+ status = await TRANSACTION_HASH_OBSERVERS[txHash];
54
+ }
55
+ if (!status.receiving) {
56
+ throw new errors_1.ServerError("Status doesn't contain receiving information.");
57
+ }
58
+ return status;
66
59
  }
67
60
  exports.waitForReceivingTransaction = waitForReceivingTransaction;
68
61
  const processMessages = {
@@ -1,4 +1,4 @@
1
- import { Token } from '@lifi/types';
1
+ import { Route, Step, Token } from '@lifi/types';
2
2
  /**
3
3
  * Predefined hook that decrypts calldata using EIP-1193 compliant wallet functions.
4
4
  * @param {string} walletAddress - The wallet address of the user that should decrypt the calldata.
@@ -17,3 +17,14 @@ export declare const getEthereumPublicKeyHook: (walletAddress: string) => () =>
17
17
  export declare const getRandomNumber: (min: number, max: number) => number;
18
18
  export declare const isSameToken: (tokenA: Token, tokenB: Token) => boolean;
19
19
  export declare const checkPackageUpdates: (packageName?: string, packageVersion?: string, disableCheck?: boolean) => Promise<void>;
20
+ /**
21
+ * Converts a quote to Route
22
+ * @param {Step} step - Step returned from the quote endpoint.
23
+ * @return {Route} - The route to be executed.
24
+ * @throws {ValidationError} Throws a ValidationError if the step has missing values.
25
+ */
26
+ export declare const convertQuoteToRoute: (step: Step) => Route;
27
+ export declare const requestSettings: {
28
+ retries: number;
29
+ };
30
+ export declare const request: <T = Response>(url: string, options?: RequestInit, retries?: number) => Promise<T>;
@@ -1,26 +1,19 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.checkPackageUpdates = exports.isSameToken = exports.getRandomNumber = exports.getEthereumPublicKeyHook = exports.getEthereumDecryptionHook = void 0;
3
+ exports.request = exports.requestSettings = exports.convertQuoteToRoute = exports.checkPackageUpdates = exports.isSameToken = exports.getRandomNumber = exports.getEthereumPublicKeyHook = exports.getEthereumDecryptionHook = void 0;
4
+ const errors_1 = require("./utils/errors");
5
+ const utils_1 = require("./utils/utils");
13
6
  const version_1 = require("./version");
14
- const ethereumRequest = (method, params) => __awaiter(void 0, void 0, void 0, function* () {
7
+ const ethereumRequest = async (method, params) => {
15
8
  // If ethereum.request() exists, the provider is probably EIP-1193 compliant.
16
- if (!(ethereum === null || ethereum === void 0 ? void 0 : ethereum.request)) {
9
+ if (!ethereum?.request) {
17
10
  throw new Error('Provider not available.');
18
11
  }
19
12
  return ethereum.request({
20
13
  method,
21
14
  params,
22
15
  });
23
- });
16
+ };
24
17
  /**
25
18
  * Predefined hook that decrypts calldata using EIP-1193 compliant wallet functions.
26
19
  * @param {string} walletAddress - The wallet address of the user that should decrypt the calldata.
@@ -66,15 +59,16 @@ function semverCompare(a, b) {
66
59
  caseFirst: 'upper',
67
60
  });
68
61
  }
69
- const checkPackageUpdates = (packageName, packageVersion, disableCheck) => __awaiter(void 0, void 0, void 0, function* () {
62
+ const checkPackageUpdates = async (packageName, packageVersion, disableCheck) => {
70
63
  if (disableCheck || process.env.NODE_ENV !== 'development') {
71
64
  return;
72
65
  }
73
66
  try {
74
- const pkgName = packageName !== null && packageName !== void 0 ? packageName : version_1.name;
75
- const response = yield (yield fetch(`https://registry.npmjs.org/${pkgName}/latest`)).json();
76
- const latestVersion = response.version;
77
- const currentVersion = packageVersion !== null && packageVersion !== void 0 ? packageVersion : version_1.version;
67
+ const pkgName = packageName ?? version_1.name;
68
+ const response = await (0, exports.request)('https://registry.npmjs.org/${pkgName}/latest');
69
+ const data = await response.json();
70
+ const latestVersion = data.version;
71
+ const currentVersion = packageVersion ?? version_1.version;
78
72
  if (semverCompare(latestVersion, currentVersion)) {
79
73
  console.warn(
80
74
  // eslint-disable-next-line max-len
@@ -84,5 +78,60 @@ const checkPackageUpdates = (packageName, packageVersion, disableCheck) => __awa
84
78
  catch (error) {
85
79
  // Cannot verify version, might be network error etc. We don't bother showing anything in that case
86
80
  }
87
- });
81
+ };
88
82
  exports.checkPackageUpdates = checkPackageUpdates;
83
+ /**
84
+ * Converts a quote to Route
85
+ * @param {Step} step - Step returned from the quote endpoint.
86
+ * @return {Route} - The route to be executed.
87
+ * @throws {ValidationError} Throws a ValidationError if the step has missing values.
88
+ */
89
+ const convertQuoteToRoute = (step) => {
90
+ if (!step.estimate.fromAmountUSD) {
91
+ throw new errors_1.ValidationError("Missing 'fromAmountUSD' in step estimate.");
92
+ }
93
+ if (!step.estimate.toAmountUSD) {
94
+ throw new errors_1.ValidationError("Missing 'toAmountUSD' in step estimate.");
95
+ }
96
+ const lifiStep = {
97
+ ...step,
98
+ type: 'lifi',
99
+ includedSteps: [],
100
+ };
101
+ const route = {
102
+ fromToken: step.action.fromToken,
103
+ toToken: step.action.toToken,
104
+ fromAmount: step.action.fromAmount,
105
+ toAmount: step.estimate.toAmount,
106
+ id: step.id,
107
+ fromChainId: step.action.fromToken.chainId,
108
+ toChainId: step.action.toToken.chainId,
109
+ fromAmountUSD: step.estimate.fromAmountUSD,
110
+ toAmountUSD: step.estimate.toAmountUSD,
111
+ steps: [lifiStep],
112
+ toAmountMin: step.estimate.toAmountMin,
113
+ };
114
+ return route;
115
+ };
116
+ exports.convertQuoteToRoute = convertQuoteToRoute;
117
+ exports.requestSettings = {
118
+ retries: 1,
119
+ };
120
+ const request = async (url, options, retries = exports.requestSettings.retries) => {
121
+ try {
122
+ const response = await fetch(url, options);
123
+ if (!response.ok) {
124
+ throw new errors_1.HTTPError(response);
125
+ }
126
+ const data = await response.json();
127
+ return data;
128
+ }
129
+ catch (error) {
130
+ if (retries > 0 && error?.status === 500) {
131
+ await (0, utils_1.sleep)(500);
132
+ return (0, exports.request)(url, options, retries - 1);
133
+ }
134
+ throw error;
135
+ }
136
+ };
137
+ exports.request = request;
@@ -1,15 +1,16 @@
1
- import { ContractCallQuoteRequest, GetStatusRequest, QuoteRequest, RequestOptions, TokensRequest, TokensResponse } from '@lifi/types';
1
+ import { ContractCallQuoteRequest, GasRecommendationRequest, GasRecommendationResponse, GetStatusRequest, QuoteRequest, RequestOptions, TokensRequest, TokensResponse } from '@lifi/types';
2
2
  import { ChainId, ChainKey, ExtendedChain, PossibilitiesRequest, PossibilitiesResponse, RoutesRequest, RoutesResponse, StatusResponse, Step, Token, ToolsRequest, ToolsResponse } from '../types';
3
3
  declare const _default: {
4
- getPossibilities: (request?: PossibilitiesRequest | undefined, options?: RequestOptions | undefined) => Promise<PossibilitiesResponse>;
5
- getToken: (chain: ChainKey | ChainId, token: string, options?: RequestOptions | undefined) => Promise<Token>;
6
- getQuote: (request: QuoteRequest, options?: RequestOptions | undefined) => Promise<Step>;
7
- getContractCallQuote: (request: ContractCallQuoteRequest, options?: RequestOptions | undefined) => Promise<Step>;
8
- getStatus: ({ bridge, fromChain, toChain, txHash }: GetStatusRequest, options?: RequestOptions | undefined) => Promise<StatusResponse>;
9
4
  getChains: (options?: RequestOptions | undefined) => Promise<ExtendedChain[]>;
10
- getRoutes: (request: RoutesRequest, options?: RequestOptions | undefined) => Promise<RoutesResponse>;
5
+ getContractCallQuote: (requestConfig: ContractCallQuoteRequest, options?: RequestOptions | undefined) => Promise<Step>;
6
+ getGasRecommendation: ({ chainId, fromChain, fromToken }: GasRecommendationRequest, options?: RequestOptions | undefined) => Promise<GasRecommendationResponse>;
7
+ getPossibilities: (requestConfig?: PossibilitiesRequest | undefined, options?: RequestOptions | undefined) => Promise<PossibilitiesResponse>;
8
+ getQuote: (requestConfig: QuoteRequest, options?: RequestOptions | undefined) => Promise<Step>;
9
+ getRoutes: (requestConfig: RoutesRequest, options?: RequestOptions | undefined) => Promise<RoutesResponse>;
10
+ getStatus: ({ bridge, fromChain, toChain, txHash }: GetStatusRequest, options?: RequestOptions | undefined) => Promise<StatusResponse>;
11
11
  getStepTransaction: (step: Step, options?: RequestOptions | undefined) => Promise<Step>;
12
- getTools: (request?: ToolsRequest | undefined, options?: RequestOptions | undefined) => Promise<ToolsResponse>;
13
- getTokens: (request?: TokensRequest | undefined, options?: RequestOptions | undefined) => Promise<TokensResponse>;
12
+ getToken: (chain: ChainKey | ChainId, token: string, options?: RequestOptions | undefined) => Promise<Token>;
13
+ getTokens: (requestConfig?: TokensRequest | undefined, options?: RequestOptions | undefined) => Promise<TokensResponse>;
14
+ getTools: (requestConfig?: ToolsRequest | undefined, options?: RequestOptions | undefined) => Promise<ToolsResponse>;
14
15
  };
15
16
  export default _default;