Skip to content

Commit

Permalink
Merge pull request #21 from darwinia-network/aki-better-logs-and-rpcs
Browse files Browse the repository at this point in the history
update
  • Loading branch information
wuminzhe authored Apr 1, 2024
2 parents 5c298b3 + 88c0dad commit a8f345f
Show file tree
Hide file tree
Showing 7 changed files with 628 additions and 546 deletions.
9 changes: 6 additions & 3 deletions .env.sample
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
PORT=3389
API_KEY=
INFURA_API_KEY=
ALCHEMY_API_KEY=
ANKR_API_KEY=
ETHEREUM_MAINNET_RPC=
ETHEREUM_SEPOLIA_RPC=
ARBITRUM_MAINNET_RPC=
ARBITRUM_SEPOLIA_RPC=
POLYGON_MAINNET_RPC=
BLAST_MAINNET_RPC=
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"axios": "^1.4.0",
"dotenv": "^16.3.1",
"ethers": "^5.7.0",
"express": "^4.18.2"
"express": "^4.18.2",
"express-http-context": "^1.2.4"
}
}
54 changes: 38 additions & 16 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,25 @@
import express, { Express, Request, Response } from "express";
var httpContext = require('express-http-context');
import { IEstimateFee } from "./interfaces/IEstimateFee";
import { ensureError } from "./errors";

require('dotenv').config({ silent: true })


