butterjs-sdk
Version:
Butter Network SDK
82 lines (81 loc) • 3.37 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ButterSmartRouter = void 0;
const ethers_1 = require("ethers");
const axios_1 = __importDefault(require("axios"));
const constants_1 = require("../../constants/constants");
const chainUtil_1 = require("../../utils/chainUtil");
class ButterSmartRouter {
async getBestRoute(fromToken, toToken, amountIn) {
const fromChainId = fromToken.chainId;
const toChainId = toToken.chainId;
if ((0, chainUtil_1.IS_MAINNET)(fromChainId) != (0, chainUtil_1.IS_MAINNET)(toChainId)) {
throw new Error(`getBestRoute: fromToken and toToken not on the same network. From: ${fromChainId}, To: ${toChainId}`);
}
const smartRouterServerUrl = (0, chainUtil_1.IS_MAINNET)(fromChainId)
? constants_1.BUTTER_SMART_ROUTER_URL_MAINNET
: constants_1.BUTTER_SMART_ROUTER_URL;
const requestUrl = smartRouterServerUrl +
'?' +
`fromChainId=${fromChainId}&` +
`toChainId=${toChainId}&` +
`amountIn=${ethers_1.ethers.utils.formatUnits(amountIn, fromToken.decimals)}&` +
`tokenInAddress=${fromToken.address}&` +
`tokenInDecimal=${fromToken.decimals}&` +
`tokenInSymbol=${fromToken.symbol}&` +
`tokenOutAddress=${toToken.address}&` +
`tokenOutDecimal=${toToken.decimals}&` +
`tokenOutSymbol=${toToken.symbol}`;
console.log(requestUrl);
let routeResponse;
try {
await axios_1.default.get(requestUrl).then(function (response) {
const data = response.data;
if (data.hasOwnProperty('status') && data.hasOwnProperty('error')) {
routeResponse = {
status: 200,
code: 10001,
msg: 'Insufficient Liquidity',
};
}
else if (data.hasOwnProperty('mapChain')) {
const mapAmountOut = data['mapChain'][0]['amountOut'];
if (parseFloat(mapAmountOut) <= 0) {
routeResponse = {
status: 200,
code: 10002,
msg: 'Input Amount Less Than Fee',
};
}
else {
routeResponse = {
data: response.data,
status: response.status,
code: 10000,
msg: response.statusText,
};
}
}
else {
routeResponse = {
status: 500,
code: 99999,
msg: 'Internal Server Error',
};
}
});
}
catch (error) {
routeResponse = {
status: 500,
code: 99999,
msg: error.message,
};
}
return routeResponse;
}
}
exports.ButterSmartRouter = ButterSmartRouter;
;