-
Notifications
You must be signed in to change notification settings - Fork 305
Entropy tester #2762
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Entropy tester #2762
Changes from 8 commits
f424e89
97e9fcc
91d8de3
b3a9394
e229136
3adf992
d478132
0d7f6fa
cd2b56e
7b805e8
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| lib |
| 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(); |
| 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" | ||
| } | ||
| ] |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export { nextjs as default } from "@cprussin/eslint-config"; |
| 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" | ||
| } |
| 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[] }; | ||
| 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 }; | ||
|
||
| }); | ||
| 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; | ||
| }; | ||
| }; | ||
| }; | ||
| }; | ||
|
||
| // 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)); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
| 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>>, | ||
|
||
| ) => { | ||
| 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(); | ||
| }; | ||
| 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"], | ||
|
||
| "exclude": ["node_modules"] | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
There was a problem hiding this comment.
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: