Implement on-chain token balance retrieval and enhance SpotBot logging

- Added a new method in IWeb3ProxyService to retrieve token balances directly from the blockchain, ensuring accurate decimal handling.
- Updated ExchangeService to utilize the new on-chain balance method, replacing the previous balance retrieval logic.
- Enhanced SpotBot logging to provide clearer warnings when token balances are significantly lower than expected, and to log cases of excess token balances.
- Introduced a new API endpoint for fetching token balances on-chain, improving the overall functionality of the service.
This commit is contained in:
2026-01-05 20:30:24 +07:00
parent 25a2b202a1
commit 700d975da7
10 changed files with 317 additions and 34 deletions

View File

@@ -392,27 +392,45 @@ public class SpotBot : TradingBotBase
if (tokenBalance is { Amount: > 0 })
{
// Verify that the token balance matches the position amount with 0.1% tolerance
// Verify that the token balance matches the position amount
var positionQuantity = internalPosition.Open.Quantity;
var tokenBalanceAmount = tokenBalance.Amount;
if (positionQuantity > 0)
{
var tolerance = positionQuantity * 0.006m; // 0.6% tolerance to account for slippage
var difference = Math.Abs(tokenBalanceAmount - positionQuantity);
if (difference > tolerance)
// Only check tolerance if token balance is LESS than position quantity
// If balance is greater, it could be orphaned tokens from previous positions
if (tokenBalanceAmount < positionQuantity)
{
await LogWarningAsync(
$"⚠️ Token Balance Mismatch - Position Verification Failed\n" +
var tolerance = positionQuantity * 0.006m; // 0.6% tolerance to account for slippage
var difference = positionQuantity - tokenBalanceAmount;
if (difference > tolerance)
{
await LogWarningAsync(
$"⚠️ Token Balance Below Position Quantity\n" +
$"Position: `{internalPosition.Identifier}`\n" +
$"Position Quantity: `{positionQuantity:F5}`\n" +
$"Token Balance: `{tokenBalanceAmount:F5}`\n" +
$"Difference: `{difference:F5}`\n" +
$"Tolerance (0.6%): `{tolerance:F5}`\n" +
$"Token balance is significantly lower than expected\n" +
$"Skipping position synchronization");
return; // Skip processing if balance is too low
}
}
else if (tokenBalanceAmount > positionQuantity)
{
// Token balance is higher than position - likely orphaned tokens
// Log but continue with synchronization
var excess = tokenBalanceAmount - positionQuantity;
await LogDebugAsync(
$" Token Balance Exceeds Position Quantity\n" +
$"Position: `{internalPosition.Identifier}`\n" +
$"Position Quantity: `{positionQuantity:F5}`\n" +
$"Token Balance: `{tokenBalanceAmount:F5}`\n" +
$"Difference: `{difference:F5}`\n" +
$"Tolerance (0.6%): `{tolerance:F5}`\n" +
$"Token balance does not match position amount within tolerance\n" +
$"Skipping position synchronization");
return; // Skip processing if amounts don't match
$"Excess: `{excess:F5}`\n" +
$"Proceeding with position synchronization");
}
}