|
| 1 | +import asyncio |
| 2 | +from typing import Any, Dict |
| 3 | + |
| 4 | +from grpc import RpcError |
| 5 | + |
| 6 | +from pyinjective.async_client_v2 import AsyncClient |
| 7 | +from pyinjective.core.network import Network |
| 8 | + |
| 9 | +ORACLE_TYPE = "chainlinkdatastreams" |
| 10 | +ORACLE_SYMBOLS = { |
| 11 | + "INJ": "0x000344d7a7d81f051ee273a63f94f8bef7d44ca89aa03e0c5bf4d085df19adb6", |
| 12 | + "USDC": "0x00038f83323b6b08116d1614cf33a9bd71ab5e0abf0c9f1b783a74a43e7bd992", |
| 13 | +} |
| 14 | + |
| 15 | + |
| 16 | +async def oracle_price_event_processor(event: Dict[str, Any]): |
| 17 | + for oracle_price in event.get("oraclePrices", []): |
| 18 | + print( |
| 19 | + { |
| 20 | + "blockHeight": event["blockHeight"], |
| 21 | + "blockTime": event["blockTime"], |
| 22 | + **oracle_price, |
| 23 | + } |
| 24 | + ) |
| 25 | + |
| 26 | + |
| 27 | +def stream_error_processor(exception: RpcError): |
| 28 | + print(f"There was an error listening to oracle price updates ({exception})") |
| 29 | + |
| 30 | + |
| 31 | +def stream_closed_processor(): |
| 32 | + print("The oracle price updates stream has been closed") |
| 33 | + |
| 34 | + |
| 35 | +async def main() -> None: |
| 36 | + network = Network.mainnet() |
| 37 | + |
| 38 | + client = AsyncClient(network) |
| 39 | + composer = await client.composer() |
| 40 | + |
| 41 | + print(f"Streaming {ORACLE_TYPE} prices for {', '.join(ORACLE_SYMBOLS)}") |
| 42 | + # To receive all oracle price updates, use composer.chain_stream_oracle_price_filter() without symbols. |
| 43 | + oracle_price_filter = composer.chain_stream_oracle_price_filter(symbols=list(ORACLE_SYMBOLS.values())) |
| 44 | + |
| 45 | + task = asyncio.get_event_loop().create_task( |
| 46 | + client.listen_chain_stream_updates( |
| 47 | + callback=oracle_price_event_processor, |
| 48 | + on_end_callback=stream_closed_processor, |
| 49 | + on_status_callback=stream_error_processor, |
| 50 | + oracle_price_filter=oracle_price_filter, |
| 51 | + ) |
| 52 | + ) |
| 53 | + |
| 54 | + await asyncio.sleep(delay=60) |
| 55 | + task.cancel() |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + asyncio.get_event_loop().run_until_complete(main()) |