index.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* eslint-disable no-console */
  2. /* eslint-disable @typescript-eslint/no-empty-function */
  3. import { PythLazerClient } from "../src/index.js";
  4. // Ignore debug messages
  5. console.debug = () => {};
  6. const client = await PythLazerClient.create(
  7. ["wss://pyth-lazer.dourolabs.app/v1/stream"],
  8. "access_token",
  9. 3, // Optionally specify number of parallel redundant connections to reduce the chance of dropped messages. The connections will round-robin across the provided URLs. Default is 3.
  10. console // Optionally log socket operations (to the console in this case.)
  11. );
  12. // Read and process messages from the Lazer stream
  13. client.addMessageListener((message) => {
  14. console.info("got message:", message);
  15. switch (message.type) {
  16. case "json": {
  17. if (message.value.type == "streamUpdated") {
  18. console.info(
  19. "stream updated for subscription",
  20. message.value.subscriptionId,
  21. ":",
  22. message.value.parsed?.priceFeeds
  23. );
  24. }
  25. break;
  26. }
  27. case "binary": {
  28. if ("solana" in message.value) {
  29. console.info("solana message:", message.value.solana?.toString("hex"));
  30. }
  31. if ("evm" in message.value) {
  32. console.info("evm message:", message.value.evm?.toString("hex"));
  33. }
  34. break;
  35. }
  36. }
  37. });
  38. // Monitor for all connections in the pool being down simultaneously (e.g. if the internet goes down)
  39. // The connections may still try to reconnect in the background. To shut down the client completely, call shutdown().
  40. client.addAllConnectionsDownListener(() => {
  41. console.error("All connections are down!");
  42. });
  43. // Create and remove one or more subscriptions on the fly
  44. await client.subscribe({
  45. type: "subscribe",
  46. subscriptionId: 1,
  47. priceFeedIds: [1, 2],
  48. properties: ["price"],
  49. chains: ["solana"],
  50. deliveryFormat: "binary",
  51. channel: "fixed_rate@200ms",
  52. parsed: false,
  53. jsonBinaryEncoding: "base64",
  54. });
  55. await client.subscribe({
  56. type: "subscribe",
  57. subscriptionId: 2,
  58. priceFeedIds: [1, 2, 3, 4, 5],
  59. properties: ["price", "exponent", "publisherCount"],
  60. chains: ["evm"],
  61. deliveryFormat: "json",
  62. channel: "fixed_rate@200ms",
  63. parsed: true,
  64. jsonBinaryEncoding: "hex",
  65. });
  66. await new Promise((resolve) => setTimeout(resolve, 10_000));
  67. await client.unsubscribe(1);
  68. await client.unsubscribe(2);
  69. client.shutdown();