latency_entropy_with_callback.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import yargs from "yargs";
  2. import { hideBin } from "yargs/helpers";
  3. import { toPrivateKey } from "../src";
  4. import {
  5. COMMON_DEPLOY_OPTIONS,
  6. findEntropyContract,
  7. findEvmChain,
  8. } from "./common";
  9. import Web3 from "web3";
  10. const parser = yargs(hideBin(process.argv))
  11. .usage(
  12. "Requests a random number from an entropy contract and measures the\n" +
  13. "latency between request submission and fulfillment by the Fortuna keeper service.\n" +
  14. "Usage: $0 --chain-id <chain-id> --private-key <private-key>"
  15. )
  16. .options({
  17. chain: {
  18. type: "string",
  19. demandOption: true,
  20. desc: "test latency for the contract on this chain",
  21. },
  22. "private-key": COMMON_DEPLOY_OPTIONS["private-key"],
  23. });
  24. async function main() {
  25. const argv = await parser.argv;
  26. const chain = findEvmChain(argv.chain);
  27. const contract = findEntropyContract(chain);
  28. const provider = await contract.getDefaultProvider();
  29. const userRandomNumber = contract.generateUserRandomNumber();
  30. const privateKey = toPrivateKey(argv.privateKey);
  31. const requestResponse = await contract.requestRandomness(
  32. userRandomNumber,
  33. provider,
  34. privateKey,
  35. true // with callback
  36. );
  37. console.log(`Request tx hash : ${requestResponse.transactionHash}`);
  38. // Read the sequence number for the request from the transaction events.
  39. const sequenceNumber =
  40. requestResponse.events.RequestedWithCallback.returnValues.sequenceNumber;
  41. console.log(`sequence : ${sequenceNumber}`);
  42. const startTime = Date.now();
  43. let fromBlock = requestResponse.blockNumber;
  44. const web3 = new Web3(contract.chain.getRpcUrl());
  45. const entropyContract = contract.getContract();
  46. // eslint-disable-next-line no-constant-condition
  47. while (true) {
  48. const currentBlock = await web3.eth.getBlockNumber();
  49. if (fromBlock > currentBlock) {
  50. continue;
  51. }
  52. const events = await entropyContract.getPastEvents("RevealedWithCallback", {
  53. fromBlock: fromBlock,
  54. toBlock: currentBlock,
  55. });
  56. fromBlock = currentBlock + 1;
  57. const event = events.find(
  58. (event) => event.returnValues.request[1] == sequenceNumber
  59. );
  60. if (event !== undefined) {
  61. console.log(`Random number : ${event.returnValues.randomNumber}`);
  62. const endTime = Date.now();
  63. console.log(`Fortuna Latency : ${endTime - startTime}ms`);
  64. console.log(
  65. `Revealed after : ${
  66. currentBlock - requestResponse.blockNumber
  67. } blocks`
  68. );
  69. break;
  70. }
  71. await new Promise((resolve) => setTimeout(resolve, 300));
  72. }
  73. }
  74. main();