@lifi/sdk 1.0.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 (63) hide show
  1. package/CHANGELOG.md +354 -0
  2. package/LICENSE +1 -0
  3. package/README.md +16 -0
  4. package/dist/Lifi.d.ts +186 -0
  5. package/dist/Lifi.js +461 -0
  6. package/dist/allowance/index.d.ts +22 -0
  7. package/dist/allowance/index.js +160 -0
  8. package/dist/allowance/utils.d.ts +14 -0
  9. package/dist/allowance/utils.js +137 -0
  10. package/dist/balances/index.d.ts +11 -0
  11. package/dist/balances/index.js +104 -0
  12. package/dist/balances/utils.d.ts +5 -0
  13. package/dist/balances/utils.js +255 -0
  14. package/dist/connectors.d.ts +6 -0
  15. package/dist/connectors.js +150 -0
  16. package/dist/execution/StatusManager.d.ts +63 -0
  17. package/dist/execution/StatusManager.js +150 -0
  18. package/dist/execution/StepExecutor.d.ts +15 -0
  19. package/dist/execution/StepExecutor.js +139 -0
  20. package/dist/execution/allowance.execute.d.ts +4 -0
  21. package/dist/execution/allowance.execute.js +156 -0
  22. package/dist/execution/balanceCheck.execute.d.ts +3 -0
  23. package/dist/execution/balanceCheck.execute.js +86 -0
  24. package/dist/execution/bridges/bridge.execute.d.ts +7 -0
  25. package/dist/execution/bridges/bridge.execute.js +218 -0
  26. package/dist/execution/exchanges/swap.execute.d.ts +7 -0
  27. package/dist/execution/exchanges/swap.execute.js +222 -0
  28. package/dist/execution/index.d.ts +1 -0
  29. package/dist/execution/index.js +17 -0
  30. package/dist/execution/switchChain.d.ts +16 -0
  31. package/dist/execution/switchChain.js +102 -0
  32. package/dist/execution/utils.d.ts +5 -0
  33. package/dist/execution/utils.js +175 -0
  34. package/dist/helpers.d.ts +18 -0
  35. package/dist/helpers.js +85 -0
  36. package/dist/index.d.ts +6 -0
  37. package/dist/index.js +27 -0
  38. package/dist/services/ApiService.d.ts +14 -0
  39. package/dist/services/ApiService.js +350 -0
  40. package/dist/services/ChainsService.d.ts +11 -0
  41. package/dist/services/ChainsService.js +108 -0
  42. package/dist/services/ConfigService.d.ts +23 -0
  43. package/dist/services/ConfigService.js +133 -0
  44. package/dist/typeguards.d.ts +4 -0
  45. package/dist/typeguards.js +55 -0
  46. package/dist/types/ERC20.d.ts +22 -0
  47. package/dist/types/ERC20.js +53 -0
  48. package/dist/types/index.d.ts +4 -0
  49. package/dist/types/index.js +22 -0
  50. package/dist/types/internal.types.d.ts +75 -0
  51. package/dist/types/internal.types.js +2 -0
  52. package/dist/utils/errors.d.ts +73 -0
  53. package/dist/utils/errors.js +147 -0
  54. package/dist/utils/getProvider.d.ts +3 -0
  55. package/dist/utils/getProvider.js +11 -0
  56. package/dist/utils/multicall.d.ts +10 -0
  57. package/dist/utils/multicall.js +111 -0
  58. package/dist/utils/multicallAbi.json +313 -0
  59. package/dist/utils/parseError.d.ts +37 -0
  60. package/dist/utils/parseError.js +184 -0
  61. package/dist/utils/utils.d.ts +26 -0
  62. package/dist/utils/utils.js +188 -0
  63. package/package.json +90 -0
