Compare commits
35 Commits
v1.4.4-rc.
...
v1.4.6-rc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3949959aa3
|
||
|
|
99893eac5c
|
||
|
|
277e4e179d
|
||
|
|
ca2a50375b
|
||
|
|
4dfccb3ff2
|
||
|
|
88b5a33c2e
|
||
|
|
a4f036c88d
|
||
|
|
46e98b5b9e
|
||
|
|
ead5dd7b8c
|
||
|
|
0a69e04229
|
||
|
|
ea9875584f
|
||
|
|
6bb87a7b33
|
||
|
|
cfc38402f0
|
||
|
|
07e0e877d5
|
||
|
|
f7de79f51a
|
||
|
|
e2ff3d20d5
|
||
|
|
cbe5b211d8
|
||
|
|
101955c1b3
|
||
|
|
d0f7692fa2
|
||
|
|
7441fde4af
|
||
|
|
adb7a402d0
|
||
| b908dc1881 | |||
|
|
523f680276
|
||
|
|
b337c9260b
|
||
|
|
c380915100
|
||
|
|
7d8fd065f0
|
||
|
|
40292ebcdd
|
||
|
|
4edcdfa987
|
||
|
|
a56f94896d
|
||
|
|
a447f230ca
|
||
|
|
65badc4ccc
|
||
| 89d3d19d77 | |||
|
|
817b523135 | ||
| e0e3d9b6cf | |||
|
|
2cabae1e74
|
1
.gitignore
vendored
1
.gitignore
vendored
@@ -8,3 +8,4 @@ id_*
|
||||
*.gdbm
|
||||
*.log
|
||||
user-data
|
||||
**/*/vise-asm
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
262
handlers/application/paydebt.go
Normal file
262
handlers/application/paydebt.go
Normal 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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
2
services/registration/confirm_debt_removal
Normal file
2
services/registration/confirm_debt_removal
Normal file
@@ -0,0 +1,2 @@
|
||||
{{.confirm_debt_removal}}
|
||||
Enter your PIN:
|
||||
13
services/registration/confirm_debt_removal.vis
Normal file
13
services/registration/confirm_debt_removal.vis
Normal 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 *
|
||||
@@ -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
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
Credit-Send
|
||||
@@ -1 +0,0 @@
|
||||
Tuma-Mkopo
|
||||
4
services/registration/initiate_pay_debt.vis
Normal file
4
services/registration/initiate_pay_debt.vis
Normal file
@@ -0,0 +1,4 @@
|
||||
LOAD reset_incorrect_pin 6
|
||||
CATCH _ flag_account_authorized 0
|
||||
LOAD initiate_pay_debt 0
|
||||
HALT
|
||||
@@ -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:"
|
||||
1
services/registration/low_pay_debt_amount
Normal file
1
services/registration/low_pay_debt_amount
Normal file
@@ -0,0 +1 @@
|
||||
You have a low debt amount
|
||||
5
services/registration/low_pay_debt_amount.vis
Normal file
5
services/registration/low_pay_debt_amount.vis
Normal file
@@ -0,0 +1,5 @@
|
||||
MOUT back 0
|
||||
MOUT quit 9
|
||||
HALT
|
||||
INCMP ^ 0
|
||||
INCMP quit 9
|
||||
1
services/registration/low_pay_debt_amount_swa
Normal file
1
services/registration/low_pay_debt_amount_swa
Normal file
@@ -0,0 +1 @@
|
||||
Kiasi cha deni lako ni cha chini sana
|
||||
@@ -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
|
||||
|
||||
1
services/registration/pay_debt
Normal file
1
services/registration/pay_debt
Normal file
@@ -0,0 +1 @@
|
||||
{{.calculate_max_pay_debt}}
|
||||
8
services/registration/pay_debt.vis
Normal file
8
services/registration/pay_debt.vis
Normal 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 *
|
||||
1
services/registration/pay_debt_menu
Normal file
1
services/registration/pay_debt_menu
Normal file
@@ -0,0 +1 @@
|
||||
Pay debt
|
||||
1
services/registration/pay_debt_menu_swa
Normal file
1
services/registration/pay_debt_menu_swa
Normal file
@@ -0,0 +1 @@
|
||||
Lipa deni
|
||||
1
services/registration/pay_debt_swa
Normal file
1
services/registration/pay_debt_swa
Normal file
@@ -0,0 +1 @@
|
||||
{{.calculate_max_pay_debt}}
|
||||
@@ -1 +0,0 @@
|
||||
Enter recipient's phone number/address/alias:
|
||||
@@ -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 *
|
||||
@@ -1 +0,0 @@
|
||||
Weka nambari ya simu/Anwani/Lakabu:
|
||||
@@ -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 (
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user