@lifi/sdk 1.0.2 → 1.1.2

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.
@@ -1,4 +1,15 @@
1
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
+ };
2
13
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
14
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
15
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -49,6 +60,7 @@ var parseError_1 = require("../../utils/parseError");
49
60
  var utils_1 = require("../../utils/utils");
50
61
  var allowance_execute_1 = require("../allowance.execute");
51
62
  var balanceCheck_execute_1 = require("../balanceCheck.execute");
63
+ var stepComparison_1 = require("../stepComparison");
52
64
  var switchChain_1 = require("../switchChain");
53
65
  var utils_2 = require("../utils");
54
66
  var SwapExecutionManager = /** @class */ (function () {
@@ -61,10 +73,10 @@ var SwapExecutionManager = /** @class */ (function () {
61
73
  this.execute = function (_a) {
62
74
  var signer = _a.signer, step = _a.step, statusManager = _a.statusManager, settings = _a.settings;
63
75
  return __awaiter(_this, void 0, void 0, function () {
64
- var action, estimate, chainsService, fromChain, swapProcess, tx, personalizedStep, transactionRequest, updatedSigner, e_1, error, receipt, e_2, error, statusResponse, e_3;
65
- var _b, _c, _d, _e;
66
- return __generator(this, function (_f) {
67
- switch (_f.label) {
76
+ var action, estimate, chainsService, fromChain, swapProcess, tx, personalizedStep, updatedStep, _b, transactionRequest, updatedSigner, e_1, error, receipt, e_2, error, statusResponse, e_3;
77
+ var _c, _d, _e, _f;
78
+ return __generator(this, function (_g) {
79
+ switch (_g.label) {
68
80
  case 0:
69
81
  action = step.action, estimate = step.estimate;
70
82
  step.execution = statusManager.initExecutionObject(step);
@@ -73,23 +85,23 @@ var SwapExecutionManager = /** @class */ (function () {
73
85
  // Approval
74
86
  ];
75
87
  case 1:
76
- fromChain = _f.sent();
88
+ fromChain = _g.sent();
77
89
  if (!(action.fromToken.address !== ethers_1.constants.AddressZero)) return [3 /*break*/, 3];
78
90
  return [4 /*yield*/, (0, allowance_execute_1.checkAllowance)(signer, step, fromChain, action.fromToken, action.fromAmount, estimate.approvalAddress, statusManager, settings.infiniteApproval, this.shouldContinue)];
79
91
  case 2:
80
- _f.sent();
81
- _f.label = 3;
92
+ _g.sent();
93
+ _g.label = 3;
82
94
  case 3:
83
95
  swapProcess = statusManager.findOrCreateProcess('SWAP', step);
84
- _f.label = 4;
96
+ _g.label = 4;
85
97
  case 4:
86
- _f.trys.push([4, 13, , 15]);
98
+ _g.trys.push([4, 14, , 16]);
87
99
  if (!swapProcess.txHash) return [3 /*break*/, 6];
88
100
  return [4 /*yield*/, (0, getProvider_1.getProvider)(signer).getTransaction(swapProcess.txHash)];
89
101
  case 5:
90
102
  // -> restore existing tx
91
- tx = _f.sent();
92
- return [3 /*break*/, 12];
103
+ tx = _g.sent();
104
+ return [3 /*break*/, 13];
93
105
  case 6:
94
106
  // -> check balance
95
107
  return [4 /*yield*/, (0, balanceCheck_execute_1.balanceCheck)(signer, step)
@@ -97,41 +109,46 @@ var SwapExecutionManager = /** @class */ (function () {
97
109
  ];
98
110
  case 7:
99
111
  // -> check balance
100
- _f.sent();
112
+ _g.sent();
101
113
  return [4 /*yield*/, (0, utils_1.personalizeStep)(signer, step)];
102
114
  case 8:
103
- personalizedStep = _f.sent();
115
+ personalizedStep = _g.sent();
104
116
  return [4 /*yield*/, ApiService_1.default.getStepTransaction(personalizedStep)];
105
117
  case 9:
106
- transactionRequest = (_f.sent()).transactionRequest;
118
+ updatedStep = _g.sent();
119
+ _b = [{}];
120
+ return [4 /*yield*/, (0, stepComparison_1.stepComparison)(statusManager, personalizedStep, updatedStep, settings.acceptSlippageUpdateHook, this.shouldContinue)];
121
+ case 10:
122
+ step = __assign.apply(void 0, [__assign.apply(void 0, _b.concat([(_g.sent())])), { execution: step.execution }]);
123
+ transactionRequest = step.transactionRequest;
107
124
  if (!transactionRequest) {
108
125
  throw new errors_1.TransactionError(errors_1.LifiErrorCode.TransactionUnprepared, 'Unable to prepare transaction.');
109
126
  }
110
127
  return [4 /*yield*/, (0, switchChain_1.switchChain)(signer, statusManager, step, settings.switchChainHook, this.shouldContinue)];
111
- case 10:
112
- updatedSigner = _f.sent();
128
+ case 11:
129
+ updatedSigner = _g.sent();
113
130
  if (!updatedSigner) {
114
131
  // chain switch was not successful, stop execution here
115
132
  return [2 /*return*/, step.execution];
116
133
  }
117
134
  signer = updatedSigner;
118
135
  // -> set step.execution
119
- statusManager.updateProcess(step, swapProcess.type, 'ACTION_REQUIRED');
136
+ swapProcess = swapProcess = statusManager.updateProcess(step, swapProcess.type, 'ACTION_REQUIRED');
120
137
  if (!this.shouldContinue) {
121
138
  return [2 /*return*/, step.execution]; // stop before user interaction is needed
122
139
  }
123
140
  return [4 /*yield*/, signer.sendTransaction(transactionRequest)];
124
- case 11:
141
+ case 12:
125
142
  // -> submit tx
126
- tx = _f.sent();
127
- _f.label = 12;
128
- case 12: return [3 /*break*/, 15];
129
- case 13:
130
- e_1 = _f.sent();
131
- return [4 /*yield*/, (0, parseError_1.parseError)(e_1, step, swapProcess)];
143
+ tx = _g.sent();
144
+ _g.label = 13;
145
+ case 13: return [3 /*break*/, 16];
132
146
  case 14:
133
- error = _f.sent();
134
- statusManager.updateProcess(step, swapProcess.type, 'FAILED', {
147
+ e_1 = _g.sent();
148
+ return [4 /*yield*/, (0, parseError_1.parseError)(e_1, step, swapProcess)];
149
+ case 15:
150
+ error = _g.sent();
151
+ swapProcess = statusManager.updateProcess(step, swapProcess.type, 'FAILED', {
135
152
  error: {
136
153
  message: error.message,
137
154
  htmlMessage: error.htmlMessage,
@@ -140,34 +157,34 @@ var SwapExecutionManager = /** @class */ (function () {
140
157
  });
141
158
  statusManager.updateExecution(step, 'FAILED');
142
159
  throw error;
143
- case 15:
160
+ case 16:
144
161
  // Wait for Transaction
145
- statusManager.updateProcess(step, swapProcess.type, 'PENDING', {
162
+ swapProcess = statusManager.updateProcess(step, swapProcess.type, 'PENDING', {
146
163
  txLink: fromChain.metamask.blockExplorerUrls[0] + 'tx/' + tx.hash,
147
164
  txHash: tx.hash,
148
165
  });
149
- _f.label = 16;
150
- case 16:
151
- _f.trys.push([16, 18, , 22]);
152
- return [4 /*yield*/, tx.wait()];
166
+ _g.label = 17;
153
167
  case 17:
154
- receipt = _f.sent();
155
- return [3 /*break*/, 22];
168
+ _g.trys.push([17, 19, , 23]);
169
+ return [4 /*yield*/, tx.wait()];
156
170
  case 18:
157
- e_2 = _f.sent();
158
- if (!(e_2.code === 'TRANSACTION_REPLACED' && e_2.replacement)) return [3 /*break*/, 19];
171
+ receipt = _g.sent();
172
+ return [3 /*break*/, 23];
173
+ case 19:
174
+ e_2 = _g.sent();
175
+ if (!(e_2.code === 'TRANSACTION_REPLACED' && e_2.replacement)) return [3 /*break*/, 20];
159
176
  receipt = e_2.replacement;
160
- statusManager.updateProcess(step, swapProcess.type, 'PENDING', {
177
+ swapProcess = statusManager.updateProcess(step, swapProcess.type, 'PENDING', {
161
178
  txHash: e_2.replacement.hash,
162
179
  txLink: fromChain.metamask.blockExplorerUrls[0] +
163
180
  'tx/' +
164
181
  e_2.replacement.hash,
165
182
  });
166
- return [3 /*break*/, 21];
167
- case 19: return [4 /*yield*/, (0, parseError_1.parseError)(e_2)];
168
- case 20:
169
- error = _f.sent();
170
- statusManager.updateProcess(step, swapProcess.type, 'FAILED', {
183
+ return [3 /*break*/, 22];
184
+ case 20: return [4 /*yield*/, (0, parseError_1.parseError)(e_2)];
185
+ case 21:
186
+ error = _g.sent();
187
+ swapProcess = statusManager.updateProcess(step, swapProcess.type, 'FAILED', {
171
188
  error: {
172
189
  message: error.message,
173
190
  htmlMessage: error.htmlMessage,
@@ -176,19 +193,19 @@ var SwapExecutionManager = /** @class */ (function () {
176
193
  });
177
194
  statusManager.updateExecution(step, 'FAILED');
178
195
  throw error;
179
- case 21: return [3 /*break*/, 22];
180
- case 22:
181
- _f.trys.push([22, 24, , 25]);
196
+ case 22: return [3 /*break*/, 23];
197
+ case 23:
198
+ _g.trys.push([23, 25, , 26]);
182
199
  if (!swapProcess.txHash) {
183
200
  throw new Error('Transaction hash is undefined.');
184
201
  }
185
202
  return [4 /*yield*/, (0, utils_2.waitForReceivingTransaction)(swapProcess.txHash, statusManager, swapProcess.type, step)];
186
- case 23:
187
- statusResponse = _f.sent();
188
- return [3 /*break*/, 25];
189
203
  case 24:
190
- e_3 = _f.sent();
191
- statusManager.updateProcess(step, swapProcess.type, 'FAILED', {
204
+ statusResponse = _g.sent();
205
+ return [3 /*break*/, 26];
206
+ case 25:
207
+ e_3 = _g.sent();
208
+ swapProcess = statusManager.updateProcess(step, swapProcess.type, 'FAILED', {
192
209
  error: {
193
210
  code: errors_1.LifiErrorCode.TransactionFailed,
194
211
  message: 'Failed while waiting for receiving chain.',
@@ -197,18 +214,19 @@ var SwapExecutionManager = /** @class */ (function () {
197
214
  });
198
215
  statusManager.updateExecution(step, 'FAILED');
199
216
  throw e_3;
200
- case 25:
201
- statusManager.updateProcess(step, swapProcess.type, 'DONE', {
202
- txHash: (_b = statusResponse.receiving) === null || _b === void 0 ? void 0 : _b.txHash,
217
+ case 26:
218
+ swapProcess = statusManager.updateProcess(step, swapProcess.type, 'DONE', {
219
+ txHash: (_c = statusResponse.receiving) === null || _c === void 0 ? void 0 : _c.txHash,
203
220
  txLink: fromChain.metamask.blockExplorerUrls[0] +
204
221
  'tx/' +
205
- ((_c = statusResponse.receiving) === null || _c === void 0 ? void 0 : _c.txHash),
222
+ ((_d = statusResponse.receiving) === null || _d === void 0 ? void 0 : _d.txHash),
206
223
  });
207
224
  statusManager.updateExecution(step, 'DONE', {
208
225
  fromAmount: statusResponse.sending.amount,
209
- toAmount: (_d = statusResponse.receiving) === null || _d === void 0 ? void 0 : _d.amount,
210
- toToken: (_e = statusResponse.receiving) === null || _e === void 0 ? void 0 : _e.token,
211
- // gasUsed: statusResponse.gasUsed,
226
+ toAmount: (_e = statusResponse.receiving) === null || _e === void 0 ? void 0 : _e.amount,
227
+ toToken: (_f = statusResponse.receiving) === null || _f === void 0 ? void 0 : _f.token,
228
+ gasUsed: statusResponse.sending.gasUsed,
229
+ gasPrice: statusResponse.sending.gasPrice,
212
230
  });
213
231
  // DONE
214
232
  return [2 /*return*/, step.execution];
@@ -0,0 +1,14 @@
1
+ import { StatusManager } from '.';
2
+ import { AcceptSlippageUpdateHook, Step } from '../types';
3
+ /**
4
+ * This method checks whether the new and updated Step meets the required slippage conditions.
5
+ * If yes it returns the updated Step.
6
+ * If no and if user interaction is allowed it triggers the acceptSlippageUpdateHook. If no user interaction is allowed it aborts.
7
+ *
8
+ * @param statusManager
9
+ * @param oldStep
10
+ * @param newStep
11
+ * @param acceptSlippageUpdateHook
12
+ * @param allowUserInteraction
13
+ */
14
+ export declare const stepComparison: (statusManager: StatusManager, oldStep: Step, newStep: Step, acceptSlippageUpdateHook: AcceptSlippageUpdateHook, allowUserInteraction: boolean) => Promise<Step>;
@@ -0,0 +1,81 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.stepComparison = void 0;
40
+ var errors_1 = require("../utils/errors");
41
+ var parseError_1 = require("../utils/parseError");
42
+ var utils_1 = require("./utils");
43
+ /**
44
+ * This method checks whether the new and updated Step meets the required slippage conditions.
45
+ * If yes it returns the updated Step.
46
+ * If no and if user interaction is allowed it triggers the acceptSlippageUpdateHook. If no user interaction is allowed it aborts.
47
+ *
48
+ * @param statusManager
49
+ * @param oldStep
50
+ * @param newStep
51
+ * @param acceptSlippageUpdateHook
52
+ * @param allowUserInteraction
53
+ */
54
+ var stepComparison = function (statusManager, oldStep, newStep, acceptSlippageUpdateHook, allowUserInteraction) { return __awaiter(void 0, void 0, void 0, function () {
55
+ var allowStepUpdate;
56
+ return __generator(this, function (_a) {
57
+ switch (_a.label) {
58
+ case 0:
59
+ if ((0, utils_1.updatedStepMeetsSlippageConditions)(oldStep, newStep)) {
60
+ return [2 /*return*/, statusManager.updateStepInRoute(newStep)];
61
+ }
62
+ if (!allowUserInteraction) return [3 /*break*/, 2];
63
+ return [4 /*yield*/, acceptSlippageUpdateHook({
64
+ oldToAmount: oldStep.estimate.toAmount,
65
+ newToAmount: newStep.estimate.toAmount,
66
+ toToken: newStep.action.toToken,
67
+ oldSlippage: oldStep.action.slippage,
68
+ newSlippage: newStep.action.slippage,
69
+ })];
70
+ case 1:
71
+ allowStepUpdate = _a.sent();
72
+ _a.label = 2;
73
+ case 2:
74
+ if (!allowStepUpdate) {
75
+ throw new errors_1.TransactionError(errors_1.LifiErrorCode.SlippageNotMet, 'Slippage conditions not met!', (0, parseError_1.getSlippageNotMetMessage)(oldStep));
76
+ }
77
+ return [2 /*return*/, statusManager.updateStepInRoute(newStep)];
78
+ }
79
+ });
80
+ }); };
81
+ exports.stepComparison = stepComparison;
@@ -82,12 +82,12 @@ var switchChain = function (signer, statusManager, step, switchChainHook, allowU
82
82
  if (_a) {
83
83
  throw new errors_1.ProviderError(errors_1.LifiErrorCode.ChainSwitchError, 'Chain switch required.');
84
84
  }
85
- statusManager.updateProcess(step, switchProcess.type, 'DONE');
85
+ switchProcess = statusManager.updateProcess(step, switchProcess.type, 'DONE');
86
86
  statusManager.updateExecution(step, 'PENDING');
87
87
  return [2 /*return*/, updatedSigner];
88
88
  case 6:
89
89
  error_1 = _b.sent();
90
- statusManager.updateProcess(step, switchProcess.type, 'FAILED', {
90
+ switchProcess = statusManager.updateProcess(step, switchProcess.type, 'FAILED', {
91
91
  error: {
92
92
  message: error_1.message,
93
93
  code: error_1.code,
@@ -3,3 +3,4 @@ import { StatusManager } from '..';
3
3
  export declare function waitForReceivingTransaction(txHash: string, statusManager: StatusManager, processType: ProcessType, step: Step): Promise<StatusResponse>;
4
4
  export declare function getProcessMessage(type: ProcessType, status: Status): string | undefined;
5
5
  export declare function getSubstatusMessage(status: StatusMessage, substatus?: Substatus): string | undefined;
6
+ export declare function updatedStepMeetsSlippageConditions(oldStep: Step, newStep: Step): boolean;
@@ -39,7 +39,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
39
39
  return (mod && mod.__esModule) ? mod : { "default": mod };
40
40
  };
41
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
- exports.getSubstatusMessage = exports.getProcessMessage = exports.waitForReceivingTransaction = void 0;
42
+ exports.updatedStepMeetsSlippageConditions = exports.getSubstatusMessage = exports.getProcessMessage = exports.waitForReceivingTransaction = void 0;
43
+ var bignumber_js_1 = __importDefault(require("bignumber.js"));
43
44
  var ApiService_1 = __importDefault(require("../services/ApiService"));
44
45
  var errors_1 = require("../utils/errors");
45
46
  var utils_1 = require("../utils/utils");
@@ -173,3 +174,13 @@ function getSubstatusMessage(status, substatus) {
173
174
  return message;
174
175
  }
175
176
  exports.getSubstatusMessage = getSubstatusMessage;
177
+ function updatedStepMeetsSlippageConditions(oldStep, newStep) {
178
+ var setSlippage = new bignumber_js_1.default(oldStep.action.slippage);
179
+ var oldEstimatedToAmount = new bignumber_js_1.default(oldStep.estimate.toAmountMin);
180
+ var newEstimatedToAmount = new bignumber_js_1.default(newStep.estimate.toAmountMin);
181
+ var amountDifference = oldEstimatedToAmount.minus(newEstimatedToAmount);
182
+ var actualSlippage = amountDifference.dividedBy(oldEstimatedToAmount);
183
+ return (newEstimatedToAmount.gte(oldEstimatedToAmount) &&
184
+ actualSlippage.lte(setSlippage));
185
+ }
186
+ exports.updatedStepMeetsSlippageConditions = updatedStepMeetsSlippageConditions;
@@ -1,9 +1,10 @@
1
- import { GetStatusRequest, QuoteRequest, RequestOptions, TokensRequest, TokensResponse } from '@lifi/types';
1
+ import { ContractCallQuoteRequest, GetStatusRequest, QuoteRequest, RequestOptions, TokensRequest, TokensResponse } from '@lifi/types';
2
2
  import { ChainId, ChainKey, PossibilitiesRequest, PossibilitiesResponse, RoutesRequest, RoutesResponse, StatusResponse, Step, Token, ToolsRequest, ToolsResponse } from '../types';
3
3
  declare const _default: {
4
4
  getPossibilities: (request?: PossibilitiesRequest | undefined, options?: RequestOptions | undefined) => Promise<PossibilitiesResponse>;
5
5
  getToken: (chain: ChainKey | ChainId, token: string, options?: RequestOptions | undefined) => Promise<Token>;
6
- getQuote: ({ fromChain, fromToken, fromAddress, fromAmount, toChain, toToken, toAddress, order, slippage, integrator, referrer, allowBridges, denyBridges, preferBridges, allowExchanges, denyExchanges, preferExchanges, }: QuoteRequest, options?: RequestOptions | undefined) => Promise<Step>;
6
+ getQuote: (request: QuoteRequest, options?: RequestOptions | undefined) => Promise<Step>;
7
+ getContractCallQuote: (request: ContractCallQuoteRequest, options?: RequestOptions | undefined) => Promise<Step>;
7
8
  getStatus: ({ bridge, fromChain, toChain, txHash }: GetStatusRequest, options?: RequestOptions | undefined) => Promise<StatusResponse>;
8
9
  getChains: (options?: RequestOptions | undefined) => Promise<import("@lifi/types").EVMChain[]>;
9
10
  getRoutes: (request: RoutesRequest, options?: RequestOptions | undefined) => Promise<RoutesResponse>;