Files
pumpfun-bonkfun-bot/src/cleanup/manager.py
T
Alex Kuligowski 40ad32b8d0 feat(core): add RPC rate limiting and retry handling (#154)
* feat(core): add RPC rate limiting, retry logic, and 429 handling

Addresses #44 — users on free-tier RPC endpoints hit HTTP 429 errors
during buy transactions due to no rate limiting or retry handling.

- Add TokenBucketRateLimiter (new file: src/core/rpc_rate_limiter.py)
- Gate all RPC methods through rate limiter (both post_rpc and solana-py calls)
- Rewrite post_rpc() with retry loop, exponential backoff, jitter, and
  specific 429 detection with Retry-After header support
- Replace per-call aiohttp session with shared persistent session
- Wire node.max_rps from YAML bot config through to SolanaClient
- Fix cleanup manager and learning example to use SolanaClient abstraction
  instead of bypassing it via get_client()

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(core): address CodeRabbitAI review feedback on rate limiting PR

Validate max_rps > 0 in TokenBucketRateLimiter to prevent ZeroDivisionError
and infinite loops with fractional values. Add asyncio.Lock to _get_session
to fix race condition, handle non-numeric Retry-After headers gracefully,
replace dead json.JSONDecodeError with aiohttp.ContentTypeError, and combine
burn+close into a single transaction in cleanup example.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: document RPC rate limiting feature in README

- Add section on built-in RPC rate limiting with token bucket algorithm
- Document configurable max RPS and automatic retry logic
- Update roadmap to mark "Configurable RPS" as completed
- Clarify benefits of rate limiting for provider compliance

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: use math.ceil for burst_size to handle fractional max_rps

- Replace int(max_rps) with math.ceil(max_rps) in burst_size calculation
- Prevents infinite loop when max_rps < 1.0 (e.g., 0.5 RPS would result in burst_size=0)
- Ensures burst_size is always at least 1 for valid fractional rates
- Addresses CodeRabbit feedback on rpc_rate_limiter.py:27

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix(core): validate burst_size and fix table pipe consistency

Address remaining CodeRabbitAI review feedback: add burst_size
validation guard, fix TRY003 lint (use msg variable for ValueError),
break long line under 88 chars, and fix MD055 table pipe style in README.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(core): separate 429 retry budget from error retries in post_rpc

429 responses no longer count against max_retries — they use a dedicated
max_429_retries counter (default 10) so free-tier users hitting rate
limits won't exhaust retries prematurely. Also refresh the aiohttp
session inside the retry loop to avoid stale references after network
failures, and fix cleanup log message accuracy.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Anton Sauchyk <antonsauchyk@gmail.com>
2026-02-17 10:02:11 +01:00

119 lines
3.9 KiB
Python

import asyncio
from solders.pubkey import Pubkey
from spl.token.instructions import BurnParams, CloseAccountParams, burn, close_account
from core.client import SolanaClient
from core.priority_fee.manager import PriorityFeeManager
from core.pubkeys import SystemAddresses
from core.wallet import Wallet
from utils.logger import get_logger
logger = get_logger(__name__)
class AccountCleanupManager:
"""Handles safe cleanup of token accounts (ATA) after trading sessions."""
def __init__(
self,
client: SolanaClient,
wallet: Wallet,
priority_fee_manager: PriorityFeeManager,
use_priority_fee: bool = False,
force_burn: bool = False,
):
"""
Args:
client: Solana RPC client
wallet: Wallet for signing transactions
"""
self.client = client
self.wallet = wallet
self.priority_fee_manager = priority_fee_manager
self.use_priority_fee = use_priority_fee
self.close_with_force_burn = force_burn
async def cleanup_ata(
self, mint: Pubkey, token_program_id: Pubkey | None = None
) -> None:
"""
Attempt to burn any remaining tokens and close the ATA.
Skips if account doesn't exist or is already empty/closed.
Args:
mint: Token mint address
token_program_id: Token program (TOKEN or TOKEN_2022). Defaults to TOKEN_2022_PROGRAM
"""
if token_program_id is None:
token_program_id = SystemAddresses.TOKEN_2022_PROGRAM
ata = self.wallet.get_associated_token_address(mint, token_program_id)
priority_fee = (
await self.priority_fee_manager.calculate_priority_fee([ata])
if self.use_priority_fee
else None
)
logger.info("Waiting for 15 seconds for RPC node to synchronize...")
await asyncio.sleep(15)
try:
try:
await self.client.get_account_info(ata)
except ValueError:
logger.info(f"ATA {ata} does not exist or already closed.")
return
balance = await self.client.get_token_account_balance(ata)
instructions = []
if balance > 0 and self.close_with_force_burn:
logger.info(
f"Burning {balance} tokens from ATA {ata} (mint: {mint})..."
)
burn_ix = burn(
BurnParams(
account=ata,
mint=mint,
owner=self.wallet.pubkey,
amount=balance,
program_id=token_program_id,
)
)
instructions.append(burn_ix)
elif balance > 0:
logger.info(
f"Skipping ATA {ata} with non-zero balance ({balance} tokens) "
f"because CLEANUP_FORCE_CLOSE_WITH_BURN is disabled."
)
return
# Include close account instruction
logger.info(f"Closing ATA: {ata}")
close_ix = close_account(
CloseAccountParams(
account=ata,
dest=self.wallet.pubkey,
owner=self.wallet.pubkey,
program_id=token_program_id,
)
)
instructions.append(close_ix)
# Send both burn and close instructions in the same transaction
if instructions:
tx_sig = await self.client.build_and_send_transaction(
instructions,
self.wallet.keypair,
skip_preflight=True,
priority_fee=priority_fee,
)
await self.client.confirm_transaction(tx_sig)
logger.info(f"Closed successfully: {ata}")
except Exception as e:
logger.warning(f"Cleanup failed for ATA {ata}: {e!s}")