Fix restart/start if not account with the first account of the user

This commit is contained in:
2025-10-12 16:08:12 +07:00
parent 176573ddd1
commit ff74296c26
4 changed files with 61 additions and 7 deletions

View File

@@ -1006,4 +1006,17 @@ public class LiveTradingBotGrain : Grain, ILiveTradingBotGrain, IRemindable
return true;
}
}
/// <summary>
/// Gets the user who owns this bot
/// </summary>
public Task<User> GetUserAsync()
{
if (_state.State.User == null)
{
throw new InvalidOperationException($"Bot '{_state.State.Config?.Name}' (ID: {_state.State.Identifier}) has no user information.");
}
return Task.FromResult(_state.State.User);
}
}

View File

@@ -109,9 +109,35 @@ namespace Managing.Application.ManageBot
// Check balances for EVM/GMX V2 bots before starting/restarting
var botConfig = await botGrain.GetConfiguration();
var account = await ServiceScopeHelpers.WithScopedService<IAccountService, Account>(
_scopeFactory,
async accountService => await accountService.GetAccount(botConfig.AccountName, true, true));
Account account;
if (string.IsNullOrEmpty(botConfig.AccountName))
{
// Fallback: Get the first account for the user
var user = await botGrain.GetUserAsync();
account = await ServiceScopeHelpers.WithScopedService<IAccountService, Account>(
_scopeFactory,
async accountService =>
{
var userAccounts = await accountService.GetAccountsByUserAsync(user, true, true);
var firstAccount = userAccounts.FirstOrDefault();
if (firstAccount == null)
{
throw new InvalidOperationException($"User '{user.Name}' has no accounts configured.");
}
return firstAccount;
});
_tradingBotLogger.LogInformation("Bot '{BotName}' (ID: {BotId}) using fallback account '{AccountName}' for user '{UserName}'",
botConfig.Name, identifier, account.Name, user.Name);
}
else
{
account = await ServiceScopeHelpers.WithScopedService<IAccountService, Account>(
_scopeFactory,
async accountService => await accountService.GetAccount(botConfig.AccountName, true, true));
}
if (account.Exchange == TradingExchanges.Evm || account.Exchange == TradingExchanges.GmxV2)
{

View File

@@ -43,11 +43,21 @@ namespace Managing.Application.ManageBot
$"Bot trading balance must be greater than {Constants.GMX.Config.MinimumPositionAmount}");
}
var account = await _accountService.GetAccount(request.Config.AccountName, true, true);
if (account == null)
Account account;
if (string.IsNullOrEmpty(request.Config.AccountName))
{
throw new Exception($"Account {request.Config.AccountName} not found");
// Fallback: Get the first account for the user
var userAccounts = await _accountService.GetAccountsByUserAsync(request.User, true, true);
var firstAccount = userAccounts.FirstOrDefault();
if (firstAccount == null)
{
throw new InvalidOperationException($"User '{request.User.Name}' has no accounts configured.");
}
account = firstAccount;
}
else
{
account = await _accountService.GetAccount(request.Config.AccountName, true, true);
}
// Check balances for EVM/GMX V2 accounts before starting