@lifi/sdk
Advanced tools
Comparing version 1.1.2 to 1.1.3
@@ -5,2 +5,9 @@ # Changelog | ||
### [1.1.3](https://github.com/lifinance/sdk/compare/v1.1.2...v1.1.3) (2022-08-06) | ||
### Bug Fixes | ||
* cleanup after failure ([#99](https://github.com/lifinance/sdk/issues/99)) ([04501d6](https://github.com/lifinance/sdk/commit/04501d6a1600cd0354cd2cd83b54cde9e2915deb)) | ||
### [1.1.2](https://github.com/lifinance/sdk/compare/v1.1.1...v1.1.2) (2022-08-04) | ||
@@ -7,0 +14,0 @@ |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -11,151 +10,60 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
import BigNumber from 'bignumber.js'; | ||
import { constants } from 'ethers'; | ||
import { isSameToken } from '../helpers'; | ||
import { isNativeTokenAddress } from '../utils/utils'; | ||
import { getAllowanceViaMulticall, getApproved, groupByChain, setApproval, } from './utils'; | ||
export const getTokenApproval = (signer, token, approvalAddress) => __awaiter(void 0, void 0, void 0, function* () { | ||
// native token don't need approval | ||
if (isNativeTokenAddress(token.address)) { | ||
return; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.revokeTokenApproval = exports.approveToken = exports.bulkGetTokenApproval = exports.getTokenApproval = void 0; | ||
var bignumber_js_1 = __importDefault(require("bignumber.js")); | ||
var ethers_1 = require("ethers"); | ||
var helpers_1 = require("../helpers"); | ||
var utils_1 = require("../utils/utils"); | ||
var utils_2 = require("./utils"); | ||
var getTokenApproval = function (signer, token, approvalAddress) { return __awaiter(void 0, void 0, void 0, function () { | ||
var approved; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
// native token don't need approval | ||
if ((0, utils_1.isNativeTokenAddress)(token.address)) { | ||
return [2 /*return*/]; | ||
} | ||
return [4 /*yield*/, (0, utils_2.getApproved)(signer, token.address, approvalAddress)]; | ||
case 1: | ||
approved = _a.sent(); | ||
return [2 /*return*/, approved.toString()]; | ||
const approved = yield getApproved(signer, token.address, approvalAddress); | ||
return approved.toString(); | ||
}); | ||
export const bulkGetTokenApproval = (signer, tokenData) => __awaiter(void 0, void 0, void 0, function* () { | ||
// filter out native tokens | ||
const filteredTokenData = tokenData.filter(({ token }) => !isNativeTokenAddress(token.address)); | ||
// group by chain | ||
const tokenDataByChain = groupByChain(filteredTokenData); | ||
const approvalPromises = Object.keys(tokenDataByChain).map((chainId) => __awaiter(void 0, void 0, void 0, function* () { | ||
const parsedChainId = Number.parseInt(chainId); | ||
// get allowances for current chain and token list | ||
return getAllowanceViaMulticall(signer, parsedChainId, tokenDataByChain[parsedChainId]); | ||
})); | ||
const approvalsByChain = yield Promise.all(approvalPromises); | ||
const approvals = approvalsByChain.flat(); | ||
return tokenData.map(({ token }) => { | ||
// native token don't need approval | ||
if (isNativeTokenAddress(token.address)) { | ||
return { token, approval: undefined }; | ||
} | ||
const approved = approvals.find((approval) => isSameToken(approval.token, token)); | ||
return { token, approval: approved === null || approved === void 0 ? void 0 : approved.approvedAmount.toString() }; | ||
}); | ||
}); }; | ||
exports.getTokenApproval = getTokenApproval; | ||
var bulkGetTokenApproval = function (signer, tokenData) { return __awaiter(void 0, void 0, void 0, function () { | ||
var filteredTokenData, tokenDataByChain, approvalPromises, approvalsByChain, approvals; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
filteredTokenData = tokenData.filter(function (_a) { | ||
var token = _a.token; | ||
return !(0, utils_1.isNativeTokenAddress)(token.address); | ||
}); | ||
tokenDataByChain = (0, utils_2.groupByChain)(filteredTokenData); | ||
approvalPromises = Object.keys(tokenDataByChain).map(function (chainId) { return __awaiter(void 0, void 0, void 0, function () { | ||
var parsedChainId; | ||
return __generator(this, function (_a) { | ||
parsedChainId = Number.parseInt(chainId); | ||
// get allowances for current chain and token list | ||
return [2 /*return*/, (0, utils_2.getAllowanceViaMulticall)(signer, parsedChainId, tokenDataByChain[parsedChainId])]; | ||
}); | ||
}); }); | ||
return [4 /*yield*/, Promise.all(approvalPromises)]; | ||
case 1: | ||
approvalsByChain = _a.sent(); | ||
approvals = approvalsByChain.flat(); | ||
return [2 /*return*/, tokenData.map(function (_a) { | ||
var token = _a.token; | ||
// native token don't need approval | ||
if ((0, utils_1.isNativeTokenAddress)(token.address)) { | ||
return { token: token, approval: undefined }; | ||
} | ||
var approved = approvals.find(function (approval) { | ||
return (0, helpers_1.isSameToken)(approval.token, token); | ||
}); | ||
return { token: token, approval: approved === null || approved === void 0 ? void 0 : approved.approvedAmount.toString() }; | ||
})]; | ||
} | ||
}); | ||
}); }; | ||
exports.bulkGetTokenApproval = bulkGetTokenApproval; | ||
var approveToken = function (_a) { | ||
var signer = _a.signer, token = _a.token, approvalAddress = _a.approvalAddress, amount = _a.amount, _b = _a.infiniteApproval, infiniteApproval = _b === void 0 ? false : _b; | ||
return __awaiter(void 0, void 0, void 0, function () { | ||
var approvedAmount, approvalAmount, approveTx; | ||
return __generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
// native token don't need approval | ||
if ((0, utils_1.isNativeTokenAddress)(token.address)) { | ||
return [2 /*return*/]; | ||
} | ||
return [4 /*yield*/, (0, utils_2.getApproved)(signer, token.address, approvalAddress)]; | ||
case 1: | ||
approvedAmount = _c.sent(); | ||
if (!new bignumber_js_1.default(amount).gt(approvedAmount)) return [3 /*break*/, 4]; | ||
approvalAmount = infiniteApproval | ||
? ethers_1.constants.MaxUint256.toString() | ||
: amount; | ||
return [4 /*yield*/, (0, utils_2.setApproval)(signer, token.address, approvalAddress, approvalAmount)]; | ||
case 2: | ||
approveTx = _c.sent(); | ||
return [4 /*yield*/, approveTx.wait()]; | ||
case 3: | ||
_c.sent(); | ||
_c.label = 4; | ||
case 4: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
}; | ||
exports.approveToken = approveToken; | ||
var revokeTokenApproval = function (_a) { | ||
var signer = _a.signer, token = _a.token, approvalAddress = _a.approvalAddress; | ||
return __awaiter(void 0, void 0, void 0, function () { | ||
var approvedAmount, approveTx; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
// native token don't need approval | ||
if ((0, utils_1.isNativeTokenAddress)(token.address)) { | ||
return [2 /*return*/]; | ||
} | ||
return [4 /*yield*/, (0, utils_2.getApproved)(signer, token.address, approvalAddress)]; | ||
case 1: | ||
approvedAmount = _b.sent(); | ||
if (!!approvedAmount.isZero()) return [3 /*break*/, 4]; | ||
return [4 /*yield*/, (0, utils_2.setApproval)(signer, token.address, approvalAddress, '0')]; | ||
case 2: | ||
approveTx = _b.sent(); | ||
return [4 /*yield*/, approveTx.wait()]; | ||
case 3: | ||
_b.sent(); | ||
_b.label = 4; | ||
case 4: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
}; | ||
exports.revokeTokenApproval = revokeTokenApproval; | ||
}); | ||
export const approveToken = ({ signer, token, approvalAddress, amount, infiniteApproval = false, }) => __awaiter(void 0, void 0, void 0, function* () { | ||
// native token don't need approval | ||
if (isNativeTokenAddress(token.address)) { | ||
return; | ||
} | ||
const approvedAmount = yield getApproved(signer, token.address, approvalAddress); | ||
if (new BigNumber(amount).gt(approvedAmount)) { | ||
const approvalAmount = infiniteApproval | ||
? constants.MaxUint256.toString() | ||
: amount; | ||
const approveTx = yield setApproval(signer, token.address, approvalAddress, approvalAmount); | ||
yield approveTx.wait(); | ||
} | ||
}); | ||
export const revokeTokenApproval = ({ signer, token, approvalAddress, }) => __awaiter(void 0, void 0, void 0, function* () { | ||
// native token don't need approval | ||
if (isNativeTokenAddress(token.address)) { | ||
return; | ||
} | ||
const approvedAmount = yield getApproved(signer, token.address, approvalAddress); | ||
if (!approvedAmount.isZero()) { | ||
const approveTx = yield setApproval(signer, token.address, approvalAddress, '0'); | ||
yield approveTx.wait(); | ||
} | ||
}); |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -11,121 +10,58 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
import BigNumber from 'bignumber.js'; | ||
import { Contract } from 'ethers'; | ||
import ChainsService from '../services/ChainsService'; | ||
import { ERC20_ABI } from '../types'; | ||
import { ServerError } from '../utils/errors'; | ||
import { fetchDataUsingMulticall } from '../utils/multicall'; | ||
export const getApproved = (signer, tokenAddress, contractAddress) => __awaiter(void 0, void 0, void 0, function* () { | ||
const signerAddress = yield signer.getAddress(); | ||
const erc20 = new Contract(tokenAddress, ERC20_ABI, signer); | ||
try { | ||
const approved = yield erc20.allowance(signerAddress, contractAddress); | ||
return new BigNumber(approved.toString()); | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.groupByChain = exports.getAllowanceViaMulticall = exports.setApproval = exports.getApproved = void 0; | ||
var bignumber_js_1 = __importDefault(require("bignumber.js")); | ||
var ethers_1 = require("ethers"); | ||
var ChainsService_1 = __importDefault(require("../services/ChainsService")); | ||
var types_1 = require("../types"); | ||
var errors_1 = require("../utils/errors"); | ||
var multicall_1 = require("../utils/multicall"); | ||
var getApproved = function (signer, tokenAddress, contractAddress) { return __awaiter(void 0, void 0, void 0, function () { | ||
var signerAddress, erc20, approved, e_1; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, signer.getAddress()]; | ||
case 1: | ||
signerAddress = _a.sent(); | ||
erc20 = new ethers_1.Contract(tokenAddress, types_1.ERC20_ABI, signer); | ||
_a.label = 2; | ||
case 2: | ||
_a.trys.push([2, 4, , 5]); | ||
return [4 /*yield*/, erc20.allowance(signerAddress, contractAddress)]; | ||
case 3: | ||
approved = _a.sent(); | ||
return [2 /*return*/, new bignumber_js_1.default(approved.toString())]; | ||
case 4: | ||
e_1 = _a.sent(); | ||
return [2 /*return*/, new bignumber_js_1.default(0)]; | ||
case 5: return [2 /*return*/]; | ||
} | ||
}); | ||
}); }; | ||
exports.getApproved = getApproved; | ||
var setApproval = function (signer, tokenAddress, contractAddress, amount) { | ||
var erc20 = new ethers_1.Contract(tokenAddress, types_1.ERC20_ABI, signer); | ||
catch (e) { | ||
return new BigNumber(0); | ||
} | ||
}); | ||
export const setApproval = (signer, tokenAddress, contractAddress, amount) => { | ||
const erc20 = new Contract(tokenAddress, ERC20_ABI, signer); | ||
return erc20.approve(contractAddress, amount); | ||
}; | ||
exports.setApproval = setApproval; | ||
var getAllowanceViaMulticall = function (signer, chainId, tokenData) { return __awaiter(void 0, void 0, void 0, function () { | ||
var chainsService, chain, ownerAddress, calls, result, parsedResult; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
chainsService = ChainsService_1.default.getInstance(); | ||
return [4 /*yield*/, chainsService.getChainById(chainId)]; | ||
case 1: | ||
chain = _a.sent(); | ||
if (!chain.multicallAddress) { | ||
throw new errors_1.ServerError("No multicall address configured for chainId ".concat(chainId, ".")); | ||
} | ||
return [4 /*yield*/, signer.getAddress()]; | ||
case 2: | ||
ownerAddress = _a.sent(); | ||
calls = []; | ||
tokenData.map(function (_a) { | ||
var token = _a.token, approvalAddress = _a.approvalAddress; | ||
calls.push({ | ||
address: token.address, | ||
name: 'allowance', | ||
params: [ownerAddress, approvalAddress], | ||
}); | ||
}); | ||
return [4 /*yield*/, (0, multicall_1.fetchDataUsingMulticall)(calls, types_1.ERC20_ABI, chainId, chain.multicallAddress)]; | ||
case 3: | ||
result = _a.sent(); | ||
if (!result.length) { | ||
throw new errors_1.ServerError("Couldn't load allowance from chainId ".concat(chainId, " using multicall.")); | ||
} | ||
parsedResult = result.map(function (_a) { | ||
var _b; | ||
var data = _a.data; | ||
return ({ | ||
approvalAmount: (_b = data) !== null && _b !== void 0 ? _b : new bignumber_js_1.default(0), | ||
}); | ||
}); | ||
return [2 /*return*/, tokenData.map(function (_a, i) { | ||
var token = _a.token, approvalAddress = _a.approvalAddress; | ||
return ({ | ||
token: token, | ||
approvalAddress: approvalAddress, | ||
approvedAmount: parsedResult[i].approvalAmount, | ||
}); | ||
})]; | ||
} | ||
export const getAllowanceViaMulticall = (signer, chainId, tokenData) => __awaiter(void 0, void 0, void 0, function* () { | ||
const chainsService = ChainsService.getInstance(); | ||
const chain = yield chainsService.getChainById(chainId); | ||
if (!chain.multicallAddress) { | ||
throw new ServerError(`No multicall address configured for chainId ${chainId}.`); | ||
} | ||
const ownerAddress = yield signer.getAddress(); | ||
const calls = []; | ||
tokenData.map(({ token, approvalAddress }) => { | ||
calls.push({ | ||
address: token.address, | ||
name: 'allowance', | ||
params: [ownerAddress, approvalAddress], | ||
}); | ||
}); | ||
}); }; | ||
exports.getAllowanceViaMulticall = getAllowanceViaMulticall; | ||
var groupByChain = function (tokenDataList) { | ||
const result = yield fetchDataUsingMulticall(calls, ERC20_ABI, chainId, chain.multicallAddress); | ||
if (!result.length) { | ||
throw new ServerError(`Couldn't load allowance from chainId ${chainId} using multicall.`); | ||
} | ||
const parsedResult = result.map(({ data }) => { | ||
var _a; | ||
return ({ | ||
approvalAmount: (_a = data) !== null && _a !== void 0 ? _a : new BigNumber(0), | ||
}); | ||
}); | ||
return tokenData.map(({ token, approvalAddress }, i) => ({ | ||
token, | ||
approvalAddress, | ||
approvedAmount: parsedResult[i].approvalAmount, | ||
})); | ||
}); | ||
export const groupByChain = (tokenDataList) => { | ||
// group by chain | ||
var tokenDataByChain = {}; | ||
tokenDataList.forEach(function (tokenData) { | ||
const tokenDataByChain = {}; | ||
tokenDataList.forEach((tokenData) => { | ||
if (!tokenDataByChain[tokenData.token.chainId]) { | ||
@@ -138,2 +74,1 @@ tokenDataByChain[tokenData.token.chainId] = []; | ||
}; | ||
exports.groupByChain = groupByChain; |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -11,95 +10,33 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var utils_1 = __importDefault(require("./utils")); | ||
var getTokenBalance = function (walletAddress, token) { return __awaiter(void 0, void 0, void 0, function () { | ||
var tokenAmounts; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, getTokenBalances(walletAddress, [token])]; | ||
case 1: | ||
tokenAmounts = _a.sent(); | ||
return [2 /*return*/, tokenAmounts.length ? tokenAmounts[0] : null]; | ||
import utils from './utils'; | ||
const getTokenBalance = (walletAddress, token) => __awaiter(void 0, void 0, void 0, function* () { | ||
const tokenAmounts = yield getTokenBalances(walletAddress, [token]); | ||
return tokenAmounts.length ? tokenAmounts[0] : null; | ||
}); | ||
const getTokenBalances = (walletAddress, tokens) => __awaiter(void 0, void 0, void 0, function* () { | ||
// split by chain | ||
const tokensByChain = {}; | ||
tokens.forEach((token) => { | ||
if (!tokensByChain[token.chainId]) { | ||
tokensByChain[token.chainId] = []; | ||
} | ||
tokensByChain[token.chainId].push(token); | ||
}); | ||
}); }; | ||
var getTokenBalances = function (walletAddress, tokens) { return __awaiter(void 0, void 0, void 0, function () { | ||
var tokensByChain, tokenAmountsByChain; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
tokensByChain = {}; | ||
tokens.forEach(function (token) { | ||
if (!tokensByChain[token.chainId]) { | ||
tokensByChain[token.chainId] = []; | ||
} | ||
tokensByChain[token.chainId].push(token); | ||
}); | ||
return [4 /*yield*/, getTokenBalancesForChains(walletAddress, tokensByChain)]; | ||
case 1: | ||
tokenAmountsByChain = _a.sent(); | ||
return [2 /*return*/, Object.values(tokenAmountsByChain).flat()]; | ||
} | ||
}); | ||
}); }; | ||
var getTokenBalancesForChains = function (walletAddress, tokensByChain) { return __awaiter(void 0, void 0, void 0, function () { | ||
var tokenAmountsByChain, promises; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
tokenAmountsByChain = {}; | ||
promises = Object.keys(tokensByChain).map(function (chainIdStr) { return __awaiter(void 0, void 0, void 0, function () { | ||
var chainId, tokenAmounts; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
chainId = parseInt(chainIdStr); | ||
return [4 /*yield*/, utils_1.default.getBalances(walletAddress, tokensByChain[chainId])]; | ||
case 1: | ||
tokenAmounts = _a.sent(); | ||
tokenAmountsByChain[chainId] = tokenAmounts; | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
return [4 /*yield*/, Promise.allSettled(promises)]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/, tokenAmountsByChain]; | ||
} | ||
}); | ||
}); }; | ||
exports.default = { | ||
getTokenBalance: getTokenBalance, | ||
getTokenBalances: getTokenBalances, | ||
getTokenBalancesForChains: getTokenBalancesForChains, | ||
const tokenAmountsByChain = yield getTokenBalancesForChains(walletAddress, tokensByChain); | ||
return Object.values(tokenAmountsByChain).flat(); | ||
}); | ||
const getTokenBalancesForChains = (walletAddress, tokensByChain) => __awaiter(void 0, void 0, void 0, function* () { | ||
const tokenAmountsByChain = {}; | ||
const promises = Object.keys(tokensByChain).map((chainIdStr) => __awaiter(void 0, void 0, void 0, function* () { | ||
const chainId = parseInt(chainIdStr); | ||
const tokenAmounts = yield utils.getBalances(walletAddress, tokensByChain[chainId]); | ||
tokenAmountsByChain[chainId] = tokenAmounts; | ||
})); | ||
yield Promise.allSettled(promises); | ||
return tokenAmountsByChain; | ||
}); | ||
export default { | ||
getTokenBalance, | ||
getTokenBalances, | ||
getTokenBalancesForChains, | ||
}; |
@@ -1,13 +0,1 @@ | ||
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -22,39 +10,8 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var bignumber_js_1 = __importDefault(require("bignumber.js")); | ||
var ethers_1 = require("ethers"); | ||
var connectors_1 = require("../connectors"); | ||
var multicall_1 = require("../utils/multicall"); | ||
var utils_1 = require("../utils/utils"); | ||
var balanceAbi = [ | ||
import BigNumber from 'bignumber.js'; | ||
import { ethers } from 'ethers'; | ||
import { getMulticallAddress, getRpcProvider } from '../connectors'; | ||
import { fetchDataUsingMulticall } from '../utils/multicall'; | ||
import { isZeroAddress } from '../utils/utils'; | ||
const balanceAbi = [ | ||
{ | ||
@@ -79,179 +36,112 @@ constant: true, | ||
]; | ||
var getBalances = function (walletAddress, tokens) { return __awaiter(void 0, void 0, void 0, function () { | ||
var chainId; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (tokens.length === 0) { | ||
return [2 /*return*/, []]; | ||
} | ||
chainId = tokens[0].chainId; | ||
tokens.forEach(function (token) { | ||
if (token.chainId !== chainId) { | ||
// eslint-disable-next-line no-console | ||
console.warn("Requested tokens have to be on same chain."); | ||
return []; | ||
} | ||
}); | ||
return [4 /*yield*/, (0, connectors_1.getMulticallAddress)(chainId)]; | ||
case 1: | ||
if ((_a.sent()) && tokens.length > 1) { | ||
return [2 /*return*/, getBalancesFromProviderUsingMulticall(walletAddress, tokens)]; | ||
} | ||
else { | ||
return [2 /*return*/, getBalancesFromProvider(walletAddress, tokens)]; | ||
} | ||
return [2 /*return*/]; | ||
const getBalances = (walletAddress, tokens) => __awaiter(void 0, void 0, void 0, function* () { | ||
if (tokens.length === 0) { | ||
return []; | ||
} | ||
const { chainId } = tokens[0]; | ||
tokens.forEach((token) => { | ||
if (token.chainId !== chainId) { | ||
// eslint-disable-next-line no-console | ||
console.warn(`Requested tokens have to be on same chain.`); | ||
return []; | ||
} | ||
}); | ||
}); }; | ||
var getBalancesFromProviderUsingMulticall = function (walletAddress, tokens) { return __awaiter(void 0, void 0, void 0, function () { | ||
var chainId, multicallAddress; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
chainId = tokens[0].chainId; | ||
return [4 /*yield*/, (0, connectors_1.getMulticallAddress)(chainId)]; | ||
case 1: | ||
multicallAddress = _a.sent(); | ||
if (!multicallAddress) { | ||
throw new Error('No multicallAddress found for the given chain.'); | ||
} | ||
return [2 /*return*/, executeMulticall(walletAddress, tokens, multicallAddress, chainId)]; | ||
if ((yield getMulticallAddress(chainId)) && tokens.length > 1) { | ||
return getBalancesFromProviderUsingMulticall(walletAddress, tokens); | ||
} | ||
else { | ||
return getBalancesFromProvider(walletAddress, tokens); | ||
} | ||
}); | ||
const getBalancesFromProviderUsingMulticall = (walletAddress, tokens) => __awaiter(void 0, void 0, void 0, function* () { | ||
// Configuration | ||
const { chainId } = tokens[0]; | ||
const multicallAddress = yield getMulticallAddress(chainId); | ||
if (!multicallAddress) { | ||
throw new Error('No multicallAddress found for the given chain.'); | ||
} | ||
return executeMulticall(walletAddress, tokens, multicallAddress, chainId); | ||
}); | ||
const executeMulticall = (walletAddress, tokens, multicallAddress, chainId) => __awaiter(void 0, void 0, void 0, function* () { | ||
// Collect calls we want to make | ||
const calls = []; | ||
tokens.map((token) => { | ||
if (isZeroAddress(token.address)) { | ||
calls.push({ | ||
address: multicallAddress, | ||
name: 'getEthBalance', | ||
params: [walletAddress], | ||
}); | ||
} | ||
}); | ||
}); }; | ||
var executeMulticall = function (walletAddress, tokens, multicallAddress, chainId) { return __awaiter(void 0, void 0, void 0, function () { | ||
var calls, res; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
calls = []; | ||
tokens.map(function (token) { | ||
if ((0, utils_1.isZeroAddress)(token.address)) { | ||
calls.push({ | ||
address: multicallAddress, | ||
name: 'getEthBalance', | ||
params: [walletAddress], | ||
}); | ||
} | ||
else { | ||
calls.push({ | ||
address: token.address, | ||
name: 'balanceOf', | ||
params: [walletAddress], | ||
}); | ||
} | ||
}); | ||
return [4 /*yield*/, fetchViaMulticall(calls, balanceAbi, chainId, multicallAddress)]; | ||
case 1: | ||
res = _a.sent(); | ||
if (!res.length) { | ||
return [2 /*return*/, []]; | ||
} | ||
return [2 /*return*/, tokens.map(function (token, i) { | ||
var amount = new bignumber_js_1.default(res[i].amount.toString() || '0') | ||
.shiftedBy(-token.decimals) | ||
.toFixed(); | ||
return __assign(__assign({}, token), { amount: amount || '0', blockNumber: res[i].blockNumber }); | ||
})]; | ||
else { | ||
calls.push({ | ||
address: token.address, | ||
name: 'balanceOf', | ||
params: [walletAddress], | ||
}); | ||
} | ||
}); | ||
}); }; | ||
var fetchViaMulticall = function (calls, abi, chainId, multicallAddress) { return __awaiter(void 0, void 0, void 0, function () { | ||
var result; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, (0, multicall_1.fetchDataUsingMulticall)(calls, abi, chainId, multicallAddress)]; | ||
case 1: | ||
result = _a.sent(); | ||
return [2 /*return*/, result.map(function (_a) { | ||
var data = _a.data, blockNumber = _a.blockNumber; | ||
return ({ | ||
amount: data ? data : new bignumber_js_1.default(0), | ||
blockNumber: blockNumber, | ||
}); | ||
})]; | ||
} | ||
const res = yield fetchViaMulticall(calls, balanceAbi, chainId, multicallAddress); | ||
if (!res.length) { | ||
return []; | ||
} | ||
return tokens.map((token, i) => { | ||
const amount = new BigNumber(res[i].amount.toString() || '0') | ||
.shiftedBy(-token.decimals) | ||
.toFixed(); | ||
return Object.assign(Object.assign({}, token), { amount: amount || '0', blockNumber: res[i].blockNumber }); | ||
}); | ||
}); }; | ||
var getBalancesFromProvider = function (walletAddress, tokens) { return __awaiter(void 0, void 0, void 0, function () { | ||
var chainId, rpc, tokenAmountPromises; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
chainId = tokens[0].chainId; | ||
return [4 /*yield*/, (0, connectors_1.getRpcProvider)(chainId)]; | ||
case 1: | ||
rpc = _a.sent(); | ||
tokenAmountPromises = tokens.map(function (token) { return __awaiter(void 0, void 0, void 0, function () { | ||
var amount, blockNumber, balance, e_1; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
amount = '0'; | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, getBalanceFromProvider(walletAddress, token.address, chainId, rpc)]; | ||
case 2: | ||
balance = _a.sent(); | ||
amount = new bignumber_js_1.default(balance.amount.toString()) | ||
.shiftedBy(-token.decimals) | ||
.toString(); | ||
blockNumber = balance.blockNumber; | ||
return [3 /*break*/, 4]; | ||
case 3: | ||
e_1 = _a.sent(); | ||
// eslint-disable-next-line no-console | ||
console.warn(e_1); | ||
return [3 /*break*/, 4]; | ||
case 4: return [2 /*return*/, __assign(__assign({}, token), { amount: amount, blockNumber: blockNumber })]; | ||
} | ||
}); | ||
}); }); | ||
return [2 /*return*/, Promise.all(tokenAmountPromises)]; | ||
}); | ||
const fetchViaMulticall = (calls, abi, chainId, multicallAddress) => __awaiter(void 0, void 0, void 0, function* () { | ||
const result = yield fetchDataUsingMulticall(calls, abi, chainId, multicallAddress); | ||
return result.map(({ data, blockNumber }) => ({ | ||
amount: data ? data : new BigNumber(0), | ||
blockNumber, | ||
})); | ||
}); | ||
const getBalancesFromProvider = (walletAddress, tokens) => __awaiter(void 0, void 0, void 0, function* () { | ||
const chainId = tokens[0].chainId; | ||
const rpc = yield getRpcProvider(chainId); | ||
const tokenAmountPromises = tokens.map((token) => __awaiter(void 0, void 0, void 0, function* () { | ||
let amount = '0'; | ||
let blockNumber; | ||
try { | ||
const balance = yield getBalanceFromProvider(walletAddress, token.address, chainId, rpc); | ||
amount = new BigNumber(balance.amount.toString()) | ||
.shiftedBy(-token.decimals) | ||
.toString(); | ||
blockNumber = balance.blockNumber; | ||
} | ||
}); | ||
}); }; | ||
var getBalanceFromProvider = function (walletAddress, assetId, chainId, provider) { return __awaiter(void 0, void 0, void 0, function () { | ||
var blockNumber, balance, contract; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, getCurrentBlockNumber(chainId)]; | ||
case 1: | ||
blockNumber = _a.sent(); | ||
if (!(0, utils_1.isZeroAddress)(assetId)) return [3 /*break*/, 3]; | ||
return [4 /*yield*/, provider.getBalance(walletAddress, blockNumber)]; | ||
case 2: | ||
balance = _a.sent(); | ||
return [3 /*break*/, 5]; | ||
case 3: | ||
contract = new ethers_1.ethers.Contract(assetId, ['function balanceOf(address owner) view returns (uint256)'], provider); | ||
return [4 /*yield*/, contract.balanceOf(walletAddress, { | ||
blockTag: blockNumber, | ||
})]; | ||
case 4: | ||
balance = _a.sent(); | ||
_a.label = 5; | ||
case 5: return [2 /*return*/, { | ||
amount: balance, | ||
blockNumber: blockNumber, | ||
}]; | ||
catch (e) { | ||
// eslint-disable-next-line no-console | ||
console.warn(e); | ||
} | ||
}); | ||
}); }; | ||
var getCurrentBlockNumber = function (chainId) { return __awaiter(void 0, void 0, void 0, function () { | ||
var rpc; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, (0, connectors_1.getRpcProvider)(chainId)]; | ||
case 1: | ||
rpc = _a.sent(); | ||
return [2 /*return*/, rpc.getBlockNumber()]; | ||
} | ||
}); | ||
}); }; | ||
exports.default = { | ||
getBalances: getBalances, | ||
return Object.assign(Object.assign({}, token), { amount, | ||
blockNumber }); | ||
})); | ||
return Promise.all(tokenAmountPromises); | ||
}); | ||
const getBalanceFromProvider = (walletAddress, assetId, chainId, provider) => __awaiter(void 0, void 0, void 0, function* () { | ||
const blockNumber = yield getCurrentBlockNumber(chainId); | ||
let balance; | ||
if (isZeroAddress(assetId)) { | ||
balance = yield provider.getBalance(walletAddress, blockNumber); | ||
} | ||
else { | ||
const contract = new ethers.Contract(assetId, ['function balanceOf(address owner) view returns (uint256)'], provider); | ||
balance = yield contract.balanceOf(walletAddress, { | ||
blockTag: blockNumber, | ||
}); | ||
} | ||
return { | ||
amount: balance, | ||
blockNumber, | ||
}; | ||
}); | ||
const getCurrentBlockNumber = (chainId) => __awaiter(void 0, void 0, void 0, function* () { | ||
const rpc = yield getRpcProvider(chainId); | ||
return rpc.getBlockNumber(); | ||
}); | ||
export default { | ||
getBalances, | ||
}; |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -11,141 +10,59 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
var _a; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.getMulticallAddress = exports.getRpcProvider = exports.getRpcUrls = exports.getRpcUrl = void 0; | ||
var ethers_1 = require("ethers"); | ||
var _1 = require("."); | ||
var types_1 = require("./types"); | ||
var ConfigService_1 = __importDefault(require("./services/ConfigService")); | ||
import { providers } from 'ethers'; | ||
import { getRandomNumber, ServerError } from '.'; | ||
import { ChainId } from './types'; | ||
import ConfigService from './services/ConfigService'; | ||
// cached providers | ||
var chainProviders = {}; | ||
const chainProviders = {}; | ||
// Archive RPC Provider | ||
var archiveRpcs = (_a = {}, | ||
_a[types_1.ChainId.ETH] = 'https://speedy-nodes-nyc.moralis.io/5ed6053dc39eba789ff466c9/eth/mainnet/archive', | ||
_a[types_1.ChainId.BSC] = 'https://speedy-nodes-nyc.moralis.io/5ed6053dc39eba789ff466c9/bsc/mainnet/archive', | ||
_a[types_1.ChainId.POL] = 'https://speedy-nodes-nyc.moralis.io/5ed6053dc39eba789ff466c9/polygon/mainnet/archive', | ||
_a[types_1.ChainId.FTM] = 'https://speedy-nodes-nyc.moralis.io/5ed6053dc39eba789ff466c9/fantom/mainnet', | ||
_a); | ||
const archiveRpcs = { | ||
[ChainId.ETH]: 'https://speedy-nodes-nyc.moralis.io/5ed6053dc39eba789ff466c9/eth/mainnet/archive', | ||
[ChainId.BSC]: 'https://speedy-nodes-nyc.moralis.io/5ed6053dc39eba789ff466c9/bsc/mainnet/archive', | ||
[ChainId.POL]: 'https://speedy-nodes-nyc.moralis.io/5ed6053dc39eba789ff466c9/polygon/mainnet/archive', | ||
[ChainId.FTM]: 'https://speedy-nodes-nyc.moralis.io/5ed6053dc39eba789ff466c9/fantom/mainnet', | ||
}; | ||
// RPC Urls | ||
var getRpcUrl = function (chainId, archive) { | ||
if (archive === void 0) { archive = false; } | ||
return __awaiter(void 0, void 0, void 0, function () { | ||
var rpcUrls; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, (0, exports.getRpcUrls)(chainId, archive)]; | ||
case 1: | ||
rpcUrls = _a.sent(); | ||
return [2 /*return*/, rpcUrls[0]]; | ||
} | ||
}); | ||
}); | ||
}; | ||
exports.getRpcUrl = getRpcUrl; | ||
var getRpcUrls = function (chainId, archive) { | ||
if (archive === void 0) { archive = false; } | ||
return __awaiter(void 0, void 0, void 0, function () { | ||
var configService, config; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (archive && archiveRpcs[chainId]) { | ||
return [2 /*return*/, [archiveRpcs[chainId]]]; | ||
} | ||
configService = ConfigService_1.default.getInstance(); | ||
return [4 /*yield*/, configService.getConfigAsync()]; | ||
case 1: | ||
config = _a.sent(); | ||
return [2 /*return*/, config.rpcs[chainId]]; | ||
} | ||
}); | ||
}); | ||
}; | ||
exports.getRpcUrls = getRpcUrls; | ||
var getRandomProvider = function (providerList) { | ||
var index = (0, _1.getRandomNumber)(0, providerList.length - 1); | ||
export const getRpcUrl = (chainId, archive = false) => __awaiter(void 0, void 0, void 0, function* () { | ||
const rpcUrls = yield getRpcUrls(chainId, archive); | ||
return rpcUrls[0]; | ||
}); | ||
export const getRpcUrls = (chainId, archive = false) => __awaiter(void 0, void 0, void 0, function* () { | ||
if (archive && archiveRpcs[chainId]) { | ||
return [archiveRpcs[chainId]]; | ||
} | ||
const configService = ConfigService.getInstance(); | ||
const config = yield configService.getConfigAsync(); | ||
return config.rpcs[chainId]; | ||
}); | ||
const getRandomProvider = (providerList) => { | ||
const index = getRandomNumber(0, providerList.length - 1); | ||
return providerList[index]; | ||
}; | ||
// Provider | ||
var getRpcProvider = function (chainId, archive) { | ||
if (archive === void 0) { archive = false; } | ||
return __awaiter(void 0, void 0, void 0, function () { | ||
var _a, _b, _c, _d, urls; | ||
return __generator(this, function (_e) { | ||
switch (_e.label) { | ||
case 0: | ||
if (!(archive && archiveRpcs[chainId])) return [3 /*break*/, 2]; | ||
_b = (_a = ethers_1.providers.FallbackProvider).bind; | ||
_d = (_c = ethers_1.providers.StaticJsonRpcProvider).bind; | ||
return [4 /*yield*/, (0, exports.getRpcUrl)(chainId, archive)]; | ||
case 1: | ||
// return archive PRC, but don't cache it | ||
return [2 /*return*/, new (_b.apply(_a, [void 0, [ | ||
new (_d.apply(_c, [void 0, _e.sent(), chainId]))() | ||
]]))()]; | ||
case 2: | ||
if (!!chainProviders[chainId]) return [3 /*break*/, 4]; | ||
chainProviders[chainId] = []; | ||
return [4 /*yield*/, (0, exports.getRpcUrls)(chainId, archive)]; | ||
case 3: | ||
urls = _e.sent(); | ||
urls.forEach(function (url) { | ||
chainProviders[chainId].push(new ethers_1.providers.FallbackProvider([ | ||
new ethers_1.providers.StaticJsonRpcProvider(url, chainId), | ||
])); | ||
}); | ||
_e.label = 4; | ||
case 4: | ||
if (!chainProviders[chainId].length) { | ||
throw new _1.ServerError("Unable to configure provider for chain ".concat(chainId)); | ||
} | ||
return [2 /*return*/, getRandomProvider(chainProviders[chainId])]; | ||
} | ||
export const getRpcProvider = (chainId, archive = false) => __awaiter(void 0, void 0, void 0, function* () { | ||
if (archive && archiveRpcs[chainId]) { | ||
// return archive PRC, but don't cache it | ||
return new providers.FallbackProvider([ | ||
new providers.StaticJsonRpcProvider(yield getRpcUrl(chainId, archive), chainId), | ||
]); | ||
} | ||
if (!chainProviders[chainId]) { | ||
chainProviders[chainId] = []; | ||
const urls = yield getRpcUrls(chainId, archive); | ||
urls.forEach((url) => { | ||
chainProviders[chainId].push(new providers.FallbackProvider([ | ||
new providers.StaticJsonRpcProvider(url, chainId), | ||
])); | ||
}); | ||
}); | ||
}; | ||
exports.getRpcProvider = getRpcProvider; | ||
} | ||
if (!chainProviders[chainId].length) { | ||
throw new ServerError(`Unable to configure provider for chain ${chainId}`); | ||
} | ||
return getRandomProvider(chainProviders[chainId]); | ||
}); | ||
// Multicall | ||
var getMulticallAddress = function (chainId) { return __awaiter(void 0, void 0, void 0, function () { | ||
var configService, config; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
configService = ConfigService_1.default.getInstance(); | ||
return [4 /*yield*/, configService.getConfigAsync()]; | ||
case 1: | ||
config = _a.sent(); | ||
return [2 /*return*/, config.multicallAddresses[chainId]]; | ||
} | ||
}); | ||
}); }; | ||
exports.getMulticallAddress = getMulticallAddress; | ||
export const getMulticallAddress = (chainId) => __awaiter(void 0, void 0, void 0, function* () { | ||
const configService = ConfigService.getInstance(); | ||
const config = yield configService.getConfigAsync(); | ||
return config.multicallAddresses[chainId]; | ||
}); |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -11,147 +10,82 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.checkAllowance = void 0; | ||
var bignumber_js_1 = __importDefault(require("bignumber.js")); | ||
var ethers_1 = require("ethers"); | ||
var utils_1 = require("../allowance/utils"); | ||
var getProvider_1 = require("../utils/getProvider"); | ||
var parseError_1 = require("../utils/parseError"); | ||
var checkAllowance = function (signer, step, chain, token, amount, spenderAddress, statusManager, infiniteApproval, allowUserInteraction | ||
import BigNumber from 'bignumber.js'; | ||
import { constants } from 'ethers'; | ||
import { getApproved, setApproval } from '../allowance/utils'; | ||
import { getProvider } from '../utils/getProvider'; | ||
import { parseError } from '../utils/parseError'; | ||
export const checkAllowance = (signer, step, chain, token, amount, spenderAddress, statusManager, infiniteApproval = false, allowUserInteraction = false | ||
// eslint-disable-next-line max-params | ||
) { | ||
if (infiniteApproval === void 0) { infiniteApproval = false; } | ||
if (allowUserInteraction === void 0) { allowUserInteraction = false; } | ||
return __awaiter(void 0, void 0, void 0, function () { | ||
var allowanceProcess, approved, approvalAmount, approveTx, e_1, error; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
allowanceProcess = statusManager.findOrCreateProcess('TOKEN_ALLOWANCE', step); | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 10, , 15]); | ||
if (!allowanceProcess.txHash) return [3 /*break*/, 3]; | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'PENDING'); | ||
return [4 /*yield*/, (0, getProvider_1.getProvider)(signer).waitForTransaction(allowanceProcess.txHash)]; | ||
case 2: | ||
_a.sent(); | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE'); | ||
return [3 /*break*/, 9]; | ||
case 3: | ||
if (!(allowanceProcess.status === 'DONE')) return [3 /*break*/, 4]; | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE'); | ||
return [3 /*break*/, 9]; | ||
case 4: return [4 /*yield*/, (0, utils_1.getApproved)(signer, token.address, spenderAddress)]; | ||
case 5: | ||
approved = _a.sent(); | ||
if (!new bignumber_js_1.default(amount).gt(approved)) return [3 /*break*/, 8]; | ||
if (!allowUserInteraction) { | ||
return [2 /*return*/]; | ||
} | ||
approvalAmount = infiniteApproval | ||
? ethers_1.constants.MaxUint256.toString() | ||
: amount; | ||
return [4 /*yield*/, (0, utils_1.setApproval)(signer, token.address, spenderAddress, approvalAmount) | ||
// update currentExecution | ||
]; | ||
case 6: | ||
approveTx = _a.sent(); | ||
// update currentExecution | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'PENDING', { | ||
txHash: approveTx.hash, | ||
txLink: chain.metamask.blockExplorerUrls[0] + 'tx/' + approveTx.hash, | ||
}); | ||
// wait for transcation | ||
return [4 /*yield*/, approveTx.wait()]; | ||
case 7: | ||
// wait for transcation | ||
_a.sent(); | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE'); | ||
return [3 /*break*/, 9]; | ||
case 8: | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE'); | ||
_a.label = 9; | ||
case 9: return [3 /*break*/, 15]; | ||
case 10: | ||
e_1 = _a.sent(); | ||
if (!(e_1.code === 'TRANSACTION_REPLACED' && e_1.replacement)) return [3 /*break*/, 12]; | ||
return [4 /*yield*/, transactionReplaced(e_1.replacement, allowanceProcess, step, chain, statusManager)]; | ||
case 11: | ||
_a.sent(); | ||
return [3 /*break*/, 14]; | ||
case 12: return [4 /*yield*/, (0, parseError_1.parseError)(e_1, step, allowanceProcess)]; | ||
case 13: | ||
error = _a.sent(); | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'FAILED', { | ||
error: { | ||
message: error.message, | ||
htmlMessage: error.htmlMessage, | ||
code: error.code, | ||
}, | ||
}); | ||
statusManager.updateExecution(step, 'FAILED'); | ||
throw error; | ||
case 14: return [3 /*break*/, 15]; | ||
case 15: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
}; | ||
exports.checkAllowance = checkAllowance; | ||
var transactionReplaced = function (replacementTx, allowanceProcess, step, chain, statusManager) { return __awaiter(void 0, void 0, void 0, function () { | ||
var e_2; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
_a.trys.push([0, 2, , 5]); | ||
) => __awaiter(void 0, void 0, void 0, function* () { | ||
// Ask user to set allowance | ||
// -> set currentExecution | ||
let allowanceProcess = statusManager.findOrCreateProcess('TOKEN_ALLOWANCE', step); | ||
// -> check allowance | ||
try { | ||
if (allowanceProcess.txHash) { | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'PENDING'); | ||
yield getProvider(signer).waitForTransaction(allowanceProcess.txHash); | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE'); | ||
// TODO: Do we need this check? | ||
} | ||
else if (allowanceProcess.status === 'DONE') { | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE'); | ||
} | ||
else { | ||
const approved = yield getApproved(signer, token.address, spenderAddress); | ||
if (new BigNumber(amount).gt(approved)) { | ||
if (!allowUserInteraction) { | ||
return; | ||
} | ||
const approvalAmount = infiniteApproval | ||
? constants.MaxUint256.toString() | ||
: amount; | ||
const approveTx = yield setApproval(signer, token.address, spenderAddress, approvalAmount); | ||
// update currentExecution | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'PENDING', { | ||
txHash: replacementTx.hash, | ||
txLink: chain.metamask.blockExplorerUrls[0] + 'tx/' + replacementTx.hash, | ||
txHash: approveTx.hash, | ||
txLink: chain.metamask.blockExplorerUrls[0] + 'tx/' + approveTx.hash, | ||
}); | ||
return [4 /*yield*/, replacementTx.wait()]; | ||
case 1: | ||
_a.sent(); | ||
// wait for transcation | ||
yield approveTx.wait(); | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE'); | ||
return [3 /*break*/, 5]; | ||
case 2: | ||
e_2 = _a.sent(); | ||
if (!(e_2.code === 'TRANSACTION_REPLACED' && e_2.replacement)) return [3 /*break*/, 4]; | ||
return [4 /*yield*/, transactionReplaced(e_2.replacement, allowanceProcess, step, chain, statusManager)]; | ||
case 3: | ||
_a.sent(); | ||
_a.label = 4; | ||
case 4: throw e_2; | ||
case 5: return [2 /*return*/]; | ||
} | ||
else { | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE'); | ||
} | ||
} | ||
}); | ||
}); }; | ||
} | ||
catch (e) { | ||
// -> set status | ||
if (e.code === 'TRANSACTION_REPLACED' && e.replacement) { | ||
yield transactionReplaced(e.replacement, allowanceProcess, step, chain, statusManager); | ||
} | ||
else { | ||
const error = yield parseError(e, step, allowanceProcess); | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'FAILED', { | ||
error: { | ||
message: error.message, | ||
htmlMessage: error.htmlMessage, | ||
code: error.code, | ||
}, | ||
}); | ||
statusManager.updateExecution(step, 'FAILED'); | ||
throw error; | ||
} | ||
} | ||
}); | ||
const transactionReplaced = (replacementTx, allowanceProcess, step, chain, statusManager) => __awaiter(void 0, void 0, void 0, function* () { | ||
try { | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'PENDING', { | ||
txHash: replacementTx.hash, | ||
txLink: chain.metamask.blockExplorerUrls[0] + 'tx/' + replacementTx.hash, | ||
}); | ||
yield replacementTx.wait(); | ||
allowanceProcess = statusManager.updateProcess(step, allowanceProcess.type, 'DONE'); | ||
} | ||
catch (e) { | ||
if (e.code === 'TRANSACTION_REPLACED' && e.replacement) { | ||
yield transactionReplaced(e.replacement, allowanceProcess, step, chain, statusManager); | ||
} | ||
throw e; | ||
} | ||
}); |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -11,77 +10,33 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
import BigNumber from 'bignumber.js'; | ||
import balances from '../balances'; | ||
import { ValidationError } from '../utils/errors'; | ||
export const balanceCheck = (signer, step) => __awaiter(void 0, void 0, void 0, function* () { | ||
const tokenAmount = yield balances.getTokenBalance(yield signer.getAddress(), step.action.fromToken); | ||
if (tokenAmount) { | ||
const currentBalance = new BigNumber(tokenAmount.amount).shiftedBy(tokenAmount.decimals); | ||
const neededBalance = new BigNumber(step.action.fromAmount); | ||
if (currentBalance.lt(neededBalance)) { | ||
if (neededBalance.multipliedBy(1 - step.action.slippage).lte(currentBalance)) { | ||
// adjust amount in slippage limits | ||
step.action.fromAmount = currentBalance.toFixed(0); | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.balanceCheck = void 0; | ||
var bignumber_js_1 = __importDefault(require("bignumber.js")); | ||
var balances_1 = __importDefault(require("../balances")); | ||
var errors_1 = require("../utils/errors"); | ||
var balanceCheck = function (signer, step) { return __awaiter(void 0, void 0, void 0, function () { | ||
var tokenAmount, _a, _b, currentBalance, neededBalance, neeeded, current, errorMessage; | ||
return __generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
_b = (_a = balances_1.default).getTokenBalance; | ||
return [4 /*yield*/, signer.getAddress()]; | ||
case 1: return [4 /*yield*/, _b.apply(_a, [_c.sent(), step.action.fromToken])]; | ||
case 2: | ||
tokenAmount = _c.sent(); | ||
if (tokenAmount) { | ||
currentBalance = new bignumber_js_1.default(tokenAmount.amount).shiftedBy(tokenAmount.decimals); | ||
neededBalance = new bignumber_js_1.default(step.action.fromAmount); | ||
if (currentBalance.lt(neededBalance)) { | ||
if (neededBalance.multipliedBy(1 - step.action.slippage).lte(currentBalance)) { | ||
// adjust amount in slippage limits | ||
step.action.fromAmount = currentBalance.toFixed(0); | ||
} | ||
else { | ||
neeeded = neededBalance.shiftedBy(-tokenAmount.decimals).toFixed(); | ||
current = currentBalance | ||
.shiftedBy(-tokenAmount.decimals) | ||
.toFixed(); | ||
errorMessage = "Your ".concat(tokenAmount.symbol, " balance is too low, ") + | ||
"you try to transfer ".concat(neeeded, " ").concat(tokenAmount.symbol, ", ") + | ||
"but your wallet only holds ".concat(current, " ").concat(tokenAmount.symbol, ". ") + | ||
"No funds have been sent. "; | ||
if (!currentBalance.isZero()) { | ||
errorMessage += | ||
"If the problem consists, please delete this transfer and " + | ||
"start a new one with a maximum of ".concat(current, " ").concat(tokenAmount.symbol, "."); | ||
} | ||
throw new errors_1.ValidationError('The balance is too low.', errorMessage); | ||
} | ||
} | ||
else { | ||
const neeeded = neededBalance.shiftedBy(-tokenAmount.decimals).toFixed(); | ||
const current = currentBalance | ||
.shiftedBy(-tokenAmount.decimals) | ||
.toFixed(); | ||
let errorMessage = `Your ${tokenAmount.symbol} balance is too low, ` + | ||
`you try to transfer ${neeeded} ${tokenAmount.symbol}, ` + | ||
`but your wallet only holds ${current} ${tokenAmount.symbol}. ` + | ||
`No funds have been sent. `; | ||
if (!currentBalance.isZero()) { | ||
errorMessage += | ||
`If the problem consists, please delete this transfer and ` + | ||
`start a new one with a maximum of ${current} ${tokenAmount.symbol}.`; | ||
} | ||
return [2 /*return*/]; | ||
throw new ValidationError('The balance is too low.', errorMessage); | ||
} | ||
} | ||
}); | ||
}); }; | ||
exports.balanceCheck = balanceCheck; | ||
} | ||
}); |
@@ -1,13 +0,1 @@ | ||
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -22,216 +10,139 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.BridgeExecutionManager = void 0; | ||
var ethers_1 = require("ethers"); | ||
var ApiService_1 = __importDefault(require("../../services/ApiService")); | ||
var ChainsService_1 = __importDefault(require("../../services/ChainsService")); | ||
var errors_1 = require("../../utils/errors"); | ||
var getProvider_1 = require("../../utils/getProvider"); | ||
var parseError_1 = require("../../utils/parseError"); | ||
var utils_1 = require("../../utils/utils"); | ||
var allowance_execute_1 = require("../allowance.execute"); | ||
var balanceCheck_execute_1 = require("../balanceCheck.execute"); | ||
var stepComparison_1 = require("../stepComparison"); | ||
var switchChain_1 = require("../switchChain"); | ||
var utils_2 = require("../utils"); | ||
var BridgeExecutionManager = /** @class */ (function () { | ||
function BridgeExecutionManager() { | ||
var _this = this; | ||
import { constants } from 'ethers'; | ||
import ApiService from '../../services/ApiService'; | ||
import ChainsService from '../../services/ChainsService'; | ||
import { LifiErrorCode, TransactionError } from '../../utils/errors'; | ||
import { getProvider } from '../../utils/getProvider'; | ||
import { getTransactionFailedMessage, parseError } from '../../utils/parseError'; | ||
import { personalizeStep } from '../../utils/utils'; | ||
import { checkAllowance } from '../allowance.execute'; | ||
import { balanceCheck } from '../balanceCheck.execute'; | ||
import { stepComparison } from '../stepComparison'; | ||
import { switchChain } from '../switchChain'; | ||
import { getSubstatusMessage, waitForReceivingTransaction } from '../utils'; | ||
export class BridgeExecutionManager { | ||
constructor() { | ||
this.shouldContinue = true; | ||
this.setShouldContinue = function (val) { | ||
_this.shouldContinue = val; | ||
this.setShouldContinue = (val) => { | ||
this.shouldContinue = val; | ||
}; | ||
this.execute = function (_a) { | ||
var signer = _a.signer, step = _a.step, statusManager = _a.statusManager, settings = _a.settings; | ||
return __awaiter(_this, void 0, void 0, function () { | ||
var action, estimate, chainsService, fromChain, toChain, oldCrossProcess, crossChainProcess, tx, personalizedStep, updatedStep, _b, transactionRequest, updatedSigner, e_1, error, receivingChainProcess, statusResponse, e_2; | ||
var _c, _d, _e, _f; | ||
return __generator(this, function (_g) { | ||
switch (_g.label) { | ||
case 0: | ||
action = step.action, estimate = step.estimate; | ||
step.execution = statusManager.initExecutionObject(step); | ||
chainsService = ChainsService_1.default.getInstance(); | ||
return [4 /*yield*/, chainsService.getChainById(action.fromChainId)]; | ||
case 1: | ||
fromChain = _g.sent(); | ||
return [4 /*yield*/, chainsService.getChainById(action.toChainId) | ||
// STEP 1: Check Allowance //////////////////////////////////////////////// | ||
// approval still needed? | ||
]; | ||
case 2: | ||
toChain = _g.sent(); | ||
oldCrossProcess = step.execution.process.find(function (p) { return p.type === 'CROSS_CHAIN'; }); | ||
if (!!(oldCrossProcess === null || oldCrossProcess === void 0 ? void 0 : oldCrossProcess.txHash)) return [3 /*break*/, 4]; | ||
if (!(action.fromToken.address !== ethers_1.constants.AddressZero)) return [3 /*break*/, 4]; | ||
// Check Token Approval only if fromToken is not the native token => no approval needed in that case | ||
return [4 /*yield*/, (0, allowance_execute_1.checkAllowance)(signer, step, fromChain, action.fromToken, action.fromAmount, estimate.approvalAddress, statusManager, settings.infiniteApproval, this.shouldContinue)]; | ||
case 3: | ||
// Check Token Approval only if fromToken is not the native token => no approval needed in that case | ||
_g.sent(); | ||
_g.label = 4; | ||
case 4: | ||
crossChainProcess = statusManager.findOrCreateProcess('CROSS_CHAIN', step); | ||
_g.label = 5; | ||
case 5: | ||
_g.trys.push([5, 16, , 20]); | ||
tx = void 0; | ||
if (!crossChainProcess.txHash) return [3 /*break*/, 7]; | ||
return [4 /*yield*/, (0, getProvider_1.getProvider)(signer).getTransaction(crossChainProcess.txHash)]; | ||
case 6: | ||
// load exiting transaction | ||
tx = _g.sent(); | ||
return [3 /*break*/, 14]; | ||
case 7: | ||
// check balance | ||
return [4 /*yield*/, (0, balanceCheck_execute_1.balanceCheck)(signer, step) | ||
// create new transaction | ||
]; | ||
case 8: | ||
// check balance | ||
_g.sent(); | ||
return [4 /*yield*/, (0, utils_1.personalizeStep)(signer, step)]; | ||
case 9: | ||
personalizedStep = _g.sent(); | ||
return [4 /*yield*/, ApiService_1.default.getStepTransaction(personalizedStep)]; | ||
case 10: | ||
updatedStep = _g.sent(); | ||
_b = [{}]; | ||
return [4 /*yield*/, (0, stepComparison_1.stepComparison)(statusManager, personalizedStep, updatedStep, settings.acceptSlippageUpdateHook, this.shouldContinue)]; | ||
case 11: | ||
step = __assign.apply(void 0, [__assign.apply(void 0, _b.concat([(_g.sent())])), { execution: step.execution }]); | ||
transactionRequest = step.transactionRequest; | ||
if (!transactionRequest) { | ||
throw new errors_1.TransactionError(errors_1.LifiErrorCode.TransactionUnprepared, 'Unable to prepare transaction.'); | ||
} | ||
return [4 /*yield*/, (0, switchChain_1.switchChain)(signer, statusManager, step, settings.switchChainHook, this.shouldContinue)]; | ||
case 12: | ||
updatedSigner = _g.sent(); | ||
if (!updatedSigner) { | ||
// chain switch was not successful, stop execution here | ||
return [2 /*return*/, step.execution]; | ||
} | ||
signer = updatedSigner; | ||
crossChainProcess = statusManager.updateProcess(step, crossChainProcess.type, 'ACTION_REQUIRED'); | ||
if (!this.shouldContinue) { | ||
return [2 /*return*/, step.execution]; | ||
} | ||
return [4 /*yield*/, signer.sendTransaction(transactionRequest) | ||
// STEP 4: Wait for Transaction /////////////////////////////////////////// | ||
]; | ||
case 13: | ||
tx = _g.sent(); | ||
// STEP 4: Wait for Transaction /////////////////////////////////////////// | ||
crossChainProcess = statusManager.updateProcess(step, crossChainProcess.type, 'PENDING', { | ||
txHash: tx.hash, | ||
txLink: fromChain.metamask.blockExplorerUrls[0] + 'tx/' + tx.hash, | ||
}); | ||
_g.label = 14; | ||
case 14: return [4 /*yield*/, tx.wait()]; | ||
case 15: | ||
_g.sent(); | ||
return [3 /*break*/, 20]; | ||
case 16: | ||
e_1 = _g.sent(); | ||
if (!(e_1.code === 'TRANSACTION_REPLACED' && e_1.replacement)) return [3 /*break*/, 17]; | ||
crossChainProcess = statusManager.updateProcess(step, crossChainProcess.type, 'PENDING', { | ||
txHash: e_1.replacement.hash, | ||
txLink: fromChain.metamask.blockExplorerUrls[0] + | ||
'tx/' + | ||
e_1.replacement.hash, | ||
}); | ||
return [3 /*break*/, 19]; | ||
case 17: return [4 /*yield*/, (0, parseError_1.parseError)(e_1, step, crossChainProcess)]; | ||
case 18: | ||
error = _g.sent(); | ||
crossChainProcess = statusManager.updateProcess(step, crossChainProcess.type, 'FAILED', { | ||
error: { | ||
message: error.message, | ||
htmlMessage: error.htmlMessage, | ||
code: error.code, | ||
}, | ||
}); | ||
statusManager.updateExecution(step, 'FAILED'); | ||
throw error; | ||
case 19: return [3 /*break*/, 20]; | ||
case 20: | ||
crossChainProcess = statusManager.updateProcess(step, crossChainProcess.type, 'DONE'); | ||
receivingChainProcess = statusManager.findOrCreateProcess('RECEIVING_CHAIN', step, 'PENDING'); | ||
_g.label = 21; | ||
case 21: | ||
_g.trys.push([21, 23, , 24]); | ||
if (!crossChainProcess.txHash) { | ||
throw new Error('Transaction hash is undefined.'); | ||
} | ||
return [4 /*yield*/, (0, utils_2.waitForReceivingTransaction)(crossChainProcess.txHash, statusManager, receivingChainProcess.type, step)]; | ||
case 22: | ||
statusResponse = _g.sent(); | ||
return [3 /*break*/, 24]; | ||
case 23: | ||
e_2 = _g.sent(); | ||
receivingChainProcess = statusManager.updateProcess(step, receivingChainProcess.type, 'FAILED', { | ||
error: { | ||
code: errors_1.LifiErrorCode.TransactionFailed, | ||
message: 'Failed while waiting for receiving chain.', | ||
htmlMessage: (0, parseError_1.getTransactionFailedMessage)(step, crossChainProcess.txLink), | ||
}, | ||
}); | ||
statusManager.updateExecution(step, 'FAILED'); | ||
throw e_2; | ||
case 24: | ||
receivingChainProcess = statusManager.updateProcess(step, receivingChainProcess.type, 'DONE', { | ||
substatus: statusResponse.substatus, | ||
substatusMessage: statusResponse.substatusMessage || | ||
(0, utils_2.getSubstatusMessage)(statusResponse.status, statusResponse.substatus), | ||
txHash: (_c = statusResponse.receiving) === null || _c === void 0 ? void 0 : _c.txHash, | ||
txLink: toChain.metamask.blockExplorerUrls[0] + | ||
'tx/' + | ||
((_d = statusResponse.receiving) === null || _d === void 0 ? void 0 : _d.txHash), | ||
}); | ||
statusManager.updateExecution(step, 'DONE', { | ||
fromAmount: statusResponse.sending.amount, | ||
toAmount: (_e = statusResponse.receiving) === null || _e === void 0 ? void 0 : _e.amount, | ||
toToken: (_f = statusResponse.receiving) === null || _f === void 0 ? void 0 : _f.token, | ||
gasUsed: statusResponse.sending.gasUsed, | ||
gasPrice: statusResponse.sending.gasPrice, | ||
}); | ||
// DONE | ||
return [2 /*return*/, step.execution]; | ||
this.execute = ({ signer, step, statusManager, settings, }) => __awaiter(this, void 0, void 0, function* () { | ||
var _a, _b, _c, _d; | ||
const { action, estimate } = step; | ||
step.execution = statusManager.initExecutionObject(step); | ||
const chainsService = ChainsService.getInstance(); | ||
const fromChain = yield chainsService.getChainById(action.fromChainId); | ||
const toChain = yield chainsService.getChainById(action.toChainId); | ||
// STEP 1: Check Allowance //////////////////////////////////////////////// | ||
// approval still needed? | ||
const oldCrossProcess = step.execution.process.find((p) => p.type === 'CROSS_CHAIN'); | ||
if (!(oldCrossProcess === null || oldCrossProcess === void 0 ? void 0 : oldCrossProcess.txHash)) { | ||
if (action.fromToken.address !== constants.AddressZero) { | ||
// Check Token Approval only if fromToken is not the native token => no approval needed in that case | ||
yield checkAllowance(signer, step, fromChain, action.fromToken, action.fromAmount, estimate.approvalAddress, statusManager, settings.infiniteApproval, this.shouldContinue); | ||
} | ||
} | ||
// STEP 2: Get Transaction //////////////////////////////////////////////// | ||
let crossChainProcess = statusManager.findOrCreateProcess('CROSS_CHAIN', step); | ||
try { | ||
let tx; | ||
if (crossChainProcess.txHash) { | ||
// load exiting transaction | ||
tx = yield getProvider(signer).getTransaction(crossChainProcess.txHash); | ||
} | ||
else { | ||
// check balance | ||
yield balanceCheck(signer, step); | ||
// create new transaction | ||
const personalizedStep = yield personalizeStep(signer, step); | ||
const updatedStep = yield ApiService.getStepTransaction(personalizedStep); | ||
step = Object.assign(Object.assign({}, (yield stepComparison(statusManager, personalizedStep, updatedStep, settings.acceptSlippageUpdateHook, this.shouldContinue))), { execution: step.execution }); | ||
const { transactionRequest } = step; | ||
if (!transactionRequest) { | ||
throw new TransactionError(LifiErrorCode.TransactionUnprepared, 'Unable to prepare transaction.'); | ||
} | ||
// STEP 3: Send Transaction /////////////////////////////////////////////// | ||
// make sure that chain is still correct | ||
const updatedSigner = yield switchChain(signer, statusManager, step, settings.switchChainHook, this.shouldContinue); | ||
if (!updatedSigner) { | ||
// chain switch was not successful, stop execution here | ||
return step.execution; | ||
} | ||
signer = updatedSigner; | ||
crossChainProcess = statusManager.updateProcess(step, crossChainProcess.type, 'ACTION_REQUIRED'); | ||
if (!this.shouldContinue) { | ||
return step.execution; | ||
} | ||
tx = yield signer.sendTransaction(transactionRequest); | ||
// STEP 4: Wait for Transaction /////////////////////////////////////////// | ||
crossChainProcess = statusManager.updateProcess(step, crossChainProcess.type, 'PENDING', { | ||
txHash: tx.hash, | ||
txLink: fromChain.metamask.blockExplorerUrls[0] + 'tx/' + tx.hash, | ||
}); | ||
} | ||
yield tx.wait(); | ||
} | ||
catch (e) { | ||
if (e.code === 'TRANSACTION_REPLACED' && e.replacement) { | ||
crossChainProcess = statusManager.updateProcess(step, crossChainProcess.type, 'PENDING', { | ||
txHash: e.replacement.hash, | ||
txLink: fromChain.metamask.blockExplorerUrls[0] + | ||
'tx/' + | ||
e.replacement.hash, | ||
}); | ||
} | ||
else { | ||
const error = yield parseError(e, step, crossChainProcess); | ||
crossChainProcess = statusManager.updateProcess(step, crossChainProcess.type, 'FAILED', { | ||
error: { | ||
message: error.message, | ||
htmlMessage: error.htmlMessage, | ||
code: error.code, | ||
}, | ||
}); | ||
statusManager.updateExecution(step, 'FAILED'); | ||
throw error; | ||
} | ||
} | ||
crossChainProcess = statusManager.updateProcess(step, crossChainProcess.type, 'DONE'); | ||
// STEP 5: Wait for Receiver ////////////////////////////////////// | ||
let receivingChainProcess = statusManager.findOrCreateProcess('RECEIVING_CHAIN', step, 'PENDING'); | ||
let statusResponse; | ||
try { | ||
if (!crossChainProcess.txHash) { | ||
throw new Error('Transaction hash is undefined.'); | ||
} | ||
statusResponse = yield waitForReceivingTransaction(crossChainProcess.txHash, statusManager, receivingChainProcess.type, step); | ||
} | ||
catch (e) { | ||
receivingChainProcess = statusManager.updateProcess(step, receivingChainProcess.type, 'FAILED', { | ||
error: { | ||
code: LifiErrorCode.TransactionFailed, | ||
message: 'Failed while waiting for receiving chain.', | ||
htmlMessage: getTransactionFailedMessage(step, crossChainProcess.txLink), | ||
}, | ||
}); | ||
statusManager.updateExecution(step, 'FAILED'); | ||
throw e; | ||
} | ||
receivingChainProcess = statusManager.updateProcess(step, receivingChainProcess.type, 'DONE', { | ||
substatus: statusResponse.substatus, | ||
substatusMessage: statusResponse.substatusMessage || | ||
getSubstatusMessage(statusResponse.status, statusResponse.substatus), | ||
txHash: (_a = statusResponse.receiving) === null || _a === void 0 ? void 0 : _a.txHash, | ||
txLink: toChain.metamask.blockExplorerUrls[0] + | ||
'tx/' + | ||
((_b = statusResponse.receiving) === null || _b === void 0 ? void 0 : _b.txHash), | ||
}); | ||
}; | ||
statusManager.updateExecution(step, 'DONE', { | ||
fromAmount: statusResponse.sending.amount, | ||
toAmount: (_c = statusResponse.receiving) === null || _c === void 0 ? void 0 : _c.amount, | ||
toToken: (_d = statusResponse.receiving) === null || _d === void 0 ? void 0 : _d.token, | ||
gasUsed: statusResponse.sending.gasUsed, | ||
gasPrice: statusResponse.sending.gasPrice, | ||
}); | ||
// DONE | ||
return step.execution; | ||
}); | ||
} | ||
return BridgeExecutionManager; | ||
}()); | ||
exports.BridgeExecutionManager = BridgeExecutionManager; | ||
} |
@@ -1,13 +0,1 @@ | ||
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -22,220 +10,149 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.SwapExecutionManager = void 0; | ||
var ethers_1 = require("ethers"); | ||
var ApiService_1 = __importDefault(require("../../services/ApiService")); | ||
var ChainsService_1 = __importDefault(require("../../services/ChainsService")); | ||
var errors_1 = require("../../utils/errors"); | ||
var getProvider_1 = require("../../utils/getProvider"); | ||
var parseError_1 = require("../../utils/parseError"); | ||
var utils_1 = require("../../utils/utils"); | ||
var allowance_execute_1 = require("../allowance.execute"); | ||
var balanceCheck_execute_1 = require("../balanceCheck.execute"); | ||
var stepComparison_1 = require("../stepComparison"); | ||
var switchChain_1 = require("../switchChain"); | ||
var utils_2 = require("../utils"); | ||
var SwapExecutionManager = /** @class */ (function () { | ||
function SwapExecutionManager() { | ||
var _this = this; | ||
import { constants } from 'ethers'; | ||
import ApiService from '../../services/ApiService'; | ||
import ChainsService from '../../services/ChainsService'; | ||
import { LifiErrorCode, TransactionError } from '../../utils/errors'; | ||
import { getProvider } from '../../utils/getProvider'; | ||
import { getTransactionFailedMessage, parseError } from '../../utils/parseError'; | ||
import { personalizeStep } from '../../utils/utils'; | ||
import { checkAllowance } from '../allowance.execute'; | ||
import { balanceCheck } from '../balanceCheck.execute'; | ||
import { stepComparison } from '../stepComparison'; | ||
import { switchChain } from '../switchChain'; | ||
import { waitForReceivingTransaction } from '../utils'; | ||
export class SwapExecutionManager { | ||
constructor() { | ||
this.shouldContinue = true; | ||
this.setShouldContinue = function (val) { | ||
_this.shouldContinue = val; | ||
this.setShouldContinue = (val) => { | ||
this.shouldContinue = val; | ||
}; | ||
this.execute = function (_a) { | ||
var signer = _a.signer, step = _a.step, statusManager = _a.statusManager, settings = _a.settings; | ||
return __awaiter(_this, void 0, void 0, function () { | ||
var action, estimate, chainsService, fromChain, swapProcess, tx, personalizedStep, updatedStep, _b, transactionRequest, updatedSigner, e_1, error, receipt, e_2, error, statusResponse, e_3; | ||
var _c, _d, _e, _f; | ||
return __generator(this, function (_g) { | ||
switch (_g.label) { | ||
case 0: | ||
action = step.action, estimate = step.estimate; | ||
step.execution = statusManager.initExecutionObject(step); | ||
chainsService = ChainsService_1.default.getInstance(); | ||
return [4 /*yield*/, chainsService.getChainById(action.fromChainId) | ||
// Approval | ||
]; | ||
case 1: | ||
fromChain = _g.sent(); | ||
if (!(action.fromToken.address !== ethers_1.constants.AddressZero)) return [3 /*break*/, 3]; | ||
return [4 /*yield*/, (0, allowance_execute_1.checkAllowance)(signer, step, fromChain, action.fromToken, action.fromAmount, estimate.approvalAddress, statusManager, settings.infiniteApproval, this.shouldContinue)]; | ||
case 2: | ||
_g.sent(); | ||
_g.label = 3; | ||
case 3: | ||
swapProcess = statusManager.findOrCreateProcess('SWAP', step); | ||
_g.label = 4; | ||
case 4: | ||
_g.trys.push([4, 14, , 16]); | ||
if (!swapProcess.txHash) return [3 /*break*/, 6]; | ||
return [4 /*yield*/, (0, getProvider_1.getProvider)(signer).getTransaction(swapProcess.txHash)]; | ||
case 5: | ||
// -> restore existing tx | ||
tx = _g.sent(); | ||
return [3 /*break*/, 13]; | ||
case 6: | ||
// -> check balance | ||
return [4 /*yield*/, (0, balanceCheck_execute_1.balanceCheck)(signer, step) | ||
// -> get tx from backend | ||
]; | ||
case 7: | ||
// -> check balance | ||
_g.sent(); | ||
return [4 /*yield*/, (0, utils_1.personalizeStep)(signer, step)]; | ||
case 8: | ||
personalizedStep = _g.sent(); | ||
return [4 /*yield*/, ApiService_1.default.getStepTransaction(personalizedStep)]; | ||
case 9: | ||
updatedStep = _g.sent(); | ||
_b = [{}]; | ||
return [4 /*yield*/, (0, stepComparison_1.stepComparison)(statusManager, personalizedStep, updatedStep, settings.acceptSlippageUpdateHook, this.shouldContinue)]; | ||
case 10: | ||
step = __assign.apply(void 0, [__assign.apply(void 0, _b.concat([(_g.sent())])), { execution: step.execution }]); | ||
transactionRequest = step.transactionRequest; | ||
if (!transactionRequest) { | ||
throw new errors_1.TransactionError(errors_1.LifiErrorCode.TransactionUnprepared, 'Unable to prepare transaction.'); | ||
} | ||
return [4 /*yield*/, (0, switchChain_1.switchChain)(signer, statusManager, step, settings.switchChainHook, this.shouldContinue)]; | ||
case 11: | ||
updatedSigner = _g.sent(); | ||
if (!updatedSigner) { | ||
// chain switch was not successful, stop execution here | ||
return [2 /*return*/, step.execution]; | ||
} | ||
signer = updatedSigner; | ||
// -> set step.execution | ||
swapProcess = swapProcess = statusManager.updateProcess(step, swapProcess.type, 'ACTION_REQUIRED'); | ||
if (!this.shouldContinue) { | ||
return [2 /*return*/, step.execution]; // stop before user interaction is needed | ||
} | ||
return [4 /*yield*/, signer.sendTransaction(transactionRequest)]; | ||
case 12: | ||
// -> submit tx | ||
tx = _g.sent(); | ||
_g.label = 13; | ||
case 13: return [3 /*break*/, 16]; | ||
case 14: | ||
e_1 = _g.sent(); | ||
return [4 /*yield*/, (0, parseError_1.parseError)(e_1, step, swapProcess)]; | ||
case 15: | ||
error = _g.sent(); | ||
swapProcess = statusManager.updateProcess(step, swapProcess.type, 'FAILED', { | ||
error: { | ||
message: error.message, | ||
htmlMessage: error.htmlMessage, | ||
code: error.code, | ||
}, | ||
}); | ||
statusManager.updateExecution(step, 'FAILED'); | ||
throw error; | ||
case 16: | ||
// Wait for Transaction | ||
swapProcess = statusManager.updateProcess(step, swapProcess.type, 'PENDING', { | ||
txLink: fromChain.metamask.blockExplorerUrls[0] + 'tx/' + tx.hash, | ||
txHash: tx.hash, | ||
}); | ||
_g.label = 17; | ||
case 17: | ||
_g.trys.push([17, 19, , 23]); | ||
return [4 /*yield*/, tx.wait()]; | ||
case 18: | ||
receipt = _g.sent(); | ||
return [3 /*break*/, 23]; | ||
case 19: | ||
e_2 = _g.sent(); | ||
if (!(e_2.code === 'TRANSACTION_REPLACED' && e_2.replacement)) return [3 /*break*/, 20]; | ||
receipt = e_2.replacement; | ||
swapProcess = statusManager.updateProcess(step, swapProcess.type, 'PENDING', { | ||
txHash: e_2.replacement.hash, | ||
txLink: fromChain.metamask.blockExplorerUrls[0] + | ||
'tx/' + | ||
e_2.replacement.hash, | ||
}); | ||
return [3 /*break*/, 22]; | ||
case 20: return [4 /*yield*/, (0, parseError_1.parseError)(e_2)]; | ||
case 21: | ||
error = _g.sent(); | ||
swapProcess = statusManager.updateProcess(step, swapProcess.type, 'FAILED', { | ||
error: { | ||
message: error.message, | ||
htmlMessage: error.htmlMessage, | ||
code: error.code, | ||
}, | ||
}); | ||
statusManager.updateExecution(step, 'FAILED'); | ||
throw error; | ||
case 22: return [3 /*break*/, 23]; | ||
case 23: | ||
_g.trys.push([23, 25, , 26]); | ||
if (!swapProcess.txHash) { | ||
throw new Error('Transaction hash is undefined.'); | ||
} | ||
return [4 /*yield*/, (0, utils_2.waitForReceivingTransaction)(swapProcess.txHash, statusManager, swapProcess.type, step)]; | ||
case 24: | ||
statusResponse = _g.sent(); | ||
return [3 /*break*/, 26]; | ||
case 25: | ||
e_3 = _g.sent(); | ||
swapProcess = statusManager.updateProcess(step, swapProcess.type, 'FAILED', { | ||
error: { | ||
code: errors_1.LifiErrorCode.TransactionFailed, | ||
message: 'Failed while waiting for receiving chain.', | ||
htmlMessage: (0, parseError_1.getTransactionFailedMessage)(step, swapProcess.txLink), | ||
}, | ||
}); | ||
statusManager.updateExecution(step, 'FAILED'); | ||
throw e_3; | ||
case 26: | ||
swapProcess = statusManager.updateProcess(step, swapProcess.type, 'DONE', { | ||
txHash: (_c = statusResponse.receiving) === null || _c === void 0 ? void 0 : _c.txHash, | ||
txLink: fromChain.metamask.blockExplorerUrls[0] + | ||
'tx/' + | ||
((_d = statusResponse.receiving) === null || _d === void 0 ? void 0 : _d.txHash), | ||
}); | ||
statusManager.updateExecution(step, 'DONE', { | ||
fromAmount: statusResponse.sending.amount, | ||
toAmount: (_e = statusResponse.receiving) === null || _e === void 0 ? void 0 : _e.amount, | ||
toToken: (_f = statusResponse.receiving) === null || _f === void 0 ? void 0 : _f.token, | ||
gasUsed: statusResponse.sending.gasUsed, | ||
gasPrice: statusResponse.sending.gasPrice, | ||
}); | ||
// DONE | ||
return [2 /*return*/, step.execution]; | ||
this.execute = ({ signer, step, statusManager, settings, }) => __awaiter(this, void 0, void 0, function* () { | ||
// setup | ||
var _a, _b, _c, _d; | ||
const { action, estimate } = step; | ||
step.execution = statusManager.initExecutionObject(step); | ||
const chainsService = ChainsService.getInstance(); | ||
const fromChain = yield chainsService.getChainById(action.fromChainId); | ||
// Approval | ||
if (action.fromToken.address !== constants.AddressZero) { | ||
yield checkAllowance(signer, step, fromChain, action.fromToken, action.fromAmount, estimate.approvalAddress, statusManager, settings.infiniteApproval, this.shouldContinue); | ||
} | ||
// Start Swap | ||
// -> set step.execution | ||
let swapProcess = statusManager.findOrCreateProcess('SWAP', step); | ||
// -> swapping | ||
let tx; | ||
try { | ||
if (swapProcess.txHash) { | ||
// -> restore existing tx | ||
tx = yield getProvider(signer).getTransaction(swapProcess.txHash); | ||
} | ||
else { | ||
// -> check balance | ||
yield balanceCheck(signer, step); | ||
// -> get tx from backend | ||
const personalizedStep = yield personalizeStep(signer, step); | ||
const updatedStep = yield ApiService.getStepTransaction(personalizedStep); | ||
step = Object.assign(Object.assign({}, (yield stepComparison(statusManager, personalizedStep, updatedStep, settings.acceptSlippageUpdateHook, this.shouldContinue))), { execution: step.execution }); | ||
const { transactionRequest } = step; | ||
if (!transactionRequest) { | ||
throw new TransactionError(LifiErrorCode.TransactionUnprepared, 'Unable to prepare transaction.'); | ||
} | ||
// make sure that chain is still correct | ||
const updatedSigner = yield switchChain(signer, statusManager, step, settings.switchChainHook, this.shouldContinue); | ||
if (!updatedSigner) { | ||
// chain switch was not successful, stop execution here | ||
return step.execution; | ||
} | ||
signer = updatedSigner; | ||
// -> set step.execution | ||
swapProcess = swapProcess = statusManager.updateProcess(step, swapProcess.type, 'ACTION_REQUIRED'); | ||
if (!this.shouldContinue) { | ||
return step.execution; // stop before user interaction is needed | ||
} | ||
// -> submit tx | ||
tx = yield signer.sendTransaction(transactionRequest); | ||
} | ||
} | ||
catch (e) { | ||
const error = yield parseError(e, step, swapProcess); | ||
swapProcess = statusManager.updateProcess(step, swapProcess.type, 'FAILED', { | ||
error: { | ||
message: error.message, | ||
htmlMessage: error.htmlMessage, | ||
code: error.code, | ||
}, | ||
}); | ||
statusManager.updateExecution(step, 'FAILED'); | ||
throw error; | ||
} | ||
// Wait for Transaction | ||
swapProcess = statusManager.updateProcess(step, swapProcess.type, 'PENDING', { | ||
txLink: fromChain.metamask.blockExplorerUrls[0] + 'tx/' + tx.hash, | ||
txHash: tx.hash, | ||
}); | ||
}; | ||
// -> waiting | ||
let receipt; | ||
try { | ||
receipt = yield tx.wait(); | ||
} | ||
catch (e) { | ||
// -> set status | ||
if (e.code === 'TRANSACTION_REPLACED' && e.replacement) { | ||
receipt = e.replacement; | ||
swapProcess = statusManager.updateProcess(step, swapProcess.type, 'PENDING', { | ||
txHash: e.replacement.hash, | ||
txLink: fromChain.metamask.blockExplorerUrls[0] + | ||
'tx/' + | ||
e.replacement.hash, | ||
}); | ||
} | ||
else { | ||
const error = yield parseError(e); | ||
swapProcess = statusManager.updateProcess(step, swapProcess.type, 'FAILED', { | ||
error: { | ||
message: error.message, | ||
htmlMessage: error.htmlMessage, | ||
code: error.code, | ||
}, | ||
}); | ||
statusManager.updateExecution(step, 'FAILED'); | ||
throw error; | ||
} | ||
} | ||
let statusResponse; | ||
try { | ||
if (!swapProcess.txHash) { | ||
throw new Error('Transaction hash is undefined.'); | ||
} | ||
statusResponse = yield waitForReceivingTransaction(swapProcess.txHash, statusManager, swapProcess.type, step); | ||
} | ||
catch (e) { | ||
swapProcess = statusManager.updateProcess(step, swapProcess.type, 'FAILED', { | ||
error: { | ||
code: LifiErrorCode.TransactionFailed, | ||
message: 'Failed while waiting for receiving chain.', | ||
htmlMessage: getTransactionFailedMessage(step, swapProcess.txLink), | ||
}, | ||
}); | ||
statusManager.updateExecution(step, 'FAILED'); | ||
throw e; | ||
} | ||
swapProcess = statusManager.updateProcess(step, swapProcess.type, 'DONE', { | ||
txHash: (_a = statusResponse.receiving) === null || _a === void 0 ? void 0 : _a.txHash, | ||
txLink: fromChain.metamask.blockExplorerUrls[0] + | ||
'tx/' + | ||
((_b = statusResponse.receiving) === null || _b === void 0 ? void 0 : _b.txHash), | ||
}); | ||
statusManager.updateExecution(step, 'DONE', { | ||
fromAmount: statusResponse.sending.amount, | ||
toAmount: (_c = statusResponse.receiving) === null || _c === void 0 ? void 0 : _c.amount, | ||
toToken: (_d = statusResponse.receiving) === null || _d === void 0 ? void 0 : _d.token, | ||
gasUsed: statusResponse.sending.gasUsed, | ||
gasPrice: statusResponse.sending.gasPrice, | ||
}); | ||
// DONE | ||
return step.execution; | ||
}); | ||
} | ||
return SwapExecutionManager; | ||
}()); | ||
exports.SwapExecutionManager = SwapExecutionManager; | ||
} |
@@ -1,17 +0,1 @@ | ||
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
o[k2] = m[k]; | ||
})); | ||
var __exportStar = (this && this.__exportStar) || function(m, exports) { | ||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
__exportStar(require("./StatusManager"), exports); | ||
export * from './StatusManager'; |
@@ -1,7 +0,4 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.StatusManager = void 0; | ||
var types_1 = require("../types"); | ||
var utils_1 = require("../utils/utils"); | ||
var utils_2 = require("./utils"); | ||
import { emptyExecution, } from '../types'; | ||
import { deepClone } from '../utils/utils'; | ||
import { getProcessMessage } from './utils'; | ||
/** | ||
@@ -14,5 +11,4 @@ * Manages status updates of a route and provides various functions for tracking processes | ||
*/ | ||
var StatusManager = /** @class */ (function () { | ||
function StatusManager(route, settings, internalUpdateRouteCallback) { | ||
var _this = this; | ||
export class StatusManager { | ||
constructor(route, settings, internalUpdateRouteCallback) { | ||
this.shouldUpdate = true; | ||
@@ -24,8 +20,8 @@ /** | ||
*/ | ||
this.initExecutionObject = function (step) { | ||
var currentExecution = step.execution || (0, utils_1.deepClone)(types_1.emptyExecution); | ||
this.initExecutionObject = (step) => { | ||
const currentExecution = step.execution || deepClone(emptyExecution); | ||
if (!step.execution) { | ||
step.execution = currentExecution; | ||
step.execution.status = 'PENDING'; | ||
_this.updateStepInRoute(step); | ||
this.updateStepInRoute(step); | ||
} | ||
@@ -35,3 +31,3 @@ // Change status to PENDING after resuming from FAILED | ||
currentExecution.status = 'PENDING'; | ||
_this.updateStepInRoute(step); | ||
this.updateStepInRoute(step); | ||
} | ||
@@ -47,18 +43,18 @@ return currentExecution; | ||
*/ | ||
this.findOrCreateProcess = function (type, step, status) { | ||
this.findOrCreateProcess = (type, step, status) => { | ||
if (!step.execution || !step.execution.process) { | ||
throw new Error("Execution hasn't been initialized."); | ||
} | ||
var process = step.execution.process.find(function (p) { return p.type === type; }); | ||
const process = step.execution.process.find((p) => p.type === type); | ||
if (process) { | ||
return process; | ||
} | ||
var newProcess = { | ||
const newProcess = { | ||
type: type, | ||
startedAt: Date.now(), | ||
message: (0, utils_2.getProcessMessage)(type, status !== null && status !== void 0 ? status : 'STARTED'), | ||
message: getProcessMessage(type, status !== null && status !== void 0 ? status : 'STARTED'), | ||
status: status !== null && status !== void 0 ? status : 'STARTED', | ||
}; | ||
step.execution.process.push(newProcess); | ||
_this.updateStepInRoute(step); | ||
this.updateStepInRoute(step); | ||
return newProcess; | ||
@@ -74,3 +70,3 @@ }; | ||
*/ | ||
this.updateProcess = function (step, type, status, params) { | ||
this.updateProcess = (step, type, status, params) => { | ||
var _a; | ||
@@ -80,3 +76,3 @@ if (!step.execution) { | ||
} | ||
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; }); | ||
const currentProcess = (_a = step === null || step === void 0 ? void 0 : step.execution) === null || _a === void 0 ? void 0 : _a.process.find((p) => p.type === type); | ||
if (!currentProcess) { | ||
@@ -109,11 +105,10 @@ throw new Error("Can't find a process for the given type."); | ||
currentProcess.status = status; | ||
currentProcess.message = (0, utils_2.getProcessMessage)(type, status); | ||
currentProcess.message = getProcessMessage(type, status); | ||
// set extra parameters or overwritte the standard params set in the switch statement | ||
if (params) { | ||
for (var _i = 0, _b = Object.entries(params); _i < _b.length; _i++) { | ||
var _c = _b[_i], key = _c[0], value = _c[1]; | ||
for (const [key, value] of Object.entries(params)) { | ||
currentProcess[key] = value; | ||
} | ||
} | ||
_this.updateStepInRoute(step); // updates the step in the route | ||
this.updateStepInRoute(step); // updates the step in the route | ||
return currentProcess; | ||
@@ -127,22 +122,22 @@ }; | ||
*/ | ||
this.removeProcess = function (step, type) { | ||
this.removeProcess = (step, type) => { | ||
if (!step.execution) { | ||
throw new Error("Execution hasn't been initialized."); | ||
} | ||
var index = step.execution.process.findIndex(function (p) { return p.type === type; }); | ||
const index = step.execution.process.findIndex((p) => p.type === type); | ||
step.execution.process.splice(index, 1); | ||
_this.updateStepInRoute(step); | ||
this.updateStepInRoute(step); | ||
}; | ||
this.updateStepInRoute = function (step) { | ||
if (!_this.shouldUpdate) { | ||
this.updateStepInRoute = (step) => { | ||
if (!this.shouldUpdate) { | ||
return step; | ||
} | ||
var stepIndex = _this.route.steps.findIndex(function (routeStep) { return routeStep.id === step.id; }); | ||
const stepIndex = this.route.steps.findIndex((routeStep) => routeStep.id === step.id); | ||
if (stepIndex === -1) { | ||
throw new Error("Couldn't find a step to update."); | ||
} | ||
_this.route.steps[stepIndex] = Object.assign(_this.route.steps[stepIndex], step); | ||
_this.settings.updateCallback(_this.route); | ||
_this.internalUpdateRouteCallback(_this.route); | ||
return _this.route.steps[stepIndex]; | ||
this.route.steps[stepIndex] = Object.assign(this.route.steps[stepIndex], step); | ||
this.settings.updateCallback(this.route); | ||
this.internalUpdateRouteCallback(this.route); | ||
return this.route.steps[stepIndex]; | ||
}; | ||
@@ -160,3 +155,3 @@ this.route = route; | ||
*/ | ||
StatusManager.prototype.updateExecution = function (step, status, receipt) { | ||
updateExecution(step, status, receipt) { | ||
if (!step.execution) { | ||
@@ -173,8 +168,6 @@ throw Error("Can't update empty execution."); | ||
return step; | ||
}; | ||
StatusManager.prototype.setShouldUpdate = function (value) { | ||
} | ||
setShouldUpdate(value) { | ||
this.shouldUpdate = value; | ||
}; | ||
return StatusManager; | ||
}()); | ||
exports.StatusManager = StatusManager; | ||
} | ||
} |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -11,34 +10,5 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.stepComparison = void 0; | ||
var errors_1 = require("../utils/errors"); | ||
var parseError_1 = require("../utils/parseError"); | ||
var utils_1 = require("./utils"); | ||
import { LifiErrorCode, TransactionError } from '../utils/errors'; | ||
import { getSlippageNotMetMessage } from '../utils/parseError'; | ||
import { updatedStepMeetsSlippageConditions } from './utils'; | ||
/** | ||
@@ -55,29 +25,20 @@ * This method checks whether the new and updated Step meets the required slippage conditions. | ||
*/ | ||
var stepComparison = function (statusManager, oldStep, newStep, acceptSlippageUpdateHook, allowUserInteraction) { return __awaiter(void 0, void 0, void 0, function () { | ||
var allowStepUpdate; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if ((0, utils_1.updatedStepMeetsSlippageConditions)(oldStep, newStep)) { | ||
return [2 /*return*/, statusManager.updateStepInRoute(newStep)]; | ||
} | ||
if (!allowUserInteraction) return [3 /*break*/, 2]; | ||
return [4 /*yield*/, acceptSlippageUpdateHook({ | ||
oldToAmount: oldStep.estimate.toAmount, | ||
newToAmount: newStep.estimate.toAmount, | ||
toToken: newStep.action.toToken, | ||
oldSlippage: oldStep.action.slippage, | ||
newSlippage: newStep.action.slippage, | ||
})]; | ||
case 1: | ||
allowStepUpdate = _a.sent(); | ||
_a.label = 2; | ||
case 2: | ||
if (!allowStepUpdate) { | ||
throw new errors_1.TransactionError(errors_1.LifiErrorCode.SlippageNotMet, 'Slippage conditions not met!', (0, parseError_1.getSlippageNotMetMessage)(oldStep)); | ||
} | ||
return [2 /*return*/, statusManager.updateStepInRoute(newStep)]; | ||
} | ||
}); | ||
}); }; | ||
exports.stepComparison = stepComparison; | ||
export const stepComparison = (statusManager, oldStep, newStep, acceptSlippageUpdateHook, allowUserInteraction) => __awaiter(void 0, void 0, void 0, function* () { | ||
if (updatedStepMeetsSlippageConditions(oldStep, newStep)) { | ||
return statusManager.updateStepInRoute(newStep); | ||
} | ||
let allowStepUpdate; | ||
if (allowUserInteraction) { | ||
allowStepUpdate = yield acceptSlippageUpdateHook({ | ||
oldToAmount: oldStep.estimate.toAmount, | ||
newToAmount: newStep.estimate.toAmount, | ||
toToken: newStep.action.toToken, | ||
oldSlippage: oldStep.action.slippage, | ||
newSlippage: newStep.action.slippage, | ||
}); | ||
} | ||
if (!allowStepUpdate) { | ||
throw new TransactionError(LifiErrorCode.SlippageNotMet, 'Slippage conditions not met!', getSlippageNotMetMessage(oldStep)); | ||
} | ||
return statusManager.updateStepInRoute(newStep); | ||
}); |
@@ -1,13 +0,1 @@ | ||
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -22,119 +10,62 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.StepExecutor = void 0; | ||
var bridge_execute_1 = require("./bridges/bridge.execute"); | ||
var swap_execute_1 = require("./exchanges/swap.execute"); | ||
var switchChain_1 = require("./switchChain"); | ||
var defaultExecutionHaltSettings = { | ||
import { BridgeExecutionManager } from './bridges/bridge.execute'; | ||
import { SwapExecutionManager } from './exchanges/swap.execute'; | ||
import { switchChain } from './switchChain'; | ||
const defaultExecutionHaltSettings = { | ||
allowUpdates: true, | ||
}; | ||
var StepExecutor = /** @class */ (function () { | ||
function StepExecutor(statusManager, settings) { | ||
var _this = this; | ||
this.swapExecutionManager = new swap_execute_1.SwapExecutionManager(); | ||
this.bridgeExecutionManager = new bridge_execute_1.BridgeExecutionManager(); | ||
export class StepExecutor { | ||
constructor(statusManager, settings) { | ||
this.swapExecutionManager = new SwapExecutionManager(); | ||
this.bridgeExecutionManager = new BridgeExecutionManager(); | ||
this.executionStopped = false; | ||
this.stopStepExecution = function (settings) { | ||
var haltingSettings = __assign(__assign({}, defaultExecutionHaltSettings), settings); | ||
_this.swapExecutionManager.setShouldContinue(false); | ||
_this.bridgeExecutionManager.setShouldContinue(false); | ||
_this.statusManager.setShouldUpdate(haltingSettings.allowUpdates); | ||
_this.executionStopped = true; | ||
this.stopStepExecution = (settings) => { | ||
const haltingSettings = Object.assign(Object.assign({}, defaultExecutionHaltSettings), settings); | ||
this.swapExecutionManager.setShouldContinue(false); | ||
this.bridgeExecutionManager.setShouldContinue(false); | ||
this.statusManager.setShouldUpdate(haltingSettings.allowUpdates); | ||
this.executionStopped = true; | ||
}; | ||
this.executeStep = function (signer, step) { return __awaiter(_this, void 0, void 0, function () { | ||
var updatedSigner, _a; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: return [4 /*yield*/, (0, switchChain_1.switchChain)(signer, this.statusManager, step, this.settings.switchChainHook, !this.executionStopped)]; | ||
case 1: | ||
updatedSigner = _b.sent(); | ||
if (!updatedSigner) { | ||
// chain switch was not successful, stop execution here | ||
return [2 /*return*/, step]; | ||
} | ||
signer = updatedSigner; | ||
_a = step.type; | ||
switch (_a) { | ||
case 'lifi': return [3 /*break*/, 2]; | ||
case 'cross': return [3 /*break*/, 2]; | ||
case 'swap': return [3 /*break*/, 4]; | ||
} | ||
return [3 /*break*/, 6]; | ||
case 2: return [4 /*yield*/, this.executeCross(signer, step)]; | ||
case 3: | ||
_b.sent(); | ||
return [3 /*break*/, 7]; | ||
case 4: return [4 /*yield*/, this.executeSwap(signer, step)]; | ||
case 5: | ||
_b.sent(); | ||
return [3 /*break*/, 7]; | ||
case 6: throw new Error('Unsupported step type.'); | ||
case 7: return [2 /*return*/, step]; | ||
} | ||
}); | ||
}); }; | ||
this.executeSwap = function (signer, step) { return __awaiter(_this, void 0, void 0, function () { | ||
var swapParams; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
swapParams = { | ||
signer: signer, | ||
step: step, | ||
settings: this.settings, | ||
statusManager: this.statusManager, | ||
}; | ||
return [4 /*yield*/, this.swapExecutionManager.execute(swapParams)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
}); }; | ||
this.executeCross = function (signer, step) { return __awaiter(_this, void 0, void 0, function () { | ||
var crossParams; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
crossParams = { | ||
signer: signer, | ||
step: step, | ||
settings: this.settings, | ||
statusManager: this.statusManager, | ||
}; | ||
return [4 /*yield*/, this.bridgeExecutionManager.execute(crossParams)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
}); }; | ||
this.executeStep = (signer, step) => __awaiter(this, void 0, void 0, function* () { | ||
// check if signer is for correct chain | ||
const updatedSigner = yield switchChain(signer, this.statusManager, step, this.settings.switchChainHook, !this.executionStopped); | ||
if (!updatedSigner) { | ||
// chain switch was not successful, stop execution here | ||
return step; | ||
} | ||
signer = updatedSigner; | ||
switch (step.type) { | ||
case 'lifi': | ||
case 'cross': | ||
yield this.executeCross(signer, step); | ||
break; | ||
case 'swap': | ||
yield this.executeSwap(signer, step); | ||
break; | ||
default: | ||
throw new Error('Unsupported step type.'); | ||
} | ||
return step; | ||
}); | ||
this.executeSwap = (signer, step) => __awaiter(this, void 0, void 0, function* () { | ||
const swapParams = { | ||
signer, | ||
step, | ||
settings: this.settings, | ||
statusManager: this.statusManager, | ||
}; | ||
return yield this.swapExecutionManager.execute(swapParams); | ||
}); | ||
this.executeCross = (signer, step) => __awaiter(this, void 0, void 0, function* () { | ||
const crossParams = { | ||
signer, | ||
step, | ||
settings: this.settings, | ||
statusManager: this.statusManager, | ||
}; | ||
return yield this.bridgeExecutionManager.execute(crossParams); | ||
}); | ||
this.statusManager = statusManager; | ||
this.settings = settings; | ||
} | ||
return StepExecutor; | ||
}()); | ||
exports.StepExecutor = StepExecutor; | ||
} |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -11,32 +10,3 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.switchChain = void 0; | ||
var errors_1 = require("../utils/errors"); | ||
import { LifiErrorCode, ProviderError } from '../utils/errors'; | ||
/** | ||
@@ -53,52 +23,34 @@ * This method checks whether the signer is configured for the correct chain. | ||
*/ | ||
var switchChain = function (signer, statusManager, step, switchChainHook, allowUserInteraction) { return __awaiter(void 0, void 0, void 0, function () { | ||
var switchProcess, updatedSigner, _a, error_1; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: return [4 /*yield*/, signer.getChainId()]; | ||
case 1: | ||
// if we are already on the correct chain we can proceed directly | ||
if ((_b.sent()) === step.action.fromChainId) { | ||
return [2 /*return*/, signer]; | ||
} | ||
// -> set status message | ||
step.execution = statusManager.initExecutionObject(step); | ||
statusManager.updateExecution(step, 'CHAIN_SWITCH_REQUIRED'); | ||
switchProcess = statusManager.findOrCreateProcess('SWITCH_CHAIN', step, 'PENDING'); | ||
if (!allowUserInteraction) { | ||
return [2 /*return*/]; | ||
} | ||
_b.label = 2; | ||
case 2: | ||
_b.trys.push([2, 6, , 7]); | ||
return [4 /*yield*/, switchChainHook(step.action.fromChainId)]; | ||
case 3: | ||
updatedSigner = _b.sent(); | ||
_a = !updatedSigner; | ||
if (_a) return [3 /*break*/, 5]; | ||
return [4 /*yield*/, updatedSigner.getChainId()]; | ||
case 4: | ||
_a = (_b.sent()) !== step.action.fromChainId; | ||
_b.label = 5; | ||
case 5: | ||
if (_a) { | ||
throw new errors_1.ProviderError(errors_1.LifiErrorCode.ChainSwitchError, 'Chain switch required.'); | ||
} | ||
switchProcess = statusManager.updateProcess(step, switchProcess.type, 'DONE'); | ||
statusManager.updateExecution(step, 'PENDING'); | ||
return [2 /*return*/, updatedSigner]; | ||
case 6: | ||
error_1 = _b.sent(); | ||
switchProcess = statusManager.updateProcess(step, switchProcess.type, 'FAILED', { | ||
error: { | ||
message: error_1.message, | ||
code: error_1.code, | ||
}, | ||
}); | ||
statusManager.updateExecution(step, 'FAILED'); | ||
throw error_1; | ||
case 7: return [2 /*return*/]; | ||
export const switchChain = (signer, statusManager, step, switchChainHook, allowUserInteraction) => __awaiter(void 0, void 0, void 0, function* () { | ||
// if we are already on the correct chain we can proceed directly | ||
if ((yield signer.getChainId()) === step.action.fromChainId) { | ||
return signer; | ||
} | ||
// -> set status message | ||
step.execution = statusManager.initExecutionObject(step); | ||
statusManager.updateExecution(step, 'CHAIN_SWITCH_REQUIRED'); | ||
let switchProcess = statusManager.findOrCreateProcess('SWITCH_CHAIN', step, 'PENDING'); | ||
if (!allowUserInteraction) { | ||
return; | ||
} | ||
try { | ||
const updatedSigner = yield switchChainHook(step.action.fromChainId); | ||
const updatedChainId = yield (updatedSigner === null || updatedSigner === void 0 ? void 0 : updatedSigner.getChainId()); | ||
if (updatedChainId !== step.action.fromChainId) { | ||
throw new ProviderError(LifiErrorCode.ChainSwitchError, 'Chain switch required.'); | ||
} | ||
}); | ||
}); }; | ||
exports.switchChain = switchChain; | ||
switchProcess = statusManager.updateProcess(step, switchProcess.type, 'DONE'); | ||
statusManager.updateExecution(step, 'PENDING'); | ||
return updatedSigner; | ||
} | ||
catch (error) { | ||
switchProcess = statusManager.updateProcess(step, switchProcess.type, 'FAILED', { | ||
error: { | ||
message: error.message, | ||
code: error.code, | ||
}, | ||
}); | ||
statusManager.updateExecution(step, 'FAILED'); | ||
throw error; | ||
} | ||
}); |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -11,110 +10,55 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
import BigNumber from 'bignumber.js'; | ||
import ApiService from '../services/ApiService'; | ||
import { ServerError } from '../utils/errors'; | ||
import { repeatUntilDone } from '../utils/utils'; | ||
const TRANSACTION_HASH_OBSERVERS = {}; | ||
export function waitForReceivingTransaction(txHash, statusManager, processType, step) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const getStatus = () => new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { | ||
let statusResponse; | ||
try { | ||
statusResponse = yield ApiService.getStatus({ | ||
bridge: step.tool, | ||
fromChain: step.action.fromChainId, | ||
toChain: step.action.toChainId, | ||
txHash, | ||
}); | ||
} | ||
catch (e) { | ||
console.debug('Fetching status from backend failed.', e); | ||
return resolve(undefined); | ||
} | ||
switch (statusResponse.status) { | ||
case 'DONE': | ||
return resolve(statusResponse); | ||
case 'PENDING': | ||
statusManager === null || statusManager === void 0 ? void 0 : statusManager.updateProcess(step, processType, 'PENDING', { | ||
substatus: statusResponse.substatus, | ||
substatusMessage: statusResponse.substatusMessage || | ||
getSubstatusMessage(statusResponse.status, statusResponse.substatus), | ||
}); | ||
return resolve(undefined); | ||
case 'NOT_FOUND': | ||
return resolve(undefined); | ||
case 'FAILED': | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
return reject(); | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.updatedStepMeetsSlippageConditions = exports.getSubstatusMessage = exports.getProcessMessage = exports.waitForReceivingTransaction = void 0; | ||
var bignumber_js_1 = __importDefault(require("bignumber.js")); | ||
var ApiService_1 = __importDefault(require("../services/ApiService")); | ||
var errors_1 = require("../utils/errors"); | ||
var utils_1 = require("../utils/utils"); | ||
var TRANSACTION_HASH_OBSERVERS = {}; | ||
function waitForReceivingTransaction(txHash, statusManager, processType, step) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var getStatus, status; | ||
var _this = this; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
getStatus = function () { | ||
return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { | ||
var statusResponse, e_1; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
_a.trys.push([0, 2, , 3]); | ||
return [4 /*yield*/, ApiService_1.default.getStatus({ | ||
bridge: step.tool, | ||
fromChain: step.action.fromChainId, | ||
toChain: step.action.toChainId, | ||
txHash: txHash, | ||
})]; | ||
case 1: | ||
statusResponse = _a.sent(); | ||
return [3 /*break*/, 3]; | ||
case 2: | ||
e_1 = _a.sent(); | ||
console.debug('Fetching status from backend failed.', e_1); | ||
return [2 /*return*/, resolve(undefined)]; | ||
case 3: | ||
switch (statusResponse.status) { | ||
case 'DONE': | ||
return [2 /*return*/, resolve(statusResponse)]; | ||
case 'PENDING': | ||
statusManager === null || statusManager === void 0 ? void 0 : statusManager.updateProcess(step, processType, 'PENDING', { | ||
substatus: statusResponse.substatus, | ||
substatusMessage: statusResponse.substatusMessage || | ||
getSubstatusMessage(statusResponse.status, statusResponse.substatus), | ||
}); | ||
return [2 /*return*/, resolve(undefined)]; | ||
case 'NOT_FOUND': | ||
return [2 /*return*/, resolve(undefined)]; | ||
case 'FAILED': | ||
default: | ||
return [2 /*return*/, reject()]; | ||
} | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
}; | ||
if (!(txHash in TRANSACTION_HASH_OBSERVERS)) return [3 /*break*/, 2]; | ||
return [4 /*yield*/, TRANSACTION_HASH_OBSERVERS[txHash]]; | ||
case 1: | ||
status = _a.sent(); | ||
return [3 /*break*/, 4]; | ||
case 2: | ||
TRANSACTION_HASH_OBSERVERS[txHash] = (0, utils_1.repeatUntilDone)(getStatus, 5000); | ||
return [4 /*yield*/, TRANSACTION_HASH_OBSERVERS[txHash]]; | ||
case 3: | ||
status = _a.sent(); | ||
_a.label = 4; | ||
case 4: | ||
if (!status.receiving) { | ||
throw new errors_1.ServerError("Status doesn't contain receiving information."); | ||
} | ||
return [2 /*return*/, status]; | ||
} | ||
}); | ||
})); | ||
let status; | ||
if (txHash in TRANSACTION_HASH_OBSERVERS) { | ||
status = yield TRANSACTION_HASH_OBSERVERS[txHash]; | ||
} | ||
else { | ||
TRANSACTION_HASH_OBSERVERS[txHash] = repeatUntilDone(getStatus, 5000); | ||
status = yield TRANSACTION_HASH_OBSERVERS[txHash]; | ||
} | ||
if (!status.receiving) { | ||
throw new ServerError("Status doesn't contain receiving information."); | ||
} | ||
return status; | ||
}); | ||
} | ||
exports.waitForReceivingTransaction = waitForReceivingTransaction; | ||
var processMessages = { | ||
const processMessages = { | ||
TOKEN_ALLOWANCE: { | ||
@@ -147,3 +91,3 @@ STARTED: 'Setting token allowance.', | ||
}; | ||
var substatusMessages = { | ||
const substatusMessages = { | ||
PENDING: { | ||
@@ -166,24 +110,21 @@ BRIDGE_NOT_AVAILABLE: 'Bridge communication is temporarily unavailable.', | ||
}; | ||
function getProcessMessage(type, status) { | ||
var processMessage = processMessages[type][status]; | ||
export function getProcessMessage(type, status) { | ||
const processMessage = processMessages[type][status]; | ||
return processMessage; | ||
} | ||
exports.getProcessMessage = getProcessMessage; | ||
function getSubstatusMessage(status, substatus) { | ||
export function getSubstatusMessage(status, substatus) { | ||
if (!substatus) { | ||
return; | ||
} | ||
var message = substatusMessages[status][substatus]; | ||
const message = substatusMessages[status][substatus]; | ||
return message; | ||
} | ||
exports.getSubstatusMessage = getSubstatusMessage; | ||
function updatedStepMeetsSlippageConditions(oldStep, newStep) { | ||
var setSlippage = new bignumber_js_1.default(oldStep.action.slippage); | ||
var oldEstimatedToAmount = new bignumber_js_1.default(oldStep.estimate.toAmountMin); | ||
var newEstimatedToAmount = new bignumber_js_1.default(newStep.estimate.toAmountMin); | ||
var amountDifference = oldEstimatedToAmount.minus(newEstimatedToAmount); | ||
var actualSlippage = amountDifference.dividedBy(oldEstimatedToAmount); | ||
export function updatedStepMeetsSlippageConditions(oldStep, newStep) { | ||
const setSlippage = new BigNumber(oldStep.action.slippage); | ||
const oldEstimatedToAmount = new BigNumber(oldStep.estimate.toAmountMin); | ||
const newEstimatedToAmount = new BigNumber(newStep.estimate.toAmountMin); | ||
const amountDifference = oldEstimatedToAmount.minus(newEstimatedToAmount); | ||
const actualSlippage = amountDifference.dividedBy(oldEstimatedToAmount); | ||
return (newEstimatedToAmount.gte(oldEstimatedToAmount) && | ||
actualSlippage.lte(setSlippage)); | ||
} | ||
exports.updatedStepMeetsSlippageConditions = updatedStepMeetsSlippageConditions; |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -11,43 +10,12 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
const ethereumRequest = (method, params) => __awaiter(void 0, void 0, void 0, function* () { | ||
// If ethereum.request() exists, the provider is probably EIP-1193 compliant. | ||
if (!ethereum || !ethereum.request) { | ||
throw new Error('Provider not available.'); | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.isSameToken = exports.getRandomNumber = exports.getEthereumPublicKeyHook = exports.getEthereumDecryptionHook = void 0; | ||
var ethereumRequest = function (method, params) { return __awaiter(void 0, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
// If ethereum.request() exists, the provider is probably EIP-1193 compliant. | ||
if (!ethereum || !ethereum.request) { | ||
throw new Error('Provider not available.'); | ||
} | ||
return [2 /*return*/, ethereum.request({ | ||
method: method, | ||
params: params, | ||
})]; | ||
return ethereum.request({ | ||
method, | ||
params, | ||
}); | ||
}); }; | ||
}); | ||
/** | ||
@@ -58,8 +26,7 @@ * Predefined hook that decrypts calldata using EIP-1193 compliant wallet functions. | ||
*/ | ||
var getEthereumDecryptionHook = function (walletAddress) { | ||
return function (encryptedData) { | ||
export const getEthereumDecryptionHook = (walletAddress) => { | ||
return (encryptedData) => { | ||
return ethereumRequest('eth_decrypt', [encryptedData, walletAddress]); | ||
}; | ||
}; | ||
exports.getEthereumDecryptionHook = getEthereumDecryptionHook; | ||
/** | ||
@@ -70,19 +37,14 @@ * Predefined hook that get the public encryption key of a user using EIP-1193 compliant wallet functions. | ||
*/ | ||
var getEthereumPublicKeyHook = function (walletAddress) { | ||
return function () { | ||
export const getEthereumPublicKeyHook = (walletAddress) => { | ||
return () => { | ||
return ethereumRequest('eth_getEncryptionPublicKey', [walletAddress]); | ||
}; | ||
}; | ||
exports.getEthereumPublicKeyHook = getEthereumPublicKeyHook; | ||
/** | ||
* Returns a random number between min (inclusive) and max (inclusive) | ||
*/ | ||
var getRandomNumber = function (min, max) { | ||
export const getRandomNumber = (min, max) => { | ||
return Math.floor(Math.random() * (max - min + 1) + min); | ||
}; | ||
exports.getRandomNumber = getRandomNumber; | ||
var isSameToken = function (tokenA, tokenB) { | ||
return tokenA.chainId === tokenB.chainId && | ||
tokenA.address.toLowerCase() === tokenB.address.toLowerCase(); | ||
}; | ||
exports.isSameToken = isSameToken; | ||
export const isSameToken = (tokenA, tokenB) => tokenA.chainId === tokenB.chainId && | ||
tokenA.address.toLowerCase() === tokenB.address.toLowerCase(); |
@@ -1,27 +0,8 @@ | ||
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
o[k2] = m[k]; | ||
})); | ||
var __exportStar = (this && this.__exportStar) || function(m, exports) { | ||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
// expose types and helpers | ||
var Lifi_1 = __importDefault(require("./Lifi")); | ||
__exportStar(require("./execution"), exports); | ||
__exportStar(require("./helpers"), exports); | ||
__exportStar(require("./types"), exports); | ||
__exportStar(require("./utils/errors"), exports); | ||
import LIFI from './Lifi'; | ||
export * from './execution'; | ||
export * from './helpers'; | ||
export * from './types'; | ||
export * from './utils/errors'; | ||
// expose sdk | ||
exports.default = Lifi_1.default; | ||
export default LIFI; |
464
dist/Lifi.js
@@ -1,13 +0,1 @@ | ||
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -22,48 +10,16 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var allowance_1 = require("./allowance"); | ||
var balances_1 = __importDefault(require("./balances")); | ||
var connectors_1 = require("./connectors"); | ||
var StatusManager_1 = require("./execution/StatusManager"); | ||
var StepExecutor_1 = require("./execution/StepExecutor"); | ||
var ApiService_1 = __importDefault(require("./services/ApiService")); | ||
var ChainsService_1 = __importDefault(require("./services/ChainsService")); | ||
var ConfigService_1 = __importDefault(require("./services/ConfigService")); | ||
var typeguards_1 = require("./typeguards"); | ||
var errors_1 = require("./utils/errors"); | ||
var preRestart_1 = require("./utils/preRestart"); | ||
var utils_1 = require("./utils/utils"); | ||
var LIFI = /** @class */ (function () { | ||
function LIFI(configUpdate) { | ||
var _this = this; | ||
import { approveToken, bulkGetTokenApproval, getTokenApproval, revokeTokenApproval, } from './allowance'; | ||
import balances from './balances'; | ||
import { getRpcProvider } from './connectors'; | ||
import { StatusManager } from './execution/StatusManager'; | ||
import { StepExecutor } from './execution/StepExecutor'; | ||
import ApiService from './services/ApiService'; | ||
import ChainsService from './services/ChainsService'; | ||
import ConfigService from './services/ConfigService'; | ||
import { isToken } from './typeguards'; | ||
import { ValidationError } from './utils/errors'; | ||
import { handlePreRestart } from './utils/preRestart'; | ||
import { deepClone } from './utils/utils'; | ||
export default class LIFI { | ||
constructor(configUpdate) { | ||
this.activeRouteDictionary = {}; | ||
@@ -74,4 +30,4 @@ /** | ||
*/ | ||
this.getConfig = function () { | ||
return _this.configService.getConfig(); | ||
this.getConfig = () => { | ||
return this.configService.getConfig(); | ||
}; | ||
@@ -82,4 +38,4 @@ /** | ||
*/ | ||
this.getConfigAsync = function () { | ||
return _this.configService.getConfigAsync(); | ||
this.getConfigAsync = () => { | ||
return this.configService.getConfigAsync(); | ||
}; | ||
@@ -92,5 +48,4 @@ /** | ||
*/ | ||
this.getRpcProvider = function (chainId, archive) { | ||
if (archive === void 0) { archive = false; } | ||
return (0, connectors_1.getRpcProvider)(chainId, archive); | ||
this.getRpcProvider = (chainId, archive = false) => { | ||
return getRpcProvider(chainId, archive); | ||
}; | ||
@@ -102,4 +57,4 @@ /** | ||
*/ | ||
this.setConfig = function (configUpdate) { | ||
return _this.configService.updateConfig(configUpdate); | ||
this.setConfig = (configUpdate) => { | ||
return this.configService.updateConfig(configUpdate); | ||
}; | ||
@@ -112,7 +67,5 @@ /** | ||
*/ | ||
this.getPossibilities = function (request, options) { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, ApiService_1.default.getPossibilities(request, options)]; | ||
}); | ||
}); }; | ||
this.getPossibilities = (request, options) => __awaiter(this, void 0, void 0, function* () { | ||
return ApiService.getPossibilities(request, options); | ||
}); | ||
/** | ||
@@ -124,7 +77,5 @@ * Fetch information about a Token | ||
*/ | ||
this.getToken = function (chain, token, options) { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, ApiService_1.default.getToken(chain, token, options)]; | ||
}); | ||
}); }; | ||
this.getToken = (chain, token, options) => __awaiter(this, void 0, void 0, function* () { | ||
return ApiService.getToken(chain, token, options); | ||
}); | ||
/** | ||
@@ -135,7 +86,5 @@ * Get a quote for a token transfer | ||
*/ | ||
this.getQuote = function (request, options) { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, ApiService_1.default.getQuote(request, options)]; | ||
}); | ||
}); }; | ||
this.getQuote = (request, options) => __awaiter(this, void 0, void 0, function* () { | ||
return ApiService.getQuote(request, options); | ||
}); | ||
/** | ||
@@ -146,7 +95,5 @@ * Get a quote for a destination contract call | ||
*/ | ||
this.getContractCallQuote = function (request, options) { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, ApiService_1.default.getContractCallQuote(request, options)]; | ||
}); | ||
}); }; | ||
this.getContractCallQuote = (request, options) => __awaiter(this, void 0, void 0, function* () { | ||
return ApiService.getContractCallQuote(request, options); | ||
}); | ||
/** | ||
@@ -157,7 +104,5 @@ * Check the status of a transfer. For cross chain transfers, the "bridge" parameter is required. | ||
*/ | ||
this.getStatus = function (request, options) { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, ApiService_1.default.getStatus(request, options)]; | ||
}); | ||
}); }; | ||
this.getStatus = (request, options) => __awaiter(this, void 0, void 0, function* () { | ||
return ApiService.getStatus(request, options); | ||
}); | ||
/** | ||
@@ -168,7 +113,5 @@ * Get the available tools to bridge and swap tokens. | ||
*/ | ||
this.getTools = function (request, options) { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, ApiService_1.default.getTools(request || {}, options)]; | ||
}); | ||
}); }; | ||
this.getTools = (request, options) => __awaiter(this, void 0, void 0, function* () { | ||
return ApiService.getTools(request || {}, options); | ||
}); | ||
/** | ||
@@ -179,7 +122,5 @@ * Get all known tokens. | ||
*/ | ||
this.getTokens = function (request, options) { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, ApiService_1.default.getTokens(request || {}, options)]; | ||
}); | ||
}); }; | ||
this.getTokens = (request, options) => __awaiter(this, void 0, void 0, function* () { | ||
return ApiService.getTokens(request || {}, options); | ||
}); | ||
/** | ||
@@ -190,7 +131,5 @@ * Get all available chains | ||
*/ | ||
this.getChains = function () { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, this.chainsService.getChains()]; | ||
}); | ||
}); }; | ||
this.getChains = () => __awaiter(this, void 0, void 0, function* () { | ||
return this.chainsService.getChains(); | ||
}); | ||
/** | ||
@@ -202,7 +141,5 @@ * Get a set of routes for a request that describes a transfer of tokens. | ||
*/ | ||
this.getRoutes = function (request, options) { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, ApiService_1.default.getRoutes(request, options)]; | ||
}); | ||
}); }; | ||
this.getRoutes = (request, options) => __awaiter(this, void 0, void 0, function* () { | ||
return ApiService.getRoutes(request, options); | ||
}); | ||
/** | ||
@@ -214,7 +151,5 @@ * Get the transaction data for a single step of a route | ||
*/ | ||
this.getStepTransaction = function (step, options) { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, ApiService_1.default.getStepTransaction(step, options)]; | ||
}); | ||
}); }; | ||
this.getStepTransaction = (step, options) => __awaiter(this, void 0, void 0, function* () { | ||
return ApiService.getStepTransaction(step, options); | ||
}); | ||
/** | ||
@@ -225,11 +160,10 @@ * Stops the execution of an active route. | ||
*/ | ||
this.stopExecution = function (route) { | ||
if (!_this.activeRouteDictionary[route.id]) { | ||
this.stopExecution = (route) => { | ||
if (!this.activeRouteDictionary[route.id]) { | ||
return route; | ||
} | ||
for (var _i = 0, _a = _this.activeRouteDictionary[route.id].executors; _i < _a.length; _i++) { | ||
var executor = _a[_i]; | ||
for (const executor of this.activeRouteDictionary[route.id].executors) { | ||
executor.stopStepExecution({ allowUpdates: false }); | ||
} | ||
delete _this.activeRouteDictionary[route.id]; | ||
delete this.activeRouteDictionary[route.id]; | ||
return route; | ||
@@ -241,8 +175,7 @@ }; | ||
*/ | ||
this.moveExecutionToBackground = function (route) { | ||
if (!_this.activeRouteDictionary[route.id]) { | ||
this.moveExecutionToBackground = (route) => { | ||
if (!this.activeRouteDictionary[route.id]) { | ||
return; | ||
} | ||
for (var _i = 0, _a = _this.activeRouteDictionary[route.id].executors; _i < _a.length; _i++) { | ||
var executor = _a[_i]; | ||
for (const executor of this.activeRouteDictionary[route.id].executors) { | ||
executor.stopStepExecution({ allowUpdates: true }); | ||
@@ -259,15 +192,11 @@ } | ||
*/ | ||
this.executeRoute = function (signer, route, settings) { return __awaiter(_this, void 0, void 0, function () { | ||
var clonedRoute; | ||
return __generator(this, function (_a) { | ||
clonedRoute = (0, utils_1.deepClone)(route) // deep clone to prevent side effects | ||
; | ||
// check if route is already running | ||
if (this.activeRouteDictionary[clonedRoute.id]) { | ||
// TODO: maybe inform user why nothing happens? | ||
return [2 /*return*/, clonedRoute]; | ||
} | ||
return [2 /*return*/, this.executeSteps(signer, clonedRoute, settings)]; | ||
}); | ||
}); }; | ||
this.executeRoute = (signer, route, settings) => __awaiter(this, void 0, void 0, function* () { | ||
const clonedRoute = deepClone(route); // deep clone to prevent side effects | ||
// check if route is already running | ||
if (this.activeRouteDictionary[clonedRoute.id]) { | ||
// TODO: maybe inform user why nothing happens? | ||
return clonedRoute; | ||
} | ||
return this.executeSteps(signer, clonedRoute, settings); | ||
}); | ||
/** | ||
@@ -281,82 +210,60 @@ * Resume the execution of a route that has been stopped or had an error while executing. | ||
*/ | ||
this.resumeRoute = function (signer, route, settings) { return __awaiter(_this, void 0, void 0, function () { | ||
var clonedRoute, activeRoute, executionHalted; | ||
return __generator(this, function (_a) { | ||
clonedRoute = (0, utils_1.deepClone)(route) // deep clone to prevent side effects | ||
; | ||
activeRoute = this.activeRouteDictionary[clonedRoute.id]; | ||
if (activeRoute) { | ||
executionHalted = activeRoute.executors.some(function (executor) { return executor.executionStopped; }); | ||
if (!executionHalted) { | ||
return [2 /*return*/, clonedRoute]; | ||
} | ||
this.resumeRoute = (signer, route, settings) => __awaiter(this, void 0, void 0, function* () { | ||
const clonedRoute = deepClone(route); // deep clone to prevent side effects | ||
const activeRoute = this.activeRouteDictionary[clonedRoute.id]; | ||
if (activeRoute) { | ||
const executionHalted = activeRoute.executors.some((executor) => executor.executionStopped); | ||
if (!executionHalted) { | ||
return clonedRoute; | ||
} | ||
(0, preRestart_1.handlePreRestart)(clonedRoute); | ||
return [2 /*return*/, this.executeSteps(signer, clonedRoute, settings)]; | ||
}); | ||
}); }; | ||
this.executeSteps = function (signer, route, settings) { return __awaiter(_this, void 0, void 0, function () { | ||
var config, execData, statusManager, index, step, previousStep, stepExecutor, e_1; | ||
var _this = this; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
config = this.configService.getConfig(); | ||
execData = { | ||
route: route, | ||
executors: [], | ||
settings: __assign(__assign({}, config.defaultExecutionSettings), settings), | ||
}; | ||
this.activeRouteDictionary[route.id] = execData; | ||
statusManager = new StatusManager_1.StatusManager(route, this.activeRouteDictionary[route.id].settings, function (route) { return (_this.activeRouteDictionary[route.id].route = route); }); | ||
index = 0; | ||
_a.label = 1; | ||
case 1: | ||
if (!(index < route.steps.length)) return [3 /*break*/, 7]; | ||
//check if execution has stopped in meantime | ||
if (!this.activeRouteDictionary[route.id]) { | ||
return [3 /*break*/, 7]; | ||
} | ||
step = route.steps[index]; | ||
previousStep = index !== 0 ? route.steps[index - 1] : undefined; | ||
// check if step already done | ||
if (step.execution && step.execution.status === 'DONE') { | ||
return [3 /*break*/, 6]; | ||
} | ||
// update amount using output of previous execution. In the future this should be handled by calling `updateRoute` | ||
if (previousStep && | ||
previousStep.execution && | ||
previousStep.execution.toAmount) { | ||
step.action.fromAmount = previousStep.execution.toAmount; | ||
} | ||
stepExecutor = void 0; | ||
_a.label = 2; | ||
case 2: | ||
_a.trys.push([2, 4, , 5]); | ||
stepExecutor = new StepExecutor_1.StepExecutor(statusManager, this.activeRouteDictionary[route.id].settings); | ||
this.activeRouteDictionary[route.id].executors.push(stepExecutor); | ||
return [4 /*yield*/, stepExecutor.executeStep(signer, step)]; | ||
case 3: | ||
_a.sent(); | ||
return [3 /*break*/, 5]; | ||
case 4: | ||
e_1 = _a.sent(); | ||
this.stopExecution(route); | ||
throw e_1; | ||
case 5: | ||
// execution stopped during the current step, we don't want to continue to the next step so we return already | ||
if (stepExecutor.executionStopped) { | ||
return [2 /*return*/, route]; | ||
} | ||
_a.label = 6; | ||
case 6: | ||
index++; | ||
return [3 /*break*/, 1]; | ||
case 7: | ||
//clean up after execution | ||
delete this.activeRouteDictionary[route.id]; | ||
return [2 /*return*/, route]; | ||
} | ||
handlePreRestart(clonedRoute); | ||
return this.executeSteps(signer, clonedRoute, settings); | ||
}); | ||
this.executeSteps = (signer, route, settings) => __awaiter(this, void 0, void 0, function* () { | ||
const config = this.configService.getConfig(); | ||
const execData = { | ||
route, | ||
executors: [], | ||
settings: Object.assign(Object.assign({}, config.defaultExecutionSettings), settings), | ||
}; | ||
this.activeRouteDictionary[route.id] = execData; | ||
const statusManager = new StatusManager(route, this.activeRouteDictionary[route.id].settings, (route) => (this.activeRouteDictionary[route.id].route = route)); | ||
// loop over steps and execute them | ||
for (let index = 0; index < route.steps.length; index++) { | ||
//check if execution has stopped in meantime | ||
if (!this.activeRouteDictionary[route.id]) { | ||
break; | ||
} | ||
}); | ||
}); }; | ||
const step = route.steps[index]; | ||
const previousStep = index !== 0 ? route.steps[index - 1] : undefined; | ||
// check if step already done | ||
if (step.execution && step.execution.status === 'DONE') { | ||
continue; | ||
} | ||
// update amount using output of previous execution. In the future this should be handled by calling `updateRoute` | ||
if (previousStep && | ||
previousStep.execution && | ||
previousStep.execution.toAmount) { | ||
step.action.fromAmount = previousStep.execution.toAmount; | ||
} | ||
let stepExecutor; | ||
try { | ||
stepExecutor = new StepExecutor(statusManager, this.activeRouteDictionary[route.id].settings); | ||
this.activeRouteDictionary[route.id].executors.push(stepExecutor); | ||
yield stepExecutor.executeStep(signer, step); | ||
} | ||
catch (e) { | ||
this.stopExecution(route); | ||
throw e; | ||
} | ||
// execution stopped during the current step, we don't want to continue to the next step so we return already | ||
if (stepExecutor.executionStopped) { | ||
return route; | ||
} | ||
} | ||
//clean up after execution | ||
delete this.activeRouteDictionary[route.id]; | ||
return route; | ||
}); | ||
/** | ||
@@ -368,8 +275,8 @@ * Update the ExecutionSettings for an active route. | ||
*/ | ||
this.updateExecutionSettings = function (settings, route) { | ||
if (!_this.activeRouteDictionary[route.id]) { | ||
throw new errors_1.ValidationError("Can't set ExecutionSettings for the inactive route."); | ||
this.updateExecutionSettings = (settings, route) => { | ||
if (!this.activeRouteDictionary[route.id]) { | ||
throw new ValidationError("Can't set ExecutionSettings for the inactive route."); | ||
} | ||
var config = _this.configService.getConfig(); | ||
_this.activeRouteDictionary[route.id].settings = __assign(__assign({}, config.defaultExecutionSettings), settings); | ||
const config = this.configService.getConfig(); | ||
this.activeRouteDictionary[route.id].settings = Object.assign(Object.assign({}, config.defaultExecutionSettings), settings); | ||
}; | ||
@@ -380,4 +287,4 @@ /** | ||
*/ | ||
this.getActiveRoutes = function () { | ||
return Object.values(_this.activeRouteDictionary).map(function (dict) { return dict.route; }); | ||
this.getActiveRoutes = () => { | ||
return Object.values(this.activeRouteDictionary).map((dict) => dict.route); | ||
}; | ||
@@ -389,4 +296,5 @@ /** | ||
*/ | ||
this.getActiveRoute = function (route) { | ||
return _this.activeRouteDictionary[route.id].route; | ||
this.getActiveRoute = (route) => { | ||
var _a; | ||
return (_a = this.activeRouteDictionary[route.id]) === null || _a === void 0 ? void 0 : _a.route; | ||
}; | ||
@@ -400,13 +308,11 @@ /** | ||
*/ | ||
this.getTokenBalance = function (walletAddress, token) { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
if (!walletAddress) { | ||
throw new errors_1.ValidationError('Missing walletAddress.'); | ||
} | ||
if (!(0, typeguards_1.isToken)(token)) { | ||
throw new errors_1.ValidationError("Invalid token passed: address \"".concat(token.address, "\" on chainId \"").concat(token.chainId, "\"")); | ||
} | ||
return [2 /*return*/, balances_1.default.getTokenBalance(walletAddress, token)]; | ||
}); | ||
}); }; | ||
this.getTokenBalance = (walletAddress, token) => __awaiter(this, void 0, void 0, function* () { | ||
if (!walletAddress) { | ||
throw new ValidationError('Missing walletAddress.'); | ||
} | ||
if (!isToken(token)) { | ||
throw new ValidationError(`Invalid token passed: address "${token.address}" on chainId "${token.chainId}"`); | ||
} | ||
return balances.getTokenBalance(walletAddress, token); | ||
}); | ||
/** | ||
@@ -419,15 +325,12 @@ * Returns the balances for a list tokens a wallet holds across all aggregated chains. | ||
*/ | ||
this.getTokenBalances = function (walletAddress, tokens) { return __awaiter(_this, void 0, void 0, function () { | ||
var invalidTokens; | ||
return __generator(this, function (_a) { | ||
if (!walletAddress) { | ||
throw new errors_1.ValidationError('Missing walletAddress.'); | ||
} | ||
invalidTokens = tokens.filter(function (token) { return !(0, typeguards_1.isToken)(token); }); | ||
if (invalidTokens.length) { | ||
throw new errors_1.ValidationError("Invalid token passed: address \"".concat(invalidTokens[0].address, "\" on chainId \"").concat(invalidTokens[0].chainId, "\"")); | ||
} | ||
return [2 /*return*/, balances_1.default.getTokenBalances(walletAddress, tokens)]; | ||
}); | ||
}); }; | ||
this.getTokenBalances = (walletAddress, tokens) => __awaiter(this, void 0, void 0, function* () { | ||
if (!walletAddress) { | ||
throw new ValidationError('Missing walletAddress.'); | ||
} | ||
const invalidTokens = tokens.filter((token) => !isToken(token)); | ||
if (invalidTokens.length) { | ||
throw new ValidationError(`Invalid token passed: address "${invalidTokens[0].address}" on chainId "${invalidTokens[0].chainId}"`); | ||
} | ||
return balances.getTokenBalances(walletAddress, tokens); | ||
}); | ||
/** | ||
@@ -440,16 +343,13 @@ * This method queries the balances of tokens for a specific list of chains for a given wallet. | ||
*/ | ||
this.getTokenBalancesForChains = function (walletAddress, tokensByChain) { return __awaiter(_this, void 0, void 0, function () { | ||
var tokenList, invalidTokens; | ||
return __generator(this, function (_a) { | ||
if (!walletAddress) { | ||
throw new errors_1.ValidationError('Missing walletAddress.'); | ||
} | ||
tokenList = Object.values(tokensByChain).flat(); | ||
invalidTokens = tokenList.filter(function (token) { return !(0, typeguards_1.isToken)(token); }); | ||
if (invalidTokens.length) { | ||
throw new errors_1.ValidationError("Invalid token passed: address \"".concat(invalidTokens[0].address, "\" on chainId \"").concat(invalidTokens[0].chainId, "\"")); | ||
} | ||
return [2 /*return*/, balances_1.default.getTokenBalancesForChains(walletAddress, tokensByChain)]; | ||
}); | ||
}); }; | ||
this.getTokenBalancesForChains = (walletAddress, tokensByChain) => __awaiter(this, void 0, void 0, function* () { | ||
if (!walletAddress) { | ||
throw new ValidationError('Missing walletAddress.'); | ||
} | ||
const tokenList = Object.values(tokensByChain).flat(); | ||
const invalidTokens = tokenList.filter((token) => !isToken(token)); | ||
if (invalidTokens.length) { | ||
throw new ValidationError(`Invalid token passed: address "${invalidTokens[0].address}" on chainId "${invalidTokens[0].chainId}"`); | ||
} | ||
return balances.getTokenBalancesForChains(walletAddress, tokensByChain); | ||
}); | ||
/** | ||
@@ -461,7 +361,5 @@ * Get the current approval for a certain token. | ||
*/ | ||
this.getTokenApproval = function (signer, token, approvalAddress) { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, (0, allowance_1.getTokenApproval)(signer, token, approvalAddress)]; | ||
}); | ||
}); }; | ||
this.getTokenApproval = (signer, token, approvalAddress) => __awaiter(this, void 0, void 0, function* () { | ||
return getTokenApproval(signer, token, approvalAddress); | ||
}); | ||
/** | ||
@@ -472,7 +370,5 @@ * Get the current approval for a list of token / approval address pairs. | ||
*/ | ||
this.bulkGetTokenApproval = function (signer, tokenData) { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, (0, allowance_1.bulkGetTokenApproval)(signer, tokenData)]; | ||
}); | ||
}); }; | ||
this.bulkGetTokenApproval = (signer, tokenData) => __awaiter(this, void 0, void 0, function* () { | ||
return bulkGetTokenApproval(signer, tokenData); | ||
}); | ||
/** | ||
@@ -482,4 +378,4 @@ * Set approval for a certain token and amount. | ||
*/ | ||
this.approveToken = function (request) { | ||
return (0, allowance_1.approveToken)(request); | ||
this.approveToken = (request) => { | ||
return approveToken(request); | ||
}; | ||
@@ -490,16 +386,14 @@ /** | ||
*/ | ||
this.revokeTokenApproval = function (request) { | ||
return (0, allowance_1.revokeTokenApproval)(request); | ||
this.revokeTokenApproval = (request) => { | ||
return revokeTokenApproval(request); | ||
}; | ||
this.configService = ConfigService_1.default.getInstance(); | ||
this.configService = ConfigService.getInstance(); | ||
if (configUpdate) { | ||
this.configService.updateConfig(configUpdate); // update API urls before we request chains | ||
} | ||
this.chainsService = ChainsService_1.default.getInstance(); | ||
this.chainsService.getChains().then(function (chains) { | ||
_this.configService.updateChains(chains); | ||
this.chainsService = ChainsService.getInstance(); | ||
this.chainsService.getChains().then((chains) => { | ||
this.configService.updateChains(chains); | ||
}); | ||
} | ||
return LIFI; | ||
}()); | ||
exports.default = LIFI; | ||
} |
@@ -1,13 +0,1 @@ | ||
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -22,384 +10,259 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
import axios from 'axios'; | ||
import { isRoutesRequest, isStep } from '../typeguards'; | ||
import { ValidationError } from '../utils/errors'; | ||
import { parseBackendError } from '../utils/parseError'; | ||
import ConfigService from './ConfigService'; | ||
const getPossibilities = (request, options) => __awaiter(void 0, void 0, void 0, function* () { | ||
if (!request) { | ||
request = {}; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var axios_1 = __importDefault(require("axios")); | ||
var typeguards_1 = require("../typeguards"); | ||
var errors_1 = require("../utils/errors"); | ||
var parseError_1 = require("../utils/parseError"); | ||
var ConfigService_1 = __importDefault(require("./ConfigService")); | ||
var getPossibilities = function (request, options) { return __awaiter(void 0, void 0, void 0, function () { | ||
var configService, config, result, e_1; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!request) { | ||
request = {}; | ||
} | ||
configService = ConfigService_1.default.getInstance(); | ||
config = configService.getConfig(); | ||
// apply defaults | ||
request.bridges = request.bridges || config.defaultRouteOptions.bridges; | ||
request.exchanges = request.exchanges || config.defaultRouteOptions.exchanges; | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, axios_1.default.post(config.apiUrl + 'advanced/possibilities', request, { | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
})]; | ||
case 2: | ||
result = _a.sent(); | ||
return [2 /*return*/, result.data]; | ||
case 3: | ||
e_1 = _a.sent(); | ||
throw (0, parseError_1.parseBackendError)(e_1); | ||
case 4: return [2 /*return*/]; | ||
} | ||
}); | ||
}); }; | ||
var getToken = function (chain, token, options) { return __awaiter(void 0, void 0, void 0, function () { | ||
var configService, config, result, e_2; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!chain) { | ||
throw new errors_1.ValidationError('Required parameter "chain" is missing.'); | ||
} | ||
if (!token) { | ||
throw new errors_1.ValidationError('Required parameter "token" is missing.'); | ||
} | ||
configService = ConfigService_1.default.getInstance(); | ||
config = configService.getConfig(); | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, axios_1.default.get(config.apiUrl + 'token', { | ||
params: { | ||
chain: chain, | ||
token: token, | ||
}, | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
})]; | ||
case 2: | ||
result = _a.sent(); | ||
return [2 /*return*/, result.data]; | ||
case 3: | ||
e_2 = _a.sent(); | ||
throw (0, parseError_1.parseBackendError)(e_2); | ||
case 4: return [2 /*return*/]; | ||
} | ||
}); | ||
}); }; | ||
var getQuote = function (request, options) { return __awaiter(void 0, void 0, void 0, function () { | ||
var configService, config, requiredParameters, result, e_3; | ||
const configService = ConfigService.getInstance(); | ||
const config = configService.getConfig(); | ||
// apply defaults | ||
request.bridges = request.bridges || config.defaultRouteOptions.bridges; | ||
request.exchanges = request.exchanges || config.defaultRouteOptions.exchanges; | ||
// send request | ||
try { | ||
const result = yield axios.post(config.apiUrl + 'advanced/possibilities', request, { | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
}); | ||
return result.data; | ||
} | ||
catch (e) { | ||
throw parseBackendError(e); | ||
} | ||
}); | ||
const getToken = (chain, token, options) => __awaiter(void 0, void 0, void 0, function* () { | ||
if (!chain) { | ||
throw new ValidationError('Required parameter "chain" is missing.'); | ||
} | ||
if (!token) { | ||
throw new ValidationError('Required parameter "token" is missing.'); | ||
} | ||
const configService = ConfigService.getInstance(); | ||
const config = configService.getConfig(); | ||
try { | ||
const result = yield axios.get(config.apiUrl + 'token', { | ||
params: { | ||
chain, | ||
token, | ||
}, | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
}); | ||
return result.data; | ||
} | ||
catch (e) { | ||
throw parseBackendError(e); | ||
} | ||
}); | ||
const getQuote = (request, options) => __awaiter(void 0, void 0, void 0, function* () { | ||
var _a, _b, _c, _d, _e, _f; | ||
return __generator(this, function (_g) { | ||
switch (_g.label) { | ||
case 0: | ||
configService = ConfigService_1.default.getInstance(); | ||
config = configService.getConfig(); | ||
requiredParameters = [ | ||
'fromChain', | ||
'fromToken', | ||
'fromAddress', | ||
'fromAmount', | ||
'toChain', | ||
'toToken', | ||
]; | ||
requiredParameters.forEach(function (requiredParameter) { | ||
if (!request[requiredParameter]) { | ||
throw new errors_1.ValidationError("Required parameter \"".concat(requiredParameter, "\" is missing.")); | ||
} | ||
}); | ||
// apply defaults | ||
request.order = request.order || config.defaultRouteOptions.order; | ||
request.slippage = request.slippage || config.defaultRouteOptions.slippage; | ||
request.integrator = | ||
request.integrator || config.defaultRouteOptions.integrator; | ||
request.referrer = request.referrer || config.defaultRouteOptions.referrer; | ||
request.fee = request.fee || config.defaultRouteOptions.fee; | ||
request.allowBridges = | ||
request.allowBridges || ((_a = config.defaultRouteOptions.bridges) === null || _a === void 0 ? void 0 : _a.allow); | ||
request.denyBridges = | ||
request.denyBridges || ((_b = config.defaultRouteOptions.bridges) === null || _b === void 0 ? void 0 : _b.deny); | ||
request.preferBridges = | ||
request.preferBridges || ((_c = config.defaultRouteOptions.bridges) === null || _c === void 0 ? void 0 : _c.prefer); | ||
request.allowExchanges = | ||
request.allowExchanges || ((_d = config.defaultRouteOptions.bridges) === null || _d === void 0 ? void 0 : _d.allow); | ||
request.denyExchanges = | ||
request.denyExchanges || ((_e = config.defaultRouteOptions.bridges) === null || _e === void 0 ? void 0 : _e.deny); | ||
request.preferExchanges = | ||
request.preferExchanges || ((_f = config.defaultRouteOptions.bridges) === null || _f === void 0 ? void 0 : _f.prefer); | ||
_g.label = 1; | ||
case 1: | ||
_g.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, axios_1.default.get(config.apiUrl + 'quote', { | ||
params: request, | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
})]; | ||
case 2: | ||
result = _g.sent(); | ||
return [2 /*return*/, result.data]; | ||
case 3: | ||
e_3 = _g.sent(); | ||
throw (0, parseError_1.parseBackendError)(e_3); | ||
case 4: return [2 /*return*/]; | ||
const configService = ConfigService.getInstance(); | ||
const config = configService.getConfig(); | ||
// validation | ||
const requiredParameters = [ | ||
'fromChain', | ||
'fromToken', | ||
'fromAddress', | ||
'fromAmount', | ||
'toChain', | ||
'toToken', | ||
]; | ||
requiredParameters.forEach((requiredParameter) => { | ||
if (!request[requiredParameter]) { | ||
throw new ValidationError(`Required parameter "${requiredParameter}" is missing.`); | ||
} | ||
}); | ||
}); }; | ||
var getContractCallQuote = function (request, options) { return __awaiter(void 0, void 0, void 0, function () { | ||
var configService, config, requiredParameters, result, e_4; | ||
var _a, _b, _c, _d, _e, _f; | ||
return __generator(this, function (_g) { | ||
switch (_g.label) { | ||
case 0: | ||
configService = ConfigService_1.default.getInstance(); | ||
config = configService.getConfig(); | ||
requiredParameters = [ | ||
'fromChain', | ||
'fromToken', | ||
'fromAddress', | ||
'toChain', | ||
'toToken', | ||
'toAmount', | ||
'toContractAddress', | ||
'toContractCallData', | ||
'toContractGasLimit', | ||
]; | ||
requiredParameters.forEach(function (requiredParameter) { | ||
if (!request[requiredParameter]) { | ||
throw new errors_1.ValidationError("Required parameter \"".concat(requiredParameter, "\" is missing.")); | ||
} | ||
}); | ||
// apply defaults | ||
// option.order is not used in this endpoint | ||
request.slippage = request.slippage || config.defaultRouteOptions.slippage; | ||
request.integrator = | ||
request.integrator || config.defaultRouteOptions.integrator; | ||
request.referrer = request.referrer || config.defaultRouteOptions.referrer; | ||
request.fee = request.fee || config.defaultRouteOptions.fee; | ||
request.allowBridges = | ||
request.allowBridges || ((_a = config.defaultRouteOptions.bridges) === null || _a === void 0 ? void 0 : _a.allow); | ||
request.denyBridges = | ||
request.denyBridges || ((_b = config.defaultRouteOptions.bridges) === null || _b === void 0 ? void 0 : _b.deny); | ||
request.preferBridges = | ||
request.preferBridges || ((_c = config.defaultRouteOptions.bridges) === null || _c === void 0 ? void 0 : _c.prefer); | ||
request.allowExchanges = | ||
request.allowExchanges || ((_d = config.defaultRouteOptions.bridges) === null || _d === void 0 ? void 0 : _d.allow); | ||
request.denyExchanges = | ||
request.denyExchanges || ((_e = config.defaultRouteOptions.bridges) === null || _e === void 0 ? void 0 : _e.deny); | ||
request.preferExchanges = | ||
request.preferExchanges || ((_f = config.defaultRouteOptions.bridges) === null || _f === void 0 ? void 0 : _f.prefer); | ||
_g.label = 1; | ||
case 1: | ||
_g.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, axios_1.default.post(config.apiUrl + 'quote/contractCall', request, { | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
})]; | ||
case 2: | ||
result = _g.sent(); | ||
return [2 /*return*/, result.data]; | ||
case 3: | ||
e_4 = _g.sent(); | ||
throw (0, parseError_1.parseBackendError)(e_4); | ||
case 4: return [2 /*return*/]; | ||
// apply defaults | ||
request.order = request.order || config.defaultRouteOptions.order; | ||
request.slippage = request.slippage || config.defaultRouteOptions.slippage; | ||
request.integrator = | ||
request.integrator || config.defaultRouteOptions.integrator; | ||
request.referrer = request.referrer || config.defaultRouteOptions.referrer; | ||
request.fee = request.fee || config.defaultRouteOptions.fee; | ||
request.allowBridges = | ||
request.allowBridges || ((_a = config.defaultRouteOptions.bridges) === null || _a === void 0 ? void 0 : _a.allow); | ||
request.denyBridges = | ||
request.denyBridges || ((_b = config.defaultRouteOptions.bridges) === null || _b === void 0 ? void 0 : _b.deny); | ||
request.preferBridges = | ||
request.preferBridges || ((_c = config.defaultRouteOptions.bridges) === null || _c === void 0 ? void 0 : _c.prefer); | ||
request.allowExchanges = | ||
request.allowExchanges || ((_d = config.defaultRouteOptions.bridges) === null || _d === void 0 ? void 0 : _d.allow); | ||
request.denyExchanges = | ||
request.denyExchanges || ((_e = config.defaultRouteOptions.bridges) === null || _e === void 0 ? void 0 : _e.deny); | ||
request.preferExchanges = | ||
request.preferExchanges || ((_f = config.defaultRouteOptions.bridges) === null || _f === void 0 ? void 0 : _f.prefer); | ||
try { | ||
const result = yield axios.get(config.apiUrl + 'quote', { | ||
params: request, | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
}); | ||
return result.data; | ||
} | ||
catch (e) { | ||
throw parseBackendError(e); | ||
} | ||
}); | ||
const getContractCallQuote = (request, options) => __awaiter(void 0, void 0, void 0, function* () { | ||
var _g, _h, _j, _k, _l, _m; | ||
const configService = ConfigService.getInstance(); | ||
const config = configService.getConfig(); | ||
// validation | ||
const requiredParameters = [ | ||
'fromChain', | ||
'fromToken', | ||
'fromAddress', | ||
'toChain', | ||
'toToken', | ||
'toAmount', | ||
'toContractAddress', | ||
'toContractCallData', | ||
'toContractGasLimit', | ||
]; | ||
requiredParameters.forEach((requiredParameter) => { | ||
if (!request[requiredParameter]) { | ||
throw new ValidationError(`Required parameter "${requiredParameter}" is missing.`); | ||
} | ||
}); | ||
}); }; | ||
var getStatus = function (_a, options) { | ||
var bridge = _a.bridge, fromChain = _a.fromChain, toChain = _a.toChain, txHash = _a.txHash; | ||
return __awaiter(void 0, void 0, void 0, function () { | ||
var configService, config, result, e_5; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
if (fromChain !== toChain && !bridge) { | ||
throw new errors_1.ValidationError('Parameter "bridge" is required for cross chain transfers.'); | ||
} | ||
if (!fromChain) { | ||
throw new errors_1.ValidationError('Required parameter "fromChain" is missing.'); | ||
} | ||
if (!toChain) { | ||
throw new errors_1.ValidationError('Required parameter "toChain" is missing.'); | ||
} | ||
if (!txHash) { | ||
throw new errors_1.ValidationError('Required parameter "txHash" is missing.'); | ||
} | ||
configService = ConfigService_1.default.getInstance(); | ||
config = configService.getConfig(); | ||
_b.label = 1; | ||
case 1: | ||
_b.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, axios_1.default.get(config.apiUrl + 'status', { | ||
params: { | ||
bridge: bridge, | ||
fromChain: fromChain, | ||
toChain: toChain, | ||
txHash: txHash, | ||
}, | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
})]; | ||
case 2: | ||
result = _b.sent(); | ||
return [2 /*return*/, result.data]; | ||
case 3: | ||
e_5 = _b.sent(); | ||
throw (0, parseError_1.parseBackendError)(e_5); | ||
case 4: return [2 /*return*/]; | ||
} | ||
// apply defaults | ||
// option.order is not used in this endpoint | ||
request.slippage = request.slippage || config.defaultRouteOptions.slippage; | ||
request.integrator = | ||
request.integrator || config.defaultRouteOptions.integrator; | ||
request.referrer = request.referrer || config.defaultRouteOptions.referrer; | ||
request.fee = request.fee || config.defaultRouteOptions.fee; | ||
request.allowBridges = | ||
request.allowBridges || ((_g = config.defaultRouteOptions.bridges) === null || _g === void 0 ? void 0 : _g.allow); | ||
request.denyBridges = | ||
request.denyBridges || ((_h = config.defaultRouteOptions.bridges) === null || _h === void 0 ? void 0 : _h.deny); | ||
request.preferBridges = | ||
request.preferBridges || ((_j = config.defaultRouteOptions.bridges) === null || _j === void 0 ? void 0 : _j.prefer); | ||
request.allowExchanges = | ||
request.allowExchanges || ((_k = config.defaultRouteOptions.bridges) === null || _k === void 0 ? void 0 : _k.allow); | ||
request.denyExchanges = | ||
request.denyExchanges || ((_l = config.defaultRouteOptions.bridges) === null || _l === void 0 ? void 0 : _l.deny); | ||
request.preferExchanges = | ||
request.preferExchanges || ((_m = config.defaultRouteOptions.bridges) === null || _m === void 0 ? void 0 : _m.prefer); | ||
// send request | ||
try { | ||
const result = yield axios.post(config.apiUrl + 'quote/contractCall', request, { | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
}); | ||
return result.data; | ||
} | ||
catch (e) { | ||
throw parseBackendError(e); | ||
} | ||
}); | ||
const getStatus = ({ bridge, fromChain, toChain, txHash }, options) => __awaiter(void 0, void 0, void 0, function* () { | ||
if (fromChain !== toChain && !bridge) { | ||
throw new ValidationError('Parameter "bridge" is required for cross chain transfers.'); | ||
} | ||
if (!fromChain) { | ||
throw new ValidationError('Required parameter "fromChain" is missing.'); | ||
} | ||
if (!toChain) { | ||
throw new ValidationError('Required parameter "toChain" is missing.'); | ||
} | ||
if (!txHash) { | ||
throw new ValidationError('Required parameter "txHash" is missing.'); | ||
} | ||
const configService = ConfigService.getInstance(); | ||
const config = configService.getConfig(); | ||
try { | ||
const result = yield axios.get(config.apiUrl + 'status', { | ||
params: { | ||
bridge, | ||
fromChain, | ||
toChain, | ||
txHash, | ||
}, | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
}); | ||
return result.data; | ||
} | ||
catch (e) { | ||
throw parseBackendError(e); | ||
} | ||
}); | ||
const getChains = (options) => __awaiter(void 0, void 0, void 0, function* () { | ||
const configService = ConfigService.getInstance(); | ||
const config = configService.getConfig(); | ||
try { | ||
const result = yield axios.get(config.apiUrl + 'chains', { | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
}); | ||
return result.data.chains; | ||
} | ||
catch (e) { | ||
throw parseBackendError(e); | ||
} | ||
}); | ||
const getRoutes = (request, options) => __awaiter(void 0, void 0, void 0, function* () { | ||
if (!isRoutesRequest(request)) { | ||
throw new ValidationError('Invalid routes request.'); | ||
} | ||
const configService = ConfigService.getInstance(); | ||
const config = configService.getConfig(); | ||
// apply defaults | ||
request.options = Object.assign(Object.assign({}, config.defaultRouteOptions), request.options); | ||
// send request | ||
try { | ||
const result = yield axios.post(config.apiUrl + 'advanced/routes', request, { | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
}); | ||
return result.data; | ||
} | ||
catch (e) { | ||
throw parseBackendError(e); | ||
} | ||
}); | ||
const getStepTransaction = (step, options) => __awaiter(void 0, void 0, void 0, function* () { | ||
if (!isStep(step)) { | ||
// While the validation fails for some users we should not enforce it | ||
// eslint-disable-next-line no-console | ||
console.warn('SDK Validation: Invalid Step', step); | ||
} | ||
const configService = ConfigService.getInstance(); | ||
const config = configService.getConfig(); | ||
try { | ||
const result = yield axios.post(config.apiUrl + 'advanced/stepTransaction', step, { | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
}); | ||
return result.data; | ||
} | ||
catch (e) { | ||
throw parseBackendError(e); | ||
} | ||
}); | ||
const getTools = (request, options) => __awaiter(void 0, void 0, void 0, function* () { | ||
const configService = ConfigService.getInstance(); | ||
const config = configService.getConfig(); | ||
const r = yield axios.get(config.apiUrl + 'tools', { | ||
params: request, | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
}); | ||
}; | ||
var getChains = function (options) { return __awaiter(void 0, void 0, void 0, function () { | ||
var configService, config, result, e_6; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
configService = ConfigService_1.default.getInstance(); | ||
config = configService.getConfig(); | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, axios_1.default.get(config.apiUrl + 'chains', { | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
})]; | ||
case 2: | ||
result = _a.sent(); | ||
return [2 /*return*/, result.data.chains]; | ||
case 3: | ||
e_6 = _a.sent(); | ||
throw (0, parseError_1.parseBackendError)(e_6); | ||
case 4: return [2 /*return*/]; | ||
} | ||
return r.data; | ||
}); | ||
const getTokens = (request, options) => __awaiter(void 0, void 0, void 0, function* () { | ||
const configService = ConfigService.getInstance(); | ||
const config = configService.getConfig(); | ||
const r = yield axios.get(config.apiUrl + 'tokens', { | ||
params: request, | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
}); | ||
}); }; | ||
var getRoutes = function (request, options) { return __awaiter(void 0, void 0, void 0, function () { | ||
var configService, config, result, e_7; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!(0, typeguards_1.isRoutesRequest)(request)) { | ||
throw new errors_1.ValidationError('Invalid routes request.'); | ||
} | ||
configService = ConfigService_1.default.getInstance(); | ||
config = configService.getConfig(); | ||
// apply defaults | ||
request.options = __assign(__assign({}, config.defaultRouteOptions), request.options); | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, axios_1.default.post(config.apiUrl + 'advanced/routes', request, { | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
})]; | ||
case 2: | ||
result = _a.sent(); | ||
return [2 /*return*/, result.data]; | ||
case 3: | ||
e_7 = _a.sent(); | ||
throw (0, parseError_1.parseBackendError)(e_7); | ||
case 4: return [2 /*return*/]; | ||
} | ||
}); | ||
}); }; | ||
var getStepTransaction = function (step, options) { return __awaiter(void 0, void 0, void 0, function () { | ||
var configService, config, result, e_8; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!(0, typeguards_1.isStep)(step)) { | ||
// While the validation fails for some users we should not enforce it | ||
// eslint-disable-next-line no-console | ||
console.warn('SDK Validation: Invalid Step', step); | ||
} | ||
configService = ConfigService_1.default.getInstance(); | ||
config = configService.getConfig(); | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, axios_1.default.post(config.apiUrl + 'advanced/stepTransaction', step, { | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
})]; | ||
case 2: | ||
result = _a.sent(); | ||
return [2 /*return*/, result.data]; | ||
case 3: | ||
e_8 = _a.sent(); | ||
throw (0, parseError_1.parseBackendError)(e_8); | ||
case 4: return [2 /*return*/]; | ||
} | ||
}); | ||
}); }; | ||
var getTools = function (request, options) { return __awaiter(void 0, void 0, void 0, function () { | ||
var configService, config, r; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
configService = ConfigService_1.default.getInstance(); | ||
config = configService.getConfig(); | ||
return [4 /*yield*/, axios_1.default.get(config.apiUrl + 'tools', { | ||
params: request, | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
})]; | ||
case 1: | ||
r = _a.sent(); | ||
return [2 /*return*/, r.data]; | ||
} | ||
}); | ||
}); }; | ||
var getTokens = function (request, options) { return __awaiter(void 0, void 0, void 0, function () { | ||
var configService, config, r; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
configService = ConfigService_1.default.getInstance(); | ||
config = configService.getConfig(); | ||
return [4 /*yield*/, axios_1.default.get(config.apiUrl + 'tokens', { | ||
params: request, | ||
signal: options === null || options === void 0 ? void 0 : options.signal, | ||
})]; | ||
case 1: | ||
r = _a.sent(); | ||
return [2 /*return*/, r.data]; | ||
} | ||
}); | ||
}); }; | ||
exports.default = { | ||
getPossibilities: getPossibilities, | ||
getToken: getToken, | ||
getQuote: getQuote, | ||
getContractCallQuote: getContractCallQuote, | ||
getStatus: getStatus, | ||
getChains: getChains, | ||
getRoutes: getRoutes, | ||
getStepTransaction: getStepTransaction, | ||
getTools: getTools, | ||
getTokens: getTokens, | ||
return r.data; | ||
}); | ||
export default { | ||
getPossibilities, | ||
getToken, | ||
getQuote, | ||
getContractCallQuote, | ||
getStatus, | ||
getChains, | ||
getRoutes, | ||
getStepTransaction, | ||
getTools, | ||
getTokens, | ||
}; |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -11,56 +10,15 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var errors_1 = require("../utils/errors"); | ||
var ApiService_1 = __importDefault(require("./ApiService")); | ||
var ChainsService = /** @class */ (function () { | ||
function ChainsService() { | ||
import { ValidationError } from '../utils/errors'; | ||
import ApiService from './ApiService'; | ||
export default class ChainsService { | ||
constructor() { | ||
this.chains = []; | ||
this.loadingPromise = this.loadAvailableChains(); | ||
} | ||
ChainsService.prototype.loadAvailableChains = function () { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var _a; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
_a = this; | ||
return [4 /*yield*/, ApiService_1.default.getChains()]; | ||
case 1: | ||
_a.chains = _b.sent(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
loadAvailableChains() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
this.chains = yield ApiService.getChains(); | ||
}); | ||
}; | ||
ChainsService.getInstance = function () { | ||
} | ||
static getInstance() { | ||
if (!this.instance) { | ||
@@ -70,41 +28,23 @@ this.instance = new ChainsService(); | ||
return this.instance; | ||
}; | ||
ChainsService.prototype.getChainById = function (chainId) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var chain; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!this.loadingPromise) return [3 /*break*/, 2]; | ||
return [4 /*yield*/, this.loadingPromise]; | ||
case 1: | ||
_a.sent(); | ||
_a.label = 2; | ||
case 2: | ||
chain = this.chains.find(function (chain) { return chain.id === chainId; }); | ||
if (!chain) { | ||
throw new errors_1.ValidationError("Unknown chainId passed: ".concat(chainId, ".")); | ||
} | ||
return [2 /*return*/, chain]; | ||
} | ||
}); | ||
} | ||
getChainById(chainId) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (this.loadingPromise) { | ||
yield this.loadingPromise; | ||
} | ||
const chain = this.chains.find((chain) => chain.id === chainId); | ||
if (!chain) { | ||
throw new ValidationError(`Unknown chainId passed: ${chainId}.`); | ||
} | ||
return chain; | ||
}); | ||
}; | ||
ChainsService.prototype.getChains = function () { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!this.loadingPromise) return [3 /*break*/, 2]; | ||
return [4 /*yield*/, this.loadingPromise]; | ||
case 1: | ||
_a.sent(); | ||
_a.label = 2; | ||
case 2: return [2 /*return*/, this.chains]; | ||
} | ||
}); | ||
} | ||
getChains() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (this.loadingPromise) { | ||
yield this.loadingPromise; | ||
} | ||
return this.chains; | ||
}); | ||
}; | ||
return ChainsService; | ||
}()); | ||
exports.default = ChainsService; | ||
} | ||
} |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -11,41 +10,12 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var types_1 = require("../types"); | ||
var DefaultExecutionSettings = { | ||
import { ChainId, } from '../types'; | ||
const DefaultExecutionSettings = { | ||
/* eslint-disable-next-line @typescript-eslint/no-empty-function */ | ||
updateCallback: function () { }, | ||
switchChainHook: function () { return Promise.resolve(undefined); }, | ||
acceptSlippageUpdateHook: function () { return Promise.resolve(undefined); }, | ||
updateCallback: () => { }, | ||
switchChainHook: () => Promise.resolve(undefined), | ||
acceptSlippageUpdateHook: () => Promise.resolve(undefined), | ||
infiniteApproval: false, | ||
}; | ||
var ConfigService = /** @class */ (function () { | ||
function ConfigService() { | ||
var _this = this; | ||
export default class ConfigService { | ||
constructor() { | ||
this.resolveSetupPromise = undefined; | ||
@@ -56,4 +26,4 @@ /** | ||
*/ | ||
this.getConfig = function () { | ||
return _this.config; | ||
this.getConfig = () => { | ||
return this.config; | ||
}; | ||
@@ -64,51 +34,44 @@ /** | ||
*/ | ||
this.getConfigAsync = function () { return __awaiter(_this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.setupPromise]; | ||
case 1: | ||
_a.sent(); | ||
return [2 /*return*/, this.config]; | ||
} | ||
}); | ||
}); }; | ||
this.updateConfig = function (configUpdate) { | ||
this.getConfigAsync = () => __awaiter(this, void 0, void 0, function* () { | ||
yield this.setupPromise; | ||
return this.config; | ||
}); | ||
this.updateConfig = (configUpdate) => { | ||
// API | ||
_this.config.apiUrl = configUpdate.apiUrl || _this.config.apiUrl; | ||
this.config.apiUrl = configUpdate.apiUrl || this.config.apiUrl; | ||
// RPCS | ||
_this.config.rpcs = Object.assign(_this.config.rpcs, configUpdate.rpcs); | ||
this.config.rpcs = Object.assign(this.config.rpcs, configUpdate.rpcs); | ||
// MULTICALL | ||
_this.config.multicallAddresses = Object.assign(_this.config.multicallAddresses, configUpdate.multicallAddresses); | ||
this.config.multicallAddresses = Object.assign(this.config.multicallAddresses, configUpdate.multicallAddresses); | ||
// SETTINGS | ||
_this.config.defaultExecutionSettings = Object.assign(_this.config.defaultExecutionSettings, configUpdate.defaultExecutionSettings); | ||
this.config.defaultExecutionSettings = Object.assign(this.config.defaultExecutionSettings, configUpdate.defaultExecutionSettings); | ||
// OPTIONS | ||
_this.config.defaultRouteOptions = Object.assign(_this.config.defaultRouteOptions, configUpdate.defaultRouteOptions); | ||
return _this.config; | ||
this.config.defaultRouteOptions = Object.assign(this.config.defaultRouteOptions, configUpdate.defaultRouteOptions); | ||
return this.config; | ||
}; | ||
this.updateChains = function (chains) { | ||
this.updateChains = (chains) => { | ||
var _a; | ||
for (var _i = 0, chains_1 = chains; _i < chains_1.length; _i++) { | ||
var chain = chains_1[_i]; | ||
var chainId = chain.id; | ||
for (const chain of chains) { | ||
const chainId = chain.id; | ||
// set RPCs if they were not configured by the user before | ||
if (!_this.config.rpcs[chainId].length) { | ||
_this.config.rpcs[chainId] = chain.metamask.rpcUrls; | ||
if (!this.config.rpcs[chainId].length) { | ||
this.config.rpcs[chainId] = chain.metamask.rpcUrls; | ||
} | ||
// set multicall addresses if they exist and were not configured by the user before | ||
if (chain.multicallAddress && !_this.config.multicallAddresses[chainId]) { | ||
_this.config.multicallAddresses[chainId] = chain.multicallAddress; | ||
if (chain.multicallAddress && !this.config.multicallAddresses[chainId]) { | ||
this.config.multicallAddresses[chainId] = chain.multicallAddress; | ||
} | ||
} | ||
(_a = _this.resolveSetupPromise) === null || _a === void 0 ? void 0 : _a.call(_this); | ||
return _this.config; | ||
(_a = this.resolveSetupPromise) === null || _a === void 0 ? void 0 : _a.call(this); | ||
return this.config; | ||
}; | ||
this.config = ConfigService.getDefaultConfig(); | ||
this.setupPromise = new Promise(function (resolve) { | ||
_this.resolveSetupPromise = resolve; | ||
this.setupPromise = new Promise((resolve) => { | ||
this.resolveSetupPromise = resolve; | ||
}); | ||
} | ||
ConfigService.chainIdToObject = function (val) { | ||
var result = {}; | ||
var values = Object.values(types_1.ChainId); | ||
values.forEach(function (chainId) { | ||
static chainIdToObject(val) { | ||
const result = {}; | ||
const values = Object.values(ChainId); | ||
values.forEach((chainId) => { | ||
if (typeof chainId !== 'string') { | ||
@@ -119,4 +82,4 @@ result[chainId] = val ? JSON.parse(JSON.stringify(val)) : val; | ||
return result; | ||
}; | ||
ConfigService.getInstance = function () { | ||
} | ||
static getInstance() { | ||
if (!this.instance) { | ||
@@ -126,14 +89,12 @@ this.instance = new ConfigService(); | ||
return this.instance; | ||
} | ||
} | ||
ConfigService.getDefaultConfig = () => { | ||
return { | ||
apiUrl: 'https://li.quest/v1/', | ||
rpcs: ConfigService.chainIdToObject([]), | ||
multicallAddresses: ConfigService.chainIdToObject(undefined), | ||
defaultExecutionSettings: DefaultExecutionSettings, | ||
defaultRouteOptions: {}, | ||
}; | ||
ConfigService.getDefaultConfig = function () { | ||
return { | ||
apiUrl: 'https://li.quest/v1/', | ||
rpcs: ConfigService.chainIdToObject([]), | ||
multicallAddresses: ConfigService.chainIdToObject(undefined), | ||
defaultExecutionSettings: DefaultExecutionSettings, | ||
defaultRouteOptions: {}, | ||
}; | ||
}; | ||
return ConfigService; | ||
}()); | ||
exports.default = ConfigService; | ||
}; |
@@ -1,6 +0,3 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.isToken = exports.isStep = exports.isRoutesRequest = void 0; | ||
var isRoutesRequest = function (routesRequest) { | ||
var fromChainId = routesRequest.fromChainId, fromAmount = routesRequest.fromAmount, fromTokenAddress = routesRequest.fromTokenAddress, toChainId = routesRequest.toChainId, toTokenAddress = routesRequest.toTokenAddress, options = routesRequest.options; | ||
export const isRoutesRequest = (routesRequest) => { | ||
const { fromChainId, fromAmount, fromTokenAddress, toChainId, toTokenAddress, options, } = routesRequest; | ||
return (typeof fromChainId === 'number' && | ||
@@ -16,8 +13,5 @@ typeof fromAmount === 'string' && | ||
}; | ||
exports.isRoutesRequest = isRoutesRequest; | ||
var isRoutesOptions = function (routeOptions) { | ||
return !(routeOptions === null || routeOptions === void 0 ? void 0 : routeOptions.slippage) || typeof routeOptions.slippage === 'number'; | ||
}; | ||
var isStep = function (step) { | ||
var id = step.id, type = step.type, tool = step.tool, action = step.action, estimate = step.estimate; | ||
const isRoutesOptions = (routeOptions) => !(routeOptions === null || routeOptions === void 0 ? void 0 : routeOptions.slippage) || typeof routeOptions.slippage === 'number'; | ||
export const isStep = (step) => { | ||
const { id, type, tool, action, estimate } = step; | ||
return (typeof id === 'string' && | ||
@@ -29,15 +23,14 @@ ['swap', 'cross', 'lifi'].includes(type) && | ||
}; | ||
exports.isStep = isStep; | ||
var isAction = function (action) { | ||
var fromChainId = action.fromChainId, fromAmount = action.fromAmount, fromToken = action.fromToken, toChainId = action.toChainId, toToken = action.toToken, slippage = action.slippage; | ||
const isAction = (action) => { | ||
const { fromChainId, fromAmount, fromToken, toChainId, toToken, slippage } = action; | ||
return (typeof fromChainId === 'number' && | ||
typeof fromAmount === 'string' && | ||
fromAmount !== '' && | ||
(0, exports.isToken)(fromToken) && | ||
isToken(fromToken) && | ||
typeof toChainId === 'number' && | ||
(0, exports.isToken)(toToken) && | ||
isToken(toToken) && | ||
typeof slippage === 'number'); | ||
}; | ||
var isEstimate = function (estimate) { | ||
var fromAmount = estimate.fromAmount, toAmount = estimate.toAmount, toAmountMin = estimate.toAmountMin, approvalAddress = estimate.approvalAddress; | ||
const isEstimate = (estimate) => { | ||
const { fromAmount, toAmount, toAmountMin, approvalAddress } = estimate; | ||
return (typeof fromAmount === 'string' && | ||
@@ -51,4 +44,4 @@ fromAmount !== '' && | ||
}; | ||
var isToken = function (token) { | ||
var address = token.address, decimals = token.decimals, chainId = token.chainId; | ||
export const isToken = (token) => { | ||
const { address, decimals, chainId } = token; | ||
return (typeof address === 'string' && | ||
@@ -58,2 +51,1 @@ typeof decimals === 'number' && | ||
}; | ||
exports.isToken = isToken; |
@@ -1,5 +0,2 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.ERC20_ABI = void 0; | ||
exports.ERC20_ABI = [ | ||
export const ERC20_ABI = [ | ||
{ | ||
@@ -6,0 +3,0 @@ name: 'approve', |
@@ -1,22 +0,4 @@ | ||
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
o[k2] = m[k]; | ||
})); | ||
var __exportStar = (this && this.__exportStar) || function(m, exports) { | ||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.LifiError = void 0; | ||
__exportStar(require("@lifi/types"), exports); | ||
var errors_1 = require("../utils/errors"); | ||
Object.defineProperty(exports, "LifiError", { enumerable: true, get: function () { return errors_1.LifiError; } }); | ||
__exportStar(require("./ERC20"), exports); | ||
__exportStar(require("./internal.types"), exports); | ||
export * from '@lifi/types'; | ||
export { LifiError } from '../utils/errors'; | ||
export * from './ERC20'; | ||
export * from './internal.types'; |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
export {}; |
@@ -1,19 +0,1 @@ | ||
"use strict"; | ||
var __extends = (this && this.__extends) || (function () { | ||
var extendStatics = function (d, b) { | ||
extendStatics = Object.setPrototypeOf || | ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || | ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; | ||
return extendStatics(d, b); | ||
}; | ||
return function (d, b) { | ||
if (typeof b !== "function" && b !== null) | ||
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); | ||
extendStatics(d, b); | ||
function __() { this.constructor = d; } | ||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); | ||
}; | ||
})(); | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.UnknownError = exports.NotFoundError = exports.SlippageError = exports.TransactionError = exports.ValidationError = exports.ServerError = exports.ProviderError = exports.RPCError = exports.LifiError = exports.MetaMaskProviderErrorCode = exports.MetaMaskRPCErrorCode = exports.LifiErrorCode = void 0; | ||
var ErrorType; | ||
@@ -30,3 +12,3 @@ (function (ErrorType) { | ||
})(ErrorType || (ErrorType = {})); | ||
var LifiErrorCode; | ||
export var LifiErrorCode; | ||
(function (LifiErrorCode) { | ||
@@ -45,4 +27,4 @@ LifiErrorCode[LifiErrorCode["InternalError"] = 1000] = "InternalError"; | ||
LifiErrorCode[LifiErrorCode["GasLimitError"] = 1009] = "GasLimitError"; | ||
})(LifiErrorCode = exports.LifiErrorCode || (exports.LifiErrorCode = {})); | ||
var MetaMaskRPCErrorCode; | ||
})(LifiErrorCode || (LifiErrorCode = {})); | ||
export var MetaMaskRPCErrorCode; | ||
(function (MetaMaskRPCErrorCode) { | ||
@@ -60,4 +42,4 @@ MetaMaskRPCErrorCode[MetaMaskRPCErrorCode["invalidInput"] = -32000] = "invalidInput"; | ||
MetaMaskRPCErrorCode[MetaMaskRPCErrorCode["internal"] = -32603] = "internal"; | ||
})(MetaMaskRPCErrorCode = exports.MetaMaskRPCErrorCode || (exports.MetaMaskRPCErrorCode = {})); | ||
var MetaMaskProviderErrorCode; | ||
})(MetaMaskRPCErrorCode || (MetaMaskRPCErrorCode = {})); | ||
export var MetaMaskProviderErrorCode; | ||
(function (MetaMaskProviderErrorCode) { | ||
@@ -69,85 +51,57 @@ MetaMaskProviderErrorCode[MetaMaskProviderErrorCode["userRejectedRequest"] = 4001] = "userRejectedRequest"; | ||
MetaMaskProviderErrorCode[MetaMaskProviderErrorCode["chainDisconnected"] = 4901] = "chainDisconnected"; | ||
})(MetaMaskProviderErrorCode = exports.MetaMaskProviderErrorCode || (exports.MetaMaskProviderErrorCode = {})); | ||
var LifiError = /** @class */ (function (_super) { | ||
__extends(LifiError, _super); | ||
function LifiError(type, code, message, htmlMessage, stack) { | ||
var _this = _super.call(this, message) || this; | ||
})(MetaMaskProviderErrorCode || (MetaMaskProviderErrorCode = {})); | ||
export class LifiError extends Error { | ||
constructor(type, code, message, htmlMessage, stack) { | ||
super(message); | ||
// Set the prototype explicitly: https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work | ||
Object.setPrototypeOf(_this, LifiError.prototype); | ||
_this.code = code; | ||
Object.setPrototypeOf(this, LifiError.prototype); | ||
this.code = code; | ||
// the name property is used by toString(). It is a string and we can't use our custom ErrorTypes, that's why we have to cast | ||
_this.name = type.toString(); | ||
_this.htmlMessage = htmlMessage; | ||
this.name = type.toString(); | ||
this.htmlMessage = htmlMessage; | ||
// passing a stack allows us to preserve the stack from errors that we caught and just want to transform in one of our custom errors | ||
if (stack) { | ||
_this.stack = stack; | ||
this.stack = stack; | ||
} | ||
return _this; | ||
} | ||
return LifiError; | ||
}(Error)); | ||
exports.LifiError = LifiError; | ||
var RPCError = /** @class */ (function (_super) { | ||
__extends(RPCError, _super); | ||
function RPCError(code, message, htmlMessage, stack) { | ||
return _super.call(this, ErrorType.RPCError, code, message, htmlMessage, stack) || this; | ||
} | ||
export class RPCError extends LifiError { | ||
constructor(code, message, htmlMessage, stack) { | ||
super(ErrorType.RPCError, code, message, htmlMessage, stack); | ||
} | ||
return RPCError; | ||
}(LifiError)); | ||
exports.RPCError = RPCError; | ||
var ProviderError = /** @class */ (function (_super) { | ||
__extends(ProviderError, _super); | ||
function ProviderError(code, message, htmlMessage, stack) { | ||
return _super.call(this, ErrorType.ProviderError, code, message, htmlMessage, stack) || this; | ||
} | ||
export class ProviderError extends LifiError { | ||
constructor(code, message, htmlMessage, stack) { | ||
super(ErrorType.ProviderError, code, message, htmlMessage, stack); | ||
} | ||
return ProviderError; | ||
}(LifiError)); | ||
exports.ProviderError = ProviderError; | ||
var ServerError = /** @class */ (function (_super) { | ||
__extends(ServerError, _super); | ||
function ServerError(message, htmlMessage, stack) { | ||
return _super.call(this, ErrorType.ServerError, LifiErrorCode.InternalError, message, htmlMessage, stack) || this; | ||
} | ||
export class ServerError extends LifiError { | ||
constructor(message, htmlMessage, stack) { | ||
super(ErrorType.ServerError, LifiErrorCode.InternalError, message, htmlMessage, stack); | ||
} | ||
return ServerError; | ||
}(LifiError)); | ||
exports.ServerError = ServerError; | ||
var ValidationError = /** @class */ (function (_super) { | ||
__extends(ValidationError, _super); | ||
function ValidationError(message, htmlMessage, stack) { | ||
return _super.call(this, ErrorType.ValidationError, LifiErrorCode.ValidationError, message, htmlMessage, stack) || this; | ||
} | ||
export class ValidationError extends LifiError { | ||
constructor(message, htmlMessage, stack) { | ||
super(ErrorType.ValidationError, LifiErrorCode.ValidationError, message, htmlMessage, stack); | ||
} | ||
return ValidationError; | ||
}(LifiError)); | ||
exports.ValidationError = ValidationError; | ||
var TransactionError = /** @class */ (function (_super) { | ||
__extends(TransactionError, _super); | ||
function TransactionError(code, message, htmlMessage, stack) { | ||
return _super.call(this, ErrorType.TransactionError, code, message, htmlMessage, stack) || this; | ||
} | ||
export class TransactionError extends LifiError { | ||
constructor(code, message, htmlMessage, stack) { | ||
super(ErrorType.TransactionError, code, message, htmlMessage, stack); | ||
} | ||
return TransactionError; | ||
}(LifiError)); | ||
exports.TransactionError = TransactionError; | ||
var SlippageError = /** @class */ (function (_super) { | ||
__extends(SlippageError, _super); | ||
function SlippageError(message, htmlMessage, stack) { | ||
return _super.call(this, ErrorType.SlippageError, LifiErrorCode.SlippageError, message, htmlMessage, stack) || this; | ||
} | ||
export class SlippageError extends LifiError { | ||
constructor(message, htmlMessage, stack) { | ||
super(ErrorType.SlippageError, LifiErrorCode.SlippageError, message, htmlMessage, stack); | ||
} | ||
return SlippageError; | ||
}(LifiError)); | ||
exports.SlippageError = SlippageError; | ||
var NotFoundError = /** @class */ (function (_super) { | ||
__extends(NotFoundError, _super); | ||
function NotFoundError(message, htmlMessage, stack) { | ||
return _super.call(this, ErrorType.NotFoundError, LifiErrorCode.NotFound, message, htmlMessage, stack) || this; | ||
} | ||
export class NotFoundError extends LifiError { | ||
constructor(message, htmlMessage, stack) { | ||
super(ErrorType.NotFoundError, LifiErrorCode.NotFound, message, htmlMessage, stack); | ||
} | ||
return NotFoundError; | ||
}(LifiError)); | ||
exports.NotFoundError = NotFoundError; | ||
var UnknownError = /** @class */ (function (_super) { | ||
__extends(UnknownError, _super); | ||
function UnknownError(code, message, htmlMessage, stack) { | ||
return _super.call(this, ErrorType.UnknownError, code, message, htmlMessage, stack) || this; | ||
} | ||
export class UnknownError extends LifiError { | ||
constructor(code, message, htmlMessage, stack) { | ||
super(ErrorType.UnknownError, code, message, htmlMessage, stack); | ||
} | ||
return UnknownError; | ||
}(LifiError)); | ||
exports.UnknownError = UnknownError; | ||
} |
@@ -1,11 +0,7 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.getProvider = void 0; | ||
var errors_1 = require("./errors"); | ||
var getProvider = function (signer) { | ||
import { LifiErrorCode, ProviderError } from './errors'; | ||
export const getProvider = (signer) => { | ||
if (!signer.provider) { | ||
throw new errors_1.ProviderError(errors_1.LifiErrorCode.ProviderUnavailable, 'No provider available in signer.'); | ||
throw new ProviderError(LifiErrorCode.ProviderUnavailable, 'No provider available in signer.'); | ||
} | ||
return signer.provider; | ||
}; | ||
exports.getProvider = getProvider; |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -11,117 +10,62 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.fetchDataUsingMulticall = void 0; | ||
var abi_1 = require("@ethersproject/abi"); | ||
var contracts_1 = require("@ethersproject/contracts"); | ||
var connectors_1 = require("../connectors"); | ||
var utils_1 = require("./utils"); | ||
var multicallAbi_json_1 = __importDefault(require("./multicallAbi.json")); | ||
var MAX_MULTICALL_SIZE = 100; | ||
var fetchDataUsingMulticall = function (calls, abi, chainId, multicallAddress, requireSuccess) { | ||
if (requireSuccess === void 0) { requireSuccess = false; } | ||
return __awaiter(void 0, void 0, void 0, function () { | ||
var provider, multicallContract, abiInterface, chunkedList, chunkedResults; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, (0, connectors_1.getRpcProvider)(chainId)]; | ||
case 1: | ||
provider = _a.sent(); | ||
multicallContract = new contracts_1.Contract(multicallAddress, multicallAbi_json_1.default, provider); | ||
abiInterface = new abi_1.Interface(abi); | ||
chunkedList = (0, utils_1.splitListIntoChunks)(calls, MAX_MULTICALL_SIZE); | ||
return [4 /*yield*/, Promise.all(chunkedList.map(function (chunkedCalls) { return __awaiter(void 0, void 0, void 0, function () { | ||
var callData, _a, blockNumber_1, returnData, e_1; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
callData = chunkedCalls.map(function (call) { return [ | ||
call.address.toLowerCase(), | ||
abiInterface.encodeFunctionData(call.name, call.params), | ||
]; }); | ||
_b.label = 1; | ||
case 1: | ||
_b.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, multicallContract.tryBlockAndAggregate(requireSuccess, callData) | ||
// 4. decode bytes array to useful data array... | ||
]; | ||
case 2: | ||
_a = _b.sent(), blockNumber_1 = _a.blockNumber, returnData = _a.returnData; | ||
// 4. decode bytes array to useful data array... | ||
return [2 /*return*/, returnData | ||
.map(function (_a, i) { | ||
var success = _a.success, returnData = _a.returnData; | ||
if (!success) { | ||
// requested function failed | ||
console.error("Multicall unsuccessful for address \"".concat(chunkedCalls[i].address, "\", ") + | ||
"function \"".concat(chunkedCalls[i].name, "\", chainId \"").concat(chainId, "\"")); | ||
return []; | ||
} | ||
if (returnData.toString() === '0x') { | ||
// requested function does probably not exist | ||
console.error("Multicall no response for address \"".concat(chunkedCalls[i].address, "\", ") + | ||
"function \"".concat(chunkedCalls[i].name, "\", chainId \"").concat(chainId, "\"")); | ||
return []; | ||
} | ||
try { | ||
return abiInterface.decodeFunctionResult(chunkedCalls[i].name, returnData); | ||
} | ||
catch (e) { | ||
// requested function returns other data than expected | ||
console.error("Multicall parsing unsuccessful for address \"".concat(chunkedCalls[i].address, "\", ") + | ||
"function \"".concat(chunkedCalls[i].name, "\", chainId \"").concat(chainId, "\"")); | ||
return []; | ||
} | ||
}) | ||
.map(function (data) { | ||
return { | ||
data: data[0], | ||
blockNumber: blockNumber_1.toNumber(), | ||
}; | ||
})]; | ||
case 3: | ||
e_1 = _b.sent(); | ||
// whole rpc call failed, probably an rpc issue | ||
console.error("Multicall failed on chainId \"".concat(chainId, "\""), chunkedList, e_1); | ||
return [2 /*return*/, []]; | ||
case 4: return [2 /*return*/]; | ||
} | ||
}); | ||
}); }))]; | ||
case 2: | ||
chunkedResults = _a.sent(); | ||
return [2 /*return*/, chunkedResults.flat()]; | ||
} | ||
}); | ||
}); | ||
}; | ||
exports.fetchDataUsingMulticall = fetchDataUsingMulticall; | ||
import { Interface } from '@ethersproject/abi'; | ||
import { Contract } from '@ethersproject/contracts'; | ||
import { getRpcProvider } from '../connectors'; | ||
import { splitListIntoChunks } from './utils'; | ||
import MULTICALL_ABI from './multicallAbi.json'; | ||
const MAX_MULTICALL_SIZE = 100; | ||
export const fetchDataUsingMulticall = (calls, abi, chainId, multicallAddress, requireSuccess = false) => __awaiter(void 0, void 0, void 0, function* () { | ||
// 1. create contract using multicall contract address and abi... | ||
const provider = yield getRpcProvider(chainId); | ||
const multicallContract = new Contract(multicallAddress, MULTICALL_ABI, provider); | ||
const abiInterface = new Interface(abi); | ||
// split up lists into chunks to stay below multicall limit | ||
const chunkedList = splitListIntoChunks(calls, MAX_MULTICALL_SIZE); | ||
const chunkedResults = yield Promise.all(chunkedList.map((chunkedCalls) => __awaiter(void 0, void 0, void 0, function* () { | ||
const callData = chunkedCalls.map((call) => [ | ||
call.address.toLowerCase(), | ||
abiInterface.encodeFunctionData(call.name, call.params), | ||
]); | ||
try { | ||
// 3. get bytes array from multicall contract by process aggregate method... | ||
const { blockNumber, returnData } = yield multicallContract.tryBlockAndAggregate(requireSuccess, callData); | ||
// 4. decode bytes array to useful data array... | ||
return returnData | ||
.map(({ success, returnData }, i) => { | ||
if (!success) { | ||
// requested function failed | ||
console.error(`Multicall unsuccessful for address "${chunkedCalls[i].address}", ` + | ||
`function "${chunkedCalls[i].name}", chainId "${chainId}"`); | ||
return []; | ||
} | ||
if (returnData.toString() === '0x') { | ||
// requested function does probably not exist | ||
console.error(`Multicall no response for address "${chunkedCalls[i].address}", ` + | ||
`function "${chunkedCalls[i].name}", chainId "${chainId}"`); | ||
return []; | ||
} | ||
try { | ||
return abiInterface.decodeFunctionResult(chunkedCalls[i].name, returnData); | ||
} | ||
catch (e) { | ||
// requested function returns other data than expected | ||
console.error(`Multicall parsing unsuccessful for address "${chunkedCalls[i].address}", ` + | ||
`function "${chunkedCalls[i].name}", chainId "${chainId}"`); | ||
return []; | ||
} | ||
}) | ||
.map((data) => { | ||
return { | ||
data: data[0], | ||
blockNumber: blockNumber.toNumber(), | ||
}; | ||
}); | ||
} | ||
catch (e) { | ||
// whole rpc call failed, probably an rpc issue | ||
console.error(`Multicall failed on chainId "${chainId}"`, chunkedList, e); | ||
return []; | ||
} | ||
}))); | ||
return chunkedResults.flat(); | ||
}); |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -11,39 +10,7 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.getSlippageNotMetMessage = exports.parseBackendError = exports.parseError = exports.getTransactionFailedMessage = exports.getTransactionNotSentMessage = void 0; | ||
var types_1 = require("@lifi/types"); | ||
var eth_rpc_errors_1 = require("eth-rpc-errors"); | ||
var ChainsService_1 = __importDefault(require("../services/ChainsService")); | ||
var errors_1 = require("./errors"); | ||
var utils_1 = require("./utils"); | ||
import { getChainById } from '@lifi/types'; | ||
import { errorCodes as MetaMaskErrorCodes, getMessageFromCode, } from 'eth-rpc-errors'; | ||
import ChainsService from '../services/ChainsService'; | ||
import { LifiError, LifiErrorCode, NotFoundError, ProviderError, RPCError, ServerError, SlippageError, TransactionError, UnknownError, ValidationError, } from './errors'; | ||
import { formatTokenAmountOnly } from './utils'; | ||
/** | ||
@@ -80,121 +47,86 @@ * Available MetaMask error codes: | ||
*/ | ||
var getTransactionNotSentMessage = function (step, process) { return __awaiter(void 0, void 0, void 0, function () { | ||
var transactionNotSend, chainService, chain; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
transactionNotSend = 'Transaction was not sent, your funds are still in your wallet'; | ||
if (!step) return [3 /*break*/, 2]; | ||
chainService = ChainsService_1.default.getInstance(); | ||
return [4 /*yield*/, chainService.getChainById(step.action.fromChainId)]; | ||
case 1: | ||
chain = _a.sent(); | ||
transactionNotSend += " (".concat((0, utils_1.formatTokenAmountOnly)(step.action.fromToken, step.action.fromAmount), " ").concat(step.action.fromToken.symbol, " on ").concat(chain.name, ")"); | ||
_a.label = 2; | ||
case 2: | ||
transactionNotSend += | ||
", please retry.<br/>If it still doesn't work, it is safe to delete this transfer and start a new one."; | ||
// add transaction explorer link if available | ||
transactionNotSend += | ||
process && process.txLink | ||
? "<br>You can check the failed transaction <a href=\"".concat(process.txLink, "\" target=\"_blank\" rel=\"nofollow noreferrer\">here</a>.") | ||
: ''; | ||
return [2 /*return*/, transactionNotSend]; | ||
} | ||
}); | ||
}); }; | ||
exports.getTransactionNotSentMessage = getTransactionNotSentMessage; | ||
var getTransactionFailedMessage = function (step, txLink) { | ||
var baseString = "It appears that your transaction may not have been successful.\n However, to confirm this, please check your ".concat((0, types_1.getChainById)(step.action.toChainId).name, " wallet for ").concat(step.action.toToken.symbol, "."); | ||
export const getTransactionNotSentMessage = (step, process) => __awaiter(void 0, void 0, void 0, function* () { | ||
let transactionNotSend = 'Transaction was not sent, your funds are still in your wallet'; | ||
// add information about funds if available | ||
if (step) { | ||
const chainService = ChainsService.getInstance(); | ||
const chain = yield chainService.getChainById(step.action.fromChainId); | ||
transactionNotSend += ` (${formatTokenAmountOnly(step.action.fromToken, step.action.fromAmount)} ${step.action.fromToken.symbol} on ${chain.name})`; | ||
} | ||
transactionNotSend += | ||
", please retry.<br/>If it still doesn't work, it is safe to delete this transfer and start a new one."; | ||
// add transaction explorer link if available | ||
transactionNotSend += | ||
process && process.txLink | ||
? `<br>You can check the failed transaction <a href="${process.txLink}" target="_blank" rel="nofollow noreferrer">here</a>.` | ||
: ''; | ||
return transactionNotSend; | ||
}); | ||
export const getTransactionFailedMessage = (step, txLink) => { | ||
const baseString = `It appears that your transaction may not have been successful. | ||
However, to confirm this, please check your ${getChainById(step.action.toChainId).name} wallet for ${step.action.toToken.symbol}.`; | ||
return txLink | ||
? "".concat(baseString, "\n You can also check the <a href=\"").concat(txLink, "\" target=\"_blank\" rel=\"nofollow noreferrer\">block explorer</a> for more information.") | ||
? `${baseString} | ||
You can also check the <a href="${txLink}" target="_blank" rel="nofollow noreferrer">block explorer</a> for more information.` | ||
: baseString; | ||
}; | ||
exports.getTransactionFailedMessage = getTransactionFailedMessage; | ||
var parseError = function (e, step, process) { return __awaiter(void 0, void 0, void 0, function () { | ||
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; | ||
var _o, _p; | ||
return __generator(this, function (_q) { | ||
switch (_q.label) { | ||
case 0: | ||
if (e instanceof errors_1.LifiError) { | ||
return [2 /*return*/, e]; | ||
} | ||
if (!e.code) return [3 /*break*/, 13]; | ||
if (!(typeof e.code === 'number')) return [3 /*break*/, 8]; | ||
if (!Object.values(eth_rpc_errors_1.errorCodes.rpc).includes(e.code)) return [3 /*break*/, 6]; | ||
if (!(e.code === eth_rpc_errors_1.errorCodes.rpc.internal && | ||
export const parseError = (e, step, process) => __awaiter(void 0, void 0, void 0, function* () { | ||
var _a, _b; | ||
if (e instanceof LifiError) { | ||
return e; | ||
} | ||
if (e.code) { | ||
// MetaMask errors have a numeric error code | ||
if (typeof e.code === 'number') { | ||
if (Object.values(MetaMaskErrorCodes.rpc).includes(e.code)) { | ||
// rpc errors | ||
// underpriced errors are sent as internal errors, so we need to parse the message manually | ||
if (e.code === MetaMaskErrorCodes.rpc.internal && | ||
e.message && | ||
e.message.includes('underpriced'))) return [3 /*break*/, 2]; | ||
_a = errors_1.RPCError.bind; | ||
_b = [void 0, errors_1.LifiErrorCode.TransactionUnderpriced, | ||
'Transaction is underpriced.']; | ||
return [4 /*yield*/, (0, exports.getTransactionNotSentMessage)(step, process)]; | ||
case 1: return [2 /*return*/, new (_a.apply(errors_1.RPCError, _b.concat([_q.sent(), e.stack])))()]; | ||
case 2: | ||
if (!(((_o = e.message) === null || _o === void 0 ? void 0 : _o.includes('intrinsic gas too low')) || | ||
((_p = e.message) === null || _p === void 0 ? void 0 : _p.includes('out of gas')))) return [3 /*break*/, 4]; | ||
_c = errors_1.TransactionError.bind; | ||
_d = [void 0, errors_1.LifiErrorCode.GasLimitError, | ||
'Gas limit is too low.']; | ||
return [4 /*yield*/, (0, exports.getTransactionNotSentMessage)(step, process)]; | ||
case 3: return [2 /*return*/, new (_c.apply(errors_1.TransactionError, _d.concat([_q.sent(), e.stack])))()]; | ||
case 4: | ||
_e = errors_1.RPCError.bind; | ||
_f = [void 0, e.code, | ||
(0, eth_rpc_errors_1.getMessageFromCode)(e.code)]; | ||
return [4 /*yield*/, (0, exports.getTransactionNotSentMessage)(step, process)]; | ||
case 5: return [2 /*return*/, new (_e.apply(errors_1.RPCError, _f.concat([_q.sent(), e.stack])))()]; | ||
case 6: | ||
if (!Object.values(eth_rpc_errors_1.errorCodes.provider).includes(e.code)) return [3 /*break*/, 8]; | ||
_g = errors_1.ProviderError.bind; | ||
_h = [void 0, e.code, | ||
(0, eth_rpc_errors_1.getMessageFromCode)(e.code)]; | ||
return [4 /*yield*/, (0, exports.getTransactionNotSentMessage)(step, process)]; | ||
case 7: return [2 /*return*/, new (_g.apply(errors_1.ProviderError, _h.concat([_q.sent(), e.stack])))()]; | ||
case 8: | ||
if (!(e.code === 'CALL_EXCEPTION')) return [3 /*break*/, 10]; | ||
_j = errors_1.ProviderError.bind; | ||
_k = [void 0, errors_1.LifiErrorCode.TransactionFailed, | ||
e.reason]; | ||
return [4 /*yield*/, (0, exports.getTransactionNotSentMessage)(step, process)]; | ||
case 9: return [2 /*return*/, new (_j.apply(errors_1.ProviderError, _k.concat([_q.sent(), e.stack])))()]; | ||
case 10: | ||
if (!(e.code === errors_1.LifiErrorCode.TransactionUnprepared)) return [3 /*break*/, 12]; | ||
_l = errors_1.TransactionError.bind; | ||
_m = [void 0, errors_1.LifiErrorCode.TransactionUnprepared, | ||
e.message]; | ||
return [4 /*yield*/, (0, exports.getTransactionNotSentMessage)(step, process)]; | ||
case 11: return [2 /*return*/, new (_l.apply(errors_1.TransactionError, _m.concat([_q.sent(), e.stack])))()]; | ||
case 12: | ||
if (e.code === errors_1.LifiErrorCode.ValidationError) { | ||
return [2 /*return*/, new errors_1.TransactionError(errors_1.LifiErrorCode.ValidationError, e.message, e.htmlMessage)]; | ||
e.message.includes('underpriced')) { | ||
return new RPCError(LifiErrorCode.TransactionUnderpriced, 'Transaction is underpriced.', yield getTransactionNotSentMessage(step, process), e.stack); | ||
} | ||
_q.label = 13; | ||
case 13: return [2 /*return*/, new errors_1.UnknownError(errors_1.LifiErrorCode.InternalError, e.message || 'Unknown error occurred.', undefined, e.stack)]; | ||
if (((_a = e.message) === null || _a === void 0 ? void 0 : _a.includes('intrinsic gas too low')) || | ||
((_b = e.message) === null || _b === void 0 ? void 0 : _b.includes('out of gas'))) { | ||
return new TransactionError(LifiErrorCode.GasLimitError, 'Gas limit is too low.', yield getTransactionNotSentMessage(step, process), e.stack); | ||
} | ||
return new RPCError(e.code, getMessageFromCode(e.code), yield getTransactionNotSentMessage(step, process), e.stack); | ||
} | ||
// provider errors | ||
if (Object.values(MetaMaskErrorCodes.provider).includes(e.code)) { | ||
return new ProviderError(e.code, getMessageFromCode(e.code), yield getTransactionNotSentMessage(step, process), e.stack); | ||
} | ||
} | ||
}); | ||
}); }; | ||
exports.parseError = parseError; | ||
var parseBackendError = function (e) { | ||
if (e.code === 'CALL_EXCEPTION') { | ||
return new ProviderError(LifiErrorCode.TransactionFailed, e.reason, yield getTransactionNotSentMessage(step, process), e.stack); | ||
} | ||
if (e.code === LifiErrorCode.TransactionUnprepared) { | ||
return new TransactionError(LifiErrorCode.TransactionUnprepared, e.message, yield getTransactionNotSentMessage(step, process), e.stack); | ||
} | ||
if (e.code === LifiErrorCode.ValidationError) { | ||
return new TransactionError(LifiErrorCode.ValidationError, e.message, e.htmlMessage); | ||
} | ||
} | ||
return new UnknownError(LifiErrorCode.InternalError, e.message || 'Unknown error occurred.', undefined, e.stack); | ||
}); | ||
export const parseBackendError = (e) => { | ||
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; | ||
if (((_a = e.response) === null || _a === void 0 ? void 0 : _a.status) === 400) { | ||
return new errors_1.ValidationError(((_c = (_b = e.response) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.message) || ((_d = e.response) === null || _d === void 0 ? void 0 : _d.statusText), undefined, e.stack); | ||
return new ValidationError(((_c = (_b = e.response) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.message) || ((_d = e.response) === null || _d === void 0 ? void 0 : _d.statusText), undefined, e.stack); | ||
} | ||
if (((_e = e.response) === null || _e === void 0 ? void 0 : _e.status) === 404) { | ||
return new errors_1.NotFoundError(((_g = (_f = e.response) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.message) || ((_h = e.response) === null || _h === void 0 ? void 0 : _h.statusText), undefined, e.stack); | ||
return new NotFoundError(((_g = (_f = e.response) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.message) || ((_h = e.response) === null || _h === void 0 ? void 0 : _h.statusText), undefined, e.stack); | ||
} | ||
if (((_j = e.response) === null || _j === void 0 ? void 0 : _j.status) === 409) { | ||
return new errors_1.SlippageError(((_l = (_k = e.response) === null || _k === void 0 ? void 0 : _k.data) === null || _l === void 0 ? void 0 : _l.message) || ((_m = e.response) === null || _m === void 0 ? void 0 : _m.statusText), 'The slippage is larger than the defined threshold. Please request a new route to get a fresh quote.', e.stack); | ||
return new SlippageError(((_l = (_k = e.response) === null || _k === void 0 ? void 0 : _k.data) === null || _l === void 0 ? void 0 : _l.message) || ((_m = e.response) === null || _m === void 0 ? void 0 : _m.statusText), 'The slippage is larger than the defined threshold. Please request a new route to get a fresh quote.', e.stack); | ||
} | ||
if (((_o = e.response) === null || _o === void 0 ? void 0 : _o.status) === 500) { | ||
return new errors_1.ServerError(((_q = (_p = e.response) === null || _p === void 0 ? void 0 : _p.data) === null || _q === void 0 ? void 0 : _q.message) || ((_r = e.response) === null || _r === void 0 ? void 0 : _r.statusText), undefined, e.stack); | ||
return new ServerError(((_q = (_p = e.response) === null || _p === void 0 ? void 0 : _p.data) === null || _q === void 0 ? void 0 : _q.message) || ((_r = e.response) === null || _r === void 0 ? void 0 : _r.statusText), undefined, e.stack); | ||
} | ||
return new errors_1.ServerError('Something went wrong.', undefined, e.stack); | ||
return new ServerError('Something went wrong.', undefined, e.stack); | ||
}; | ||
exports.parseBackendError = parseBackendError; | ||
var getSlippageNotMetMessage = function (step) { | ||
var slippage = step.action.slippage; | ||
return "Transaction was not sent, your funds are still in your wallet.\n The updated quote for the current transaction does not meet your set slippage of ".concat(slippage * 100, "%."); | ||
export const getSlippageNotMetMessage = (step) => { | ||
const { slippage } = step.action; | ||
return `Transaction was not sent, your funds are still in your wallet. | ||
The updated quote for the current transaction does not meet your set slippage of ${slippage * 100}%.`; | ||
}; | ||
exports.getSlippageNotMetMessage = getSlippageNotMetMessage; |
@@ -1,34 +0,27 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.handlePreRestart = void 0; | ||
var errors_1 = require("./errors"); | ||
var handlePreRestart = function (route) { | ||
import { LifiErrorCode } from './errors'; | ||
export const handlePreRestart = (route) => { | ||
var _a; | ||
for (var index = 0; index < route.steps.length; index++) { | ||
var stepHasFailed = ((_a = route.steps[index].execution) === null || _a === void 0 ? void 0 : _a.status) === 'FAILED'; | ||
for (let index = 0; index < route.steps.length; index++) { | ||
const stepHasFailed = ((_a = route.steps[index].execution) === null || _a === void 0 ? void 0 : _a.status) === 'FAILED'; | ||
if (stepHasFailed) { | ||
handleErrorType(route, index); | ||
popLastProcess(route, index); | ||
deleteFailedProcesses(route, index); | ||
} | ||
} | ||
}; | ||
exports.handlePreRestart = handlePreRestart; | ||
var handleErrorType = function (route, index) { | ||
const handleErrorType = (route, index) => { | ||
var _a, _b, _c, _d; | ||
var isGasLimitError = (_a = route.steps[index].execution) === null || _a === void 0 ? void 0 : _a.process.some(function (p) { var _a; return ((_a = p.error) === null || _a === void 0 ? void 0 : _a.code) === errors_1.LifiErrorCode.GasLimitError; }); | ||
var isGasPriceError = (_b = route.steps[index].execution) === null || _b === void 0 ? void 0 : _b.process.some(function (p) { var _a; return ((_a = p.error) === null || _a === void 0 ? void 0 : _a.code) === errors_1.LifiErrorCode.TransactionUnderpriced; }); | ||
const isGasLimitError = (_a = route.steps[index].execution) === null || _a === void 0 ? void 0 : _a.process.some((p) => { var _a; return ((_a = p.error) === null || _a === void 0 ? void 0 : _a.code) === LifiErrorCode.GasLimitError; }); | ||
const isGasPriceError = (_b = route.steps[index].execution) === null || _b === void 0 ? void 0 : _b.process.some((p) => { var _a; return ((_a = p.error) === null || _a === void 0 ? void 0 : _a.code) === LifiErrorCode.TransactionUnderpriced; }); | ||
if (isGasLimitError) { | ||
(_c = route.steps[index].estimate.gasCosts) === null || _c === void 0 ? void 0 : _c.forEach(function (gasCost) { | ||
return (gasCost.limit = "".concat(Math.round(Number(gasCost.limit) * 1.25))); | ||
}); | ||
(_c = route.steps[index].estimate.gasCosts) === null || _c === void 0 ? void 0 : _c.forEach((gasCost) => (gasCost.limit = `${Math.round(Number(gasCost.limit) * 1.25)}`)); | ||
} | ||
if (isGasPriceError) { | ||
(_d = route.steps[index].estimate.gasCosts) === null || _d === void 0 ? void 0 : _d.forEach(function (gasCost) { | ||
return (gasCost.price = "".concat(Math.round(Number(gasCost.price) * 1.25))); | ||
}); | ||
(_d = route.steps[index].estimate.gasCosts) === null || _d === void 0 ? void 0 : _d.forEach((gasCost) => (gasCost.price = `${Math.round(Number(gasCost.price) * 1.25)}`)); | ||
} | ||
}; | ||
var popLastProcess = function (route, index) { | ||
var _a; | ||
(_a = route.steps[index].execution) === null || _a === void 0 ? void 0 : _a.process.pop(); | ||
const deleteFailedProcesses = (route, index) => { | ||
if (route.steps[index].execution) { | ||
route.steps[index].execution.process = route.steps[index].execution.process.filter((process) => process.status !== 'FAILED'); | ||
} | ||
}; |
@@ -1,13 +0,1 @@ | ||
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -22,81 +10,36 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
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; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.isNativeTokenAddress = exports.isZeroAddress = exports.loadTransactionReceipt = exports.repeatUntilDone = exports.formatTokenAmountOnly = exports.splitListIntoChunks = exports.personalizeStep = exports.sleep = exports.deepClone = void 0; | ||
var bignumber_js_1 = __importDefault(require("bignumber.js")); | ||
var ethers_1 = require("ethers"); | ||
var connectors_1 = require("../connectors"); | ||
var deepClone = function (src) { | ||
import BigNumber from 'bignumber.js'; | ||
import { constants } from 'ethers'; | ||
import { getRpcProvider } from '../connectors'; | ||
export const deepClone = (src) => { | ||
return JSON.parse(JSON.stringify(src)); | ||
}; | ||
exports.deepClone = deepClone; | ||
var sleep = function (mills) { | ||
return new Promise(function (resolve) { | ||
export const sleep = (mills) => { | ||
return new Promise((resolve) => { | ||
setTimeout(resolve, mills); | ||
}); | ||
}; | ||
exports.sleep = sleep; | ||
var personalizeStep = function (signer, step) { return __awaiter(void 0, void 0, void 0, function () { | ||
var address, fromAddress, toAddress; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (step.action.toAddress && step.action.fromAddress) { | ||
return [2 /*return*/, step]; | ||
} | ||
return [4 /*yield*/, signer.getAddress()]; | ||
case 1: | ||
address = _a.sent(); | ||
fromAddress = step.action.fromAddress || address; | ||
toAddress = step.action.toAddress || address; | ||
return [2 /*return*/, __assign(__assign({}, step), { action: __assign(__assign({}, step.action), { fromAddress: fromAddress, toAddress: toAddress }) })]; | ||
} | ||
}); | ||
}); }; | ||
exports.personalizeStep = personalizeStep; | ||
var splitListIntoChunks = function (list, chunkSize) { | ||
return list.reduce(function (resultList, item, index) { | ||
var chunkIndex = Math.floor(index / chunkSize); | ||
if (!resultList[chunkIndex]) { | ||
resultList[chunkIndex] = []; // start a new chunk | ||
} | ||
resultList[chunkIndex].push(item); | ||
return resultList; | ||
}, []); | ||
}; | ||
exports.splitListIntoChunks = splitListIntoChunks; | ||
var formatTokenAmountOnly = function (token, amount) { | ||
export const personalizeStep = (signer, step) => __awaiter(void 0, void 0, void 0, function* () { | ||
if (step.action.toAddress && step.action.fromAddress) { | ||
return step; | ||
} | ||
const address = yield signer.getAddress(); | ||
const fromAddress = step.action.fromAddress || address; | ||
const toAddress = step.action.toAddress || address; | ||
return Object.assign(Object.assign({}, step), { action: Object.assign(Object.assign({}, step.action), { fromAddress, | ||
toAddress }) }); | ||
}); | ||
export const splitListIntoChunks = (list, chunkSize) => list.reduce((resultList, item, index) => { | ||
const chunkIndex = Math.floor(index / chunkSize); | ||
if (!resultList[chunkIndex]) { | ||
resultList[chunkIndex] = []; // start a new chunk | ||
} | ||
resultList[chunkIndex].push(item); | ||
return resultList; | ||
}, []); | ||
export const formatTokenAmountOnly = (token, amount) => { | ||
if (!amount) { | ||
return '0.0'; | ||
} | ||
var floated; | ||
let floated; | ||
if (typeof amount === 'string') { | ||
@@ -106,3 +49,3 @@ if (amount === '0') { | ||
} | ||
floated = new bignumber_js_1.default(amount).shiftedBy(-token.decimals); | ||
floated = new BigNumber(amount).shiftedBy(-token.decimals); | ||
} | ||
@@ -116,3 +59,3 @@ else { | ||
// show at least 4 decimal places and at least two non-zero digests | ||
var decimalPlaces = 3; | ||
let decimalPlaces = 3; | ||
while (floated.lt(1 / Math.pow(10, decimalPlaces))) { | ||
@@ -123,3 +66,2 @@ decimalPlaces++; | ||
}; | ||
exports.formatTokenAmountOnly = formatTokenAmountOnly; | ||
/** | ||
@@ -131,25 +73,12 @@ * Repeatedly calls a given asynchronous function until it resolves with a value | ||
*/ | ||
var repeatUntilDone = function (toRepeat, timeout) { | ||
if (timeout === void 0) { timeout = 5000; } | ||
return __awaiter(void 0, void 0, void 0, function () { | ||
var result; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!!result) return [3 /*break*/, 4]; | ||
return [4 /*yield*/, toRepeat()]; | ||
case 1: | ||
result = _a.sent(); | ||
if (!!result) return [3 /*break*/, 3]; | ||
return [4 /*yield*/, (0, exports.sleep)(timeout)]; | ||
case 2: | ||
_a.sent(); | ||
_a.label = 3; | ||
case 3: return [3 /*break*/, 0]; | ||
case 4: return [2 /*return*/, result]; | ||
} | ||
}); | ||
}); | ||
}; | ||
exports.repeatUntilDone = repeatUntilDone; | ||
export const repeatUntilDone = (toRepeat, timeout = 5000) => __awaiter(void 0, void 0, void 0, function* () { | ||
let result; | ||
while (!result) { | ||
result = yield toRepeat(); | ||
if (!result) { | ||
yield sleep(timeout); | ||
} | ||
} | ||
return result; | ||
}); | ||
/** | ||
@@ -161,19 +90,9 @@ * Loads a transaction receipt using the rpc for the given chain id | ||
*/ | ||
var loadTransactionReceipt = function (chainId, txHash) { return __awaiter(void 0, void 0, void 0, function () { | ||
var rpc, tx; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, (0, connectors_1.getRpcProvider)(chainId)]; | ||
case 1: | ||
rpc = _a.sent(); | ||
return [4 /*yield*/, rpc.getTransaction(txHash)]; | ||
case 2: | ||
tx = _a.sent(); | ||
return [2 /*return*/, tx.wait()]; | ||
} | ||
}); | ||
}); }; | ||
exports.loadTransactionReceipt = loadTransactionReceipt; | ||
var isZeroAddress = function (address) { | ||
if (address === ethers_1.constants.AddressZero || | ||
export const loadTransactionReceipt = (chainId, txHash) => __awaiter(void 0, void 0, void 0, function* () { | ||
const rpc = yield getRpcProvider(chainId); | ||
const tx = yield rpc.getTransaction(txHash); | ||
return tx.wait(); | ||
}); | ||
export const isZeroAddress = (address) => { | ||
if (address === constants.AddressZero || | ||
address === '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee') { | ||
@@ -184,5 +103,4 @@ return true; | ||
}; | ||
exports.isZeroAddress = isZeroAddress; | ||
var isNativeTokenAddress = function (address) { | ||
if (address === ethers_1.constants.AddressZero || | ||
export const isNativeTokenAddress = (address) => { | ||
if (address === constants.AddressZero || | ||
address === '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' || | ||
@@ -195,2 +113,1 @@ // CELO native token | ||
}; | ||
exports.isNativeTokenAddress = isNativeTokenAddress; |
{ | ||
"name": "@lifi/sdk", | ||
"version": "1.1.2", | ||
"version": "1.1.3", | ||
"description": "LI.FI Any-to-Any Cross-Chain-Swap SDK", | ||
@@ -5,0 +5,0 @@ "main": "./dist/index.js", |
206570
3717