Skip to content
This repository has been archived by the owner on Feb 25, 2023. It is now read-only.

Commit

Permalink
Merge pull request #103 from CoinAlpha/feat/improve_uni_v3_fee_responses
Browse files Browse the repository at this point in the history
fix broken getPosition function and add feature to estimate gas fee f…
  • Loading branch information
dennisocana authored Jul 14, 2021
2 parents cf1fcde + 9acb458 commit 536aae7
Show file tree
Hide file tree
Showing 12 changed files with 716 additions and 69 deletions.
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@
"format": "prettier . --write",
"lint": "eslint src test --format table --fix",
"debug": "DEBUG=*router nodemon --ext 'ts,js,json' --exec 'ts-node' src/index.ts",
"start": "nodemon dist/index.js",
"start": "pm2 start dist/index.js --no-daemon",
"status": "pm2 monit",
"stop": "pm2 stop all",
"logs": "pm2 logs",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
Expand Down Expand Up @@ -48,7 +51,8 @@
"util": "^0.12.3",
"winston": "^3.3.3",
"winston-daily-rotate-file": "^4.5.4",
"yaml": "^1.10.2"
"yaml": "^1.10.2",
"pm2": "^4.5.6"
},
"devDependencies": {
"@types/express": "^4.17.12",
Expand Down
3 changes: 0 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,8 @@ const onListening = () => {
if (addr) {
const bind =
typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
console.log('listening on ' + bind);
logger.debug('listening on ' + bind);
} else {
console.log('server.address() failed, not listening');
logger.debug('server.address() failed, not listening');
}
};
Expand All @@ -95,4 +93,3 @@ const serverConfig = {
};

logger.info(JSON.stringify(serverConfig));
console.log(serverConfig);
3 changes: 0 additions & 3 deletions src/routes/ethereum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,9 @@ router.post('/balances', async (req: Request, res: Response) => {

tokenContractList[symbol] = tokenContractInfo;
}
console.log(tokenContractList);

// Getting user balancers
const balances: Record<string, string> = {};
console.log('balances');
balances.ETH = await ethereumService.getETHBalance(wallet);
await Promise.all(
Object.keys(tokenContractList).map(async (symbol) => {
Expand Down Expand Up @@ -170,7 +168,6 @@ router.post('/approve', async (req: Request, res: Response) => {
tokenContractInfo.decimals
);
}
console.log('approve');
// call approve function
let approval;
try {
Expand Down
3 changes: 1 addition & 2 deletions src/routes/index.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,12 @@ router.post('/update', async (req, res) => {
const paramData = getParamData(req.body);

try {
console.log(updateConfig(paramData));
updateConfig(paramData);
const config = loadConfig();
res.status(200).json({
config: config,
});
} catch (err) {
console.log(err);
let reason;
err.reason
? (reason = err.reason)
Expand Down
1 change: 0 additions & 1 deletion src/routes/perpetual_finance.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,6 @@ router.post('/open', async (req, res) => {
const margin = paramData.margin;
const leverage = paramData.leverage;
const minBaseAssetAmount = paramData.minBaseAssetAmount;
console.log(minBaseAssetAmount);
const privateKey = paramData.privateKey;
let wallet;
try {
Expand Down
24 changes: 15 additions & 9 deletions src/routes/uniswap_v3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,13 +366,9 @@ router.post('/price', async (req: Request, res: Response) => {
}
const gasLimit = estimateGasLimit();
const gasCost = await fees.getGasCost(gasPrice, gasLimit);
console.log('made it here');
try {
// fetch pools for all tiers
let priceResult, price;
console.log('try it');
console.log(req.body);

if (req.body.amount) {
// get price at this depth
const amount = req.body.amount;
Expand Down Expand Up @@ -483,7 +479,7 @@ router.post('/position', async (req: Request, res: Response) => {

try {
// fetch position data
const positionData = await uniswap.getPosition(wallet, tokenId);
const positionData = await uniswap.getPosition(wallet, tokenId, eth);

const result = {
network: uniswap.network,
Expand Down Expand Up @@ -601,6 +597,7 @@ router.post('/remove-position', async (req: Request, res: Response) => {
new ethers.Wallet(privateKey, uniswap.provider)
);
const tokenId = req.body.tokenId;
const getFee = req.body.getFee.toUpperCase() === "TRUE" ? true : false

let gasPrice;
if (req.body.gasPrice) {
Expand All @@ -624,21 +621,30 @@ router.post('/remove-position', async (req: Request, res: Response) => {
wallet,
tokenId,
eth,
reducePercent
reducePercent,
getFee
);

const result = {
network: uniswap.network,
timestamp: initTime,
latency: latency(initTime, Date.now()),

hash: removelp.hash,
gasPrice: gasPrice,
gasLimit: gasLimit,
gasCost: gasCost,
gasFee: 0,
hash: ''

};

debug(`Remove lp: ${removelp.hash}`);
if (getFee && gasPrice){
result.gasFee = parseInt(removelp.toString()) * gasPrice;
debug(`Estimated gas to remove lp: ${result.gasFee}`);
} else {
result.hash = removelp.hash;
debug(`Remove lp: ${result.hash}`);
}

res.status(200).json(result);
} catch (err) {
logger.error(req.originalUrl, { message: err });
Expand Down
2 changes: 1 addition & 1 deletion src/services/access.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const validateAccess = (req, res, next) => {
const method = req.method;
const url = req.url;
const requestInfo = 'Request from IP: ' + ip + ' ' + method + ' ' + url;
console.log(requestInfo);
logger.info(requestInfo);
next();
} else if (cert.subject) {
logger.error(statusMessages.ssl_cert_invalid);
Expand Down
19 changes: 18 additions & 1 deletion src/services/ethereum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export interface EthTransactionReceipt {
blockNumber: number;
confirmations: number;
status: number;
logs: Array<Object>;
}

export interface TokenERC20Info {
Expand Down Expand Up @@ -215,7 +216,7 @@ export class EthereumService {
/**
* Get ERC20 token address
* @param {string} tokenSymbol
* @return string | null
* @return {TokenERC20Info} | null
*/
getERC20TokenAddress(tokenSymbol: string): TokenERC20Info | undefined {
if (this.erc20TokenList) {
Expand All @@ -229,6 +230,21 @@ export class EthereumService {
return;
}

/**
* Get ERC20 by token address
* @param {string} tokenAddress
* @return {TokenERC20Info} | null
*/
getERC20TokenByAddress(tokenAddress: string): TokenERC20Info | undefined {
if (this.erc20TokenList) {
const tokenContract = this.erc20TokenList.tokens.filter((obj) => {
return obj.address.toUpperCase() === tokenAddress.toUpperCase();
});
return tokenContract[0];
}
return;
}

/**
* Return wallet of a private string
* @param {string} privateKey
Expand All @@ -251,6 +267,7 @@ export class EthereumService {
blockNumber: transaction.blockNumber,
confirmations: transaction.confirmations,
status: transaction.status || 0,
logs: transaction.logs
};
}
}
5 changes: 2 additions & 3 deletions src/services/fees.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,20 @@ export default class Fees {
const response = await axios.get(ethGasStationURL);
// divite by 10 to convert it to Gwei)
this.ethGasPrice = response.data[gasLevel] / 10;
console.log(
logger.info(
`get ETHGasStation gas price (${gasLevel}): ${
this.ethGasPrice
} / interval: ${this.ethGasStationRefreshTime / 1000} sec`
);
} else {
this.ethGasPrice = ethManualGasPrice;
console.log(
logger.info(
`get manual fixed gas price: ${this.ethGasPrice} / interval: ${
this.ethGasStationRefreshTime / 1000
} sec`
);
}
} catch (err) {
console.log(err);
logger.error(err);
let reason;
err.reason
Expand Down
2 changes: 0 additions & 2 deletions src/services/perpetual_finance.js
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,6 @@ export default class PerpetualFinance {
}
return price;
} catch (err) {
console.log(err);
logger.error(err);
let reason;
err.reason ? (reason = err.reason) : (reason = 'error getting Price');
Expand Down Expand Up @@ -414,7 +413,6 @@ export default class PerpetualFinance {
(funding.markPrice - funding.indexPrice) / 24 / funding.indexPrice;
return funding;
} catch (err) {
console.log(err);
logger.error(err)();
let reason;
err.reason ? (reason = err.reason) : (reason = 'error getting fee');
Expand Down
17 changes: 12 additions & 5 deletions src/services/uniswap_v3.js
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,7 @@ Note that extending the uniswap v2 code may be possible in the future if uniswap
});
}

async reducePosition(wallet, tokenId, eth, decreasePercent = 100) {
async reducePosition(wallet, tokenId, eth, decreasePercent = 100, getFee = false) {
// Reduce position and burn
const contract = this.get_contract('nft', wallet);
const positionData = await this.getPosition(wallet, tokenId, 0, true);
Expand Down Expand Up @@ -576,10 +576,17 @@ Note that extending the uniswap v2 code may be possible in the future if uniswap
wallet
)
);
return await contract.multicall([callData.calldata], {
value: callData.value,
gasLimit: GAS_LIMIT,
});
if (getFee){
return await contract.estimateGas.multicall([callData.calldata], {
value: callData.value,
gasLimit: GAS_LIMIT,
});
} else {
return await contract.multicall([callData.calldata], {
value: callData.value,
gasLimit: GAS_LIMIT,
});
}
}

async collectFees(wallet, tokenId, isStatic = false) {
Expand Down
Loading

0 comments on commit 536aae7

Please sign in to comment.