Skip to content

Commit

Permalink
update wait_for_tansaction api to support long poll
Browse files Browse the repository at this point in the history
  • Loading branch information
fishronsage committed Jul 31, 2024
1 parent f65bdd5 commit 009eeb3
Showing 1 changed file with 31 additions and 9 deletions.
40 changes: 31 additions & 9 deletions aptos_sdk/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -568,25 +568,47 @@ async def transaction_pending(self, txn_hash: str) -> bool:
raise ApiError(response.text, response.status_code)
return response.json()["type"] == "pending_transaction"

async def wait_for_transaction(self, txn_hash: str) -> None:
async def _wait_for_txn(self, txn_hash: str) -> None:
"""
Waits up to the duration specified in client_config for a transaction to move past pending
state.
"""

count = 0
while await self.transaction_pending(txn_hash):
assert (
count < self.client_config.transaction_wait_in_seconds
), f"transaction {txn_hash} timed out"
response = await self._get(endpoint=f"transactions/by_hash/{txn_hash}")
if response.status_code != 404 and response.status_code >= 400:
raise ApiError(response.text, response.status_code)
is_pending = response.json()["type"] == "pending_transaction"

# If the transaction is pending, we do a long wait once to avoid polling
if is_pending:
response = await self._get(endpoint=f"transactions/wait_by_hash/{txn_hash}")
if response.status_code != 404 and response.status_code >= 400:
raise ApiError(response.text, response.status_code)
is_pending = response.json()["type"] == "pending_transaction"

# Now we do polling to see if the transaction is still pending
while is_pending:
response = await self._get(endpoint=f"transactions/by_hash/{txn_hash}")
if response.status_code != 404 and response.status_code >= 400:
raise ApiError(response.text, response.status_code)
is_pending = response.json()["type"] == "pending_transaction"
if not is_pending:
break
await asyncio.sleep(1)
count += 1

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

async def wait_for_transaction(self, txn_hash: str) -> None:
await asyncio.wait_for(
self._wait_for_txn(txn_hash),
timeout=(
self.client_config.transaction_wait_in_seconds
if self.client_config.transaction_wait_in_seconds
else None
),
)

async def account_transaction_sequence_number_status(
self, address: AccountAddress, sequence_number: int
) -> bool:
Expand Down

0 comments on commit 009eeb3

Please sign in to comment.