mirror of
https://github.com/NoFxAiOS/nofx.git
synced 2026-07-18 01:44:38 +08:00
refactor: standardize code comments
This commit is contained in:
@@ -18,68 +18,68 @@ import (
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
)
|
||||
|
||||
// AccountInfo LIGHTER 賬戶信息
|
||||
// AccountInfo LIGHTER account information
|
||||
type AccountInfo struct {
|
||||
AccountIndex int64 `json:"account_index"`
|
||||
L1Address string `json:"l1_address"`
|
||||
// 其他字段可以根據實際 API 響應添加
|
||||
// Other fields can be added based on actual API response
|
||||
}
|
||||
|
||||
// LighterTraderV2 使用官方 lighter-go SDK 的新實現
|
||||
// LighterTraderV2 New implementation using official lighter-go SDK
|
||||
type LighterTraderV2 struct {
|
||||
ctx context.Context
|
||||
privateKey *ecdsa.PrivateKey // L1 錢包私鑰(用於識別賬戶)
|
||||
walletAddr string // Ethereum 錢包地址
|
||||
privateKey *ecdsa.PrivateKey // L1 wallet private key (for account identification)
|
||||
walletAddr string // Ethereum wallet address
|
||||
|
||||
client *http.Client
|
||||
baseURL string
|
||||
testnet bool
|
||||
chainID uint32
|
||||
|
||||
// SDK 客戶端
|
||||
// SDK clients
|
||||
httpClient lighterClient.MinimalHTTPClient
|
||||
txClient *lighterClient.TxClient
|
||||
|
||||
// API Key 管理
|
||||
apiKeyPrivateKey string // 40字節的 API Key 私鑰(用於簽名交易)
|
||||
apiKeyIndex uint8 // API Key 索引(默認 0)
|
||||
accountIndex int64 // 賬戶索引
|
||||
// API Key management
|
||||
apiKeyPrivateKey string // 40-byte API Key private key (for signing transactions)
|
||||
apiKeyIndex uint8 // API Key index (default 0)
|
||||
accountIndex int64 // Account index
|
||||
|
||||
// 認證令牌
|
||||
// Authentication token
|
||||
authToken string
|
||||
tokenExpiry time.Time
|
||||
accountMutex sync.RWMutex
|
||||
|
||||
// 市場信息緩存
|
||||
// Market info cache
|
||||
symbolPrecision map[string]SymbolPrecision
|
||||
precisionMutex sync.RWMutex
|
||||
|
||||
// 市場索引緩存
|
||||
// Market index cache
|
||||
marketIndexMap map[string]uint8 // symbol -> market_id
|
||||
marketMutex sync.RWMutex
|
||||
}
|
||||
|
||||
// NewLighterTraderV2 創建新的 LIGHTER 交易器(使用官方 SDK)
|
||||
// 參數說明:
|
||||
// - l1PrivateKeyHex: L1 錢包私鑰(32字節,標準以太坊私鑰)
|
||||
// - walletAddr: 以太坊錢包地址(可選,會從私鑰自動派生)
|
||||
// - apiKeyPrivateKeyHex: API Key 私鑰(40字節,用於簽名交易)如果為空則需要生成
|
||||
// - testnet: 是否使用測試網
|
||||
// NewLighterTraderV2 Create new LIGHTER trader (using official SDK)
|
||||
// Parameters:
|
||||
// - l1PrivateKeyHex: L1 wallet private key (32 bytes, standard Ethereum private key)
|
||||
// - walletAddr: Ethereum wallet address (optional, will be derived from private key if empty)
|
||||
// - apiKeyPrivateKeyHex: API Key private key (40 bytes, for signing transactions) - needs generation if empty
|
||||
// - testnet: Whether to use testnet
|
||||
func NewLighterTraderV2(l1PrivateKeyHex, walletAddr, apiKeyPrivateKeyHex string, testnet bool) (*LighterTraderV2, error) {
|
||||
// 1. 解析 L1 私鑰
|
||||
// 1. Parse L1 private key
|
||||
l1PrivateKeyHex = strings.TrimPrefix(strings.ToLower(l1PrivateKeyHex), "0x")
|
||||
l1PrivateKey, err := crypto.HexToECDSA(l1PrivateKeyHex)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("無效的 L1 私鑰: %w", err)
|
||||
return nil, fmt.Errorf("invalid L1 private key: %w", err)
|
||||
}
|
||||
|
||||
// 2. 如果沒有提供錢包地址,從私鑰派生
|
||||
// 2. If wallet address not provided, derive from private key
|
||||
if walletAddr == "" {
|
||||
walletAddr = crypto.PubkeyToAddress(*l1PrivateKey.Public().(*ecdsa.PublicKey)).Hex()
|
||||
logger.Infof("✓ 從私鑰派生錢包地址: %s", walletAddr)
|
||||
logger.Infof("✓ Derived wallet address from private key: %s", walletAddr)
|
||||
}
|
||||
|
||||
// 3. 確定 API URL 和 Chain ID
|
||||
// 3. Determine API URL and Chain ID
|
||||
baseURL := "https://mainnet.zklighter.elliot.ai"
|
||||
chainID := uint32(42766) // Mainnet Chain ID
|
||||
if testnet {
|
||||
@@ -87,7 +87,7 @@ func NewLighterTraderV2(l1PrivateKeyHex, walletAddr, apiKeyPrivateKeyHex string,
|
||||
chainID = uint32(42069) // Testnet Chain ID
|
||||
}
|
||||
|
||||
// 4. 創建 HTTP 客戶端
|
||||
// 4. Create HTTP client
|
||||
httpClient := lighterHTTP.NewClient(baseURL)
|
||||
|
||||
trader := &LighterTraderV2{
|
||||
@@ -100,24 +100,24 @@ func NewLighterTraderV2(l1PrivateKeyHex, walletAddr, apiKeyPrivateKeyHex string,
|
||||
chainID: chainID,
|
||||
httpClient: httpClient,
|
||||
apiKeyPrivateKey: apiKeyPrivateKeyHex,
|
||||
apiKeyIndex: 0, // 默認使用索引 0
|
||||
apiKeyIndex: 0, // Default to index 0
|
||||
symbolPrecision: make(map[string]SymbolPrecision),
|
||||
marketIndexMap: make(map[string]uint8),
|
||||
}
|
||||
|
||||
// 5. 初始化賬戶(獲取賬戶索引)
|
||||
// 5. Initialize account (get account index)
|
||||
if err := trader.initializeAccount(); err != nil {
|
||||
return nil, fmt.Errorf("初始化賬戶失敗: %w", err)
|
||||
return nil, fmt.Errorf("failed to initialize account: %w", err)
|
||||
}
|
||||
|
||||
// 6. 如果沒有 API Key,提示用戶需要生成
|
||||
// 6. If no API Key, prompt user to generate one
|
||||
if apiKeyPrivateKeyHex == "" {
|
||||
logger.Infof("⚠️ 未提供 API Key 私鑰,請調用 GenerateAndRegisterAPIKey() 生成")
|
||||
logger.Infof(" 或者從 LIGHTER 官網獲取現有的 API Key")
|
||||
logger.Infof("⚠️ No API Key private key provided, please call GenerateAndRegisterAPIKey() to generate")
|
||||
logger.Infof(" Or get an existing API Key from LIGHTER website")
|
||||
return trader, nil
|
||||
}
|
||||
|
||||
// 7. 創建 TxClient(用於簽名交易)
|
||||
// 7. Create TxClient (for signing transactions)
|
||||
txClient, err := lighterClient.NewTxClient(
|
||||
httpClient,
|
||||
apiKeyPrivateKeyHex,
|
||||
@@ -126,41 +126,41 @@ func NewLighterTraderV2(l1PrivateKeyHex, walletAddr, apiKeyPrivateKeyHex string,
|
||||
trader.chainID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("創建 TxClient 失敗: %w", err)
|
||||
return nil, fmt.Errorf("failed to create TxClient: %w", err)
|
||||
}
|
||||
|
||||
trader.txClient = txClient
|
||||
|
||||
// 8. 驗證 API Key 是否正確
|
||||
// 8. Verify API Key is correct
|
||||
if err := trader.checkClient(); err != nil {
|
||||
logger.Infof("⚠️ API Key 驗證失敗: %v", err)
|
||||
logger.Infof(" 您可能需要重新生成 API Key 或檢查配置")
|
||||
logger.Infof("⚠️ API Key verification failed: %v", err)
|
||||
logger.Infof(" You may need to regenerate API Key or check configuration")
|
||||
return trader, err
|
||||
}
|
||||
|
||||
logger.Infof("✓ LIGHTER 交易器初始化成功 (account=%d, apiKey=%d, testnet=%v)",
|
||||
logger.Infof("✓ LIGHTER trader initialized successfully (account=%d, apiKey=%d, testnet=%v)",
|
||||
trader.accountIndex, trader.apiKeyIndex, testnet)
|
||||
|
||||
return trader, nil
|
||||
}
|
||||
|
||||
// initializeAccount 初始化賬戶信息(獲取賬戶索引)
|
||||
// initializeAccount Initialize account information (get account index)
|
||||
func (t *LighterTraderV2) initializeAccount() error {
|
||||
// 通過 L1 地址獲取賬戶信息
|
||||
// Get account info by L1 address
|
||||
accountInfo, err := t.getAccountByL1Address()
|
||||
if err != nil {
|
||||
return fmt.Errorf("獲取賬戶信息失敗: %w", err)
|
||||
return fmt.Errorf("failed to get account info: %w", err)
|
||||
}
|
||||
|
||||
t.accountMutex.Lock()
|
||||
t.accountIndex = accountInfo.AccountIndex
|
||||
t.accountMutex.Unlock()
|
||||
|
||||
logger.Infof("✓ 賬戶索引: %d", t.accountIndex)
|
||||
logger.Infof("✓ Account index: %d", t.accountIndex)
|
||||
return nil
|
||||
}
|
||||
|
||||
// getAccountByL1Address 通過 L1 錢包地址獲取 LIGHTER 賬戶信息
|
||||
// getAccountByL1Address Get LIGHTER account info by L1 wallet address
|
||||
func (t *LighterTraderV2) getAccountByL1Address() (*AccountInfo, error) {
|
||||
endpoint := fmt.Sprintf("%s/api/v1/account?by=address&value=%s", t.baseURL, t.walletAddr)
|
||||
|
||||
@@ -181,67 +181,67 @@ func (t *LighterTraderV2) getAccountByL1Address() (*AccountInfo, error) {
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("獲取賬戶失敗 (status %d): %s", resp.StatusCode, string(body))
|
||||
return nil, fmt.Errorf("failed to get account (status %d): %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var accountInfo AccountInfo
|
||||
if err := json.Unmarshal(body, &accountInfo); err != nil {
|
||||
return nil, fmt.Errorf("解析賬戶響應失敗: %w", err)
|
||||
return nil, fmt.Errorf("failed to parse account response: %w", err)
|
||||
}
|
||||
|
||||
return &accountInfo, nil
|
||||
}
|
||||
|
||||
// checkClient 驗證 API Key 是否正確
|
||||
// checkClient Verify if API Key is correct
|
||||
func (t *LighterTraderV2) checkClient() error {
|
||||
if t.txClient == nil {
|
||||
return fmt.Errorf("TxClient 未初始化")
|
||||
return fmt.Errorf("TxClient not initialized")
|
||||
}
|
||||
|
||||
// 獲取服務器上註冊的 API Key 公鑰
|
||||
// Get API Key public key registered on server
|
||||
publicKey, err := t.httpClient.GetApiKey(t.accountIndex, t.apiKeyIndex)
|
||||
if err != nil {
|
||||
return fmt.Errorf("獲取 API Key 失敗: %w", err)
|
||||
return fmt.Errorf("failed to get API Key: %w", err)
|
||||
}
|
||||
|
||||
// 獲取本地 API Key 的公鑰
|
||||
// Get local API Key public key
|
||||
pubKeyBytes := t.txClient.GetKeyManager().PubKeyBytes()
|
||||
localPubKey := hexutil.Encode(pubKeyBytes[:])
|
||||
localPubKey = strings.Replace(localPubKey, "0x", "", 1)
|
||||
|
||||
// 比對公鑰
|
||||
// Compare public keys
|
||||
if publicKey != localPubKey {
|
||||
return fmt.Errorf("API Key 不匹配:本地=%s, 服務器=%s", localPubKey, publicKey)
|
||||
return fmt.Errorf("API Key mismatch: local=%s, server=%s", localPubKey, publicKey)
|
||||
}
|
||||
|
||||
logger.Infof("✓ API Key 驗證通過")
|
||||
logger.Infof("✓ API Key verification passed")
|
||||
return nil
|
||||
}
|
||||
|
||||
// GenerateAndRegisterAPIKey 生成新的 API Key 並註冊到 LIGHTER
|
||||
// 注意:這需要 L1 私鑰簽名,所以必須在有 L1 私鑰的情況下調用
|
||||
// GenerateAndRegisterAPIKey Generate new API Key and register to LIGHTER
|
||||
// Note: This requires L1 private key signature, so must be called with L1 private key available
|
||||
func (t *LighterTraderV2) GenerateAndRegisterAPIKey(seed string) (privateKey, publicKey string, err error) {
|
||||
// 這個功能需要調用官方 SDK 的 GenerateAPIKey 函數
|
||||
// 但這是在 sharedlib 中的 CGO 函數,無法直接在純 Go 代碼中調用
|
||||
// This function needs to call the official SDK's GenerateAPIKey function
|
||||
// But this is a CGO function in sharedlib, cannot be called directly in pure Go code
|
||||
//
|
||||
// 解決方案:
|
||||
// 1. 讓用戶從 LIGHTER 官網生成 API Key
|
||||
// 2. 或者我們可以實現一個簡單的 API Key 生成包裝器
|
||||
// Solutions:
|
||||
// 1. Let users generate API Key from LIGHTER website
|
||||
// 2. Or we can implement a simple API Key generation wrapper
|
||||
|
||||
return "", "", fmt.Errorf("GenerateAndRegisterAPIKey 功能待實現,請從 LIGHTER 官網生成 API Key")
|
||||
return "", "", fmt.Errorf("GenerateAndRegisterAPIKey feature not implemented yet, please generate API Key from LIGHTER website")
|
||||
}
|
||||
|
||||
// refreshAuthToken 刷新認證令牌(使用官方 SDK)
|
||||
// refreshAuthToken Refresh authentication token (using official SDK)
|
||||
func (t *LighterTraderV2) refreshAuthToken() error {
|
||||
if t.txClient == nil {
|
||||
return fmt.Errorf("TxClient 未初始化,請先設置 API Key")
|
||||
return fmt.Errorf("TxClient not initialized, please set API Key first")
|
||||
}
|
||||
|
||||
// 使用官方 SDK 生成認證令牌(有效期 7 小時)
|
||||
// Generate auth token using official SDK (valid for 7 hours)
|
||||
deadline := time.Now().Add(7 * time.Hour)
|
||||
authToken, err := t.txClient.GetAuthToken(deadline)
|
||||
if err != nil {
|
||||
return fmt.Errorf("生成認證令牌失敗: %w", err)
|
||||
return fmt.Errorf("failed to generate auth token: %w", err)
|
||||
}
|
||||
|
||||
t.accountMutex.Lock()
|
||||
@@ -249,31 +249,31 @@ func (t *LighterTraderV2) refreshAuthToken() error {
|
||||
t.tokenExpiry = deadline
|
||||
t.accountMutex.Unlock()
|
||||
|
||||
logger.Infof("✓ 認證令牌已生成(有效期至: %s)", t.tokenExpiry.Format(time.RFC3339))
|
||||
logger.Infof("✓ Auth token generated (valid until: %s)", t.tokenExpiry.Format(time.RFC3339))
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureAuthToken 確保認證令牌有效
|
||||
// ensureAuthToken Ensure authentication token is valid
|
||||
func (t *LighterTraderV2) ensureAuthToken() error {
|
||||
t.accountMutex.RLock()
|
||||
expired := time.Now().After(t.tokenExpiry.Add(-30 * time.Minute)) // 提前 30 分鐘刷新
|
||||
expired := time.Now().After(t.tokenExpiry.Add(-30 * time.Minute)) // Refresh 30 minutes early
|
||||
t.accountMutex.RUnlock()
|
||||
|
||||
if expired {
|
||||
logger.Info("🔄 認證令牌即將過期,刷新中...")
|
||||
logger.Info("🔄 Auth token about to expire, refreshing...")
|
||||
return t.refreshAuthToken()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetExchangeType 獲取交易所類型
|
||||
// GetExchangeType Get exchange type
|
||||
func (t *LighterTraderV2) GetExchangeType() string {
|
||||
return "lighter"
|
||||
}
|
||||
|
||||
// Cleanup 清理資源
|
||||
// Cleanup Clean up resources
|
||||
func (t *LighterTraderV2) Cleanup() error {
|
||||
logger.Info("⏹ LIGHTER 交易器清理完成")
|
||||
logger.Info("⏹ LIGHTER trader cleanup completed")
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user