Skip to content

Commit 73ea5b6

Browse files
committed
update wait_for_tansaction api to support long poll
1 parent f65bdd5 commit 73ea5b6

File tree

1 file changed

+27
-9
lines changed

1 file changed

+27
-9
lines changed

aptos_sdk/async_client.py

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -568,25 +568,43 @@ async def transaction_pending(self, txn_hash: str) -> bool:
568568
raise ApiError(response.text, response.status_code)
569569
return response.json()["type"] == "pending_transaction"
570570

571-
async def wait_for_transaction(self, txn_hash: str) -> None:
571+
async def _wait_for_txn(self, txn_hash: str) -> None:
572572
"""
573573
Waits up to the duration specified in client_config for a transaction to move past pending
574574
state.
575575
"""
576-
577-
count = 0
578-
while await self.transaction_pending(txn_hash):
579-
assert (
580-
count < self.client_config.transaction_wait_in_seconds
581-
), f"transaction {txn_hash} timed out"
576+
response = await self._get(endpoint=f"transactions/by_hash/{txn_hash}")
577+
if response.status_code != 404 and response.status_code >= 400:
578+
raise ApiError(response.text, response.status_code)
579+
is_pending = response.json()["type"] == "pending_transaction"
580+
581+
# If the transaction is pending, we do a long wait once to avoid polling
582+
if is_pending:
583+
response = await self._get(endpoint=f"transactions/wait_by_hash/{txn_hash}")
584+
if response.status_code != 404 and response.status_code >= 400:
585+
raise ApiError(response.text, response.status_code)
586+
is_pending = response.json()["type"] == "pending_transaction"
587+
588+
# Now we do polling to see if the transaction is still pending
589+
while is_pending:
590+
response = await self._get(endpoint=f"transactions/by_hash/{txn_hash}")
591+
if response.status_code != 404 and response.status_code >= 400:
592+
raise ApiError(response.text, response.status_code)
593+
is_pending = response.json()["type"] == "pending_transaction"
594+
if not is_pending:
595+
break
582596
await asyncio.sleep(1)
583-
count += 1
584597

585-
response = await self._get(endpoint=f"transactions/by_hash/{txn_hash}")
586598
assert (
587599
"success" in response.json() and response.json()["success"]
588600
), f"{response.text} - {txn_hash}"
589601

602+
async def wait_for_transaction(self, txn_hash: str) -> None:
603+
await asyncio.wait_for(
604+
self._wait_for_txn(txn_hash),
605+
timeout=self.client_config.transaction_wait_in_seconds,
606+
)
607+
590608
async def account_transaction_sequence_number_status(
591609
self, address: AccountAddress, sequence_number: int
592610
) -> bool:

0 commit comments

Comments
 (0)