hermes-swap 0.0.31 → 0.0.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -1,5 +1,13 @@
1
+ var _excluded = ["gasLimit"],
2
+ _excluded2 = ["gasLimit"],
3
+ _excluded3 = ["gasLimit"],
4
+ _excluded4 = ["gasPrice"];
1
5
  function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
6
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
7
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2
8
  function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
9
+ function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
10
+ function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
3
11
  function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
4
12
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
5
13
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
@@ -16,8 +24,7 @@ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key i
16
24
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
17
25
  function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
18
26
  import { ChainNameEnum, AddressConst, DexType, BridgeType, IEstimateType } from "./types.js";
19
- import { ethers } from 'ethers';
20
- import { Contract } from 'ethers';
27
+ import { ethers, Contract } from 'ethers';
21
28
  import QuoterAbi from "./abis/quoter.js";
22
29
  import AggregatorAbi from "./abis/aggregator.js";
23
30
 
@@ -117,27 +124,50 @@ var Hermes = /*#__PURE__*/function () {
117
124
  key: "swap",
118
125
  value: function () {
119
126
  var _swap = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(params) {
120
- var fromTokenAddress, toTokenAddress, aggregatorAddress, wallet, aggregator, swapParams, erc20, userBalance, currentAllowance, gas, txResponse, receipt, iface, amountOut, _iterator, _step, log, parsed;
127
+ var txReq,
128
+ fromTokenAddress,
129
+ toTokenAddress,
130
+ aggregatorAddress,
131
+ wallet,
132
+ aggregator,
133
+ swapParams,
134
+ erc20,
135
+ userBalance,
136
+ currentAllowance,
137
+ estimateGas,
138
+ _txReq,
139
+ _ignore,
140
+ estimationOverrides,
141
+ txResponse,
142
+ receipt,
143
+ iface,
144
+ amountOut,
145
+ _iterator,
146
+ _step,
147
+ log,
148
+ parsed,
149
+ _args2 = arguments;
121
150
  return _regeneratorRuntime().wrap(function _callee2$(_context2) {
122
151
  while (1) switch (_context2.prev = _context2.next) {
123
152
  case 0:
153
+ txReq = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : {};
124
154
  this.validateParams(params);
125
155
  if (params.path.length) {
126
- _context2.next = 3;
156
+ _context2.next = 4;
127
157
  break;
128
158
  }
129
159
  throw new Error('Swap path not provided');
130
- case 3:
160
+ case 4:
131
161
  fromTokenAddress = params.path[0].fromCoinAddress;
132
162
  toTokenAddress = params.path[params.path.length - 1].toCoinAddress;
133
163
  aggregatorAddress = this.getAggregatorAddress(params.chain);
134
164
  wallet = this.walletMap.get(params.chain);
135
165
  if (wallet) {
136
- _context2.next = 9;
166
+ _context2.next = 10;
137
167
  break;
138
168
  }
139
169
  throw new Error("Wallet not configured for chain: ".concat(params.chain));
140
- case 9:
170
+ case 10:
141
171
  aggregator = new Contract(aggregatorAddress, AggregatorAbi, wallet);
142
172
  swapParams = params.path.map(function (pathItem) {
143
173
  var _pathItem$extra;
@@ -150,104 +180,107 @@ var Hermes = /*#__PURE__*/function () {
150
180
  };
151
181
  });
152
182
  erc20 = new Contract(fromTokenAddress, ['function balanceOf(address) view returns (uint256)', 'function allowance(address, address) view returns (uint256)'], wallet);
153
- _context2.next = 14;
183
+ _context2.next = 15;
154
184
  return erc20.balanceOf(params.user);
155
- case 14:
185
+ case 15:
156
186
  userBalance = _context2.sent;
157
187
  if (!(userBalance < params.amountInWei)) {
158
- _context2.next = 17;
188
+ _context2.next = 18;
159
189
  break;
160
190
  }
161
191
  throw new Error('Insufficient balance for swap');
162
- case 17:
163
- _context2.next = 19;
192
+ case 18:
193
+ _context2.next = 20;
164
194
  return erc20.allowance(params.user, aggregatorAddress);
165
- case 19:
195
+ case 20:
166
196
  currentAllowance = _context2.sent;
167
197
  if (!(currentAllowance < params.amountInWei)) {
168
- _context2.next = 22;
198
+ _context2.next = 23;
169
199
  break;
170
200
  }
171
201
  throw new Error('Insufficient allowance token amount for swap');
172
- case 22:
173
- _context2.prev = 22;
174
- _context2.next = 25;
175
- return aggregator.getFunction('swap').estimateGas(params.user, params.amountInWei, swapParams, params.minAmountOutList, {
176
- from: wallet.address
177
- });
178
- case 25:
179
- gas = _context2.sent;
180
- _context2.next = 32;
202
+ case 23:
203
+ _txReq = txReq, _ignore = _txReq.gasLimit, estimationOverrides = _objectWithoutProperties(_txReq, _excluded);
204
+ _context2.prev = 24;
205
+ _context2.next = 27;
206
+ return aggregator.swap.estimateGas(params.user, params.amountInWei, swapParams, params.minAmountOutList, estimationOverrides);
207
+ case 27:
208
+ estimateGas = _context2.sent;
209
+ _context2.next = 34;
181
210
  break;
182
- case 28:
183
- _context2.prev = 28;
184
- _context2.t0 = _context2["catch"](22);
211
+ case 30:
212
+ _context2.prev = 30;
213
+ _context2.t0 = _context2["catch"](24);
185
214
  console.warn('Aggregator estimateGas.swap failed', _context2.t0);
186
215
  throw _context2.t0;
187
- case 32:
188
- _context2.prev = 32;
189
- _context2.next = 35;
190
- return aggregator.getFunction('swap')(params.user, params.amountInWei, swapParams, params.minAmountOutList, {
191
- from: wallet.address
192
- });
193
- case 35:
216
+ case 34:
217
+ txReq = this.resolveGasLimit(txReq, estimateGas);
218
+ _context2.next = 37;
219
+ return this.resolveNonce(wallet.provider, wallet.address, txReq);
220
+ case 37:
221
+ txReq = _context2.sent;
222
+ _context2.next = 40;
223
+ return this.resolvePricing(wallet.provider, txReq);
224
+ case 40:
225
+ txReq = _context2.sent;
226
+ _context2.next = 43;
227
+ return aggregator.swap(params.user, params.amountInWei, swapParams, params.minAmountOutList, txReq);
228
+ case 43:
194
229
  txResponse = _context2.sent;
195
- _context2.next = 42;
196
- break;
197
- case 38:
198
- _context2.prev = 38;
199
- _context2.t1 = _context2["catch"](32);
200
- console.error('Aggregator swap transaction failed', _context2.t1);
201
- throw _context2.t1;
202
- case 42:
203
- _context2.next = 44;
230
+ _context2.next = 46;
204
231
  return txResponse.wait();
205
- case 44:
232
+ case 46:
206
233
  receipt = _context2.sent;
207
234
  iface = new ethers.Interface(AggregatorAbi);
208
- amountOut = params.amountInWei;
235
+ amountOut = null;
209
236
  _iterator = _createForOfIteratorHelper(receipt.logs);
210
- _context2.prev = 48;
237
+ _context2.prev = 50;
211
238
  _iterator.s();
212
- case 50:
239
+ case 52:
213
240
  if ((_step = _iterator.n()).done) {
214
- _context2.next = 64;
241
+ _context2.next = 66;
215
242
  break;
216
243
  }
217
244
  log = _step.value;
218
245
  if (!(log.address.toLowerCase() === aggregatorAddress.toLowerCase())) {
219
- _context2.next = 62;
246
+ _context2.next = 64;
220
247
  break;
221
248
  }
222
- _context2.prev = 53;
249
+ _context2.prev = 55;
223
250
  parsed = iface.parseLog(log);
224
251
  if (!(parsed && parsed.name === 'Swapped' && parsed.args && parsed.args.amountOut !== undefined)) {
225
- _context2.next = 58;
252
+ _context2.next = 60;
226
253
  break;
227
254
  }
228
255
  amountOut = parsed.args.amountOut;
229
- return _context2.abrupt("break", 64);
230
- case 58:
231
- _context2.next = 62;
232
- break;
256
+ return _context2.abrupt("break", 66);
233
257
  case 60:
234
- _context2.prev = 60;
235
- _context2.t2 = _context2["catch"](53);
236
- case 62:
237
- _context2.next = 50;
258
+ _context2.next = 64;
238
259
  break;
260
+ case 62:
261
+ _context2.prev = 62;
262
+ _context2.t1 = _context2["catch"](55);
239
263
  case 64:
240
- _context2.next = 69;
264
+ _context2.next = 52;
241
265
  break;
242
266
  case 66:
243
- _context2.prev = 66;
244
- _context2.t3 = _context2["catch"](48);
245
- _iterator.e(_context2.t3);
246
- case 69:
247
- _context2.prev = 69;
267
+ _context2.next = 71;
268
+ break;
269
+ case 68:
270
+ _context2.prev = 68;
271
+ _context2.t2 = _context2["catch"](50);
272
+ _iterator.e(_context2.t2);
273
+ case 71:
274
+ _context2.prev = 71;
248
275
  _iterator.f();
249
- return _context2.finish(69);
250
- case 72:
276
+ return _context2.finish(71);
277
+ case 74:
278
+ if (amountOut) {
279
+ _context2.next = 76;
280
+ break;
281
+ }
282
+ throw new Error("Swapped event not found: ".concat(receipt.hash));
283
+ case 76:
251
284
  return _context2.abrupt("return", {
252
285
  fromToken: fromTokenAddress,
253
286
  toToken: toTokenAddress,
@@ -257,11 +290,11 @@ var Hermes = /*#__PURE__*/function () {
257
290
  to: receipt.from,
258
291
  logs: receipt.logs
259
292
  });
260
- case 73:
293
+ case 77:
261
294
  case "end":
262
295
  return _context2.stop();
263
296
  }
264
- }, _callee2, this, [[22, 28], [32, 38], [48, 66, 69, 72], [53, 60]]);
297
+ }, _callee2, this, [[24, 30], [50, 68, 71, 74], [55, 62]]);
265
298
  }));
