Compare commits

..

35 Commits

Author SHA1 Message Date
Alfred Kamanda
3949959aa3 use the correct terms for clarity
Some checks failed
release / docker (push) Has been cancelled
2026-01-30 16:41:44 +03:00
Alfred Kamanda
99893eac5c include the ActiveSwapToDecimal on the SwapData 2026-01-30 16:34:52 +03:00
Alfred Kamanda
277e4e179d added a CATCH for a low amount response from the API 2026-01-30 16:33:44 +03:00
Alfred Kamanda
ca2a50375b added functions to perform the debt removal 2026-01-30 15:13:33 +03:00
Alfred Kamanda
4dfccb3ff2 log the correct fields 2026-01-30 10:22:36 +03:00
Alfred Kamanda
88b5a33c2e update the sym name to be more descriptive 2026-01-29 19:37:33 +03:00
Alfred Kamanda
a4f036c88d remove the amount as it is present in the response content 2026-01-29 19:29:35 +03:00
Alfred Kamanda
46e98b5b9e update the translations 2026-01-29 19:17:38 +03:00
Alfred Kamanda
ead5dd7b8c store the filtered vouchers from the GetPoolSwappableFromVouchers 2026-01-29 17:10:20 +03:00
Alfred Kamanda
0a69e04229 added helper functions to add scaled down balances 2026-01-29 17:00:24 +03:00
Alfred Kamanda
ea9875584f added the calc_credit_debt to the main.vis and local handler 2026-01-29 16:59:02 +03:00
Alfred Kamanda
6bb87a7b33 added the CalculateCreditAndDebt function 2026-01-29 16:57:00 +03:00
Alfred Kamanda
cfc38402f0 display the credit and debt 2026-01-29 16:14:04 +03:00
Alfred Kamanda
07e0e877d5 added data keys for the credit and debt values 2026-01-29 16:08:53 +03:00
Alfred Kamanda
f7de79f51a added option to go back to the main menu 2026-01-26 13:32:44 +03:00
Alfred Kamanda
e2ff3d20d5 updated the resolveActivePoolAddress to resolveActivePoolDetails 2026-01-26 13:28:31 +03:00
Alfred Kamanda
cbe5b211d8 added the local functions to the menu handler 2026-01-22 17:42:52 +03:00
Alfred Kamanda
101955c1b3 added a node to initialize the pay debt 2026-01-22 17:42:27 +03:00
Alfred Kamanda
d0f7692fa2 added a node for the pay debt confirmation 2026-01-22 17:42:10 +03:00
Alfred Kamanda
7441fde4af added translations for the pay debt node 2026-01-22 17:40:49 +03:00
Alfred Kamanda
adb7a402d0 added the Pay debt top node 2026-01-22 17:40:13 +03:00
b908dc1881 Merge pull request 'have-single-send-node' (#113) from have-single-send-node into master
Reviewed-on: #113
2026-01-22 14:22:20 +01:00
Alfred Kamanda
523f680276 append the flag_swap_transaction once all checks pass
Some checks failed
release / docker (push) Has been cancelled
2026-01-15 11:25:02 +03:00
Alfred Kamanda
b337c9260b add a debug statement 2026-01-15 11:17:41 +03:00
Alfred Kamanda
c380915100 remove misplaced CATCH on the api_error flag 2026-01-15 10:56:52 +03:00
Alfred Kamanda
7d8fd065f0 default to a normal send if an error occurs on calculateSendCreditLimits 2026-01-15 10:56:20 +03:00
Alfred Kamanda
40292ebcdd removed unused send node specific files
Some checks failed
release / docker (push) Has been cancelled
2026-01-13 12:52:10 +03:00
Alfred Kamanda
4edcdfa987 change the order to only have Send 2026-01-13 12:46:34 +03:00
Alfred Kamanda
a56f94896d add a RELOAD for the reset_transaction_amount 2026-01-13 12:46:13 +03:00
Alfred Kamanda
a447f230ca refactor the code to handle credit send or normal transactions 2026-01-13 12:45:27 +03:00
Alfred Kamanda
65badc4ccc ignore the generated vise-asm file 2026-01-13 11:09:13 +03:00
89d3d19d77 Merge pull request 'use the ResetRoot config to clear the cache once a user quits' (#112) from cache-error-fix into master
Reviewed-on: #112
2025-12-09 10:29:37 +01:00
Alfred Kamanda
817b523135 Merge branch 'master' into cache-error-fix
Some checks failed
release / docker (push) Has been cancelled
2025-12-08 17:43:21 +03:00
e0e3d9b6cf Merge pull request 'mpesa-onramp-offramp' (#110) from mpesa-onramp-offramp into master
Reviewed-on: #110
2025-12-08 15:41:23 +01:00
Alfred Kamanda
2cabae1e74 use the ResetRoot config to clear the cache once a user quits
Some checks are pending
release / docker (push) Waiting to run
2025-12-08 17:29:13 +03:00
32 changed files with 615 additions and 69 deletions

1
.gitignore vendored
View File

@@ -8,3 +8,4 @@ id_*
*.gdbm
*.log
user-data
**/*/vise-asm

View File

@@ -79,11 +79,12 @@ func main() {
pfp := path.Join(scriptDir, "pp.csv")
cfg := engine.Config{
Root: "root",
OutputSize: uint32(size),
FlagCount: uint32(128),
MenuSeparator: menuSeparator,
Root: "root",
OutputSize: uint32(size),
FlagCount: uint32(128),
MenuSeparator: menuSeparator,
ResetOnEmptyInput: true,
ResetRoot: true, // clear the cache once a user quits
}
if engineDebug {

View File

@@ -94,11 +94,12 @@ func main() {
pfp := path.Join(scriptDir, "pp.csv")
cfg := engine.Config{
Root: "root",
OutputSize: uint32(size),
FlagCount: uint32(128),
MenuSeparator: menuSeparator,
Root: "root",
OutputSize: uint32(size),
FlagCount: uint32(128),
MenuSeparator: menuSeparator,
ResetOnEmptyInput: true,
ResetRoot: true, // clear the cache once a user quits
}
if engineDebug {

View File

@@ -82,6 +82,7 @@ func main() {
MenuSeparator: menuSeparator,
EngineDebug: engineDebug,
ResetOnEmptyInput: true,
ResetRoot: true, // clear the cache once a user quits
}
menuStorageService := storage.NewMenuStorageService(conns)

View File

@@ -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"
)
@@ -52,7 +54,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 +82,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 +95,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
}
@@ -98,3 +131,131 @@ 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
}
// 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
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_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
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
}

View File

@@ -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
}

View File

@@ -0,0 +1,262 @@
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, ActiveSwapToAddress as the from (FT), ActiveSwapFromAddress as the to (AT) and PublicKey to get the swap max limit
r, err := h.accountService.GetSwapFromTokenMaxLimit(ctx, swapData.ActivePoolAddress, swapData.ActiveSwapToAddress, swapData.ActiveSwapFromAddress, swapData.PublicKey)
if err != nil {
res.FlagSet = append(res.FlagSet, flag_api_call_error)
logg.ErrorCtxf(ctx, "failed on GetSwapFromTokenMaxLimit", "error", err)
return res, nil
}
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.ActiveSwapToDecimal)
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
}
storedMax, _ := userStore.ReadEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE)
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))
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.ActiveSwapToSym,
activePoolName,
)
res.FlagReset = append(res.FlagReset, flag_account_authorized)
return res, nil
}

View File

@@ -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
}

View File

@@ -258,6 +258,7 @@ func (h *MenuHandlers) TransactionReset(ctx context.Context, sym string, input [
flag_invalid_recipient, _ := h.flagManager.GetFlag("flag_invalid_recipient")
flag_invalid_recipient_with_invite, _ := h.flagManager.GetFlag("flag_invalid_recipient_with_invite")
store := h.userdataStore
err = store.WriteEntry(ctx, sessionId, storedb.DATA_AMOUNT, []byte(""))
if err != nil {
@@ -336,30 +337,15 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte)
// Format the active balance amount to 2 decimal places
formattedBalance, _ := store.TruncateDecimalString(string(activeBal), 2)
// If normal transaction, or if the sym is send_max_amount, return balance
if string(transactionType) == "normal" || sym == "send_max_amount" {
// If normal transaction return balance
if string(transactionType) == "normal" {
res.FlagReset = append(res.FlagReset, flag_swap_transaction)
res.Content = l.Get("Maximum amount: %s %s\nEnter amount:", formattedBalance, string(activeSym))
return res, nil
}
res.FlagSet = append(res.FlagSet, flag_swap_transaction)
// 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
}
recipientActiveSym, recipientActiveAddress, recipientActiveDecimal, err := h.getRecipientData(ctx, string(recipientPhoneNumber))
if err != nil {
return res, err
}
// Resolve active pool address
activePoolAddress, err := h.resolveActivePoolAddress(ctx, sessionId)
activePoolAddress, _, err := h.resolveActivePoolDetails(ctx, sessionId)
if err != nil {
return res, err
}
@@ -372,16 +358,31 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte)
logg.ErrorCtxf(ctx, "failed on CheckTokenInPool", "error", err)
return res, nil
}
res.FlagReset = append(res.FlagReset, flag_swap_transaction)
res.Content = l.Get("Maximum amount: %s %s\nEnter amount:", formattedBalance, string(activeSym))
return res, nil
}
// 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
}
recipientActiveSym, recipientActiveAddress, recipientActiveDecimal, err := h.getRecipientData(ctx, string(recipientPhoneNumber))
if err != nil {
return res, err
}
// retrieve the max credit send amounts
maxSAT, maxRAT, err := h.calculateSendCreditLimits(ctx, activePoolAddress, activeAddress, recipientActiveAddress, publicKey, activeDecimal, recipientActiveDecimal)
if err != nil {
res.FlagSet = append(res.FlagSet, flag_api_call_error)
// if an error (such as Swap rates not found for the speficied pool and tokens), fall back to a normal transaction
logg.ErrorCtxf(ctx, "failed on calculateSendCreditLimits", "error", err)
res.FlagReset = append(res.FlagReset, flag_swap_transaction)
res.Content = l.Get("Maximum amount: %s %s\nEnter amount:", formattedBalance, string(activeSym))
return res, nil
}
@@ -413,6 +414,9 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte)
return res, err
}
// only set the flag once all checks pass
res.FlagSet = append(res.FlagSet, flag_swap_transaction)
res.Content = l.Get(
"Credit Available: %s %s\n(You can swap up to %s %s -> %s %s).\nEnter %s amount:",
maxRAT,
@@ -475,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) {

View File

@@ -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)
@@ -146,6 +147,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_max_pay_debt", appHandlers.CalculateMaxPayDebt)
ls.DbRs.AddLocalFunc("confirm_debt_removal", appHandlers.ConfirmDebtRemoval)
ls.DbRs.AddLocalFunc("initiate_pay_debt", appHandlers.InitiatePayDebt)
ls.first = appHandlers.Init

View File

@@ -0,0 +1,2 @@
{{.confirm_debt_removal}}
Enter your PIN:

View File

@@ -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 *

View File

@@ -1,4 +1,5 @@
LOAD reset_transaction_amount 10
RELOAD reset_transaction_amount
LOAD credit_max_amount 160
RELOAD credit_max_amount
CATCH api_failure flag_api_call_error 1
@@ -10,7 +11,6 @@ RELOAD clear_trans_type_flag
CATCH transaction_swap flag_swap_transaction 1
LOAD validate_amount 64
RELOAD validate_amount
CATCH api_failure flag_api_call_error 1
CATCH invalid_amount flag_invalid_amount 1
INCMP _ 0
LOAD get_recipient 0

View File

@@ -1 +0,0 @@
Credit-Send

View File

@@ -1 +0,0 @@
Tuma-Mkopo

View File

@@ -0,0 +1,4 @@
LOAD reset_incorrect_pin 6
CATCH _ flag_account_authorized 0
LOAD initiate_pay_debt 0
HALT

View File

@@ -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"
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 "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:"

View File

@@ -0,0 +1 @@
You have a low debt amount

View File

@@ -0,0 +1,5 @@
MOUT back 0
MOUT quit 9
HALT
INCMP ^ 0
INCMP quit 9

View File

@@ -0,0 +1 @@
Kiasi cha deni lako ni cha chini sana

View File

@@ -3,11 +3,14 @@ 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
MOUT credit_send 2
MOUT pay_debt 2
MOUT swap 3
MOUT vouchers 4
MOUT select_pool 5
@@ -16,8 +19,8 @@ MOUT account 7
MOUT help 8
MOUT quit 9
HALT
INCMP send 1
INCMP credit_send 2
INCMP credit_send 1
INCMP pay_debt 2
INCMP swap_to_list 3
INCMP my_vouchers 4
INCMP select_pool 5

View File

@@ -0,0 +1 @@
{{.calculate_max_pay_debt}}

View File

@@ -0,0 +1,8 @@
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 *

View File

@@ -0,0 +1 @@
Pay debt

View File

@@ -0,0 +1 @@
Lipa deni

View File

@@ -0,0 +1 @@
{{.calculate_max_pay_debt}}

View File

@@ -1 +0,0 @@
Enter recipient's phone number/address/alias:

View File

@@ -1,12 +0,0 @@
LOAD transaction_reset 0
RELOAD transaction_reset
CATCH no_voucher flag_no_active_voucher 1
MOUT back 0
HALT
LOAD validate_recipient 50
RELOAD validate_recipient
CATCH api_failure flag_api_call_error 1
CATCH invalid_recipient flag_invalid_recipient 1
CATCH invite_recipient flag_invalid_recipient_with_invite 1
INCMP _ 0
INCMP amount *

View File

@@ -1 +0,0 @@
Weka nambari ya simu/Anwani/Lakabu:

View File

@@ -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 (

View File

@@ -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()

View File

@@ -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
}