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

@@ -14,18 +14,22 @@ namespace Managing.Api.Controllers
public class AccountController : BaseController public class AccountController : BaseController
{ {
private readonly IAccountService _AccountService; private readonly IAccountService _AccountService;
private readonly ITradingService _TradingService;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="AccountController"/> class. /// Initializes a new instance of the <see cref="AccountController"/> class.
/// </summary> /// </summary>
/// <param name="AccountService">Service for account-related operations.</param> /// <param name="AccountService">Service for account-related operations.</param>
/// <param name="userService">Service for user-related operations.</param> /// <param name="userService">Service for user-related operations.</param>
/// <param name="TradingService">Service for trading-related operations.</param>
public AccountController( public AccountController(
IAccountService AccountService, IAccountService AccountService,
IUserService userService) IUserService userService,
ITradingService TradingService)
: base(userService) : base(userService)
{ {
_AccountService = AccountService; _AccountService = AccountService;
_TradingService = TradingService;
} }
/// <summary> /// <summary>
@@ -101,7 +105,7 @@ namespace Managing.Api.Controllers
public async Task<ActionResult<SwapInfos>> SwapGmxTokens(string name, [FromBody] SwapTokensRequest request) public async Task<ActionResult<SwapInfos>> SwapGmxTokens(string name, [FromBody] SwapTokensRequest request)
{ {
var user = await GetUser(); var user = await GetUser();
var result = await _AccountService.SwapGmxTokensAsync( var result = await _TradingService.SwapGmxTokensAsync(
user, user,
name, name,
request.FromTicker, request.FromTicker,

View File

@@ -37,9 +37,6 @@ public interface IAccountService
Task<IEnumerable<Account>> GetAccountsBalancesByUserAsync(User user, bool hideSecrets = true); Task<IEnumerable<Account>> GetAccountsBalancesByUserAsync(User user, bool hideSecrets = true);
Task<GmxClaimableSummary> GetGmxClaimableSummaryAsync(User user, string accountName); Task<GmxClaimableSummary> GetGmxClaimableSummaryAsync(User user, string accountName);
Task<SwapInfos> SwapGmxTokensAsync(User user, string accountName, Ticker fromTicker, Ticker toTicker,
double amount, string orderType = "market", double? triggerRatio = null, double allowedSlippage = 0.5);
Task<SwapInfos> SendTokenAsync(User user, string accountName, string recipientAddress, Ticker ticker, Task<SwapInfos> SendTokenAsync(User user, string accountName, string recipientAddress, Ticker ticker,
decimal amount, int? chainId = null); decimal amount, int? chainId = null);

View File

@@ -55,4 +55,6 @@ public interface ITradingService
Task<IndicatorBase?> GetIndicatorByNameUserAsync(string name, User user); Task<IndicatorBase?> GetIndicatorByNameUserAsync(string name, User user);
Task<Scenario?> GetScenarioByNameUserAsync(string scenarioName, User user); Task<Scenario?> GetScenarioByNameUserAsync(string scenarioName, User user);
Task<IEnumerable<Position>> GetPositionByUserIdAsync(int userId); Task<IEnumerable<Position>> GetPositionByUserIdAsync(int userId);
Task<SwapInfos> SwapGmxTokensAsync(User user, string accountName, Ticker fromTicker, Ticker toTicker,
double amount, string orderType = "market", double? triggerRatio = null, double allowedSlippage = 0.5);
} }

View File

@@ -258,46 +258,6 @@ public class AccountService : IAccountService
} }
} }
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 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);
}
}
public async Task<SwapInfos> SendTokenAsync(User user, string accountName, string recipientAddress, Ticker ticker, public async Task<SwapInfos> SendTokenAsync(User user, string accountName, string recipientAddress, Ticker ticker,
decimal amount, int? chainId = null) decimal amount, int? chainId = null)
{ {

View File

@@ -448,7 +448,7 @@ public class AgentGrain : Grain, IAgentGrain
var user = await _userService.GetUserByIdAsync(userId); var user = await _userService.GetUserByIdAsync(userId);
// Perform the swap // Perform the swap
var swapInfo = await _accountService.SwapGmxTokensAsync(user, accountName, var swapInfo = await _tradingService.SwapGmxTokensAsync(user, accountName,
Ticker.USDC, Ticker.ETH, Constants.GMX.Config.AutoSwapAmount); Ticker.USDC, Ticker.ETH, Constants.GMX.Config.AutoSwapAmount);
if (swapInfo.Success) if (swapInfo.Success)

View File

@@ -28,6 +28,7 @@ public class TradingService : ITradingService
private readonly IEvmManager _evmManager; private readonly IEvmManager _evmManager;
private readonly ILogger<TradingService> _logger; private readonly ILogger<TradingService> _logger;
private readonly ISynthPredictionService _synthPredictionService; private readonly ISynthPredictionService _synthPredictionService;
private readonly IWeb3ProxyService _web3ProxyService;
public TradingService( public TradingService(
ITradingRepository tradingRepository, ITradingRepository tradingRepository,
@@ -39,7 +40,8 @@ public class TradingService : ITradingService
IMessengerService messengerService, IMessengerService messengerService,
IStatisticRepository statisticRepository, IStatisticRepository statisticRepository,
IEvmManager evmManager, IEvmManager evmManager,
ISynthPredictionService synthPredictionService) ISynthPredictionService synthPredictionService,
IWeb3ProxyService web3ProxyService)
{ {
_tradingRepository = tradingRepository; _tradingRepository = tradingRepository;
_exchangeService = exchangeService; _exchangeService = exchangeService;
@@ -51,6 +53,7 @@ public class TradingService : ITradingService
_statisticRepository = statisticRepository; _statisticRepository = statisticRepository;
_evmManager = evmManager; _evmManager = evmManager;
_synthPredictionService = synthPredictionService; _synthPredictionService = synthPredictionService;
_web3ProxyService = web3ProxyService;
} }
public async Task DeleteScenarioAsync(string name) public async Task DeleteScenarioAsync(string name)
@@ -447,4 +450,44 @@ public class TradingService : ITradingService
{ {
return await _tradingRepository.GetPositionByUserIdAsync(userId); 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);
}
}
} }