|
| 1 | +package solana |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "net/http" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/anilcse/cosmoscope/internal/config" |
| 13 | + "github.com/anilcse/cosmoscope/internal/portfolio" |
| 14 | + "github.com/anilcse/cosmoscope/internal/price" |
| 15 | + "github.com/anilcse/cosmoscope/pkg/utils" |
| 16 | +) |
| 17 | + |
| 18 | +var httpClient = &http.Client{Timeout: 15 * time.Second} |
| 19 | + |
| 20 | +func QueryBalances(network config.SolanaNetwork, address string, balanceChan chan<- portfolio.Balance) { |
| 21 | + if network.RPC == "" { |
| 22 | + return |
| 23 | + } |
| 24 | + |
| 25 | + networkName := network.Name |
| 26 | + if networkName == "" { |
| 27 | + networkName = "solana" |
| 28 | + } |
| 29 | + |
| 30 | + if balance, ok := querySOLBalance(network.RPC, address, networkName); ok && balance.Amount > 0 { |
| 31 | + balanceChan <- balance |
| 32 | + } |
| 33 | + |
| 34 | + for _, programID := range []string{tokenProgramID, token2022Program} { |
| 35 | + tokens, err := querySPLBalances(network.RPC, address, programID, networkName) |
| 36 | + if err != nil { |
| 37 | + fmt.Printf("Error fetching SPL balances for %s: %v\n", address, err) |
| 38 | + continue |
| 39 | + } |
| 40 | + for _, token := range tokens { |
| 41 | + balanceChan <- token |
| 42 | + } |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +func querySOLBalance(rpc, address, networkName string) (portfolio.Balance, bool) { |
| 47 | + result, err := rpcCall(rpc, "getBalance", []interface{}{address}) |
| 48 | + if err != nil { |
| 49 | + fmt.Printf("Error fetching SOL balance for %s: %v\n", address, err) |
| 50 | + return portfolio.Balance{}, false |
| 51 | + } |
| 52 | + |
| 53 | + var balance balanceResult |
| 54 | + if err := json.Unmarshal(result, &balance); err != nil { |
| 55 | + fmt.Printf("Error decoding SOL balance for %s: %v\n", address, err) |
| 56 | + return portfolio.Balance{}, false |
| 57 | + } |
| 58 | + |
| 59 | + amount := float64(balance.Value) / lamportsPerSOL |
| 60 | + usdValue := price.CalculateUSDValue("SOL", amount) |
| 61 | + |
| 62 | + return portfolio.Balance{ |
| 63 | + Network: networkName, |
| 64 | + Account: address, |
| 65 | + Token: "SOL", |
| 66 | + Amount: amount, |
| 67 | + USDValue: usdValue, |
| 68 | + Decimals: 9, |
| 69 | + }, true |
| 70 | +} |
| 71 | + |
| 72 | +func querySPLBalances(rpc, address, programID, networkName string) ([]portfolio.Balance, error) { |
| 73 | + params := []interface{}{ |
| 74 | + address, |
| 75 | + map[string]string{"programId": programID}, |
| 76 | + map[string]string{"encoding": "jsonParsed"}, |
| 77 | + } |
| 78 | + |
| 79 | + result, err := rpcCall(rpc, "getTokenAccountsByOwner", params) |
| 80 | + if err != nil { |
| 81 | + return nil, err |
| 82 | + } |
| 83 | + |
| 84 | + var accounts tokenAccountsResult |
| 85 | + if err := json.Unmarshal(result, &accounts); err != nil { |
| 86 | + return nil, fmt.Errorf("decoding token accounts: %w", err) |
| 87 | + } |
| 88 | + |
| 89 | + var balances []portfolio.Balance |
| 90 | + for _, entry := range accounts.Value { |
| 91 | + info := entry.Account.Data.Parsed.Info |
| 92 | + if info.TokenAmount.UIAmount == 0 && info.TokenAmount.Amount == "0" { |
| 93 | + continue |
| 94 | + } |
| 95 | + |
| 96 | + symbol, decimals, ok := lookupMint(info.Mint) |
| 97 | + if !ok { |
| 98 | + continue |
| 99 | + } |
| 100 | + if symbol == "SOL" { |
| 101 | + continue // native SOL handled separately |
| 102 | + } |
| 103 | + if !price.HasPrice(symbol) { |
| 104 | + continue |
| 105 | + } |
| 106 | + |
| 107 | + amount := info.TokenAmount.UIAmount |
| 108 | + if amount == 0 { |
| 109 | + amount = utils.ParseAmount(info.TokenAmount.Amount, info.TokenAmount.Decimals) |
| 110 | + } |
| 111 | + |
| 112 | + balances = append(balances, portfolio.Balance{ |
| 113 | + Network: networkName, |
| 114 | + Account: address, |
| 115 | + Token: symbol, |
| 116 | + Amount: amount, |
| 117 | + USDValue: price.CalculateUSDValue(symbol, amount), |
| 118 | + Decimals: decimals, |
| 119 | + }) |
| 120 | + } |
| 121 | + |
| 122 | + return balances, nil |
| 123 | +} |
| 124 | + |
| 125 | +func rpcCall(rpc, method string, params []interface{}) (json.RawMessage, error) { |
| 126 | + payload, err := json.Marshal(rpcRequest{ |
| 127 | + JSONRPC: "2.0", |
| 128 | + ID: 1, |
| 129 | + Method: method, |
| 130 | + Params: params, |
| 131 | + }) |
| 132 | + if err != nil { |
| 133 | + return nil, err |
| 134 | + } |
| 135 | + |
| 136 | + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) |
| 137 | + defer cancel() |
| 138 | + |
| 139 | + req, err := http.NewRequestWithContext(ctx, http.MethodPost, rpc, bytes.NewReader(payload)) |
| 140 | + if err != nil { |
| 141 | + return nil, err |
| 142 | + } |
| 143 | + req.Header.Set("Content-Type", "application/json") |
| 144 | + |
| 145 | + resp, err := httpClient.Do(req) |
| 146 | + if err != nil { |
| 147 | + return nil, err |
| 148 | + } |
| 149 | + defer resp.Body.Close() |
| 150 | + |
| 151 | + body, err := io.ReadAll(resp.Body) |
| 152 | + if err != nil { |
| 153 | + return nil, err |
| 154 | + } |
| 155 | + |
| 156 | + var response rpcResponse |
| 157 | + if err := json.Unmarshal(body, &response); err != nil { |
| 158 | + return nil, fmt.Errorf("decoding rpc response: %w", err) |
| 159 | + } |
| 160 | + if response.Error != nil { |
| 161 | + return nil, fmt.Errorf("rpc error %d: %s", response.Error.Code, response.Error.Message) |
| 162 | + } |
| 163 | + if response.Result.raw == nil { |
| 164 | + return nil, fmt.Errorf("empty rpc result for %s", method) |
| 165 | + } |
| 166 | + |
| 167 | + return json.RawMessage(response.Result.raw), nil |
| 168 | +} |
0 commit comments