Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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";
60 changes: 60 additions & 0 deletions apps/entropy-tester/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
{
"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"
},
"keywords": [],
"author": "",
"license": "Apache-2.0"
}
194 changes: 194 additions & 0 deletions apps/entropy-tester/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
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 type { ArgumentsCamelCase, InferredOptionTypes } from "yargs";
import yargs from "yargs";
import { hideBin } from "yargs/helpers";

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.");
}
}
}

type ParsedConfig = {
"chain-id": string;
interval: string;
};

async function loadConfig(configPath: string): Promise<LoadedConfig[]> {
const configs = (await import(configPath, {
with: { type: "json" },
})) as { default: ParsedConfig[] };
Copy link
Collaborator

Choose a reason for hiding this comment

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

For all the same reasons you use serde to deserialize in Rust and you don't just unsafe cast external data, we should also avoid typecasting in typescript and should instead validate the schema using zod: https://v3.zod.dev/ (note we still use v3 everywhere in the monorepo but you're welcome to try v4 if you want). This would look basically like this:

const configSchema = z.array(z.strictObject({
  "chain-id": z.string(),
  interval: z.string(),
}));

// ...

const configs = configSchema.parse(
  (await import(configPath, { with: { type: 'json' } })).default
);

const loadedConfigs = configs.default.map((config) => {
const interval = timeToSeconds(config.interval);
const contracts = Object.values(DefaultStore.entropy_contracts).filter(
(contract) => contract.chain.getId() == config["chain-id"],
);
if (contracts.length === 0 || !contracts[0]) {
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: contracts[0], interval };
Copy link
Collaborator

Choose a reason for hiding this comment

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

Marginally better here is to store contracts[0] in a variable and reuse that:

const firstContract = contracts[0];

if (contracts.length === 0 || !firstContract) {
  /* ... */
} else if (contracts.length > 1) {
  /* ... */
} else {
  return { contract: firstContract, interval }
}

The reason this is preferable is that typescript can guarantee statically with this code that firstContract is not undefined in the return branch, but it cannot guarantee the same with contracts[0] due to how typescript narrowing is designed.

});
return loadedConfigs;
}

async function testLatency(
contract: EvmEntropyContract,
privateKey: PrivateKey,
logger: Logger,
) {
const provider = await contract.getDefaultProvider();
const userRandomNumber = contract.generateUserRandomNumber();
const requestResponse = (await contract.requestRandomness(
userRandomNumber,
provider,
privateKey,
true, // with callback
)) as {
transactionHash: string;
events: {
RequestedWithCallback: {
returnValues: {
sequenceNumber: string;
};
};
};
};
Copy link
Collaborator

Choose a reason for hiding this comment

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

Same comment -- don't typecast, instead parse with zod. Typecasting is unsafe and it breaks all the type safety the type checker attempts to provide.

// 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({
command: "run",
describe: "run the tester until manually stopped",
builder: RUN_OPTIONS,
handler: async (
argv: ArgumentsCamelCase<InferredOptionTypes<typeof RUN_OPTIONS>>,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Hmm yargs should be able to infer this type automatically, are you not finding that to be the case?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

correct

) => {
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": ["svg.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
Copy link
Collaborator

Choose a reason for hiding this comment

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

You should remove the first and last option here give you aren't in a next app so there's no .next folder at all, and you have no svgs so the first one doesn't make sense

"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