Skip to content

Commit

Permalink
chore: refactor functions & prometheus logs
Browse files Browse the repository at this point in the history
  • Loading branch information
DenisCarriere committed Jun 13, 2023
1 parent 93b71a9 commit 2703563
Show file tree
Hide file tree
Showing 19 changed files with 139 additions and 114 deletions.
5 changes: 3 additions & 2 deletions bin/claim.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createSession, explorer } from "../src/config.js";
import * as actions from "../src/actions.js";
import { createSession } from "../src/createSession.js";
import { getExplorer } from "../src/getExplorer.js";
import { balances } from "../src/tables.js";
import { type DefaultOptions } from "./cli.js"

Expand All @@ -16,7 +17,7 @@ export async function claim(options: DefaultOptions) {
const action = actions.withdraw(session, balance);
const response = await session.transact({action})
const trx_id = response.response?.transaction_id;
console.log(`${session.actor.toString()} claimed ${balance} ${explorer(session, trx_id)}`);
console.log(`${session.actor.toString()} claimed ${balance} ${getExplorer(session, trx_id)}`);
} else {
console.log(`${session.actor.toString()} has no balance to claim`);
}
Expand Down
4 changes: 2 additions & 2 deletions bin/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,6 @@ export interface DefaultOptions {
function defaultOptions(command: Command) {
return command
.option('--private-key <string>', 'Miner private key (ex: "PVT_K1_...")')
.option('--account <string>', 'Miner account name (ex: "miner.evm")')
.option('--permission <string>', 'Miner permission', DEFAULT_MINER_PERMISSION)
.option('--actor <string>', 'Miner account name (ex: "miner.enf")')
.option(`--permission <string>', 'Miner permission (ex: ${DEFAULT_MINER_PERMISSION})`)
}
5 changes: 3 additions & 2 deletions bin/open.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createSession, explorer } from "../src/config.js";
import * as actions from "../src/actions.js";
import { createSession } from "../src/createSession.js";
import { getExplorer } from "../src/getExplorer.js";
import { balances } from "../src/tables.js";
import { type DefaultOptions } from "./cli.js"

Expand All @@ -15,7 +16,7 @@ export async function open(options: DefaultOptions) {
const action = actions.open(session);
const response = await session.transact({action})
const trx_id = response.response?.transaction_id;
console.log(`${session.actor.toString()} balance opened ${explorer(session, trx_id)}`);
console.log(`${session.actor.toString()} balance opened ${getExplorer(session, trx_id)}`);
} else {
console.log(`${session.actor.toString()} balance is already opened`);
}
Expand Down
5 changes: 3 additions & 2 deletions bin/powerup.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createSession, explorer } from "../src/config.js";
import * as actions from "../src/actions.js";
import { createSession } from "../src/createSession.js";
import { getExplorer } from "../src/getExplorer.js";
import { type DefaultOptions } from "./cli.js"