console.log = (function() {
var console_log = console.log;

return function() {
var time = "[" + new Date().toUTCString() + "]";
var args = [];
args.push(time + ':');
for(var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
console_log.apply(console, args);
};
})();

////////////////////////////////////////////
// Server
////////////////////////////////////////////
Expand All @@ -17,6 +34,8 @@ app.use((_req, res, next) => {
next()
})

app.use(httpContext.middleware);

app.get("/", (_req: Request, res: Response) => {
res.send("Hello, Darwinia");
});
Expand Down Expand Up @@ -54,13 +73,13 @@ app.get("/:protocol/fee", async (req: Request, res: Response) => {
const toAddress: string = req.query.to_address as string;
const refundAddress: string = req.query.refund_address as string;
const extra: string = req.query.extra as string; // extra=[[1, 10]]
console.log(`protocol: ${protocol}`);
console.log(`fromChain: ${fromChainId}, toChain: ${toChainId}`);
console.log(`fromAddress: ${fromAddress}, toAddress: ${toAddress}`)
console.log(`payload: ${payload}`);
console.log(`gasLimit: ${gasLimit}`)
console.log(`refundAddress: ${refundAddress}`)
console.log(`extra: ${extra}`);
const logTitle = `${protocol}:${fromChainId}>${toChainId}`
console.log(`${logTitle} - ==============================================================================================================`);
console.log(`${logTitle} - fromAddress: ${fromAddress}, toAddress: ${toAddress}`)
console.log(`${logTitle} - payload: ${payload}`);
console.log(`${logTitle} - gasLimit: ${gasLimit}`)
console.log(`${logTitle} - refundAddress: ${refundAddress}`)
console.log(`${logTitle} - extra: ${extra}`);
if (
!fromChainId ||
!toChainId ||
Expand Down Expand Up @@ -88,7 +107,8 @@ app.get("/:protocol/fee", async (req: Request, res: Response) => {
fromAddress,
toAddress,
refundAddress,
extra
extra,
logTitle
);
const result = await estimateFee(
protocol,
Expand All @@ -107,12 +127,12 @@ app.get("/:protocol/fee", async (req: Request, res: Response) => {
}
});

async function getEstimateFeeFunction(protocol: string) {
async function getEstimateFeeFunction(protocol: string, title: string) {
try {
const buildEstimateFee = await import(`./${protocol}/estimateFee`)
return buildEstimateFee.default();
} catch (e) {
console.log(e);
console.log(`${title} - `, e);
throw new Error(`${protocol} - ${e.message}`);
}
}
Expand All @@ -128,8 +148,9 @@ async function estimateFee(
refundAddress: string,
extraParams: any
) {
const title = `${protocol}:${fromChainId}>${toChainId}`
try {
const estimateFee = await getEstimateFeeFunction(protocol);
const estimateFee = await getEstimateFeeFunction(protocol, title);
return await estimateFee(
fromChainId,
toChainId,
Expand All @@ -142,7 +163,7 @@ async function estimateFee(
);
} catch (e) {
const err = ensureError(e);
console.error(err);
console.error(`${title} - `, err);
throw err;
}
}
Expand All @@ -154,13 +175,14 @@ function checkParams(
fromAddress: string,
toAddress: string,
refundAddress: string,
extra: any
extra: any,
logTitle: string
) {
try {
const fromChainIdInt = parseInt(fromChainId);
const toChainIdInt = parseInt(toChainId);
const gasLimitInt = parseInt(gasLimit);
const extraParams = parseExtraParams(extra);
const extraParams = parseExtraParams(extra, logTitle);

return {
fromChainIdInt,
Expand All @@ -176,7 +198,7 @@ function checkParams(
}
}

function parseExtraParams(extra: string) {
function parseExtraParams(extra: string, logTitle: string) {
try {
if (extra) {
const extraParams: any[] = JSON.parse(extra);
Expand Down Expand Up @@ -212,5 +234,5 @@ function errorWith(res: Response, code: number, error: Error | string) {
}

app.listen(port, host, () => {
console.log(`[Server]: I am running at https://${host}:${port}`);
console.log(`Server: I am running at https://${host}:${port}`);
});
32 changes: 19 additions & 13 deletions src/ormp/doEstimateFee.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ethers } from "ethers";
import { getContract, estimateGas, callFunction } from "../utils/evmChainsUtils";
import { blockNumber, getContract, estimateGas, callFunction } from "../utils/evmChainsUtils";
import { FeestimiError } from "../errors";

const srcOrmpLineAbi = [
Expand All @@ -18,50 +18,56 @@ async function doEstimateFee(params, config): Promise<[string, string]> {
const portAddresses = config.portAddresses;
const ormpAddresses = config.ormpAddresses;

const logTitle = `ormp:${fromChainId}>${toChainId}`

// PARAMS PREPARATION
const srcPortAddress = portAddresses[fromChainId]
console.log(srcPortAddress)
console.log(`${logTitle} - srcPortAddress: ${srcPortAddress}`);
if (!srcPortAddress) {
throw new FeestimiError(`srcPortAddress not found`, {
context: { fromChainId },
});
}
console.log(`srcPortAddress: ${srcPortAddress}`);

const tgtPortAddress = portAddresses[toChainId]
console.log(`${logTitle} - tgtPortAddress: ${tgtPortAddress}`);
if (!tgtPortAddress) {
throw new FeestimiError(`tgtPortAddress not found`, {
context: { toChainId },
});
}
console.log(`tgtPortAddress: ${tgtPortAddress}`);

const tgtOrmpAddress = ormpAddresses[toChainId];
if (!tgtOrmpAddress) {
throw new FeestimiError(`tgtOrmpAddress not found`, {
context: { toChainId },
});
}
console.log(`tgtOrmpAddress: ${tgtOrmpAddress}`)
console.log(`${logTitle} - tgtOrmpAddress: ${tgtOrmpAddress}`);

// BUILD FULL PAYLOAD
const fullPayload = buildFullPayload(fromUAAddress, toUAAddress, payload, fromChainId, srcPortAddress)
console.log(`fullPayload: ${fullPayload}`);
console.log(`${logTitle} - fullPayload: ${fullPayload}`);

// GAS ESTIMATION IF NOT PROVIDED
if (!gasLimit) {
console.log(`${logTitle} - TARGET GASLIMIT NOT PROVIDED, ESTIMATING...`)
console.log(`${logTitle} - __blockNumber: ${await blockNumber(toChainId)}`)
gasLimit = await estimateGas(toChainId, tgtOrmpAddress, tgtPortAddress, fullPayload);
console.log(`fullPayload gasLimit estimated: ${gasLimit}`)
console.log(`${logTitle} - __gasLimit: ${gasLimit} (fullPayload)`)

const baseGas = isArb(toChainId) ? (await fetchBaseGas(toChainId)) : 0;
console.log(`baseGas: ${baseGas}`)
const arb = isArb(toChainId);
const baseGas = arb ? (await fetchBaseGas(toChainId)) : 0;
console.log(`${logTitle} - __baseGas: ${baseGas}${arb ? '(arb)' : ''}`)

let m = 1.2;
if (toChainId == 44) {
gasLimit = Math.round((baseGas + gasLimit) * 1.5);
m = 1.5;
gasLimit = Math.round((baseGas + gasLimit) * m);
} else {
gasLimit = Math.round((baseGas + gasLimit) * 1.2);
gasLimit = Math.round((baseGas + gasLimit) * m);
}
console.log(`fullPayload gasLimit estimated with buffer: ${gasLimit}`)
console.log(`${logTitle} - __gasLimit full: ${gasLimit} ( (gasLimit+baseGas)*${m} )`)
}

// 1. BUILD PARAMS STR FOR UA TO CALL ORMP
Expand All @@ -82,7 +88,7 @@ async function doEstimateFee(params, config): Promise<[string, string]> {
);

return [
fee.toLocaleString('fullwide', { useGrouping: false }),
Number(fee).toLocaleString('fullwide', { useGrouping: false }),
paramsStr
];
}
Expand Down
66 changes: 37 additions & 29 deletions src/utils/evmChainsUtils.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import { eth_chainId, eth_estimateGas, eth_call } from "./evmJsonRpcClient";
import { eth_chainId, eth_estimateGas, eth_blockNumber, eth_call } from "./evmJsonRpcClient";
import { ethers } from "ethers";
import { FeestimiError } from "../errors";
import 'dotenv/config'

const jsonRpcHttpUrls: { [key: number]: string } = {
1: "https://ethereum.publicnode.com",
11155111: "https://ethereum-sepolia.publicnode.com",
421614: "https://arbitrum-sepolia.blockpi.network/v1/rpc/public",
42161: "https://arbitrum-one.publicnode.com",
1: process.env.ETHEREUM_MAINNET_RPC,
11155111: process.env.ETHEREUM_SEPOLIA_RPC,
421614: process.env.ARBITRUM_SEPOLIA_RPC,
42161: process.env.ARBITRUM_MAINNET_RPC,
43: "https://pangolin-rpc.darwinia.network",
44: "https://crab-rpc.darwinia.network",
46: "https://rpc.darwinia.network",
2494104990: "https://api.shasta.trongrid.io/jsonrpc",
728126428: "https://api.trongrid.io/jsonrpc",
137: "https://polygon-bor-rpc.publicnode.com",
81457: "https://rpc.blast.io"
137: process.env.POLYGON_MAINNET_RPC,
81457: process.env.BLAST_MAINNET_RPC
};

async function estimateGas(chainId: number, from: string, to: string, data: string) {
console.log("chainId - " + chainId)
const url = jsonRpcHttpUrls[chainId];
if (!url) {
throw new FeestimiError("json rpc url not found");
Expand All @@ -31,7 +31,6 @@ async function estimateGas(chainId: number, from: string, to: string, data: stri
}

async function call(chainId: number, contract: string, data: string) {
console.log("chainId - " + chainId)
const url = jsonRpcHttpUrls[chainId];
if (!url) {
throw new FeestimiError("json rpc url not found");
Expand Down Expand Up @@ -61,7 +60,6 @@ async function callFunction(chainId: number, contract: string, abi: string[], fu
const getProvider = async (
chainId: number
): Promise<ethers.providers.Provider> => {
console.log("chainId - " + chainId)
const url = jsonRpcHttpUrls[chainId];
if (!url) {
throw new FeestimiError("json rpc url not found");
Expand All @@ -79,30 +77,40 @@ const getContract = async (
return new ethers.Contract(address, abi, provider);
};

const blockNumber = async (chainId: number): Promise<Number> => {
const url = jsonRpcHttpUrls[chainId];
if (!url) {
throw new FeestimiError("json rpc url not found");
}

return await eth_blockNumber(url);
}

export {
blockNumber,
getProvider,
getContract,
estimateGas,
callFunction,
};

async function main() {
// way 1
const address = "0x" + ethers.utils.hexlify(
ethers.utils.base58.decode("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t")
).slice(4, 44)
console.log(address);
const abi = ["function totalSupply() external view returns (uint256)"];
const provider = new ethers.providers.JsonRpcProvider("https://api.trongrid.io/jsonrpc");
const usdt = new ethers.Contract(address, abi, provider);
const totalSupply = await usdt.totalSupply();

// // way 2
// const totalSupply = await call(728126428, "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "0x18160ddd")

// // way 3
// const totalSupply = await callFunction(728126428, "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", ["function totalSupply() external view returns (uint256)"], "totalSupply", [])

console.log("usdt total supply on tron: " + totalSupply);
}
// async function main() {
// // way 1
// const address = "0x" + ethers.utils.hexlify(
// ethers.utils.base58.decode("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t")
// ).slice(4, 44)
// console.log(address);
// const abi = ["function totalSupply() external view returns (uint256)"];
// const provider = new ethers.providers.JsonRpcProvider("https://api.trongrid.io/jsonrpc");
// const usdt = new ethers.Contract(address, abi, provider);
// const totalSupply = await usdt.totalSupply();
//
// // // way 2
// // const totalSupply = await call(728126428, "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "0x18160ddd")
//
// // // way 3
// // const totalSupply = await callFunction(728126428, "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", ["function totalSupply() external view returns (uint256)"], "totalSupply", [])
//
// console.log("usdt total supply on tron: " + totalSupply);
// }
// main()
Loading

0 comments on commit a8f345f

Please sign in to comment.