Add copy trading authorization checks in LiveTradingBotGrain and StartCopyTradingCommandHandler. Integrated IKaigenService to verify user ownership of master strategy keys before allowing copy trading. Enhanced error handling and logging for authorization verification.

This commit is contained in:
2025-11-16 22:11:54 +07:00
parent 2baa2e173c
commit c229212acd
4 changed files with 149 additions and 19 deletions

View File

@@ -29,6 +29,7 @@ public class LiveTradingBotGrain : Grain, ILiveTradingBotGrain, IRemindable
private readonly IPersistentState<TradingBotGrainState> _state;
private readonly ILogger<LiveTradingBotGrain> _logger;
private readonly IServiceScopeFactory _scopeFactory;
private readonly IKaigenService _kaigenService;
private TradingBotBase? _tradingBot;
private IDisposable? _timer;
private string _reminderName = "RebootReminder";
@@ -38,11 +39,13 @@ public class LiveTradingBotGrain : Grain, ILiveTradingBotGrain, IRemindable
[PersistentState("live-trading-bot", "bot-store")]
IPersistentState<TradingBotGrainState> state,
ILogger<LiveTradingBotGrain> logger,
IServiceScopeFactory scopeFactory)
IServiceScopeFactory scopeFactory,
IKaigenService kaigenService)
{
_logger = logger;
_scopeFactory = scopeFactory;
_state = state;
_kaigenService = kaigenService;
}
public override async Task OnActivateAsync(CancellationToken cancellationToken)
@@ -505,6 +508,35 @@ public class LiveTradingBotGrain : Grain, ILiveTradingBotGrain, IRemindable
return;
}
// Check if copy trading authorization is still valid
if (_state.State.Config.IsForCopyTrading && _state.State.Config.MasterBotIdentifier.HasValue)
{
try
{
var ownedKeys = await _kaigenService.GetOwnedKeysAsync(_state.State.User);
var hasMasterStrategyKey = ownedKeys.Items.Any(key =>
string.Equals(key.AgentName, _state.State.Config.MasterBotIdentifier.Value.ToString(), StringComparison.OrdinalIgnoreCase) &&
key.Owned >= 1);
if (!hasMasterStrategyKey)
{
_logger.LogWarning(
"Copy trading bot {GrainId} no longer has authorization for master strategy {MasterBotId}. Stopping bot.",
this.GetPrimaryKey(), _state.State.Config.MasterBotIdentifier.Value);
await StopAsync("Copy trading authorization revoked - user no longer owns keys for master strategy");
return;
}
}
catch (Exception ex)
{
_logger.LogError(ex,
"Failed to verify copy trading authorization for bot {GrainId} with master strategy {MasterBotId}. Continuing execution.",
this.GetPrimaryKey(), _state.State.Config.MasterBotIdentifier.Value);
SentrySdk.CaptureException(ex);
}
}
if (_tradingBot.Positions.Any(p => p.Value.IsOpen() || p.Value.Status.Equals(PositionStatus.New)))
{
_logger.LogInformation(