get_total_subwallet_balance.go raw

   1  package queries
   2  
   3  import (
   4  	"github.com/getAlby/hub/constants"
   5  	"github.com/getAlby/hub/db"
   6  	"gorm.io/datatypes"
   7  	"gorm.io/gorm"
   8  )
   9  
  10  func GetTotalSubwalletBalanceMsat(tx *gorm.DB) (int64, error) {
  11  	subwalletAppIDsQuery := tx.Model(&db.App{}).
  12  		Select("id").
  13  		Where(datatypes.JSONQuery("metadata").Equals(constants.SUBWALLET_APPSTORE_APP_ID, constants.METADATA_APPSTORE_APP_ID_KEY))
  14  
  15  	var received struct {
  16  		Sum int64
  17  	}
  18  	res := tx.
  19  		Table("transactions").
  20  		Select("SUM(amount_msat) as sum").
  21  		Where("app_id IN (?) AND type = ? AND state = ?", subwalletAppIDsQuery, constants.TRANSACTION_TYPE_INCOMING, constants.TRANSACTION_STATE_SETTLED).
  22  		Scan(&received)
  23  	if res.Error != nil {
  24  		return 0, res.Error
  25  	}
  26  
  27  	var spent struct {
  28  		Sum int64
  29  	}
  30  	res = tx.
  31  		Table("transactions").
  32  		Select("SUM(amount_msat + fee_msat + fee_reserve_msat) as sum").
  33  		Where("app_id IN (?) AND type = ? AND (state = ? OR state = ?)", subwalletAppIDsQuery, constants.TRANSACTION_TYPE_OUTGOING, constants.TRANSACTION_STATE_SETTLED, constants.TRANSACTION_STATE_PENDING).
  34  		Scan(&spent)
  35  	if res.Error != nil {
  36  		return 0, res.Error
  37  	}
  38  
  39  	return received.Sum - spent.Sum, nil
  40  }
  41