@mstable/protocol
Version:
mStable Contracts
53 lines • 2.76 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.quoteSwap = exports.quoteExactInput = exports.getWETHPath = exports.encodeUniswapPath = void 0;
const generated_1 = require("types/generated");
const math_1 = require("../math");
const uniswapEthToken = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
const uniswapQuoterV3Address = "0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6";
const encodeUniswapPath = (tokenAddresses, fees) => {
const FEE_SIZE = 3;
if (tokenAddresses.length !== fees.length + 1) {
throw new Error("tokenAddresses/fees lengths do not match");
}
let encoded = "0x";
let encodedReversed = "";
fees.forEach((fee, i) => {
// 20 byte hex encoding of the address
const encodedAddress = tokenAddresses[i].slice(2);
encoded += encodedAddress;
encodedReversed = encodedAddress + encodedReversed;
// 3 byte hex encoding of the fee
const encodedFee = fees[i].toString(16).padStart(2 * FEE_SIZE, "0");
encoded += encodedFee;
encodedReversed = encodedFee + encodedReversed;
});
// encode the final token
const finalAddress = tokenAddresses[tokenAddresses.length - 1].slice(2);
encoded += finalAddress;
encodedReversed = `0x${finalAddress}${encodedReversed}`;
return {
encoded: encoded.toLowerCase(),
encodedReversed: encodedReversed.toLowerCase(),
};
};
exports.encodeUniswapPath = encodeUniswapPath;
const getWETHPath = (fromPath, toPath) => [fromPath, uniswapEthToken, toPath];
exports.getWETHPath = getWETHPath;
// It makes it easier to mock this function.
const quoteExactInput = (quoter, encodedPath, amount, blockNumber = "latest") => quoter.callStatic.quoteExactInput(encodedPath, amount, { blockTag: blockNumber });
exports.quoteExactInput = quoteExactInput;
const quoteSwap = async (signer, from, to, inAmount, blockNumber, path, fees = [3000, 3000]) => {
// Get quote value from UniswapV3
const uniswapPath = path || exports.getWETHPath(from.address, to.address);
// console.log("ts: quoteSwap uniswapPath", uniswapPath)
// Use Uniswap V3
const encodedPath = exports.encodeUniswapPath(uniswapPath, fees);
const quoter = generated_1.IUniswapV3Quoter__factory.connect(uniswapQuoterV3Address, signer);
const outAmount = await exports.quoteExactInput(quoter, encodedPath.encoded, inAmount, blockNumber);
const exchangeRate = outAmount.div(math_1.simpleToExactAmount(1, to.decimals)).mul(math_1.simpleToExactAmount(1, from.decimals)).div(inAmount);
// Exchange rate is not precise enough, better to relay on the output amount.
return { outAmount, exchangeRate };
};
exports.quoteSwap = quoteSwap;
//# sourceMappingURL=uniswap.js.map