btc-pay-checker/internal/services/btc/listaddressgroupings.go

125 lines
3.0 KiB
Go

package btc
import (
"encoding/json"
"fmt"
"log"
)
type ListAddressGroupingsResponse struct {
Result [][][]any `json:"result"`
Error any `json:"error"`
ID string `json:"id"`
}
func NewListAddressGroupingsResponse(bts []byte) (*ListAddressGroupingsResponse, error) {
resp := new(ListAddressGroupingsResponse)
err := json.Unmarshal(bts, resp)
if err != nil {
return nil, err
}
return resp, nil
}
// func (b *bitcoinService) listaddressgroupings() ([][]any, error) {
// req := b.NewRPCRequest().WithMethod(LIST_ADDRESS_GROUPINGS)
// if req == nil {
// return nil, fmt.Errorf("NewRPCRequest %s is nil", LIST_ADDRESS_GROUPINGS)
// }
// resp, err := req.Call(nil)
// if err != nil {
// return nil, fmt.Errorf("req.Call: %s", err)
// }
// strinResp := string(resp)
// if strinResp == "" {
// return nil, fmt.Errorf("strinResp: %s", err)
// }
// log.Println(strinResp)
// addressResp, err := NewListAddressGroupingsResponse(resp)
// if err != nil {
// return nil, fmt.Errorf("NewFundTransactionResponse: %s", err)
// }
// if addressResp.Error != nil {
// return nil, fmt.Errorf("raw.Error: %+v", addressResp.Error)
// }
// if len(addressResp.Result) != 1 {
// return nil, fmt.Errorf("no addresses found")
// }
// if len(addressResp.Result[0]) <= 0 {
// return nil, fmt.Errorf("no addresses found")
// }
// return addressResp.Result[0], nil
// }
type AddressGrouping struct {
address string
funds float64
}
func (b *BitcoinService) listaddressgroupingsWithFunds() ([]AddressGrouping, error) {
return b.getAddressGroupings(true)
}
func (b *BitcoinService) getAddressGroupings(withFunds bool) ([]AddressGrouping, error) {
req := b.NewRPCRequest().WithMethod(LIST_ADDRESS_GROUPINGS)
if req == nil {
return nil, fmt.Errorf("NewRPCRequest %s is nil", LIST_ADDRESS_GROUPINGS)
}
resp, err := req.Call()
if err != nil {
return nil, fmt.Errorf("req.Call: %s", err)
}
strinResp := string(resp)
if strinResp == "" {
return nil, fmt.Errorf("strinResp: %s", err)
}
addressResp, err := NewListAddressGroupingsResponse(resp)
if err != nil {
return nil, fmt.Errorf("NewListAddressGroupingsResponse: %s", err)
}
if addressResp.Error != nil {
return nil, fmt.Errorf("raw.Error: %+v", addressResp.Error)
}
if len(addressResp.Result) != 1 {
return nil, fmt.Errorf("no addresses found")
}
if len(addressResp.Result[0]) <= 0 {
return nil, fmt.Errorf("no addresses found")
}
var addressList []AddressGrouping
for i := range addressResp.Result[0] {
addressRaw, fundsRaw := addressResp.Result[0][i][0], addressResp.Result[0][i][1]
address, ok := addressRaw.(string)
if !ok {
log.Fatalf("Address is not a string: %v", addressRaw)
continue
}
funds, ok := fundsRaw.(float64)
if !ok {
log.Fatalf("Funds is not a float64: %v", fundsRaw)
continue
}
if withFunds && funds <= 0.0 {
continue
}
addressList = append(addressList, AddressGrouping{address: address, funds: funds})
}
return addressList, nil
}