pyth_publisher.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. #!/usr/bin/env python3
  2. from pyth_utils import *
  3. from http.server import HTTPServer, BaseHTTPRequestHandler
  4. from concurrent.futures import ThreadPoolExecutor, as_completed
  5. import json
  6. import os
  7. import random
  8. import sys
  9. import threading
  10. import time
  11. class PythAccEndpoint(BaseHTTPRequestHandler):
  12. """
  13. A dumb endpoint to respond with a JSON containing Pyth symbol and mapping addresses
  14. """
  15. def do_GET(self):
  16. print(f"Got path {self.path}")
  17. sys.stdout.flush()
  18. data = json.dumps(HTTP_ENDPOINT_DATA).encode("utf-8")
  19. print(f"Sending:\n{data}")
  20. self.send_response(200)
  21. self.send_header("Content-Type", "application/json")
  22. self.send_header("Content-Length", str(len(data)))
  23. self.end_headers()
  24. self.wfile.write(data)
  25. self.wfile.flush()
  26. # Test publisher state that gets served via the HTTP endpoint. Note: the schema of this dict is extended here and there
  27. HTTP_ENDPOINT_DATA = {"symbols": [], "mapping_address": None}
  28. def publisher_random_update(price_pubkey):
  29. """
  30. Update the specified price with random values
  31. """
  32. value = random.randrange(1000, 2000)
  33. confidence = random.randrange(1, 10)
  34. pyth_run_or_die("upd_price_val", args=[
  35. price_pubkey, str(value), str(confidence), "trading"
  36. ])
  37. print(f"Price {price_pubkey} value updated to {str(value)}!")
  38. def accounts_endpoint():
  39. """
  40. Run a barebones HTTP server to share the dynamic Pyth
  41. mapping/product/price account addresses
  42. """
  43. server_address = ('', 4242)
  44. httpd = HTTPServer(server_address, PythAccEndpoint)
  45. httpd.serve_forever()
  46. def add_symbol(num: int):
  47. """
  48. NOTE: Updates HTTP_ENDPOINT_DATA
  49. """
  50. symbol_name = f"Test symbol {num}"
  51. # Add a product
  52. prod_pubkey = pyth_admin_run_or_die(
  53. "add_product", capture_output=True).stdout.strip()
  54. print(f"{symbol_name}: Added product {prod_pubkey}")
  55. # Add a price
  56. price_pubkey = pyth_admin_run_or_die(
  57. "add_price",
  58. args=[prod_pubkey, "price"],
  59. capture_output=True
  60. ).stdout.strip()
  61. print(f"{symbol_name}: Added price {price_pubkey}")
  62. # Become a publisher for the new price
  63. pyth_admin_run_or_die(
  64. "add_publisher", args=[publisher_pubkey, price_pubkey],
  65. debug=True,
  66. capture_output=True)
  67. print(f"{symbol_name}: Added publisher {publisher_pubkey}")
  68. # Update the prices as the newly added publisher
  69. publisher_random_update(price_pubkey)
  70. sym = {
  71. "name": symbol_name,
  72. "product": prod_pubkey,
  73. "price": price_pubkey
  74. }
  75. HTTP_ENDPOINT_DATA["symbols"].append(sym)
  76. sys.stdout.flush()
  77. print(f"New symbol: {num}")
  78. return num
  79. # Fund the publisher
  80. sol_run_or_die("airdrop", [
  81. str(SOL_AIRDROP_AMT),
  82. "--keypair", PYTH_PUBLISHER_KEYPAIR,
  83. "--commitment", "finalized",
  84. ])
  85. # Create a mapping
  86. pyth_admin_run_or_die("init_mapping", capture_output=True)
  87. mapping_addr = sol_run_or_die("address", args=[
  88. "--keypair", PYTH_MAPPING_KEYPAIR
  89. ], capture_output=True).stdout.strip()
  90. HTTP_ENDPOINT_DATA["mapping_addr"] = mapping_addr
  91. print(f"New mapping at {mapping_addr}")
  92. print(f"Creating {PYTH_TEST_SYMBOL_COUNT} test Pyth symbols")
  93. publisher_pubkey = sol_run_or_die("address", args=[
  94. "--keypair", PYTH_PUBLISHER_KEYPAIR
  95. ], capture_output=True).stdout.strip()
  96. with ThreadPoolExecutor(max_workers=PYTH_TEST_SYMBOL_COUNT) as executor:
  97. add_symbol_futures = {executor.submit(add_symbol, sym_id) for sym_id in range(PYTH_TEST_SYMBOL_COUNT)}
  98. for future in as_completed(add_symbol_futures):
  99. print(f"Completed {future.result()}")
  100. print(
  101. f"Mock updates ready to roll. Updating every {str(PYTH_PUBLISHER_INTERVAL_SECS)} seconds")
  102. # Spin off the readiness probe endpoint into a separate thread
  103. readiness_thread = threading.Thread(target=readiness, daemon=True)
  104. # Start an HTTP endpoint for looking up test product/price addresses
  105. http_service = threading.Thread(target=accounts_endpoint, daemon=True)
  106. readiness_thread.start()
  107. http_service.start()
  108. next_new_symbol_id = PYTH_TEST_SYMBOL_COUNT
  109. last_new_sym_added_at = time.monotonic()
  110. with ThreadPoolExecutor() as executor: # Used for async adding of products and prices
  111. while True:
  112. for sym in HTTP_ENDPOINT_DATA["symbols"]:
  113. publisher_random_update(sym["price"])
  114. # Add a symbol if new symbol interval configured
  115. if PYTH_NEW_SYMBOL_INTERVAL_SECS > 0:
  116. # Do it if enough time passed
  117. now = time.monotonic()
  118. if (now - last_new_sym_added_at) >= PYTH_NEW_SYMBOL_INTERVAL_SECS:
  119. executor.submit(add_symbol, next_new_symbol_id) # Returns immediately, runs in background
  120. last_sym_added_at = now
  121. next_new_symbol_id += 1
  122. time.sleep(PYTH_PUBLISHER_INTERVAL_SECS)
  123. sys.stdout.flush()
  124. readiness_thread.join()
  125. http_service.join()