Refactor SwapGmxTokens functionality into TradingService

- Moved SwapGmxTokensAsync method from AccountService to TradingService to centralize trading operations.
- Updated AccountController and AgentGrain to utilize the new TradingService method for swapping GMX tokens.
- Removed the old SwapGmxTokensAsync method from IAccountService and its implementation in AccountService.
This commit is contained in:
2025-12-01 22:49:30 +07:00
parent 9d536ea49e
commit 3771bb5dde
7 changed files with 53 additions and 47 deletions

View File

@@ -28,6 +28,7 @@ public class TradingService : ITradingService
private readonly IEvmManager _evmManager;
private readonly ILogger<TradingService> _logger;
private readonly ISynthPredictionService _synthPredictionService;
private readonly IWeb3ProxyService _web3ProxyService;
public TradingService(
ITradingRepository tradingRepository,
@@ -39,7 +40,8 @@ public class TradingService : ITradingService
IMessengerService messengerService,
IStatisticRepository statisticRepository,
IEvmManager evmManager,
ISynthPredictionService synthPredictionService)
ISynthPredictionService synthPredictionService,
IWeb3ProxyService web3ProxyService)
{
_tradingRepository = tradingRepository;
_exchangeService = exchangeService;
@@ -51,6 +53,7 @@ public class TradingService : ITradingService
_statisticRepository = statisticRepository;
_evmManager = evmManager;
_synthPredictionService = synthPredictionService;
_web3ProxyService = web3ProxyService;
}
public async Task DeleteScenarioAsync(string name)
@@ -447,4 +450,44 @@ public class TradingService : ITradingService
{
return await _tradingRepository.GetPositionByUserIdAsync(userId);
}
public async Task<SwapInfos> SwapGmxTokensAsync(User user, string accountName, Ticker fromTicker, Ticker toTicker,
double amount, string orderType = "market", double? triggerRatio = null, double allowedSlippage = 0.5)
{
// Get the account for the user
var account = await _accountService.GetAccountByUser(user, accountName, true, false);
if (account == null)
{
throw new ArgumentException($"Account '{accountName}' not found for user '{user.Name}'");
}
// Ensure the account has a valid address/key
if (string.IsNullOrEmpty(account.Key))
{
throw new ArgumentException($"Account '{accountName}' does not have a valid address");
}
try
{
// Call the Web3ProxyService to swap GMX tokens
var swapInfos = await _web3ProxyService.SwapGmxTokensAsync(
account.Key,
fromTicker,
toTicker,
amount,
orderType,
triggerRatio,
allowedSlippage
);
return swapInfos;
}
catch (Exception ex) when (!(ex is ArgumentException || ex is InvalidOperationException))
{
_logger.LogError(ex, "Error swapping GMX tokens for account {AccountName} and user {UserName}",
accountName, user.Name);
throw new InvalidOperationException($"Failed to swap GMX tokens: {ex.Message}", ex);
}
}
}