From 9b9a86a506d1522d818e9cf520b2bb49c4347453 Mon Sep 17 00:00:00 2001 From: smypmsa Date: Fri, 4 Apr 2025 21:31:00 +0000 Subject: [PATCH 1/2] feat: add blockhash caching --- src/core/client.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/core/client.py b/src/core/client.py index b1b74b4..ac64487 100644 --- a/src/core/client.py +++ b/src/core/client.py @@ -34,6 +34,28 @@ class SolanaClient: """ self.rpc_endpoint = rpc_endpoint self._client = None + self._cached_blockhash: Hash | None = None + self._blockhash_lock = asyncio.Lock() + + asyncio.create_task(self.start_blockhash_updater()) + + async def start_blockhash_updater(self, interval: float = 5.0): + """Start background task to update recent blockhash.""" + while True: + try: + blockhash = await self.get_latest_blockhash() + async with self._blockhash_lock: + self._cached_blockhash = blockhash + except Exception as e: + logger.warning(f"Blockhash fetch failed: {e!s}") + await asyncio.sleep(interval) + + async def get_cached_blockhash(self) -> Hash: + """Return the most recently cached blockhash.""" + async with self._blockhash_lock: + if self._cached_blockhash is None: + raise RuntimeError("No cached blockhash available yet") + return self._cached_blockhash async def get_client(self) -> AsyncClient: """Get or create the AsyncClient instance. @@ -128,7 +150,7 @@ class SolanaClient: ] instructions = fee_instructions + instructions - recent_blockhash = await self.get_latest_blockhash() + recent_blockhash = await self.get_cached_blockhash() message = Message(instructions, signer_keypair.pubkey()) transaction = Transaction([signer_keypair], message, recent_blockhash) From 7cfd89d1ae60371340b31a754b50e4572f852035 Mon Sep 17 00:00:00 2001 From: smypmsa Date: Fri, 4 Apr 2025 21:38:36 +0000 Subject: [PATCH 2/2] fix: gracefully cancel blockhash updater task --- src/core/client.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/core/client.py b/src/core/client.py index ac64487..a39140b 100644 --- a/src/core/client.py +++ b/src/core/client.py @@ -36,8 +36,7 @@ class SolanaClient: self._client = None self._cached_blockhash: Hash | None = None self._blockhash_lock = asyncio.Lock() - - asyncio.create_task(self.start_blockhash_updater()) + self._blockhash_updater_task = asyncio.create_task(self.start_blockhash_updater()) async def start_blockhash_updater(self, interval: float = 5.0): """Start background task to update recent blockhash.""" @@ -68,7 +67,14 @@ class SolanaClient: return self._client async def close(self): - """Close the client connection if open.""" + """Close the client connection and stop the blockhash updater.""" + if self._blockhash_updater_task: + self._blockhash_updater_task.cancel() + try: + await self._blockhash_updater_task + except asyncio.CancelledError: + pass + if self._client: await self._client.close() self._client = None