-
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
Merged
Merged
Entropy tester #2762
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
f424e89
feat(entropy-tester): Init
m30m 97e9fcc
handle multiple chains
m30m 91d8de3
typo
m30m b3a9394
polish
m30m e229136
prettier
m30m 3adf992
fixed some of the issues
m30m d478132
fix
m30m 0d7f6fa
fix
m30m cd2b56e
more fix
m30m 7b805e8
last fix
m30m File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| lib |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export { nextjs as default } from "@cprussin/eslint-config"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); | ||
| 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(); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"] | ||
| } | ||
|
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 |
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Don't do this, but for your entertainment, if you want some very esoteric node facts, you can actually do this:
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 thepromisifyfunction actually can return a completely separate implementation which is defined in the Node lib internals.