@@ -0,0 +1,63 @@
1
+ import { Execution, InternalExecutionSettings, Process, ProcessType, Route, Status, Step, Token } from '../types';
2
+ interface Receipt {
3
+ fromAmount?: string;
4
+ toAmount?: string;
5
+ toToken?: Token;
6
+ }
7
+ declare type InternalUpdateRouteCallback = (route: Route) => void;
8
+ declare type OptionalParameters = Partial<Pick<Process, 'doneAt' | 'failedAt' | 'txHash' | 'txLink' | 'error' | 'substatus' | 'substatusMessage'>>;
9
+ /**
10
+ * Manages status updates of a route and provides various functions for tracking processes
11
+ * @param {Route} route The route this StatusManger belongs to.
12
+ * @param {InternalExecutionSettings} settings The ExecutionSettings for this route.
13
+ * @param {InternalUpdateRouteCallback} internalUpdateRouteCallback Internal callback to propage route changes.
14
+ * @return {StatusManager} An instance of StatusManager.
15
+ */
16
+ export declare class StatusManager {
17
+ private readonly route;
18
+ private readonly settings;
19
+ private readonly internalUpdateRouteCallback;
20
+ private shouldUpdate;
21
+ constructor(route: Route, settings: InternalExecutionSettings, internalUpdateRouteCallback: InternalUpdateRouteCallback);
22
+ /**
23
+ * Initializes the execution object of a Step.
24
+ * @param {Step} step The current step in execution
25
+ * @return {Execution} The initialized execution object for this step and a function to update this step
26
+ */
27
+ initExecutionObject: (step: Step) => Execution;
28
+ /**
29
+ * Updates the execution object of a Step.
30
+ * @param {Step} step The current step in execution
31
+ * @param {Status} status The status for the execution
32
+ * @param {Receipt} receipt Optional. Information about received tokens
33
+ * @return {Step} The step with the updated execution object
34
+ */
35
+ updateExecution(step: Step, status: Status, receipt?: Receipt): Step;
36
+ /**
37
+ * Create and push a new process into the execution.
38
+ * @param {ProcessType} type Type of the process. Used to identify already existing processes.
39
+ * @param {Step} step The step that should contain the new process.
40
+ * @param {Status} status By default created procces is set to the STARTED status. We can override new process with the needed status.
41
+ * @return {Process}
42
+ */
43
+ findOrCreateProcess: (type: ProcessType, step: Step, status?: Status) => Process;
44
+ /**
45
+ * Update a process object.
46
+ * @param {Step} step The step where the process should be updated
47
+ * @param {ProcessType} type The process type to update
48
+ * @param {Status} status The status the process gets.
49
+ * @param {object} [params] Additional parameters to append to the process.
50
+ * @return {Process} The update process
51
+ */
52
+ updateProcess: (step: Step, type: ProcessType, status: Status, params?: OptionalParameters) => Process;
53
+ /**
54
+ * Remove a process from the execution
55
+ * @param {Step} step The step where the process should be removed from
56
+ * @param {ProcessType} type The process type to remove
57
+ * @return {void}
58
+ */
59
+ removeProcess: (step: Step, type: ProcessType) => void;
60
+ private updateStepInRoute;
61
+ setShouldUpdate(value: boolean): void;
62
+ }
63
+ export {};
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StatusManager = void 0;
4
+ var types_1 = require("../types");
5
+ var utils_1 = require("../utils/utils");
6
+ var utils_2 = require("./utils");
7
+ /**
8
+ * Manages status updates of a route and provides various functions for tracking processes
9
+ * @param {Route} route The route this StatusManger belongs to.
10
+ * @param {InternalExecutionSettings} settings The ExecutionSettings for this route.
11
+ * @param {InternalUpdateRouteCallback} internalUpdateRouteCallback Internal callback to propage route changes.
12
+ * @return {StatusManager} An instance of StatusManager.
13
+ */
14
+ var StatusManager = /** @class */ (function () {
15
+ function StatusManager(route, settings, internalUpdateRouteCallback) {
16
+ var _this = this;
17
+ this.shouldUpdate = true;
18
+ /**
19
+ * Initializes the execution object of a Step.
20
+ * @param {Step} step The current step in execution
21
+ * @return {Execution} The initialized execution object for this step and a function to update this step
22
+ */
23
+ this.initExecutionObject = function (step) {
24
+ var currentExecution = step.execution || (0, utils_1.deepClone)(types_1.emptyExecution);
25
+ if (!step.execution) {
26
+ step.execution = currentExecution;
27
+ _this.updateStepInRoute(step);
28
+ }
29
+ return currentExecution;
30
+ };
31
+ /**
32
+ * Create and push a new process into the execution.
33
+ * @param {ProcessType} type Type of the process. Used to identify already existing processes.
34
+ * @param {Step} step The step that should contain the new process.
35
+ * @param {Status} status By default created procces is set to the STARTED status. We can override new process with the needed status.
36
+ * @return {Process}
37
+ */
38
+ this.findOrCreateProcess = function (type, step, status) {
39
+ if (!step.execution || !step.execution.process) {
40
+ throw new Error("Execution hasn't been initialized.");
41
+ }
42
+ var process = step.execution.process.find(function (p) { return p.type === type; });
43
+ if (process) {
44
+ return process;
45
+ }
46
+ var newProcess = {
47
+ type: type,
48
+ startedAt: Date.now(),
49
+ message: (0, utils_2.getProcessMessage)(type, status !== null && status !== void 0 ? status : 'STARTED'),
50
+ status: status !== null && status !== void 0 ? status : 'STARTED',
51
+ };
52
+ step.execution.process.push(newProcess);
53
+ _this.updateStepInRoute(step);
54
+ return newProcess;
55
+ };
56
+ /**
57
+ * Update a process object.
58
+ * @param {Step} step The step where the process should be updated
59
+ * @param {ProcessType} type The process type to update
60
+ * @param {Status} status The status the process gets.
61
+ * @param {object} [params] Additional parameters to append to the process.
62
+ * @return {Process} The update process
63
+ */
64
+ this.updateProcess = function (step, type, status, params) {
65
+ var _a;
66
+ var currentProcess = (_a = step === null || step === void 0 ? void 0 : step.execution) === null || _a === void 0 ? void 0 : _a.process.find(function (p) { return p.type === type; });
67
+ if (!currentProcess) {
68
+ throw new Error("Can't find a process for the given type.");
69
+ }
70
+ switch (status) {
71
+ case 'CANCELLED':
72
+ currentProcess.doneAt = Date.now();
73
+ break;
74
+ case 'FAILED':
75
+ currentProcess.doneAt = Date.now();
76
+ break;
77
+ case 'DONE':
78
+ currentProcess.doneAt = Date.now();
79
+ break;
80
+ default:
81
+ break;
82
+ }
83
+ currentProcess.status = status;
84
+ currentProcess.message = (0, utils_2.getProcessMessage)(type, status);
85
+ // set extra parameters or overwritte the standard params set in the switch statement
86
+ if (params) {
87
+ for (var _i = 0, _b = Object.entries(params); _i < _b.length; _i++) {
88
+ var _c = _b[_i], key = _c[0], value = _c[1];
89
+ currentProcess[key] = value;
90
+ }
91
+ }
92
+ _this.updateStepInRoute(step); // updates the step in the route
93
+ return currentProcess;
94
+ };
95
+ /**
96
+ * Remove a process from the execution
97
+ * @param {Step} step The step where the process should be removed from
98
+ * @param {ProcessType} type The process type to remove
99
+ * @return {void}
100
+ */
101
+ this.removeProcess = function (step, type) {
102
+ if (!step.execution) {
103
+ throw new Error("Execution hasn't been initialized.");
104
+ }
105
+ var index = step.execution.process.findIndex(function (p) { return p.type === type; });
106
+ step.execution.process.splice(index, 1);
107
+ _this.updateStepInRoute(step);
108
+ };
109
+ this.updateStepInRoute = function (step) {
110
+ if (!_this.shouldUpdate) {
111
+ return;
112
+ }
113
+ var stepIndex = _this.route.steps.findIndex(function (routeStep) { return routeStep.id === step.id; });
114
+ if (stepIndex === -1) {
115
+ throw new Error("Couldn't find a step to update.");
116
+ }
117
+ _this.route.steps[stepIndex] = Object.assign(_this.route.steps[stepIndex], step);
118
+ _this.settings.updateCallback(_this.route);
119
+ _this.internalUpdateRouteCallback(_this.route);
120
+ };
121
+ this.route = route;
122
+ this.settings = settings;
123
+ this.internalUpdateRouteCallback = internalUpdateRouteCallback;
124
+ }
125
+ /**
126
+ * Updates the execution object of a Step.
127
+ * @param {Step} step The current step in execution
128
+ * @param {Status} status The status for the execution
129
+ * @param {Receipt} receipt Optional. Information about received tokens
130
+ * @return {Step} The step with the updated execution object
131
+ */
132
+ StatusManager.prototype.updateExecution = function (step, status, receipt) {
133
+ if (!step.execution) {
134
+ throw Error("Can't update empty execution.");
135
+ }
136
+ step.execution.status = status;
137
+ if (receipt) {
138
+ step.execution.fromAmount = receipt.fromAmount;
139
+ step.execution.toAmount = receipt.toAmount;
140
+ step.execution.toToken = receipt.toToken;
141
+ }
142
+ this.updateStepInRoute(step);
143
+ return step;
144
+ };
145
+ StatusManager.prototype.setShouldUpdate = function (value) {
146
+ this.shouldUpdate = value;
147
+ };
148
+ return StatusManager;
149
+ }());
150
+ exports.StatusManager = StatusManager;
@@ -0,0 +1,15 @@
1
+ import { Signer } from 'ethers';
2
+ import { HaltingSettings, InternalExecutionSettings, Step } from '../types';
3
+ import { StatusManager } from './StatusManager';
4
+ export declare class StepExecutor {
5
+ settings: InternalExecutionSettings;
6
+ statusManager: StatusManager;
7
+ private swapExecutionManager;
8
+ private bridgeExecutionManager;
9
+ executionStopped: boolean;
10
+ constructor(statusManager: StatusManager, settings: InternalExecutionSettings);
11
+ stopStepExecution: (settings?: HaltingSettings) => void;
12
+ executeStep: (signer: Signer, step: Step) => Promise<Step>;
13
+ private executeSwap;
14
+ private executeCross;
15
+ }
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (_) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.StepExecutor = void 0;
51
+ var bridge_execute_1 = require("./bridges/bridge.execute");
52
+ var swap_execute_1 = require("./exchanges/swap.execute");
53
+ var switchChain_1 = require("./switchChain");
54
+ var defaultExecutionHaltSettings = {
55
+ allowUpdates: true,
56
+ };
57
+ var StepExecutor = /** @class */ (function () {
58
+ function StepExecutor(statusManager, settings) {
59
+ var _this = this;
60
+ this.swapExecutionManager = new swap_execute_1.SwapExecutionManager();
61
+ this.bridgeExecutionManager = new bridge_execute_1.BridgeExecutionManager();
62
+ this.executionStopped = false;
63
+ this.stopStepExecution = function (settings) {
64
+ var haltingSettings = __assign(__assign({}, defaultExecutionHaltSettings), settings);
65
+ _this.swapExecutionManager.setShouldContinue(false);
66
+ _this.bridgeExecutionManager.setShouldContinue(false);
67
+ _this.statusManager.setShouldUpdate(haltingSettings.allowUpdates);
68
+ _this.executionStopped = true;
69
+ };
70
+ this.executeStep = function (signer, step) { return __awaiter(_this, void 0, void 0, function () {
71
+ var updatedSigner, _a;
72
+ return __generator(this, function (_b) {
73
+ switch (_b.label) {
74
+ case 0: return [4 /*yield*/, (0, switchChain_1.switchChain)(signer, this.statusManager, step, this.settings.switchChainHook, !this.executionStopped)];
75
+ case 1:
76
+ updatedSigner = _b.sent();
77
+ if (!updatedSigner) {
78
+ // chain switch was not successful, stop execution here
79
+ return [2 /*return*/, step];
80
+ }
81
+ signer = updatedSigner;
82
+ _a = step.type;
83
+ switch (_a) {
84
+ case 'lifi': return [3 /*break*/, 2];
85
+ case 'cross': return [3 /*break*/, 2];
86
+ case 'swap': return [3 /*break*/, 4];
87
+ }
88
+ return [3 /*break*/, 6];
89
+ case 2: return [4 /*yield*/, this.executeCross(signer, step)];
90
+ case 3:
91
+ _b.sent();
92
+ return [3 /*break*/, 7];
93
+ case 4: return [4 /*yield*/, this.executeSwap(signer, step)];
94
+ case 5:
95
+ _b.sent();
96
+ return [3 /*break*/, 7];
97
+ case 6: throw new Error('Unsupported step type.');
98
+ case 7: return [2 /*return*/, step];
99
+ }
100
+ });
101
+ }); };
102
+ this.executeSwap = function (signer, step) { return __awaiter(_this, void 0, void 0, function () {
103
+ var swapParams;
104
+ return __generator(this, function (_a) {
105
+ switch (_a.label) {
106
+ case 0:
107
+ swapParams = {
108
+ signer: signer,
109
+ step: step,
110
+ settings: this.settings,
111
+ statusManager: this.statusManager,
112
+ };
113
+ return [4 /*yield*/, this.swapExecutionManager.execute(swapParams)];
114
+ case 1: return [2 /*return*/, _a.sent()];
115
+ }
116
+ });
117
+ }); };
118
+ this.executeCross = function (signer, step) { return __awaiter(_this, void 0, void 0, function () {
119
+ var crossParams;
120
+ return __generator(this, function (_a) {
121
+ switch (_a.label) {
122
+ case 0:
123
+ crossParams = {
124
+ signer: signer,
125
+ step: step,
126
+ settings: this.settings,
127
+ statusManager: this.statusManager,
128
+ };
129
+ return [4 /*yield*/, this.bridgeExecutionManager.execute(crossParams)];
130
+ case 1: return [2 /*return*/, _a.sent()];
131
+ }
132
+ });
133
+ }); };
134
+ this.statusManager = statusManager;
135
+ this.settings = settings;
136
+ }
137
+ return StepExecutor;
138
+ }());
139
+ exports.StepExecutor = StepExecutor;
@@ -0,0 +1,4 @@
1
+ import { Signer } from 'ethers';
2
+ import { Chain, Step, Token } from '../types';
3
+ import { StatusManager } from './StatusManager';
4
+ export declare const checkAllowance: (signer: Signer, step: Step, chain: Chain, token: Token, amount: string, spenderAddress: string, statusManager: StatusManager, infiniteApproval?: boolean, allowUserInteraction?: boolean) => Promise<void>;
@@ -0,0 +1,156 @@
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
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.checkAllowance = void 0;
43
+ var bignumber_js_1 = __importDefault(require("bignumber.js"));
44
+ var ethers_1 = require("ethers");
45
+ var utils_1 = require("../allowance/utils");
46
+ var getProvider_1 = require("../utils/getProvider");
47
+ var parseError_1 = require("../utils/parseError");
48
+ var checkAllowance = function (signer, step, chain, token, amount, spenderAddress, statusManager, infiniteApproval, allowUserInteraction
49
+ // eslint-disable-next-line max-params
50
+ ) {
51
+ if (infiniteApproval === void 0) { infiniteApproval = false; }
52
+ if (allowUserInteraction === void 0) { allowUserInteraction = false; }
53
+ return __awaiter(void 0, void 0, void 0, function () {
54
+ var allowanceProcess, approved, approvalAmount, approveTx, e_1, error;
55
+ return __generator(this, function (_a) {
56
+ switch (_a.label) {
57
+ case 0:
58
+ allowanceProcess = statusManager.findOrCreateProcess('TOKEN_ALLOWANCE', step);
59
+ _a.label = 1;
60
+ case 1:
61
+ _a.trys.push([1, 10, , 15]);
62
+ if (!allowanceProcess.txHash) return [3 /*break*/, 3];
63
+ statusManager.updateProcess(step, allowanceProcess.type, 'PENDING');
64
+ return [4 /*yield*/, (0, getProvider_1.getProvider)(signer).waitForTransaction(allowanceProcess.txHash)];
65
+ case 2:
66
+ _a.sent();
67
+ statusManager.updateProcess(step, allowanceProcess.type, 'DONE');
68
+ return [3 /*break*/, 9];
69
+ case 3:
70
+ if (!(allowanceProcess.status === 'DONE')) return [3 /*break*/, 4];
71
+ statusManager.updateProcess(step, allowanceProcess.type, 'DONE');
72
+ return [3 /*break*/, 9];
73
+ case 4: return [4 /*yield*/, (0, utils_1.getApproved)(signer, token.address, spenderAddress)];
74
+ case 5:
75
+ approved = _a.sent();
76
+ if (!new bignumber_js_1.default(amount).gt(approved)) return [3 /*break*/, 8];
77
+ if (!allowUserInteraction) {
78
+ return [2 /*return*/];
79
+ }
80
+ approvalAmount = infiniteApproval
81
+ ? ethers_1.constants.MaxUint256.toString()
82
+ : amount;
83
+ return [4 /*yield*/, (0, utils_1.setApproval)(signer, token.address, spenderAddress, approvalAmount)
84
+ // update currentExecution
85
+ ];
86
+ case 6:
87
+ approveTx = _a.sent();
88
+ // update currentExecution
89
+ statusManager.updateProcess(step, allowanceProcess.type, 'PENDING', {
90
+ txHash: approveTx.hash,
91
+ txLink: chain.metamask.blockExplorerUrls[0] + 'tx/' + approveTx.hash,
92
+ });
93
+ // wait for transcation
94
+ return [4 /*yield*/, approveTx.wait()];
95
+ case 7:
96
+ // wait for transcation
97
+ _a.sent();
98
+ statusManager.updateProcess(step, allowanceProcess.type, 'DONE');
99
+ return [3 /*break*/, 9];
100
+ case 8:
101
+ statusManager.updateProcess(step, allowanceProcess.type, 'DONE');
102
+ _a.label = 9;
103
+ case 9: return [3 /*break*/, 15];
104
+ case 10:
105
+ e_1 = _a.sent();
106
+ if (!(e_1.code === 'TRANSACTION_REPLACED' && e_1.replacement)) return [3 /*break*/, 12];
107
+ return [4 /*yield*/, transactionReplaced(e_1.replacement, allowanceProcess, step, chain, statusManager)];
108
+ case 11:
109
+ _a.sent();
110
+ return [3 /*break*/, 14];
111
+ case 12: return [4 /*yield*/, (0, parseError_1.parseError)(e_1, step, allowanceProcess)];
112
+ case 13:
113
+ error = _a.sent();
114
+ statusManager.updateProcess(step, allowanceProcess.type, 'FAILED', {
115
+ error: {
116
+ message: error.message,
117
+ htmlMessage: error.htmlMessage,
118
+ code: error.code,
119
+ },
120
+ });
121
+ statusManager.updateExecution(step, 'FAILED');
122
+ throw error;
123
+ case 14: return [3 /*break*/, 15];
124
+ case 15: return [2 /*return*/];
125
+ }
126
+ });
127
+ });
128
+ };
129
+ exports.checkAllowance = checkAllowance;
130
+ var transactionReplaced = function (replacementTx, allowanceProcess, step, chain, statusManager) { return __awaiter(void 0, void 0, void 0, function () {
131
+ var e_2;
132
+ return __generator(this, function (_a) {
133
+ switch (_a.label) {
134
+ case 0:
135
+ _a.trys.push([0, 2, , 5]);
136
+ statusManager.updateProcess(step, allowanceProcess.type, 'PENDING', {
137
+ txHash: replacementTx.hash,
138
+ txLink: chain.metamask.blockExplorerUrls[0] + 'tx/' + replacementTx.hash,
139
+ });
140
+ return [4 /*yield*/, replacementTx.wait()];
141
+ case 1:
142
+ _a.sent();
143
+ statusManager.updateProcess(step, allowanceProcess.type, 'DONE');
144
+ return [3 /*break*/, 5];
145
+ case 2:
146
+ e_2 = _a.sent();
147
+ if (!(e_2.code === 'TRANSACTION_REPLACED' && e_2.replacement)) return [3 /*break*/, 4];
148
+ return [4 /*yield*/, transactionReplaced(e_2.replacement, allowanceProcess, step, chain, statusManager)];
149
+ case 3:
150
+ _a.sent();
151
+ _a.label = 4;
152
+ case 4: throw e_2;
153
+ case 5: return [2 /*return*/];
154
+ }
155
+ });
156
+ }); };
@@ -0,0 +1,3 @@
1
+ import { ethers } from 'ethers';
2
+ import { Step } from '..';
3
+ export declare const balanceCheck: (signer: ethers.Signer, step: Step) => Promise<void>;
@@ -0,0 +1,86 @@
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
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.balanceCheck = void 0;
43
+ var bignumber_js_1 = __importDefault(require("bignumber.js"));
44
+ var balances_1 = __importDefault(require("../balances"));
45
+ var errors_1 = require("../utils/errors");
46
+ var balanceCheck = function (signer, step) { return __awaiter(void 0, void 0, void 0, function () {
47
+ var tokenAmount, _a, _b, currentBalance, neededBalance, neeeded, current, errorMessage;
48
+ return __generator(this, function (_c) {
49
+ switch (_c.label) {
50
+ case 0:
51
+ _b = (_a = balances_1.default).getTokenBalance;
52
+ return [4 /*yield*/, signer.getAddress()];
53
+ case 1: return [4 /*yield*/, _b.apply(_a, [_c.sent(), step.action.fromToken])];
54
+ case 2:
55
+ tokenAmount = _c.sent();
56
+ if (tokenAmount) {
57
+ currentBalance = new bignumber_js_1.default(tokenAmount.amount).shiftedBy(tokenAmount.decimals);
58
+ neededBalance = new bignumber_js_1.default(step.action.fromAmount);
59
+ if (currentBalance.lt(neededBalance)) {
60
+ if (neededBalance.multipliedBy(1 - step.action.slippage).lte(currentBalance)) {
61
+ // adjust amount in slippage limits
62
+ step.action.fromAmount = currentBalance.toFixed(0);
63
+ }
64
+ else {
65
+ neeeded = neededBalance.shiftedBy(-tokenAmount.decimals).toFixed();
66
+ current = currentBalance
67
+ .shiftedBy(-tokenAmount.decimals)
68
+ .toFixed();
69
+ errorMessage = "Your ".concat(tokenAmount.symbol, " balance is too low, ") +
70
+ "you try to transfer ".concat(neeeded, " ").concat(tokenAmount.symbol, ", ") +
71
+ "but your wallet only holds ".concat(current, " ").concat(tokenAmount.symbol, ". ") +
72
+ "No funds have been sent. ";
73
+ if (!currentBalance.isZero()) {
74
+ errorMessage +=
75
+ "If the problem consists, please delete this transfer and " +
76
+ "start a new one with a maximum of ".concat(current, " ").concat(tokenAmount.symbol, ".");
77
+ }
78
+ throw new errors_1.ValidationError('The balance is too low.', errorMessage);
79
+ }
80
+ }
81
+ }
82
+ return [2 /*return*/];
83
+ }
84
+ });
85
+ }); };
86
+ exports.balanceCheck = balanceCheck;
@@ -0,0 +1,7 @@
1
+ import { Execution } from '@lifi/types';
2
+ import { ExecuteCrossParams } from '../../types';
3
+ export declare class BridgeExecutionManager {
4
+ shouldContinue: boolean;
5
+ setShouldContinue: (val: boolean) => void;
6
+ execute: ({ signer, step, statusManager, settings, }: ExecuteCrossParams) => Promise<Execution>;
7
+ }