mirror of
https://github.com/laoxong/nofx.git
synced 2026-06-04 09:58:22 +08:00
7ae5bf8247
* feat(store): prevent deletion of active strategies and update translations (#1461) Co-authored-by: Dean <afei.wuhao@gmail.com> * fix: allow model switching without re-entering wallet key Users with existing wallets could not switch AI models because the "Start Trading" button required a valid private key even when one was already configured. Now the button is enabled when hasExistingWallet is true, and handleSubmit passes an empty key so the backend preserves the existing key. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: replace window.location with useNavigate for routing in auth components (#1470) Co-authored-by: Dean <afei.wuhao@gmail.com> * feat(trader): implement margin mode handling for order and leverage settings * refactor(trader): update SetMarginMode to avoid legacy endpoint and improve logging * feat(api): enhance strategy handling by integrating claw402 wallet key validation Added validation for the claw402 model's wallet key during strategy test runs. If the selected AI model is claw402, the server now checks for a valid wallet key and returns appropriate error messages if it's missing or if the model fails to load. This ensures better error handling and user feedback when working with AI models. * refactor(api): streamline claw402 wallet key retrieval and error handling Refactored the strategy handling logic to encapsulate claw402 wallet key retrieval in a new method, `resolveStrategyDataWalletKey`. This improves code readability and maintains consistent error handling for missing or invalid wallet keys during strategy test runs. The changes enhance the overall robustness of the AI model integration. * feat(trader): add claw402 wallet key resolution for trader configuration Implemented a new method, `resolveTraderDataWalletKey`, to retrieve the claw402 wallet key based on the selected AI model and user ID. This enhancement allows for better integration of the claw402 model within the trader configuration, ensuring that the correct wallet key is used for trading operations. The `AutoTraderConfig` struct has been updated to include the new `Claw402WalletKey` field, improving the overall handling of wallet keys in the trading process. * feat(claw402): preflight USDC balance before AI calls (#1479) * chore: ignore nofx-server build artifact Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(claw402): preflight USDC balance before AI calls Short-circuit claw402 Call/CallWithRequestFull when the wallet balance can't cover the estimated cost of the call, surfacing ErrInsufficientFunds instead of letting x402 fail mid-flight after the sign step. - wallet: cached balance lookup (30s TTL, per-address mutex) to avoid hammering the Base RPC; separate error-returning and display-only APIs so callers can distinguish zero balance from an unreachable RPC. - claw402: 1.5× safety multiplier on the flat per-call estimate, 4.0× for reasoner models whose chain-of-thought cost can blow past the flat rate. Fail-open on RPC errors — x402 still gates actually-empty wallets, and we prefer availability over extra strictness. - shortAddr redacts the wallet in error strings to avoid leaking the full address into telemetry bundles. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> * fix(telemetry): report token usage for SSE streaming paths (#1475) * fix(telemetry): report token usage for SSE streaming paths ParseSSEStream already parsed the usage block from SSE chunks but only printed it, so claw402 streaming calls (and native streaming) never fired TokenUsageCallback. GA4 therefore undercounted AI usage on the streaming path. Return the parsed usage from ParseSSEStream and have both callers fire the callback with their own Provider/Model. * chore: drop leftover debug Printf in ParseSSEStream Telemetry is now wired via TokenUsageCallback, so the Printf is redundant noise in the stream path. * fix(gemini): update default model to gemini-3.1-pro Google discontinued gemini-3-pro-preview on 2026-03-26 and directs all callers to gemini-3.1-pro / gemini-3.1-pro-preview. Users on their own API key were getting errors from the native Gemini endpoint because the provider default pointed at the retired ID. Claw402 was unaffected because its route map already used gemini-3.1-pro. Align both the native provider default and the handler's preset list with gemini-3.1-pro so every code path sends a live model ID. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: extract ResolveClaw402WalletKey to store layer and expand OKX margin mode tests - Move duplicated claw402 wallet resolution logic into store.AIModelStore.ResolveClaw402WalletKey - api/strategy.go and manager/trader_manager.go now delegate to the shared method - Add detailed doc comment on OKX SetMarginMode explaining the local-state-only approach and why the legacy /api/v5/account/set-isolated-mode endpoint is not called - Add 3 new test cases: cross mode leverage, OpenShort tdMode, SetTakeProfit tdMode * fix(auth): prevent SetupPage remount from wiping freshly-set auth token (#1481) After #1470 moved routing into react-router, SetupPage is rendered at two different tree positions (top-level guard + /setup Route). When register success flushSync-sets `user`, the top-level guard stops matching and the Route-level SetupPage mounts as a new instance, re-running its cleanup useEffect and removing the auth_token that handlePostAuthSuccess just wrote. Subsequent requests 401 and bounce the user back to /login. Redirect /setup to /welcome when user is already set so SetupPage is never re-mounted during the auth transition. * fix(wallet): handle JSON-RPC null error field in balance query Some RPC implementations return explicit "error": null on success. json.RawMessage deserializes this as the 4-byte literal "null", so len() > 0 was true, causing every balance query to fail with "rpc error: null". Skip the null literal to avoid false positives. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: deanokk <wuhao@vergex.trade> Co-authored-by: Dean <afei.wuhao@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: root <root@localhost.localdomain>
226 lines
8.4 KiB
Go
226 lines
8.4 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"nofx/config"
|
|
"nofx/crypto"
|
|
"nofx/logger"
|
|
"nofx/security"
|
|
"nofx/wallet"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type ModelConfig struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Provider string `json:"provider"`
|
|
Enabled bool `json:"enabled"`
|
|
APIKey string `json:"apiKey,omitempty"`
|
|
CustomAPIURL string `json:"customApiUrl,omitempty"`
|
|
}
|
|
|
|
// SafeModelConfig Safe model configuration structure (does not contain sensitive information)
|
|
type SafeModelConfig struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Provider string `json:"provider"`
|
|
Enabled bool `json:"enabled"`
|
|
CustomAPIURL string `json:"customApiUrl"` // Custom API URL (usually not sensitive)
|
|
CustomModelName string `json:"customModelName"` // Custom model name (not sensitive)
|
|
WalletAddress string `json:"walletAddress,omitempty"`
|
|
BalanceUSDC string `json:"balanceUsdc,omitempty"`
|
|
}
|
|
|
|
type UpdateModelConfigRequest struct {
|
|
Models map[string]struct {
|
|
Enabled bool `json:"enabled"`
|
|
APIKey string `json:"api_key"`
|
|
CustomAPIURL string `json:"custom_api_url"`
|
|
CustomModelName string `json:"custom_model_name"`
|
|
} `json:"models"`
|
|
}
|
|
|
|
// handleGetModelConfigs Get AI model configurations
|
|
func (s *Server) handleGetModelConfigs(c *gin.Context) {
|
|
userID := c.GetString("user_id")
|
|
logger.Infof("🔍 Querying AI model configs for user %s", userID)
|
|
models, err := s.store.AIModel().List(userID)
|
|
if err != nil {
|
|
logger.Infof("❌ Failed to get AI model configs: %v", err)
|
|
SafeInternalError(c, "Failed to get AI model configs", err)
|
|
return
|
|
}
|
|
|
|
// If no models in database, return default models
|
|
if len(models) == 0 {
|
|
logger.Infof("⚠️ No AI models in database, returning defaults")
|
|
defaultModels := []SafeModelConfig{
|
|
{ID: "deepseek", Name: "DeepSeek AI", Provider: "deepseek", Enabled: false},
|
|
{ID: "qwen", Name: "Qwen AI", Provider: "qwen", Enabled: false},
|
|
{ID: "openai", Name: "OpenAI", Provider: "openai", Enabled: false},
|
|
{ID: "claude", Name: "Claude AI", Provider: "claude", Enabled: false},
|
|
{ID: "gemini", Name: "Gemini AI", Provider: "gemini", Enabled: false},
|
|
{ID: "grok", Name: "Grok AI", Provider: "grok", Enabled: false},
|
|
{ID: "kimi", Name: "Kimi AI", Provider: "kimi", Enabled: false},
|
|
{ID: "minimax", Name: "MiniMax AI", Provider: "minimax", Enabled: false},
|
|
}
|
|
c.JSON(http.StatusOK, defaultModels)
|
|
return
|
|
}
|
|
|
|
logger.Infof("✅ Found %d AI model configs", len(models))
|
|
|
|
// Convert to safe response structure, remove sensitive information
|
|
safeModels := make([]SafeModelConfig, len(models))
|
|
for i, model := range models {
|
|
safeModel := SafeModelConfig{
|
|
ID: model.ID,
|
|
Name: model.Name,
|
|
Provider: model.Provider,
|
|
Enabled: model.Enabled,
|
|
CustomAPIURL: model.CustomAPIURL,
|
|
CustomModelName: model.CustomModelName,
|
|
}
|
|
|
|
if model.Provider == "claw402" {
|
|
if privateKey := strings.TrimSpace(model.APIKey.String()); privateKey != "" {
|
|
if walletAddress, addrErr := walletAddressFromPrivateKey(privateKey); addrErr == nil {
|
|
safeModel.WalletAddress = walletAddress
|
|
safeModel.BalanceUSDC = wallet.QueryUSDCBalanceStr(walletAddress)
|
|
} else {
|
|
logger.Warnf("⚠️ Failed to derive claw402 wallet address for model %s: %v", model.ID, addrErr)
|
|
}
|
|
}
|
|
}
|
|
|
|
safeModels[i] = safeModel
|
|
}
|
|
|
|
c.JSON(http.StatusOK, safeModels)
|
|
}
|
|
|
|
// handleUpdateModelConfigs Update AI model configurations (supports both encrypted and plain text based on config)
|
|
func (s *Server) handleUpdateModelConfigs(c *gin.Context) {
|
|
userID := c.GetString("user_id")
|
|
cfg := config.Get()
|
|
|
|
// Read raw request body
|
|
bodyBytes, err := c.GetRawData()
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to read request body"})
|
|
return
|
|
}
|
|
|
|
var req UpdateModelConfigRequest
|
|
|
|
// Check if transport encryption is enabled
|
|
if !cfg.TransportEncryption {
|
|
// Transport encryption disabled, accept plain JSON
|
|
if err := json.Unmarshal(bodyBytes, &req); err != nil {
|
|
logger.Infof("❌ Failed to parse plain JSON request: %v", err)
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request format"})
|
|
return
|
|
}
|
|
logger.Infof("📝 Received plain text model config (UserID: %s)", userID)
|
|
} else {
|
|
// Transport encryption enabled, require encrypted payload
|
|
var encryptedPayload crypto.EncryptedPayload
|
|
if err := json.Unmarshal(bodyBytes, &encryptedPayload); err != nil {
|
|
logger.Infof("❌ Failed to parse encrypted payload: %v", err)
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request format, encrypted transmission required"})
|
|
return
|
|
}
|
|
|
|
// Verify encrypted data
|
|
if encryptedPayload.WrappedKey == "" {
|
|
logger.Infof("❌ Detected unencrypted request (UserID: %s)", userID)
|
|
c.JSON(http.StatusBadRequest, gin.H{
|
|
"error": "This endpoint only supports encrypted transmission, please use encrypted client",
|
|
"code": "ENCRYPTION_REQUIRED",
|
|
"message": "Encrypted transmission is required for security reasons",
|
|
})
|
|
return
|
|
}
|
|
|
|
// Decrypt data
|
|
decrypted, err := s.cryptoHandler.cryptoService.DecryptSensitiveData(&encryptedPayload)
|
|
if err != nil {
|
|
logger.Infof("❌ Failed to decrypt model config (UserID: %s): %v", userID, err)
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to decrypt data"})
|
|
return
|
|
}
|
|
|
|
// Parse decrypted data
|
|
if err := json.Unmarshal([]byte(decrypted), &req); err != nil {
|
|
logger.Infof("❌ Failed to parse decrypted data: %v", err)
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to parse decrypted data"})
|
|
return
|
|
}
|
|
logger.Infof("🔓 Decrypted model config data (UserID: %s)", userID)
|
|
}
|
|
|
|
// Update each model's configuration and track traders that need reload
|
|
tradersToReload := make(map[string]bool)
|
|
for modelID, modelData := range req.Models {
|
|
// SSRF protection: validate custom_api_url before storing
|
|
if modelData.CustomAPIURL != "" {
|
|
cleanURL := strings.TrimSuffix(modelData.CustomAPIURL, "#")
|
|
if err := security.ValidateURL(cleanURL); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("Invalid custom_api_url for model %s: %s", modelID, err.Error())})
|
|
return
|
|
}
|
|
}
|
|
|
|
// Find traders using this AI model BEFORE updating
|
|
traders, _ := s.store.Trader().ListByAIModelID(userID, modelID)
|
|
for _, t := range traders {
|
|
tradersToReload[t.ID] = true
|
|
}
|
|
|
|
err := s.store.AIModel().Update(userID, modelID, modelData.Enabled, modelData.APIKey, modelData.CustomAPIURL, modelData.CustomModelName)
|
|
if err != nil {
|
|
SafeInternalError(c, fmt.Sprintf("Update model %s", modelID), err)
|
|
return
|
|
}
|
|
}
|
|
|
|
// Remove affected traders from memory BEFORE reloading to pick up new config
|
|
for traderID := range tradersToReload {
|
|
logger.Infof("🔄 Removing trader %s from memory to reload with new AI model config", traderID)
|
|
s.traderManager.RemoveTrader(traderID)
|
|
}
|
|
|
|
// Reload all traders for this user to make new config take effect immediately
|
|
err = s.traderManager.LoadUserTradersFromStore(s.store, userID)
|
|
if err != nil {
|
|
logger.Infof("⚠️ Failed to reload user traders into memory: %v", err)
|
|
// Don't return error here since model config was successfully updated to database
|
|
}
|
|
|
|
logger.Infof("✓ AI model config updated: %+v", req.Models)
|
|
c.JSON(http.StatusOK, gin.H{"message": "Model configuration updated"})
|
|
}
|
|
|
|
// handleGetSupportedModels Get list of AI models supported by the system
|
|
func (s *Server) handleGetSupportedModels(c *gin.Context) {
|
|
// Return static list of supported AI models with default versions
|
|
supportedModels := []map[string]interface{}{
|
|
{"id": "deepseek", "name": "DeepSeek", "provider": "deepseek", "defaultModel": "deepseek-chat"},
|
|
{"id": "qwen", "name": "Qwen", "provider": "qwen", "defaultModel": "qwen3-max"},
|
|
{"id": "openai", "name": "OpenAI", "provider": "openai", "defaultModel": "gpt-5.1"},
|
|
{"id": "claude", "name": "Claude", "provider": "claude", "defaultModel": "claude-opus-4-6"},
|
|
{"id": "gemini", "name": "Google Gemini", "provider": "gemini", "defaultModel": "gemini-3.1-pro"},
|
|
{"id": "grok", "name": "Grok (xAI)", "provider": "grok", "defaultModel": "grok-3-latest"},
|
|
{"id": "kimi", "name": "Kimi (Moonshot)", "provider": "kimi", "defaultModel": "moonshot-v1-auto"},
|
|
{"id": "minimax", "name": "MiniMax", "provider": "minimax", "defaultModel": "MiniMax-M2.7"},
|
|
{"id": "claw402", "name": "Claw402 (Base USDC)", "provider": "claw402", "defaultModel": "glm-5"},
|
|
}
|
|
|
|
c.JSON(http.StatusOK, supportedModels)
|
|
}
|