ufomarketplace-sdk-new
Version:
SDK to interact with set ufo marketplace contracts
378 lines • 17.6 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getNftIdsFromTx = exports.approveTokenToRouter = exports.swapForExactInput = exports.getAmountIn = exports.getAmountOut = exports.swapForExactOutput = exports.getTokenBalance = exports.getToken1Token2Rate = exports.getMaticPriceFromUniswap = exports.getUfoPrice = exports.getWETHPriceFromUniswap = exports.getWETHPrice = exports.getWBEAMPrice = void 0;
const constants_1 = require("./constants/constants");
const ethers_1 = require("ethers");
const bignumber_js_1 = require("bignumber.js");
const quickswap_sdk_1 = require("quickswap-sdk");
const ERC20_json_1 = __importDefault(require("./abis/ERC20.json"));
const Events_json_1 = __importDefault(require("./abis/Events.json"));
const UniswapV2Router02_json_1 = __importDefault(require("./abis/UniswapV2Router02.json"));
const axios_1 = __importDefault(require("axios"));
const underscore_1 = __importDefault(require("underscore"));
const MAX_INT = ethers_1.BigNumber.from('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
const priceOracleUrl = 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2';
const wethAddr = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';
const ufoAddr = '0x249e38ea4102d0cf8264d3701f1a0e39c4f2dc3b';
function getWBEAMPrice() {
return __awaiter(this, void 0, void 0, function* () {
let rpcAddr, usdtAddr, wBeamAddr;
rpcAddr = constants_1.RPCS[constants_1.NETWORK_ID.BEAM];
usdtAddr = constants_1.USDT_ADDR[constants_1.NETWORK_ID.BEAM];
wBeamAddr = constants_1.WBEAM_ADDR[constants_1.NETWORK_ID.BEAM];
return getTokenPrice(rpcAddr, usdtAddr, 6, wBeamAddr, 18, constants_1.NETWORK_ID.BEAM);
});
}
exports.getWBEAMPrice = getWBEAMPrice;
function getWETHPrice() {
return __awaiter(this, void 0, void 0, function* () {
return getWETHPriceFromUniswap();
});
}
exports.getWETHPrice = getWETHPrice;
function getWETHPriceFromUniswap() {
return __awaiter(this, void 0, void 0, function* () {
let price = yield getPrice(priceOracleUrl, wethAddr);
return price.toString();
});
}
exports.getWETHPriceFromUniswap = getWETHPriceFromUniswap;
function getUfoPrice() {
return __awaiter(this, void 0, void 0, function* () {
let ethUfoPrice = yield getPriceETHUFO(priceOracleUrl, ufoAddr);
let price = yield getPrice(priceOracleUrl, wethAddr);
return (0, bignumber_js_1.BigNumber)(ethUfoPrice).multipliedBy(price).toFixed(9);
});
}
exports.getUfoPrice = getUfoPrice;
function getMaticPriceFromUniswap() {
return __awaiter(this, void 0, void 0, function* () {
let ufoAddr = '0x7c9f4c87d911613fe9ca58b579f737911aad2d43';
let price = yield getPrice(priceOracleUrl, ufoAddr);
return price.toString();
});
}
exports.getMaticPriceFromUniswap = getMaticPriceFromUniswap;
function fetchData(requestData) {
return __awaiter(this, void 0, void 0, function* () {
const { data } = yield axios_1.default.post(requestData.url, requestData.body, { headers: requestData.headers });
return data;
});
}
function getPriceETHUFO(url, address) {
return __awaiter(this, void 0, void 0, function* () {
address = address.toLowerCase();
const data = JSON.stringify({
query: `
{
price0: pairs(where:{
token0: "${address}",
token1_in : [
"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
]
}, orderBy: volumeUSD, orderDirection: desc, first: 1) {
token1Price
volumeUSD
}
price1: pairs(where:{
token1: "${address}",
token0_in : [
"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
]
}, orderBy: volumeUSD, orderDirection: desc, first: 1) {
token0Price
volumeUSD
}
}
`,
});
const options = {
url,
headers: { 'Content-Type': 'application/json' },
body: data,
};
const result = yield fetchData(options);
if (!result) {
throw new Error('Error while fetching data from subgraph');
}
if (result.errors) {
throw new Error('Error while fetching data from subgraph');
}
let price = (0, bignumber_js_1.BigNumber)(0);
if (result.data.price0 && result.data.price0.length != 0) {
price = result.data.price0[0].token1Price;
}
if (result.data.price1 && result.data.price1.length != 0) {
price = result.data.price1[0].token0Price;
}
if (result.data.price0 && result.data.price1 && result.data.price0.length != 0 && result.data.price1.length != 0) {
const volume0 = (0, bignumber_js_1.BigNumber)(result.data.price0[0].volumeUSD);
const volume1 = (0, bignumber_js_1.BigNumber)(result.data.price1[0].volumeUSD);
if (volume0.gt(volume1)) {
price = result.data.price0[0].token1Price;
}
}
return price;
});
}
function getPrice(url, address) {
return __awaiter(this, void 0, void 0, function* () {
address = address.toLowerCase();
const data = JSON.stringify({
query: `
{
price0: pairs(where:{
token0: "${address}",
token1_in : [
"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
"0xdac17f958d2ee523a2206206994597c13d831ec7",
"0x6b175474e89094c44da98b954eedeac495271d0f"
]
}, orderBy: volumeUSD, orderDirection: desc, first: 1) {
token1Price
volumeUSD
}
price1: pairs(where:{
token1: "${address}",
token0_in : [
"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
"0xdac17f958d2ee523a2206206994597c13d831ec7",
"0x6b175474e89094c44da98b954eedeac495271d0f"
]
}, orderBy: volumeUSD, orderDirection: desc, first: 1) {
token0Price
volumeUSD
}
}
`,
});
const options = {
url,
headers: { 'Content-Type': 'application/json' },
body: data,
};
const result = yield fetchData(options);
if (!result) {
throw new Error('Error while fetching data from subgraph');
}
if (result.errors) {
throw new Error('Error while fetching data from subgraph');
}
let price = (0, bignumber_js_1.BigNumber)(0);
if (result.data.price0 && result.data.price0.length != 0) {
price = result.data.price0[0].token1Price;
}
if (result.data.price1 && result.data.price1.length != 0) {
price = result.data.price1[0].token0Price;
}
if (result.data.price0 && result.data.price1 && result.data.price0.length != 0 && result.data.price1.length != 0) {
const volume0 = (0, bignumber_js_1.BigNumber)(result.data.price0[0].volumeUSD);
const volume1 = (0, bignumber_js_1.BigNumber)(result.data.price1[0].volumeUSD);
if (volume0.gt(volume1)) {
price = result.data.price0[0].token1Price;
}
}
return price;
});
}
function getToken1Token2Rate(networkId, token1, token2) {
return __awaiter(this, void 0, void 0, function* () {
let rpcAddr, token1Addr, token2Addr;
rpcAddr = constants_1.RPCS[networkId];
token1Addr = constants_1.COIN_ADDR[token1][networkId];
token2Addr = constants_1.COIN_ADDR[token2][networkId];
return getTokenPrice(rpcAddr, token2Addr, constants_1.COIN_ADDR[token2]['decimal'], token1Addr, constants_1.COIN_ADDR[token1]['decimal'], networkId);
});
}
exports.getToken1Token2Rate = getToken1Token2Rate;
function getTokenBalance(networkId, token, wallet) {
return __awaiter(this, void 0, void 0, function* () {
let rpcAddr, tokenAddr;
rpcAddr = constants_1.RPCS[networkId];
tokenAddr = constants_1.COIN_ADDR[token][networkId];
const provider = ethers_1.ethers.providers.getDefaultProvider(rpcAddr);
const cryptoContract = new ethers_1.Contract(tokenAddr, ERC20_json_1.default.abi, provider);
try {
const balance = yield cryptoContract.balanceOf(wallet);
return ethers_1.ethers.utils.formatUnits(balance.toString(), constants_1.COIN_ADDR[token]['decimal']).toString();
}
catch (e) {
console.log(e);
return '0';
}
});
}
exports.getTokenBalance = getTokenBalance;
function getTokenPrice(rpcProvider, sourceAddr, sourceDecimal, destination, destDecimal, networkId) {
return __awaiter(this, void 0, void 0, function* () {
const provider = ethers_1.ethers.providers.getDefaultProvider(rpcProvider);
const token1 = new quickswap_sdk_1.Token(networkId, sourceAddr, sourceDecimal);
const token2 = new quickswap_sdk_1.Token(networkId, destination, destDecimal);
try {
const pair = yield quickswap_sdk_1.Fetcher.fetchPairData(token1, token2, provider);
const route = new quickswap_sdk_1.Route([pair], token2);
return route.midPrice.toSignificant(6);
}
catch (e) {
console.log('get Token price error', e);
return '0';
}
});
}
function swapForExactOutput(amountOut, networkId, signer, inputTokenType, outputTokenType) {
return __awaiter(this, void 0, void 0, function* () {
let sourceTokenAddr, destTokenAddr;
sourceTokenAddr = constants_1.COIN_ADDR[inputTokenType][networkId];
destTokenAddr = constants_1.COIN_ADDR[outputTokenType][networkId];
const routerContract = new ethers_1.Contract(constants_1.ROUTER_ADDR[networkId], UniswapV2Router02_json_1.default.abi, signer);
const address = yield signer.getAddress();
return swapExactOutputTokens(sourceTokenAddr, destTokenAddr, amountOut, routerContract, address, signer);
});
}
exports.swapForExactOutput = swapForExactOutput;
function getAmountOut(amountIn, networkId, signer, inputTokenType, outputTokenType) {
return __awaiter(this, void 0, void 0, function* () {
let sourceTokenAddr, destTokenAddr;
sourceTokenAddr = constants_1.COIN_ADDR[inputTokenType][networkId];
destTokenAddr = constants_1.COIN_ADDR[outputTokenType][networkId];
const routerContract = new ethers_1.Contract(constants_1.ROUTER_ADDR[networkId], UniswapV2Router02_json_1.default.abi, signer);
const tokens = [sourceTokenAddr, destTokenAddr];
const amountOut = yield routerContract.callStatic.getAmountsOut(amountIn, tokens);
return amountOut[1];
});
}
exports.getAmountOut = getAmountOut;
function getAmountIn(amountOut, networkId, signer, inputTokenType, outputTokenType) {
return __awaiter(this, void 0, void 0, function* () {
let sourceTokenAddr, destTokenAddr;
sourceTokenAddr = constants_1.COIN_ADDR[inputTokenType][networkId];
destTokenAddr = constants_1.COIN_ADDR[outputTokenType][networkId];
const routerContract = new ethers_1.Contract(constants_1.ROUTER_ADDR[networkId], UniswapV2Router02_json_1.default.abi, signer);
const tokens = [sourceTokenAddr, destTokenAddr];
const amountIn = yield routerContract.callStatic.getAmountsIn(amountOut, tokens);
return amountIn[1];
});
}
exports.getAmountIn = getAmountIn;
function swapForExactInput(amountIn, networkId, signer, inputTokenType, outputTokenType) {
return __awaiter(this, void 0, void 0, function* () {
let sourceTokenAddr, destTokenAddr;
sourceTokenAddr = constants_1.COIN_ADDR[inputTokenType][networkId];
destTokenAddr = constants_1.COIN_ADDR[outputTokenType][networkId];
const routerContract = new ethers_1.Contract(constants_1.ROUTER_ADDR[networkId], UniswapV2Router02_json_1.default.abi, signer);
const address = yield signer.getAddress();
return swapExactInputTokens(sourceTokenAddr, destTokenAddr, amountIn, routerContract, address, signer);
});
}
exports.swapForExactInput = swapForExactInput;
function approveTokenToRouter(tokenType, networkId, signer) {
return __awaiter(this, void 0, void 0, function* () {
let tokenAddr = constants_1.COIN_ADDR[tokenType][networkId];
const token1 = new ethers_1.Contract(tokenAddr, ERC20_json_1.default.abi, signer);
return yield token1.approve(constants_1.ROUTER_ADDR[networkId], MAX_INT);
});
}
exports.approveTokenToRouter = approveTokenToRouter;
function swapExactInputTokens(address1, address2, amountExactInput, routerContract, accountAddress, signer) {
return __awaiter(this, void 0, void 0, function* () {
const tokens = [address1, address2];
const time = Math.floor(Date.now() / 1000) + 200000;
const deadline = ethers_1.ethers.BigNumber.from(time);
const token1 = new ethers_1.Contract(address1, ERC20_json_1.default.abi, signer);
const tokenDecimals = yield getDecimals(token1);
const amountIn = ethers_1.ethers.utils.parseUnits(amountExactInput, tokenDecimals);
const amountOut = yield routerContract.callStatic.getAmountsOut(amountIn, tokens);
const wMaticAddress = yield routerContract.WETH();
if (address1 === wMaticAddress) {
// Eth -> Token
return yield routerContract.swapExactETHForTokens(amountOut[1], tokens, accountAddress, deadline, {
value: amountIn,
});
}
else if (address2 === wMaticAddress) {
// Token -> Eth
return yield routerContract.swapExactTokensForETH(amountIn, amountOut[1], tokens, accountAddress, deadline);
}
else {
return yield routerContract.swapExactTokensForTokens(amountIn, amountOut[1], tokens, accountAddress, deadline);
}
});
}
function swapExactOutputTokens(address1, address2, amountExactOut, routerContract, accountAddress, signer) {
return __awaiter(this, void 0, void 0, function* () {
const tokens = [address1, address2];
const time = Math.floor(Date.now() / 1000) + 200000;
const deadline = ethers_1.ethers.BigNumber.from(time);
const token2 = new ethers_1.Contract(address2, ERC20_json_1.default.abi, signer);
const tokenDecimals = yield getDecimals(token2);
const amountOut = ethers_1.ethers.utils.parseUnits(amountExactOut, tokenDecimals);
const amountIn = yield routerContract.callStatic.getAmountsIn(amountOut, tokens);
const wethAddress = yield routerContract.WETH();
if (address1 === wethAddress) {
// Eth -> Token
return yield routerContract.swapETHForExactTokens(amountOut, tokens, accountAddress, deadline, {
value: amountIn[0],
});
}
else if (address2 === wethAddress) {
// Token -> Eth
return yield routerContract.swapTokensForExactETH(amountIn[0], amountOut, tokens, accountAddress, deadline);
}
else {
return yield routerContract.swapTokensForExactTokens(amountIn[0], amountOut, tokens, accountAddress, deadline);
}
});
}
function getDecimals(token) {
return __awaiter(this, void 0, void 0, function* () {
const decimals = yield token
.decimals()
.then((result) => {
return result;
})
.catch((error) => {
console.log('No tokenDecimals function for this token, set to 0');
return 0;
});
return decimals;
});
}
function getNftIdsFromTx(eventName, logs) {
let ret = [];
let iface = new ethers_1.ethers.utils.Interface(Events_json_1.default);
logs.forEach((log) => {
try {
let data = iface.parseLog(log);
if (data) {
if (data.name == eventName && eventName == 'purchaseLootEvent') {
ret.push(data.args.tokenIds);
}
else if (data.name == eventName && eventName == 'purchaseAndSendGiftEvent') {
ret.push(data.args.tokenIds);
}
else if (data.name == eventName && eventName == 'mintGensisNFT') {
ret.push(data.args.nftId);
}
else if (data.name == eventName && eventName == 'mintRandomGensisNFT') {
ret.push(log.address.substring(2) + '0x' + data.args.nftId);
}
}
}
catch (e) { }
});
return underscore_1.default.flatten(ret);
}
exports.getNftIdsFromTx = getNftIdsFromTx;
//# sourceMappingURL=utils.js.map