266
299
  function swap(_x2) {
267
300
  return _swap.apply(this, arguments);
@@ -307,49 +340,63 @@ var Hermes = /*#__PURE__*/function () {
307
340
  value: function () {
308
341
  var _bridge = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(params) {
309
342
  var _params$extra;
310
- var aggregatorAddress, wallet, provider, nativeBalance, aggregator, bridgeArgs, txOverrides, txResponse, receipt;
343
+ var txReq,
344
+ aggregatorAddress,
345
+ wallet,
346
+ provider,
347
+ nativeBalance,
348
+ aggregator,
349
+ bridgeArgs,
350
+ estimateGas,
351
+ _txReq2,
352
+ _ignore,
353
+ estimationOverrides,
354
+ response,
355
+ txReceipt,
356
+ _args3 = arguments;
311
357
  return _regeneratorRuntime().wrap(function _callee3$(_context3) {
312
358
  while (1) switch (_context3.prev = _context3.next) {
313
359
  case 0:
360
+ txReq = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : {};
314
361
  this.validateParams(params);
315
362
 
316
363
  // set up
317
364
  aggregatorAddress = this.getAggregatorAddress(params.chain);
318
365
  wallet = this.walletMap.get(params.chain);
319
366
  if (wallet) {
320
- _context3.next = 5;
367
+ _context3.next = 6;
321
368
  break;
322
369
  }
323
370
  throw new Error("Wallet not configured for chain: ".concat(params.chain));
324
- case 5:
371
+ case 6:
325
372
  if (!(params.tokenAddress && params.tokenAddress !== ethers.ZeroAddress)) {
326
- _context3.next = 8;
373
+ _context3.next = 9;
327
374
  break;
328
375
  }
329
- _context3.next = 8;
376
+ _context3.next = 9;
330
377
  return this.checkIsEnoughToken(params.tokenAddress, params.user, params.amountInWei, aggregatorAddress, wallet);
331
- case 8:
378
+ case 9:
332
379
  if (!(params.bridgeFee > 0n)) {
333
- _context3.next = 17;
380
+ _context3.next = 18;
334
381
  break;
335
382
  }
336
383
  provider = this.providerMap.get(params.chain);
337
384
  if (provider) {
338
- _context3.next = 12;
385
+ _context3.next = 13;
339
386
  break;
340
387
  }
341
388
  throw new Error("Provider not configured for chain: ".concat(params.chain));
342
- case 12:
343
- _context3.next = 14;
389
+ case 13:
390
+ _context3.next = 15;
344
391
  return provider.getBalance(params.user);
345
- case 14:
392
+ case 15:
346
393
  nativeBalance = _context3.sent;
347
394
  if (!(nativeBalance < params.bridgeFee)) {
348
- _context3.next = 17;
395
+ _context3.next = 18;
349
396
  break;
350
397
  }
351
398
  throw new Error('Insufficient native balance for bridge fee');
352
- case 17:
399
+ case 18:
353
400
  aggregator = new Contract(aggregatorAddress, AggregatorAbi, wallet); // simulate
354
401
  bridgeArgs = {
355
402
  bridge: params.bridgeType,
@@ -360,50 +407,59 @@ var Hermes = /*#__PURE__*/function () {
360
407
  destUser: params.destUser,
361
408
  extra: (_params$extra = params.extra) !== null && _params$extra !== void 0 ? _params$extra : '0x'
362
409
  };
363
- txOverrides = {
364
- from: wallet.address,
365
- value: params.bridgeFee
366
- }; // simulate
367
- _context3.prev = 20;
368
- _context3.next = 23;
369
- return aggregator.bridge.estimateGas(params.user, bridgeArgs, txOverrides);
370
- case 23:
371
- _context3.next = 29;
372
- break;
410
+ if (txReq.value == null) {
411
+ txReq = _objectSpread(_objectSpread({}, txReq), {}, {
412
+ value: params.bridgeFee
413
+ });
414
+ }
415
+
416
+ // simulate
417
+ _txReq2 = txReq, _ignore = _txReq2.gasLimit, estimationOverrides = _objectWithoutProperties(_txReq2, _excluded2);
418
+ _context3.prev = 22;
419
+ _context3.next = 25;
420
+ return aggregator.bridge.estimateGas(params.user, bridgeArgs, estimationOverrides);
373
421
  case 25:
374
- _context3.prev = 25;
375
- _context3.t0 = _context3["catch"](20);
422
+ estimateGas = _context3.sent;
423
+ _context3.next = 32;
424
+ break;
425
+ case 28:
426
+ _context3.prev = 28;
427
+ _context3.t0 = _context3["catch"](22);
376
428
  console.error('Bridge gas estimation reverted', _context3.t0);
377
429
  throw _context3.t0;
378
- case 29:
379
- _context3.prev = 29;
380
- _context3.next = 32;
381
- return aggregator.bridge(params.user, bridgeArgs, txOverrides);
382
430
  case 32:
383
- txResponse = _context3.sent;
384
- _context3.next = 39;
385
- break;
431
+ // 构造tx req
432
+ txReq = this.resolveGasLimit(txReq, estimateGas);
433
+ _context3.next = 35;
434
+ return this.resolveNonce(wallet.provider, wallet.address, txReq);
386
435
  case 35:
387
- _context3.prev = 35;
388
- _context3.t1 = _context3["catch"](29);
389
- console.error('Aggregator swap transaction failed', _context3.t1);
390
- throw _context3.t1;
391
- case 39:
392
- receipt = {
436
+ txReq = _context3.sent;
437
+ _context3.next = 38;
438
+ return this.resolvePricing(wallet.provider, txReq);
439
+ case 38:
440
+ txReq = _context3.sent;
441
+ _context3.next = 41;
442
+ return aggregator.bridge(params.user, bridgeArgs, txReq);
443
+ case 41:
444
+ response = _context3.sent;
445
+ _context3.next = 44;
446
+ return response.wait();
447
+ case 44:
448
+ txReceipt = _context3.sent;
449
+ return _context3.abrupt("return", {
393
450
  fromToken: params.tokenAddress,
394
451
  toToken: params.tokenAddress,
395
452
  amountOut: params.amountInWei,
396
- hash: txResponse.hash,
397
- from: txResponse.from,
398
- to: txResponse.to,
399
- logs: txResponse.logs
400
- };
401
- return _context3.abrupt("return", Promise.resolve(receipt));
402
- case 41:
453
+ hash: txReceipt.hash,
454
+ from: txReceipt.from,
455
+ to: txReceipt.to,
456
+ logs: txReceipt.logs
457
+ });
458
+ case 46:
403
459
  case "end":
404
460
  return _context3.stop();
405
461
  }
406
- }, _callee3, this, [[20, 25], [29, 35]]);
462
+ }, _callee3, this, [[22, 28]]);
407
463
  }));