export interface PowerupOptions extends DefaultOptions {
Expand All @@ -16,5 +17,5 @@ export async function powerup(net_frac: string, cpu_frac: string, max_payment: s
const action = actions.powerup(session, net_frac, cpu_frac, max_payment);
const response = await session.transact({action})
const trx_id = response.response?.transaction_id;
console.log(`${session.actor.toString()} powerup success ${explorer(session, trx_id)}`);
console.log(`${session.actor.toString()} powerup success ${getExplorer(session, trx_id)}`);
}
45 changes: 18 additions & 27 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import { JSONRPCClient, JSONRPCResponse, JSONRPCServer } from "json-rpc-2.0";
import { JSONRPCServer } from "json-rpc-2.0";
import { Session } from "@wharfkit/session";
import { DEFAULT_HOSTNAME, HOSTNAME, LOCK_GAS_PRICE, PORT,PROMETHEUS_PORT, createSession, METRICS_DISABLED, VERBOSE, LOCK_CHAIN_ID, LOCK_GENESIS_TIME, RPC_EVM_ENDPOINT, RPC_ENDPOINT } from "./src/config.js";
import { DEFAULT_HOSTNAME, HOSTNAME, LOCK_GAS_PRICE, PORT,PROMETHEUS_PORT, METRICS_DISABLED, VERBOSE, LOCK_CHAIN_ID, LOCK_GENESIS_TIME, RPC_EVM_ENDPOINT } from "./src/config.js";
import { logger } from "./src/logger.js";
import { DefaultOptions } from "./bin/cli.js";
import * as prometheus from "./src/prometheus.js"
import { eth_sendRawTransaction } from "./src/eth_sendRawTransaction.js";
import { eth_gasPrice } from "./src/eth_gasPrice.js";
import { eth_chainId } from "./src/eth_chainId.js";
import { eth_blockNumber } from "./src/eth_blockNumber.js";
import * as prometheus from "./src/prometheus.js"
import { eth_getBalance } from "./src/eth_getBalance.js";
import { net_version } from "./src/net_version.js";
import { eth_getCode } from "./src/eth_getCode.js";
import { createSession } from "./src/createSession.js";
import { createClient } from "./src/createClient.js";

export interface StartOptions extends DefaultOptions {
port?: number;
Expand All @@ -35,24 +37,13 @@ export default function (options: StartOptions) {
const lockGenesisTime = options.lockGenesisTime ?? LOCK_GENESIS_TIME;
const verbose = options.verbose ?? VERBOSE;
const rpcEvmEndpoint = options.rpcEvmEndpoint ?? RPC_EVM_ENDPOINT;
const rpcEndpoint = options.rpcEndpoint ?? RPC_ENDPOINT;

// create Wharfkit session
const session = createSession(options);

// JSON RPC server & client
const server = new JSONRPCServer();
const client: JSONRPCClient<void> = new JSONRPCClient(async jsonRPCRequest => {
const response = await fetch(rpcEvmEndpoint, {
method: "POST",
headers: { "content-type": "application/json"},
body: JSON.stringify(jsonRPCRequest),
});
if ( jsonRPCRequest.id !== undefined ) new Error(response.statusText);
if ( response.status !== 200) new Error(response.statusText);
const jsonRPCResponse: JSONRPCResponse = await response.json();
return client.receive(jsonRPCResponse);
});
const client = createClient(rpcEvmEndpoint);

// enable logging if verbose enabled
if (verbose) {
Expand All @@ -61,36 +52,36 @@ export default function (options: StartOptions) {
}

server.addMethod("eth_sendRawTransaction", async params => {
prometheus.sendRawTransaction.requests?.inc();
prometheus.eth_sendRawTransaction.requests?.inc();
const result = await eth_sendRawTransaction(session, params)
prometheus.sendRawTransaction.success?.inc();
prometheus.eth_sendRawTransaction.success?.inc();
return result;
});
server.addMethod("eth_gasPrice", async () => {
prometheus.gasPrice.requests?.inc();
prometheus.eth_gasPrice.requests?.inc();
const result = await eth_gasPrice(session, lockGasPrice)
prometheus.gasPrice.success?.inc();
prometheus.eth_gasPrice.success?.inc();
return result;
});
server.addMethod("eth_chainId", async () => {
logger.info("eth_chainId");
prometheus.chainId.requests?.inc();
prometheus.eth_chainId.requests?.inc();
const result = await eth_chainId(session, lockChainId)
prometheus.chainId.success?.inc();
prometheus.eth_chainId.success?.inc();
return result;
});
server.addMethod("eth_blockNumber", async () => {
logger.info("eth_blockNumber");
prometheus.blockNumber.requests?.inc();
prometheus.eth_blockNumber.requests?.inc();
const result = await eth_blockNumber(session, lockGenesisTime)
prometheus.blockNumber.success?.inc();
prometheus.eth_blockNumber.success?.inc();
return result;
});
server.addMethod("eth_getBalance", async params => {
logger.info("eth_getBalance");
prometheus.blockNumber.requests?.inc();
prometheus.eth_getBalance.requests?.inc();
const result = await eth_getBalance(session, params)
prometheus.blockNumber.success?.inc();
prometheus.eth_getBalance.success?.inc();
return result;
});
server.addMethod("net_version", async () => {
Expand All @@ -102,9 +93,9 @@ export default function (options: StartOptions) {
});
server.addMethod("eth_getCode", async params => {
logger.info("eth_getCode");
prometheus.blockNumber.requests?.inc();
prometheus.eth_getCode.requests?.inc();
const result = await eth_getCode(session, params)
prometheus.blockNumber.success?.inc();
prometheus.eth_getCode.success?.inc();
return result;
});
// Proxied - Move to internal
Expand Down
57 changes: 4 additions & 53 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { ChainDefinitionType, Session } from "@wharfkit/session";
import { WalletPluginPrivateKey } from "@wharfkit/wallet-plugin-privatekey";
import "dotenv/config";

// defaults
Expand All @@ -22,61 +20,14 @@ export const PROMETHEUS_PORT = parseInt(process.env.PROMETHEUS_PORT ?? String(DE
export const LOCK_GAS_PRICE = process.env.LOCK_GAS_PRICE;
export const LOCK_CHAIN_ID = process.env.LOCK_CHAIN_ID ?? DEFAULT_LOCK_CHAIN_ID;
export const LOCK_GENESIS_TIME = process.env.LOCK_GENESIS_TIME ?? DEFAULT_LOCK_GENESIS_TIME;
export const MINER_PERMISSION = process.env.MINER_PERMISSION ?? DEFAULT_MINER_PERMISSION;
export const CHAIN_ID = process.env.CHAIN_ID ?? DEFAULT_CHAIN_ID;
export const RPC_ENDPOINT = process.env.RPC_ENDPOINT ?? DEFAULT_RPC_ENDPOINT;
export const RPC_EVM_ENDPOINT = process.env.RPC_EVM_ENDPOINT ?? DEFAULT_RPC_EVM_ENDPOINT;
export const HOSTNAME = process.env.HOSTNAME;
export const METRICS_DISABLED = JSON.parse(process.env.METRICS_DISABLED ?? String(DEFAULT_METRICS_DISABLED)) as boolean;
export const VERBOSE = JSON.parse(process.env.VERBOSE ?? String(DEFAULT_VERBOSE)) as boolean;

interface CreateSessionOptions {
privateKey?: string;
actor?: string;
permission?: string;
chain?: ChainDefinitionType;
}

export function createSession(options: CreateSessionOptions = {}) {
// required
const actor = options.actor ?? process.env.MINER_ACCOUNT;
if (!actor) throw new Error('actor is required (env=MINER_ACCOUNT)');
const privateKey = options.privateKey ?? process.env.PRIVATE_KEY;
if (!privateKey) throw new Error('privateKey is required (env=PRIVATE_KEY)');

// optional
const permission = options.permission ?? process.env.MINER_PERMISSION ?? "active"
const chain = options.chain ?? {
id: CHAIN_ID,
url: RPC_ENDPOINT,
}

return new Session({
chain,
actor,
permission,
walletPlugin: new WalletPluginPrivateKey(privateKey),
})
}

export function getChain(session: Session) {
if ( session.chain.id.equals("aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906") ) return "eos";
if ( session.chain.id.equals("73e4385a2708e6d7048834fbc1079f2fabb17b3c125b146af438971e90716c4d") ) return "jungle4";
if ( session.chain.id.equals("5fff1dae8dc8e2fc4d5b23b2c7665c97f9e9d8edf2b6485a86ba311c25639191") ) return "kylin";
if ( session.chain.id.equals("1064487b3cd1a897ce03ae5b6a865651747e2e152090f99c1d19d44e01aea5a4") ) return "wax";
if ( session.chain.id.equals("f16b1833c747c43682f4386fca9cbb327929334a762755ebec17f6f23c9b8a12") ) return "waxtest";
if ( session.chain.id.equals("4667b205c6838ef70ff7988f6e8257e8be0e1284a2f59699054a018f743b1d11") ) return "telos";
if ( session.chain.id.equals("1eaa0824707c8c16bd25145493bf062aecddfeb56c736f6ba6397f3195f33c9f") ) return "telostest";
if ( session.chain.id.equals("8fc6dce7942189f842170de953932b1f66693ad3788f766e777b6f9d22335c02") ) return "ux";
return null;
}


export function explorer(session: Session, trx_id: string) {
const chain = getChain(session);
if (!chain) return trx_id;;
if (["eos", "wax", "jungle4", "kylin"].includes(chain)) return `https://${chain}.eosq.eosnation.io/tx/${trx_id}`;
if (["telos"].includes(chain)) return `https://explorer.telos.net/transaction/${trx_id}`;
if (["ux"].includes(chain)) return `https://explorer.uxnetwork.io/tx/${trx_id}`;
return trx_id;
}
// Miner details
export const MINER_PERMISSION = process.env.MINER_PERMISSION ?? process.env.PERMISSION ?? DEFAULT_MINER_PERMISSION;
export const MINER_PRIVATE_KEY = process.env.MINER_PRIVATE_KEY ?? process.env.PRIVATE_KEY;
export const MINER_ACCOUNT = process.env.MINER_ACCOUNT ?? process.env.ACTOR;
16 changes: 16 additions & 0 deletions src/createClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { JSONRPCClient, JSONRPCResponse } from "json-rpc-2.0";

export function createClient(rpcEvmEndpoint: string) {
const client = new JSONRPCClient(async jsonRPCRequest => {
const response = await fetch(rpcEvmEndpoint, {
method: "POST",
headers: { "content-type": "application/json"},
body: JSON.stringify(jsonRPCRequest),
});
if ( jsonRPCRequest.id !== undefined ) new Error(response.statusText);
if ( response.status !== 200) new Error(response.statusText);
const jsonRPCResponse: JSONRPCResponse = await response.json();
client.receive(jsonRPCResponse);
});
return client;
};
31 changes: 31 additions & 0 deletions src/createSession.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { ChainDefinitionType, Session } from "@wharfkit/session";
import { CHAIN_ID, MINER_PERMISSION, RPC_ENDPOINT, MINER_ACCOUNT } from "./config.js";
import { WalletPluginPrivateKey } from "@wharfkit/wallet-plugin-privatekey";
import { DefaultOptions } from "../bin/cli.js";

interface CreateSessionOptions extends DefaultOptions {
chain?: ChainDefinitionType;
rpcEndpoint?: string;
}

export function createSession(options: CreateSessionOptions) {
// required
const actor = options.actor ?? MINER_ACCOUNT;
const privateKey = options.privateKey ?? process.env.PRIVATE_KEY;
if (!actor) throw new Error('--actor is required (env=ACTOR)');
if (!privateKey) throw new Error('--privateKey is required (env=PRIVATE_KEY)');

// optional
const permission = options.permission ?? MINER_PERMISSION;
const chain = options.chain ?? {
id: CHAIN_ID,
url: options.rpcEndpoint ?? RPC_ENDPOINT,
}

return new Session({
chain,
actor,
permission,
walletPlugin: new WalletPluginPrivateKey(privateKey),
})
}
2 changes: 1 addition & 1 deletion src/eth_blockNumber.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import assert from "node:assert";
import { eth_blockNumber } from "./eth_blockNumber.js"
import { PrivateKey } from "@wharfkit/session";
import { createSession } from "./config.js";
import { test } from "bun:test";
import { createSession } from "./createSession.js";

// start the miner
const session = createSession({
Expand Down
2 changes: 1 addition & 1 deletion src/eth_chainId.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import assert from "node:assert";
import { eth_chainId } from "./eth_chainId.js"
import { PrivateKey } from "@wharfkit/session";
import { createSession } from "./config.js";
import { test } from "bun:test";
import { createSession } from "./createSession.js";

// start the miner
const session = createSession({
Expand Down
2 changes: 1 addition & 1 deletion src/eth_estimateGas.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import assert from "node:assert";
import { eth_gasPrice } from "./eth_gasPrice.js"
import { PrivateKey } from "@wharfkit/session";
import { createSession } from "./config.js";
import { test } from "bun:test";
import { createSession } from "./createSession.js";

// start the miner
const session = createSession({
Expand Down
2 changes: 1 addition & 1 deletion src/eth_gasPrice.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import assert from "node:assert";
import { eth_gasPrice } from "./eth_gasPrice.js"
import { PrivateKey } from "@wharfkit/session";
import { createSession } from "./config.js";
import { test } from "bun:test";
import { createSession } from "./createSession.js";

// start the miner
const session = createSession({
Expand Down
2 changes: 1 addition & 1 deletion src/eth_getBalance.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import assert from "node:assert";
import { eth_getBalance } from "./eth_getBalance.js"
import { PrivateKey } from "@wharfkit/session";
import { createSession } from "./config.js";
import { test } from "bun:test";
import { createSession } from "./createSession.js";

// start the miner
const session = createSession({
Expand Down
2 changes: 1 addition & 1 deletion src/eth_getCode.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import assert from "node:assert";
import { eth_getCode } from "./eth_getCode.js"
import { PrivateKey } from "@wharfkit/session";
import { createSession } from "./config.js";
import { test } from "bun:test";
import { createSession } from "./createSession.js";

// start the miner
const session = createSession({
Expand Down
2 changes: 1 addition & 1 deletion src/eth_sendRawTransaction.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { test } from "bun:test";
import assert from "node:assert";
import { eth_sendRawTransaction } from "./eth_sendRawTransaction.js"
import { PrivateKey } from "@wharfkit/session";
import { createSession } from "./config.js";
import { createSession } from "./createSession.js";

// start the miner
const session = createSession({
Expand Down
13 changes: 13 additions & 0 deletions src/getChain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Session } from "@wharfkit/session";

export function getChain(session: Session) {
if ( session.chain.id.equals("aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906") ) return "eos";
if ( session.chain.id.equals("73e4385a2708e6d7048834fbc1079f2fabb17b3c125b146af438971e90716c4d") ) return "jungle4";
if ( session.chain.id.equals("5fff1dae8dc8e2fc4d5b23b2c7665c97f9e9d8edf2b6485a86ba311c25639191") ) return "kylin";
if ( session.chain.id.equals("1064487b3cd1a897ce03ae5b6a865651747e2e152090f99c1d19d44e01aea5a4") ) return "wax";
if ( session.chain.id.equals("f16b1833c747c43682f4386fca9cbb327929334a762755ebec17f6f23c9b8a12") ) return "waxtest";
if ( session.chain.id.equals("4667b205c6838ef70ff7988f6e8257e8be0e1284a2f59699054a018f743b1d11") ) return "telos";
if ( session.chain.id.equals("1eaa0824707c8c16bd25145493bf062aecddfeb56c736f6ba6397f3195f33c9f") ) return "telostest";
if ( session.chain.id.equals("8fc6dce7942189f842170de953932b1f66693ad3788f766e777b6f9d22335c02") ) return "ux";
return null;
}
11 changes: 11 additions & 0 deletions src/getExplorer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Session } from "@wharfkit/session";
import { getChain } from "./getChain.js";

export function getExplorer(session: Session, trx_id: string) {
const chain = getChain(session);
if (!chain) return trx_id;;
if (["eos", "wax", "jungle4", "kylin"].includes(chain)) return `https://${chain}.eosq.eosnation.io/tx/${trx_id}`;
if (["telos"].includes(chain)) return `https://explorer.telos.net/transaction/${trx_id}`;
if (["ux"].includes(chain)) return `https://explorer.uxnetwork.io/tx/${trx_id}`;
return trx_id;
}
2 changes: 1 addition & 1 deletion src/net_version.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import assert from "node:assert";
import { net_version } from "./net_version.js"
import { PrivateKey } from "@wharfkit/session";
import { createSession } from "./config.js";
import { test } from "bun:test";
import { createSession } from "./createSession.js";

// start the miner
const session = createSession({
Expand Down
Loading

0 comments on commit 2703563

Please sign in to comment.