Compare commits

..

No commits in common. "5c1b4ab00206e72957ce066e4ec56267cf4e8d68" and "504fcb67d3898d56c56f91bd9bfdf6b061b99114" have entirely different histories.

7 changed files with 111 additions and 169 deletions

View File

@ -3,13 +3,10 @@ package application
import (
"context"
"fmt"
"sort"
"strconv"
"strings"
"git.defalsify.org/vise.git/db"
"git.defalsify.org/vise.git/resource"
"git.grassecon.net/grassrootseconomics/sarafu-vise/config"
"git.grassecon.net/grassrootseconomics/sarafu-vise/store"
storedb "git.grassecon.net/grassrootseconomics/sarafu-vise/store/db"
dataserviceapi "github.com/grassrootseconomics/ussd-data-service/pkg/api"
@ -122,13 +119,14 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i
l.AddDomain("default")
flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error")
flag_no_stable_vouchers, _ := h.flagManager.GetFlag("flag_no_stable_vouchers")
// default response
res.FlagReset = append(res.FlagReset, flag_api_call_error)
res.Content = l.Get("Credit: %s KSH\nDebt: %s KSH\n", "0", "0")
// Fetch session data
_, activeBal, activeSym, _, publicKey, _, err := h.getSessionData(ctx, sessionId)
_, _, activeSym, _, publicKey, _, err := h.getSessionData(ctx, sessionId)
if err != nil {
return res, nil
}
@ -150,69 +148,51 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i
return res, nil
}
// Build stable voucher priority (lower index = higher priority)
stablePriority := make(map[string]int)
stableAddresses := config.StableVoucherAddresses()
for i, addr := range stableAddresses {
stablePriority[strings.ToLower(addr)] = i
}
// Helper: order vouchers (stable first, priority-based)
orderVouchers := func(vouchers []dataserviceapi.TokenHoldings) []dataserviceapi.TokenHoldings {
stable := make([]dataserviceapi.TokenHoldings, 0)
nonStable := make([]dataserviceapi.TokenHoldings, 0)
for _, v := range vouchers {
if isStableVoucher(v.TokenAddress) {
stable = append(stable, v)
} else {
nonStable = append(nonStable, v)
}
}
sort.SliceStable(stable, func(i, j int) bool {
ai := stablePriority[strings.ToLower(stable[i].TokenAddress)]
aj := stablePriority[strings.ToLower(stable[j].TokenAddress)]
return ai < aj
})
return append(stable, nonStable...)
}
// Remove active voucher
filteredVouchers := make([]dataserviceapi.TokenHoldings, 0, len(swappableVouchers))
// Filter stable vouchers (excluding active voucher)
filteredSwappableVouchers := make([]dataserviceapi.TokenHoldings, 0)
for _, v := range swappableVouchers {
if v.TokenSymbol != string(activeSym) {
filteredVouchers = append(filteredVouchers, v)
}
}
// Order remaining vouchers
orderedFilteredVouchers := orderVouchers(filteredVouchers)
// Process & store
data := store.ProcessVouchers(orderedFilteredVouchers)
dataMap := map[storedb.DataTyp]string{
storedb.DATA_VOUCHER_SYMBOLS: data.Symbols,
storedb.DATA_VOUCHER_BALANCES: data.Balances,
storedb.DATA_VOUCHER_DECIMALS: data.Decimals,
storedb.DATA_VOUCHER_ADDRESSES: data.Addresses,
}
for key, value := range dataMap {
if err := userStore.WriteEntry(ctx, sessionId, key, []byte(value)); err != nil {
logg.ErrorCtxf(ctx, "Failed to write data entry for sessionId: %s", sessionId, "key", key, "error", err)
if v.TokenSymbol == string(activeSym) {
continue
}
if isStableVoucher(v.TokenAddress) {
filteredSwappableVouchers = append(filteredSwappableVouchers, v)
}
}
// No stable vouchers → cannot pay debt
if len(filteredSwappableVouchers) == 0 {
res.FlagSet = append(res.FlagSet, flag_no_stable_vouchers)
return res, nil
}
res.FlagReset = append(res.FlagReset, flag_no_stable_vouchers)
// Process stable vouchers for later use
data := store.ProcessVouchers(filteredSwappableVouchers)
// Find active voucher data
activeSymStr := string(activeSym)
var activeData *dataserviceapi.TokenHoldings
for _, v := range swappableVouchers {
if v.TokenSymbol == activeSymStr {
activeData = &v
break
}
}
if activeData == nil {
return res, nil
}
// Credit = active voucher balance
scaledCredit := string(activeBal)
scaledCredit := store.ScaleDownBalance(
activeData.Balance,
activeData.TokenDecimals,
)
// Debt = sum of stable vouchers only
scaledDebt := "0"
for _, v := range orderedFilteredVouchers {
for _, v := range filteredSwappableVouchers {
scaled := store.ScaleDownBalance(v.Balance, v.TokenDecimals)
scaledDebt = store.AddDecimalStrings(scaledDebt, scaled)
}
@ -235,6 +215,21 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i
kshFormattedCredit, _ := store.TruncateDecimalString(creditKsh, 0)
kshFormattedDebt, _ := store.TruncateDecimalString(debtKsh, 0)
// Persist swap data
dataMap := map[storedb.DataTyp]string{
storedb.DATA_POOL_TO_SYMBOLS: data.Symbols,
storedb.DATA_POOL_TO_BALANCES: data.Balances,
storedb.DATA_POOL_TO_DECIMALS: data.Decimals,
storedb.DATA_POOL_TO_ADDRESSES: data.Addresses,
}
for key, value := range dataMap {
if err := userStore.WriteEntry(ctx, sessionId, key, []byte(value)); err != nil {
logg.ErrorCtxf(ctx, "Failed to write data entry for sessionId: %s", sessionId, "key", key, "error", err)
continue
}
}
res.Content = l.Get(
"Credit: %s KSH\nDebt: %s KSH\n",
kshFormattedCredit,

View File

@ -13,7 +13,7 @@ import (
"gopkg.in/leonelquinteros/gotext.v1"
)
// CalculateMaxPayDebt calculates the max debt removal based on the selected voucher
// CalculateMaxPayDebt calculates the max debt removal
func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, input []byte) (resource.Result, error) {
var res resource.Result
sessionId, ok := ctx.Value("SessionId").(string)
@ -29,28 +29,21 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu
l.AddDomain("default")
inputStr := string(input)
if inputStr == "0" || inputStr == "99" || inputStr == "88" || inputStr == "98" {
if inputStr == "0" || inputStr == "9" {
res.FlagReset = append(res.FlagReset, flag_low_swap_amount, flag_api_call_error)
return res, nil
}
userStore := h.userdataStore
// Fetch session data
_, _, activeSym, activeAddress, publicKey, activeDecimal, err := h.getSessionData(ctx, sessionId)
if err != nil {
return res, nil
}
// Resolve active pool
activePoolAddress, activePoolName, err := h.resolveActivePoolDetails(ctx, sessionId)
_, activePoolName, err := h.resolveActivePoolDetails(ctx, sessionId)
if err != nil {
res.FlagReset = append(res.FlagReset, flag_low_swap_amount, flag_api_call_error)
return res, err
}
// get the voucher data based on the input
metadata, err := store.GetVoucherData(ctx, userStore, sessionId, inputStr)
metadata, err := store.GetSwapToVoucherData(ctx, userStore, sessionId, "1")
if err != nil {
res.FlagReset = append(res.FlagReset, flag_low_swap_amount, flag_api_call_error)
return res, fmt.Errorf("failed to retrieve swap to voucher data: %v", err)
@ -60,26 +53,35 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu
return res, nil
}
logg.InfoCtxf(ctx, "Metadata from GetVoucherData:", "metadata", metadata)
logg.InfoCtxf(ctx, "Metadata from GetSwapToVoucherData:", "metadata", metadata)
// Store the active swap from data
if err := store.UpdateSwapFromVoucherData(ctx, userStore, sessionId, metadata); err != nil {
logg.ErrorCtxf(ctx, "failed on UpdateSwapFromVoucherData", "error", err)
// Store the active swap_to data
if err := store.UpdateSwapToVoucherData(ctx, userStore, sessionId, metadata); err != nil {
logg.ErrorCtxf(ctx, "failed on UpdateSwapToVoucherData", "error", err)
return res, err
}
// Get the max swap limit with the selected voucher
r, err := h.accountService.GetSwapFromTokenMaxLimit(ctx, string(activePoolAddress), metadata.TokenAddress, string(activeAddress), string(publicKey))
swapData, err := store.ReadSwapData(ctx, userStore, sessionId)
if err != nil {
return res, err
}
// call the api using the ActivePoolAddress, ActiveSwapToAddress as the from (FT), ActiveSwapFromAddress as the to (AT) and PublicKey to get the swap max limit
r, err := h.accountService.GetSwapFromTokenMaxLimit(ctx, swapData.ActivePoolAddress, swapData.ActiveSwapToAddress, swapData.ActiveSwapFromAddress, swapData.PublicKey)
if err != nil {
res.FlagSet = append(res.FlagSet, flag_api_call_error)
logg.ErrorCtxf(ctx, "failed on GetSwapFromTokenMaxLimit", "error", err)
return res, nil
}
maxLimit := r.Max
err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(r.Max))
if err != nil {
logg.ErrorCtxf(ctx, "failed to write full max amount entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", r.Max, "error", err)
return res, err
}
// Scale down the amount
maxAmountStr := store.ScaleDownBalance(maxLimit, metadata.TokenDecimals)
maxAmountStr := store.ScaleDownBalance(r.Max, swapData.ActiveSwapToDecimal)
if err != nil {
return res, err
}
@ -106,32 +108,12 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu
return res, err
}
// Do a pool quote to get the max AT that can be removed (gotten)
// if we swapped the max of the FT
// call the API to get the quote
qoute, err := h.accountService.GetPoolSwapQuote(ctx, maxLimit, string(publicKey), metadata.TokenAddress, string(activePoolAddress), string(activeAddress))
if err != nil {
flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error")
res.FlagSet = append(res.FlagSet, flag_api_call_error)
res.Content = l.Get("Your request failed. Please try again later.")
logg.ErrorCtxf(ctx, "failed on poolSwap", "error", err)
return res, nil
}
// Scale down the quoted amount
quoteAmountStr := store.ScaleDownBalance(qoute.OutValue, string(activeDecimal))
// Format to 2 decimal places
quoteStr, _ := store.TruncateDecimalString(string(quoteAmountStr), 2)
res.Content = l.Get(
"You can remove a max of %s %s from '%s'\nEnter amount of %s:(Max: %s)",
quoteStr,
string(activeSym),
string(activePoolName),
metadata.TokenSymbol,
"You can remove a maximum of %s %s from '%s'\n\nEnter amount of %s:",
maxStr,
swapData.ActiveSwapToSym,
string(activePoolName),
swapData.ActiveSwapToSym,
)
res.FlagReset = append(res.FlagReset, flag_low_swap_amount, flag_api_call_error)

View File

@ -148,36 +148,7 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b
}
}
// Build stable voucher priority (lower index = higher priority)
stablePriority := make(map[string]int)
stableAddresses := config.StableVoucherAddresses()
for i, addr := range stableAddresses {
stablePriority[strings.ToLower(addr)] = i
}
// Helper: order vouchers (stable first, priority-based)
orderVouchers := func(vouchers []dataserviceapi.TokenHoldings) []dataserviceapi.TokenHoldings {
stable := make([]dataserviceapi.TokenHoldings, 0)
nonStable := make([]dataserviceapi.TokenHoldings, 0)
for _, v := range vouchers {
if isStableVoucher(v.TokenAddress) {
stable = append(stable, v)
} else {
nonStable = append(nonStable, v)
}
}
sort.SliceStable(stable, func(i, j int) bool {
ai := stablePriority[strings.ToLower(stable[i].TokenAddress)]
aj := stablePriority[strings.ToLower(stable[j].TokenAddress)]
return ai < aj
})
return append(stable, nonStable...)
}
// Remove active voucher
// Filter out the active voucher from vouchersResp
filteredVouchers := make([]dataserviceapi.TokenHoldings, 0, len(vouchersResp))
for _, v := range vouchersResp {
if v.TokenSymbol != activeSymStr {
@ -185,11 +156,8 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b
}
}
// Order remaining vouchers
orderedFilteredVouchers := orderVouchers(filteredVouchers)
// Process & store
data := store.ProcessVouchers(orderedFilteredVouchers)
// Store all voucher data (excluding the current active voucher)
data := store.ProcessVouchers(filteredVouchers)
dataMap := map[storedb.DataTyp]string{
storedb.DATA_VOUCHER_SYMBOLS: data.Symbols,
@ -202,27 +170,47 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b
for key, value := range dataMap {
if err := userStore.WriteEntry(ctx, sessionId, key, []byte(value)); err != nil {
logg.ErrorCtxf(ctx, "Failed to write data entry for sessionId: %s", sessionId, "key", key, "error", err)
continue
}
}
// Order all vouchers
orderedVouchers := orderVouchers(vouchersResp)
// Get stable voucher priority order (lower index = higher priority)
stablePriority := make(map[string]int)
stableAddresses := config.StableVoucherAddresses()
// Stable voucher presence flag (based on full list)
hasStable := false
for _, v := range orderedVouchers {
for i, addr := range stableAddresses {
stablePriority[strings.ToLower(addr)] = i
}
// Split vouchers into stable and non-stable
stableVouchers := make([]dataserviceapi.TokenHoldings, 0)
nonStableVouchers := make([]dataserviceapi.TokenHoldings, 0)
for _, v := range vouchersResp {
if isStableVoucher(v.TokenAddress) {
hasStable = true
break
stableVouchers = append(stableVouchers, v)
} else {
nonStableVouchers = append(nonStableVouchers, v)
}
}
if !hasStable {
// No stable vouchers at all
if len(stableVouchers) == 0 {
res.FlagSet = append(res.FlagSet, flag_no_stable_vouchers)
} else {
res.FlagReset = append(res.FlagReset, flag_no_stable_vouchers)
}
// Sort stable vouchers by configured priority
sort.SliceStable(stableVouchers, func(i, j int) bool {
ai := stablePriority[strings.ToLower(stableVouchers[i].TokenAddress)]
aj := stablePriority[strings.ToLower(stableVouchers[j].TokenAddress)]
return ai < aj
})
// Final ordered list: stable first, then others
orderedVouchers := append(stableVouchers, nonStableVouchers...)
// Process ALL vouchers (stable first)
orderedVoucherData := store.ProcessVouchers(orderedVouchers)

View File

@ -93,8 +93,6 @@ const (
DATA_SEND_TRANSACTION_TYPE
// Holds the recipient formatted phone number
DATA_RECIPIENT_PHONE_NUMBER
// Currently active swap from balance for the swap
DATA_ACTIVE_SWAP_FROM_BALANCE
)
const (

View File

@ -189,24 +189,3 @@ func UpdateSwapToVoucherData(ctx context.Context, store DataStore, sessionId str
return nil
}
// UpdateSwapFromVoucherData updates the active swap from voucher data in the DataStore.
func UpdateSwapFromVoucherData(ctx context.Context, store DataStore, sessionId string, data *dataserviceapi.TokenHoldings) error {
logg.InfoCtxf(ctx, "UpdateSwapFromVoucherData", "data", data)
// Active swap to voucher data entries
activeEntries := map[storedb.DataTyp][]byte{
storedb.DATA_ACTIVE_SWAP_FROM_SYM: []byte(data.TokenSymbol),
storedb.DATA_ACTIVE_SWAP_FROM_DECIMAL: []byte(data.TokenDecimals),
storedb.DATA_ACTIVE_SWAP_FROM_ADDRESS: []byte(data.TokenAddress),
storedb.DATA_ACTIVE_SWAP_FROM_BALANCE: []byte(data.Balance),
}
// Write active data
for key, value := range activeEntries {
if err := store.WriteEntry(ctx, sessionId, key, value); err != nil {
return err
}
}
return nil
}