Compare commits
3 Commits
v1.4.6-rc.
...
credit-sen
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f32f93dff2
|
||
|
|
5ee99cdcd8
|
||
|
|
6abcb97f3a
|
@@ -37,6 +37,3 @@ 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
|
||||
|
||||
@@ -114,22 +114,3 @@ 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
|
||||
}
|
||||
@@ -3,13 +3,11 @@ 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"
|
||||
)
|
||||
|
||||
@@ -54,7 +52,6 @@ func (h *MenuHandlers) CheckBalance(ctx context.Context, sym string, input []byt
|
||||
return res, err
|
||||
}
|
||||
}
|
||||
|
||||
content, err = loadUserContent(ctx, string(activeSym), string(activeBal), string(accAlias))
|
||||
if err != nil {
|
||||
return res, err
|
||||
@@ -65,7 +62,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 string) (string, error) {
|
||||
func loadUserContent(ctx context.Context, activeSym string, balance string, alias string) (string, error) {
|
||||
var content string
|
||||
|
||||
code := codeFromCtx(ctx)
|
||||
@@ -78,9 +75,8 @@ func loadUserContent(ctx context.Context, activeSym, balance, alias string) (str
|
||||
formattedAmount = "0.00"
|
||||
}
|
||||
|
||||
// format the final outputs
|
||||
// format the final output
|
||||
balStr := fmt.Sprintf("%s %s", formattedAmount, activeSym)
|
||||
|
||||
if alias != "" {
|
||||
content = l.Get("%s\nBalance: %s\n", alias, balStr)
|
||||
} else {
|
||||
@@ -102,139 +98,3 @@ 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")
|
||||
flag_no_pay_debt_vouchers, _ := h.flagManager.GetFlag("flag_no_pay_debt_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)
|
||||
if err != nil {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// Resolve active pool
|
||||
activePoolAddress, _, err := h.resolveActivePoolDetails(ctx, sessionId)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
if len(swappableVouchers) == 0 {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
// 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,
|
||||
)
|
||||
|
||||
// Debt = sum of stable vouchers only
|
||||
scaledDebt := "0"
|
||||
for _, v := range filteredSwappableVouchers {
|
||||
scaled := store.ScaleDownBalance(v.Balance, v.TokenDecimals)
|
||||
scaledDebt = store.AddDecimalStrings(scaledDebt, scaled)
|
||||
}
|
||||
|
||||
// Fetch MPESA 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)
|
||||
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)
|
||||
|
||||
// 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,
|
||||
kshFormattedDebt,
|
||||
)
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
@@ -106,7 +106,7 @@ func (h *MenuHandlers) GetMpesaMaxLimit(ctx context.Context, sym string, input [
|
||||
}
|
||||
|
||||
// Resolve active pool address
|
||||
activePoolAddress, _, err := h.resolveActivePoolDetails(ctx, sessionId)
|
||||
activePoolAddress, err := h.resolveActivePoolAddress(ctx, sessionId)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
@@ -1,279 +0,0 @@
|
||||
package application
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
// 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" {
|
||||
res.FlagReset = append(res.FlagReset, flag_low_swap_amount, flag_api_call_error)
|
||||
return res, nil
|
||||
}
|
||||
|
||||
userStore := h.userdataStore
|
||||
|
||||
// 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 {
|
||||
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,
|
||||
)
|
||||
|
||||
res.FlagReset = append(res.FlagReset, flag_low_swap_amount, flag_api_call_error)
|
||||
|
||||
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.ActiveSwapFromDecimal)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
func isStableVoucher(tokenAddress string) bool {
|
||||
addr := strings.ToLower(strings.TrimSpace(tokenAddress))
|
||||
for _, stable := range config.StableVoucherAddresses() {
|
||||
if addr == stable {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package application
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.defalsify.org/vise.git/db"
|
||||
"git.defalsify.org/vise.git/resource"
|
||||
@@ -104,6 +105,7 @@ func (h *MenuHandlers) GetDefaultPool(ctx context.Context, sym string, input []b
|
||||
|
||||
// ViewPool retrieves the pool details from the user store
|
||||
// and displays it to the user for them to select it.
|
||||
// if the data does not exist, it calls the API to get the pool details
|
||||
func (h *MenuHandlers) ViewPool(ctx context.Context, sym string, input []byte) (resource.Result, error) {
|
||||
var res resource.Result
|
||||
sessionId, ok := ctx.Value("SessionId").(string)
|
||||
@@ -131,8 +133,11 @@ func (h *MenuHandlers) ViewPool(ctx context.Context, sym string, input []byte) (
|
||||
if poolData == nil {
|
||||
flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error")
|
||||
|
||||
// convert to uppercase before the call
|
||||
poolSymbol := strings.ToUpper(inputStr)
|
||||
|
||||
// no match found. Call the API using the inputStr as the symbol
|
||||
poolResp, err := h.accountService.RetrievePoolDetails(ctx, inputStr)
|
||||
poolResp, err := h.accountService.RetrievePoolDetails(ctx, poolSymbol)
|
||||
if err != nil {
|
||||
res.FlagSet = append(res.FlagSet, flag_api_call_error)
|
||||
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 inputStr amount entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", inputStr, "error", err)
|
||||
logg.ErrorCtxf(ctx, "failed to write swap amount entry with", "key", storedb.DATA_ACTIVE_SWAP_AMOUNT, "value", finalAmountStr, "error", err)
|
||||
return res, err
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -345,7 +346,7 @@ func (h *MenuHandlers) MaxAmount(ctx context.Context, sym string, input []byte)
|
||||
}
|
||||
|
||||
// Resolve active pool address
|
||||
activePoolAddress, _, err := h.resolveActivePoolDetails(ctx, sessionId)
|
||||
activePoolAddress, err := h.resolveActivePoolAddress(ctx, sessionId)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
@@ -479,53 +480,22 @@ 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) resolveActivePoolAddress(ctx context.Context, sessionId string) ([]byte, error) {
|
||||
store := h.userdataStore
|
||||
|
||||
// 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
|
||||
addr, err := store.ReadEntry(ctx, sessionId, storedb.DATA_ACTIVE_POOL_ADDRESS)
|
||||
if err == nil {
|
||||
return addr, 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
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
logg.ErrorCtxf(ctx, "failed to read active pool address", "error", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (h *MenuHandlers) calculateSendCreditLimits(ctx context.Context, poolAddress, fromAddress, toAddress, publicKey, fromDecimal, toDecimal []byte) (string, string, error) {
|
||||
@@ -788,8 +758,19 @@ 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, swapData.ActivePoolAddress, swapData.ActiveSwapFromAddress, swapData.ActiveSwapToAddress, finalAmountStr)
|
||||
r, err := h.accountService.GetCreditSendReverseQuote(ctx, swapData.ActivePoolAddress, swapData.ActiveSwapFromAddress, swapData.ActiveSwapToAddress, scaledFinalAmountStr)
|
||||
if err != nil {
|
||||
flag_api_call_error, _ := h.flagManager.GetFlag("flag_api_call_error")
|
||||
res.FlagSet = append(res.FlagSet, flag_api_call_error)
|
||||
@@ -801,23 +782,23 @@ 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 sendOutputAmount as the final amount (that will be sent)
|
||||
err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_AMOUNT, []byte(sendOutputAmount))
|
||||
// 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)
|
||||
return res, err
|
||||
}
|
||||
|
||||
// Scale down the quoted output amount
|
||||
quoteAmountStr := store.ScaleDownBalance(sendOutputAmount, swapData.ActiveSwapToDecimal)
|
||||
// quoteAmountStr := store.ScaleDownBalance(sendOutputAmount, swapData.ActiveSwapToDecimal)
|
||||
|
||||
// Format the qouteAmount amount to 2 decimal places
|
||||
qouteAmount, _ := store.TruncateDecimalString(quoteAmountStr, 2)
|
||||
// qouteAmount, _ := store.TruncateDecimalString(quoteAmountStr, 2)
|
||||
|
||||
// store the qouteAmount in the temporary value
|
||||
err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(qouteAmount))
|
||||
err = userStore.WriteEntry(ctx, sessionId, storedb.DATA_TEMPORARY_VALUE, []byte(inputStr))
|
||||
if err != nil {
|
||||
logg.ErrorCtxf(ctx, "failed to write temporary qouteAmount entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", qouteAmount, "error", err)
|
||||
logg.ErrorCtxf(ctx, "failed to write temporary inputStr entry with", "key", storedb.DATA_TEMPORARY_VALUE, "value", inputStr, "error", err)
|
||||
return res, err
|
||||
}
|
||||
|
||||
@@ -830,7 +811,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(recipientPhoneNumber), inputStr, swapData.ActiveSwapToSym,
|
||||
)
|
||||
|
||||
return res, nil
|
||||
|
||||
@@ -181,18 +181,8 @@ 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)
|
||||
@@ -201,11 +191,6 @@ 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 {
|
||||
@@ -218,7 +203,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 = l.Get("Select number or symbol from your vouchers:\n%s", finalOutput)
|
||||
res.Content = finalOutput
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
@@ -81,7 +81,6 @@ 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)
|
||||
@@ -147,9 +146,6 @@ 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
|
||||
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
{{.confirm_debt_removal}}
|
||||
Enter your PIN:
|
||||
@@ -1,13 +0,0 @@
|
||||
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 +0,0 @@
|
||||
LOAD reset_incorrect_pin 6
|
||||
CATCH _ flag_account_authorized 0
|
||||
LOAD initiate_pay_debt 0
|
||||
HALT
|
||||
@@ -71,16 +71,4 @@ 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"
|
||||
|
||||
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:"
|
||||
|
||||
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"
|
||||
msgstr "Ombi lako limetumwa. Asante kwa kutumia huduma ya Sarafu"
|
||||
@@ -1 +0,0 @@
|
||||
You have a low debt amount
|
||||
@@ -1,5 +0,0 @@
|
||||
MOUT back 0
|
||||
MOUT quit 9
|
||||
HALT
|
||||
INCMP ^ 0
|
||||
INCMP quit 9
|
||||
@@ -1 +0,0 @@
|
||||
Kiasi cha deni lako ni cha chini sana
|
||||
@@ -3,7 +3,7 @@ RELOAD clear_temporary_value
|
||||
LOAD manage_vouchers 160
|
||||
RELOAD manage_vouchers
|
||||
CATCH api_failure flag_api_call_error 1
|
||||
LOAD check_balance 148
|
||||
LOAD check_balance 128
|
||||
RELOAD check_balance
|
||||
MAP check_balance
|
||||
MOUT send 1
|
||||
|
||||
@@ -1 +1 @@
|
||||
{{.calc_credit_debt}}
|
||||
{{.check_balance}}
|
||||
@@ -1,16 +1,9 @@
|
||||
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
|
||||
MAP check_balance
|
||||
MOUT get_mpesa 1
|
||||
MOUT send_mpesa 2
|
||||
MOUT quit 9
|
||||
HALT
|
||||
INCMP ^ 0
|
||||
INCMP pay_debt 1
|
||||
INCMP get_mpesa 2
|
||||
INCMP send_mpesa 3
|
||||
INCMP get_mpesa 1
|
||||
INCMP send_mpesa 2
|
||||
INCMP quit 9
|
||||
INCMP . *
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
No stable voucher found
|
||||
@@ -1,5 +0,0 @@
|
||||
MOUT back 0
|
||||
MOUT quit 9
|
||||
HALT
|
||||
INCMP ^ 0
|
||||
INCMP quit 9
|
||||
@@ -1 +0,0 @@
|
||||
Hakuna sarafu thabiti iliyopatikana
|
||||
@@ -1 +0,0 @@
|
||||
{{.calculate_max_pay_debt}}
|
||||
@@ -1,10 +0,0 @@
|
||||
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
|
||||
CATCH low_pay_debt_amount flag_low_swap_amount 1
|
||||
MOUT back 0
|
||||
HALT
|
||||
INCMP _ 0
|
||||
INCMP confirm_debt_removal *
|
||||
@@ -1 +0,0 @@
|
||||
Pay debt
|
||||
@@ -1 +0,0 @@
|
||||
Lipa deni
|
||||
@@ -1 +0,0 @@
|
||||
{{.calculate_max_pay_debt}}
|
||||
@@ -36,4 +36,3 @@ 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
|
||||
|
||||
|
@@ -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 40
|
||||
LOAD check_account_status 0
|
||||
RELOAD check_account_status
|
||||
CATCH api_failure flag_api_call_error 1
|
||||
CATCH account_pending flag_account_pending 1
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
Select number or symbol from your vouchers:
|
||||
{{.get_vouchers}}
|
||||
2
services/registration/select_voucher_swa
Normal file
2
services/registration/select_voucher_swa
Normal file
@@ -0,0 +1,2 @@
|
||||
Chagua nambari au ishara kutoka kwa salio zako:
|
||||
{{.get_vouchers}}
|
||||
@@ -18,7 +18,6 @@ type SwapData struct {
|
||||
ActiveSwapFromAddress string
|
||||
ActiveSwapToSym string
|
||||
ActiveSwapToAddress string
|
||||
ActiveSwapToDecimal string
|
||||
}
|
||||
|
||||
type SwapPreviewData struct {
|
||||
@@ -44,7 +43,6 @@ 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,46 +225,3 @@ 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