Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/entropy-tester/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
lib
3 changes: 3 additions & 0 deletions apps/entropy-tester/cli/run.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/usr/bin/env node
import { main } from "../dist/index.js";
main();
14 changes: 14 additions & 0 deletions apps/entropy-tester/config.sample.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[
{
"chain-id": "berachain_mainnet",
"interval": "3h"
},
{
"chain-id": "apechain_mainnet",
"interval": "6h"
},
{
"chain-id": "blast",
"interval": "10m"
}
]
1 change: 1 addition & 0 deletions apps/entropy-tester/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { nextjs as default } from "@cprussin/eslint-config";
61 changes: 61 additions & 0 deletions apps/entropy-tester/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{
"name": "@pythnetwork/entropy-tester",
"version": "1.0.0",
"description": "Utility to test entropy provider callbacks",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"files": [
"dist/**/*",
"cli/**/*"
],
"scripts": {
"build": "tsc",
"fix:format": "prettier --write .",
"fix:lint": "eslint --fix .",
"test:format": "prettier --check .",
"test:lint": "eslint . --max-warnings 0",
"test:types": "tsc",
"start": "tsc && node cli/run.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/pyth-network/pyth-crosschain.git",
"directory": "apps/entropy-tester"
},
"bin": {
"pyth-entropy-tester": "./cli/run.js"
},
"devDependencies": {
"@cprussin/eslint-config": "catalog:",
"@cprussin/prettier-config": "catalog:",
"@cprussin/tsconfig": "catalog:",
"@types/express": "^4.17.21",
"@types/yargs": "^17.0.10",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"eslint": "catalog:",
"pino-pretty": "^11.2.1",
"prettier": "catalog:",
"ts-node": "catalog:",
"typescript": "catalog:"
},
"dependencies": {
"@pythnetwork/contract-manager": "workspace:*",
"joi": "^17.6.0",
"pino": "catalog:",
"prom-client": "^15.1.0",
"viem": "catalog:",
"yargs": "^17.5.1",
"zod": "catalog:"
},
"keywords": [],
"author": "",
"license": "Apache-2.0"
}
198 changes: 198 additions & 0 deletions apps/entropy-tester/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
import fs from "node:fs/promises";

import type { PrivateKey } from "@pythnetwork/contract-manager/core/base";
import { toPrivateKey } from "@pythnetwork/contract-manager/core/base";
import { EvmEntropyContract } from "@pythnetwork/contract-manager/core/contracts/evm";
import { DefaultStore } from "@pythnetwork/contract-manager/node/store";
import type { Logger } from "pino";
import { pino } from "pino";
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
import { z } from "zod";

type LoadedConfig = {
contract: EvmEntropyContract;
interval: number;
};

function timeToSeconds(timeStr: string): number {
const match = /^(\d+)([hms])$/i.exec(timeStr);
if (!match?.[1] || !match[2])
throw new Error("Invalid format. Use formats like '6h', '15m', or '30s'.");

const value = Number.parseInt(match[1], 10);
const unit = match[2].toLowerCase();

switch (unit) {
case "h": {
return value * 3600;
}
case "m": {
return value * 60;
}
case "s": {
return value;
}
default: {
throw new Error("Unsupported time unit.");
}
}
}

async function loadConfig(configPath: string): Promise<LoadedConfig[]> {
const configSchema = z.array(
z.strictObject({
"chain-id": z.string(),
interval: z.string(),
}),
);
const configContent = (await import(configPath, {
with: { type: "json" },
})) as { default: string };
const configs = configSchema.parse(configContent.default);
const loadedConfigs = configs.map((config) => {
const interval = timeToSeconds(config.interval);
const contracts = Object.values(DefaultStore.entropy_contracts).filter(
(contract) => contract.chain.getId() == config["chain-id"],
);
const firstContract = contracts[0];
if (contracts.length === 0 || !firstContract) {
throw new Error(
`Can not find the contract for chain ${config["chain-id"]}, check contract manager store.`,
);
}
if (contracts.length > 1) {
throw new Error(
`Multiple contracts found for chain ${config["chain-id"]}, check contract manager store.`,
);
}
return { contract: firstContract, interval };
});
return loadedConfigs;
}

async function testLatency(
contract: EvmEntropyContract,
privateKey: PrivateKey,
logger: Logger,
) {
const provider = await contract.getDefaultProvider();
const userRandomNumber = contract.generateUserRandomNumber();
const requestResponseSchema = z.object({
transactionHash: z.string(),
events: z.object({
RequestedWithCallback: z.object({
returnValues: z.object({
sequenceNumber: z.string(),
}),
}),
}),
});
const requestResponse = requestResponseSchema.parse(
await contract.requestRandomness(
userRandomNumber,
provider,
privateKey,
true, // with callback
),
);
// Read the sequence number for the request from the transaction events.
const sequenceNumber = Number.parseInt(
requestResponse.events.RequestedWithCallback.returnValues.sequenceNumber,
);
logger.info(
{ sequenceNumber, txHash: requestResponse.transactionHash },
`Request submitted`,
);

const startTime = Date.now();

// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
while (true) {
await new Promise((resolve) => setTimeout(resolve, 2000));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't do this, but for your entertainment, if you want some very esoteric node facts, you can actually do this:

import { promisify } from "util";

await promisify(setTimeout)(2000);

You wouldn't expect it to work due to the argument order of setTimeout, but this works because of some absolutely wild Node internals where the promisify function actually can return a completely separate implementation which is defined in the Node lib internals.

const request = await contract.getRequest(provider, sequenceNumber);
logger.debug(request);

if (Number.parseInt(request.sequenceNumber) === 0) {
// 0 means the request is cleared
const endTime = Date.now();
logger.info(
{ sequenceNumber, latency: endTime - startTime },
`Successful callback`,
);
break;
}
if (Date.now() - startTime > 60_000) {
logger.error(
{ sequenceNumber },
"Timeout: 60s passed without the callback being called",
);
break;
}
}
}

const RUN_OPTIONS = {
validate: {
description: "Only validate the configs and exit",
type: "boolean",
default: false,
required: false,
},
config: {
description: "Yaml config file",
type: "string",
required: true,
},
"private-key": {
type: "string",
required: true,
description:
"Path to the private key to sign the transactions with. Should be hex encoded",
},
} as const;

export const main = function () {
yargs(hideBin(process.argv))
.parserConfiguration({
"parse-numbers": false,
})
.command(
"run",
"run the tester until manually stopped",
RUN_OPTIONS,
async (argv) => {
const logger = pino();
const configs = await loadConfig(argv.config);
if (argv.validate) {
logger.info("Config validated");
return;
}
const privateKeyFileContent = await fs.readFile(
argv["private-key"],
"utf8",
);
const privateKey = toPrivateKey(
privateKeyFileContent.replace("0x", "").trimEnd(),
);
logger.info("Running");
const promises = configs.map(async ({ contract, interval }) => {
const child = logger.child({ chain: contract.chain.getId() });
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
while (true) {
try {
await testLatency(contract, privateKey, child);
} catch (error) {
child.error(error, "Error testing latency");
}
await new Promise((resolve) =>
setTimeout(resolve, interval * 1000),
);
}
});
await Promise.all(promises);
},
)
.demandCommand()
.help();
};
5 changes: 5 additions & 0 deletions apps/entropy-tester/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": "@cprussin/tsconfig/nextjs.json",
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest using my canned tsconfig as a base here, as that will enable a lot of much stricter configs which make the type system much more reliable / trustworthy. You can use it like this if you decide to do so

Loading
Loading