408
464
  function bridge(_x3) {
409
465
  return _bridge.apply(this, arguments);
@@ -467,29 +523,49 @@ var Hermes = /*#__PURE__*/function () {
467
523
  value: function () {
468
524
  var _swapAndBridge = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(params) {
469
525
  var _params$extra3;
470
- var aggregatorAddress, wallet, fromCoinAddress, swapParams, bridgeArgs, txOverrides, aggregator, txResponse, receipt;
526
+ var txReq,
527
+ aggregatorAddress,
528
+ wallet,
529
+ fromCoinAddress,
530
+ swapParams,
531
+ bridgeArgs,
532
+ _txReq3,
533
+ _ignore,
534
+ estimationOverrides,
535
+ aggregator,
536
+ estimateGas,
537
+ response,
538
+ txReceipt,
539
+ iface,
540
+ outputAmountWei,
541
+ _iterator2,
542
+ _step2,
543
+ log,
544
+ parsed,
545
+ _args5 = arguments;
471
546
  return _regeneratorRuntime().wrap(function _callee5$(_context5) {
472
547
  while (1) switch (_context5.prev = _context5.next) {
473
548
  case 0:
549
+ txReq = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {};
474
550
  this.validateParams(params);
475
551
 
476
552
  // call the aggregator swap and bridge
477
553
  aggregatorAddress = this.getAggregatorAddress(params.chain);
478
554
  wallet = this.walletMap.get(params.chain);
479
555
  if (wallet) {
480
- _context5.next = 5;
556
+ _context5.next = 6;
481
557
  break;
482
558
  }
483
559
  throw new Error("Wallet not configured for chain: ".concat(params.chain));
484
- case 5:
560
+ case 6:
485
561
  fromCoinAddress = params.path[0].fromCoinAddress;
486
562
  if (!(fromCoinAddress && fromCoinAddress !== ethers.ZeroAddress)) {
487
- _context5.next = 9;
563
+ _context5.next = 10;
488
564
  break;
489
565
  }
490
- _context5.next = 9;
566
+ _context5.next = 10;
491
567
  return this.checkIsEnoughToken(fromCoinAddress, params.user, params.amountInWei, aggregatorAddress, wallet);
492
- case 9:
568
+ case 10:
493
569
  // 准备合约参数
494
570
  swapParams = params.path.map(function (pathItem) {
495
571
  var _pathItem$extra3;
@@ -510,51 +586,99 @@ var Hermes = /*#__PURE__*/function () {
510
586
  destUser: params.destUser,
511
587
  extra: (_params$extra3 = params.extra) !== null && _params$extra3 !== void 0 ? _params$extra3 : '0x'
512
588
  };
513
- txOverrides = {
514
- from: wallet.address,
515
- value: params.bridgeFee
516
- }; // simulate
589
+ if (txReq.value == null) {
590
+ txReq = _objectSpread(_objectSpread({}, txReq), {}, {
591
+ value: params.bridgeFee
592
+ });
593
+ }
594
+ _txReq3 = txReq, _ignore = _txReq3.gasLimit, estimationOverrides = _objectWithoutProperties(_txReq3, _excluded3);
517
595
  aggregator = new Contract(aggregatorAddress, AggregatorAbi, wallet);
518
- _context5.prev = 13;
519
- _context5.next = 16;
520
- return aggregator.swapAndBridge.estimateGas(params.user, params.amountInWei, swapParams, params.minAmountOutList, bridgeArgs, txOverrides);
521
- case 16:
522
- _context5.next = 22;
596
+ _context5.next = 17;
597
+ return aggregator.swapAndBridge.estimateGas(params.user, params.amountInWei, swapParams, params.minAmountOutList, bridgeArgs, estimationOverrides);
598
+ case 17:
599
+ estimateGas = _context5.sent;
600
+ txReq = this.resolveGasLimit(txReq, estimateGas);
601
+ _context5.next = 21;
602
+ return this.resolveNonce(wallet.provider, wallet.address, txReq);
603
+ case 21:
604
+ txReq = _context5.sent;
605
+ _context5.next = 24;
606
+ return this.resolvePricing(wallet.provider, txReq);
607
+ case 24:
608
+ txReq = _context5.sent;
609
+ _context5.next = 27;
610
+ return aggregator.swapAndBridge(params.user, params.amountInWei, swapParams, params.minAmountOutList, bridgeArgs, txReq);
611
+ case 27:
612
+ response = _context5.sent;
613
+ _context5.next = 30;
614
+ return response.wait();
615
+ case 30:
616
+ txReceipt = _context5.sent;
617
+ // 解析 SwapAndBridge 事件
618
+ iface = new ethers.Interface(AggregatorAbi);
619
+ outputAmountWei = null;
620
+ _iterator2 = _createForOfIteratorHelper(txReceipt.logs);
621
+ _context5.prev = 34;
622
+ _iterator2.s();
623
+ case 36:
624
+ if ((_step2 = _iterator2.n()).done) {
625
+ _context5.next = 50;
626
+ break;
627
+ }
628
+ log = _step2.value;
629
+ if (!(log.address.toLowerCase() === aggregatorAddress.toLowerCase())) {
630
+ _context5.next = 48;
631
+ break;
632
+ }
633
+ _context5.prev = 39;
634
+ parsed = iface.parseLog(log);
635
+ if (!(parsed && parsed.name === 'SwapAndBridge' && parsed.args && parsed.args.amountOut !== undefined)) {
636
+ _context5.next = 44;
637
+ break;
638
+ }
639
+ outputAmountWei = parsed.args.amountOut;
640
+ return _context5.abrupt("break", 50);
641
+ case 44:
642
+ _context5.next = 48;
523
643
  break;
524
- case 18:
525
- _context5.prev = 18;
526
- _context5.t0 = _context5["catch"](13);
527
- console.error('Bridge gas estimation reverted', _context5.t0);
528
- throw _context5.t0;
529
- case 22:
530
- _context5.prev = 22;
531
- _context5.next = 25;
532
- return aggregator.swapAndBridge(params.user, params.amountInWei, swapParams, params.minAmountOutList, bridgeArgs, txOverrides);
533
- case 25:
534
- txResponse = _context5.sent;
535
- _context5.next = 32;
644
+ case 46:
645
+ _context5.prev = 46;
646
+ _context5.t0 = _context5["catch"](39);
647
+ case 48:
648
+ _context5.next = 36;
536
649
  break;
537
- case 28:
538
- _context5.prev = 28;
539
- _context5.t1 = _context5["catch"](22);
540
- console.error('Aggregator swap and bridge transaction failed', _context5.t1);
541
- throw _context5.t1;
542
- case 32:
543
- receipt = {
650
+ case 50:
651
+ _context5.next = 55;
652
+ break;
653
+ case 52:
654
+ _context5.prev = 52;
655
+ _context5.t1 = _context5["catch"](34);
656
+ _iterator2.e(_context5.t1);
657
+ case 55:
658
+ _context5.prev = 55;
659
+ _iterator2.f();
660
+ return _context5.finish(55);
661
+ case 58:
662
+ if (outputAmountWei) {
663
+ _context5.next = 60;
664
+ break;
665
+ }
666
+ throw new Error("SwapAndBridge event not found: ".concat(txReceipt.hash));
667
+ case 60:
668
+ return _context5.abrupt("return", {
544
669
  fromToken: params.path[0].fromCoinAddress,
545
670
  toToken: params.path[params.path.length - 1].toCoinAddress,
546
- amountOut: params.minAmountOutList[params.minAmountOutList.length - 1],
547
- hash: txResponse.hash,
548
- from: txResponse.from,
549
- to: txResponse.to,
550
- logs: txResponse.logs
551
- };
552
- return _context5.abrupt("return", Promise.resolve(receipt));
553
- case 34:
671
+ amountOut: outputAmountWei,
672
+ hash: txReceipt.hash,
673
+ from: txReceipt.from,
674
+ to: txReceipt.to,
675
+ logs: txReceipt.logs
676
+ });
677
+ case 61:
554
678
  case "end":
555
679
  return _context5.stop();
556
680
  }
557
- }, _callee5, this, [[13, 18], [22, 28]]);
681
+ }, _callee5, this, [[34, 52, 55, 58], [39, 46]]);
558
682
  }));
559
683
  function swapAndBridge(_x5) {
560
684
  return _swapAndBridge.apply(this, arguments);
@@ -875,41 +999,141 @@ var Hermes = /*#__PURE__*/function () {
875
999
  };
876
1000
  }
877
1001
  }, {
878
- key: "checkIsEnoughToken",
1002
+ key: "resolveGasLimit",
1003
+ value: function resolveGasLimit(txReq, estimateGas) {
1004
+ if (txReq.gasLimit != null) {
1005
+ return txReq;
1006
+ }
1007
+ return _objectSpread(_objectSpread({}, txReq), {}, {
1008
+ gasLimit: estimateGas * 130n / 100n // 上浮30%
1009
+ });
1010
+ }
1011
+ }, {
1012
+ key: "resolveNonce",
879
1013
  value: function () {
880
- var _checkIsEnoughToken = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(fromTokenAddress, userAddress, amountInWei, aggregatorAddress, wallet) {
881
- var erc20, userBalance, currentAllowance;
1014
+ var _resolveNonce = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(provider, from, tx) {
1015
+ var nonce;
882
1016
  return _regeneratorRuntime().wrap(function _callee11$(_context11) {
883
1017
  while (1) switch (_context11.prev = _context11.next) {
1018
+ case 0:
1019
+ if (!(tx.nonce != null)) {
1020
+ _context11.next = 2;
1021
+ break;
1022
+ }
1023
+ return _context11.abrupt("return", tx);
1024
+ case 2:
1025
+ _context11.next = 4;
1026
+ return provider.getTransactionCount(from, 'latest');
1027
+ case 4:
1028
+ nonce = _context11.sent;
1029
+ return _context11.abrupt("return", _objectSpread(_objectSpread({}, tx), {}, {
1030
+ nonce: nonce
1031
+ }));
1032
+ case 6:
1033
+ case "end":
1034
+ return _context11.stop();
1035
+ }
1036
+ }, _callee11);
1037
+ }));
1038
+ function resolveNonce(_x14, _x15, _x16) {
1039
+ return _resolveNonce.apply(this, arguments);
1040
+ }
1041
+ return resolveNonce;
1042
+ }()
1043
+ }, {
1044
+ key: "resolvePricing",
1045
+ value: function () {
1046
+ var _resolvePricing = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(provider, tx) {
1047
+ var fd;
1048
+ return _regeneratorRuntime().wrap(function _callee12$(_context12) {
1049
+ while (1) switch (_context12.prev = _context12.next) {
1050
+ case 0:
1051
+ if (!(tx.gasPrice != null || tx.maxFeePerGas != null || tx.maxPriorityFeePerGas != null)) {
1052
+ _context12.next = 2;
1053
+ break;
1054
+ }
1055
+ return _context12.abrupt("return", this.sanitizePricing(tx));
1056
+ case 2:
1057
+ _context12.next = 4;
1058
+ return provider.getFeeData();
1059
+ case 4:
1060
+ fd = _context12.sent;
1061
+ if (!(fd.maxFeePerGas != null && fd.maxPriorityFeePerGas != null)) {
1062
+ _context12.next = 7;
1063
+ break;
1064
+ }
1065
+ return _context12.abrupt("return", _objectSpread(_objectSpread({}, tx), {}, {
1066
+ maxFeePerGas: fd.maxFeePerGas * 150n / 100n,
1067
+ // 上浮50%
1068
+ maxPriorityFeePerGas: fd.maxPriorityFeePerGas
1069
+ }));
1070
+ case 7:
1071
+ if (!(fd.gasPrice != null)) {
1072
+ _context12.next = 9;
1073
+ break;
1074
+ }
1075
+ return _context12.abrupt("return", _objectSpread(_objectSpread({}, tx), {}, {
1076
+ gasPrice: fd.gasPrice
1077
+ }));
1078
+ case 9:
1079
+ return _context12.abrupt("return", tx);
1080
+ case 10:
1081
+ case "end":
1082
+ return _context12.stop();
1083
+ }
1084
+ }, _callee12, this);
1085
+ }));
1086
+ function resolvePricing(_x17, _x18) {
1087
+ return _resolvePricing.apply(this, arguments);
1088
+ }
1089
+ return resolvePricing;
1090
+ }()
1091
+ }, {
1092
+ key: "sanitizePricing",
1093
+ value: function sanitizePricing(tx) {
1094
+ // If user supplied any EIP-1559 field, remove legacy gasPrice to avoid mixing.
1095
+ if (tx.maxFeePerGas != null || tx.maxPriorityFeePerGas != null) {
1096
+ var gasPrice = tx.gasPrice,
1097
+ rest = _objectWithoutProperties(tx, _excluded4);
1098
+ return rest;
1099
+ }
1100
+ return tx;
1101
+ }
1102
+ }, {
1103
+ key: "checkIsEnoughToken",
1104
+ value: function () {
1105
+ var _checkIsEnoughToken = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(fromTokenAddress, userAddress, amountInWei, aggregatorAddress, wallet) {
1106
+ var erc20, userBalance, currentAllowance;
1107
+ return _regeneratorRuntime().wrap(function _callee13$(_context13) {
1108
+ while (1) switch (_context13.prev = _context13.next) {
884
1109
  case 0:
885
1110
  erc20 = new Contract(fromTokenAddress, ['function balanceOf(address) view returns (uint256)', 'function allowance(address, address) view returns (uint256)'], wallet);
886
- _context11.next = 3;
1111
+ _context13.next = 3;
887
1112
  return erc20.balanceOf(userAddress);
888
1113
  case 3:
889
- userBalance = _context11.sent;
1114
+ userBalance = _context13.sent;
890
1115
  if (!(userBalance < amountInWei)) {
891
- _context11.next = 6;
1116
+ _context13.next = 6;
892
1117
  break;
893
1118
  }
894
1119
  throw new Error('Insufficient balance token amount');
895
1120
  case 6:
896
- _context11.next = 8;
1121
+ _context13.next = 8;
897
1122
  return erc20.allowance(userAddress, aggregatorAddress);
898
1123
  case 8:
899
- currentAllowance = _context11.sent;
900
- console.log(currentAllowance);
1124
+ currentAllowance = _context13.sent;
901
1125
  if (!(currentAllowance < amountInWei)) {
902
- _context11.next = 12;
1126
+ _context13.next = 11;
903
1127
  break;
904
1128
  }
905
1129
  throw new Error('Insufficient allowance token amount');
906
- case 12:
1130
+ case 11:
907
1131
  case "end":
908
- return _context11.stop();
1132
+ return _context13.stop();
909
1133
  }
910
- }, _callee11);
1134
+ }, _callee13);
911
1135
  }));
912
- function checkIsEnoughToken(_x14, _x15, _x16, _x17, _x18) {
1136
+ function checkIsEnoughToken(_x19, _x20, _x21, _x22, _x23) {
913
1137
  return _checkIsEnoughToken.apply(this, arguments);
914
1138
  }
915
1139
  return checkIsEnoughToken;