From adb7a402d0bc97a533ca571b3d3f2c1b5e2fde5e Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 22 Jan 2026 17:40:13 +0300 Subject: [PATCH 001/130] added the Pay debt top node --- services/registration/main.vis | 26 +++++++++++++------------ services/registration/pay_debt | 2 ++ services/registration/pay_debt.vis | 6 ++++++ services/registration/pay_debt_menu | 1 + services/registration/pay_debt_menu_swa | 1 + services/registration/pay_debt_swa | 2 ++ 6 files changed, 26 insertions(+), 12 deletions(-) create mode 100644 services/registration/pay_debt create mode 100644 services/registration/pay_debt.vis create mode 100644 services/registration/pay_debt_menu create mode 100644 services/registration/pay_debt_menu_swa create mode 100644 services/registration/pay_debt_swa diff --git a/services/registration/main.vis b/services/registration/main.vis index f210214..d23ae05 100644 --- a/services/registration/main.vis +++ b/services/registration/main.vis @@ -7,20 +7,22 @@ LOAD check_balance 128 RELOAD check_balance MAP check_balance MOUT send 1 -MOUT swap 2 -MOUT vouchers 3 -MOUT select_pool 4 -MOUT mpesa 5 -MOUT account 6 -MOUT help 7 +MOUT pay_debt 2 +MOUT swap 3 +MOUT vouchers 4 +MOUT select_pool 5 +MOUT mpesa 6 +MOUT account 7 +MOUT help 8 MOUT quit 9 HALT INCMP credit_send 1 -INCMP swap_to_list 2 -INCMP my_vouchers 3 -INCMP select_pool 4 -INCMP mpesa 5 -INCMP my_account 6 -INCMP help 7 +INCMP pay_debt 2 +INCMP swap_to_list 3 +INCMP my_vouchers 4 +INCMP select_pool 5 +INCMP mpesa 6 +INCMP my_account 7 +INCMP help 8 INCMP quit 9 INCMP . * diff --git a/services/registration/pay_debt b/services/registration/pay_debt new file mode 100644 index 0000000..6c4e62c --- /dev/null +++ b/services/registration/pay_debt @@ -0,0 +1,2 @@ +{{.calculate_pay_debt}} +Enter amount: \ No newline at end of file diff --git a/services/registration/pay_debt.vis b/services/registration/pay_debt.vis new file mode 100644 index 0000000..325a256 --- /dev/null +++ b/services/registration/pay_debt.vis @@ -0,0 +1,6 @@ +LOAD calculate_pay_debt 0 +RELOAD calculate_pay_debt +MAP calculate_pay_debt +MOUT back 0 +HALT +INCMP confirm_debt_removal * diff --git a/services/registration/pay_debt_menu b/services/registration/pay_debt_menu new file mode 100644 index 0000000..0f0629e --- /dev/null +++ b/services/registration/pay_debt_menu @@ -0,0 +1 @@ +Pay debt \ No newline at end of file diff --git a/services/registration/pay_debt_menu_swa b/services/registration/pay_debt_menu_swa new file mode 100644 index 0000000..7fc9f8a --- /dev/null +++ b/services/registration/pay_debt_menu_swa @@ -0,0 +1 @@ +Lipa deni \ No newline at end of file diff --git a/services/registration/pay_debt_swa b/services/registration/pay_debt_swa new file mode 100644 index 0000000..1e828f0 --- /dev/null +++ b/services/registration/pay_debt_swa @@ -0,0 +1,2 @@ +{{.calculate_pay_debt}} +Weka kiwango: \ No newline at end of file From 7441fde4af0c93d594ad8dd39d5d050262555f88 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 22 Jan 2026 17:40:49 +0300 Subject: [PATCH 002/130] added translations for the pay debt node --- services/registration/locale/swa/default.po | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/services/registration/locale/swa/default.po b/services/registration/locale/swa/default.po index 6ed288b..b77b0c6 100644 --- a/services/registration/locale/swa/default.po +++ b/services/registration/locale/swa/default.po @@ -71,4 +71,10 @@ msgid "You will get a prompt for your M-Pesa PIN shortly to send %s ksh and rece msgstr "Utapokea kidokezo cha PIN yako ya M-Pesa hivi karibuni kutuma %s ksh na kupokea ~ %s cUSD" msgid "Your request has been sent. Thank you for using Sarafu" -msgstr "Ombi lako limetumwa. Asante kwa kutumia huduma ya Sarafu" \ No newline at end of file +msgstr "Ombi lako limetumwa. Asante kwa kutumia huduma ya Sarafu" + +msgid "You can remove a maximum of %s %s from %s pool\n" +msgstr "Unaweza kuondoa kiwango cha juu cha %s %s kutoka kwenye bwawa la %s.\n" + +msgid "Please confirm that you will use %s %s to remove your debt of %s %s\n" +msgstr "Tafadhali thibitisha kwamba utatumia %s %s kulipa deni lako la %s %s.\nWeka PIN yako:" \ No newline at end of file From d0f7692fa21323f182996a2351241493628f81c6 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 22 Jan 2026 17:42:10 +0300 Subject: [PATCH 003/130] added a node for the pay debt confirmation --- services/registration/confirm_debt_removal | 2 ++ services/registration/confirm_debt_removal.vis | 13 +++++++++++++ 2 files changed, 15 insertions(+) create mode 100644 services/registration/confirm_debt_removal create mode 100644 services/registration/confirm_debt_removal.vis diff --git a/services/registration/confirm_debt_removal b/services/registration/confirm_debt_removal new file mode 100644 index 0000000..3943b54 --- /dev/null +++ b/services/registration/confirm_debt_removal @@ -0,0 +1,2 @@ +{{.confirm_debt_removal}} +Enter your PIN: \ No newline at end of file diff --git a/services/registration/confirm_debt_removal.vis b/services/registration/confirm_debt_removal.vis new file mode 100644 index 0000000..e5c79c8 --- /dev/null +++ b/services/registration/confirm_debt_removal.vis @@ -0,0 +1,13 @@ +LOAD confirm_debt_removal 0 +MAP confirm_debt_removal +CATCH api_failure flag_api_call_error 1 +CATCH invalid_credit_send_amount flag_invalid_amount 1 +MOUT back 0 +MOUT quit 9 +HALT +LOAD authorize_account 6 +RELOAD authorize_account +CATCH incorrect_pin flag_incorrect_pin 1 +INCMP _ 0 +INCMP quit 9 +INCMP initiate_pay_debt * From 101955c1b342324d948477ad3a4fb4679652b95b Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 22 Jan 2026 17:42:27 +0300 Subject: [PATCH 004/130] added a node to initialize the pay debt --- services/registration/initiate_pay_debt.vis | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 services/registration/initiate_pay_debt.vis diff --git a/services/registration/initiate_pay_debt.vis b/services/registration/initiate_pay_debt.vis new file mode 100644 index 0000000..7d20dbf --- /dev/null +++ b/services/registration/initiate_pay_debt.vis @@ -0,0 +1,4 @@ +LOAD reset_incorrect_pin 6 +CATCH _ flag_account_authorized 0 +LOAD initiate_pay_debt 0 +HALT From cbe5b211d8829bb486e8ea010e6d13bcc7c4657f Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 22 Jan 2026 17:42:52 +0300 Subject: [PATCH 005/130] added the local functions to the menu handler --- handlers/local.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/handlers/local.go b/handlers/local.go index a34be02..b3204a1 100644 --- a/handlers/local.go +++ b/handlers/local.go @@ -146,6 +146,9 @@ func (ls *LocalHandlerService) GetHandler(accountService remote.AccountService) ls.DbRs.AddLocalFunc("send_mpesa_min_limit", appHandlers.SendMpesaMinLimit) ls.DbRs.AddLocalFunc("send_mpesa_preview", appHandlers.SendMpesaPreview) ls.DbRs.AddLocalFunc("initiate_send_mpesa", appHandlers.InitiateSendMpesa) + ls.DbRs.AddLocalFunc("calculate_pay_debt", appHandlers.CalculatePayDebt) + ls.DbRs.AddLocalFunc("confirm_debt_removal", appHandlers.ConfirmDebtRemoval) + ls.DbRs.AddLocalFunc("initiate_pay_debt", appHandlers.InitiatePayDebt) ls.first = appHandlers.Init From e2ff3d20d5a76bbe72a26fec4e63c85b33e55c98 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Mon, 26 Jan 2026 13:28:31 +0300 Subject: [PATCH 006/130] updated the resolveActivePoolAddress to resolveActivePoolDetails --- handlers/application/mpesa.go | 2 +- handlers/application/send.go | 59 ++++++++++++++++++++++++++--------- 2 files changed, 46 insertions(+), 15 deletions(-) diff --git a/handlers/application/mpesa.go b/handlers/application/mpesa.go index a1b9e02..876cd95 100644 --- a/handlers/application/mpesa.go +++ b/handlers/application/mpesa.go @@ -106,7 +106,7 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ } // Resolve active pool address - activePoolAddress, err := h.resolveActivePoolAddress(ctx, sessionId) + activePoolAddress, _, err := h.resolveActivePoolDetails(ctx, sessionId) if err != nil { return res, err } diff --git a/handlers/application/send.go b/handlers/application/send.go index bbcea64..f7cdbfc 100644 --- a/handlers/application/send.go +++ b/handlers/application/send.go @@ -345,7 +345,7 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte) } // Resolve active pool address - activePoolAddress, err := h.resolveActivePoolAddress(ctx, sessionId) + activePoolAddress, _, err := h.resolveActivePoolDetails(ctx, sessionId) if err != nil { return res, err } @@ -479,22 +479,53 @@ func (h *MenuHandlers) getRecipientData(ctx context.Context, sessionId string) ( return } -func (h *MenuHandlers) resolveActivePoolAddress(ctx context.Context, sessionId string) ([]byte, error) { +func (h *MenuHandlers) resolveActivePoolDetails(ctx context.Context, sessionId string) (defaultPoolAddress, defaultPoolName []byte, err error) { store := h.userdataStore - addr, err := store.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_POOL_ADDRESS) - if err == nil { - return addr, nil + + // Try read address + defaultPoolAddress, err = store.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_POOL_ADDRESS) + if err != nil && !db.IsNotFound(err) { + logg.ErrorCtxf(ctx, "failed to read active pool address", "error", err) + return nil, nil, err } - if db.IsNotFound(err) { - defaultAddr := []byte(config.DefaultPoolAddress()) - if err := store.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_POOL_ADDRESS, defaultAddr); err != nil { - logg.ErrorCtxf(ctx, "failed to write default pool address", "error", err) - return nil, err - } - return defaultAddr, nil + + // Try read name + defaultPoolName, err = store.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_POOL_NAME) + if err != nil && !db.IsNotFound(err) { + logg.ErrorCtxf(ctx, "failed to read active pool name", "error", err) + return nil, nil, err } - logg.ErrorCtxf(ctx, "failed to read active pool address", "error", err) - return nil, err + + // If both exist, return them + if defaultPoolAddress != nil && defaultPoolName != nil { + return defaultPoolAddress, defaultPoolName, nil + } + + // Fallback to config defaults + defaultPoolAddress = []byte(config.DefaultPoolAddress()) + defaultPoolName = []byte(config.DefaultPoolName()) + + if err := store.WriteEntry( + ctx, + sessionId, + storedb.DATA_ACTIVE_POOL_ADDRESS, + defaultPoolAddress, + ); err != nil { + logg.ErrorCtxf(ctx, "failed to write default pool address", "error", err) + return nil, nil, err + } + + if err := store.WriteEntry( + ctx, + sessionId, + storedb.DATA_ACTIVE_POOL_NAME, + defaultPoolName, + ); err != nil { + logg.ErrorCtxf(ctx, "failed to write default pool name", "error", err) + return nil, nil, err + } + + return defaultPoolAddress, defaultPoolName, nil } func (h *MenuHandlers) calculateSendCreditLimits(ctx context.Context, poolAddress, fromAddress, toAddress, publicKey, fromDecimal, toDecimal []byte) (string, string, error) { From f7de79f51aec0e2d3d792b44aed437f35b3e118c Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Mon, 26 Jan 2026 13:32:44 +0300 Subject: [PATCH 007/130] added option to go back to the main menu --- services/registration/pay_debt.vis | 1 + 1 file changed, 1 insertion(+) diff --git a/services/registration/pay_debt.vis b/services/registration/pay_debt.vis index 325a256..eee4b2c 100644 --- a/services/registration/pay_debt.vis +++ b/services/registration/pay_debt.vis @@ -3,4 +3,5 @@ RELOAD calculate_pay_debt MAP calculate_pay_debt MOUT back 0 HALT +INCMP _ 0 INCMP confirm_debt_removal * From 07e0e877d57a1fc9d91a1072e776a2b1406534f4 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 29 Jan 2026 16:08:53 +0300 Subject: [PATCH 008/130] added data keys for the credit and debt values --- store/db/db.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/store/db/db.go b/store/db/db.go index 4cc3f57..5ecce84 100644 --- a/store/db/db.go +++ b/store/db/db.go @@ -93,6 +93,10 @@ const ( DATA_SEND_TRANSACTION_TYPE // Holds the recipient formatted phone number DATA_RECIPIENT_PHONE_NUMBER + // holds the current credit of the user + DATA_CURRENT_CREDIT + // holds the current debt of the user + DATA_CURRENT_DEBT ) const ( From cfc38402f0a9efe3a43bb397136ce5bff13c06c1 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 29 Jan 2026 16:14:04 +0300 Subject: [PATCH 009/130] display the credit and debt --- handlers/application/balance.go | 41 +++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index f5c0a0b..b27ab28 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -52,7 +52,25 @@ func (h *MenuHandlers) CheckBalance(ctx context.Context, sym string, input []byt return res, err } } - content, err = loadUserContent(ctx, string(activeSym), string(activeBal), string(accAlias)) + + // get current credit + currentCredit, err := store.ReadEntry(ctx, sessionId, storedb.DATA_CURRENT_CREDIT) + if err != nil { + if !db.IsNotFound(err) { + logg.ErrorCtxf(ctx, "failed to read currentCredit entry with", "key", storedb.DATA_CURRENT_CREDIT, "error", err) + return res, err + } + } + // get current debt + currentDebt, err := store.ReadEntry(ctx, sessionId, storedb.DATA_CURRENT_DEBT) + if err != nil { + if !db.IsNotFound(err) { + logg.ErrorCtxf(ctx, "failed to read currentDebt entry with", "key", storedb.DATA_CURRENT_DEBT, "error", err) + return res, err + } + } + + content, err = loadUserContent(ctx, string(activeSym), string(activeBal), string(accAlias), string(currentCredit), string(currentDebt)) if err != nil { return res, err } @@ -62,7 +80,7 @@ func (h *MenuHandlers) CheckBalance(ctx context.Context, sym string, input []byt } // loadUserContent loads the main user content in the main menu: the alias, balance and active symbol associated with active voucher -func loadUserContent(ctx context.Context, activeSym string, balance string, alias string) (string, error) { +func loadUserContent(ctx context.Context, activeSym, balance, alias, currectCredit, currentDebt string) (string, error) { var content string code := codeFromCtx(ctx) @@ -75,12 +93,25 @@ func loadUserContent(ctx context.Context, activeSym string, balance string, alia formattedAmount = "0.00" } - // format the final output + formattedCredit, err := store.TruncateDecimalString(currectCredit, 0) + if err != nil { + formattedCredit = "0" + } + + formattedDebt, err := store.TruncateDecimalString(currentDebt, 0) + if err != nil { + formattedDebt = "0" + } + + // format the final outputs balStr := fmt.Sprintf("%s %s", formattedAmount, activeSym) + creditStr := fmt.Sprintf("Credit: %s ksh", formattedCredit) + debtStr := fmt.Sprintf("Debt: %s ksh", formattedDebt) + if alias != "" { - content = l.Get("%s\nBalance: %s\n", alias, balStr) + content = l.Get("%s\nBalance: %s\n%s\n%s", alias, balStr, creditStr, debtStr) } else { - content = l.Get("Balance: %s\n", balStr) + content = l.Get("Balance: %s\n%s\n%s", balStr, creditStr, debtStr) } return content, nil } From 6bb87a7b3316edb1294a055dbc35f8b25548a801 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 29 Jan 2026 16:57:00 +0300 Subject: [PATCH 010/130] added the CalculateCreditAndDebt function --- handlers/application/balance.go | 113 ++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index b27ab28..dfab8ff 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -3,11 +3,13 @@ package application import ( "context" "fmt" + "strconv" "git.defalsify.org/vise.git/db" "git.defalsify.org/vise.git/resource" "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" "gopkg.in/leonelquinteros/gotext.v1" ) @@ -129,3 +131,114 @@ func (h *MenuHandlers) FetchCommunityBalance(ctx context.Context, sym string, in res.Content = l.Get("Community Balance: 0.00") return res, nil } + +// CalculateCreditAndDebt calls the API to get the credit and debt +// uses the pretium rates to convert the value to Ksh +func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, input []byte) (resource.Result, error) { + var res resource.Result + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + + userStore := h.userdataStore + + code := codeFromCtx(ctx) + l := gotext.NewLocale(translationDir, code) + l.AddDomain("default") + + flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error") + + // Fetch session data + _, _, activeSym, _, publicKey, _, err := h.getSessionData(ctx, sessionId) + if err != nil { + return res, err + } + + // Get active pool address and symbol or fall back to default + activePoolAddress, _, err := h.resolveActivePoolDetails(ctx, sessionId) + if err != nil { + return res, err + } + + // call the api using the activePoolAddress to get a list of SwapToSymbolsData + swappableVouchers, err := h.accountService.GetPoolSwappableFromVouchers(ctx, string(activePoolAddress), string(publicKey)) + if err != nil { + res.FlagSet = append(res.FlagSet, flag_api_call_error) + logg.ErrorCtxf(ctx, "failed on GetPoolSwappableFromVouchers", "error", err) + return res, err + } + + logg.InfoCtxf(ctx, "GetPoolSwappableFromVouchers", "swappable vouchers", swappableVouchers) + + // Return if there are no vouchers + if len(swappableVouchers) == 0 { + return res, nil + } + + // Find the matching voucher data + activeSymStr := string(activeSym) + var activeData *dataserviceapi.TokenHoldings + for _, voucher := range swappableVouchers { + if voucher.TokenSymbol == activeSymStr { + activeData = &voucher + break + } + } + + if activeData == nil { + logg.InfoCtxf(ctx, "activeSym not found in vouchers, returning 0", "activeSym", activeSymStr) + return res, nil + } + + // Scale down the active balance (credit) + // Max swappable value from pool using the active token + scaledCredit := store.ScaleDownBalance(activeData.Balance, activeData.TokenDecimals) + + // Calculate total debt (sum of other vouchers) + scaledDebt := "0" + + for _, voucher := range swappableVouchers { + // Skip the active token + if voucher.TokenSymbol == activeSymStr { + continue + } + + scaled := store.ScaleDownBalance(voucher.Balance, voucher.TokenDecimals) + + // Add scaled balances (decimal-safe) + scaledDebt = store.AddDecimalStrings(scaledDebt, scaled) + } + + // call the mpesa rates API to get the rates + rates, err := h.accountService.GetMpesaOnrampRates(ctx) + if err != nil { + 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 GetMpesaOnrampRates", "error", err) + return res, nil + } + + creditFloat, _ := strconv.ParseFloat(scaledCredit, 64) + creditksh := fmt.Sprintf("%f", creditFloat*rates.Buy) + kshFormattedCredit, _ := store.TruncateDecimalString(creditksh, 0) + + debtFloat, _ := strconv.ParseFloat(scaledDebt, 64) + debtksh := fmt.Sprintf("%f", debtFloat*rates.Buy) + kshFormattedDebt, _ := store.TruncateDecimalString(debtksh, 0) + + dataMap := map[storedb.DataTyp]string{ + storedb.DATA_CURRENT_CREDIT: kshFormattedCredit, + storedb.DATA_CURRENT_DEBT: kshFormattedDebt, + } + + // Write data entries + 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 + } + } + + return res, nil +} From ea9875584fd2666193fb56a0456fe78f46e4324a Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 29 Jan 2026 16:59:02 +0300 Subject: [PATCH 011/130] added the calc_credit_debt to the main.vis and local handler --- handlers/local.go | 1 + services/registration/main.vis | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/handlers/local.go b/handlers/local.go index b3204a1..4c13794 100644 --- a/handlers/local.go +++ b/handlers/local.go @@ -81,6 +81,7 @@ func (ls *LocalHandlerService) GetHandler(accountService remote.AccountService) ls.DbRs.AddLocalFunc("check_account_status", appHandlers.CheckAccountStatus) ls.DbRs.AddLocalFunc("authorize_account", appHandlers.Authorize) ls.DbRs.AddLocalFunc("quit", appHandlers.Quit) + ls.DbRs.AddLocalFunc("calc_credit_debt", appHandlers.CalculateCreditAndDebt) ls.DbRs.AddLocalFunc("check_balance", appHandlers.CheckBalance) ls.DbRs.AddLocalFunc("validate_recipient", appHandlers.ValidateRecipient) ls.DbRs.AddLocalFunc("transaction_reset", appHandlers.TransactionReset) diff --git a/services/registration/main.vis b/services/registration/main.vis index d23ae05..2ce38f3 100644 --- a/services/registration/main.vis +++ b/services/registration/main.vis @@ -3,7 +3,10 @@ RELOAD clear_temporary_value LOAD manage_vouchers 160 RELOAD manage_vouchers CATCH api_failure flag_api_call_error 1 -LOAD check_balance 128 +LOAD calc_credit_debt 60 +RELOAD calc_credit_debt +CATCH api_failure flag_api_call_error 1 +LOAD check_balance 148 RELOAD check_balance MAP check_balance MOUT send 1 From 0a69e04229bacda9a9febbdf802892c5b4c38c49 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 29 Jan 2026 17:00:24 +0300 Subject: [PATCH 012/130] added helper functions to add scaled down balances --- store/vouchers.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/store/vouchers.go b/store/vouchers.go index efb59ed..dc849c6 100644 --- a/store/vouchers.go +++ b/store/vouchers.go @@ -225,3 +225,46 @@ func FormatVoucherList(ctx context.Context, symbolsData, balancesData string) [] } return combined } + +// AddDecimalStrings adds two decimal numbers represented as strings +// and returns the result as a string without losing precision. +func AddDecimalStrings(a, b string) string { + x, ok := new(big.Rat).SetString(a) + if !ok { + x = new(big.Rat) + } + + y, ok := new(big.Rat).SetString(b) + if !ok { + y = new(big.Rat) + } + + x.Add(x, y) + + // Convert back to string without scientific notation + return x.FloatString(maxDecimalPlaces(x, y)) +} + +// maxDecimalPlaces ensures we preserve enough decimal precision +func maxDecimalPlaces(rats ...*big.Rat) int { + max := 0 + for _, r := range rats { + if r == nil { + continue + } + if d := decimalPlaces(r); d > max { + max = d + } + } + return max +} + +func decimalPlaces(r *big.Rat) int { + s := r.FloatString(18) + for i := len(s) - 1; i >= 0; i-- { + if s[i] == '.' { + return len(s) - i - 1 + } + } + return 0 +} From ead5dd7b8c2f79524e6ef252ace3de0086e1314d Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 29 Jan 2026 17:10:20 +0300 Subject: [PATCH 013/130] store the filtered vouchers from the GetPoolSwappableFromVouchers --- handlers/application/balance.go | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index dfab8ff..e3b67ec 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -176,6 +176,19 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i return res, nil } + // Filter out the active voucher from swappableVouchers + filteredSwappableVouchers := make([]dataserviceapi.TokenHoldings, 0, len(swappableVouchers)) + for _, s := range swappableVouchers { + if s.TokenSymbol != string(activeSym) { + filteredSwappableVouchers = append(filteredSwappableVouchers, s) + } + } + + // Store as filtered swap to list data (excluding the current active voucher) for future reference + data := store.ProcessVouchers(filteredSwappableVouchers) + + logg.InfoCtxf(ctx, "ProcessVouchers", "data", data) + // Find the matching voucher data activeSymStr := string(activeSym) var activeData *dataserviceapi.TokenHoldings @@ -228,8 +241,12 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i kshFormattedDebt, _ := store.TruncateDecimalString(debtksh, 0) dataMap := map[storedb.DataTyp]string{ - storedb.DATA_CURRENT_CREDIT: kshFormattedCredit, - storedb.DATA_CURRENT_DEBT: kshFormattedDebt, + 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, + storedb.DATA_CURRENT_CREDIT: kshFormattedCredit, + storedb.DATA_CURRENT_DEBT: kshFormattedDebt, } // Write data entries From 46e98b5b9ebffc6fea869582fabf7b7ea0fa16a9 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 29 Jan 2026 19:17:38 +0300 Subject: [PATCH 014/130] update the translations --- services/registration/locale/swa/default.po | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/registration/locale/swa/default.po b/services/registration/locale/swa/default.po index b77b0c6..e1188d7 100644 --- a/services/registration/locale/swa/default.po +++ b/services/registration/locale/swa/default.po @@ -73,8 +73,8 @@ msgstr "Utapokea kidokezo cha PIN yako ya M-Pesa hivi karibuni kutuma %s ksh na msgid "Your request has been sent. Thank you for using Sarafu" msgstr "Ombi lako limetumwa. Asante kwa kutumia huduma ya Sarafu" -msgid "You can remove a maximum of %s %s from %s pool\n" -msgstr "Unaweza kuondoa kiwango cha juu cha %s %s kutoka kwenye bwawa la %s.\n" +msgid "You can remove a maximum of %s %s from '%s' pool\n\nEnter amount of %s:" +msgstr "Unaweza kuondoa kiwango cha juu cha %s %s kutoka kwenye '%s'\n\nWeka kiwango cha %s:" msgid "Please confirm that you will use %s %s to remove your debt of %s %s\n" msgstr "Tafadhali thibitisha kwamba utatumia %s %s kulipa deni lako la %s %s.\nWeka PIN yako:" \ No newline at end of file From a4f036c88d8c8d937b817ec77c83cb4d036627a2 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 29 Jan 2026 19:29:35 +0300 Subject: [PATCH 015/130] remove the amount as it is present in the response content --- services/registration/pay_debt | 3 +-- services/registration/pay_debt_swa | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/services/registration/pay_debt b/services/registration/pay_debt index 6c4e62c..0fa2022 100644 --- a/services/registration/pay_debt +++ b/services/registration/pay_debt @@ -1,2 +1 @@ -{{.calculate_pay_debt}} -Enter amount: \ No newline at end of file +{{.calculate_pay_debt}} \ No newline at end of file diff --git a/services/registration/pay_debt_swa b/services/registration/pay_debt_swa index 1e828f0..0fa2022 100644 --- a/services/registration/pay_debt_swa +++ b/services/registration/pay_debt_swa @@ -1,2 +1 @@ -{{.calculate_pay_debt}} -Weka kiwango: \ No newline at end of file +{{.calculate_pay_debt}} \ No newline at end of file From 88b5a33c2e1b50d2979dfd9d02ee8e4db003afe3 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 29 Jan 2026 19:37:33 +0300 Subject: [PATCH 016/130] update the sym name to be more descriptive --- handlers/local.go | 2 +- services/registration/pay_debt | 2 +- services/registration/pay_debt.vis | 6 +++--- services/registration/pay_debt_swa | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/handlers/local.go b/handlers/local.go index 4c13794..7c4b696 100644 --- a/handlers/local.go +++ b/handlers/local.go @@ -147,7 +147,7 @@ func (ls *LocalHandlerService) GetHandler(accountService remote.AccountService) ls.DbRs.AddLocalFunc("send_mpesa_min_limit", appHandlers.SendMpesaMinLimit) ls.DbRs.AddLocalFunc("send_mpesa_preview", appHandlers.SendMpesaPreview) ls.DbRs.AddLocalFunc("initiate_send_mpesa", appHandlers.InitiateSendMpesa) - ls.DbRs.AddLocalFunc("calculate_pay_debt", appHandlers.CalculatePayDebt) + ls.DbRs.AddLocalFunc("calculate_max_pay_debt", appHandlers.CalculateMaxPayDebt) ls.DbRs.AddLocalFunc("confirm_debt_removal", appHandlers.ConfirmDebtRemoval) ls.DbRs.AddLocalFunc("initiate_pay_debt", appHandlers.InitiatePayDebt) diff --git a/services/registration/pay_debt b/services/registration/pay_debt index 0fa2022..1e2b322 100644 --- a/services/registration/pay_debt +++ b/services/registration/pay_debt @@ -1 +1 @@ -{{.calculate_pay_debt}} \ No newline at end of file +{{.calculate_max_pay_debt}} \ No newline at end of file diff --git a/services/registration/pay_debt.vis b/services/registration/pay_debt.vis index eee4b2c..1b5a819 100644 --- a/services/registration/pay_debt.vis +++ b/services/registration/pay_debt.vis @@ -1,6 +1,6 @@ -LOAD calculate_pay_debt 0 -RELOAD calculate_pay_debt -MAP calculate_pay_debt +LOAD calculate_max_pay_debt 0 +RELOAD calculate_max_pay_debt +MAP calculate_max_pay_debt MOUT back 0 HALT INCMP _ 0 diff --git a/services/registration/pay_debt_swa b/services/registration/pay_debt_swa index 0fa2022..1e2b322 100644 --- a/services/registration/pay_debt_swa +++ b/services/registration/pay_debt_swa @@ -1 +1 @@ -{{.calculate_pay_debt}} \ No newline at end of file +{{.calculate_max_pay_debt}} \ No newline at end of file From 4dfccb3ff2fc176d1ccb0e4d84be48fa079b532e Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 30 Jan 2026 10:22:36 +0300 Subject: [PATCH 017/130] log the correct fields --- handlers/application/poolswap.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/handlers/application/poolswap.go b/handlers/application/poolswap.go index 7426cd9..1c6f923 100644 --- a/handlers/application/poolswap.go +++ b/handlers/application/poolswap.go @@ -303,7 +303,7 @@ func (h *MenuHandlers) SwapPreview(ctx context.Context, sym string, input []byte // store the user's input amount in the temporary value err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(inputStr)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write swap amount entry with", "key", storedb.DATA_ACTIVE_SWAP_AMOUNT, "value", finalAmountStr, "error", err) + logg.ErrorCtxf(ctx, "failed to write inputStr amount entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", inputStr, "error", err) return res, err } From ca2a50375b1225d8067d92351d807f98ebdf3436 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 30 Jan 2026 15:13:33 +0300 Subject: [PATCH 018/130] added functions to perform the debt removal --- handlers/application/paydebt.go | 263 ++++++++++++++++++++++++++++++++ 1 file changed, 263 insertions(+) create mode 100644 handlers/application/paydebt.go diff --git a/handlers/application/paydebt.go b/handlers/application/paydebt.go new file mode 100644 index 0000000..b60c426 --- /dev/null +++ b/handlers/application/paydebt.go @@ -0,0 +1,263 @@ +package application + +import ( + "context" + "fmt" + "strconv" + + "git.defalsify.org/vise.git/resource" + "git.grassecon.net/grassrootseconomics/sarafu-vise/store" + storedb "git.grassecon.net/grassrootseconomics/sarafu-vise/store/db" + "gopkg.in/leonelquinteros/gotext.v1" +) + +// 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) + if !ok { + return res, fmt.Errorf("missing session") + } + + flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error") + flag_low_swap_amount, _ := h.flagManager.GetFlag("flag_low_swap_amount") + + code := codeFromCtx(ctx) + l := gotext.NewLocale(translationDir, code) + l.AddDomain("default") + + inputStr := string(input) + if inputStr == "0" || inputStr == "9" { + return res, nil + } + + userStore := h.userdataStore + + // Resolve active pool + _, activePoolName, err := h.resolveActivePoolDetails(ctx, sessionId) + if err != nil { + return res, err + } + + metadata, err := store.GetSwapToVoucherData(ctx, userStore, sessionId, "1") + if err != nil { + return res, fmt.Errorf("failed to retrieve swap to voucher data: %v", err) + } + if metadata == nil { + res.FlagSet = append(res.FlagSet, flag_api_call_error) + return res, nil + } + + logg.InfoCtxf(ctx, "Metadata from GetSwapToVoucherData:", "metadata", metadata) + + // 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 + } + + swapData, err := store.ReadSwapData(ctx, userStore, sessionId) + if err != nil { + return res, err + } + + // call the api using the ActivePoolAddress, ActiveSwapFromAddress as the to (FT), ActiveSwapToAddress as the from (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 + } + + 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(r.Max, swapData.ActiveSwapFromDecimal) + if err != nil { + return res, err + } + + maxAmountFloat, err := strconv.ParseFloat(maxAmountStr, 64) + if err != nil { + logg.ErrorCtxf(ctx, "failed to parse maxAmountStr as float", "value", maxAmountStr, "error", err) + return res, err + } + + // Format to 2 decimal places + maxStr, _ := store.TruncateDecimalString(string(maxAmountStr), 2) + + if maxAmountFloat < 0.1 { + // return with low amount flag + res.Content = maxStr + res.FlagSet = append(res.FlagSet, flag_low_swap_amount) + return res, nil + } + + err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_SWAP_MAX_AMOUNT, []byte(maxStr)) + if err != nil { + logg.ErrorCtxf(ctx, "failed to write swap max amount entry with", "key", storedb.DATA_ACTIVE_SWAP_MAX_AMOUNT, "value", maxStr, "error", err) + return res, err + } + + res.Content = l.Get( + "You can remove a maximum of %s %s from '%s'\n\nEnter amount of %s:", + maxStr, + swapData.ActiveSwapToSym, + string(activePoolName), + swapData.ActiveSwapToSym, + ) + + return res, nil +} + +// ConfirmDebtRemoval displays the debt preview for a confirmation +func (h *MenuHandlers) ConfirmDebtRemoval(ctx context.Context, sym string, input []byte) (resource.Result, error) { + var res resource.Result + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + + inputStr := string(input) + if inputStr == "0" { + return res, nil + } + + flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") + + code := codeFromCtx(ctx) + l := gotext.NewLocale(translationDir, code) + l.AddDomain("default") + + userStore := h.userdataStore + + swapData, err := store.ReadSwapPreviewData(ctx, userStore, sessionId) + if err != nil { + return res, err + } + + maxValue, err := strconv.ParseFloat(swapData.ActiveSwapMaxAmount, 64) + if err != nil { + logg.ErrorCtxf(ctx, "Failed to convert the swapMaxAmount to a float", "error", err) + return res, err + } + + inputAmount, err := strconv.ParseFloat(inputStr, 64) + if err != nil || inputAmount > maxValue { + res.FlagSet = append(res.FlagSet, flag_invalid_amount) + res.Content = inputStr + return res, nil + } + + // Format the amount to 2 decimal places + formattedAmount, err := store.TruncateDecimalString(inputStr, 2) + if err != nil { + res.FlagSet = append(res.FlagSet, flag_invalid_amount) + res.Content = inputStr + return res, nil + } + + finalAmountStr, err := store.ParseAndScaleAmount(formattedAmount, swapData.ActiveSwapFromDecimal) + if err != nil { + return res, err + } + + err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_SWAP_AMOUNT, []byte(finalAmountStr)) + if err != nil { + logg.ErrorCtxf(ctx, "failed to write swap amount entry with", "key", storedb.DATA_ACTIVE_SWAP_AMOUNT, "value", finalAmountStr, "error", err) + return res, err + } + // store the user's input amount in the temporary value + err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(inputStr)) + if err != nil { + logg.ErrorCtxf(ctx, "failed to write inputStr amount entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", inputStr, "error", err) + return res, err + } + + // call the API to get the quote + r, err := h.accountService.GetPoolSwapQuote(ctx, finalAmountStr, swapData.PublicKey, swapData.ActiveSwapToAddress, swapData.ActivePoolAddress, swapData.ActiveSwapFromAddress) + 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(r.OutValue, swapData.ActiveSwapToDecimal) + + // Format to 2 decimal places + qouteStr, _ := store.TruncateDecimalString(string(quoteAmountStr), 2) + + res.Content = l.Get( + "Please confirm that you will use %s %s to remove your debt of %s %s\n", + inputStr, swapData.ActiveSwapToSym, qouteStr, swapData.ActiveSwapFromSym, + ) + + return res, nil +} + +// InitiatePayDebt calls the poolSwap to swap the token for the active voucher. +func (h *MenuHandlers) InitiatePayDebt(ctx context.Context, sym string, input []byte) (resource.Result, error) { + var res resource.Result + var err error + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + + flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") + + code := codeFromCtx(ctx) + l := gotext.NewLocale(translationDir, code) + l.AddDomain("default") + + userStore := h.userdataStore + + // Resolve active pool + _, activePoolName, err := h.resolveActivePoolDetails(ctx, sessionId) + if err != nil { + return res, err + } + + swapData, err := store.ReadSwapPreviewData(ctx, userStore, sessionId) + if err != nil { + return res, err + } + + swapAmount, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_SWAP_AMOUNT) + if err != nil { + logg.ErrorCtxf(ctx, "failed to read swapAmount entry with", "key", storedb.DATA_ACTIVE_SWAP_AMOUNT, "error", err) + return res, err + } + + swapAmountStr := string(swapAmount) + + // Call the poolSwap API + r, err := h.accountService.PoolSwap(ctx, swapAmountStr, swapData.PublicKey, swapData.ActiveSwapToAddress, swapData.ActivePoolAddress, swapData.ActiveSwapFromAddress) + 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 + } + + trackingId := r.TrackingId + logg.InfoCtxf(ctx, "poolSwap", "trackingId", trackingId) + + res.Content = l.Get( + "Your request has been sent. You will receive an SMS when your debt of %s %s has been removed from %s.", + swapData.TemporaryValue, + swapData.ActiveSwapFromSym, + activePoolName, + ) + + res.FlagReset = append(res.FlagReset, flag_account_authorized) + return res, nil +} From 277e4e179d88eaeb491a2a58d782f6955ade91fd Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 30 Jan 2026 16:33:44 +0300 Subject: [PATCH 019/130] added a CATCH for a low amount response from the API --- services/registration/low_pay_debt_amount | 1 + services/registration/low_pay_debt_amount.vis | 5 +++++ services/registration/low_pay_debt_amount_swa | 1 + services/registration/pay_debt.vis | 1 + 4 files changed, 8 insertions(+) create mode 100644 services/registration/low_pay_debt_amount create mode 100644 services/registration/low_pay_debt_amount.vis create mode 100644 services/registration/low_pay_debt_amount_swa diff --git a/services/registration/low_pay_debt_amount b/services/registration/low_pay_debt_amount new file mode 100644 index 0000000..56f14ae --- /dev/null +++ b/services/registration/low_pay_debt_amount @@ -0,0 +1 @@ +You have a low debt amount \ No newline at end of file diff --git a/services/registration/low_pay_debt_amount.vis b/services/registration/low_pay_debt_amount.vis new file mode 100644 index 0000000..832ef22 --- /dev/null +++ b/services/registration/low_pay_debt_amount.vis @@ -0,0 +1,5 @@ +MOUT back 0 +MOUT quit 9 +HALT +INCMP ^ 0 +INCMP quit 9 diff --git a/services/registration/low_pay_debt_amount_swa b/services/registration/low_pay_debt_amount_swa new file mode 100644 index 0000000..26fcfc0 --- /dev/null +++ b/services/registration/low_pay_debt_amount_swa @@ -0,0 +1 @@ +Kiasi cha deni lako ni cha chini sana \ No newline at end of file diff --git a/services/registration/pay_debt.vis b/services/registration/pay_debt.vis index 1b5a819..91bdf8e 100644 --- a/services/registration/pay_debt.vis +++ b/services/registration/pay_debt.vis @@ -1,6 +1,7 @@ LOAD calculate_max_pay_debt 0 RELOAD calculate_max_pay_debt MAP calculate_max_pay_debt +CATCH low_pay_debt_amount flag_low_swap_amount 1 MOUT back 0 HALT INCMP _ 0 From 99893eac5c0d0a6c13711e9bd96dad5c7b782225 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 30 Jan 2026 16:34:52 +0300 Subject: [PATCH 020/130] include the ActiveSwapToDecimal on the SwapData --- store/swap.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/store/swap.go b/store/swap.go index 3510720..097ad4a 100644 --- a/store/swap.go +++ b/store/swap.go @@ -18,6 +18,7 @@ type SwapData struct { ActiveSwapFromAddress string ActiveSwapToSym string ActiveSwapToAddress string + ActiveSwapToDecimal string } type SwapPreviewData struct { @@ -43,6 +44,7 @@ func ReadSwapData(ctx context.Context, store DataStore, sessionId string) (SwapD "ActiveSwapFromAddress": storedb.DATA_ACTIVE_ADDRESS, "ActiveSwapToSym": storedb.DATA_ACTIVE_SWAP_TO_SYM, "ActiveSwapToAddress": storedb.DATA_ACTIVE_SWAP_TO_ADDRESS, + "ActiveSwapToDecimal": storedb.DATA_ACTIVE_SWAP_TO_DECIMAL, } v := reflect.ValueOf(&data).Elem() From 3949959aa36e9153a98019f4ce4d816e93989a6f Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 30 Jan 2026 16:41:44 +0300 Subject: [PATCH 021/130] use the correct terms for clarity --- handlers/application/paydebt.go | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/handlers/application/paydebt.go b/handlers/application/paydebt.go index b60c426..086b660 100644 --- a/handlers/application/paydebt.go +++ b/handlers/application/paydebt.go @@ -61,7 +61,7 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu return res, err } - // call the api using the ActivePoolAddress, ActiveSwapFromAddress as the to (FT), ActiveSwapToAddress as the from (AT) and PublicKey to get the swap max limit + // 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) @@ -76,7 +76,7 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu } // Scale down the amount - maxAmountStr := store.ScaleDownBalance(r.Max, swapData.ActiveSwapFromDecimal) + maxAmountStr := store.ScaleDownBalance(r.Max, swapData.ActiveSwapToDecimal) if err != nil { return res, err } @@ -153,17 +153,16 @@ func (h *MenuHandlers) ConfirmDebtRemoval(ctx context.Context, sym string, input return res, nil } - // Format the amount to 2 decimal places - formattedAmount, err := store.TruncateDecimalString(inputStr, 2) - if err != nil { - res.FlagSet = append(res.FlagSet, flag_invalid_amount) - res.Content = inputStr - return res, nil - } + storedMax, _ := userStore.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) - finalAmountStr, err := store.ParseAndScaleAmount(formattedAmount, swapData.ActiveSwapFromDecimal) - if err != nil { - return res, err + var finalAmountStr string + if inputStr == swapData.ActiveSwapMaxAmount { + finalAmountStr = string(storedMax) + } else { + finalAmountStr, err = store.ParseAndScaleAmount(inputStr, swapData.ActiveSwapToDecimal) + if err != nil { + return res, err + } } err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_SWAP_AMOUNT, []byte(finalAmountStr)) @@ -254,7 +253,7 @@ func (h *MenuHandlers) InitiatePayDebt(ctx context.Context, sym string, input [] res.Content = l.Get( "Your request has been sent. You will receive an SMS when your debt of %s %s has been removed from %s.", swapData.TemporaryValue, - swapData.ActiveSwapFromSym, + swapData.ActiveSwapToSym, activePoolName, ) From 0b3b407ab7876500acb772e66f5294e31aafe30d Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Tue, 3 Feb 2026 13:31:44 +0300 Subject: [PATCH 022/130] add a CATCH for users who do not have vouchers --- services/registration/pay_debt.vis | 1 + 1 file changed, 1 insertion(+) diff --git a/services/registration/pay_debt.vis b/services/registration/pay_debt.vis index 91bdf8e..94fcc99 100644 --- a/services/registration/pay_debt.vis +++ b/services/registration/pay_debt.vis @@ -1,3 +1,4 @@ +CATCH no_voucher flag_no_active_voucher 1 LOAD calculate_max_pay_debt 0 RELOAD calculate_max_pay_debt MAP calculate_max_pay_debt From 85b8775fd0b03fa0c4b73dc0125388767d2a0e4a Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Tue, 3 Feb 2026 13:32:13 +0300 Subject: [PATCH 023/130] return nil instead of an error to prevent failure --- handlers/application/balance.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index e3b67ec..d2d92d7 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -152,7 +152,8 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i // Fetch session data _, _, activeSym, _, publicKey, _, err := h.getSessionData(ctx, sessionId) if err != nil { - return res, err + // return if the user does not have an active voucher + return res, nil } // Get active pool address and symbol or fall back to default @@ -166,7 +167,7 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i if err != nil { res.FlagSet = append(res.FlagSet, flag_api_call_error) logg.ErrorCtxf(ctx, "failed on GetPoolSwappableFromVouchers", "error", err) - return res, err + return res, nil } logg.InfoCtxf(ctx, "GetPoolSwappableFromVouchers", "swappable vouchers", swappableVouchers) From 42f7b0f8a792154e595028b8c3aa19f03f221bf6 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Tue, 3 Feb 2026 13:34:05 +0300 Subject: [PATCH 024/130] remove the api failure flag if no swappable vouchers are found --- handlers/application/balance.go | 1 - 1 file changed, 1 deletion(-) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index d2d92d7..5a6c1b2 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -165,7 +165,6 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i // call the api using the activePoolAddress to get a list of SwapToSymbolsData swappableVouchers, err := h.accountService.GetPoolSwappableFromVouchers(ctx, string(activePoolAddress), string(publicKey)) if err != nil { - res.FlagSet = append(res.FlagSet, flag_api_call_error) logg.ErrorCtxf(ctx, "failed on GetPoolSwappableFromVouchers", "error", err) return res, nil } From 9ef27fda14e7c8c262bccbc4c48f08147269bf76 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Tue, 3 Feb 2026 13:36:14 +0300 Subject: [PATCH 025/130] reset the api_call_error flag --- handlers/application/balance.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index 5a6c1b2..6702cf8 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -149,6 +149,8 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error") + res.FlagReset = append(res.FlagReset, flag_api_call_error) + // Fetch session data _, _, activeSym, _, publicKey, _, err := h.getSessionData(ctx, sessionId) if err != nil { From fd7b3af57c255f77b7ed4c37935142e343bb9fa5 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Tue, 3 Feb 2026 14:19:10 +0300 Subject: [PATCH 026/130] added next and prev inputs for long menus --- services/registration/main.vis | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/registration/main.vis b/services/registration/main.vis index 2ce38f3..c4e4ca6 100644 --- a/services/registration/main.vis +++ b/services/registration/main.vis @@ -18,6 +18,8 @@ MOUT mpesa 6 MOUT account 7 MOUT help 8 MOUT quit 9 +MNEXT next 11 +MPREV prev 22 HALT INCMP credit_send 1 INCMP pay_debt 2 @@ -28,4 +30,6 @@ INCMP mpesa 6 INCMP my_account 7 INCMP help 8 INCMP quit 9 +INCMP > 11 +INCMP < 22 INCMP . * From 94b2eca1866948f4da0f541f98b2af0f1e17ad39 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Tue, 3 Feb 2026 14:23:21 +0300 Subject: [PATCH 027/130] debug: change the size outputs --- services/registration/main.vis | 2 +- services/registration/root.vis | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/registration/main.vis b/services/registration/main.vis index c4e4ca6..0c903b6 100644 --- a/services/registration/main.vis +++ b/services/registration/main.vis @@ -1,6 +1,6 @@ LOAD clear_temporary_value 2 RELOAD clear_temporary_value -LOAD manage_vouchers 160 +LOAD manage_vouchers 0 RELOAD manage_vouchers CATCH api_failure flag_api_call_error 1 LOAD calc_credit_debt 60 diff --git a/services/registration/root.vis b/services/registration/root.vis index 035db83..921ac98 100644 --- a/services/registration/root.vis +++ b/services/registration/root.vis @@ -7,7 +7,7 @@ CATCH blocked_account flag_account_blocked 1 CATCH select_language flag_language_set 0 CATCH terms flag_account_created 0 CATCH create_pin flag_pin_set 0 -LOAD check_account_status 0 +LOAD check_account_status 40 RELOAD check_account_status CATCH api_failure flag_api_call_error 1 CATCH account_pending flag_account_pending 1 From 70ae3c7818bbbc3005cfeac269612fc8af352508 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Tue, 3 Feb 2026 14:32:21 +0300 Subject: [PATCH 028/130] debug: shorten the displayed content --- handlers/application/balance.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index 6702cf8..2b6463b 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -107,13 +107,13 @@ func loadUserContent(ctx context.Context, activeSym, balance, alias, currectCred // format the final outputs balStr := fmt.Sprintf("%s %s", formattedAmount, activeSym) - creditStr := fmt.Sprintf("Credit: %s ksh", formattedCredit) - debtStr := fmt.Sprintf("Debt: %s ksh", formattedDebt) + creditStr := fmt.Sprintf("C: %s ksh", formattedCredit) + debtStr := fmt.Sprintf("D: %s ksh", formattedDebt) if alias != "" { - content = l.Get("%s\nBalance: %s\n%s\n%s", alias, balStr, creditStr, debtStr) + content = l.Get("%s\nBal: %s\n%s\n%s", alias, balStr, creditStr, debtStr) } else { - content = l.Get("Balance: %s\n%s\n%s", balStr, creditStr, debtStr) + content = l.Get("Bal: %s\n%s\n%s", balStr, creditStr, debtStr) } return content, nil } From e4c10d23d3d8c8ccc0be1be9df798e8d95c67cc1 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Tue, 3 Feb 2026 16:49:11 +0300 Subject: [PATCH 029/130] reset the flags to clear out old states --- handlers/application/paydebt.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/handlers/application/paydebt.go b/handlers/application/paydebt.go index 086b660..896dabd 100644 --- a/handlers/application/paydebt.go +++ b/handlers/application/paydebt.go @@ -28,6 +28,7 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu inputStr := string(input) if inputStr == "0" || inputStr == "9" { + res.FlagReset = append(res.FlagReset, flag_low_swap_amount, flag_api_call_error) return res, nil } @@ -36,11 +37,13 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu // Resolve active pool _, 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 } 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) } if metadata == nil { @@ -111,6 +114,8 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu swapData.ActiveSwapToSym, ) + res.FlagReset = append(res.FlagReset, flag_low_swap_amount, flag_api_call_error) + return res, nil } From 7783ba8835f0a942cf35048216468cfabb6c4a3e Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Tue, 3 Feb 2026 17:02:44 +0300 Subject: [PATCH 030/130] removed unused data keys --- store/db/db.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/store/db/db.go b/store/db/db.go index 5ecce84..4cc3f57 100644 --- a/store/db/db.go +++ b/store/db/db.go @@ -93,10 +93,6 @@ const ( DATA_SEND_TRANSACTION_TYPE // Holds the recipient formatted phone number DATA_RECIPIENT_PHONE_NUMBER - // holds the current credit of the user - DATA_CURRENT_CREDIT - // holds the current debt of the user - DATA_CURRENT_DEBT ) const ( From 6a4909b8a1bd4f9b9dd794937c722bd27a3aabc8 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Tue, 3 Feb 2026 17:03:38 +0300 Subject: [PATCH 031/130] separate the main balance from the credit and debt calculation and UI --- handlers/application/balance.go | 43 ++++++--------------------------- 1 file changed, 8 insertions(+), 35 deletions(-) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index 2b6463b..b0db61a 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -55,24 +55,7 @@ func (h *MenuHandlers) CheckBalance(ctx context.Context, sym string, input []byt } } - // get current credit - currentCredit, err := store.ReadEntry(ctx, sessionId, storedb.DATA_CURRENT_CREDIT) - if err != nil { - if !db.IsNotFound(err) { - logg.ErrorCtxf(ctx, "failed to read currentCredit entry with", "key", storedb.DATA_CURRENT_CREDIT, "error", err) - return res, err - } - } - // get current debt - currentDebt, err := store.ReadEntry(ctx, sessionId, storedb.DATA_CURRENT_DEBT) - if err != nil { - if !db.IsNotFound(err) { - logg.ErrorCtxf(ctx, "failed to read currentDebt entry with", "key", storedb.DATA_CURRENT_DEBT, "error", err) - return res, err - } - } - - content, err = loadUserContent(ctx, string(activeSym), string(activeBal), string(accAlias), string(currentCredit), string(currentDebt)) + content, err = loadUserContent(ctx, string(activeSym), string(activeBal), string(accAlias)) if err != nil { return res, err } @@ -82,7 +65,7 @@ func (h *MenuHandlers) CheckBalance(ctx context.Context, sym string, input []byt } // loadUserContent loads the main user content in the main menu: the alias, balance and active symbol associated with active voucher -func loadUserContent(ctx context.Context, activeSym, balance, alias, currectCredit, currentDebt string) (string, error) { +func loadUserContent(ctx context.Context, activeSym, balance, alias string) (string, error) { var content string code := codeFromCtx(ctx) @@ -95,25 +78,13 @@ func loadUserContent(ctx context.Context, activeSym, balance, alias, currectCred formattedAmount = "0.00" } - formattedCredit, err := store.TruncateDecimalString(currectCredit, 0) - if err != nil { - formattedCredit = "0" - } - - formattedDebt, err := store.TruncateDecimalString(currentDebt, 0) - if err != nil { - formattedDebt = "0" - } - // format the final outputs balStr := fmt.Sprintf("%s %s", formattedAmount, activeSym) - creditStr := fmt.Sprintf("C: %s ksh", formattedCredit) - debtStr := fmt.Sprintf("D: %s ksh", formattedDebt) if alias != "" { - content = l.Get("%s\nBal: %s\n%s\n%s", alias, balStr, creditStr, debtStr) + content = l.Get("%s\nBalance: %s\n", alias, balStr) } else { - content = l.Get("Bal: %s\n%s\n%s", balStr, creditStr, debtStr) + content = l.Get("Balance: %s\n", balStr) } return content, nil } @@ -149,7 +120,9 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error") + // set the default flag set/reset and content 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 _, _, activeSym, _, publicKey, _, err := h.getSessionData(ctx, sessionId) @@ -247,8 +220,6 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i storedb.DATA_POOL_TO_BALANCES: data.Balances, storedb.DATA_POOL_TO_DECIMALS: data.Decimals, storedb.DATA_POOL_TO_ADDRESSES: data.Addresses, - storedb.DATA_CURRENT_CREDIT: kshFormattedCredit, - storedb.DATA_CURRENT_DEBT: kshFormattedDebt, } // Write data entries @@ -259,5 +230,7 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i } } + res.Content = l.Get("Credit: %s KSH\nDebt: %s KSH\n", kshFormattedCredit, kshFormattedDebt) + return res, nil } From 0f7be3147e501f66ff7c014b296b1b98f0c298b9 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Tue, 3 Feb 2026 17:04:58 +0300 Subject: [PATCH 032/130] move the pay debt functionality to the mpesa menu --- services/registration/main.vis | 35 ++++++++++++--------------------- services/registration/mpesa | 2 +- services/registration/mpesa.vis | 17 +++++++++++----- 3 files changed, 26 insertions(+), 28 deletions(-) diff --git a/services/registration/main.vis b/services/registration/main.vis index 0c903b6..1766c10 100644 --- a/services/registration/main.vis +++ b/services/registration/main.vis @@ -1,35 +1,26 @@ LOAD clear_temporary_value 2 RELOAD clear_temporary_value -LOAD manage_vouchers 0 +LOAD manage_vouchers 160 RELOAD manage_vouchers CATCH api_failure flag_api_call_error 1 -LOAD calc_credit_debt 60 -RELOAD calc_credit_debt -CATCH api_failure flag_api_call_error 1 LOAD check_balance 148 RELOAD check_balance MAP check_balance MOUT send 1 -MOUT pay_debt 2 -MOUT swap 3 -MOUT vouchers 4 -MOUT select_pool 5 -MOUT mpesa 6 -MOUT account 7 -MOUT help 8 +MOUT swap 2 +MOUT vouchers 3 +MOUT select_pool 4 +MOUT mpesa 5 +MOUT account 6 +MOUT help 7 MOUT quit 9 -MNEXT next 11 -MPREV prev 22 HALT INCMP credit_send 1 -INCMP pay_debt 2 -INCMP swap_to_list 3 -INCMP my_vouchers 4 -INCMP select_pool 5 -INCMP mpesa 6 -INCMP my_account 7 -INCMP help 8 +INCMP swap_to_list 2 +INCMP my_vouchers 3 +INCMP select_pool 4 +INCMP mpesa 5 +INCMP my_account 6 +INCMP help 7 INCMP quit 9 -INCMP > 11 -INCMP < 22 INCMP . * diff --git a/services/registration/mpesa b/services/registration/mpesa index afae8c1..61e50b4 100644 --- a/services/registration/mpesa +++ b/services/registration/mpesa @@ -1 +1 @@ -{{.check_balance}} \ No newline at end of file +{{.calc_credit_debt}} \ No newline at end of file diff --git a/services/registration/mpesa.vis b/services/registration/mpesa.vis index a51c002..91e75ae 100644 --- a/services/registration/mpesa.vis +++ b/services/registration/mpesa.vis @@ -1,9 +1,16 @@ -MAP check_balance -MOUT get_mpesa 1 -MOUT send_mpesa 2 +LOAD calc_credit_debt 150 +RELOAD calc_credit_debt +CATCH api_failure flag_api_call_error 1 +MAP calc_credit_debt +MOUT pay_debt 1 +MOUT get_mpesa 2 +MOUT send_mpesa 3 +MOUT back 0 MOUT quit 9 HALT -INCMP get_mpesa 1 -INCMP send_mpesa 2 +INCMP ^ 0 +INCMP pay_debt 1 +INCMP get_mpesa 2 +INCMP send_mpesa 3 INCMP quit 9 INCMP . * From 7b461d9b640800c8c15964803cb73b9acacb9f17 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Wed, 4 Feb 2026 16:17:07 +0300 Subject: [PATCH 033/130] add the env example for the Stable vouchers addresses --- .env.example | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.env.example b/.env.example index 3b311ed..2afa594 100644 --- a/.env.example +++ b/.env.example @@ -37,3 +37,6 @@ MAX_MPESA_SEND_AMOUNT=250000 DEFAULT_MPESA_ASSET=cUSD MPESA_BEARER_TOKEN=eyJeSIsInRcCI6IkpXVCJ.yJwdWJsaWNLZXkiOiIwrrrrrr MPESA_ONRAMP_BASE=https://pretium.v1.grassecon.net + +# Stable vouchers allowed for Pay Debt (USDT, USDm) +STABLE_VOUCHER_ADDRESSES=0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e,0x765DE816845861e75A25fCA122bb6898B8B1282a From f77c82f418a4a240898a1710a68384984ce7323e Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Wed, 4 Feb 2026 16:21:25 +0300 Subject: [PATCH 034/130] added a flag for flag_no_pay_debt_vouchers --- services/registration/pp.csv | 1 + 1 file changed, 1 insertion(+) diff --git a/services/registration/pp.csv b/services/registration/pp.csv index 16fccbd..92ba16d 100644 --- a/services/registration/pp.csv +++ b/services/registration/pp.csv @@ -36,3 +36,4 @@ flag,flag_incorrect_pool,42,this is set when the user selects an invalid pool flag,flag_low_swap_amount,43,this is set when the swap max limit is less than 0.1 flag,flag_alias_unavailable,44,this is set when the preferred alias is not available flag,flag_swap_transaction,45,this is set when the transaction will involve performing a swap +flag,flag_no_pay_debt_vouchers,46,this is set when the user does not have a stable voucher to pay debt From 3a4f824ab9eddde1388d9670f6fd97b7ec1385c3 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Wed, 4 Feb 2026 16:31:32 +0300 Subject: [PATCH 035/130] added a CATCH when no stable voucher exists during the pay debt --- services/registration/no_stable_voucher | 1 + services/registration/no_stable_voucher.vis | 5 +++++ services/registration/no_stable_voucher_swa | 1 + services/registration/pay_debt.vis | 1 + 4 files changed, 8 insertions(+) create mode 100644 services/registration/no_stable_voucher create mode 100644 services/registration/no_stable_voucher.vis create mode 100644 services/registration/no_stable_voucher_swa diff --git a/services/registration/no_stable_voucher b/services/registration/no_stable_voucher new file mode 100644 index 0000000..2988bb3 --- /dev/null +++ b/services/registration/no_stable_voucher @@ -0,0 +1 @@ +No stable voucher found \ No newline at end of file diff --git a/services/registration/no_stable_voucher.vis b/services/registration/no_stable_voucher.vis new file mode 100644 index 0000000..832ef22 --- /dev/null +++ b/services/registration/no_stable_voucher.vis @@ -0,0 +1,5 @@ +MOUT back 0 +MOUT quit 9 +HALT +INCMP ^ 0 +INCMP quit 9 diff --git a/services/registration/no_stable_voucher_swa b/services/registration/no_stable_voucher_swa new file mode 100644 index 0000000..ab8cbf2 --- /dev/null +++ b/services/registration/no_stable_voucher_swa @@ -0,0 +1 @@ +Hakuna sarafu thabiti iliyopatikana \ No newline at end of file diff --git a/services/registration/pay_debt.vis b/services/registration/pay_debt.vis index 94fcc99..147fe06 100644 --- a/services/registration/pay_debt.vis +++ b/services/registration/pay_debt.vis @@ -1,4 +1,5 @@ CATCH no_voucher flag_no_active_voucher 1 +CATCH no_stable_voucher flag_no_pay_debt_vouchers 1 LOAD calculate_max_pay_debt 0 RELOAD calculate_max_pay_debt MAP calculate_max_pay_debt From ce36e584dde347263e95ea1cb9c1d820bf0b1ff8 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Wed, 4 Feb 2026 16:35:07 +0300 Subject: [PATCH 036/130] check whether any of the users vouchers are stables or set a flag --- config/config.go | 19 +++++++ handlers/application/balance.go | 88 +++++++++++++++++---------------- handlers/application/paydebt.go | 12 +++++ 3 files changed, 77 insertions(+), 42 deletions(-) diff --git a/config/config.go b/config/config.go index 522e9cb..7ee27e0 100644 --- a/config/config.go +++ b/config/config.go @@ -114,3 +114,22 @@ func MaxMpesaSendAmount() float64 { func DefaultMpesaAsset() string { return env.GetEnv("DEFAULT_MPESA_ASSET", "") } + +func StableVoucherAddresses() []string { + var parsed []string + + raw := env.GetEnv("STABLE_VOUCHER_ADDRESSES", "") + if raw == "" { + return parsed + } + + list := strings.Split(raw, ",") + for _, addr := range list { + clean := strings.ToLower(strings.TrimSpace(addr)) + if clean != "" { + parsed = append(parsed, clean) + } + } + + return parsed +} \ No newline at end of file diff --git a/handlers/application/balance.go b/handlers/application/balance.go index b0db61a..b45e369 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -119,86 +119,85 @@ 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_pay_debt_vouchers, _ := h.flagManager.GetFlag("flag_no_pay_debt_vouchers") - // set the default flag set/reset and content + // 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 _, _, activeSym, _, publicKey, _, err := h.getSessionData(ctx, sessionId) if err != nil { - // return if the user does not have an active voucher return res, nil } - // Get active pool address and symbol or fall back to default + // Resolve active pool activePoolAddress, _, err := h.resolveActivePoolDetails(ctx, sessionId) if err != nil { return res, err } - // call the api using the activePoolAddress to get a list of SwapToSymbolsData + // Fetch swappable vouchers swappableVouchers, err := h.accountService.GetPoolSwappableFromVouchers(ctx, string(activePoolAddress), string(publicKey)) if err != nil { logg.ErrorCtxf(ctx, "failed on GetPoolSwappableFromVouchers", "error", err) return res, nil } - logg.InfoCtxf(ctx, "GetPoolSwappableFromVouchers", "swappable vouchers", swappableVouchers) - - // Return if there are no vouchers if len(swappableVouchers) == 0 { return res, nil } - // Filter out the active voucher from swappableVouchers - filteredSwappableVouchers := make([]dataserviceapi.TokenHoldings, 0, len(swappableVouchers)) - for _, s := range swappableVouchers { - if s.TokenSymbol != string(activeSym) { - filteredSwappableVouchers = append(filteredSwappableVouchers, s) + // Filter stable vouchers (excluding active voucher) + filteredSwappableVouchers := make([]dataserviceapi.TokenHoldings, 0) + for _, v := range swappableVouchers { + if v.TokenSymbol == string(activeSym) { + continue + } + if isStableVoucher(v.TokenAddress) { + filteredSwappableVouchers = append(filteredSwappableVouchers, v) } } - // Store as filtered swap to list data (excluding the current active voucher) for future reference + // No stable vouchers → cannot pay debt + if len(filteredSwappableVouchers) == 0 { + res.FlagSet = append(res.FlagSet, flag_no_pay_debt_vouchers) + return res, nil + } + + res.FlagReset = append(res.FlagReset, flag_no_pay_debt_vouchers) + + // Process stable vouchers for later use data := store.ProcessVouchers(filteredSwappableVouchers) - logg.InfoCtxf(ctx, "ProcessVouchers", "data", data) - - // Find the matching voucher data + // Find active voucher data activeSymStr := string(activeSym) var activeData *dataserviceapi.TokenHoldings - for _, voucher := range swappableVouchers { - if voucher.TokenSymbol == activeSymStr { - activeData = &voucher + for _, v := range swappableVouchers { + if v.TokenSymbol == activeSymStr { + activeData = &v break } } if activeData == nil { - logg.InfoCtxf(ctx, "activeSym not found in vouchers, returning 0", "activeSym", activeSymStr) return res, nil } - // Scale down the active balance (credit) - // Max swappable value from pool using the active token - scaledCredit := store.ScaleDownBalance(activeData.Balance, activeData.TokenDecimals) + // Credit = active voucher balance + scaledCredit := store.ScaleDownBalance( + activeData.Balance, + activeData.TokenDecimals, + ) - // Calculate total debt (sum of other vouchers) + // Debt = sum of stable vouchers only scaledDebt := "0" - - for _, voucher := range swappableVouchers { - // Skip the active token - if voucher.TokenSymbol == activeSymStr { - continue - } - - scaled := store.ScaleDownBalance(voucher.Balance, voucher.TokenDecimals) - - // Add scaled balances (decimal-safe) + for _, v := range filteredSwappableVouchers { + scaled := store.ScaleDownBalance(v.Balance, v.TokenDecimals) scaledDebt = store.AddDecimalStrings(scaledDebt, scaled) } - // call the mpesa rates API to get the rates + // Fetch MPESA rates rates, err := h.accountService.GetMpesaOnrampRates(ctx) if err != nil { res.FlagSet = append(res.FlagSet, flag_api_call_error) @@ -208,13 +207,15 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i } creditFloat, _ := strconv.ParseFloat(scaledCredit, 64) - creditksh := fmt.Sprintf("%f", creditFloat*rates.Buy) - kshFormattedCredit, _ := store.TruncateDecimalString(creditksh, 0) - debtFloat, _ := strconv.ParseFloat(scaledDebt, 64) - debtksh := fmt.Sprintf("%f", debtFloat*rates.Buy) - kshFormattedDebt, _ := store.TruncateDecimalString(debtksh, 0) + creditKsh := fmt.Sprintf("%f", creditFloat*rates.Buy) + debtKsh := fmt.Sprintf("%f", debtFloat*rates.Buy) + + 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, @@ -222,7 +223,6 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i storedb.DATA_POOL_TO_ADDRESSES: data.Addresses, } - // Write data entries 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) @@ -230,7 +230,11 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i } } - res.Content = l.Get("Credit: %s KSH\nDebt: %s KSH\n", kshFormattedCredit, kshFormattedDebt) + res.Content = l.Get( + "Credit: %s KSH\nDebt: %s KSH\n", + kshFormattedCredit, + kshFormattedDebt, + ) return res, nil } diff --git a/handlers/application/paydebt.go b/handlers/application/paydebt.go index 896dabd..d38ed6c 100644 --- a/handlers/application/paydebt.go +++ b/handlers/application/paydebt.go @@ -4,8 +4,10 @@ import ( "context" "fmt" "strconv" + "strings" "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" "gopkg.in/leonelquinteros/gotext.v1" @@ -265,3 +267,13 @@ func (h *MenuHandlers) InitiatePayDebt(ctx context.Context, sym string, input [] res.FlagReset = append(res.FlagReset, flag_account_authorized) return res, nil } + +func isStableVoucher(tokenAddress string) bool { + addr := strings.ToLower(strings.TrimSpace(tokenAddress)) + for _, stable := range config.StableVoucherAddresses() { + if addr == stable { + return true + } + } + return false +} From c57aa220e669ae79892fe1bc2e7652206b9f5cc6 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Wed, 4 Feb 2026 17:02:24 +0300 Subject: [PATCH 037/130] show a default message if the user only has 1 voucher --- handlers/application/vouchers.go | 17 ++++++++++++++++- services/registration/select_voucher | 1 - 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/handlers/application/vouchers.go b/handlers/application/vouchers.go index 1d9d9aa..895d9c6 100644 --- a/handlers/application/vouchers.go +++ b/handlers/application/vouchers.go @@ -181,8 +181,18 @@ func (h *MenuHandlers) GetVoucherList(ctx context.Context, sym string, input []b return res, fmt.Errorf("missing session") } + code := codeFromCtx(ctx) + l := gotext.NewLocale(translationDir, code) + l.AddDomain("default") + userStore := h.userdataStore + // Fetch session data + _, _, activeSym, _, _, _, err := h.getSessionData(ctx, sessionId) + if err != nil { + return res, nil + } + // Read vouchers from the store voucherData, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_VOUCHER_SYMBOLS) logg.InfoCtxf(ctx, "reading voucherData in GetVoucherList", "sessionId", sessionId, "key", storedb.DATA_VOUCHER_SYMBOLS, "voucherData", voucherData) @@ -191,6 +201,11 @@ func (h *MenuHandlers) GetVoucherList(ctx context.Context, sym string, input []b return res, err } + if len(voucherData) == 0 { + res.Content = l.Get("Your active voucher %s is already set", string(activeSym)) + return res, nil + } + voucherBalances, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_VOUCHER_BALANCES) logg.InfoCtxf(ctx, "reading voucherBalances in GetVoucherList", "sessionId", sessionId, "key", storedb.DATA_VOUCHER_BALANCES, "voucherBalances", voucherBalances) if err != nil { @@ -203,7 +218,7 @@ func (h *MenuHandlers) GetVoucherList(ctx context.Context, sym string, input []b logg.InfoCtxf(ctx, "final output for GetVoucherList", "sessionId", sessionId, "finalOutput", finalOutput) - res.Content = finalOutput + res.Content = l.Get("Select number or symbol from your vouchers:\n%s", finalOutput) return res, nil } diff --git a/services/registration/select_voucher b/services/registration/select_voucher index 084b9b8..ed8140f 100644 --- a/services/registration/select_voucher +++ b/services/registration/select_voucher @@ -1,2 +1 @@ -Select number or symbol from your vouchers: {{.get_vouchers}} \ No newline at end of file From 8223a0b4d5c544c2c9c6aa683c2a57f4af3c1099 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Wed, 4 Feb 2026 17:02:50 +0300 Subject: [PATCH 038/130] added translations for voucher selection --- services/registration/locale/swa/default.po | 8 +++++++- services/registration/select_voucher_swa | 2 -- 2 files changed, 7 insertions(+), 3 deletions(-) delete mode 100644 services/registration/select_voucher_swa diff --git a/services/registration/locale/swa/default.po b/services/registration/locale/swa/default.po index e1188d7..2892ce8 100644 --- a/services/registration/locale/swa/default.po +++ b/services/registration/locale/swa/default.po @@ -77,4 +77,10 @@ msgid "You can remove a maximum of %s %s from '%s' pool\n\nEnter amount of %s:" msgstr "Unaweza kuondoa kiwango cha juu cha %s %s kutoka kwenye '%s'\n\nWeka kiwango cha %s:" msgid "Please confirm that you will use %s %s to remove your debt of %s %s\n" -msgstr "Tafadhali thibitisha kwamba utatumia %s %s kulipa deni lako la %s %s.\nWeka PIN yako:" \ No newline at end of file +msgstr "Tafadhali thibitisha kwamba utatumia %s %s kulipa deni lako la %s %s.\nWeka PIN yako:" + +msgid "Your active voucher %s is already set" +msgstr "Sarafu yako %s ishachaguliwa" + +msgid "Select number or symbol from your vouchers:\n%s" +msgstr "Chagua nambari au ishara kutoka kwa sarafu zako:\n%s" \ No newline at end of file diff --git a/services/registration/select_voucher_swa b/services/registration/select_voucher_swa deleted file mode 100644 index b4720bf..0000000 --- a/services/registration/select_voucher_swa +++ /dev/null @@ -1,2 +0,0 @@ -Chagua nambari au ishara kutoka kwa salio zako: -{{.get_vouchers}} \ No newline at end of file From 916ac11585c580bf045b616a5279503a8741f6d9 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 5 Feb 2026 19:58:14 +0300 Subject: [PATCH 039/130] use the correct decimal when displaying the quote --- handlers/application/paydebt.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/handlers/application/paydebt.go b/handlers/application/paydebt.go index d38ed6c..faf6a04 100644 --- a/handlers/application/paydebt.go +++ b/handlers/application/paydebt.go @@ -195,7 +195,7 @@ func (h *MenuHandlers) ConfirmDebtRemoval(ctx context.Context, sym string, input } // Scale down the quoted amount - quoteAmountStr := store.ScaleDownBalance(r.OutValue, swapData.ActiveSwapToDecimal) + quoteAmountStr := store.ScaleDownBalance(r.OutValue, swapData.ActiveSwapFromDecimal) // Format to 2 decimal places qouteStr, _ := store.TruncateDecimalString(string(quoteAmountStr), 2) From 7f2467873fdb88679842dbdf3dda41140294d7be Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 6 Feb 2026 14:05:54 +0300 Subject: [PATCH 040/130] added the pool deposit menu node --- services/registration/mpesa.vis | 10 ++++++---- services/registration/pool_deposit | 1 + services/registration/pool_deposit.vis | 14 ++++++++++++++ 3 files changed, 21 insertions(+), 4 deletions(-) create mode 100644 services/registration/pool_deposit create mode 100644 services/registration/pool_deposit.vis diff --git a/services/registration/mpesa.vis b/services/registration/mpesa.vis index 91e75ae..73a4a55 100644 --- a/services/registration/mpesa.vis +++ b/services/registration/mpesa.vis @@ -3,14 +3,16 @@ RELOAD calc_credit_debt CATCH api_failure flag_api_call_error 1 MAP calc_credit_debt MOUT pay_debt 1 -MOUT get_mpesa 2 -MOUT send_mpesa 3 +MOUT deposit 2 +MOUT get_mpesa 3 +MOUT send_mpesa 4 MOUT back 0 MOUT quit 9 HALT INCMP ^ 0 INCMP pay_debt 1 -INCMP get_mpesa 2 -INCMP send_mpesa 3 +INCMP pool_deposit 2 +INCMP get_mpesa 3 +INCMP send_mpesa 4 INCMP quit 9 INCMP . * diff --git a/services/registration/pool_deposit b/services/registration/pool_deposit new file mode 100644 index 0000000..841c240 --- /dev/null +++ b/services/registration/pool_deposit @@ -0,0 +1 @@ +{{.get_pool_deposit_vouchers}} diff --git a/services/registration/pool_deposit.vis b/services/registration/pool_deposit.vis new file mode 100644 index 0000000..d93dfec --- /dev/null +++ b/services/registration/pool_deposit.vis @@ -0,0 +1,14 @@ +CATCH no_voucher flag_no_active_voucher 1 +CATCH no_stable_voucher flag_no_pay_debt_vouchers 1 +LOAD get_pool_deposit_vouchers 0 +MAP get_pool_deposit_vouchers +MOUT back 0 +MOUT quit 99 +MNEXT next 88 +MPREV prev 98 +HALT +INCMP > 88 +INCMP < 98 +INCMP _ 0 +INCMP quit 99 +INCMP pool_deposit_amount * From 1902ce226d6b89c0d6e57cbf686572d220bafc59 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 6 Feb 2026 14:09:40 +0300 Subject: [PATCH 041/130] added the pool deposit menu titles --- services/registration/deposit_menu | 1 + services/registration/deposit_menu_swa | 1 + 2 files changed, 2 insertions(+) create mode 100644 services/registration/deposit_menu create mode 100644 services/registration/deposit_menu_swa diff --git a/services/registration/deposit_menu b/services/registration/deposit_menu new file mode 100644 index 0000000..3f5281f --- /dev/null +++ b/services/registration/deposit_menu @@ -0,0 +1 @@ +Pool deposit \ No newline at end of file diff --git a/services/registration/deposit_menu_swa b/services/registration/deposit_menu_swa new file mode 100644 index 0000000..ca76c1a --- /dev/null +++ b/services/registration/deposit_menu_swa @@ -0,0 +1 @@ +Weka kwa bwawa \ No newline at end of file From f6dcc6db0e884850822a640fcdf943343991f8d7 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 6 Feb 2026 14:10:42 +0300 Subject: [PATCH 042/130] added the pool deposit amount node --- services/registration/pool_deposit_amount | 1 + services/registration/pool_deposit_amount.vis | 8 ++++++++ 2 files changed, 9 insertions(+) create mode 100644 services/registration/pool_deposit_amount create mode 100644 services/registration/pool_deposit_amount.vis diff --git a/services/registration/pool_deposit_amount b/services/registration/pool_deposit_amount new file mode 100644 index 0000000..ff3d119 --- /dev/null +++ b/services/registration/pool_deposit_amount @@ -0,0 +1 @@ +{{.pool_deposit_max_amount}} \ No newline at end of file diff --git a/services/registration/pool_deposit_amount.vis b/services/registration/pool_deposit_amount.vis new file mode 100644 index 0000000..68e6c8e --- /dev/null +++ b/services/registration/pool_deposit_amount.vis @@ -0,0 +1,8 @@ +LOAD pool_deposit_max_amount 0 +RELOAD pool_deposit_max_amount +CATCH _ flag_incorrect_voucher 1 +MAP pool_deposit_max_amount +MOUT back 0 +HALT +INCMP _ 0 +INCMP pool_deposit_confirmation * From 16adfdaa8a898d674e1470aa5b5948dd34119c58 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 6 Feb 2026 16:18:14 +0300 Subject: [PATCH 043/130] added data keys to easily manage a user's stable coins --- store/db/db.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/store/db/db.go b/store/db/db.go index 4cc3f57..7260243 100644 --- a/store/db/db.go +++ b/store/db/db.go @@ -65,7 +65,7 @@ const ( DATA_ACCOUNT_ALIAS //currently suggested alias by the api awaiting user's confirmation as accepted account alias DATA_SUGGESTED_ALIAS - //Key used to store a value of 1 for a user to reset their own PIN once they access the menu. + //Key used to store a value of 1 for a user to reset their own PIN once they access the menu. DATA_SELF_PIN_RESET // Holds the active pool contract address for the swap DATA_ACTIVE_POOL_ADDRESS @@ -104,7 +104,14 @@ const ( DATA_VOUCHER_DECIMALS // List of voucher EVM addresses for vouchers valid in the user context. DATA_VOUCHER_ADDRESSES - // List of senders for valid transactions in the user context. + // List of stable voucher symbols in the user context. + DATA_STABLE_VOUCHER_SYMBOLS + // List of stable voucher decimal counts for vouchers valid in the user context. + DATA_STABLE_VOUCHER_BALANCES + // List of stable voucher decimal counts for vouchers valid in the user context. + DATA_STABLE_VOUCHER_DECIMALS + // List of stable voucher EVM addresses for vouchers valid in the user context. + DATA_STABLE_VOUCHER_ADDRESSES ) const ( From f61b56407b5734b63b11ba9c3a2a2456db62f149 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 6 Feb 2026 16:19:45 +0300 Subject: [PATCH 044/130] rename the flag to flag_no_stable_vouchers --- handlers/application/balance.go | 6 +++--- services/registration/pay_debt.vis | 2 +- services/registration/pool_deposit.vis | 2 +- services/registration/pp.csv | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index b45e369..ad9a2aa 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -119,7 +119,7 @@ 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_pay_debt_vouchers, _ := h.flagManager.GetFlag("flag_no_pay_debt_vouchers") + flag_no_stable_vouchers, _ := h.flagManager.GetFlag("flag_no_stable_vouchers") // default response res.FlagReset = append(res.FlagReset, flag_api_call_error) @@ -161,11 +161,11 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i // No stable vouchers → cannot pay debt if len(filteredSwappableVouchers) == 0 { - res.FlagSet = append(res.FlagSet, flag_no_pay_debt_vouchers) + res.FlagSet = append(res.FlagSet, flag_no_stable_vouchers) return res, nil } - res.FlagReset = append(res.FlagReset, flag_no_pay_debt_vouchers) + res.FlagReset = append(res.FlagReset, flag_no_stable_vouchers) // Process stable vouchers for later use data := store.ProcessVouchers(filteredSwappableVouchers) diff --git a/services/registration/pay_debt.vis b/services/registration/pay_debt.vis index 147fe06..7cd5592 100644 --- a/services/registration/pay_debt.vis +++ b/services/registration/pay_debt.vis @@ -1,5 +1,5 @@ CATCH no_voucher flag_no_active_voucher 1 -CATCH no_stable_voucher flag_no_pay_debt_vouchers 1 +CATCH no_stable_voucher flag_no_stable_vouchers 1 LOAD calculate_max_pay_debt 0 RELOAD calculate_max_pay_debt MAP calculate_max_pay_debt diff --git a/services/registration/pool_deposit.vis b/services/registration/pool_deposit.vis index d93dfec..29b0182 100644 --- a/services/registration/pool_deposit.vis +++ b/services/registration/pool_deposit.vis @@ -1,5 +1,5 @@ CATCH no_voucher flag_no_active_voucher 1 -CATCH no_stable_voucher flag_no_pay_debt_vouchers 1 +CATCH no_stable_voucher flag_no_stable_vouchers 1 LOAD get_pool_deposit_vouchers 0 MAP get_pool_deposit_vouchers MOUT back 0 diff --git a/services/registration/pp.csv b/services/registration/pp.csv index 92ba16d..3911af7 100644 --- a/services/registration/pp.csv +++ b/services/registration/pp.csv @@ -36,4 +36,4 @@ flag,flag_incorrect_pool,42,this is set when the user selects an invalid pool flag,flag_low_swap_amount,43,this is set when the swap max limit is less than 0.1 flag,flag_alias_unavailable,44,this is set when the preferred alias is not available flag,flag_swap_transaction,45,this is set when the transaction will involve performing a swap -flag,flag_no_pay_debt_vouchers,46,this is set when the user does not have a stable voucher to pay debt +flag,flag_no_stable_vouchers,46,this is set when the user does not have a stable voucher From 601de0126a2c2f8f5281cacce471f2010bef1ac4 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 6 Feb 2026 16:20:20 +0300 Subject: [PATCH 045/130] store the list of stable coins that the user has --- handlers/application/vouchers.go | 39 +++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/handlers/application/vouchers.go b/handlers/application/vouchers.go index 895d9c6..6d0756d 100644 --- a/handlers/application/vouchers.go +++ b/handlers/application/vouchers.go @@ -16,7 +16,8 @@ import ( // ManageVouchers retrieves the token holdings from the API using the "PublicKey" and // 1. sets the first as the default voucher if no active voucher is set. // 2. Stores list of vouchers -// 3. updates the balance of the active voucher +// 3. Stores list of filtered stable vouchers +// 4. updates the balance of the active voucher func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result userStore := h.userdataStore @@ -29,6 +30,7 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b flag_no_active_voucher, _ := h.flagManager.GetFlag("flag_no_active_voucher") flag_api_error, _ := h.flagManager.GetFlag("flag_api_call_error") + flag_no_stable_vouchers, _ := h.flagManager.GetFlag("flag_no_stable_vouchers") publicKey, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY) if err != nil { @@ -170,6 +172,41 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b } } + // Filter stable vouchers + filteredStableVouchers := make([]dataserviceapi.TokenHoldings, 0) + for _, v := range vouchersResp { + + if isStableVoucher(v.TokenAddress) { + filteredStableVouchers = append(filteredStableVouchers, v) + } + } + + // No stable vouchers + if len(filteredStableVouchers) == 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 + stableVoucherData := store.ProcessVouchers(filteredStableVouchers) + + stableVoucherDataMap := map[storedb.DataTyp]string{ + storedb.DATA_STABLE_VOUCHER_SYMBOLS: stableVoucherData.Symbols, + storedb.DATA_STABLE_VOUCHER_BALANCES: stableVoucherData.Balances, + storedb.DATA_STABLE_VOUCHER_DECIMALS: stableVoucherData.Decimals, + storedb.DATA_STABLE_VOUCHER_ADDRESSES: stableVoucherData.Addresses, + } + + // Write data entries + for key, value := range stableVoucherDataMap { + 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 + } + } + return res, nil } From eb25aca96d319b126792eebbe0cf833cfe70edb4 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 6 Feb 2026 16:21:00 +0300 Subject: [PATCH 046/130] added pool deposit related functions to the local handler --- handlers/local.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/handlers/local.go b/handlers/local.go index 7c4b696..5fdb600 100644 --- a/handlers/local.go +++ b/handlers/local.go @@ -150,6 +150,10 @@ func (ls *LocalHandlerService) GetHandler(accountService remote.AccountService) ls.DbRs.AddLocalFunc("calculate_max_pay_debt", appHandlers.CalculateMaxPayDebt) ls.DbRs.AddLocalFunc("confirm_debt_removal", appHandlers.ConfirmDebtRemoval) ls.DbRs.AddLocalFunc("initiate_pay_debt", appHandlers.InitiatePayDebt) + ls.DbRs.AddLocalFunc("get_pool_deposit_vouchers", appHandlers.GetPoolDepositVouchers) + ls.DbRs.AddLocalFunc("pool_deposit_max_amount", appHandlers.PoolDepositMaxAmount) + ls.DbRs.AddLocalFunc("confirm_pool_deposit", appHandlers.ConfirmPoolDeposit) + ls.DbRs.AddLocalFunc("initiate_pool_deposit", appHandlers.InitiatePoolDeposit) ls.first = appHandlers.Init From ab8d1535c474047004986ba47c7f79cd176449fa Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 6 Feb 2026 16:40:57 +0300 Subject: [PATCH 047/130] added GetStableVoucherData --- store/vouchers.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/store/vouchers.go b/store/vouchers.go index dc849c6..5c28a0f 100644 --- a/store/vouchers.go +++ b/store/vouchers.go @@ -120,6 +120,43 @@ func GetVoucherData(ctx context.Context, store DataStore, sessionId string, inpu }, nil } +// GetStableVoucherData retrieves and matches stable voucher data +func GetStableVoucherData(ctx context.Context, store DataStore, sessionId string, input string) (*dataserviceapi.TokenHoldings, error) { + keys := []storedb.DataTyp{ + storedb.DATA_STABLE_VOUCHER_SYMBOLS, + storedb.DATA_STABLE_VOUCHER_BALANCES, + storedb.DATA_STABLE_VOUCHER_DECIMALS, + storedb.DATA_STABLE_VOUCHER_ADDRESSES, + } + data := make(map[storedb.DataTyp]string) + + for _, key := range keys { + value, err := store.ReadEntry(ctx, sessionId, key) + if err != nil { + return nil, fmt.Errorf("failed to get data key %x: %v", key, err) + } + data[key] = string(value) + } + + symbol, balance, decimal, address := MatchVoucher(input, + data[storedb.DATA_STABLE_VOUCHER_SYMBOLS], + data[storedb.DATA_STABLE_VOUCHER_BALANCES], + data[storedb.DATA_STABLE_VOUCHER_DECIMALS], + data[storedb.DATA_STABLE_VOUCHER_ADDRESSES], + ) + + if symbol == "" { + return nil, nil + } + + return &dataserviceapi.TokenHoldings{ + TokenSymbol: string(symbol), + Balance: string(balance), + TokenDecimals: string(decimal), + TokenAddress: string(address), + }, nil +} + // MatchVoucher finds the matching voucher symbol, balance, decimals and contract address based on the input. func MatchVoucher(input, symbols, balances, decimals, addresses string) (symbol, balance, decimal, address string) { symList := strings.Split(symbols, "\n") From 857e237996093e9228bafb792a5348fa38fc0f38 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Sat, 7 Feb 2026 16:50:56 +0300 Subject: [PATCH 048/130] added translations for the pool deposit --- services/registration/locale/swa/default.po | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/services/registration/locale/swa/default.po b/services/registration/locale/swa/default.po index 2892ce8..911acd7 100644 --- a/services/registration/locale/swa/default.po +++ b/services/registration/locale/swa/default.po @@ -32,7 +32,7 @@ msgid "Symbol: %s\nBalance: %s" msgstr "Sarafu: %s\nSalio: %s" msgid "Your request has been sent. You will receive an SMS when your %s %s has been swapped for %s." -msgstr "Ombi lako limetumwa. Utapokea SMS wakati %s %s yako itakapobadilishwa kuwa %s." +msgstr "Ombi lako limetumwa. Utapokea ujumbe wakati %s %s yako itakapobadilishwa kuwa %s." msgid "%s balance: %s\n" msgstr "%s salio: %s\n" @@ -83,4 +83,10 @@ msgid "Your active voucher %s is already set" msgstr "Sarafu yako %s ishachaguliwa" msgid "Select number or symbol from your vouchers:\n%s" -msgstr "Chagua nambari au ishara kutoka kwa sarafu zako:\n%s" \ No newline at end of file +msgstr "Chagua nambari au ishara kutoka kwa sarafu zako:\n%s" + +msgid "You will deposit %s %s into %s\n" +msgstr "Utaweka %s %s kwenye %s\n" + +msgid "Your request has been sent. You will receive an SMS when %s %s has been deposited into %s." +msgstr "Ombi lako limetumwa. Utapokea ujumbe wakati %s %s itawekwa kwenye %s." \ No newline at end of file From 35692d2bfd11334177ce3390b2b00ccee259cd1c Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Sat, 7 Feb 2026 17:29:40 +0300 Subject: [PATCH 049/130] prevent users from inputting amounts less than 0.1 --- handlers/application/send.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/handlers/application/send.go b/handlers/application/send.go index f7cdbfc..0114cde 100644 --- a/handlers/application/send.go +++ b/handlers/application/send.go @@ -585,7 +585,7 @@ func (h *MenuHandlers) ValidateAmount(ctx context.Context, sym string, input []b return res, nil } - if inputAmount > balanceValue { + if inputAmount > balanceValue || inputAmount < 0.1{ res.FlagSet = append(res.FlagSet, flag_invalid_amount) res.Content = amountStr return res, nil From dc2f9fce446d6ac93eb55239cbb7dbc4324f270e Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Sat, 7 Feb 2026 17:30:32 +0300 Subject: [PATCH 050/130] change the order of vis statements for error handling --- services/registration/pool_deposit.vis | 3 +++ services/registration/pool_deposit_amount.vis | 8 +++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/services/registration/pool_deposit.vis b/services/registration/pool_deposit.vis index 29b0182..8f06be6 100644 --- a/services/registration/pool_deposit.vis +++ b/services/registration/pool_deposit.vis @@ -11,4 +11,7 @@ INCMP > 88 INCMP < 98 INCMP _ 0 INCMP quit 99 +LOAD pool_deposit_max_amount 120 +RELOAD pool_deposit_max_amount +CATCH . flag_incorrect_voucher 1 INCMP pool_deposit_amount * diff --git a/services/registration/pool_deposit_amount.vis b/services/registration/pool_deposit_amount.vis index 68e6c8e..a51e140 100644 --- a/services/registration/pool_deposit_amount.vis +++ b/services/registration/pool_deposit_amount.vis @@ -1,8 +1,10 @@ -LOAD pool_deposit_max_amount 0 -RELOAD pool_deposit_max_amount -CATCH _ flag_incorrect_voucher 1 +LOAD reset_transaction_amount 10 +RELOAD reset_transaction_amount MAP pool_deposit_max_amount MOUT back 0 HALT +LOAD confirm_pool_deposit 140 +RELOAD confirm_pool_deposit +CATCH invalid_pool_deposit_amount flag_invalid_amount 1 INCMP _ 0 INCMP pool_deposit_confirmation * From f397d77989e6e831cb9bd0be76c7478d705df5bf Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Sat, 7 Feb 2026 17:31:53 +0300 Subject: [PATCH 051/130] added a CATCH for invalid pool deposit amounts --- services/registration/invalid_pool_deposit_amount | 1 + services/registration/invalid_pool_deposit_amount.vis | 7 +++++++ services/registration/invalid_pool_deposit_amount_swa | 1 + 3 files changed, 9 insertions(+) create mode 100644 services/registration/invalid_pool_deposit_amount create mode 100644 services/registration/invalid_pool_deposit_amount.vis create mode 100644 services/registration/invalid_pool_deposit_amount_swa diff --git a/services/registration/invalid_pool_deposit_amount b/services/registration/invalid_pool_deposit_amount new file mode 100644 index 0000000..e57b302 --- /dev/null +++ b/services/registration/invalid_pool_deposit_amount @@ -0,0 +1 @@ +Amount {{.confirm_pool_deposit}} is invalid, please try again: \ No newline at end of file diff --git a/services/registration/invalid_pool_deposit_amount.vis b/services/registration/invalid_pool_deposit_amount.vis new file mode 100644 index 0000000..08f5a23 --- /dev/null +++ b/services/registration/invalid_pool_deposit_amount.vis @@ -0,0 +1,7 @@ +MAP confirm_pool_deposit +RELOAD reset_transaction_amount +MOUT retry 1 +MOUT quit 9 +HALT +INCMP _ 1 +INCMP quit 9 diff --git a/services/registration/invalid_pool_deposit_amount_swa b/services/registration/invalid_pool_deposit_amount_swa new file mode 100644 index 0000000..19df9ce --- /dev/null +++ b/services/registration/invalid_pool_deposit_amount_swa @@ -0,0 +1 @@ +Kiwango {{.confirm_pool_deposit}} sio sahihi, tafadhali weka tena: \ No newline at end of file From 4ce967967d45645bc9dab02b0df5bd72b6ef01ac Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Sat, 7 Feb 2026 17:32:42 +0300 Subject: [PATCH 052/130] added a node for confirming the pool deposit --- services/registration/pool_deposit_confirmation | 2 ++ services/registration/pool_deposit_confirmation.vis | 10 ++++++++++ services/registration/pool_deposit_confirmation_swa | 2 ++ 3 files changed, 14 insertions(+) create mode 100644 services/registration/pool_deposit_confirmation create mode 100644 services/registration/pool_deposit_confirmation.vis create mode 100644 services/registration/pool_deposit_confirmation_swa diff --git a/services/registration/pool_deposit_confirmation b/services/registration/pool_deposit_confirmation new file mode 100644 index 0000000..5fe504a --- /dev/null +++ b/services/registration/pool_deposit_confirmation @@ -0,0 +1,2 @@ +{{.confirm_pool_deposit}} +Please enter your PIN to confirm: \ No newline at end of file diff --git a/services/registration/pool_deposit_confirmation.vis b/services/registration/pool_deposit_confirmation.vis new file mode 100644 index 0000000..36db1f6 --- /dev/null +++ b/services/registration/pool_deposit_confirmation.vis @@ -0,0 +1,10 @@ +MAP confirm_pool_deposit +MOUT back 0 +MOUT quit 9 +HALT +LOAD authorize_account 6 +RELOAD authorize_account +CATCH incorrect_pin flag_incorrect_pin 1 +INCMP _ 0 +INCMP quit 9 +INCMP pool_deposit_initiated * diff --git a/services/registration/pool_deposit_confirmation_swa b/services/registration/pool_deposit_confirmation_swa new file mode 100644 index 0000000..00f84a6 --- /dev/null +++ b/services/registration/pool_deposit_confirmation_swa @@ -0,0 +1,2 @@ +{{.confirm_pool_deposit}} +Tafadhali weka PIN yako kudhibitisha: \ No newline at end of file From e14387a975cdd3771fb0fb8768d5ba8c498fa1fe Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Sat, 7 Feb 2026 17:33:01 +0300 Subject: [PATCH 053/130] added a node for initializing the pool deposit --- services/registration/pool_deposit_initiated.vis | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 services/registration/pool_deposit_initiated.vis diff --git a/services/registration/pool_deposit_initiated.vis b/services/registration/pool_deposit_initiated.vis new file mode 100644 index 0000000..8524d33 --- /dev/null +++ b/services/registration/pool_deposit_initiated.vis @@ -0,0 +1,4 @@ +LOAD reset_incorrect_pin 6 +CATCH _ flag_account_authorized 0 +LOAD initiate_pool_deposit 0 +HALT From c548ea0700b85fd2b1f0d99afd8af0fa47c768f7 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Sat, 7 Feb 2026 17:57:46 +0300 Subject: [PATCH 054/130] added pool deposit functions --- handlers/application/pool_deposit.go | 220 +++++++++++++++++++++++++++ 1 file changed, 220 insertions(+) create mode 100644 handlers/application/pool_deposit.go diff --git a/handlers/application/pool_deposit.go b/handlers/application/pool_deposit.go new file mode 100644 index 0000000..bcc84c1 --- /dev/null +++ b/handlers/application/pool_deposit.go @@ -0,0 +1,220 @@ +package application + +import ( + "context" + "fmt" + "strconv" + "strings" + + "git.defalsify.org/vise.git/resource" + "git.grassecon.net/grassrootseconomics/sarafu-vise/store" + storedb "git.grassecon.net/grassrootseconomics/sarafu-vise/store/db" + "gopkg.in/leonelquinteros/gotext.v1" +) + +// GetPoolDepositVouchers returns a list of stable coins +func (h *MenuHandlers) GetPoolDepositVouchers(ctx context.Context, sym string, input []byte) (resource.Result, error) { + var res resource.Result + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + + code := codeFromCtx(ctx) + l := gotext.NewLocale(translationDir, code) + l.AddDomain("default") + + userStore := h.userdataStore + + // Read stable vouchers from the store + voucherData, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_STABLE_VOUCHER_SYMBOLS) + if err != nil { + logg.ErrorCtxf(ctx, "failed to read stable voucherData entires with", "key", storedb.DATA_STABLE_VOUCHER_SYMBOLS, "error", err) + return res, err + } + + if len(voucherData) == 0 { + return res, nil + } + + voucherBalances, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_STABLE_VOUCHER_BALANCES) + if err != nil { + logg.ErrorCtxf(ctx, "failed to read stable voucherData entires with", "key", storedb.DATA_STABLE_VOUCHER_BALANCES, "error", err) + return res, err + } + + formattedVoucherList := store.FormatVoucherList(ctx, string(voucherData), string(voucherBalances)) + finalOutput := strings.Join(formattedVoucherList, "\n") + + res.Content = l.Get("Select number or symbol from your vouchers:\n%s", finalOutput) + + return res, nil +} + +// PoolDepositMaxAmount returns the balance of the selected voucher +func (h *MenuHandlers) PoolDepositMaxAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { + var res resource.Result + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + + code := codeFromCtx(ctx) + l := gotext.NewLocale(translationDir, code) + l.AddDomain("default") + + flag_incorrect_voucher, _ := h.flagManager.GetFlag("flag_incorrect_voucher") + + res.FlagReset = append(res.FlagReset, flag_incorrect_voucher) + + inputStr := string(input) + if inputStr == "0" || inputStr == "99" || inputStr == "88" || inputStr == "98" { + return res, nil + } + + userStore := h.userdataStore + metadata, err := store.GetStableVoucherData(ctx, userStore, sessionId, inputStr) + if err != nil { + return res, fmt.Errorf("failed to retrieve swap to voucher data: %v", err) + } + if metadata == nil { + res.FlagSet = append(res.FlagSet, flag_incorrect_voucher) + return res, nil + } + + // Store the pool deposit voucher data + if err := store.StoreTemporaryVoucher(ctx, h.userdataStore, sessionId, metadata); err != nil { + logg.ErrorCtxf(ctx, "failed on StoreTemporaryVoucher", "error", err) + return res, err + } + + // Format the balance amount to 2 decimal places + formattedBalance, _ := store.TruncateDecimalString(string(metadata.Balance), 2) + + res.Content = l.Get("Maximum amount: %s %s\nEnter amount:", formattedBalance, metadata.TokenSymbol) + + return res, nil +} + +// ConfirmPoolDeposit displays the pool deposit preview for a PIN confirmation +func (h *MenuHandlers) ConfirmPoolDeposit(ctx context.Context, sym string, input []byte) (resource.Result, error) { + var res resource.Result + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + + inputStr := string(input) + if inputStr == "0" { + return res, nil + } + + flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") + + res.FlagReset = append(res.FlagReset, flag_invalid_amount) + + code := codeFromCtx(ctx) + l := gotext.NewLocale(translationDir, code) + l.AddDomain("default") + + userStore := h.userdataStore + + poolDepositVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + return res, err + } + + maxValue, err := strconv.ParseFloat(poolDepositVoucher.Balance, 64) + if err != nil { + logg.ErrorCtxf(ctx, "Failed to convert the swapMaxAmount to a float", "error", err) + return res, err + } + + inputAmount, err := strconv.ParseFloat(inputStr, 64) + if err != nil || inputAmount > maxValue || inputAmount < 0.1 { + res.FlagSet = append(res.FlagSet, flag_invalid_amount) + res.Content = inputStr + return res, nil + } + + err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_AMOUNT, []byte(inputStr)) + if err != nil { + logg.ErrorCtxf(ctx, "failed to write pool deposit amount entry with", "key", storedb.DATA_AMOUNT, "value", inputStr, "error", err) + return res, err + } + + // Resolve active pool + _, activePoolName, err := h.resolveActivePoolDetails(ctx, sessionId) + if err != nil { + return res, err + } + + res.Content = l.Get( + "You will deposit %s %s into %s\n", + inputStr, poolDepositVoucher.TokenSymbol, activePoolName, + ) + + return res, nil +} + +// InitiatePoolDeposit calls the pool deposit API +func (h *MenuHandlers) InitiatePoolDeposit(ctx context.Context, sym string, input []byte) (resource.Result, error) { + var res resource.Result + var err error + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + + flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") + + code := codeFromCtx(ctx) + l := gotext.NewLocale(translationDir, code) + l.AddDomain("default") + + // Resolve active pool + activePoolAddress, activePoolName, err := h.resolveActivePoolDetails(ctx, sessionId) + if err != nil { + return res, err + } + + poolDepositVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + return res, err + } + + poolDepositdata, err := store.ReadTransactionData(ctx, h.userdataStore, sessionId) + if err != nil { + return res, err + } + + finalAmountStr, err := store.ParseAndScaleAmount(poolDepositdata.Amount, poolDepositVoucher.TokenDecimals) + if err != nil { + return res, err + } + + // Call pool deposit API + r, err := h.accountService.PoolDeposit(ctx, finalAmountStr, poolDepositdata.PublicKey, string(activePoolAddress), poolDepositVoucher.TokenAddress) + 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 pool deposit", "error", err) + return res, nil + } + + trackingId := r.TrackingId + logg.InfoCtxf(ctx, "Pool deposit", "trackingId", trackingId) + + res.Content = l.Get( + "Your request has been sent. You will receive an SMS when %s %s has been deposited into %s.", + poolDepositdata.Amount, + poolDepositVoucher.TokenSymbol, + activePoolName, + ) + + res.FlagReset = append(res.FlagReset, flag_account_authorized) + return res, nil +} From 7f6be9258d004b42f018ea126abaed7e1b90d438 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Sat, 7 Feb 2026 18:00:47 +0300 Subject: [PATCH 055/130] updated the env example comment on stable voucher addresses --- .env.example | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.env.example b/.env.example index 2afa594..8b06a62 100644 --- a/.env.example +++ b/.env.example @@ -38,5 +38,5 @@ DEFAULT_MPESA_ASSET=cUSD MPESA_BEARER_TOKEN=eyJeSIsInRcCI6IkpXVCJ.yJwdWJsaWNLZXkiOiIwrrrrrr MPESA_ONRAMP_BASE=https://pretium.v1.grassecon.net -# Stable vouchers allowed for Pay Debt (USDT, USDm) +# Known stable voucher addresses (USDT, USDm) STABLE_VOUCHER_ADDRESSES=0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e,0x765DE816845861e75A25fCA122bb6898B8B1282a From c4e2ed6db2e73558ce0597b342854be833b6e366 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Sat, 7 Feb 2026 18:10:19 +0300 Subject: [PATCH 056/130] use the updated pool deposit URL --- go.mod | 2 +- go.sum | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 6dbc8e3..11911e6 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,7 @@ toolchain go1.24.10 require ( git.defalsify.org/vise.git v0.3.2-0.20250528124150-03bf7bfc1b66 git.grassecon.net/grassrootseconomics/common v0.9.0-beta.1.0.20251127132814-8ceadabbc215 - git.grassecon.net/grassrootseconomics/sarafu-api v0.9.0-beta.1.0.20251202085112-45469d4ba326 + git.grassecon.net/grassrootseconomics/sarafu-api v0.9.0-beta.1.0.20260207150752-71aa5ce7b537 git.grassecon.net/grassrootseconomics/visedriver v0.9.0-beta.2.0.20250408094335-e2d1f65bb306 git.grassecon.net/grassrootseconomics/visedriver-africastalking v0.0.0-20250129070628-5a539172c694 github.com/alecthomas/assert/v2 v2.2.2 diff --git a/go.sum b/go.sum index 3d4882f..067c990 100644 --- a/go.sum +++ b/go.sum @@ -6,6 +6,8 @@ git.grassecon.net/grassrootseconomics/sarafu-api v0.9.0-beta.1.0.20251128071248- git.grassecon.net/grassrootseconomics/sarafu-api v0.9.0-beta.1.0.20251128071248-bfdeef125576/go.mod h1:h/y/lJNJAVTcIzAxCMXXw8Dh2aoLxBFZ6F1nTB8C0nU= git.grassecon.net/grassrootseconomics/sarafu-api v0.9.0-beta.1.0.20251202085112-45469d4ba326 h1:qH4QulgncvAD7b/YeHGPxcDJTBIychPeoZJACefYryI= git.grassecon.net/grassrootseconomics/sarafu-api v0.9.0-beta.1.0.20251202085112-45469d4ba326/go.mod h1:h/y/lJNJAVTcIzAxCMXXw8Dh2aoLxBFZ6F1nTB8C0nU= +git.grassecon.net/grassrootseconomics/sarafu-api v0.9.0-beta.1.0.20260207150752-71aa5ce7b537 h1:2AoOHiRTN3SXX4qnc2wOaF2ktVXLlFAa3X/n9DLu8/s= +git.grassecon.net/grassrootseconomics/sarafu-api v0.9.0-beta.1.0.20260207150752-71aa5ce7b537/go.mod h1:h/y/lJNJAVTcIzAxCMXXw8Dh2aoLxBFZ6F1nTB8C0nU= git.grassecon.net/grassrootseconomics/visedriver v0.9.0-beta.2.0.20250408094335-e2d1f65bb306 h1:Jo+yWysWw/N5BJQtAyEMN8ePVvAyPHv+JG4lQti+1N4= git.grassecon.net/grassrootseconomics/visedriver v0.9.0-beta.2.0.20250408094335-e2d1f65bb306/go.mod h1:FdLwYtzsjOIcDiW4uDgDYnB4Wdzq12uJUe0QHSSPbSo= git.grassecon.net/grassrootseconomics/visedriver-africastalking v0.0.0-20250129070628-5a539172c694 h1:DjJlBSz0S13acft5XZDWk7ZYnzElym0xLMYEVgyNJ+E= From 5ed7cbd40a1b90337aafb1cb73c7c9e3d1db979e Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Mon, 9 Feb 2026 14:14:44 +0300 Subject: [PATCH 057/130] update the Mpesa response once someone requests for a withdrawal --- handlers/application/mpesa.go | 3 +-- services/registration/locale/swa/default.po | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/handlers/application/mpesa.go b/handlers/application/mpesa.go index 876cd95..695c0e2 100644 --- a/handlers/application/mpesa.go +++ b/handlers/application/mpesa.go @@ -387,11 +387,10 @@ func (h *MenuHandlers) InitiateGetMpesa(ctx context.Context, sym string, input [ logg.InfoCtxf(ctx, "TokenTransfer normal", "trackingId", tokenTransfer.TrackingId) - res.Content = l.Get("Your request has been sent. You will receive ~ %s ksh", data.TemporaryValue) + res.Content = l.Get("Your request has been sent. Please await confirmation") res.FlagReset = append(res.FlagReset, flag_account_authorized) return res, nil - } swapAmount, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_SWAP_AMOUNT) diff --git a/services/registration/locale/swa/default.po b/services/registration/locale/swa/default.po index 911acd7..21d30ce 100644 --- a/services/registration/locale/swa/default.po +++ b/services/registration/locale/swa/default.po @@ -61,8 +61,8 @@ msgstr "Weka kiasi cha M-Pesa cha kupata: (Kikomo %s Ksh)\n" msgid "You are sending %s %s in order to receive ~ %s ksh" msgstr "Unatuma ~ %s %s ili upoke %s ksh" -msgid "Your request has been sent. You will receive ~ %s ksh" -msgstr "Ombi lako limetumwa. Utapokea ~ %s ksh" +msgid "Your request has been sent. Please await confirmation" +msgstr "Ombi lako limetumwa. Tafadhali subiri" msgid "Enter the amount of M-Pesa to send: (Minimum %s Ksh)\n" msgstr "Weka kiasi cha M-Pesa cha kutuma: (Kima cha chini %s Ksh)\n" From ea71c08143a595087f77c22c05612ae964c2045d Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 12 Feb 2026 10:24:54 +0300 Subject: [PATCH 058/130] rename the data keys to store ordered voucher lists --- handlers/application/pool_deposit.go | 8 ++++---- store/db/db.go | 16 ++++++++-------- store/vouchers.go | 16 ++++++++-------- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/handlers/application/pool_deposit.go b/handlers/application/pool_deposit.go index bcc84c1..b540941 100644 --- a/handlers/application/pool_deposit.go +++ b/handlers/application/pool_deposit.go @@ -27,9 +27,9 @@ func (h *MenuHandlers) GetPoolDepositVouchers(ctx context.Context, sym string, i userStore := h.userdataStore // Read stable vouchers from the store - voucherData, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_STABLE_VOUCHER_SYMBOLS) + voucherData, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_ORDERED_VOUCHER_SYMBOLS) if err != nil { - logg.ErrorCtxf(ctx, "failed to read stable voucherData entires with", "key", storedb.DATA_STABLE_VOUCHER_SYMBOLS, "error", err) + logg.ErrorCtxf(ctx, "failed to read stable voucherData entires with", "key", storedb.DATA_ORDERED_VOUCHER_SYMBOLS, "error", err) return res, err } @@ -37,9 +37,9 @@ func (h *MenuHandlers) GetPoolDepositVouchers(ctx context.Context, sym string, i return res, nil } - voucherBalances, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_STABLE_VOUCHER_BALANCES) + voucherBalances, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_ORDERED_VOUCHER_BALANCES) if err != nil { - logg.ErrorCtxf(ctx, "failed to read stable voucherData entires with", "key", storedb.DATA_STABLE_VOUCHER_BALANCES, "error", err) + logg.ErrorCtxf(ctx, "failed to read stable voucherData entires with", "key", storedb.DATA_ORDERED_VOUCHER_BALANCES, "error", err) return res, err } diff --git a/store/db/db.go b/store/db/db.go index 7260243..e228971 100644 --- a/store/db/db.go +++ b/store/db/db.go @@ -104,14 +104,14 @@ const ( DATA_VOUCHER_DECIMALS // List of voucher EVM addresses for vouchers valid in the user context. DATA_VOUCHER_ADDRESSES - // List of stable voucher symbols in the user context. - DATA_STABLE_VOUCHER_SYMBOLS - // List of stable voucher decimal counts for vouchers valid in the user context. - DATA_STABLE_VOUCHER_BALANCES - // List of stable voucher decimal counts for vouchers valid in the user context. - DATA_STABLE_VOUCHER_DECIMALS - // List of stable voucher EVM addresses for vouchers valid in the user context. - DATA_STABLE_VOUCHER_ADDRESSES + // List of ordered voucher symbols in the user context. + DATA_ORDERED_VOUCHER_SYMBOLS + // List of ordered voucher balances in the user context. + DATA_ORDERED_VOUCHER_BALANCES + // List of ordered voucher decimals in the user context. + DATA_ORDERED_VOUCHER_DECIMALS + // List of ordered voucher EVM addresses in the user context. + DATA_ORDERED_VOUCHER_ADDRESSES ) const ( diff --git a/store/vouchers.go b/store/vouchers.go index 5c28a0f..c8d5e42 100644 --- a/store/vouchers.go +++ b/store/vouchers.go @@ -123,10 +123,10 @@ func GetVoucherData(ctx context.Context, store DataStore, sessionId string, inpu // GetStableVoucherData retrieves and matches stable voucher data func GetStableVoucherData(ctx context.Context, store DataStore, sessionId string, input string) (*dataserviceapi.TokenHoldings, error) { keys := []storedb.DataTyp{ - storedb.DATA_STABLE_VOUCHER_SYMBOLS, - storedb.DATA_STABLE_VOUCHER_BALANCES, - storedb.DATA_STABLE_VOUCHER_DECIMALS, - storedb.DATA_STABLE_VOUCHER_ADDRESSES, + storedb.DATA_ORDERED_VOUCHER_SYMBOLS, + storedb.DATA_ORDERED_VOUCHER_BALANCES, + storedb.DATA_ORDERED_VOUCHER_DECIMALS, + storedb.DATA_ORDERED_VOUCHER_ADDRESSES, } data := make(map[storedb.DataTyp]string) @@ -139,10 +139,10 @@ func GetStableVoucherData(ctx context.Context, store DataStore, sessionId string } symbol, balance, decimal, address := MatchVoucher(input, - data[storedb.DATA_STABLE_VOUCHER_SYMBOLS], - data[storedb.DATA_STABLE_VOUCHER_BALANCES], - data[storedb.DATA_STABLE_VOUCHER_DECIMALS], - data[storedb.DATA_STABLE_VOUCHER_ADDRESSES], + data[storedb.DATA_ORDERED_VOUCHER_SYMBOLS], + data[storedb.DATA_ORDERED_VOUCHER_BALANCES], + data[storedb.DATA_ORDERED_VOUCHER_DECIMALS], + data[storedb.DATA_ORDERED_VOUCHER_ADDRESSES], ) if symbol == "" { From 50c2aff79ed34b77d0f7c647644099528796276d Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 12 Feb 2026 10:25:53 +0300 Subject: [PATCH 059/130] store the ordered list of vouchers with stables at the top --- handlers/application/vouchers.go | 54 ++++++++++++++++++++++---------- 1 file changed, 38 insertions(+), 16 deletions(-) diff --git a/handlers/application/vouchers.go b/handlers/application/vouchers.go index 6d0756d..3899de6 100644 --- a/handlers/application/vouchers.go +++ b/handlers/application/vouchers.go @@ -3,10 +3,12 @@ package application import ( "context" "fmt" + "sort" "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" @@ -172,35 +174,55 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b } } - // Filter stable vouchers - filteredStableVouchers := make([]dataserviceapi.TokenHoldings, 0) - for _, v := range vouchersResp { + // Get stable voucher priority order (lower index = higher priority) + stablePriority := make(map[string]int) + stableAddresses := config.StableVoucherAddresses() + 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) { - filteredStableVouchers = append(filteredStableVouchers, v) + stableVouchers = append(stableVouchers, v) + } else { + nonStableVouchers = append(nonStableVouchers, v) } } - // No stable vouchers - if len(filteredStableVouchers) == 0 { + // No stable vouchers at all + if len(stableVouchers) == 0 { res.FlagSet = append(res.FlagSet, flag_no_stable_vouchers) - return res, nil + } else { + res.FlagReset = append(res.FlagReset, flag_no_stable_vouchers) } - 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 + }) - // Process stable vouchers for later use - stableVoucherData := store.ProcessVouchers(filteredStableVouchers) + // Final ordered list: stable first, then others + orderedVouchers := append(stableVouchers, nonStableVouchers...) - stableVoucherDataMap := map[storedb.DataTyp]string{ - storedb.DATA_STABLE_VOUCHER_SYMBOLS: stableVoucherData.Symbols, - storedb.DATA_STABLE_VOUCHER_BALANCES: stableVoucherData.Balances, - storedb.DATA_STABLE_VOUCHER_DECIMALS: stableVoucherData.Decimals, - storedb.DATA_STABLE_VOUCHER_ADDRESSES: stableVoucherData.Addresses, + // Process ALL vouchers (stable first) + orderedVoucherData := store.ProcessVouchers(orderedVouchers) + + orderedVoucherDataMap := map[storedb.DataTyp]string{ + storedb.DATA_ORDERED_VOUCHER_SYMBOLS: orderedVoucherData.Symbols, + storedb.DATA_ORDERED_VOUCHER_BALANCES: orderedVoucherData.Balances, + storedb.DATA_ORDERED_VOUCHER_DECIMALS: orderedVoucherData.Decimals, + storedb.DATA_ORDERED_VOUCHER_ADDRESSES: orderedVoucherData.Addresses, } // Write data entries - for key, value := range stableVoucherDataMap { + for key, value := range orderedVoucherDataMap { 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 From 1a61ea6de3e452e6e25bf19a390b65a97531e5f8 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 12 Feb 2026 10:29:05 +0300 Subject: [PATCH 060/130] rename the function for reuse --- handlers/application/pool_deposit.go | 6 +++--- handlers/local.go | 2 +- services/registration/pool_deposit | 2 +- services/registration/pool_deposit.vis | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/handlers/application/pool_deposit.go b/handlers/application/pool_deposit.go index b540941..f87b9c4 100644 --- a/handlers/application/pool_deposit.go +++ b/handlers/application/pool_deposit.go @@ -12,8 +12,8 @@ import ( "gopkg.in/leonelquinteros/gotext.v1" ) -// GetPoolDepositVouchers returns a list of stable coins -func (h *MenuHandlers) GetPoolDepositVouchers(ctx context.Context, sym string, input []byte) (resource.Result, error) { +// GetOrderedVouchers returns a list of ordered vouchers with stables at the top +func (h *MenuHandlers) GetOrderedVouchers(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result sessionId, ok := ctx.Value("SessionId").(string) if !ok { @@ -26,7 +26,7 @@ func (h *MenuHandlers) GetPoolDepositVouchers(ctx context.Context, sym string, i userStore := h.userdataStore - // Read stable vouchers from the store + // Read ordered vouchers from the store voucherData, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_ORDERED_VOUCHER_SYMBOLS) if err != nil { logg.ErrorCtxf(ctx, "failed to read stable voucherData entires with", "key", storedb.DATA_ORDERED_VOUCHER_SYMBOLS, "error", err) diff --git a/handlers/local.go b/handlers/local.go index 5fdb600..e19fc20 100644 --- a/handlers/local.go +++ b/handlers/local.go @@ -150,7 +150,7 @@ func (ls *LocalHandlerService) GetHandler(accountService remote.AccountService) ls.DbRs.AddLocalFunc("calculate_max_pay_debt", appHandlers.CalculateMaxPayDebt) ls.DbRs.AddLocalFunc("confirm_debt_removal", appHandlers.ConfirmDebtRemoval) ls.DbRs.AddLocalFunc("initiate_pay_debt", appHandlers.InitiatePayDebt) - ls.DbRs.AddLocalFunc("get_pool_deposit_vouchers", appHandlers.GetPoolDepositVouchers) + ls.DbRs.AddLocalFunc("get_ordered_vouchers", appHandlers.GetOrderedVouchers) ls.DbRs.AddLocalFunc("pool_deposit_max_amount", appHandlers.PoolDepositMaxAmount) ls.DbRs.AddLocalFunc("confirm_pool_deposit", appHandlers.ConfirmPoolDeposit) ls.DbRs.AddLocalFunc("initiate_pool_deposit", appHandlers.InitiatePoolDeposit) diff --git a/services/registration/pool_deposit b/services/registration/pool_deposit index 841c240..0863a44 100644 --- a/services/registration/pool_deposit +++ b/services/registration/pool_deposit @@ -1 +1 @@ -{{.get_pool_deposit_vouchers}} +{{.get_ordered_vouchers}} diff --git a/services/registration/pool_deposit.vis b/services/registration/pool_deposit.vis index 8f06be6..55f4990 100644 --- a/services/registration/pool_deposit.vis +++ b/services/registration/pool_deposit.vis @@ -1,7 +1,7 @@ CATCH no_voucher flag_no_active_voucher 1 CATCH no_stable_voucher flag_no_stable_vouchers 1 -LOAD get_pool_deposit_vouchers 0 -MAP get_pool_deposit_vouchers +LOAD get_ordered_vouchers 0 +MAP get_ordered_vouchers MOUT back 0 MOUT quit 99 MNEXT next 88 From f4c8c45ed1d73e65584ffc9206fa735ed0284f8e Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 12 Feb 2026 14:20:42 +0300 Subject: [PATCH 061/130] rename the function to match the ordered voucher data --- handlers/application/pool_deposit.go | 2 +- store/vouchers.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/handlers/application/pool_deposit.go b/handlers/application/pool_deposit.go index f87b9c4..b12b5d2 100644 --- a/handlers/application/pool_deposit.go +++ b/handlers/application/pool_deposit.go @@ -73,7 +73,7 @@ func (h *MenuHandlers) PoolDepositMaxAmount(ctx context.Context, sym string, inp } userStore := h.userdataStore - metadata, err := store.GetStableVoucherData(ctx, userStore, sessionId, inputStr) + metadata, err := store.GetOrderedVoucherData(ctx, userStore, sessionId, inputStr) if err != nil { return res, fmt.Errorf("failed to retrieve swap to voucher data: %v", err) } diff --git a/store/vouchers.go b/store/vouchers.go index c8d5e42..5e7d986 100644 --- a/store/vouchers.go +++ b/store/vouchers.go @@ -120,8 +120,8 @@ func GetVoucherData(ctx context.Context, store DataStore, sessionId string, inpu }, nil } -// GetStableVoucherData retrieves and matches stable voucher data -func GetStableVoucherData(ctx context.Context, store DataStore, sessionId string, input string) (*dataserviceapi.TokenHoldings, error) { +// GetOrderedVoucherData retrieves and matches ordered voucher data +func GetOrderedVoucherData(ctx context.Context, store DataStore, sessionId string, input string) (*dataserviceapi.TokenHoldings, error) { keys := []storedb.DataTyp{ storedb.DATA_ORDERED_VOUCHER_SYMBOLS, storedb.DATA_ORDERED_VOUCHER_BALANCES, From 115cf2fbc91c4014ba10225f2bf1409b9f28e6dc Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 12 Feb 2026 15:04:42 +0300 Subject: [PATCH 062/130] added the minimum mpesa withdrawal amount config --- .env.example | 1 + config/config.go | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/.env.example b/.env.example index 8b06a62..d4871ad 100644 --- a/.env.example +++ b/.env.example @@ -34,6 +34,7 @@ INCLUDE_STABLES_PARAM=false DEFAULT_MPESA_ADDRESS=0x48a953cA5cf5298bc6f6Af3C608351f537AAcb9e MIN_MPESA_SEND_AMOUNT=100 MAX_MPESA_SEND_AMOUNT=250000 +MIN_MPESA_WITHDRAW_AMOUNT=20 DEFAULT_MPESA_ASSET=cUSD MPESA_BEARER_TOKEN=eyJeSIsInRcCI6IkpXVCJ.yJwdWJsaWNLZXkiOiIwrrrrrr MPESA_ONRAMP_BASE=https://pretium.v1.grassecon.net diff --git a/config/config.go b/config/config.go index 7ee27e0..ec3821a 100644 --- a/config/config.go +++ b/config/config.go @@ -102,6 +102,16 @@ func MinMpesaSendAmount() float64 { return f } +func MinMpesaWithdrawAmount() float64 { + v := env.GetEnv("MIN_MPESA_WITHDRAW_AMOUNT", "20") + f, err := strconv.ParseFloat(v, 64) + if err != nil { + return 20 // fallback + } + return f +} + + func MaxMpesaSendAmount() float64 { v := env.GetEnv("MAX_MPESA_SEND_AMOUNT", "250000") f, err := strconv.ParseFloat(v, 64) From 0e38ef1d04554e7d199cd381d7f44a61a55b8787 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 12 Feb 2026 16:23:18 +0300 Subject: [PATCH 063/130] updated the withdraw mpesa flow to support selection of a voucher --- handlers/application/mpesa.go | 113 +++++++++++------- services/registration/get_mpesa | 2 +- services/registration/get_mpesa.vis | 19 +-- .../registration/get_mpesa_confirmation.vis | 3 - .../registration/invalid_get_mpesa_amount | 1 + .../registration/invalid_get_mpesa_amount.vis | 7 ++ .../registration/invalid_get_mpesa_amount_swa | 1 + services/registration/mpesa_max_limit | 1 + services/registration/mpesa_max_limit.vis | 13 ++ 9 files changed, 106 insertions(+), 54 deletions(-) create mode 100644 services/registration/invalid_get_mpesa_amount create mode 100644 services/registration/invalid_get_mpesa_amount.vis create mode 100644 services/registration/invalid_get_mpesa_amount_swa create mode 100644 services/registration/mpesa_max_limit create mode 100644 services/registration/mpesa_max_limit.vis diff --git a/handlers/application/mpesa.go b/handlers/application/mpesa.go index 695c0e2..467adc8 100644 --- a/handlers/application/mpesa.go +++ b/handlers/application/mpesa.go @@ -28,20 +28,36 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error") flag_low_swap_amount, _ := h.flagManager.GetFlag("flag_low_swap_amount") flag_incorrect_pool, _ := h.flagManager.GetFlag("flag_incorrect_pool") + flag_incorrect_voucher, _ := h.flagManager.GetFlag("flag_incorrect_voucher") code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) l.AddDomain("default") inputStr := string(input) - if inputStr == "0" || inputStr == "9" { + if inputStr == "0" || inputStr == "99" || inputStr == "88" || inputStr == "98" { + res.FlagReset = append(res.FlagReset, flag_low_swap_amount, flag_api_call_error, flag_incorrect_voucher) return res, nil } userStore := h.userdataStore + metadata, err := store.GetOrderedVoucherData(ctx, userStore, sessionId, inputStr) + if err != nil { + return res, fmt.Errorf("failed to retrieve swap to voucher data: %v", err) + } + if metadata == nil { + res.FlagSet = append(res.FlagSet, flag_incorrect_voucher) + return res, nil + } + + // Store the active transaction voucher data + if err := store.StoreTemporaryVoucher(ctx, h.userdataStore, sessionId, metadata); err != nil { + logg.ErrorCtxf(ctx, "failed on StoreTemporaryVoucher", "error", err) + return res, err + } // Fetch session data - _, activeBal, _, activeAddress, publicKey, activeDecimal, err := h.getSessionData(ctx, sessionId) + _, _, _, _, publicKey, _, err := h.getSessionData(ctx, sessionId) if err != nil { return res, err } @@ -83,8 +99,12 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ return res, err } + // Fetch min withdrawal amount from config/env + minksh := fmt.Sprintf("%f", config.MinMpesaWithdrawAmount()) + minKshFormatted, _ := store.TruncateDecimalString(minksh, 0) + // If RAT is the same as SAT, return early with KSH format - if string(activeAddress) == string(recipientActiveAddress) { + if string(metadata.TokenAddress) == string(recipientActiveAddress) { txType = "normal" // Save the transaction type if err := userStore.WriteEntry(ctx, sessionId, storedb.DATA_SEND_TRANSACTION_TYPE, []byte(txType)); err != nil { @@ -92,14 +112,15 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ return res, err } - activeFloat, _ := strconv.ParseFloat(string(activeBal), 64) + activeFloat, _ := strconv.ParseFloat(string(metadata.Balance), 64) ksh := fmt.Sprintf("%f", activeFloat*rates.Buy) - kshFormatted, _ := store.TruncateDecimalString(ksh, 0) + maxKshFormatted, _ := store.TruncateDecimalString(ksh, 0) res.Content = l.Get( - "Enter the amount of Mpesa to get: (Max %s Ksh)\n", - kshFormatted, + "Enter the amount of Mpesa to withdraw: (Min: Ksh %s, Max %s Ksh)\n", + minKshFormatted, + maxKshFormatted, ) return res, nil @@ -112,7 +133,7 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ } // Check if sender token is swappable - canSwap, err := h.accountService.CheckTokenInPool(ctx, string(activePoolAddress), string(activeAddress)) + canSwap, err := h.accountService.CheckTokenInPool(ctx, string(activePoolAddress), string(metadata.TokenAddress)) if err != nil { res.FlagSet = append(res.FlagSet, flag_api_call_error) logg.ErrorCtxf(ctx, "failed on CheckTokenInPool", "error", err) @@ -125,7 +146,7 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ } // retrieve the max credit send amounts - _, maxRAT, err := h.calculateSendCreditLimits(ctx, activePoolAddress, activeAddress, recipientActiveAddress, publicKey, activeDecimal, recipientActiveDecimal) + _, maxRAT, err := h.calculateSendCreditLimits(ctx, activePoolAddress, []byte(metadata.TokenAddress), recipientActiveAddress, publicKey, []byte(metadata.TokenDecimals), recipientActiveDecimal) if err != nil { res.FlagSet = append(res.FlagSet, flag_api_call_error) logg.ErrorCtxf(ctx, "failed on calculateSendCreditLimits", "error", err) @@ -155,25 +176,26 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ } // save swap related data for the swap preview - metadata := &dataserviceapi.TokenHoldings{ + swapMetadata := &dataserviceapi.TokenHoldings{ TokenAddress: string(recipientActiveAddress), TokenSymbol: string(recipientActiveSym), TokenDecimals: string(recipientActiveDecimal), } // Store the active swap_to data - if err := store.UpdateSwapToVoucherData(ctx, userStore, sessionId, metadata); err != nil { + if err := store.UpdateSwapToVoucherData(ctx, userStore, sessionId, swapMetadata); err != nil { logg.ErrorCtxf(ctx, "failed on UpdateSwapToVoucherData", "error", err) return res, err } maxKsh := maxFloat * rates.Buy kshStr := fmt.Sprintf("%f", maxKsh) - kshFormatted, _ := store.TruncateDecimalString(kshStr, 0) + maxKshFormatted, _ := store.TruncateDecimalString(kshStr, 0) res.Content = l.Get( - "Enter the amount of Mpesa to get: (Max %s Ksh)\n", - kshFormatted, + "Enter the amount of Mpesa to withdraw: (Min: Ksh %s, Max %s Ksh)\n", + minKshFormatted, + maxKshFormatted, ) return res, nil @@ -189,7 +211,7 @@ func (h *MenuHandlers) GetMpesaPreview(ctx context.Context, sym string, input [] // INPUT IN RAT Ksh inputStr := string(input) - if inputStr == "9" { + if inputStr == "0" || inputStr == "9" { return res, nil } @@ -219,16 +241,18 @@ func (h *MenuHandlers) GetMpesaPreview(ctx context.Context, sym string, input [] return res, nil } + min := config.MinMpesaWithdrawAmount() + + if kshAmount < min { + // if the input is below the minimum + res.FlagSet = append(res.FlagSet, flag_invalid_amount) + res.Content = inputStr + return res, nil + } + // divide by the buy rate inputAmount := kshAmount / rates.Buy - // store the user's raw input amount in the temporary value - err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(inputStr)) - if err != nil { - logg.ErrorCtxf(ctx, "failed to write temporary inputStr entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", inputStr, "error", err) - return res, err - } - swapData, err := store.ReadSwapPreviewData(ctx, userStore, sessionId) if err != nil { return res, err @@ -239,19 +263,21 @@ func (h *MenuHandlers) GetMpesaPreview(ctx context.Context, sym string, input [] return res, err } - if string(transactionType) == "normal" { - activeBal, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_BAL) - if err != nil { - logg.ErrorCtxf(ctx, "failed to read activeBal entry with", "key", storedb.DATA_ACTIVE_BAL, "error", err) - return res, err - } - balanceValue, err := strconv.ParseFloat(string(activeBal), 64) - if err != nil { - logg.ErrorCtxf(ctx, "Failed to convert the activeBal to a float", "error", err) - return res, err - } + // get the selected voucher + mpesaWithdrawalVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + return res, err + } - if inputAmount > balanceValue { + maxValue, err := strconv.ParseFloat(mpesaWithdrawalVoucher.Balance, 64) + if err != nil { + logg.ErrorCtxf(ctx, "Failed to convert the swapMaxAmount to a float", "error", err) + return res, err + } + + if string(transactionType) == "normal" { + if inputAmount > maxValue { res.FlagSet = append(res.FlagSet, flag_invalid_amount) res.Content = inputStr return res, nil @@ -270,7 +296,7 @@ func (h *MenuHandlers) GetMpesaPreview(ctx context.Context, sym string, input [] res.Content = l.Get( "You are sending %s %s in order to receive ~ %s ksh", - qouteInputAmount, swapData.ActiveSwapFromSym, inputStr, + qouteInputAmount, mpesaWithdrawalVoucher.TokenSymbol, inputStr, ) return res, nil @@ -365,6 +391,12 @@ func (h *MenuHandlers) InitiateGetMpesa(ctx context.Context, sym string, input [ return res, err } + mpesaWithdrawalVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + return res, err + } + if string(transactionType) == "normal" { // Call TokenTransfer for the normal transaction data, err := store.ReadTransactionData(ctx, h.userdataStore, sessionId) @@ -372,12 +404,12 @@ func (h *MenuHandlers) InitiateGetMpesa(ctx context.Context, sym string, input [ return res, err } - finalAmountStr, err := store.ParseAndScaleAmount(data.Amount, data.ActiveDecimal) + finalAmountStr, err := store.ParseAndScaleAmount(data.Amount, mpesaWithdrawalVoucher.TokenDecimals) if err != nil { return res, err } - tokenTransfer, err := h.accountService.TokenTransfer(ctx, finalAmountStr, data.PublicKey, mpesaAddress, data.ActiveAddress) + tokenTransfer, err := h.accountService.TokenTransfer(ctx, finalAmountStr, data.PublicKey, mpesaAddress, mpesaWithdrawalVoucher.TokenAddress) if err != nil { res.FlagSet = append(res.FlagSet, flag_api_call_error) res.Content = l.Get("Your request failed. Please try again later.") @@ -416,11 +448,6 @@ func (h *MenuHandlers) InitiateGetMpesa(ctx context.Context, sym string, input [ // TODO: remove this temporary time delay and replace with a swap and send endpoint time.Sleep(1 * time.Second) - finalKshStr, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) - if err != nil { - return res, err - } - amount, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_AMOUNT) if err != nil { return res, err @@ -437,7 +464,7 @@ func (h *MenuHandlers) InitiateGetMpesa(ctx context.Context, sym string, input [ logg.InfoCtxf(ctx, "final TokenTransfer after swap", "trackingId", tokenTransfer.TrackingId) - res.Content = l.Get("Your request has been sent. You will receive ~ %s ksh", finalKshStr) + res.Content = l.Get("Your request has been sent. Please await confirmation") res.FlagReset = append(res.FlagReset, flag_account_authorized) return res, nil } diff --git a/services/registration/get_mpesa b/services/registration/get_mpesa index 3ba5d3c..90039ed 100644 --- a/services/registration/get_mpesa +++ b/services/registration/get_mpesa @@ -1 +1 @@ -{{.get_mpesa_max_limit}} \ No newline at end of file +{{.get_ordered_vouchers}} \ No newline at end of file diff --git a/services/registration/get_mpesa.vis b/services/registration/get_mpesa.vis index bf536d3..f9a9b42 100644 --- a/services/registration/get_mpesa.vis +++ b/services/registration/get_mpesa.vis @@ -1,10 +1,15 @@ CATCH no_voucher flag_no_active_voucher 1 +LOAD get_ordered_vouchers 0 +MAP get_ordered_vouchers +MOUT back 0 +MOUT quit 99 +MNEXT next 88 +MPREV prev 98 +HALT +INCMP > 88 +INCMP < 98 +INCMP _ 0 +INCMP quit 99 LOAD get_mpesa_max_limit 0 RELOAD get_mpesa_max_limit -MAP get_mpesa_max_limit -MOUT back 0 -MOUT quit 9 -HALT -INCMP _ 0 -INCMP quit 9 -INCMP get_mpesa_confirmation * +INCMP mpesa_max_limit * diff --git a/services/registration/get_mpesa_confirmation.vis b/services/registration/get_mpesa_confirmation.vis index eccee90..5514765 100644 --- a/services/registration/get_mpesa_confirmation.vis +++ b/services/registration/get_mpesa_confirmation.vis @@ -1,7 +1,4 @@ -LOAD get_mpesa_preview 0 MAP get_mpesa_preview -CATCH api_failure flag_api_call_error 1 -CATCH invalid_credit_send_amount flag_invalid_amount 1 MOUT back 0 MOUT quit 9 HALT diff --git a/services/registration/invalid_get_mpesa_amount b/services/registration/invalid_get_mpesa_amount new file mode 100644 index 0000000..7f5fd35 --- /dev/null +++ b/services/registration/invalid_get_mpesa_amount @@ -0,0 +1 @@ +Amount {{.get_mpesa_preview}} is invalid, please try again: \ No newline at end of file diff --git a/services/registration/invalid_get_mpesa_amount.vis b/services/registration/invalid_get_mpesa_amount.vis new file mode 100644 index 0000000..3cba646 --- /dev/null +++ b/services/registration/invalid_get_mpesa_amount.vis @@ -0,0 +1,7 @@ +MAP get_mpesa_preview +RELOAD reset_transaction_amount +MOUT retry 1 +MOUT quit 9 +HALT +INCMP _ 1 +INCMP quit 9 diff --git a/services/registration/invalid_get_mpesa_amount_swa b/services/registration/invalid_get_mpesa_amount_swa new file mode 100644 index 0000000..27afab9 --- /dev/null +++ b/services/registration/invalid_get_mpesa_amount_swa @@ -0,0 +1 @@ +Kiwango {{.get_mpesa_preview}} sio sahihi, tafadhali weka tena: \ No newline at end of file diff --git a/services/registration/mpesa_max_limit b/services/registration/mpesa_max_limit new file mode 100644 index 0000000..3ba5d3c --- /dev/null +++ b/services/registration/mpesa_max_limit @@ -0,0 +1 @@ +{{.get_mpesa_max_limit}} \ No newline at end of file diff --git a/services/registration/mpesa_max_limit.vis b/services/registration/mpesa_max_limit.vis new file mode 100644 index 0000000..d3573ca --- /dev/null +++ b/services/registration/mpesa_max_limit.vis @@ -0,0 +1,13 @@ +LOAD reset_transaction_amount 10 +RELOAD reset_transaction_amount +MAP get_mpesa_max_limit +MOUT back 0 +MOUT quit 9 +HALT +INCMP _ 0 +INCMP quit 9 +LOAD get_mpesa_preview 90 +RELOAD get_mpesa_preview +CATCH api_failure flag_api_call_error 1 +CATCH invalid_get_mpesa_amount flag_invalid_amount 1 +INCMP get_mpesa_confirmation * From 504fcb67d3898d56c56f91bd9bfdf6b061b99114 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 12 Feb 2026 16:24:12 +0300 Subject: [PATCH 064/130] renamed the mpesa menu nodes for clarity --- services/registration/get_mpesa_menu | 2 +- services/registration/send_mpesa_menu | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/registration/get_mpesa_menu b/services/registration/get_mpesa_menu index 47e090b..45a2fd0 100644 --- a/services/registration/get_mpesa_menu +++ b/services/registration/get_mpesa_menu @@ -1 +1 @@ -Get M-Pesa \ No newline at end of file +Withdraw \ No newline at end of file diff --git a/services/registration/send_mpesa_menu b/services/registration/send_mpesa_menu index d39ed20..2327a63 100644 --- a/services/registration/send_mpesa_menu +++ b/services/registration/send_mpesa_menu @@ -1 +1 @@ -Send M-Pesa \ No newline at end of file +Top-up \ No newline at end of file From 80ea357e9c5187058b4bfeccdad65bba55bf872d Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 12 Feb 2026 19:19:52 +0300 Subject: [PATCH 065/130] added a new line for clear separation between voucher list and menu inputs --- services/registration/get_mpesa | 2 +- services/registration/select_voucher | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/registration/get_mpesa b/services/registration/get_mpesa index 90039ed..0863a44 100644 --- a/services/registration/get_mpesa +++ b/services/registration/get_mpesa @@ -1 +1 @@ -{{.get_ordered_vouchers}} \ No newline at end of file +{{.get_ordered_vouchers}} diff --git a/services/registration/select_voucher b/services/registration/select_voucher index ed8140f..3e1fc9d 100644 --- a/services/registration/select_voucher +++ b/services/registration/select_voucher @@ -1 +1 @@ -{{.get_vouchers}} \ No newline at end of file +{{.get_vouchers}} From 8b6f8b9a43558bc4243d6256d68b996fc816a5b3 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Thu, 12 Feb 2026 19:22:38 +0300 Subject: [PATCH 066/130] process all voucher lists as ordered, with stables at the top --- handlers/application/vouchers.go | 74 +++++++++++++++++++------------- 1 file changed, 43 insertions(+), 31 deletions(-) diff --git a/handlers/application/vouchers.go b/handlers/application/vouchers.go index 3899de6..2ff04df 100644 --- a/handlers/application/vouchers.go +++ b/handlers/application/vouchers.go @@ -148,7 +148,36 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b } } - // Filter out the active voucher from vouchersResp + // 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(vouchersResp)) for _, v := range vouchersResp { if v.TokenSymbol != activeSymStr { @@ -156,8 +185,11 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b } } - // Store all voucher data (excluding the current active voucher) - data := store.ProcessVouchers(filteredVouchers) + // Order remaining vouchers + orderedFilteredVouchers := orderVouchers(filteredVouchers) + + // Process & store + data := store.ProcessVouchers(orderedFilteredVouchers) dataMap := map[storedb.DataTyp]string{ storedb.DATA_VOUCHER_SYMBOLS: data.Symbols, @@ -170,47 +202,27 @@ 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 } } - // Get stable voucher priority order (lower index = higher priority) - stablePriority := make(map[string]int) - stableAddresses := config.StableVoucherAddresses() + // Order all vouchers + orderedVouchers := orderVouchers(vouchersResp) - 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 { + // Stable voucher presence flag (based on full list) + hasStable := false + for _, v := range orderedVouchers { if isStableVoucher(v.TokenAddress) { - stableVouchers = append(stableVouchers, v) - } else { - nonStableVouchers = append(nonStableVouchers, v) + hasStable = true + break } } - // No stable vouchers at all - if len(stableVouchers) == 0 { + if !hasStable { 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) From ba2c06c00ad390a1f4baf7675b24937201fa82c6 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 13 Feb 2026 03:54:09 +0300 Subject: [PATCH 067/130] process and store the vouchers as an ordered list --- handlers/application/balance.go | 111 +++++++++++++++++--------------- 1 file changed, 58 insertions(+), 53 deletions(-) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index ad9a2aa..0803f05 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -3,10 +3,13 @@ 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" @@ -119,14 +122,13 @@ 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 - _, _, activeSym, _, publicKey, _, err := h.getSessionData(ctx, sessionId) + _, activeBal, activeSym, _, publicKey, _, err := h.getSessionData(ctx, sessionId) if err != nil { return res, nil } @@ -148,51 +150,69 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i return res, nil } - // Filter stable vouchers (excluding active voucher) - filteredSwappableVouchers := make([]dataserviceapi.TokenHoldings, 0) + // 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)) for _, v := range swappableVouchers { - if v.TokenSymbol == string(activeSym) { + 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) 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 := store.ScaleDownBalance( - activeData.Balance, - activeData.TokenDecimals, - ) + scaledCredit := string(activeBal) // Debt = sum of stable vouchers only scaledDebt := "0" - for _, v := range filteredSwappableVouchers { + for _, v := range orderedFilteredVouchers { scaled := store.ScaleDownBalance(v.Balance, v.TokenDecimals) scaledDebt = store.AddDecimalStrings(scaledDebt, scaled) } @@ -215,21 +235,6 @@ 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, From c02aa99ed07202bfb260a50faeb8a062cd9f46b2 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 13 Feb 2026 03:56:24 +0300 Subject: [PATCH 068/130] store the active swap from voucher data --- store/swap.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/store/swap.go b/store/swap.go index 097ad4a..3359a6f 100644 --- a/store/swap.go +++ b/store/swap.go @@ -189,3 +189,24 @@ 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 +} \ No newline at end of file From 5255671a3da1948d57c251d88a5282d38de22dcd Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 13 Feb 2026 03:56:55 +0300 Subject: [PATCH 069/130] added the data key for the swap from balance --- store/db/db.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/store/db/db.go b/store/db/db.go index e228971..67850b9 100644 --- a/store/db/db.go +++ b/store/db/db.go @@ -93,6 +93,8 @@ 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 ( From 5c1b4ab00206e72957ce066e4ec56267cf4e8d68 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 13 Feb 2026 03:58:11 +0300 Subject: [PATCH 070/130] refactored the CalculateMaxPayDebt to improve logic and correctness --- handlers/application/paydebt.go | 68 +++++++++++++++++++++------------ 1 file changed, 43 insertions(+), 25 deletions(-) diff --git a/handlers/application/paydebt.go b/handlers/application/paydebt.go index faf6a04..087825a 100644 --- a/handlers/application/paydebt.go +++ b/handlers/application/paydebt.go @@ -13,7 +13,7 @@ import ( "gopkg.in/leonelquinteros/gotext.v1" ) -// CalculateMaxPayDebt calculates the max debt removal +// CalculateMaxPayDebt calculates the max debt removal based on the selected voucher 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,21 +29,28 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu l.AddDomain("default") inputStr := string(input) - if inputStr == "0" || inputStr == "9" { + if inputStr == "0" || inputStr == "99" || inputStr == "88" || inputStr == "98" { 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 - _, activePoolName, err := h.resolveActivePoolDetails(ctx, sessionId) + activePoolAddress, 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 } - metadata, err := store.GetSwapToVoucherData(ctx, userStore, sessionId, "1") + // get the voucher data based on the input + metadata, err := store.GetVoucherData(ctx, userStore, sessionId, inputStr) 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) @@ -53,35 +60,26 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu return res, nil } - logg.InfoCtxf(ctx, "Metadata from GetSwapToVoucherData:", "metadata", metadata) + logg.InfoCtxf(ctx, "Metadata from GetVoucherData:", "metadata", metadata) - // Store the active swap_to data - if err := store.UpdateSwapToVoucherData(ctx, userStore, sessionId, metadata); err != nil { - logg.ErrorCtxf(ctx, "failed on UpdateSwapToVoucherData", "error", err) + // Store the active swap from data + if err := store.UpdateSwapFromVoucherData(ctx, userStore, sessionId, metadata); err != nil { + logg.ErrorCtxf(ctx, "failed on UpdateSwapFromVoucherData", "error", err) return res, err } - 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) + // Get the max swap limit with the selected voucher + r, err := h.accountService.GetSwapFromTokenMaxLimit(ctx, string(activePoolAddress), metadata.TokenAddress, string(activeAddress), string(publicKey)) if err != nil { res.FlagSet = append(res.FlagSet, flag_api_call_error) logg.ErrorCtxf(ctx, "failed on GetSwapFromTokenMaxLimit", "error", err) return res, nil } - 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 - } + maxLimit := r.Max // Scale down the amount - maxAmountStr := store.ScaleDownBalance(r.Max, swapData.ActiveSwapToDecimal) + maxAmountStr := store.ScaleDownBalance(maxLimit, metadata.TokenDecimals) if err != nil { return res, err } @@ -108,12 +106,32 @@ 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 maximum of %s %s from '%s'\n\nEnter amount of %s:", - maxStr, - swapData.ActiveSwapToSym, + "You can remove a max of %s %s from '%s'\nEnter amount of %s:(Max: %s)", + quoteStr, + string(activeSym), string(activePoolName), - swapData.ActiveSwapToSym, + metadata.TokenSymbol, + maxStr, ) res.FlagReset = append(res.FlagReset, flag_low_swap_amount, flag_api_call_error) From 47a14555fb28675f61b75adda4421ffaa19d735d Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 13 Feb 2026 14:50:39 +0300 Subject: [PATCH 071/130] reordered vis statements to match updated menu flow --- services/registration/calculate_max_pay_debt | 1 + .../registration/calculate_max_pay_debt.vis | 10 ++++++++++ .../registration/confirm_debt_removal.vis | 3 --- services/registration/invalid_pay_debt_amount | 1 + .../registration/invalid_pay_debt_amount.vis | 7 +++++++ .../registration/invalid_pay_debt_amount_swa | 1 + services/registration/pay_debt | 2 +- services/registration/pay_debt.vis | 20 ++++++++++++------- 8 files changed, 34 insertions(+), 11 deletions(-) create mode 100644 services/registration/calculate_max_pay_debt create mode 100644 services/registration/calculate_max_pay_debt.vis create mode 100644 services/registration/invalid_pay_debt_amount create mode 100644 services/registration/invalid_pay_debt_amount.vis create mode 100644 services/registration/invalid_pay_debt_amount_swa diff --git a/services/registration/calculate_max_pay_debt b/services/registration/calculate_max_pay_debt new file mode 100644 index 0000000..1e2b322 --- /dev/null +++ b/services/registration/calculate_max_pay_debt @@ -0,0 +1 @@ +{{.calculate_max_pay_debt}} \ No newline at end of file diff --git a/services/registration/calculate_max_pay_debt.vis b/services/registration/calculate_max_pay_debt.vis new file mode 100644 index 0000000..c9e9774 --- /dev/null +++ b/services/registration/calculate_max_pay_debt.vis @@ -0,0 +1,10 @@ +LOAD reset_transaction_amount 10 +RELOAD reset_transaction_amount +MAP calculate_max_pay_debt +MOUT back 0 +HALT +LOAD confirm_debt_removal 140 +RELOAD confirm_debt_removal +CATCH invalid_pay_debt_amount flag_invalid_amount 1 +INCMP _ 0 +INCMP confirm_debt_removal * diff --git a/services/registration/confirm_debt_removal.vis b/services/registration/confirm_debt_removal.vis index e5c79c8..15d9bbe 100644 --- a/services/registration/confirm_debt_removal.vis +++ b/services/registration/confirm_debt_removal.vis @@ -1,7 +1,4 @@ -LOAD confirm_debt_removal 0 MAP confirm_debt_removal -CATCH api_failure flag_api_call_error 1 -CATCH invalid_credit_send_amount flag_invalid_amount 1 MOUT back 0 MOUT quit 9 HALT diff --git a/services/registration/invalid_pay_debt_amount b/services/registration/invalid_pay_debt_amount new file mode 100644 index 0000000..635ece1 --- /dev/null +++ b/services/registration/invalid_pay_debt_amount @@ -0,0 +1 @@ +Amount {{.confirm_debt_removal}} is invalid, please try again: \ No newline at end of file diff --git a/services/registration/invalid_pay_debt_amount.vis b/services/registration/invalid_pay_debt_amount.vis new file mode 100644 index 0000000..34713e6 --- /dev/null +++ b/services/registration/invalid_pay_debt_amount.vis @@ -0,0 +1,7 @@ +MAP confirm_debt_removal +RELOAD reset_transaction_amount +MOUT retry 1 +MOUT quit 9 +HALT +INCMP _ 1 +INCMP quit 9 diff --git a/services/registration/invalid_pay_debt_amount_swa b/services/registration/invalid_pay_debt_amount_swa new file mode 100644 index 0000000..c98b686 --- /dev/null +++ b/services/registration/invalid_pay_debt_amount_swa @@ -0,0 +1 @@ +Kiwango {{.confirm_debt_removal}} sio sahihi, tafadhali weka tena: \ No newline at end of file diff --git a/services/registration/pay_debt b/services/registration/pay_debt index 1e2b322..3e1fc9d 100644 --- a/services/registration/pay_debt +++ b/services/registration/pay_debt @@ -1 +1 @@ -{{.calculate_max_pay_debt}} \ No newline at end of file +{{.get_vouchers}} diff --git a/services/registration/pay_debt.vis b/services/registration/pay_debt.vis index 7cd5592..9cf8b87 100644 --- a/services/registration/pay_debt.vis +++ b/services/registration/pay_debt.vis @@ -1,10 +1,16 @@ CATCH no_voucher flag_no_active_voucher 1 -CATCH no_stable_voucher flag_no_stable_vouchers 1 +LOAD get_vouchers 0 +MAP get_vouchers +MOUT back 0 +MOUT quit 99 +MNEXT next 88 +MPREV prev 98 +HALT +INCMP > 88 +INCMP < 98 +INCMP _ 0 +INCMP quit 99 LOAD calculate_max_pay_debt 0 RELOAD calculate_max_pay_debt -MAP calculate_max_pay_debt -CATCH low_pay_debt_amount flag_low_swap_amount 1 -MOUT back 0 -HALT -INCMP _ 0 -INCMP confirm_debt_removal * +CATCH . flag_incorrect_voucher 1 +INCMP calculate_max_pay_debt * From 8f66a46e76b761fb0e1a9a3b4f24b9c47c5da598 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 13 Feb 2026 16:04:00 +0300 Subject: [PATCH 072/130] added a function to ReadSwapFromVoucher --- store/swap.go | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/store/swap.go b/store/swap.go index 3359a6f..9b51b98 100644 --- a/store/swap.go +++ b/store/swap.go @@ -209,4 +209,30 @@ func UpdateSwapFromVoucherData(ctx context.Context, store DataStore, sessionId s } return nil -} \ No newline at end of file +} + +// ReadSwapFromVoucher retrieves the voucher being swapped into the pool (swap from) +func ReadSwapFromVoucher(ctx context.Context, store DataStore, sessionId string) (*dataserviceapi.TokenHoldings, error) { + keys := []storedb.DataTyp{ + storedb.DATA_ACTIVE_SWAP_FROM_SYM, + storedb.DATA_ACTIVE_SWAP_FROM_DECIMAL, + storedb.DATA_ACTIVE_SWAP_FROM_ADDRESS, + storedb.DATA_ACTIVE_SWAP_FROM_BALANCE, + } + data := make(map[storedb.DataTyp]string) + + for _, key := range keys { + value, err := store.ReadEntry(ctx, sessionId, key) + if err != nil { + return nil, fmt.Errorf("failed to get data key %x: %v", key, err) + } + data[key] = string(value) + } + + return &dataserviceapi.TokenHoldings{ + TokenSymbol: data[storedb.DATA_ACTIVE_SWAP_FROM_SYM], + Balance: data[storedb.DATA_ACTIVE_SWAP_FROM_BALANCE], + TokenDecimals: data[storedb.DATA_ACTIVE_SWAP_FROM_DECIMAL], + TokenAddress: data[storedb.DATA_ACTIVE_SWAP_FROM_ADDRESS], + }, nil +} From 2e81ae58bcfd52d16a0fc3d4ac3c997fe9264765 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 13 Feb 2026 16:07:46 +0300 Subject: [PATCH 073/130] refactored the code for proper debt removal confirmation --- handlers/application/paydebt.go | 48 ++++++++++++++++++--------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/handlers/application/paydebt.go b/handlers/application/paydebt.go index 087825a..c6bb7c0 100644 --- a/handlers/application/paydebt.go +++ b/handlers/application/paydebt.go @@ -60,14 +60,6 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu return res, nil } - logg.InfoCtxf(ctx, "Metadata from GetVoucherData:", "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) - 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)) if err != nil { @@ -77,6 +69,14 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu } maxLimit := r.Max + + metadata.Balance = maxLimit + + // Store the active swap from data + if err := store.UpdateSwapFromVoucherData(ctx, userStore, sessionId, metadata); err != nil { + logg.ErrorCtxf(ctx, "failed on UpdateSwapFromVoucherData", "error", err) + return res, err + } // Scale down the amount maxAmountStr := store.ScaleDownBalance(maxLimit, metadata.TokenDecimals) @@ -160,6 +160,18 @@ func (h *MenuHandlers) ConfirmDebtRemoval(ctx context.Context, sym string, input userStore := h.userdataStore + // Fetch session data + _, _, activeSym, activeAddress, publicKey, _, err := h.getSessionData(ctx, sessionId) + if err != nil { + return res, nil + } + + payDebtVoucher, err := store.ReadSwapFromVoucher(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on ReadSwapFromVoucher", "error", err) + return res, err + } + swapData, err := store.ReadSwapPreviewData(ctx, userStore, sessionId) if err != nil { return res, err @@ -172,19 +184,17 @@ func (h *MenuHandlers) ConfirmDebtRemoval(ctx context.Context, sym string, input } inputAmount, err := strconv.ParseFloat(inputStr, 64) - if err != nil || inputAmount > maxValue { + if err != nil || inputAmount > maxValue || inputAmount < 0.1 { res.FlagSet = append(res.FlagSet, flag_invalid_amount) res.Content = inputStr return res, nil } - storedMax, _ := userStore.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) - var finalAmountStr string if inputStr == swapData.ActiveSwapMaxAmount { - finalAmountStr = string(storedMax) + finalAmountStr = string(payDebtVoucher.Balance) } else { - finalAmountStr, err = store.ParseAndScaleAmount(inputStr, swapData.ActiveSwapToDecimal) + finalAmountStr, err = store.ParseAndScaleAmount(inputStr, payDebtVoucher.TokenDecimals) if err != nil { return res, err } @@ -195,15 +205,9 @@ func (h *MenuHandlers) ConfirmDebtRemoval(ctx context.Context, sym string, input logg.ErrorCtxf(ctx, "failed to write swap amount entry with", "key", storedb.DATA_ACTIVE_SWAP_AMOUNT, "value", finalAmountStr, "error", err) return res, err } - // store the user's input amount in the temporary value - err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(inputStr)) - if err != nil { - logg.ErrorCtxf(ctx, "failed to write inputStr amount entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", inputStr, "error", err) - return res, err - } - + // call the API to get the quote - r, err := h.accountService.GetPoolSwapQuote(ctx, finalAmountStr, swapData.PublicKey, swapData.ActiveSwapToAddress, swapData.ActivePoolAddress, swapData.ActiveSwapFromAddress) + r, err := h.accountService.GetPoolSwapQuote(ctx, finalAmountStr, string(publicKey), payDebtVoucher.TokenAddress, swapData.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) @@ -220,7 +224,7 @@ func (h *MenuHandlers) ConfirmDebtRemoval(ctx context.Context, sym string, input res.Content = l.Get( "Please confirm that you will use %s %s to remove your debt of %s %s\n", - inputStr, swapData.ActiveSwapToSym, qouteStr, swapData.ActiveSwapFromSym, + inputStr, payDebtVoucher.TokenSymbol, qouteStr, string(activeSym), ) return res, nil From 43b963995f18baf8181d74875af52c16784cd93d Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Fri, 13 Feb 2026 16:36:20 +0300 Subject: [PATCH 074/130] refactored the code to send the correct pool deposit request --- handlers/application/paydebt.go | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/handlers/application/paydebt.go b/handlers/application/paydebt.go index c6bb7c0..a836054 100644 --- a/handlers/application/paydebt.go +++ b/handlers/application/paydebt.go @@ -69,9 +69,9 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu } maxLimit := r.Max - + metadata.Balance = maxLimit - + // Store the active swap from data if err := store.UpdateSwapFromVoucherData(ctx, userStore, sessionId, metadata); err != nil { logg.ErrorCtxf(ctx, "failed on UpdateSwapFromVoucherData", "error", err) @@ -205,7 +205,7 @@ func (h *MenuHandlers) ConfirmDebtRemoval(ctx context.Context, sym string, input logg.ErrorCtxf(ctx, "failed to write swap amount entry with", "key", storedb.DATA_ACTIVE_SWAP_AMOUNT, "value", finalAmountStr, "error", err) return res, err } - + // call the API to get the quote r, err := h.accountService.GetPoolSwapQuote(ctx, finalAmountStr, string(publicKey), payDebtVoucher.TokenAddress, swapData.ActivePoolAddress, string(activeAddress)) if err != nil { @@ -222,6 +222,13 @@ func (h *MenuHandlers) ConfirmDebtRemoval(ctx context.Context, sym string, input // Format to 2 decimal places qouteStr, _ := store.TruncateDecimalString(string(quoteAmountStr), 2) + // store the quote in the temporary value key + err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(qouteStr)) + if err != nil { + logg.ErrorCtxf(ctx, "failed to write swap max amount entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", qouteStr, "error", err) + return res, err + } + res.Content = l.Get( "Please confirm that you will use %s %s to remove your debt of %s %s\n", inputStr, payDebtVoucher.TokenSymbol, qouteStr, string(activeSym), @@ -247,9 +254,21 @@ func (h *MenuHandlers) InitiatePayDebt(ctx context.Context, sym string, input [] userStore := h.userdataStore - // Resolve active pool - _, activePoolName, err := h.resolveActivePoolDetails(ctx, sessionId) + // Fetch session data + _, _, activeSym, activeAddress, publicKey, _, err := h.getSessionData(ctx, sessionId) if err != nil { + return res, nil + } + + // Resolve active pool + activePoolAddress, activePoolName, err := h.resolveActivePoolDetails(ctx, sessionId) + if err != nil { + return res, err + } + + payDebtVoucher, err := store.ReadSwapFromVoucher(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on ReadSwapFromVoucher", "error", err) return res, err } @@ -267,7 +286,7 @@ func (h *MenuHandlers) InitiatePayDebt(ctx context.Context, sym string, input [] swapAmountStr := string(swapAmount) // Call the poolSwap API - r, err := h.accountService.PoolSwap(ctx, swapAmountStr, swapData.PublicKey, swapData.ActiveSwapToAddress, swapData.ActivePoolAddress, swapData.ActiveSwapFromAddress) + r, err := h.accountService.PoolSwap(ctx, swapAmountStr, string(publicKey), payDebtVoucher.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) @@ -282,7 +301,7 @@ func (h *MenuHandlers) InitiatePayDebt(ctx context.Context, sym string, input [] res.Content = l.Get( "Your request has been sent. You will receive an SMS when your debt of %s %s has been removed from %s.", swapData.TemporaryValue, - swapData.ActiveSwapToSym, + string(activeSym), activePoolName, ) From f6ecbcc79d2c4e03bbee5571a3469613ebf2708d Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Mon, 16 Feb 2026 09:06:53 +0300 Subject: [PATCH 075/130] remove lowercase conversion of voucher addresses --- config/config.go | 5 ++--- handlers/application/paydebt.go | 2 +- handlers/application/vouchers.go | 6 +++--- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/config/config.go b/config/config.go index ec3821a..697bc15 100644 --- a/config/config.go +++ b/config/config.go @@ -111,7 +111,6 @@ func MinMpesaWithdrawAmount() float64 { return f } - func MaxMpesaSendAmount() float64 { v := env.GetEnv("MAX_MPESA_SEND_AMOUNT", "250000") f, err := strconv.ParseFloat(v, 64) @@ -135,11 +134,11 @@ func StableVoucherAddresses() []string { list := strings.Split(raw, ",") for _, addr := range list { - clean := strings.ToLower(strings.TrimSpace(addr)) + clean := strings.TrimSpace(addr) if clean != "" { parsed = append(parsed, clean) } } return parsed -} \ No newline at end of file +} diff --git a/handlers/application/paydebt.go b/handlers/application/paydebt.go index a836054..8b17a9f 100644 --- a/handlers/application/paydebt.go +++ b/handlers/application/paydebt.go @@ -310,7 +310,7 @@ func (h *MenuHandlers) InitiatePayDebt(ctx context.Context, sym string, input [] } func isStableVoucher(tokenAddress string) bool { - addr := strings.ToLower(strings.TrimSpace(tokenAddress)) + addr := strings.TrimSpace(tokenAddress) for _, stable := range config.StableVoucherAddresses() { if addr == stable { return true diff --git a/handlers/application/vouchers.go b/handlers/application/vouchers.go index 2ff04df..cad629b 100644 --- a/handlers/application/vouchers.go +++ b/handlers/application/vouchers.go @@ -152,7 +152,7 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b stablePriority := make(map[string]int) stableAddresses := config.StableVoucherAddresses() for i, addr := range stableAddresses { - stablePriority[strings.ToLower(addr)] = i + stablePriority[addr] = i } // Helper: order vouchers (stable first, priority-based) @@ -169,8 +169,8 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b } sort.SliceStable(stable, func(i, j int) bool { - ai := stablePriority[strings.ToLower(stable[i].TokenAddress)] - aj := stablePriority[strings.ToLower(stable[j].TokenAddress)] + ai := stablePriority[stable[i].TokenAddress] + aj := stablePriority[stable[j].TokenAddress] return ai < aj }) From c2cfd0fe449353521d0e9a2b550c67dac3187cf7 Mon Sep 17 00:00:00 2001 From: Alfred Kamanda Date: Mon, 16 Feb 2026 09:08:13 +0300 Subject: [PATCH 076/130] updated the credit and debt calculations --- handlers/application/balance.go | 55 ++++++++++++++++++++++++--------- 1 file changed, 40 insertions(+), 15 deletions(-) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index 0803f05..6403d64 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -5,7 +5,6 @@ import ( "fmt" "sort" "strconv" - "strings" "git.defalsify.org/vise.git/db" "git.defalsify.org/vise.git/resource" @@ -128,7 +127,7 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i res.Content = l.Get("Credit: %s KSH\nDebt: %s KSH\n", "0", "0") // Fetch session data - _, activeBal, activeSym, _, publicKey, _, err := h.getSessionData(ctx, sessionId) + _, activeBal, activeSym, activeAddress, publicKey, activeDecimal, err := h.getSessionData(ctx, sessionId) if err != nil { return res, nil } @@ -154,14 +153,14 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i stablePriority := make(map[string]int) stableAddresses := config.StableVoucherAddresses() for i, addr := range stableAddresses { - stablePriority[strings.ToLower(addr)] = i + stablePriority[addr] = i } + stable := make([]dataserviceapi.TokenHoldings, 0) + nonStable := make([]dataserviceapi.TokenHoldings, 0) + // 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) @@ -171,8 +170,8 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i } sort.SliceStable(stable, func(i, j int) bool { - ai := stablePriority[strings.ToLower(stable[i].TokenAddress)] - aj := stablePriority[strings.ToLower(stable[j].TokenAddress)] + ai := stablePriority[stable[i].TokenAddress] + aj := stablePriority[stable[j].TokenAddress] return ai < aj }) @@ -207,15 +206,41 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i } } - // Credit = active voucher balance - scaledCredit := string(activeBal) + // Credit calculation: How much Active Token (such as ALF) that can be swapped for a stable coin + // + any stables sendable to Pretium (in KSH value) + scaledCredit := "0" - // Debt = sum of stable vouchers only - scaledDebt := "0" - for _, v := range orderedFilteredVouchers { - scaled := store.ScaleDownBalance(v.Balance, v.TokenDecimals) - scaledDebt = store.AddDecimalStrings(scaledDebt, scaled) + finalAmountStr, err := store.ParseAndScaleAmount(string(activeBal), string(activeDecimal)) + if err != nil { + return res, err } + // do a swap quote to get the max I can get when I swap my active voucher + // for a stable coin (say I can get 4 USD). Then I add that to my exisitng + // stable coins and covert to Ksh + stableAddress := stableAddresses[0] + r, err := h.accountService.GetPoolSwapQuote(ctx, finalAmountStr, string(publicKey), string(activeAddress), string(activePoolAddress), stableAddress) + 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 + } + + finalQuote := store.ScaleDownBalance(r.OutValue, "6") + + scaledCredit = store.AddDecimalStrings(scaledCredit, finalQuote) + + for _, v := range stable { + scaled := store.ScaleDownBalance(v.Balance, v.TokenDecimals) + scaledCredit = store.AddDecimalStrings(scaledCredit, scaled) + } + + // DEBT calculation: All outstanding active token that is in the current pool + // (how much of AT that is in the active Pool) + scaledDebt := "0" + // convert the current balance to Ksh + scaledDebt = string(activeBal) // Fetch MPESA rates rates, err := h.accountService.GetMpesaOnrampRates(ctx) From aacea81397372e98079ea061e2cca5ea4accb728 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 16 Feb 2026 10:14:41 +0300 Subject: [PATCH 077/130] added the default stable voucher address and decimals --- .env.example | 6 ++++-- config/config.go | 8 ++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/.env.example b/.env.example index d4871ad..e6ff1ce 100644 --- a/.env.example +++ b/.env.example @@ -39,5 +39,7 @@ DEFAULT_MPESA_ASSET=cUSD MPESA_BEARER_TOKEN=eyJeSIsInRcCI6IkpXVCJ.yJwdWJsaWNLZXkiOiIwrrrrrr MPESA_ONRAMP_BASE=https://pretium.v1.grassecon.net -# Known stable voucher addresses (USDT, USDm) -STABLE_VOUCHER_ADDRESSES=0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e,0x765DE816845861e75A25fCA122bb6898B8B1282a +# Known stable voucher addresses (USDm, USD₮) +STABLE_VOUCHER_ADDRESSES=0x765DE816845861e75A25fCA122bb6898B8B1282a,0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e +DEFAULT_STABLE_VOUCHER_ADDRESS=0x765DE816845861e75A25fCA122bb6898B8B1282a +DEFAULT_STABLE_VOUCHER_DECIMALS=18 diff --git a/config/config.go b/config/config.go index 697bc15..aee9439 100644 --- a/config/config.go +++ b/config/config.go @@ -142,3 +142,11 @@ func StableVoucherAddresses() []string { return parsed } + +func DefaultStableVoucherAddress() string { + return env.GetEnv("DEFAULT_STABLE_VOUCHER_ADDRESS", "") +} + +func DefaultStableVoucherDecimals() string { + return env.GetEnv("DEFAULT_STABLE_VOUCHER_DECIMALS", "") +} From 465b3b5604889165e808c0dd80b00aaf93c02e28 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 16 Feb 2026 10:20:10 +0300 Subject: [PATCH 078/130] use the default stable decimals to scale down the quote --- handlers/application/balance.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index 6403d64..aa68b03 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -206,7 +206,7 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i } } - // Credit calculation: How much Active Token (such as ALF) that can be swapped for a stable coin + // Credit calculation: How much Active Token that can be swapped for a stable coin // + any stables sendable to Pretium (in KSH value) scaledCredit := "0" @@ -214,10 +214,10 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i if err != nil { return res, err } - // do a swap quote to get the max I can get when I swap my active voucher - // for a stable coin (say I can get 4 USD). Then I add that to my exisitng - // stable coins and covert to Ksh - stableAddress := stableAddresses[0] + // do a swap quote for default stable coin from active voucher + stableAddress := config.DefaultStableVoucherAddress() + stableDecimals := config.DefaultStableVoucherDecimals() + r, err := h.accountService.GetPoolSwapQuote(ctx, finalAmountStr, string(publicKey), string(activeAddress), string(activePoolAddress), stableAddress) if err != nil { flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error") @@ -227,7 +227,7 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i return res, nil } - finalQuote := store.ScaleDownBalance(r.OutValue, "6") + finalQuote := store.ScaleDownBalance(r.OutValue, stableDecimals) scaledCredit = store.AddDecimalStrings(scaledCredit, finalQuote) From 09954d967f6721c8a30ecb1c3c8d66d583063b97 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 16 Feb 2026 10:21:20 +0300 Subject: [PATCH 079/130] read the data entries directly from the store --- handlers/application/paydebt.go | 34 ++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/handlers/application/paydebt.go b/handlers/application/paydebt.go index 8b17a9f..8172b3d 100644 --- a/handlers/application/paydebt.go +++ b/handlers/application/paydebt.go @@ -161,7 +161,7 @@ func (h *MenuHandlers) ConfirmDebtRemoval(ctx context.Context, sym string, input userStore := h.userdataStore // Fetch session data - _, _, activeSym, activeAddress, publicKey, _, err := h.getSessionData(ctx, sessionId) + _, _, activeSym, activeAddress, publicKey, activeDecimal, err := h.getSessionData(ctx, sessionId) if err != nil { return res, nil } @@ -172,12 +172,19 @@ func (h *MenuHandlers) ConfirmDebtRemoval(ctx context.Context, sym string, input return res, err } - swapData, err := store.ReadSwapPreviewData(ctx, userStore, sessionId) + // Resolve active pool + activePoolAddress, _, err := h.resolveActivePoolDetails(ctx, sessionId) if err != nil { return res, err } - maxValue, err := strconv.ParseFloat(swapData.ActiveSwapMaxAmount, 64) + swapMaxAmount, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_SWAP_MAX_AMOUNT) + if err != nil { + logg.ErrorCtxf(ctx, "failed to read swapMaxAmount entry with", "key", storedb.DATA_ACTIVE_SWAP_MAX_AMOUNT, "error", err) + return res, err + } + + maxValue, err := strconv.ParseFloat(string(swapMaxAmount), 64) if err != nil { logg.ErrorCtxf(ctx, "Failed to convert the swapMaxAmount to a float", "error", err) return res, err @@ -191,7 +198,7 @@ func (h *MenuHandlers) ConfirmDebtRemoval(ctx context.Context, sym string, input } var finalAmountStr string - if inputStr == swapData.ActiveSwapMaxAmount { + if inputStr == string(swapMaxAmount) { finalAmountStr = string(payDebtVoucher.Balance) } else { finalAmountStr, err = store.ParseAndScaleAmount(inputStr, payDebtVoucher.TokenDecimals) @@ -207,7 +214,7 @@ func (h *MenuHandlers) ConfirmDebtRemoval(ctx context.Context, sym string, input } // call the API to get the quote - r, err := h.accountService.GetPoolSwapQuote(ctx, finalAmountStr, string(publicKey), payDebtVoucher.TokenAddress, swapData.ActivePoolAddress, string(activeAddress)) + r, err := h.accountService.GetPoolSwapQuote(ctx, finalAmountStr, string(publicKey), payDebtVoucher.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) @@ -216,8 +223,8 @@ func (h *MenuHandlers) ConfirmDebtRemoval(ctx context.Context, sym string, input return res, nil } - // Scale down the quoted amount - quoteAmountStr := store.ScaleDownBalance(r.OutValue, swapData.ActiveSwapFromDecimal) + // Scale down the quoted amount (for the AT) + quoteAmountStr := store.ScaleDownBalance(r.OutValue, string(activeDecimal)) // Format to 2 decimal places qouteStr, _ := store.TruncateDecimalString(string(quoteAmountStr), 2) @@ -272,17 +279,18 @@ func (h *MenuHandlers) InitiatePayDebt(ctx context.Context, sym string, input [] return res, err } - swapData, err := store.ReadSwapPreviewData(ctx, userStore, sessionId) - if err != nil { - return res, err - } - swapAmount, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_SWAP_AMOUNT) if err != nil { logg.ErrorCtxf(ctx, "failed to read swapAmount entry with", "key", storedb.DATA_ACTIVE_SWAP_AMOUNT, "error", err) return res, err } + debtQuotedAmount, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) + if err != nil { + logg.ErrorCtxf(ctx, "failed to read debtQuotedAmount entry with", "key", storedb.DATA_TEMPORARY_VALUE, "error", err) + return res, err + } + swapAmountStr := string(swapAmount) // Call the poolSwap API @@ -300,7 +308,7 @@ func (h *MenuHandlers) InitiatePayDebt(ctx context.Context, sym string, input [] res.Content = l.Get( "Your request has been sent. You will receive an SMS when your debt of %s %s has been removed from %s.", - swapData.TemporaryValue, + string(debtQuotedAmount), string(activeSym), activePoolName, ) From a78639799de46b9203ac30e7a8df2d3cd5cb42c7 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 16 Feb 2026 14:14:50 +0300 Subject: [PATCH 080/130] add a function for ReadSwapToVoucher --- store/swap.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/store/swap.go b/store/swap.go index 9b51b98..c604a6c 100644 --- a/store/swap.go +++ b/store/swap.go @@ -236,3 +236,27 @@ func ReadSwapFromVoucher(ctx context.Context, store DataStore, sessionId string) TokenAddress: data[storedb.DATA_ACTIVE_SWAP_FROM_ADDRESS], }, nil } + +// ReadSwapToVoucher retrieves the swap to voucher being swapped from the pool +func ReadSwapToVoucher(ctx context.Context, store DataStore, sessionId string) (*dataserviceapi.TokenHoldings, error) { + keys := []storedb.DataTyp{ + storedb.DATA_ACTIVE_SWAP_TO_SYM, + storedb.DATA_ACTIVE_SWAP_TO_DECIMAL, + storedb.DATA_ACTIVE_SWAP_TO_ADDRESS, + } + data := make(map[storedb.DataTyp]string) + + for _, key := range keys { + value, err := store.ReadEntry(ctx, sessionId, key) + if err != nil { + return nil, fmt.Errorf("failed to get data key %x: %v", key, err) + } + data[key] = string(value) + } + + return &dataserviceapi.TokenHoldings{ + TokenSymbol: data[storedb.DATA_ACTIVE_SWAP_TO_SYM], + TokenDecimals: data[storedb.DATA_ACTIVE_SWAP_TO_DECIMAL], + TokenAddress: data[storedb.DATA_ACTIVE_SWAP_TO_ADDRESS], + }, nil +} From fe534b118165ea78223eb72b6ea8488bc2dfe97b Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 16 Feb 2026 14:28:30 +0300 Subject: [PATCH 081/130] polished the withdraw mpesa flow to correctly work with the selected voucher --- handlers/application/mpesa.go | 85 ++++++++++++++++++++++++----------- 1 file changed, 59 insertions(+), 26 deletions(-) diff --git a/handlers/application/mpesa.go b/handlers/application/mpesa.go index 467adc8..41470ff 100644 --- a/handlers/application/mpesa.go +++ b/handlers/application/mpesa.go @@ -50,7 +50,7 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ return res, nil } - // Store the active transaction voucher data + // Store the active transaction voucher data (from token) if err := store.StoreTemporaryVoucher(ctx, h.userdataStore, sessionId, metadata); err != nil { logg.ErrorCtxf(ctx, "failed on StoreTemporaryVoucher", "error", err) return res, err @@ -93,7 +93,7 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ return res, err } - // fetch data for verification + // fetch data for verification (to_voucher data) recipientActiveSym, recipientActiveAddress, recipientActiveDecimal, err := h.getRecipientData(ctx, string(recipientPhoneNumber)) if err != nil { return res, err @@ -103,7 +103,7 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ minksh := fmt.Sprintf("%f", config.MinMpesaWithdrawAmount()) minKshFormatted, _ := store.TruncateDecimalString(minksh, 0) - // If RAT is the same as SAT, return early with KSH format + // If SAT is the same as RAT, return early with KSH format if string(metadata.TokenAddress) == string(recipientActiveAddress) { txType = "normal" // Save the transaction type @@ -132,7 +132,7 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ return res, err } - // Check if sender token is swappable + // Check if selected token is swappable canSwap, err := h.accountService.CheckTokenInPool(ctx, string(activePoolAddress), string(metadata.TokenAddress)) if err != nil { res.FlagSet = append(res.FlagSet, flag_api_call_error) @@ -140,7 +140,7 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ return res, nil } - if !canSwap.CanSwapFrom { // pool issue (TODO on vis) + if !canSwap.CanSwapFrom { // pool issue (CATCH on .vis) res.FlagSet = append(res.FlagSet, flag_incorrect_pool) return res, nil } @@ -175,7 +175,7 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ return res, err } - // save swap related data for the swap preview + // save swap related data for the swap preview (the swap to) swapMetadata := &dataserviceapi.TokenHoldings{ TokenAddress: string(recipientActiveAddress), TokenSymbol: string(recipientActiveSym), @@ -253,7 +253,8 @@ func (h *MenuHandlers) GetMpesaPreview(ctx context.Context, sym string, input [] // divide by the buy rate inputAmount := kshAmount / rates.Buy - swapData, err := store.ReadSwapPreviewData(ctx, userStore, sessionId) + // Resolve active pool + activePoolAddress, _, err := h.resolveActivePoolDetails(ctx, sessionId) if err != nil { return res, err } @@ -270,13 +271,13 @@ func (h *MenuHandlers) GetMpesaPreview(ctx context.Context, sym string, input [] return res, err } - maxValue, err := strconv.ParseFloat(mpesaWithdrawalVoucher.Balance, 64) - if err != nil { - logg.ErrorCtxf(ctx, "Failed to convert the swapMaxAmount to a float", "error", err) - return res, err - } - if string(transactionType) == "normal" { + // get the max based on the selected voucher balance + maxValue, err := strconv.ParseFloat(mpesaWithdrawalVoucher.Balance, 64) + if err != nil { + logg.ErrorCtxf(ctx, "Failed to convert the stored balance string to a float", "error", err) + return res, err + } if inputAmount > maxValue { res.FlagSet = append(res.FlagSet, flag_invalid_amount) res.Content = inputStr @@ -302,8 +303,20 @@ func (h *MenuHandlers) GetMpesaPreview(ctx context.Context, sym string, input [] return res, nil } + swapToVoucher, err := store.ReadSwapToVoucher(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on ReadSwapFromVoucher", "error", err) + return res, err + } + + swapMaxAmount, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_SWAP_MAX_AMOUNT) + if err != nil { + logg.ErrorCtxf(ctx, "failed to read swapMaxAmount entry with", "key", storedb.DATA_ACTIVE_SWAP_MAX_AMOUNT, "error", err) + return res, err + } + // use the stored max RAT - maxRATValue, err := strconv.ParseFloat(swapData.ActiveSwapMaxAmount, 64) + maxRATValue, err := strconv.ParseFloat(string(swapMaxAmount), 64) if err != nil { logg.ErrorCtxf(ctx, "Failed to convert the swapMaxAmount to a float", "error", err) return res, err @@ -315,15 +328,21 @@ func (h *MenuHandlers) GetMpesaPreview(ctx context.Context, sym string, input [] return res, nil } - formattedAmount := fmt.Sprintf("%f", inputAmount) + // Format the amount to 2 decimal places + formattedAmount, err := store.TruncateDecimalString(fmt.Sprintf("%f", inputAmount), 2) + if err != nil { + res.FlagSet = append(res.FlagSet, flag_invalid_amount) + res.Content = inputStr + return res, nil + } - finalAmountStr, err := store.ParseAndScaleAmount(formattedAmount, swapData.ActiveSwapToDecimal) + finalAmountStr, err := store.ParseAndScaleAmount(formattedAmount, swapToVoucher.TokenDecimals) if err != nil { return res, err } // call the credit send API to get the reverse quote - r, err := h.accountService.GetCreditSendReverseQuote(ctx, swapData.ActivePoolAddress, swapData.ActiveSwapFromAddress, swapData.ActiveSwapToAddress, finalAmountStr) + r, err := h.accountService.GetCreditSendReverseQuote(ctx, string(activePoolAddress), mpesaWithdrawalVoucher.TokenAddress, swapToVoucher.TokenAddress, finalAmountStr) if err != nil { res.FlagSet = append(res.FlagSet, flag_api_call_error) res.Content = l.Get("Your request failed. Please try again later.") @@ -349,13 +368,13 @@ func (h *MenuHandlers) GetMpesaPreview(ctx context.Context, sym string, input [] } // covert for display - quoteInputStr := store.ScaleDownBalance(sendInputAmount, swapData.ActiveSwapFromDecimal) + quoteInputStr := store.ScaleDownBalance(sendInputAmount, mpesaWithdrawalVoucher.TokenDecimals) // Format the quoteInputStr amount to 2 decimal places qouteInputAmount, _ := store.TruncateDecimalString(quoteInputStr, 2) res.Content = l.Get( "You are sending %s %s in order to receive ~ %s ksh", - qouteInputAmount, swapData.ActiveSwapFromSym, inputStr, + qouteInputAmount, mpesaWithdrawalVoucher.TokenSymbol, inputStr, ) return res, nil @@ -381,16 +400,12 @@ func (h *MenuHandlers) InitiateGetMpesa(ctx context.Context, sym string, input [ mpesaAddress := config.DefaultMpesaAddress() - swapData, err := store.ReadSwapPreviewData(ctx, userStore, sessionId) - if err != nil { - return res, err - } - transactionType, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_SEND_TRANSACTION_TYPE) if err != nil { return res, err } + // get the selected voucher mpesaWithdrawalVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) if err != nil { logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) @@ -425,6 +440,24 @@ func (h *MenuHandlers) InitiateGetMpesa(ctx context.Context, sym string, input [ return res, nil } + publicKey, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY) + if err != nil { + logg.ErrorCtxf(ctx, "failed to read publicKey entry", "key", storedb.DATA_PUBLIC_KEY, "error", err) + return res, err + } + + swapToVoucher, err := store.ReadSwapToVoucher(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on ReadSwapFromVoucher", "error", err) + return res, err + } + + // Resolve active pool + activePoolAddress, _, err := h.resolveActivePoolDetails(ctx, sessionId) + if err != nil { + return res, err + } + swapAmount, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_SWAP_AMOUNT) if err != nil { logg.ErrorCtxf(ctx, "failed to read swapAmount entry with", "key", storedb.DATA_ACTIVE_SWAP_AMOUNT, "error", err) @@ -434,7 +467,7 @@ func (h *MenuHandlers) InitiateGetMpesa(ctx context.Context, sym string, input [ swapAmountStr := string(swapAmount) // Call the poolSwap API - poolSwap, err := h.accountService.PoolSwap(ctx, swapAmountStr, swapData.PublicKey, swapData.ActiveSwapFromAddress, swapData.ActivePoolAddress, swapData.ActiveSwapToAddress) + poolSwap, err := h.accountService.PoolSwap(ctx, swapAmountStr, string(publicKey), mpesaWithdrawalVoucher.TokenAddress, string(activePoolAddress), swapToVoucher.TokenAddress) if err != nil { flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error") res.FlagSet = append(res.FlagSet, flag_api_call_error) @@ -454,7 +487,7 @@ func (h *MenuHandlers) InitiateGetMpesa(ctx context.Context, sym string, input [ } // Initiate a send to mpesa after the swap - tokenTransfer, err := h.accountService.TokenTransfer(ctx, string(amount), swapData.PublicKey, mpesaAddress, swapData.ActiveSwapToAddress) + tokenTransfer, err := h.accountService.TokenTransfer(ctx, string(amount),string(publicKey), mpesaAddress, swapToVoucher.TokenAddress) if err != nil { res.FlagSet = append(res.FlagSet, flag_api_call_error) res.Content = l.Get("Your request failed. Please try again later.") From e7a3e63cd5425e71e8ad4e5aebc6ffea71be7fa2 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 17 Feb 2026 08:42:58 +0300 Subject: [PATCH 082/130] go back on 0 input for navigation --- handlers/application/send.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/handlers/application/send.go b/handlers/application/send.go index 0114cde..6ff002d 100644 --- a/handlers/application/send.go +++ b/handlers/application/send.go @@ -560,6 +560,13 @@ func (h *MenuHandlers) ValidateAmount(ctx context.Context, sym string, input []b return res, fmt.Errorf("missing session") } flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") + + inputStr := string(input) + if inputStr == "0" { + res.FlagReset = append(res.FlagReset, flag_invalid_amount) + return res, nil + } + userStore := h.userdataStore var balanceValue float64 @@ -577,7 +584,7 @@ func (h *MenuHandlers) ValidateAmount(ctx context.Context, sym string, input []b } // Extract numeric part from the input amount - amountStr := strings.TrimSpace(string(input)) + amountStr := strings.TrimSpace(inputStr) inputAmount, err := strconv.ParseFloat(amountStr, 64) if err != nil { res.FlagSet = append(res.FlagSet, flag_invalid_amount) @@ -585,7 +592,7 @@ func (h *MenuHandlers) ValidateAmount(ctx context.Context, sym string, input []b return res, nil } - if inputAmount > balanceValue || inputAmount < 0.1{ + if inputAmount > balanceValue || inputAmount < 0.1 { res.FlagSet = append(res.FlagSet, flag_invalid_amount) res.Content = amountStr return res, nil From c50c53c758c517090e3fc568894db15df6aa993c Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 17 Feb 2026 08:51:22 +0300 Subject: [PATCH 083/130] use the current balance as debt --- handlers/application/balance.go | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index aa68b03..9011f58 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -122,16 +122,17 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error") - // 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, activeAddress, publicKey, activeDecimal, err := h.getSessionData(ctx, sessionId) if err != nil { return res, nil } + // default response + formattedDebt, _ := store.TruncateDecimalString(string(activeBal), 2) + res.FlagReset = append(res.FlagReset, flag_api_call_error) + res.Content = l.Get("Credit: %s KSH\nDebt: %s %s\n", "0", formattedDebt, string(activeSym)) + // Resolve active pool activePoolAddress, _, err := h.resolveActivePoolDetails(ctx, sessionId) if err != nil { @@ -238,9 +239,6 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i // DEBT calculation: All outstanding active token that is in the current pool // (how much of AT that is in the active Pool) - scaledDebt := "0" - // convert the current balance to Ksh - scaledDebt = string(activeBal) // Fetch MPESA rates rates, err := h.accountService.GetMpesaOnrampRates(ctx) @@ -252,18 +250,16 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i } creditFloat, _ := strconv.ParseFloat(scaledCredit, 64) - debtFloat, _ := strconv.ParseFloat(scaledDebt, 64) creditKsh := fmt.Sprintf("%f", creditFloat*rates.Buy) - debtKsh := fmt.Sprintf("%f", debtFloat*rates.Buy) kshFormattedCredit, _ := store.TruncateDecimalString(creditKsh, 0) - kshFormattedDebt, _ := store.TruncateDecimalString(debtKsh, 0) res.Content = l.Get( - "Credit: %s KSH\nDebt: %s KSH\n", + "Credit: %s KSH\nDebt: %s %s\n", kshFormattedCredit, - kshFormattedDebt, + formattedDebt, + string(activeSym), ) return res, nil From a346adb8f9a134cd694f84799e118a93091ac278 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 17 Feb 2026 13:36:38 +0300 Subject: [PATCH 084/130] display the default asset during the Mpesa topup --- handlers/application/mpesa.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/handlers/application/mpesa.go b/handlers/application/mpesa.go index 41470ff..d095bc1 100644 --- a/handlers/application/mpesa.go +++ b/handlers/application/mpesa.go @@ -487,7 +487,7 @@ func (h *MenuHandlers) InitiateGetMpesa(ctx context.Context, sym string, input [ } // Initiate a send to mpesa after the swap - tokenTransfer, err := h.accountService.TokenTransfer(ctx, string(amount),string(publicKey), mpesaAddress, swapToVoucher.TokenAddress) + tokenTransfer, err := h.accountService.TokenTransfer(ctx, string(amount), string(publicKey), mpesaAddress, swapToVoucher.TokenAddress) if err != nil { res.FlagSet = append(res.FlagSet, flag_api_call_error) res.Content = l.Get("Your request failed. Please try again later.") @@ -525,7 +525,7 @@ func (h *MenuHandlers) SendMpesaMinLimit(ctx context.Context, sym string, input kshFormatted, _ := store.TruncateDecimalString(ksh, 0) res.Content = l.Get( - "Enter the amount of Mpesa to send: (Minimum %s Ksh)\n", + "Enter the amount of credit to receive: (Minimum %s Ksh)\n", kshFormatted, ) @@ -594,9 +594,11 @@ func (h *MenuHandlers) SendMpesaPreview(ctx context.Context, sym string, input [ estimateStr := fmt.Sprintf("%f", estimateValue) estimateFormatted, _ := store.TruncateDecimalString(estimateStr, 2) + defaultAsset := config.DefaultMpesaAsset() + res.Content = l.Get( - "You will get a prompt for your M-Pesa PIN shortly to send %s ksh and receive ~ %s cUSD", - inputStr, estimateFormatted, + "You will get a prompt for your M-Pesa PIN shortly to send %s ksh and receive ~ %s %s", + inputStr, estimateFormatted, defaultAsset, ) return res, nil From 96ba48bcba42521bebb09bf4ff02708822b61ae7 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 17 Feb 2026 14:04:17 +0300 Subject: [PATCH 085/130] only set the flag if the user has a single voucher --- handlers/application/vouchers.go | 8 ++++++++ services/registration/pp.csv | 1 + 2 files changed, 9 insertions(+) diff --git a/handlers/application/vouchers.go b/handlers/application/vouchers.go index cad629b..e0cd20c 100644 --- a/handlers/application/vouchers.go +++ b/handlers/application/vouchers.go @@ -33,6 +33,7 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b flag_no_active_voucher, _ := h.flagManager.GetFlag("flag_no_active_voucher") flag_api_error, _ := h.flagManager.GetFlag("flag_api_call_error") flag_no_stable_vouchers, _ := h.flagManager.GetFlag("flag_no_stable_vouchers") + flag_single_voucher, _ := h.flagManager.GetFlag("flag_single_voucher") publicKey, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY) if err != nil { @@ -73,6 +74,13 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b return res, nil } + // only set the flag if the user has a single voucher + if len(vouchersResp) == 1 { + res.FlagSet = append(res.FlagSet, flag_single_voucher) + } else { + res.FlagReset = append(res.FlagReset, flag_single_voucher) + } + res.FlagReset = append(res.FlagReset, flag_no_active_voucher) // add a variable to filter out the active voucher diff --git a/services/registration/pp.csv b/services/registration/pp.csv index 3911af7..9a3ebec 100644 --- a/services/registration/pp.csv +++ b/services/registration/pp.csv @@ -37,3 +37,4 @@ flag,flag_low_swap_amount,43,this is set when the swap max limit is less than 0. flag,flag_alias_unavailable,44,this is set when the preferred alias is not available flag,flag_swap_transaction,45,this is set when the transaction will involve performing a swap flag,flag_no_stable_vouchers,46,this is set when the user does not have a stable voucher +flag,flag_single_voucher,47,this is set when the user only has a single voucher From 2d6e7e81ddb32979ea09eeb9f1c5754037724201 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 17 Feb 2026 16:07:34 +0300 Subject: [PATCH 086/130] added a db key to store the state of the custom transaction voucher --- services/registration/pp.csv | 2 +- store/db/db.go | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/services/registration/pp.csv b/services/registration/pp.csv index 9a3ebec..f80a137 100644 --- a/services/registration/pp.csv +++ b/services/registration/pp.csv @@ -37,4 +37,4 @@ flag,flag_low_swap_amount,43,this is set when the swap max limit is less than 0. flag,flag_alias_unavailable,44,this is set when the preferred alias is not available flag,flag_swap_transaction,45,this is set when the transaction will involve performing a swap flag,flag_no_stable_vouchers,46,this is set when the user does not have a stable voucher -flag,flag_single_voucher,47,this is set when the user only has a single voucher +flag,flag_multiple_voucher,47,this is set when the user only has a multiple voucher diff --git a/store/db/db.go b/store/db/db.go index 67850b9..a984efe 100644 --- a/store/db/db.go +++ b/store/db/db.go @@ -95,6 +95,8 @@ const ( DATA_RECIPIENT_PHONE_NUMBER // Currently active swap from balance for the swap DATA_ACTIVE_SWAP_FROM_BALANCE + // Holds the state whether the transaction uses a custom voucher + DATA_TRANSACTION_CUSTOM_VOUCHER ) const ( From 108d5bdc3eb9a151113263c6ff8b1db7a15fb512 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 17 Feb 2026 16:08:22 +0300 Subject: [PATCH 087/130] added a node for credit voucher selection --- handlers/local.go | 1 + services/registration/credit_send.vis | 5 ++++- services/registration/credit_vouchers | 1 + services/registration/credit_vouchers.vis | 15 +++++++++++++++ 4 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 services/registration/credit_vouchers create mode 100644 services/registration/credit_vouchers.vis diff --git a/handlers/local.go b/handlers/local.go index e19fc20..7deb9f1 100644 --- a/handlers/local.go +++ b/handlers/local.go @@ -154,6 +154,7 @@ func (ls *LocalHandlerService) GetHandler(accountService remote.AccountService) ls.DbRs.AddLocalFunc("pool_deposit_max_amount", appHandlers.PoolDepositMaxAmount) ls.DbRs.AddLocalFunc("confirm_pool_deposit", appHandlers.ConfirmPoolDeposit) ls.DbRs.AddLocalFunc("initiate_pool_deposit", appHandlers.InitiatePoolDeposit) + ls.DbRs.AddLocalFunc("validate_credit_voucher", appHandlers.ValidateCreditVoucher) ls.first = appHandlers.Init diff --git a/services/registration/credit_send.vis b/services/registration/credit_send.vis index 35db249..a1c5669 100644 --- a/services/registration/credit_send.vis +++ b/services/registration/credit_send.vis @@ -3,10 +3,13 @@ RELOAD transaction_reset CATCH no_voucher flag_no_active_voucher 1 MOUT back 0 HALT +LOAD clear_trans_type_flag 6 +RELOAD clear_trans_type_flag LOAD validate_recipient 50 RELOAD validate_recipient -CATCH api_failure flag_api_call_error 1 +CATCH api_failure flag_api_call_error 1 CATCH invalid_recipient flag_invalid_recipient 1 CATCH invite_recipient flag_invalid_recipient_with_invite 1 +CATCH credit_vouchers flag_multiple_voucher 1 INCMP _ 0 INCMP credit_amount * diff --git a/services/registration/credit_vouchers b/services/registration/credit_vouchers new file mode 100644 index 0000000..90039ed --- /dev/null +++ b/services/registration/credit_vouchers @@ -0,0 +1 @@ +{{.get_ordered_vouchers}} \ No newline at end of file diff --git a/services/registration/credit_vouchers.vis b/services/registration/credit_vouchers.vis new file mode 100644 index 0000000..fa08202 --- /dev/null +++ b/services/registration/credit_vouchers.vis @@ -0,0 +1,15 @@ +LOAD get_ordered_vouchers 0 +MAP get_ordered_vouchers +MOUT back 0 +MOUT quit 99 +MNEXT next 88 +MPREV prev 98 +HALT +INCMP > 88 +INCMP < 98 +INCMP _ 0 +INCMP quit 99 +LOAD validate_credit_voucher 67 +RELOAD validate_credit_voucher +CATCH . flag_incorrect_voucher 1 +INCMP credit_amount * From d8a6535c6f229068d2398ab0a79542b58dd7b3e6 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 17 Feb 2026 16:09:14 +0300 Subject: [PATCH 088/130] added validation and storage of the selected custom voucher --- handlers/application/vouchers.go | 53 ++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/handlers/application/vouchers.go b/handlers/application/vouchers.go index e0cd20c..32a0d4b 100644 --- a/handlers/application/vouchers.go +++ b/handlers/application/vouchers.go @@ -33,7 +33,7 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b flag_no_active_voucher, _ := h.flagManager.GetFlag("flag_no_active_voucher") flag_api_error, _ := h.flagManager.GetFlag("flag_api_call_error") flag_no_stable_vouchers, _ := h.flagManager.GetFlag("flag_no_stable_vouchers") - flag_single_voucher, _ := h.flagManager.GetFlag("flag_single_voucher") + flag_multiple_voucher, _ := h.flagManager.GetFlag("flag_multiple_voucher") publicKey, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY) if err != nil { @@ -76,9 +76,9 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b // only set the flag if the user has a single voucher if len(vouchersResp) == 1 { - res.FlagSet = append(res.FlagSet, flag_single_voucher) + res.FlagReset = append(res.FlagReset, flag_multiple_voucher) } else { - res.FlagReset = append(res.FlagReset, flag_single_voucher) + res.FlagSet = append(res.FlagSet, flag_multiple_voucher) } res.FlagReset = append(res.FlagReset, flag_no_active_voucher) @@ -412,3 +412,50 @@ func (h *MenuHandlers) GetVoucherDetails(ctx context.Context, sym string, input return res, nil } + +// ValidateCreditVoucher sets the selected voucher as the active transaction voucher +func (h *MenuHandlers) ValidateCreditVoucher(ctx context.Context, sym string, input []byte) (resource.Result, error) { + var res resource.Result + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + + code := codeFromCtx(ctx) + l := gotext.NewLocale(translationDir, code) + l.AddDomain("default") + + flag_incorrect_voucher, _ := h.flagManager.GetFlag("flag_incorrect_voucher") + + res.FlagReset = append(res.FlagReset, flag_incorrect_voucher) + + inputStr := string(input) + if inputStr == "0" || inputStr == "99" || inputStr == "88" || inputStr == "98" { + return res, nil + } + + userStore := h.userdataStore + metadata, err := store.GetOrderedVoucherData(ctx, userStore, sessionId, inputStr) + if err != nil { + return res, fmt.Errorf("failed to retrieve swap to voucher data: %v", err) + } + if metadata == nil { + res.FlagSet = append(res.FlagSet, flag_incorrect_voucher) + return res, nil + } + + // Store the transaction voucher data + if err := store.StoreTemporaryVoucher(ctx, h.userdataStore, sessionId, metadata); err != nil { + logg.ErrorCtxf(ctx, "failed on StoreTemporaryVoucher", "error", err) + return res, err + } + + // Store the state of the custom transaction voucher + err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_TRANSACTION_CUSTOM_VOUCHER, []byte("1")) + if err != nil { + logg.ErrorCtxf(ctx, "failed to write custom transaction voucher", "key", storedb.DATA_TRANSACTION_CUSTOM_VOUCHER, "error", err) + return res, err + } + + return res, nil +} From f869ff437ee831209c3f3d6d1804f500e346b182 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Tue, 17 Feb 2026 16:10:31 +0300 Subject: [PATCH 089/130] update the transaction for custom voucher selection --- handlers/application/send.go | 63 ++++++++++++++++++++++++++++++++---- 1 file changed, 57 insertions(+), 6 deletions(-) diff --git a/handlers/application/send.go b/handlers/application/send.go index 6ff002d..ff60f4a 100644 --- a/handlers/application/send.go +++ b/handlers/application/send.go @@ -203,11 +203,11 @@ func (h *MenuHandlers) determineAndSaveTransactionType( publicKey []byte, recipientPhoneNumber []byte, ) error { - store := h.userdataStore + userStore := h.userdataStore txType := "swap" // Read sender's active address - senderActiveAddress, err := store.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_ADDRESS) + senderActiveAddress, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_ADDRESS) if err != nil { logg.ErrorCtxf(ctx, "Failed to read sender active address", "error", err) return err @@ -215,7 +215,7 @@ func (h *MenuHandlers) determineAndSaveTransactionType( var recipientActiveAddress []byte if recipientPhoneNumber != nil { - recipientActiveAddress, _ = store.ReadEntry(ctx, string(recipientPhoneNumber), storedb.DATA_ACTIVE_ADDRESS) + recipientActiveAddress, _ = userStore.ReadEntry(ctx, string(recipientPhoneNumber), storedb.DATA_ACTIVE_ADDRESS) } // recipient has no active token → normal transaction @@ -227,17 +227,34 @@ func (h *MenuHandlers) determineAndSaveTransactionType( } // Save the transaction type - if err := store.WriteEntry(ctx, sessionId, storedb.DATA_SEND_TRANSACTION_TYPE, []byte(txType)); err != nil { + if err := userStore.WriteEntry(ctx, sessionId, storedb.DATA_SEND_TRANSACTION_TYPE, []byte(txType)); err != nil { logg.ErrorCtxf(ctx, "Failed to write transaction type", "type", txType, "error", err) return err } // Save the recipient's phone number only if it exists if recipientPhoneNumber != nil { - if err := store.WriteEntry(ctx, sessionId, storedb.DATA_RECIPIENT_PHONE_NUMBER, recipientPhoneNumber); err != nil { + if err := userStore.WriteEntry(ctx, sessionId, storedb.DATA_RECIPIENT_PHONE_NUMBER, recipientPhoneNumber); err != nil { logg.ErrorCtxf(ctx, "Failed to write recipient phone number", "type", txType, "error", err) return err } + + // fetch data for use (to_voucher data) + recipientActiveSym, recipientActiveAddress, recipientActiveDecimal, err := h.getRecipientData(ctx, string(recipientPhoneNumber)) + if err != nil { + return err + } + swapMetadata := &dataserviceapi.TokenHoldings{ + TokenAddress: string(recipientActiveAddress), + TokenSymbol: string(recipientActiveSym), + TokenDecimals: string(recipientActiveDecimal), + } + + // Store the active swap_to data + if err := store.UpdateSwapToVoucherData(ctx, userStore, sessionId, swapMetadata); err != nil { + logg.ErrorCtxf(ctx, "failed on UpdateSwapToVoucherData", "error", err) + return err + } } else { logg.InfoCtxf(ctx, "No recipient phone number found for public key", "publicKey", string(publicKey)) } @@ -309,6 +326,7 @@ func (h *MenuHandlers) ResetTransactionAmount(ctx context.Context, sym string, i } // MaxAmount checks the transaction type to determine the displayed max amount. +// Checks whether the user selected a custom voucher // If the transaction type is "swap", it checks the max swappable amount and sets this as the content. // If the transaction type is "normal", gets the current sender's balance from the store and sets it as // the result content. @@ -334,9 +352,41 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte) return res, err } + customVoucherSelection, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_TRANSACTION_CUSTOM_VOUCHER) + if err == nil { + customVoucherValue, _ := strconv.ParseUint(string(customVoucherSelection), 0, 64) + if customVoucherValue == 1 { + // use the custom voucher + customTransactionVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + return res, err + } + + activeSym = []byte(customTransactionVoucher.TokenSymbol) + activeBal = []byte(customTransactionVoucher.Balance) + activeDecimal = []byte(customTransactionVoucher.TokenDecimals) + activeAddress = []byte(customTransactionVoucher.TokenAddress) + } + } + // Format the active balance amount to 2 decimal places formattedBalance, _ := store.TruncateDecimalString(string(activeBal), 2) + // confirm the transaction type + swapToVoucher, err := store.ReadSwapToVoucher(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on ReadSwapFromVoucher", "error", err) + return res, err + } + + if string(swapToVoucher.TokenAddress) == string(activeAddress) { + // recipient has active token same as selected token → normal transaction + transactionType = []byte("normal") + } else { + transactionType = []byte("swap") + } + // If normal transaction return balance if string(transactionType) == "normal" { res.FlagReset = append(res.FlagReset, flag_swap_transaction) @@ -939,10 +989,11 @@ func (h *MenuHandlers) ClearTransactionTypeFlag(ctx context.Context, sym string, var res resource.Result flag_swap_transaction, _ := h.flagManager.GetFlag("flag_swap_transaction") + flag_multiple_voucher, _ := h.flagManager.GetFlag("flag_multiple_voucher") inputStr := string(input) if inputStr == "0" { - res.FlagReset = append(res.FlagReset, flag_swap_transaction) + res.FlagReset = append(res.FlagReset, flag_swap_transaction, flag_multiple_voucher) return res, nil } From 81b56f6feda86bcfd24ce44793b14d86b7c80b4e Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 18 Feb 2026 16:04:40 +0300 Subject: [PATCH 090/130] added a key to store the initial recipient input given by the user --- store/db/db.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/store/db/db.go b/store/db/db.go index a984efe..b613b69 100644 --- a/store/db/db.go +++ b/store/db/db.go @@ -97,6 +97,8 @@ const ( DATA_ACTIVE_SWAP_FROM_BALANCE // Holds the state whether the transaction uses a custom voucher DATA_TRANSACTION_CUSTOM_VOUCHER + // Holds the initial recipient input given by the user + DATA_RECIPIENT_INPUT ) const ( From e03ca7fcaebba17790751b291ba15bfaa2496a8c Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 18 Feb 2026 16:06:40 +0300 Subject: [PATCH 091/130] use the normal transaction preview and the translation --- handlers/local.go | 3 ++- services/registration/locale/swa/default.po | 5 ++++- services/registration/transaction_pin | 2 +- services/registration/transaction_pin.vis | 8 ++------ services/registration/transaction_pin_swa | 2 -- 5 files changed, 9 insertions(+), 11 deletions(-) delete mode 100644 services/registration/transaction_pin_swa diff --git a/handlers/local.go b/handlers/local.go index 7deb9f1..2ee3ae5 100644 --- a/handlers/local.go +++ b/handlers/local.go @@ -105,7 +105,8 @@ func (ls *LocalHandlerService) GetHandler(accountService remote.AccountService) ls.DbRs.AddLocalFunc("get_profile_info", appHandlers.GetProfileInfo) ls.DbRs.AddLocalFunc("verify_yob", appHandlers.VerifyYob) ls.DbRs.AddLocalFunc("reset_incorrect_date_format", appHandlers.ResetIncorrectYob) - ls.DbRs.AddLocalFunc("initiate_transaction", appHandlers.InitiateTransaction) + ls.DbRs.AddLocalFunc("normal_transaction_preview", appHandlers.NormalTransactionPreview) + ls.DbRs.AddLocalFunc("initiate_normal_transaction", appHandlers.InitiateNormalTransaction) ls.DbRs.AddLocalFunc("confirm_pin_change", appHandlers.ConfirmPinChange) ls.DbRs.AddLocalFunc("quit_with_help", appHandlers.QuitWithHelp) ls.DbRs.AddLocalFunc("fetch_community_balance", appHandlers.FetchCommunityBalance) diff --git a/services/registration/locale/swa/default.po b/services/registration/locale/swa/default.po index 21d30ce..3dd4c23 100644 --- a/services/registration/locale/swa/default.po +++ b/services/registration/locale/swa/default.po @@ -89,4 +89,7 @@ msgid "You will deposit %s %s into %s\n" msgstr "Utaweka %s %s kwenye %s\n" msgid "Your request has been sent. You will receive an SMS when %s %s has been deposited into %s." -msgstr "Ombi lako limetumwa. Utapokea ujumbe wakati %s %s itawekwa kwenye %s." \ No newline at end of file +msgstr "Ombi lako limetumwa. Utapokea ujumbe wakati %s %s itawekwa kwenye %s." + +msgid "%s will receive %s %s from %s" +msgstr %s atapokea %s %s kutoka kwa %s" \ No newline at end of file diff --git a/services/registration/transaction_pin b/services/registration/transaction_pin index a1b7125..20fd59a 100644 --- a/services/registration/transaction_pin +++ b/services/registration/transaction_pin @@ -1,2 +1,2 @@ -{{.get_recipient}} will receive {{.get_amount}} from {{.get_sender}} +{{.normal_transaction_preview}} Please enter your PIN to confirm: \ No newline at end of file diff --git a/services/registration/transaction_pin.vis b/services/registration/transaction_pin.vis index 0388f0c..d921253 100644 --- a/services/registration/transaction_pin.vis +++ b/services/registration/transaction_pin.vis @@ -1,9 +1,5 @@ -RELOAD get_amount -MAP get_amount -RELOAD get_recipient -MAP get_recipient -RELOAD get_sender -MAP get_sender +LOAD normal_transaction_preview 0 +MAP normal_transaction_preview MOUT back 0 MOUT quit 9 LOAD authorize_account 6 diff --git a/services/registration/transaction_pin_swa b/services/registration/transaction_pin_swa deleted file mode 100644 index 1924166..0000000 --- a/services/registration/transaction_pin_swa +++ /dev/null @@ -1,2 +0,0 @@ -{{.get_recipient}} atapokea {{.get_amount}} kutoka kwa {{.get_sender}} -Tafadhali weka PIN yako kudhibitisha: \ No newline at end of file From 836ea3ce9dd8abb7a3bd29357ca03f1709a76040 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 18 Feb 2026 16:08:14 +0300 Subject: [PATCH 092/130] simplified the vis files by removing unused LOAD and RELOAD statements --- services/registration/credit_amount.vis | 3 --- services/registration/transaction_initiated.vis | 8 +------- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/services/registration/credit_amount.vis b/services/registration/credit_amount.vis index 1e402b3..7d08cbc 100644 --- a/services/registration/credit_amount.vis +++ b/services/registration/credit_amount.vis @@ -13,7 +13,4 @@ LOAD validate_amount 64 RELOAD validate_amount CATCH invalid_amount flag_invalid_amount 1 INCMP _ 0 -LOAD get_recipient 0 -LOAD get_sender 64 -LOAD get_amount 32 INCMP transaction_pin * diff --git a/services/registration/transaction_initiated.vis b/services/registration/transaction_initiated.vis index bc524ce..d5e6ece 100644 --- a/services/registration/transaction_initiated.vis +++ b/services/registration/transaction_initiated.vis @@ -1,10 +1,4 @@ LOAD reset_incorrect_pin 6 CATCH _ flag_account_authorized 0 -RELOAD get_amount -MAP get_amount -RELOAD get_recipient -MAP get_recipient -RELOAD get_sender -MAP get_sender -LOAD initiate_transaction 0 +LOAD initiate_normal_transaction 0 HALT From 8d259683a1e39773d31855063a0f5937634cebc9 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 18 Feb 2026 16:08:47 +0300 Subject: [PATCH 093/130] fetch the DATA_RECIPIENT_INPUT instead of temporary value --- store/tokens.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/store/tokens.go b/store/tokens.go index 0ac7bdf..566097b 100644 --- a/store/tokens.go +++ b/store/tokens.go @@ -13,7 +13,7 @@ import ( ) type TransactionData struct { - TemporaryValue string + RecipientInput string ActiveSym string Amount string PublicKey string @@ -77,7 +77,7 @@ func ParseAndScaleAmount(storedAmount, activeDecimal string) (string, error) { func ReadTransactionData(ctx context.Context, store DataStore, sessionId string) (TransactionData, error) { data := TransactionData{} fieldToKey := map[string]storedb.DataTyp{ - "TemporaryValue": storedb.DATA_TEMPORARY_VALUE, + "RecipientInput": storedb.DATA_RECIPIENT_INPUT, "ActiveSym": storedb.DATA_ACTIVE_SYM, "Amount": storedb.DATA_AMOUNT, "PublicKey": storedb.DATA_PUBLIC_KEY, From d2b4dcef36ca3dc2d16d41d86e69bbf4514e2e87 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 18 Feb 2026 16:09:20 +0300 Subject: [PATCH 094/130] match the updated function name in the test --- handlers/application/send_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/handlers/application/send_test.go b/handlers/application/send_test.go index 207032a..665fd10 100644 --- a/handlers/application/send_test.go +++ b/handlers/application/send_test.go @@ -452,7 +452,7 @@ func TestGetAmount(t *testing.T) { assert.Equal(t, formattedAmount, res.Content) } -func TestInitiateTransaction(t *testing.T) { +func TestInitiateNormalTransaction(t *testing.T) { sessionId := "254712345678" ctx, store := InitializeTestStore(t) ctx = context.WithValue(ctx, "SessionId", sessionId) @@ -538,7 +538,7 @@ func TestInitiateTransaction(t *testing.T) { mockAccountService.On("TokenTransfer").Return(tt.TransferResponse, nil) // Call the method under test - res, _ := h.InitiateTransaction(ctx, "transaction_reset_amount", []byte("")) + res, _ := h.InitiateNormalTransaction(ctx, "transaction_reset_amount", []byte("")) // Assert that no errors occurred assert.NoError(t, err) From 5650629ae459c16a63d60498efad581d0c560ef7 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 18 Feb 2026 16:56:40 +0300 Subject: [PATCH 095/130] update the db key name for clarity --- handlers/application/vouchers.go | 4 ++-- store/db/db.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/handlers/application/vouchers.go b/handlers/application/vouchers.go index 32a0d4b..50dd86b 100644 --- a/handlers/application/vouchers.go +++ b/handlers/application/vouchers.go @@ -451,9 +451,9 @@ func (h *MenuHandlers) ValidateCreditVoucher(ctx context.Context, sym string, in } // Store the state of the custom transaction voucher - err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_TRANSACTION_CUSTOM_VOUCHER, []byte("1")) + err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_TRANSACTION_CUSTOM_VOUCHER_STATE, []byte("1")) if err != nil { - logg.ErrorCtxf(ctx, "failed to write custom transaction voucher", "key", storedb.DATA_TRANSACTION_CUSTOM_VOUCHER, "error", err) + logg.ErrorCtxf(ctx, "failed to write custom transaction voucher", "key", storedb.DATA_TRANSACTION_CUSTOM_VOUCHER_STATE, "error", err) return res, err } diff --git a/store/db/db.go b/store/db/db.go index b613b69..b363249 100644 --- a/store/db/db.go +++ b/store/db/db.go @@ -96,7 +96,7 @@ const ( // Currently active swap from balance for the swap DATA_ACTIVE_SWAP_FROM_BALANCE // Holds the state whether the transaction uses a custom voucher - DATA_TRANSACTION_CUSTOM_VOUCHER + DATA_TRANSACTION_CUSTOM_VOUCHER_STATE // Holds the initial recipient input given by the user DATA_RECIPIENT_INPUT ) From 75caed5f085222b053f923024cc4a168485c2295 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 18 Feb 2026 16:58:28 +0300 Subject: [PATCH 096/130] added a key to store the actual transaction voucher --- store/db/db.go | 2 ++ store/vouchers.go | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/store/db/db.go b/store/db/db.go index b363249..d1ec06d 100644 --- a/store/db/db.go +++ b/store/db/db.go @@ -99,6 +99,8 @@ const ( DATA_TRANSACTION_CUSTOM_VOUCHER_STATE // Holds the initial recipient input given by the user DATA_RECIPIENT_INPUT + // Holds the transaction voucher + DATA_TRANSACTION_CUSTOM_VOUCHER ) const ( diff --git a/store/vouchers.go b/store/vouchers.go index 5e7d986..ee4202e 100644 --- a/store/vouchers.go +++ b/store/vouchers.go @@ -189,7 +189,7 @@ func MatchVoucher(input, symbols, balances, decimals, addresses string) (symbol, func StoreTemporaryVoucher(ctx context.Context, store DataStore, sessionId string, data *dataserviceapi.TokenHoldings) error { tempData := fmt.Sprintf("%s,%s,%s,%s", data.TokenSymbol, data.Balance, data.TokenDecimals, data.TokenAddress) - if err := store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(tempData)); err != nil { + if err := store.WriteEntry(ctx, sessionId, storedb.DATA_TRANSACTION_CUSTOM_VOUCHER, []byte(tempData)); err != nil { return err } @@ -198,7 +198,7 @@ func StoreTemporaryVoucher(ctx context.Context, store DataStore, sessionId strin // GetTemporaryVoucherData retrieves temporary voucher metadata from the DataStore. func GetTemporaryVoucherData(ctx context.Context, store DataStore, sessionId string) (*dataserviceapi.TokenHoldings, error) { - temp_data, err := store.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) + temp_data, err := store.ReadEntry(ctx, sessionId, storedb.DATA_TRANSACTION_CUSTOM_VOUCHER) if err != nil { return nil, err } From 4660527e662ab98249c8c9d04a8c904bfc17281c Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 18 Feb 2026 16:59:37 +0300 Subject: [PATCH 097/130] updated the send logic to work with a custom voucher --- handlers/application/send.go | 135 +++++++++++++++++++++++++++-------- 1 file changed, 107 insertions(+), 28 deletions(-) diff --git a/handlers/application/send.go b/handlers/application/send.go index ff60f4a..b103168 100644 --- a/handlers/application/send.go +++ b/handlers/application/send.go @@ -48,10 +48,10 @@ func (h *MenuHandlers) ValidateRecipient(ctx context.Context, sym string, input return res, nil } - // save the recipient as the temporaryRecipient - err = store.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(recipient)) + // save the recipient under recipient input + err = store.WriteEntry(ctx, sessionId, storedb.DATA_RECIPIENT_INPUT, []byte(recipient)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write temporaryRecipient entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", recipient, "error", err) + logg.ErrorCtxf(ctx, "failed to write recipient input entry with", "key", storedb.DATA_RECIPIENT_INPUT, "value", recipient, "error", err) return res, err } @@ -352,7 +352,7 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte) return res, err } - customVoucherSelection, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_TRANSACTION_CUSTOM_VOUCHER) + customVoucherSelection, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_TRANSACTION_CUSTOM_VOUCHER_STATE) if err == nil { customVoucherValue, _ := strconv.ParseUint(string(customVoucherSelection), 0, 64) if customVoucherValue == 1 { @@ -619,40 +619,46 @@ func (h *MenuHandlers) ValidateAmount(ctx context.Context, sym string, input []b userStore := h.userdataStore - var balanceValue float64 - // retrieve the active balance activeBal, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_BAL) if err != nil { logg.ErrorCtxf(ctx, "failed to read activeBal entry with", "key", storedb.DATA_ACTIVE_BAL, "error", err) return res, err } - balanceValue, err = strconv.ParseFloat(string(activeBal), 64) + + customVoucherSelection, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_TRANSACTION_CUSTOM_VOUCHER_STATE) + if err == nil { + customVoucherValue, _ := strconv.ParseUint(string(customVoucherSelection), 0, 64) + if customVoucherValue == 1 { + // use the custom voucher + customTransactionVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + return res, err + } + + activeBal = []byte(customTransactionVoucher.Balance) + } + } + + maxValue, err := strconv.ParseFloat(string(activeBal), 64) if err != nil { logg.ErrorCtxf(ctx, "Failed to convert the activeBal to a float", "error", err) return res, err } - // Extract numeric part from the input amount - amountStr := strings.TrimSpace(inputStr) - inputAmount, err := strconv.ParseFloat(amountStr, 64) - if err != nil { + inputAmount, err := strconv.ParseFloat(inputStr, 64) + if err != nil || inputAmount > maxValue || inputAmount < 0.1 { res.FlagSet = append(res.FlagSet, flag_invalid_amount) - res.Content = amountStr - return res, nil - } - - if inputAmount > balanceValue || inputAmount < 0.1 { - res.FlagSet = append(res.FlagSet, flag_invalid_amount) - res.Content = amountStr + res.Content = inputStr return res, nil } // Format the amount to 2 decimal places before saving (truncated) - formattedAmount, err := store.TruncateDecimalString(amountStr, 2) + formattedAmount, err := store.TruncateDecimalString(inputStr, 2) if err != nil { res.FlagSet = append(res.FlagSet, flag_invalid_amount) - res.Content = amountStr + res.Content = inputStr return res, nil } @@ -724,8 +730,62 @@ func (h *MenuHandlers) GetAmount(ctx context.Context, sym string, input []byte) return res, nil } -// InitiateTransaction calls the TokenTransfer and returns a confirmation based on the result. -func (h *MenuHandlers) InitiateTransaction(ctx context.Context, sym string, input []byte) (resource.Result, error) { +// NormalTransactionPreview displays the token transfer preview awaiting authorization +func (h *MenuHandlers) NormalTransactionPreview(ctx context.Context, sym string, input []byte) (resource.Result, error) { + var res resource.Result + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + + // Input in RAT + inputStr := string(input) + if inputStr == "0" { + return res, nil + } + + code := codeFromCtx(ctx) + l := gotext.NewLocale(translationDir, code) + l.AddDomain("default") + + userStore := h.userdataStore + + data, err := store.ReadTransactionData(ctx, h.userdataStore, sessionId) + if err != nil { + return res, err + } + + customVoucherSelection, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_TRANSACTION_CUSTOM_VOUCHER_STATE) + if err == nil { + customVoucherValue, _ := strconv.ParseUint(string(customVoucherSelection), 0, 64) + if customVoucherValue == 1 { + // use the custom voucher + customTransactionVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + return res, err + } + + data.ActiveSym = customTransactionVoucher.TokenSymbol + data.ActiveDecimal = customTransactionVoucher.TokenDecimals + data.ActiveAddress = customTransactionVoucher.TokenAddress + } + } + + res.Content = l.Get( + "%s will receive %s %s from %s", + data.RecipientInput, + data.Amount, + data.ActiveSym, + sessionId, + ) + + return res, nil +} + +// InitiateNormalTransaction calls the TokenTransfer and returns a confirmation based on the result. +// used for non-swap transactions +func (h *MenuHandlers) InitiateNormalTransaction(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result var err error sessionId, ok := ctx.Value("SessionId").(string) @@ -735,6 +795,8 @@ func (h *MenuHandlers) InitiateTransaction(ctx context.Context, sym string, inpu flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") + userStore := h.userdataStore + code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) l.AddDomain("default") @@ -744,6 +806,23 @@ func (h *MenuHandlers) InitiateTransaction(ctx context.Context, sym string, inpu return res, err } + customVoucherSelection, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_TRANSACTION_CUSTOM_VOUCHER_STATE) + if err == nil { + customVoucherValue, _ := strconv.ParseUint(string(customVoucherSelection), 0, 64) + if customVoucherValue == 1 { + // use the custom voucher + customTransactionVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + return res, err + } + + data.ActiveSym = customTransactionVoucher.TokenSymbol + data.ActiveDecimal = customTransactionVoucher.TokenDecimals + data.ActiveAddress = customTransactionVoucher.TokenAddress + } + } + finalAmountStr, err := store.ParseAndScaleAmount(data.Amount, data.ActiveDecimal) if err != nil { return res, err @@ -775,7 +854,7 @@ func (h *MenuHandlers) InitiateTransaction(ctx context.Context, sym string, inpu res.Content = l.Get( "Your request has been sent. %s will receive %s %s from %s.", - data.TemporaryValue, + data.RecipientInput, data.Amount, data.ActiveSym, sessionId, @@ -807,7 +886,7 @@ func (h *MenuHandlers) TransactionSwapPreview(ctx context.Context, sym string, i userStore := h.userdataStore - recipientPhoneNumber, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_RECIPIENT_PHONE_NUMBER) + recipientInput, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_RECIPIENT_INPUT) if err != nil { // invalid state return res, err @@ -871,7 +950,7 @@ func (h *MenuHandlers) TransactionSwapPreview(ctx context.Context, sym string, i // Format the qouteAmount amount to 2 decimal places qouteAmount, _ := store.TruncateDecimalString(quoteAmountStr, 2) - // store the qouteAmount in the temporary value + // store the qouteAmount in the temporary value (display) err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(qouteAmount)) if err != nil { logg.ErrorCtxf(ctx, "failed to write temporary qouteAmount entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", qouteAmount, "error", err) @@ -887,7 +966,7 @@ func (h *MenuHandlers) TransactionSwapPreview(ctx context.Context, sym string, i res.Content = l.Get( "%s will receive %s %s", - string(recipientPhoneNumber), qouteAmount, swapData.ActiveSwapToSym, + string(recipientInput), qouteAmount, swapData.ActiveSwapToSym, ) return res, nil @@ -946,7 +1025,7 @@ func (h *MenuHandlers) TransactionInitiateSwap(ctx context.Context, sym string, logg.ErrorCtxf(ctx, "failed to read swapAmount entry with", "key", storedb.DATA_ACTIVE_SWAP_AMOUNT, "error", err) return res, err } - recipientPhoneNumber, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_RECIPIENT_PHONE_NUMBER) + recipientInput, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_RECIPIENT_INPUT) if err != nil { // invalid state return res, err @@ -974,7 +1053,7 @@ func (h *MenuHandlers) TransactionInitiateSwap(ctx context.Context, sym string, res.Content = l.Get( "Your request has been sent. %s will receive %s %s from %s.", - string(recipientPhoneNumber), + string(recipientInput), swapData.TemporaryValue, swapData.ActiveSwapToSym, sessionId, From f6c613abd6eedd8b53ec7086c13d527052f2c256 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 18 Feb 2026 17:07:38 +0300 Subject: [PATCH 098/130] rename the func to match updated functionality --- handlers/application/mpesa.go | 12 ++++++------ handlers/application/pool_deposit.go | 12 ++++++------ handlers/application/send.go | 18 +++++++++--------- handlers/application/vouchers.go | 12 ++++++------ store/vouchers.go | 8 ++++---- store/vouchers_test.go | 8 ++++---- 6 files changed, 35 insertions(+), 35 deletions(-) diff --git a/handlers/application/mpesa.go b/handlers/application/mpesa.go index d095bc1..82b63ed 100644 --- a/handlers/application/mpesa.go +++ b/handlers/application/mpesa.go @@ -51,8 +51,8 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ } // Store the active transaction voucher data (from token) - if err := store.StoreTemporaryVoucher(ctx, h.userdataStore, sessionId, metadata); err != nil { - logg.ErrorCtxf(ctx, "failed on StoreTemporaryVoucher", "error", err) + if err := store.StoreTransactionVoucher(ctx, h.userdataStore, sessionId, metadata); err != nil { + logg.ErrorCtxf(ctx, "failed on StoreTransactionVoucher", "error", err) return res, err } @@ -265,9 +265,9 @@ func (h *MenuHandlers) GetMpesaPreview(ctx context.Context, sym string, input [] } // get the selected voucher - mpesaWithdrawalVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + mpesaWithdrawalVoucher, err := store.GetTransactionVoucherData(ctx, h.userdataStore, sessionId) if err != nil { - logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + logg.ErrorCtxf(ctx, "failed on GetTransactionVoucherData", "error", err) return res, err } @@ -406,9 +406,9 @@ func (h *MenuHandlers) InitiateGetMpesa(ctx context.Context, sym string, input [ } // get the selected voucher - mpesaWithdrawalVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + mpesaWithdrawalVoucher, err := store.GetTransactionVoucherData(ctx, h.userdataStore, sessionId) if err != nil { - logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + logg.ErrorCtxf(ctx, "failed on GetTransactionVoucherData", "error", err) return res, err } diff --git a/handlers/application/pool_deposit.go b/handlers/application/pool_deposit.go index b12b5d2..16336b8 100644 --- a/handlers/application/pool_deposit.go +++ b/handlers/application/pool_deposit.go @@ -83,8 +83,8 @@ func (h *MenuHandlers) PoolDepositMaxAmount(ctx context.Context, sym string, inp } // Store the pool deposit voucher data - if err := store.StoreTemporaryVoucher(ctx, h.userdataStore, sessionId, metadata); err != nil { - logg.ErrorCtxf(ctx, "failed on StoreTemporaryVoucher", "error", err) + if err := store.StoreTransactionVoucher(ctx, h.userdataStore, sessionId, metadata); err != nil { + logg.ErrorCtxf(ctx, "failed on StoreTransactionVoucher", "error", err) return res, err } @@ -119,9 +119,9 @@ func (h *MenuHandlers) ConfirmPoolDeposit(ctx context.Context, sym string, input userStore := h.userdataStore - poolDepositVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + poolDepositVoucher, err := store.GetTransactionVoucherData(ctx, h.userdataStore, sessionId) if err != nil { - logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + logg.ErrorCtxf(ctx, "failed on GetTransactionVoucherData", "error", err) return res, err } @@ -179,9 +179,9 @@ func (h *MenuHandlers) InitiatePoolDeposit(ctx context.Context, sym string, inpu return res, err } - poolDepositVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + poolDepositVoucher, err := store.GetTransactionVoucherData(ctx, h.userdataStore, sessionId) if err != nil { - logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + logg.ErrorCtxf(ctx, "failed on GetTransactionVoucherData", "error", err) return res, err } diff --git a/handlers/application/send.go b/handlers/application/send.go index b103168..13209a2 100644 --- a/handlers/application/send.go +++ b/handlers/application/send.go @@ -357,9 +357,9 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte) customVoucherValue, _ := strconv.ParseUint(string(customVoucherSelection), 0, 64) if customVoucherValue == 1 { // use the custom voucher - customTransactionVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + customTransactionVoucher, err := store.GetTransactionVoucherData(ctx, h.userdataStore, sessionId) if err != nil { - logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + logg.ErrorCtxf(ctx, "failed on GetTransactionVoucherData", "error", err) return res, err } @@ -625,15 +625,15 @@ func (h *MenuHandlers) ValidateAmount(ctx context.Context, sym string, input []b logg.ErrorCtxf(ctx, "failed to read activeBal entry with", "key", storedb.DATA_ACTIVE_BAL, "error", err) return res, err } - + customVoucherSelection, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_TRANSACTION_CUSTOM_VOUCHER_STATE) if err == nil { customVoucherValue, _ := strconv.ParseUint(string(customVoucherSelection), 0, 64) if customVoucherValue == 1 { // use the custom voucher - customTransactionVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + customTransactionVoucher, err := store.GetTransactionVoucherData(ctx, h.userdataStore, sessionId) if err != nil { - logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + logg.ErrorCtxf(ctx, "failed on GetTransactionVoucherData", "error", err) return res, err } @@ -760,9 +760,9 @@ func (h *MenuHandlers) NormalTransactionPreview(ctx context.Context, sym string, customVoucherValue, _ := strconv.ParseUint(string(customVoucherSelection), 0, 64) if customVoucherValue == 1 { // use the custom voucher - customTransactionVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + customTransactionVoucher, err := store.GetTransactionVoucherData(ctx, h.userdataStore, sessionId) if err != nil { - logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + logg.ErrorCtxf(ctx, "failed on GetTransactionVoucherData", "error", err) return res, err } @@ -811,9 +811,9 @@ func (h *MenuHandlers) InitiateNormalTransaction(ctx context.Context, sym string customVoucherValue, _ := strconv.ParseUint(string(customVoucherSelection), 0, 64) if customVoucherValue == 1 { // use the custom voucher - customTransactionVoucher, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + customTransactionVoucher, err := store.GetTransactionVoucherData(ctx, h.userdataStore, sessionId) if err != nil { - logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + logg.ErrorCtxf(ctx, "failed on GetTransactionVoucherData", "error", err) return res, err } diff --git a/handlers/application/vouchers.go b/handlers/application/vouchers.go index 50dd86b..0828232 100644 --- a/handlers/application/vouchers.go +++ b/handlers/application/vouchers.go @@ -333,8 +333,8 @@ func (h *MenuHandlers) ViewVoucher(ctx context.Context, sym string, input []byte return res, nil } - if err := store.StoreTemporaryVoucher(ctx, h.userdataStore, sessionId, metadata); err != nil { - logg.ErrorCtxf(ctx, "failed on StoreTemporaryVoucher", "error", err) + if err := store.StoreTransactionVoucher(ctx, h.userdataStore, sessionId, metadata); err != nil { + logg.ErrorCtxf(ctx, "failed on StoreTransactionVoucher", "error", err) return res, err } @@ -362,9 +362,9 @@ func (h *MenuHandlers) SetVoucher(ctx context.Context, sym string, input []byte) } // Get temporary data - tempData, err := store.GetTemporaryVoucherData(ctx, h.userdataStore, sessionId) + tempData, err := store.GetTransactionVoucherData(ctx, h.userdataStore, sessionId) if err != nil { - logg.ErrorCtxf(ctx, "failed on GetTemporaryVoucherData", "error", err) + logg.ErrorCtxf(ctx, "failed on GetTransactionVoucherData", "error", err) return res, err } @@ -445,8 +445,8 @@ func (h *MenuHandlers) ValidateCreditVoucher(ctx context.Context, sym string, in } // Store the transaction voucher data - if err := store.StoreTemporaryVoucher(ctx, h.userdataStore, sessionId, metadata); err != nil { - logg.ErrorCtxf(ctx, "failed on StoreTemporaryVoucher", "error", err) + if err := store.StoreTransactionVoucher(ctx, h.userdataStore, sessionId, metadata); err != nil { + logg.ErrorCtxf(ctx, "failed on StoreTransactionVoucher", "error", err) return res, err } diff --git a/store/vouchers.go b/store/vouchers.go index ee4202e..dbdd326 100644 --- a/store/vouchers.go +++ b/store/vouchers.go @@ -185,8 +185,8 @@ func MatchVoucher(input, symbols, balances, decimals, addresses string) (symbol, return } -// StoreTemporaryVoucher saves voucher metadata as temporary entries in the DataStore. -func StoreTemporaryVoucher(ctx context.Context, store DataStore, sessionId string, data *dataserviceapi.TokenHoldings) error { +// StoreTransactionVoucher saves voucher metadata in the DataStore. +func StoreTransactionVoucher(ctx context.Context, store DataStore, sessionId string, data *dataserviceapi.TokenHoldings) error { tempData := fmt.Sprintf("%s,%s,%s,%s", data.TokenSymbol, data.Balance, data.TokenDecimals, data.TokenAddress) if err := store.WriteEntry(ctx, sessionId, storedb.DATA_TRANSACTION_CUSTOM_VOUCHER, []byte(tempData)); err != nil { @@ -196,8 +196,8 @@ func StoreTemporaryVoucher(ctx context.Context, store DataStore, sessionId strin return nil } -// GetTemporaryVoucherData retrieves temporary voucher metadata from the DataStore. -func GetTemporaryVoucherData(ctx context.Context, store DataStore, sessionId string) (*dataserviceapi.TokenHoldings, error) { +// GetTransactionVoucherData retrieves the transaction voucher metadata from the DataStore. +func GetTransactionVoucherData(ctx context.Context, store DataStore, sessionId string) (*dataserviceapi.TokenHoldings, error) { temp_data, err := store.ReadEntry(ctx, sessionId, storedb.DATA_TRANSACTION_CUSTOM_VOUCHER) if err != nil { return nil, err diff --git a/store/vouchers_test.go b/store/vouchers_test.go index ff756b6..ade788d 100644 --- a/store/vouchers_test.go +++ b/store/vouchers_test.go @@ -118,7 +118,7 @@ func TestStoreTemporaryVoucher(t *testing.T) { } // Execute the function being tested - err := StoreTemporaryVoucher(ctx, store, sessionId, voucherData) + err := StoreTransactionVoucher(ctx, store, sessionId, voucherData) require.NoError(t, err) // Verify stored data @@ -142,11 +142,11 @@ func TestGetTemporaryVoucherData(t *testing.T) { } // Store the data - err := StoreTemporaryVoucher(ctx, store, sessionId, tempData) + err := StoreTransactionVoucher(ctx, store, sessionId, tempData) require.NoError(t, err) // Execute the function being tested - data, err := GetTemporaryVoucherData(ctx, store, sessionId) + data, err := GetTransactionVoucherData(ctx, store, sessionId) require.NoError(t, err) require.Equal(t, tempData, data) } @@ -170,7 +170,7 @@ func TestUpdateVoucherData(t *testing.T) { TokenDecimals: "8", TokenAddress: "0xold", } - require.NoError(t, StoreTemporaryVoucher(ctx, store, sessionId, tempData)) + require.NoError(t, StoreTransactionVoucher(ctx, store, sessionId, tempData)) // Execute update err := UpdateVoucherData(ctx, store, sessionId, newData) From 6bc9247acbcb2977db30652cbc0c21c3596db9e4 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 18 Feb 2026 17:08:11 +0300 Subject: [PATCH 099/130] updated the data keys on the test to match the retrieved data --- store/tokens_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/store/tokens_test.go b/store/tokens_test.go index 34cca1e..de4a646 100644 --- a/store/tokens_test.go +++ b/store/tokens_test.go @@ -221,7 +221,7 @@ func TestReadTransactionData(t *testing.T) { // Test transaction data transactionData := map[storedb.DataTyp]string{ - storedb.DATA_TEMPORARY_VALUE: "0712345678", + storedb.DATA_RECIPIENT_INPUT: "0712345678", storedb.DATA_ACTIVE_SYM: "SRF", storedb.DATA_AMOUNT: "1000000", storedb.DATA_PUBLIC_KEY: publicKey, @@ -238,7 +238,7 @@ func TestReadTransactionData(t *testing.T) { } expectedResult := TransactionData{ - TemporaryValue: "0712345678", + RecipientInput: "0712345678", ActiveSym: "SRF", Amount: "1000000", PublicKey: publicKey, From 3ebb4611ca1bf2357f01696a42639fcbcb0000b9 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 18 Feb 2026 18:07:49 +0300 Subject: [PATCH 100/130] use the correct data keys for the credit send --- handlers/application/send.go | 71 ++++++++++++++++++++++++++++++------ 1 file changed, 60 insertions(+), 11 deletions(-) diff --git a/handlers/application/send.go b/handlers/application/send.go index 13209a2..601f940 100644 --- a/handlers/application/send.go +++ b/handlers/application/send.go @@ -886,19 +886,40 @@ func (h *MenuHandlers) TransactionSwapPreview(ctx context.Context, sym string, i userStore := h.userdataStore + // the initial recipient that the sender input recipientInput, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_RECIPIENT_INPUT) if err != nil { // invalid state return res, err } - swapData, err := store.ReadSwapPreviewData(ctx, userStore, sessionId) + // Resolve active pool + activePoolAddress, _, err := h.resolveActivePoolDetails(ctx, sessionId) if err != nil { return res, err } + // get the selected voucher + selectedVoucher, err := store.GetTransactionVoucherData(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on GetTransactionVoucherData", "error", err) + return res, err + } + + swapToVoucher, err := store.ReadSwapToVoucher(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on ReadSwapFromVoucher", "error", err) + return res, err + } + + swapMaxAmount, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_SWAP_MAX_AMOUNT) + if err != nil { + logg.ErrorCtxf(ctx, "failed to read swapMaxAmount entry with", "key", storedb.DATA_ACTIVE_SWAP_MAX_AMOUNT, "error", err) + return res, err + } + // use the stored max RAT - maxRATValue, err := strconv.ParseFloat(swapData.ActiveSwapMaxAmount, 64) + maxRATValue, err := strconv.ParseFloat(string(swapMaxAmount), 64) if err != nil { logg.ErrorCtxf(ctx, "Failed to convert the swapMaxAmount to a float", "error", err) return res, err @@ -919,13 +940,13 @@ func (h *MenuHandlers) TransactionSwapPreview(ctx context.Context, sym string, i return res, nil } - finalAmountStr, err := store.ParseAndScaleAmount(formattedAmount, swapData.ActiveSwapToDecimal) + finalAmountStr, err := store.ParseAndScaleAmount(formattedAmount, swapToVoucher.TokenDecimals) if err != nil { return res, err } // call the credit send API to get the reverse quote - r, err := h.accountService.GetCreditSendReverseQuote(ctx, swapData.ActivePoolAddress, swapData.ActiveSwapFromAddress, swapData.ActiveSwapToAddress, finalAmountStr) + r, err := h.accountService.GetCreditSendReverseQuote(ctx, string(activePoolAddress), selectedVoucher.TokenAddress, swapToVoucher.TokenAddress, finalAmountStr) if err != nil { flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error") res.FlagSet = append(res.FlagSet, flag_api_call_error) @@ -945,7 +966,7 @@ func (h *MenuHandlers) TransactionSwapPreview(ctx context.Context, sym string, i } // Scale down the quoted output amount - quoteAmountStr := store.ScaleDownBalance(sendOutputAmount, swapData.ActiveSwapToDecimal) + quoteAmountStr := store.ScaleDownBalance(sendOutputAmount, swapToVoucher.TokenDecimals) // Format the qouteAmount amount to 2 decimal places qouteAmount, _ := store.TruncateDecimalString(quoteAmountStr, 2) @@ -966,7 +987,9 @@ func (h *MenuHandlers) TransactionSwapPreview(ctx context.Context, sym string, i res.Content = l.Get( "%s will receive %s %s", - string(recipientInput), qouteAmount, swapData.ActiveSwapToSym, + string(recipientInput), + qouteAmount, + swapToVoucher.TokenSymbol, ) return res, nil @@ -990,11 +1013,37 @@ func (h *MenuHandlers) TransactionInitiateSwap(ctx context.Context, sym string, userStore := h.userdataStore - swapData, err := store.ReadSwapPreviewData(ctx, userStore, sessionId) + // Resolve active pool + activePoolAddress, _, err := h.resolveActivePoolDetails(ctx, sessionId) if err != nil { return res, err } + // get the selected voucher + selectedVoucher, err := store.GetTransactionVoucherData(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on GetTransactionVoucherData", "error", err) + return res, err + } + + publicKey, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY) + if err != nil { + logg.ErrorCtxf(ctx, "failed to read publicKey entry", "key", storedb.DATA_PUBLIC_KEY, "error", err) + return res, err + } + + swapToVoucher, err := store.ReadSwapToVoucher(ctx, h.userdataStore, sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed on ReadSwapFromVoucher", "error", err) + return res, err + } + + quotedAmount, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE) + if err != nil { + logg.ErrorCtxf(ctx, "failed to read quotedAmount entry with", "key", storedb.DATA_TEMPORARY_VALUE, "error", err) + return res, err + } + swapAmount, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_SWAP_AMOUNT) if err != nil { logg.ErrorCtxf(ctx, "failed to read swapAmount entry with", "key", storedb.DATA_ACTIVE_SWAP_AMOUNT, "error", err) @@ -1004,7 +1053,7 @@ func (h *MenuHandlers) TransactionInitiateSwap(ctx context.Context, sym string, swapAmountStr := string(swapAmount) // Call the poolSwap API - poolSwap, err := h.accountService.PoolSwap(ctx, swapAmountStr, swapData.PublicKey, swapData.ActiveSwapFromAddress, swapData.ActivePoolAddress, swapData.ActiveSwapToAddress) + poolSwap, err := h.accountService.PoolSwap(ctx, swapAmountStr, string(publicKey), selectedVoucher.TokenAddress, string(activePoolAddress), swapToVoucher.TokenAddress) if err != nil { flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error") res.FlagSet = append(res.FlagSet, flag_api_call_error) @@ -1039,7 +1088,7 @@ func (h *MenuHandlers) TransactionInitiateSwap(ctx context.Context, sym string, } // Call TokenTransfer with the expected swap amount - tokenTransfer, err := h.accountService.TokenTransfer(ctx, string(amount), swapData.PublicKey, string(recipientPublicKey), swapData.ActiveSwapToAddress) + tokenTransfer, err := h.accountService.TokenTransfer(ctx, string(amount), string(publicKey), string(recipientPublicKey), swapToVoucher.TokenAddress) if err != nil { flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error") res.FlagSet = append(res.FlagSet, flag_api_call_error) @@ -1054,8 +1103,8 @@ func (h *MenuHandlers) TransactionInitiateSwap(ctx context.Context, sym string, res.Content = l.Get( "Your request has been sent. %s will receive %s %s from %s.", string(recipientInput), - swapData.TemporaryValue, - swapData.ActiveSwapToSym, + string(quotedAmount), + swapToVoucher.TokenSymbol, sessionId, ) From 29863d385d7cba7d2b8c6ef50e2c06c49d7040c2 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 19 Feb 2026 08:43:03 +0300 Subject: [PATCH 101/130] remove unused OutputAmount --- handlers/application/send.go | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/handlers/application/send.go b/handlers/application/send.go index 99be517..b080329 100644 --- a/handlers/application/send.go +++ b/handlers/application/send.go @@ -968,21 +968,14 @@ func (h *MenuHandlers) TransactionSwapPreview(ctx context.Context, sym string, i } sendInputAmount := r.InputAmount // amount of SAT that should be swapped - sendOutputAmount := r.OutputAmount // amount of RAT that will be received // store the finalAmountStr as the final amount (that will be sent after the swap) err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_AMOUNT, []byte(finalAmountStr)) if err != nil { - logg.ErrorCtxf(ctx, "failed to write output amount value entry with", "key", storedb.DATA_AMOUNT, "value", sendOutputAmount, "error", err) + logg.ErrorCtxf(ctx, "failed to write output amount value entry with", "key", storedb.DATA_AMOUNT, "value", finalAmountStr, "error", err) return res, err } - // Scale down the quoted output amount - // quoteAmountStr := store.ScaleDownBalance(sendOutputAmount, swapData.ActiveSwapToDecimal) - - // Format the qouteAmount amount to 2 decimal places - // qouteAmount, _ := store.TruncateDecimalString(quoteAmountStr, 2) - // store the qouteAmount in the temporary value err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(inputStr)) if err != nil { From dec8fbc3f0f9b72ddb8ed72c19b4db03ba8f4d4d Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 19 Feb 2026 09:04:52 +0300 Subject: [PATCH 102/130] use the pool symbol in place of the pool name --- handlers/application/paydebt.go | 8 ++++---- handlers/application/pool_deposit.go | 8 ++++---- handlers/application/send.go | 20 ++++++++++---------- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/handlers/application/paydebt.go b/handlers/application/paydebt.go index 8172b3d..f628c3e 100644 --- a/handlers/application/paydebt.go +++ b/handlers/application/paydebt.go @@ -43,7 +43,7 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu } // Resolve active pool - activePoolAddress, activePoolName, err := h.resolveActivePoolDetails(ctx, sessionId) + activePoolAddress, activePoolSymbol, err := h.resolveActivePoolDetails(ctx, sessionId) if err != nil { res.FlagReset = append(res.FlagReset, flag_low_swap_amount, flag_api_call_error) return res, err @@ -129,7 +129,7 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu "You can remove a max of %s %s from '%s'\nEnter amount of %s:(Max: %s)", quoteStr, string(activeSym), - string(activePoolName), + string(activePoolSymbol), metadata.TokenSymbol, maxStr, ) @@ -268,7 +268,7 @@ func (h *MenuHandlers) InitiatePayDebt(ctx context.Context, sym string, input [] } // Resolve active pool - activePoolAddress, activePoolName, err := h.resolveActivePoolDetails(ctx, sessionId) + activePoolAddress, activePoolSymbol, err := h.resolveActivePoolDetails(ctx, sessionId) if err != nil { return res, err } @@ -310,7 +310,7 @@ func (h *MenuHandlers) InitiatePayDebt(ctx context.Context, sym string, input [] "Your request has been sent. You will receive an SMS when your debt of %s %s has been removed from %s.", string(debtQuotedAmount), string(activeSym), - activePoolName, + activePoolSymbol, ) res.FlagReset = append(res.FlagReset, flag_account_authorized) diff --git a/handlers/application/pool_deposit.go b/handlers/application/pool_deposit.go index 16336b8..39e0262 100644 --- a/handlers/application/pool_deposit.go +++ b/handlers/application/pool_deposit.go @@ -145,14 +145,14 @@ func (h *MenuHandlers) ConfirmPoolDeposit(ctx context.Context, sym string, input } // Resolve active pool - _, activePoolName, err := h.resolveActivePoolDetails(ctx, sessionId) + _, activePoolSymbol, err := h.resolveActivePoolDetails(ctx, sessionId) if err != nil { return res, err } res.Content = l.Get( "You will deposit %s %s into %s\n", - inputStr, poolDepositVoucher.TokenSymbol, activePoolName, + inputStr, poolDepositVoucher.TokenSymbol, activePoolSymbol, ) return res, nil @@ -174,7 +174,7 @@ func (h *MenuHandlers) InitiatePoolDeposit(ctx context.Context, sym string, inpu l.AddDomain("default") // Resolve active pool - activePoolAddress, activePoolName, err := h.resolveActivePoolDetails(ctx, sessionId) + activePoolAddress, activePoolSymbol, err := h.resolveActivePoolDetails(ctx, sessionId) if err != nil { return res, err } @@ -212,7 +212,7 @@ func (h *MenuHandlers) InitiatePoolDeposit(ctx context.Context, sym string, inpu "Your request has been sent. You will receive an SMS when %s %s has been deposited into %s.", poolDepositdata.Amount, poolDepositVoucher.TokenSymbol, - activePoolName, + activePoolSymbol, ) res.FlagReset = append(res.FlagReset, flag_account_authorized) diff --git a/handlers/application/send.go b/handlers/application/send.go index b080329..50886fe 100644 --- a/handlers/application/send.go +++ b/handlers/application/send.go @@ -530,7 +530,7 @@ func (h *MenuHandlers) getRecipientData(ctx context.Context, sessionId string) ( return } -func (h *MenuHandlers) resolveActivePoolDetails(ctx context.Context, sessionId string) (defaultPoolAddress, defaultPoolName []byte, err error) { +func (h *MenuHandlers) resolveActivePoolDetails(ctx context.Context, sessionId string) (defaultPoolAddress, defaultPoolSymbol []byte, err error) { store := h.userdataStore // Try read address @@ -540,21 +540,21 @@ func (h *MenuHandlers) resolveActivePoolDetails(ctx context.Context, sessionId s return nil, nil, err } - // Try read name - defaultPoolName, err = store.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_POOL_NAME) + // Try read symbol + defaultPoolSymbol, err = store.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_POOL_SYM) if err != nil && !db.IsNotFound(err) { logg.ErrorCtxf(ctx, "failed to read active pool name", "error", err) return nil, nil, err } // If both exist, return them - if defaultPoolAddress != nil && defaultPoolName != nil { - return defaultPoolAddress, defaultPoolName, nil + if defaultPoolAddress != nil && defaultPoolSymbol != nil { + return defaultPoolAddress, defaultPoolSymbol, nil } // Fallback to config defaults defaultPoolAddress = []byte(config.DefaultPoolAddress()) - defaultPoolName = []byte(config.DefaultPoolName()) + defaultPoolSymbol = []byte(config.DefaultPoolSymbol()) if err := store.WriteEntry( ctx, @@ -569,14 +569,14 @@ func (h *MenuHandlers) resolveActivePoolDetails(ctx context.Context, sessionId s if err := store.WriteEntry( ctx, sessionId, - storedb.DATA_ACTIVE_POOL_NAME, - defaultPoolName, + storedb.DATA_ACTIVE_POOL_SYM, + defaultPoolSymbol, ); err != nil { - logg.ErrorCtxf(ctx, "failed to write default pool name", "error", err) + logg.ErrorCtxf(ctx, "failed to write default pool symbol", "error", err) return nil, nil, err } - return defaultPoolAddress, defaultPoolName, nil + return defaultPoolAddress, defaultPoolSymbol, nil } func (h *MenuHandlers) calculateSendCreditLimits(ctx context.Context, poolAddress, fromAddress, toAddress, publicKey, fromDecimal, toDecimal []byte) (string, string, error) { From 0ef706a47e0917fcc942c69c42e944bfde501db7 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 19 Feb 2026 09:15:09 +0300 Subject: [PATCH 103/130] include the word pool and update the translation --- handlers/application/paydebt.go | 2 +- services/registration/locale/swa/default.po | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/handlers/application/paydebt.go b/handlers/application/paydebt.go index f628c3e..2f952ab 100644 --- a/handlers/application/paydebt.go +++ b/handlers/application/paydebt.go @@ -126,7 +126,7 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu 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)", + "You can remove a max of %s %s from '%s' pool\nEnter amount of %s:(Max: %s)", quoteStr, string(activeSym), string(activePoolSymbol), diff --git a/services/registration/locale/swa/default.po b/services/registration/locale/swa/default.po index 3dd4c23..4bb0c58 100644 --- a/services/registration/locale/swa/default.po +++ b/services/registration/locale/swa/default.po @@ -73,8 +73,8 @@ msgstr "Utapokea kidokezo cha PIN yako ya M-Pesa hivi karibuni kutuma %s ksh na msgid "Your request has been sent. Thank you for using Sarafu" msgstr "Ombi lako limetumwa. Asante kwa kutumia huduma ya Sarafu" -msgid "You can remove a maximum of %s %s from '%s' pool\n\nEnter amount of %s:" -msgstr "Unaweza kuondoa kiwango cha juu cha %s %s kutoka kwenye '%s'\n\nWeka kiwango cha %s:" +msgid "You can remove a max of %s %s from '%s' pool\nEnter amount of %s:(Max: %s)" +msgstr "Unaweza kuondoa kiwango cha juu cha %s %s kutoka kwenye '%s'\n\nWeka kiwango cha %s:(Kikomo: %s)" msgid "Please confirm that you will use %s %s to remove your debt of %s %s\n" msgstr "Tafadhali thibitisha kwamba utatumia %s %s kulipa deni lako la %s %s.\nWeka PIN yako:" From cdd83dfd73cf4bb9b6ec8df8658784c15165a0e7 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 19 Feb 2026 19:36:23 +0300 Subject: [PATCH 104/130] update the credit and debt calculations --- handlers/application/balance.go | 70 ++++++++++++++++++++++----------- 1 file changed, 48 insertions(+), 22 deletions(-) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index 9011f58..ba548fe 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -128,10 +128,8 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i return res, nil } - // default response - formattedDebt, _ := store.TruncateDecimalString(string(activeBal), 2) + // default flag reset res.FlagReset = append(res.FlagReset, flag_api_call_error) - res.Content = l.Get("Credit: %s KSH\nDebt: %s %s\n", "0", formattedDebt, string(activeSym)) // Resolve active pool activePoolAddress, _, err := h.resolveActivePoolDetails(ctx, sessionId) @@ -143,6 +141,7 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i swappableVouchers, err := h.accountService.GetPoolSwappableFromVouchers(ctx, string(activePoolAddress), string(publicKey)) if err != nil { logg.ErrorCtxf(ctx, "failed on GetPoolSwappableFromVouchers", "error", err) + res.Content = l.Get("Credit: %s KSH\nDebt: %s %s\n", "0", "0", string(activeSym)) return res, nil } @@ -208,30 +207,42 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i } // Credit calculation: How much Active Token that can be swapped for a stable coin - // + any stables sendable to Pretium (in KSH value) + // that's on the pool + any stables sendable to Pretium (in KSH value) + + // Find first stable voucher from swappableVouchers + var firstStable *dataserviceapi.TokenHoldings + for i := range swappableVouchers { + if isStableVoucher(swappableVouchers[i].TokenAddress) { + firstStable = &swappableVouchers[i] + break + } + } + scaledCredit := "0" - finalAmountStr, err := store.ParseAndScaleAmount(string(activeBal), string(activeDecimal)) - if err != nil { - return res, err - } - // do a swap quote for default stable coin from active voucher - stableAddress := config.DefaultStableVoucherAddress() - stableDecimals := config.DefaultStableVoucherDecimals() + if firstStable != nil { + finalAmountStr, err := store.ParseAndScaleAmount(string(activeBal), string(activeDecimal)) + if err != nil { + logg.ErrorCtxf(ctx, "failed on ParseAndScaleAmount", "error", err) + return res, err + } - r, err := h.accountService.GetPoolSwapQuote(ctx, finalAmountStr, string(publicKey), string(activeAddress), string(activePoolAddress), stableAddress) - 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 + // swap active -> FIRST stable from pool list + r, err := h.accountService.GetPoolSwapQuote(ctx, finalAmountStr, string(publicKey), string(activeAddress), string(activePoolAddress), firstStable.TokenAddress) + 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 using REAL stable decimals + finalQuote := store.ScaleDownBalance(r.OutValue, firstStable.TokenDecimals) + scaledCredit = store.AddDecimalStrings(scaledCredit, finalQuote) } - finalQuote := store.ScaleDownBalance(r.OutValue, stableDecimals) - - scaledCredit = store.AddDecimalStrings(scaledCredit, finalQuote) - + // Add existing stable balances for _, v := range stable { scaled := store.ScaleDownBalance(v.Balance, v.TokenDecimals) scaledCredit = store.AddDecimalStrings(scaledCredit, scaled) @@ -239,6 +250,21 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i // DEBT calculation: All outstanding active token that is in the current pool // (how much of AT that is in the active Pool) + scaledDebt := "0" + + // If active voucher is NOT stable, + // check if it exists in swappableVouchers + if !isStableVoucher(string(activeAddress)) { + for _, v := range swappableVouchers { + if v.TokenSymbol == string(activeSym) { + scaledDebt = store.ScaleDownBalance(v.Balance, v.TokenDecimals) + break + } + } + } + + // Format (2 decimal places) + formattedDebt, _ := store.TruncateDecimalString(scaledDebt, 2) // Fetch MPESA rates rates, err := h.accountService.GetMpesaOnrampRates(ctx) From 2e48fbad00d2834010be37d7c58751f3024dc6a1 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 19 Feb 2026 19:51:50 +0300 Subject: [PATCH 105/130] update the vis files to CATCH the low amount flag --- services/registration/low_pay_debt_amount | 2 +- services/registration/low_pay_debt_amount.vis | 3 ++- services/registration/low_pay_debt_amount_swa | 2 +- services/registration/pay_debt.vis | 1 + 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/services/registration/low_pay_debt_amount b/services/registration/low_pay_debt_amount index 56f14ae..5f35bf4 100644 --- a/services/registration/low_pay_debt_amount +++ b/services/registration/low_pay_debt_amount @@ -1 +1 @@ -You have a low debt amount \ No newline at end of file +Available amount {{.calculate_max_pay_debt}} is too low, please choose a different voucher: \ No newline at end of file diff --git a/services/registration/low_pay_debt_amount.vis b/services/registration/low_pay_debt_amount.vis index 832ef22..77149bc 100644 --- a/services/registration/low_pay_debt_amount.vis +++ b/services/registration/low_pay_debt_amount.vis @@ -1,5 +1,6 @@ +MAP calculate_max_pay_debt MOUT back 0 MOUT quit 9 HALT -INCMP ^ 0 +INCMP _ 0 INCMP quit 9 diff --git a/services/registration/low_pay_debt_amount_swa b/services/registration/low_pay_debt_amount_swa index 26fcfc0..02658f1 100644 --- a/services/registration/low_pay_debt_amount_swa +++ b/services/registration/low_pay_debt_amount_swa @@ -1 +1 @@ -Kiasi cha deni lako ni cha chini sana \ No newline at end of file +Kiasi kinachopatikana {{.calculate_max_pay_debt}} ni cha chini sana, tafadhali chagua sarafu tofauti: \ No newline at end of file diff --git a/services/registration/pay_debt.vis b/services/registration/pay_debt.vis index 9cf8b87..acfee9f 100644 --- a/services/registration/pay_debt.vis +++ b/services/registration/pay_debt.vis @@ -12,5 +12,6 @@ INCMP _ 0 INCMP quit 99 LOAD calculate_max_pay_debt 0 RELOAD calculate_max_pay_debt +CATCH low_pay_debt_amount flag_low_swap_amount 1 CATCH . flag_incorrect_voucher 1 INCMP calculate_max_pay_debt * From 02802111976293aff9a234cdb56d925b656e8efa Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 19 Feb 2026 20:01:58 +0300 Subject: [PATCH 106/130] set a default value of 0 on an API error --- handlers/application/paydebt.go | 1 + 1 file changed, 1 insertion(+) diff --git a/handlers/application/paydebt.go b/handlers/application/paydebt.go index 2f952ab..21dd5d1 100644 --- a/handlers/application/paydebt.go +++ b/handlers/application/paydebt.go @@ -64,6 +64,7 @@ func (h *MenuHandlers) CalculateMaxPayDebt(ctx context.Context, sym string, inpu r, err := h.accountService.GetSwapFromTokenMaxLimit(ctx, string(activePoolAddress), metadata.TokenAddress, string(activeAddress), string(publicKey)) if err != nil { res.FlagSet = append(res.FlagSet, flag_api_call_error) + res.Content = "0" logg.ErrorCtxf(ctx, "failed on GetSwapFromTokenMaxLimit", "error", err) return res, nil } From 29cc4c63ebd249dc45af6316be3bd306460666c5 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 19 Feb 2026 20:02:44 +0300 Subject: [PATCH 107/130] correctly CATCH error flags --- services/registration/pay_debt.vis | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/registration/pay_debt.vis b/services/registration/pay_debt.vis index acfee9f..ec65fc9 100644 --- a/services/registration/pay_debt.vis +++ b/services/registration/pay_debt.vis @@ -12,6 +12,7 @@ INCMP _ 0 INCMP quit 99 LOAD calculate_max_pay_debt 0 RELOAD calculate_max_pay_debt -CATCH low_pay_debt_amount flag_low_swap_amount 1 CATCH . flag_incorrect_voucher 1 +CATCH low_pay_debt_amount flag_low_swap_amount 1 +CATCH low_pay_debt_amount flag_api_call_error 1 INCMP calculate_max_pay_debt * From 3595ff0d61bc34c0c501c5b748badca7520657da Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 19 Feb 2026 20:08:57 +0300 Subject: [PATCH 108/130] include the active symbol in the displayed limit --- handlers/application/poolswap.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/handlers/application/poolswap.go b/handlers/application/poolswap.go index 1c6f923..3b9b1a3 100644 --- a/handlers/application/poolswap.go +++ b/handlers/application/poolswap.go @@ -236,8 +236,8 @@ func (h *MenuHandlers) SwapMaxLimit(ctx context.Context, sym string, input []byt } res.Content = fmt.Sprintf( - "Maximum: %s\n\nEnter amount of %s to swap for %s:", - maxStr, swapData.ActiveSwapFromSym, swapData.ActiveSwapToSym, + "Maximum: %s %s\n\nEnter amount of %s to swap for %s:", + maxStr, swapData.ActiveSwapFromSym, swapData.ActiveSwapFromSym, swapData.ActiveSwapToSym, ) return res, nil From 320d10890c628d0420184fbc29d1b64e60b8dcb8 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Thu, 19 Feb 2026 20:09:24 +0300 Subject: [PATCH 109/130] improve the error message when one has a low swap amount --- services/registration/low_swap_amount | 2 +- services/registration/low_swap_amount_swa | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/registration/low_swap_amount b/services/registration/low_swap_amount index d3e50f7..397f5c8 100644 --- a/services/registration/low_swap_amount +++ b/services/registration/low_swap_amount @@ -1 +1 @@ -Available amount {{.swap_max_limit}} is too low, please try again: \ No newline at end of file +Available amount {{.swap_max_limit}} is too low, please choose a different voucher: \ No newline at end of file diff --git a/services/registration/low_swap_amount_swa b/services/registration/low_swap_amount_swa index 2d11dd9..3108a8f 100644 --- a/services/registration/low_swap_amount_swa +++ b/services/registration/low_swap_amount_swa @@ -1 +1 @@ -Kiasi kinachopatikana {{.swap_max_limit}} ni cha chini sana, tafadhali jaribu tena: \ No newline at end of file +Kiasi kinachopatikana {{.swap_max_limit}} ni cha chini sana, tafadhali chagua sarafu tofauti: \ No newline at end of file From 3108cb2f22341de007c1698703fa77662aea4740 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 20 Feb 2026 09:34:58 +0300 Subject: [PATCH 110/130] set a default content of 0 if rates are not found for the selected voucher --- handlers/application/mpesa.go | 1 + 1 file changed, 1 insertion(+) diff --git a/handlers/application/mpesa.go b/handlers/application/mpesa.go index 82b63ed..a4ac4a7 100644 --- a/handlers/application/mpesa.go +++ b/handlers/application/mpesa.go @@ -149,6 +149,7 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ _, maxRAT, err := h.calculateSendCreditLimits(ctx, activePoolAddress, []byte(metadata.TokenAddress), recipientActiveAddress, publicKey, []byte(metadata.TokenDecimals), recipientActiveDecimal) if err != nil { res.FlagSet = append(res.FlagSet, flag_api_call_error) + res.Content = "0" logg.ErrorCtxf(ctx, "failed on calculateSendCreditLimits", "error", err) return res, nil } From bfef77e20eca9570d287c366231234abd32fe45b Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 20 Feb 2026 09:41:03 +0300 Subject: [PATCH 111/130] add a CATCH for low amounts and API errors --- services/registration/get_mpesa.vis | 5 ++++- services/registration/low_withdraw_mpesa_amount | 1 + services/registration/low_withdraw_mpesa_amount.vis | 6 ++++++ services/registration/low_withdraw_mpesa_amount_swa | 1 + 4 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 services/registration/low_withdraw_mpesa_amount create mode 100644 services/registration/low_withdraw_mpesa_amount.vis create mode 100644 services/registration/low_withdraw_mpesa_amount_swa diff --git a/services/registration/get_mpesa.vis b/services/registration/get_mpesa.vis index f9a9b42..2e595e4 100644 --- a/services/registration/get_mpesa.vis +++ b/services/registration/get_mpesa.vis @@ -10,6 +10,9 @@ INCMP > 88 INCMP < 98 INCMP _ 0 INCMP quit 99 -LOAD get_mpesa_max_limit 0 +LOAD get_mpesa_max_limit 89 RELOAD get_mpesa_max_limit +CATCH . flag_incorrect_voucher 1 +CATCH low_withdraw_mpesa_amount flag_low_swap_amount 1 +CATCH low_withdraw_mpesa_amount flag_api_call_error 1 INCMP mpesa_max_limit * diff --git a/services/registration/low_withdraw_mpesa_amount b/services/registration/low_withdraw_mpesa_amount new file mode 100644 index 0000000..6837aab --- /dev/null +++ b/services/registration/low_withdraw_mpesa_amount @@ -0,0 +1 @@ +Available amount {{.get_mpesa_max_limit}} is too low, please choose a different voucher: \ No newline at end of file diff --git a/services/registration/low_withdraw_mpesa_amount.vis b/services/registration/low_withdraw_mpesa_amount.vis new file mode 100644 index 0000000..d9cd485 --- /dev/null +++ b/services/registration/low_withdraw_mpesa_amount.vis @@ -0,0 +1,6 @@ +MAP get_mpesa_max_limit +MOUT back 0 +MOUT quit 9 +HALT +INCMP _ 0 +INCMP quit 9 diff --git a/services/registration/low_withdraw_mpesa_amount_swa b/services/registration/low_withdraw_mpesa_amount_swa new file mode 100644 index 0000000..4de665d --- /dev/null +++ b/services/registration/low_withdraw_mpesa_amount_swa @@ -0,0 +1 @@ +Kiasi kinachopatikana {{.get_mpesa_max_limit}} ni cha chini sana, tafadhali chagua sarafu tofauti: \ No newline at end of file From 9646cc29557aaa4800039725f1d27a4f5a4c2d6c Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 20 Feb 2026 09:48:10 +0300 Subject: [PATCH 112/130] add a CATCH when one cannot swap from the current pool --- handlers/application/mpesa.go | 5 ++++- services/registration/get_mpesa.vis | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/handlers/application/mpesa.go b/handlers/application/mpesa.go index a4ac4a7..a497d65 100644 --- a/handlers/application/mpesa.go +++ b/handlers/application/mpesa.go @@ -36,7 +36,7 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ inputStr := string(input) if inputStr == "0" || inputStr == "99" || inputStr == "88" || inputStr == "98" { - res.FlagReset = append(res.FlagReset, flag_low_swap_amount, flag_api_call_error, flag_incorrect_voucher) + res.FlagReset = append(res.FlagReset, flag_low_swap_amount, flag_api_call_error, flag_incorrect_voucher, flag_incorrect_pool) return res, nil } @@ -142,6 +142,7 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ if !canSwap.CanSwapFrom { // pool issue (CATCH on .vis) res.FlagSet = append(res.FlagSet, flag_incorrect_pool) + res.Content = "0" return res, nil } @@ -199,6 +200,8 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ maxKshFormatted, ) + res.FlagReset = append(res.FlagReset, flag_low_swap_amount, flag_api_call_error, flag_incorrect_voucher, flag_incorrect_pool) + return res, nil } diff --git a/services/registration/get_mpesa.vis b/services/registration/get_mpesa.vis index 2e595e4..a30204d 100644 --- a/services/registration/get_mpesa.vis +++ b/services/registration/get_mpesa.vis @@ -13,6 +13,7 @@ INCMP quit 99 LOAD get_mpesa_max_limit 89 RELOAD get_mpesa_max_limit CATCH . flag_incorrect_voucher 1 +CATCH low_withdraw_mpesa_amount flag_incorrect_pool 1 CATCH low_withdraw_mpesa_amount flag_low_swap_amount 1 CATCH low_withdraw_mpesa_amount flag_api_call_error 1 INCMP mpesa_max_limit * From f948f7f27ed19132d9fd8fb2de5cd2b59c51ef62 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 20 Feb 2026 09:54:21 +0300 Subject: [PATCH 113/130] remove the amount multiplication by 1.015 --- handlers/application/send.go | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/handlers/application/send.go b/handlers/application/send.go index 50886fe..9430709 100644 --- a/handlers/application/send.go +++ b/handlers/application/send.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "math/big" "strconv" "strings" "time" @@ -946,19 +945,8 @@ func (h *MenuHandlers) TransactionSwapPreview(ctx context.Context, sym string, i return res, err } - // multiply by 1.015 (i.e. * 1015 / 1000) - amountInt, ok := new(big.Int).SetString(finalAmountStr, 10) - if !ok { - return res, fmt.Errorf("invalid amount: %s", finalAmountStr) - } - - amountInt.Mul(amountInt, big.NewInt(1015)) - amountInt.Div(amountInt, big.NewInt(1000)) - - scaledFinalAmountStr := amountInt.String() - // call the credit send API to get the reverse quote - r, err := h.accountService.GetCreditSendReverseQuote(ctx, string(activePoolAddress), selectedVoucher.TokenAddress, swapToVoucher.TokenAddress, scaledFinalAmountStr) + r, err := h.accountService.GetCreditSendReverseQuote(ctx, string(activePoolAddress), selectedVoucher.TokenAddress, swapToVoucher.TokenAddress, finalAmountStr) if err != nil { flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error") res.FlagSet = append(res.FlagSet, flag_api_call_error) @@ -967,7 +955,7 @@ func (h *MenuHandlers) TransactionSwapPreview(ctx context.Context, sym string, i return res, nil } - sendInputAmount := r.InputAmount // amount of SAT that should be swapped + sendInputAmount := r.InputAmount // amount of SAT that should be swapped // store the finalAmountStr as the final amount (that will be sent after the swap) err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_AMOUNT, []byte(finalAmountStr)) From 6553c5a7731848441233a3bc4b5bed0e70471f7a Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 20 Feb 2026 13:16:23 +0300 Subject: [PATCH 114/130] added error logs and read data keys directly --- handlers/application/pool_deposit.go | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/handlers/application/pool_deposit.go b/handlers/application/pool_deposit.go index 39e0262..e71fcac 100644 --- a/handlers/application/pool_deposit.go +++ b/handlers/application/pool_deposit.go @@ -173,9 +173,12 @@ func (h *MenuHandlers) InitiatePoolDeposit(ctx context.Context, sym string, inpu l := gotext.NewLocale(translationDir, code) l.AddDomain("default") + userStore := h.userdataStore + // Resolve active pool activePoolAddress, activePoolSymbol, err := h.resolveActivePoolDetails(ctx, sessionId) if err != nil { + logg.ErrorCtxf(ctx, "failed on resolveActivePoolDetails", "error", err) return res, err } @@ -185,18 +188,26 @@ func (h *MenuHandlers) InitiatePoolDeposit(ctx context.Context, sym string, inpu return res, err } - poolDepositdata, err := store.ReadTransactionData(ctx, h.userdataStore, sessionId) + publicKey, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY) if err != nil { + logg.ErrorCtxf(ctx, "failed to read publicKey entry", "key", storedb.DATA_PUBLIC_KEY, "error", err) return res, err } - finalAmountStr, err := store.ParseAndScaleAmount(poolDepositdata.Amount, poolDepositVoucher.TokenDecimals) + amount, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_AMOUNT) if err != nil { + logg.ErrorCtxf(ctx, "failed to read amount entry", "key", storedb.DATA_AMOUNT, "error", err) + return res, err + } + + finalAmountStr, err := store.ParseAndScaleAmount(string(amount), poolDepositVoucher.TokenDecimals) + if err != nil { + logg.ErrorCtxf(ctx, "failed on ParseAndScaleAmount", "error", err) return res, err } // Call pool deposit API - r, err := h.accountService.PoolDeposit(ctx, finalAmountStr, poolDepositdata.PublicKey, string(activePoolAddress), poolDepositVoucher.TokenAddress) + r, err := h.accountService.PoolDeposit(ctx, finalAmountStr, string(publicKey), string(activePoolAddress), poolDepositVoucher.TokenAddress) if err != nil { flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error") res.FlagSet = append(res.FlagSet, flag_api_call_error) @@ -210,7 +221,7 @@ func (h *MenuHandlers) InitiatePoolDeposit(ctx context.Context, sym string, inpu res.Content = l.Get( "Your request has been sent. You will receive an SMS when %s %s has been deposited into %s.", - poolDepositdata.Amount, + string(amount), poolDepositVoucher.TokenSymbol, activePoolSymbol, ) From 9e93bb4b591f487c7d64b7f988f2521483c1b9f0 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 20 Feb 2026 13:25:39 +0300 Subject: [PATCH 115/130] revert to a normal transaction of the recipient phone number is not present --- handlers/application/send.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/handlers/application/send.go b/handlers/application/send.go index 9430709..1a322bc 100644 --- a/handlers/application/send.go +++ b/handlers/application/send.go @@ -414,12 +414,15 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte) return res, nil } - // Get the recipient's phone number to read other data items + // Get the recipient's phone number to read other data items (*) recipientPhoneNumber, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_RECIPIENT_PHONE_NUMBER) if err != nil { - // invalid state - return res, err + // revert to normal transaction + res.FlagReset = append(res.FlagReset, flag_swap_transaction) + res.Content = l.Get("Maximum amount: %s %s\nEnter amount:", formattedBalance, string(activeSym)) + return res, nil } + recipientActiveSym, recipientActiveAddress, recipientActiveDecimal, err := h.getRecipientData(ctx, string(recipientPhoneNumber)) if err != nil { return res, err From 301d4f4232ce272cd3301d77086e73d18ba61b15 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 20 Feb 2026 13:28:29 +0300 Subject: [PATCH 116/130] add debug statements --- handlers/application/send.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/handlers/application/send.go b/handlers/application/send.go index 1a322bc..b2273e1 100644 --- a/handlers/application/send.go +++ b/handlers/application/send.go @@ -414,6 +414,8 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte) return res, nil } + fmt.Println("got 2") + // Get the recipient's phone number to read other data items (*) recipientPhoneNumber, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_RECIPIENT_PHONE_NUMBER) if err != nil { @@ -423,10 +425,14 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte) return res, nil } + fmt.Println("got 3") + recipientActiveSym, recipientActiveAddress, recipientActiveDecimal, err := h.getRecipientData(ctx, string(recipientPhoneNumber)) if err != nil { return res, err } + fmt.Println("got 4") + // retrieve the max credit send amounts maxSAT, maxRAT, err := h.calculateSendCreditLimits(ctx, activePoolAddress, activeAddress, recipientActiveAddress, publicKey, activeDecimal, recipientActiveDecimal) From e5b9a8955da324b824148a1feda763af92c4eaa2 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 20 Feb 2026 13:30:21 +0300 Subject: [PATCH 117/130] include the retrieved phone number --- handlers/application/send.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/handlers/application/send.go b/handlers/application/send.go index b2273e1..aef8095 100644 --- a/handlers/application/send.go +++ b/handlers/application/send.go @@ -425,7 +425,7 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte) return res, nil } - fmt.Println("got 3") + fmt.Println("got 3:", string(recipientPhoneNumber)) recipientActiveSym, recipientActiveAddress, recipientActiveDecimal, err := h.getRecipientData(ctx, string(recipientPhoneNumber)) if err != nil { From a2e2c0d68e03ff93047814faf828531311d9c6a9 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 20 Feb 2026 13:33:43 +0300 Subject: [PATCH 118/130] ensure the number is valid --- handlers/application/send.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/handlers/application/send.go b/handlers/application/send.go index aef8095..e59ad22 100644 --- a/handlers/application/send.go +++ b/handlers/application/send.go @@ -418,7 +418,7 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte) // Get the recipient's phone number to read other data items (*) recipientPhoneNumber, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_RECIPIENT_PHONE_NUMBER) - if err != nil { + if err != nil || !phone.IsValidPhoneNumber(string(recipientPhoneNumber)) { // revert to normal transaction res.FlagReset = append(res.FlagReset, flag_swap_transaction) res.Content = l.Get("Maximum amount: %s %s\nEnter amount:", formattedBalance, string(activeSym)) From 3bfa9820dd6f774ba0c819574124906a4a6eefd3 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 20 Feb 2026 13:35:28 +0300 Subject: [PATCH 119/130] remove debug statements --- handlers/application/send.go | 6 ------ 1 file changed, 6 deletions(-) diff --git a/handlers/application/send.go b/handlers/application/send.go index e59ad22..86a4e4a 100644 --- a/handlers/application/send.go +++ b/handlers/application/send.go @@ -414,8 +414,6 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte) return res, nil } - fmt.Println("got 2") - // Get the recipient's phone number to read other data items (*) recipientPhoneNumber, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_RECIPIENT_PHONE_NUMBER) if err != nil || !phone.IsValidPhoneNumber(string(recipientPhoneNumber)) { @@ -425,14 +423,10 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte) return res, nil } - fmt.Println("got 3:", string(recipientPhoneNumber)) - recipientActiveSym, recipientActiveAddress, recipientActiveDecimal, err := h.getRecipientData(ctx, string(recipientPhoneNumber)) if err != nil { return res, err } - fmt.Println("got 4") - // retrieve the max credit send amounts maxSAT, maxRAT, err := h.calculateSendCreditLimits(ctx, activePoolAddress, activeAddress, recipientActiveAddress, publicKey, activeDecimal, recipientActiveDecimal) From 6e426bf6a0b5f7ea1336a19c75e707975b777ece Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 23 Feb 2026 11:05:43 +0300 Subject: [PATCH 120/130] return a default credit and debt response when one doesn't have a voucher --- handlers/application/balance.go | 1 + 1 file changed, 1 insertion(+) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index ba548fe..409d409 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -125,6 +125,7 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i // Fetch session data _, activeBal, activeSym, activeAddress, publicKey, activeDecimal, err := h.getSessionData(ctx, sessionId) if err != nil { + res.Content = l.Get("Credit: %s KSH\nDebt: %s %s\n", "0", "0", string(activeSym)) return res, nil } From f198ecd913fccbf841f2991e123281128d214108 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 23 Feb 2026 16:11:19 +0300 Subject: [PATCH 121/130] have different syms to customize the final output when one has a single voucher --- handlers/application/vouchers.go | 28 +++++++++------------------- handlers/local.go | 3 ++- 2 files changed, 11 insertions(+), 20 deletions(-) diff --git a/handlers/application/vouchers.go b/handlers/application/vouchers.go index 0828232..435615d 100644 --- a/handlers/application/vouchers.go +++ b/handlers/application/vouchers.go @@ -17,8 +17,8 @@ import ( // ManageVouchers retrieves the token holdings from the API using the "PublicKey" and // 1. sets the first as the default voucher if no active voucher is set. -// 2. Stores list of vouchers -// 3. Stores list of filtered stable vouchers +// 2. Stores list of filtered ordered vouchers (exclude the active voucher) +// 3. Stores list of ordered vouchers (all vouchers) // 4. updates the balance of the active voucher func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result @@ -32,7 +32,6 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b flag_no_active_voucher, _ := h.flagManager.GetFlag("flag_no_active_voucher") flag_api_error, _ := h.flagManager.GetFlag("flag_api_call_error") - flag_no_stable_vouchers, _ := h.flagManager.GetFlag("flag_no_stable_vouchers") flag_multiple_voucher, _ := h.flagManager.GetFlag("flag_multiple_voucher") publicKey, err := userStore.ReadEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY) @@ -216,21 +215,6 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b // Order all vouchers orderedVouchers := orderVouchers(vouchersResp) - // Stable voucher presence flag (based on full list) - hasStable := false - for _, v := range orderedVouchers { - if isStableVoucher(v.TokenAddress) { - hasStable = true - break - } - } - - if !hasStable { - res.FlagSet = append(res.FlagSet, flag_no_stable_vouchers) - } else { - res.FlagReset = append(res.FlagReset, flag_no_stable_vouchers) - } - // Process ALL vouchers (stable first) orderedVoucherData := store.ProcessVouchers(orderedVouchers) @@ -253,6 +237,7 @@ func (h *MenuHandlers) ManageVouchers(ctx context.Context, sym string, input []b } // GetVoucherList fetches the list of vouchers from the store and formats them. +// does not include the active voucher and is used in select_voucher and pay_debt func (h *MenuHandlers) GetVoucherList(ctx context.Context, sym string, input []byte) (resource.Result, error) { var res resource.Result sessionId, ok := ctx.Value("SessionId").(string) @@ -281,7 +266,12 @@ func (h *MenuHandlers) GetVoucherList(ctx context.Context, sym string, input []b } if len(voucherData) == 0 { - res.Content = l.Get("Your active voucher %s is already set", string(activeSym)) + if sym == "get_paydebt_voucher_list" { + res.Content = l.Get("You need another voucher to proceed. Only found %s", string(activeSym)) + } else { + res.Content = l.Get("Your active voucher %s is already set", string(activeSym)) + } + return res, nil } diff --git a/handlers/local.go b/handlers/local.go index 2ee3ae5..c4a2564 100644 --- a/handlers/local.go +++ b/handlers/local.go @@ -111,7 +111,8 @@ func (ls *LocalHandlerService) GetHandler(accountService remote.AccountService) ls.DbRs.AddLocalFunc("quit_with_help", appHandlers.QuitWithHelp) ls.DbRs.AddLocalFunc("fetch_community_balance", appHandlers.FetchCommunityBalance) ls.DbRs.AddLocalFunc("manage_vouchers", appHandlers.ManageVouchers) - ls.DbRs.AddLocalFunc("get_vouchers", appHandlers.GetVoucherList) + ls.DbRs.AddLocalFunc("get_voucher_list", appHandlers.GetVoucherList) + ls.DbRs.AddLocalFunc("get_paydebt_voucher_list", appHandlers.GetVoucherList) ls.DbRs.AddLocalFunc("view_voucher", appHandlers.ViewVoucher) ls.DbRs.AddLocalFunc("set_voucher", appHandlers.SetVoucher) ls.DbRs.AddLocalFunc("get_voucher_details", appHandlers.GetVoucherDetails) From 62eb132b325c34883e056fe741c52bf1b1a5301d Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 23 Feb 2026 16:14:31 +0300 Subject: [PATCH 122/130] add a translation for the pay debt menu --- handlers/application/vouchers.go | 2 +- services/registration/locale/swa/default.po | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/handlers/application/vouchers.go b/handlers/application/vouchers.go index 435615d..2f9d335 100644 --- a/handlers/application/vouchers.go +++ b/handlers/application/vouchers.go @@ -267,7 +267,7 @@ func (h *MenuHandlers) GetVoucherList(ctx context.Context, sym string, input []b if len(voucherData) == 0 { if sym == "get_paydebt_voucher_list" { - res.Content = l.Get("You need another voucher to proceed. Only found %s", string(activeSym)) + res.Content = l.Get("You need another voucher to proceed. Only found %s.", string(activeSym)) } else { res.Content = l.Get("Your active voucher %s is already set", string(activeSym)) } diff --git a/services/registration/locale/swa/default.po b/services/registration/locale/swa/default.po index 4bb0c58..9af2a3a 100644 --- a/services/registration/locale/swa/default.po +++ b/services/registration/locale/swa/default.po @@ -92,4 +92,7 @@ msgid "Your request has been sent. You will receive an SMS when %s %s has been d msgstr "Ombi lako limetumwa. Utapokea ujumbe wakati %s %s itawekwa kwenye %s." msgid "%s will receive %s %s from %s" -msgstr %s atapokea %s %s kutoka kwa %s" \ No newline at end of file +msgstr %s atapokea %s %s kutoka kwa %s" + +msgid "You need another voucher to proceed. Only found %s." +msgstr "Unahitaji kua na sarafu nyingine. Tumepata tu %s." \ No newline at end of file From a27007900877d8d847b7aeff5a7374f08142a3b6 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 23 Feb 2026 16:15:12 +0300 Subject: [PATCH 123/130] add a fix for when users input a value when no vouchers exist --- store/vouchers.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/store/vouchers.go b/store/vouchers.go index dbdd326..8155e9b 100644 --- a/store/vouchers.go +++ b/store/vouchers.go @@ -159,6 +159,10 @@ func GetOrderedVoucherData(ctx context.Context, store DataStore, sessionId strin // MatchVoucher finds the matching voucher symbol, balance, decimals and contract address based on the input. func MatchVoucher(input, symbols, balances, decimals, addresses string) (symbol, balance, decimal, address string) { + // case for invalid input with no current symbols + if symbols == "" { + return + } symList := strings.Split(symbols, "\n") balList := strings.Split(balances, "\n") decList := strings.Split(decimals, "\n") From 759e424805ea4d5b8fa214f5ef3e6af325b37faa Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 23 Feb 2026 16:15:59 +0300 Subject: [PATCH 124/130] use the correct sym for proper error handling --- services/registration/pay_debt | 2 +- services/registration/pay_debt.vis | 4 ++-- services/registration/select_voucher | 2 +- services/registration/select_voucher.vis | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/services/registration/pay_debt b/services/registration/pay_debt index 3e1fc9d..c0807af 100644 --- a/services/registration/pay_debt +++ b/services/registration/pay_debt @@ -1 +1 @@ -{{.get_vouchers}} +{{.get_paydebt_voucher_list}} diff --git a/services/registration/pay_debt.vis b/services/registration/pay_debt.vis index ec65fc9..3066e75 100644 --- a/services/registration/pay_debt.vis +++ b/services/registration/pay_debt.vis @@ -1,6 +1,6 @@ CATCH no_voucher flag_no_active_voucher 1 -LOAD get_vouchers 0 -MAP get_vouchers +LOAD get_paydebt_voucher_list 0 +MAP get_paydebt_voucher_list MOUT back 0 MOUT quit 99 MNEXT next 88 diff --git a/services/registration/select_voucher b/services/registration/select_voucher index 3e1fc9d..e469f9d 100644 --- a/services/registration/select_voucher +++ b/services/registration/select_voucher @@ -1 +1 @@ -{{.get_vouchers}} +{{.get_voucher_list}} diff --git a/services/registration/select_voucher.vis b/services/registration/select_voucher.vis index 0edb553..561c888 100644 --- a/services/registration/select_voucher.vis +++ b/services/registration/select_voucher.vis @@ -1,6 +1,6 @@ CATCH no_voucher flag_no_active_voucher 1 -LOAD get_vouchers 0 -MAP get_vouchers +LOAD get_voucher_list 0 +MAP get_voucher_list MOUT back 0 MOUT quit 99 MNEXT next 88 From 686f119a9eb9f0e074086738168c64eb29019924 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 23 Feb 2026 16:16:15 +0300 Subject: [PATCH 125/130] remove unused CATCH statement --- services/registration/pool_deposit.vis | 1 - 1 file changed, 1 deletion(-) diff --git a/services/registration/pool_deposit.vis b/services/registration/pool_deposit.vis index 55f4990..3dd6c2c 100644 --- a/services/registration/pool_deposit.vis +++ b/services/registration/pool_deposit.vis @@ -1,5 +1,4 @@ CATCH no_voucher flag_no_active_voucher 1 -CATCH no_stable_voucher flag_no_stable_vouchers 1 LOAD get_ordered_vouchers 0 MAP get_ordered_vouchers MOUT back 0 From 43c4b64b42c184f36e15fb7a707ec47104379878 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 23 Feb 2026 16:20:36 +0300 Subject: [PATCH 126/130] correctly calculate the credit --- handlers/application/balance.go | 120 ++++++++++---------------------- 1 file changed, 36 insertions(+), 84 deletions(-) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index 409d409..4fc221c 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -3,12 +3,10 @@ package application import ( "context" "fmt" - "sort" "strconv" "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" @@ -114,8 +112,6 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i return res, fmt.Errorf("missing session") } - userStore := h.userdataStore - code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) l.AddDomain("default") @@ -129,7 +125,6 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i return res, nil } - // default flag reset res.FlagReset = append(res.FlagReset, flag_api_call_error) // Resolve active pool @@ -138,7 +133,7 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i return res, err } - // Fetch swappable vouchers + // Fetch swappable vouchers (pool view) swappableVouchers, err := h.accountService.GetPoolSwappableFromVouchers(ctx, string(activePoolAddress), string(publicKey)) if err != nil { logg.ErrorCtxf(ctx, "failed on GetPoolSwappableFromVouchers", "error", err) @@ -147,91 +142,46 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i } if len(swappableVouchers) == 0 { + res.Content = l.Get("Credit: %s KSH\nDebt: %s %s\n", "0", "0", string(activeSym)) 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[addr] = i + // Fetch ALL wallet vouchers (voucher holdings view) + allVouchers, err := h.accountService.FetchVouchers(ctx, string(publicKey)) + if err != nil { + logg.ErrorCtxf(ctx, "failed on FetchVouchers", "error", err) + return res, nil } - stable := make([]dataserviceapi.TokenHoldings, 0) - nonStable := make([]dataserviceapi.TokenHoldings, 0) + // CREDIT calculation + // Rule: + // 1. Swap quote of active voucher → first stable in pool from GetPoolSwappableFromVouchers + // 2. PLUS all stable balances from FetchVouchers - // Helper: order vouchers (stable first, priority-based) - orderVouchers := func(vouchers []dataserviceapi.TokenHoldings) []dataserviceapi.TokenHoldings { - for _, v := range vouchers { - if isStableVoucher(v.TokenAddress) { - stable = append(stable, v) - } else { - nonStable = append(nonStable, v) - } - } + scaledCredit := "0" - sort.SliceStable(stable, func(i, j int) bool { - ai := stablePriority[stable[i].TokenAddress] - aj := stablePriority[stable[j].TokenAddress] - return ai < aj - }) - - return append(stable, nonStable...) - } - - // Remove active voucher - filteredVouchers := make([]dataserviceapi.TokenHoldings, 0, len(swappableVouchers)) - 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) - continue - } - } - - // Credit calculation: How much Active Token that can be swapped for a stable coin - // that's on the pool + any stables sendable to Pretium (in KSH value) - - // Find first stable voucher from swappableVouchers - var firstStable *dataserviceapi.TokenHoldings + // 1️. Find first stable voucher in POOL (for swap target) + var firstPoolStable *dataserviceapi.TokenHoldings for i := range swappableVouchers { if isStableVoucher(swappableVouchers[i].TokenAddress) { - firstStable = &swappableVouchers[i] + firstPoolStable = &swappableVouchers[i] break } } - scaledCredit := "0" - - if firstStable != nil { - finalAmountStr, err := store.ParseAndScaleAmount(string(activeBal), string(activeDecimal)) + // 2️. If pool has a stable, get swap quote + if firstPoolStable != nil { + finalAmountStr, err := store.ParseAndScaleAmount( + string(activeBal), + string(activeDecimal), + ) if err != nil { - logg.ErrorCtxf(ctx, "failed on ParseAndScaleAmount", "error", err) return res, err } // swap active -> FIRST stable from pool list - r, err := h.accountService.GetPoolSwapQuote(ctx, finalAmountStr, string(publicKey), string(activeAddress), string(activePoolAddress), firstStable.TokenAddress) + r, err := h.accountService.GetPoolSwapQuote(ctx, finalAmountStr, string(publicKey), string(activeAddress), string(activePoolAddress), firstPoolStable.TokenAddress) 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) @@ -239,22 +189,27 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i } // scale using REAL stable decimals - finalQuote := store.ScaleDownBalance(r.OutValue, firstStable.TokenDecimals) + finalQuote := store.ScaleDownBalance(r.OutValue, firstPoolStable.TokenDecimals) + scaledCredit = store.AddDecimalStrings(scaledCredit, finalQuote) } - // Add existing stable balances - for _, v := range stable { - scaled := store.ScaleDownBalance(v.Balance, v.TokenDecimals) - scaledCredit = store.AddDecimalStrings(scaledCredit, scaled) + // 3️. Add ALL wallet stable balances (from FetchVouchers) + for _, v := range allVouchers { + if isStableVoucher(v.TokenAddress) { + scaled := store.ScaleDownBalance(v.Balance, v.TokenDecimals) + scaledCredit = store.AddDecimalStrings(scaledCredit, scaled) + } } - // DEBT calculation: All outstanding active token that is in the current pool - // (how much of AT that is in the active Pool) + // DEBT calculation + // Rule: + // - Default = 0 + // - If active is stable → remain 0 + // - If active is non-stable and exists in pool → use pool balance + scaledDebt := "0" - // If active voucher is NOT stable, - // check if it exists in swappableVouchers if !isStableVoucher(string(activeAddress)) { for _, v := range swappableVouchers { if v.TokenSymbol == string(activeSym) { @@ -264,7 +219,6 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i } } - // Format (2 decimal places) formattedDebt, _ := store.TruncateDecimalString(scaledDebt, 2) // Fetch MPESA rates @@ -277,9 +231,7 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i } creditFloat, _ := strconv.ParseFloat(scaledCredit, 64) - creditKsh := fmt.Sprintf("%f", creditFloat*rates.Buy) - kshFormattedCredit, _ := store.TruncateDecimalString(creditKsh, 0) res.Content = l.Get( From eea51ea40dbd8363dd5fe7db5e98a3cbefbfad17 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Mon, 23 Feb 2026 17:46:52 +0300 Subject: [PATCH 127/130] reset appropriate error flags on success --- handlers/application/mpesa.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/handlers/application/mpesa.go b/handlers/application/mpesa.go index a497d65..b37e9c3 100644 --- a/handlers/application/mpesa.go +++ b/handlers/application/mpesa.go @@ -123,6 +123,8 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ maxKshFormatted, ) + res.FlagReset = append(res.FlagReset, flag_low_swap_amount, flag_api_call_error, flag_incorrect_voucher, flag_incorrect_pool) + return res, nil } @@ -155,6 +157,8 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ return res, nil } + res.FlagReset = append(res.FlagReset, flag_api_call_error) + // Fallback if below minimum maxFloat, _ := strconv.ParseFloat(maxRAT, 64) if maxFloat < 0.1 { @@ -164,6 +168,8 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [ return res, nil } + res.FlagReset = append(res.FlagReset, flag_low_swap_amount) + // Save max RAT amount to be used in validating the user's input err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_SWAP_MAX_AMOUNT, []byte(maxRAT)) if err != nil { From 45ccefe1fe0fd67220d119ce0ef483142f678734 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 25 Feb 2026 10:16:29 +0300 Subject: [PATCH 128/130] properly format the comments --- handlers/application/balance.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/handlers/application/balance.go b/handlers/application/balance.go index 4fc221c..53104c7 100644 --- a/handlers/application/balance.go +++ b/handlers/application/balance.go @@ -160,7 +160,7 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i scaledCredit := "0" - // 1️. Find first stable voucher in POOL (for swap target) + // 1. Find first stable voucher in POOL (for swap target) var firstPoolStable *dataserviceapi.TokenHoldings for i := range swappableVouchers { if isStableVoucher(swappableVouchers[i].TokenAddress) { @@ -169,7 +169,7 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i } } - // 2️. If pool has a stable, get swap quote + // 2. If pool has a stable, get swap quote if firstPoolStable != nil { finalAmountStr, err := store.ParseAndScaleAmount( string(activeBal), @@ -194,7 +194,7 @@ func (h *MenuHandlers) CalculateCreditAndDebt(ctx context.Context, sym string, i scaledCredit = store.AddDecimalStrings(scaledCredit, finalQuote) } - // 3️. Add ALL wallet stable balances (from FetchVouchers) + // 3. Add ALL wallet stable balances (from FetchVouchers) for _, v := range allVouchers { if isStableVoucher(v.TokenAddress) { scaled := store.ScaleDownBalance(v.Balance, v.TokenDecimals) From 185ff0dc45161cf90b146c2f98327feeb885293e Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 25 Feb 2026 11:35:58 +0300 Subject: [PATCH 129/130] have a single view for the pay_debt node --- services/registration/pay_debt | 2 +- services/registration/pay_debt_swa | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) delete mode 100644 services/registration/pay_debt_swa diff --git a/services/registration/pay_debt b/services/registration/pay_debt index c0807af..59117f3 100644 --- a/services/registration/pay_debt +++ b/services/registration/pay_debt @@ -1 +1 @@ -{{.get_paydebt_voucher_list}} +{{.get_paydebt_voucher_list}} \ No newline at end of file diff --git a/services/registration/pay_debt_swa b/services/registration/pay_debt_swa deleted file mode 100644 index 1e2b322..0000000 --- a/services/registration/pay_debt_swa +++ /dev/null @@ -1 +0,0 @@ -{{.calculate_max_pay_debt}} \ No newline at end of file From c16c39f289a9bb5d161648e21000cf34614f154f Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Wed, 25 Feb 2026 11:37:36 +0300 Subject: [PATCH 130/130] update the translations for the swahili menus --- handlers/application/mpesa.go | 4 +-- handlers/application/paydebt.go | 2 +- handlers/application/poolswap.go | 10 +++++--- services/registration/confirm_debt_removal | 3 +-- services/registration/locale/swa/default.po | 25 +++++++++++++++---- services/registration/send_mpesa_confirmation | 3 +-- .../registration/send_mpesa_confirmation_swa | 3 +-- services/registration/swap_to_list.vis | 2 +- 8 files changed, 34 insertions(+), 18 deletions(-) diff --git a/handlers/application/mpesa.go b/handlers/application/mpesa.go index b37e9c3..cdb5415 100644 --- a/handlers/application/mpesa.go +++ b/handlers/application/mpesa.go @@ -535,7 +535,7 @@ func (h *MenuHandlers) SendMpesaMinLimit(ctx context.Context, sym string, input kshFormatted, _ := store.TruncateDecimalString(ksh, 0) res.Content = l.Get( - "Enter the amount of credit to receive: (Minimum %s Ksh)\n", + "Enter the amount of credit to deposit: (Minimum %s Ksh)\n", kshFormatted, ) @@ -607,7 +607,7 @@ func (h *MenuHandlers) SendMpesaPreview(ctx context.Context, sym string, input [ defaultAsset := config.DefaultMpesaAsset() res.Content = l.Get( - "You will get a prompt for your M-Pesa PIN shortly to send %s ksh and receive ~ %s %s", + "You will get a prompt for your Mpesa PIN shortly to send %s ksh and receive ~ %s %s", inputStr, estimateFormatted, defaultAsset, ) diff --git a/handlers/application/paydebt.go b/handlers/application/paydebt.go index 21dd5d1..8b5033c 100644 --- a/handlers/application/paydebt.go +++ b/handlers/application/paydebt.go @@ -238,7 +238,7 @@ func (h *MenuHandlers) ConfirmDebtRemoval(ctx context.Context, sym string, input } res.Content = l.Get( - "Please confirm that you will use %s %s to remove your debt of %s %s\n", + "Please confirm that you will use %s %s to remove your debt of %s %s\nEnter your PIN:", inputStr, payDebtVoucher.TokenSymbol, qouteStr, string(activeSym), ) diff --git a/handlers/application/poolswap.go b/handlers/application/poolswap.go index 3b9b1a3..a0a89ed 100644 --- a/handlers/application/poolswap.go +++ b/handlers/application/poolswap.go @@ -175,6 +175,10 @@ func (h *MenuHandlers) SwapMaxLimit(ctx context.Context, sym string, input []byt return res, nil } + code := codeFromCtx(ctx) + l := gotext.NewLocale(translationDir, code) + l.AddDomain("default") + userStore := h.userdataStore metadata, err := store.GetSwapToVoucherData(ctx, userStore, sessionId, inputStr) if err != nil { @@ -235,7 +239,7 @@ func (h *MenuHandlers) SwapMaxLimit(ctx context.Context, sym string, input []byt return res, err } - res.Content = fmt.Sprintf( + res.Content = l.Get( "Maximum: %s %s\n\nEnter amount of %s to swap for %s:", maxStr, swapData.ActiveSwapFromSym, swapData.ActiveSwapFromSym, swapData.ActiveSwapToSym, ) @@ -323,8 +327,8 @@ func (h *MenuHandlers) SwapPreview(ctx context.Context, sym string, input []byte // Format to 2 decimal places qouteStr, _ := store.TruncateDecimalString(string(quoteAmountStr), 2) - res.Content = fmt.Sprintf( - "You will swap:\n%s %s for %s %s:", + res.Content = l.Get( + "You will swap %s %s for %s %s:", inputStr, swapData.ActiveSwapFromSym, qouteStr, swapData.ActiveSwapToSym, ) diff --git a/services/registration/confirm_debt_removal b/services/registration/confirm_debt_removal index 3943b54..4e58995 100644 --- a/services/registration/confirm_debt_removal +++ b/services/registration/confirm_debt_removal @@ -1,2 +1 @@ -{{.confirm_debt_removal}} -Enter your PIN: \ No newline at end of file +{{.confirm_debt_removal}} \ No newline at end of file diff --git a/services/registration/locale/swa/default.po b/services/registration/locale/swa/default.po index 9af2a3a..a921f51 100644 --- a/services/registration/locale/swa/default.po +++ b/services/registration/locale/swa/default.po @@ -59,7 +59,7 @@ msgid "Enter the amount of M-Pesa to get: (Max %s Ksh)\n" msgstr "Weka kiasi cha M-Pesa cha kupata: (Kikomo %s Ksh)\n" msgid "You are sending %s %s in order to receive ~ %s ksh" -msgstr "Unatuma ~ %s %s ili upoke %s ksh" +msgstr "Unatuma ~ %s %s ili upokee %s ksh" msgid "Your request has been sent. Please await confirmation" msgstr "Ombi lako limetumwa. Tafadhali subiri" @@ -67,8 +67,8 @@ msgstr "Ombi lako limetumwa. Tafadhali subiri" msgid "Enter the amount of M-Pesa to send: (Minimum %s Ksh)\n" msgstr "Weka kiasi cha M-Pesa cha kutuma: (Kima cha chini %s Ksh)\n" -msgid "You will get a prompt for your M-Pesa PIN shortly to send %s ksh and receive ~ %s cUSD" -msgstr "Utapokea kidokezo cha PIN yako ya M-Pesa hivi karibuni kutuma %s ksh na kupokea ~ %s cUSD" +msgid "You will get a prompt for your Mpesa PIN shortly to send %s ksh and receive ~ %s %s" +msgstr "Utapokea kidokezo cha PIN yako ya Mpesa hivi karibuni kutuma %s ksh na kupokea ~ %s %s" msgid "Your request has been sent. Thank you for using Sarafu" msgstr "Ombi lako limetumwa. Asante kwa kutumia huduma ya Sarafu" @@ -76,7 +76,7 @@ msgstr "Ombi lako limetumwa. Asante kwa kutumia huduma ya Sarafu" msgid "You can remove a max of %s %s from '%s' pool\nEnter amount of %s:(Max: %s)" msgstr "Unaweza kuondoa kiwango cha juu cha %s %s kutoka kwenye '%s'\n\nWeka kiwango cha %s:(Kikomo: %s)" -msgid "Please confirm that you will use %s %s to remove your debt of %s %s\n" +msgid "Please confirm that you will use %s %s to remove your debt of %s %s\nEnter your PIN:" msgstr "Tafadhali thibitisha kwamba utatumia %s %s kulipa deni lako la %s %s.\nWeka PIN yako:" msgid "Your active voucher %s is already set" @@ -95,4 +95,19 @@ msgid "%s will receive %s %s from %s" msgstr %s atapokea %s %s kutoka kwa %s" msgid "You need another voucher to proceed. Only found %s." -msgstr "Unahitaji kua na sarafu nyingine. Tumepata tu %s." \ No newline at end of file +msgstr "Unahitaji kua na sarafu nyingine. Tumepata tu %s." + +msgid "Maximum: %s %s\n\nEnter amount of %s to swap for %s:" +msgstr "Kikimo: %s %s\n\nWeka kiasi cha %s kitakacho badilishwa kua %s:" + +msgid "You will swap %s %s for %s %s:" +msgstr "Utabadilisha %s %s kua %s %s:" + +msgid "Your request has been sent. You will receive an SMS when your debt of %s %s has been removed from %s." +msgstr "Ombi lako limetumwa. Utapokea ujumbe wakati deni lako la %s %s litatolewa kwa %s." + +msgid "Enter the amount of Mpesa to withdraw: (Min: Ksh %s, Max %s Ksh)\n" +msgstr "Weka kiasi cha Mpesa utakacho toa: (Min: Ksh %s, Max %s Ksh)\n" + +msgid "Enter the amount of credit to deposit: (Minimum %s Ksh)\n" +msgstr "Weka kiasi utakacho weka (Kima cha chini: %s Ksh)\n" \ No newline at end of file diff --git a/services/registration/send_mpesa_confirmation b/services/registration/send_mpesa_confirmation index 5c07792..eab58a3 100644 --- a/services/registration/send_mpesa_confirmation +++ b/services/registration/send_mpesa_confirmation @@ -1,3 +1,2 @@ {{.send_mpesa_preview}} - -Please enter your account PIN to confirm: \ No newline at end of file +Enter your PIN to confirm: \ No newline at end of file diff --git a/services/registration/send_mpesa_confirmation_swa b/services/registration/send_mpesa_confirmation_swa index 7ef61b3..73f4934 100644 --- a/services/registration/send_mpesa_confirmation_swa +++ b/services/registration/send_mpesa_confirmation_swa @@ -1,3 +1,2 @@ {{.send_mpesa_preview}} - -Tafadhali weka PIN ya akaunti yako kudhibitisha: \ No newline at end of file +Weka PIN yako kudhibitisha: \ No newline at end of file diff --git a/services/registration/swap_to_list.vis b/services/registration/swap_to_list.vis index 1cd7c08..39517f8 100644 --- a/services/registration/swap_to_list.vis +++ b/services/registration/swap_to_list.vis @@ -12,7 +12,7 @@ INCMP > 88 INCMP < 98 INCMP _ 0 INCMP quit 99 -LOAD swap_max_limit 64 +LOAD swap_max_limit 138 RELOAD swap_max_limit CATCH api_failure flag_api_call_error 1 CATCH . flag_incorrect_voucher 1