refactor: tx building, getting dynamic prior fee

This commit is contained in:
smypmsa
2025-03-13 21:01:26 +00:00
parent ac3d463d20
commit a1d5966f29
9 changed files with 170 additions and 91 deletions
+34 -2
View File
@@ -3,8 +3,10 @@ Solana client abstraction for blockchain operations.
"""
import asyncio
import json
from typing import Any
import aiohttp
from solana.rpc.async_api import AsyncClient
from solana.rpc.commitment import Confirmed
from solana.rpc.types import TxOpts
@@ -107,17 +109,21 @@ class SolanaClient:
instructions: List of instructions to include in the transaction.
skip_preflight: Whether to skip preflight checks.
max_retries: Maximum number of retry attempts.
priority_fee: Optional priority fee in lamports.
priority_fee: Optional priority fee in microlamports.
Returns:
Transaction signature.
"""
client = await self.get_client()
logger.info(
f"Priority fee in microlamports: {priority_fee if priority_fee else 0}"
)
# Add priority fee instructions if applicable
if priority_fee is not None:
fee_instructions = [
set_compute_unit_limit(200_000), # Default compute unit limit
set_compute_unit_limit(100_000), # Default compute unit limit
set_compute_unit_price(priority_fee),
]
instructions = fee_instructions + instructions
@@ -166,3 +172,29 @@ class SolanaClient:
except Exception as e:
logger.error(f"Failed to confirm transaction {signature}: {str(e)}")
return False
async def post_rpc(self, body: dict[str, Any]) -> dict[str, Any] | None:
"""
Send a raw RPC request to the Solana node.
Args:
body: JSON-RPC request body.
Returns:
Optional[Dict[str, Any]]: Parsed JSON response, or None if the request fails.
"""
try:
async with aiohttp.ClientSession() as session:
async with session.post(
self.rpc_endpoint,
json=body,
timeout=aiohttp.ClientTimeout(10), # 10-second timeout
) as response:
response.raise_for_status()
return await response.json()
except aiohttp.ClientError as e:
logger.error(f"RPC request failed: {str(e)}", exc_info=True)
return None
except json.JSONDecodeError as e:
logger.error(f"Failed to decode RPC response: {str(e)}", exc_info=True)
return None
+45 -14
View File
@@ -1,13 +1,16 @@
import statistics
from solders.pubkey import Pubkey
from core.priority_fee import PriorityFeePlugin
from src.core.client import SolanaClient
from src.utils.logger import get_logger
from . import PriorityFeePlugin
logger = get_logger(__name__)
class DynamicPriorityFee(PriorityFeePlugin):
"""Default dynamic priority fee plugin using getRecentPriorityFee."""
"""Dynamic priority fee plugin using getRecentPrioritizationFees."""
def __init__(self, client: SolanaClient):
"""
@@ -18,21 +21,49 @@ class DynamicPriorityFee(PriorityFeePlugin):
"""
self.client = client
async def get_priority_fee(self) -> int | None:
async def get_priority_fee(
self, accounts: list[Pubkey] | None = None
) -> int | None:
"""
Fetch the recent priority fee from the Solana network.
Fetch the recent priority fee using getRecentPrioritizationFees.
Args:
accounts: List of accounts to consider for the fee calculation.
If None, the fee is calculated without specific account constraints.
Returns:
Optional[int]: Recent priority fee in lamports, or None if the request fails.
Optional[int]: Median priority fee in microlamports, or None if the request fails.
"""
try:
client = await self.client.get_client()
response = await client.get_recent_prioritization_fees()
if response and response.value:
return response.value[
0
].prioritization_fee # Use the first fee from the list
return None
body = {
"jsonrpc": "2.0",
"id": 1,
"method": "getRecentPrioritizationFees",
"params": [[str(account) for account in accounts]] if accounts else [],
}
response = await self.client.post_rpc(body)
if not response or "result" not in response:
logger.error(
"Failed to fetch recent prioritization fees: invalid response"
)
return None
fees = [fee["prioritizationFee"] for fee in response["result"]]
if not fees:
logger.warning("No prioritization fees found in the response")
return None
# Get the 70th percentile of fees for faster processing
# It means you're paying a fee that's higher than 70% of other transactions
# Higher percentile = faster transactions but more expensive
# Lower percentile = cheaper but slower transactions
prior_fee = int(statistics.quantiles(fees, n=10)[-3]) # 70th percentile
return prior_fee
except Exception as e:
logger.error(f"Failed to fetch recent priority fee: {str(e)}")
logger.error(
f"Failed to fetch recent priority fee: {str(e)}", exc_info=True
)
return None
+2 -2
View File
@@ -9,7 +9,7 @@ class FixedPriorityFee(PriorityFeePlugin):
Initialize the fixed fee plugin.
Args:
fixed_fee: Fixed priority fee in lamports.
fixed_fee: Fixed priority fee in microlamports.
"""
self.fixed_fee = fixed_fee
@@ -18,7 +18,7 @@ class FixedPriorityFee(PriorityFeePlugin):
Return the fixed priority fee.
Returns:
Optional[int]: Fixed priority fee in lamports, or None if fixed_fee is 0.
Optional[int]: Fixed priority fee in microlamports, or None if fixed_fee is 0.
"""
if self.fixed_fee == 0:
return None
+17 -9
View File
@@ -1,3 +1,5 @@
from solders.pubkey import Pubkey
from src.core.client import SolanaClient
from src.core.priority_fee.dynamic_fee import DynamicPriorityFee
from src.core.priority_fee.fixed_fee import FixedPriorityFee
@@ -25,9 +27,9 @@ class PriorityFeeManager:
client: Solana RPC client for dynamic fee calculation.
enable_dynamic_fee: Whether to enable dynamic fee calculation.
enable_fixed_fee: Whether to enable fixed fee.
fixed_fee: Fixed priority fee in lamports.
fixed_fee: Fixed priority fee in microlamports.
extra_fee: Percentage increase to apply to the base fee.
hard_cap: Maximum allowed priority fee in lamports.
hard_cap: Maximum allowed priority fee in microlamports.
"""
self.client = client
self.enable_dynamic_fee = enable_dynamic_fee
@@ -40,14 +42,20 @@ class PriorityFeeManager:
self.dynamic_fee_plugin = DynamicPriorityFee(client)
self.fixed_fee_plugin = FixedPriorityFee(fixed_fee)
async def calculate_priority_fee(self) -> int | None:
async def calculate_priority_fee(
self, accounts: list[Pubkey] | None = None
) -> int | None:
"""
Calculate the priority fee based on the configuration.
Args:
accounts: List of accounts to consider for dynamic fee calculation.
If None, the fee is calculated without specific account constraints.
Returns:
Optional[int]: Calculated priority fee in lamports, or None if no fee should be applied.
Optional[int]: Calculated priority fee in microlamports, or None if no fee should be applied.
"""
base_fee = await self._get_base_fee()
base_fee = await self._get_base_fee(accounts)
if base_fee is None:
return None
@@ -63,16 +71,16 @@ class PriorityFeeManager:
return final_fee
async def _get_base_fee(self) -> int | None:
async def _get_base_fee(self, accounts: list[Pubkey] | None = None) -> int | None:
"""
Determine the base fee based on the configuration.
Returns:
Optional[int]: Base fee in lamports, or None if no fee should be applied.
Optional[int]: Base fee in microlamports, or None if no fee should be applied.
"""
# Prefer dynamic fee if both are enabled
if self.enable_dynamic_fee:
dynamic_fee = await self.dynamic_fee_plugin.get_priority_fee()
dynamic_fee = await self.dynamic_fee_plugin.get_priority_fee(accounts)
if dynamic_fee is not None:
return dynamic_fee
@@ -80,5 +88,5 @@ class PriorityFeeManager:
if self.enable_fixed_fee:
return await self.fixed_fee_plugin.get_priority_fee()
# No fee if both are disabled or return None
# No priority fee if both are disabled
return None