Compare commits

..

No commits in common. "6c3ff0e9dbae582e8f20eff21174bb770abca05b" and "b4454f7517070d1f1f3a121e5b8769df5243e974" have entirely different histories.

2 changed files with 101 additions and 187 deletions

View File

@ -57,14 +57,6 @@ func (fm *FlagManager) GetFlag(label string) (uint32, error) {
return fm.parser.GetFlag(label) return fm.parser.GetFlag(label)
} }
// VoucherMetadata helps organize voucher data fields
type VoucherMetadata struct {
Symbol string
Balance string
Decimal string
Address string
}
type Handlers struct { type Handlers struct {
pe *persist.Persister pe *persist.Persister
st *state.State st *state.State
@ -1102,49 +1094,41 @@ func (h *Handlers) CheckVouchers(ctx context.Context, sym string, input []byte)
return res, nil return res, nil
} }
prefixdb := storage.NewSubPrefixDb(store, []byte("vouchers")) // process voucher data
data := processVouchers(vouchersResp.Result.Holdings) voucherSymbolList, voucherBalanceList := ProcessVouchers(vouchersResp.Result.Holdings)
// Store all voucher data prefixdb := storage.NewSubPrefixDb(store, []byte("vouchers"))
dataMap := map[string]string{ err = prefixdb.Put(ctx, []byte("sym"), []byte(voucherSymbolList))
"sym": data.Symbol, if err != nil {
"bal": data.Balance, return res, nil
"deci": data.Decimal,
"addr": data.Address,
} }
for key, value := range dataMap { err = prefixdb.Put(ctx, []byte("bal"), []byte(voucherBalanceList))
if err := prefixdb.Put(ctx, []byte(key), []byte(value)); err != nil { if err != nil {
return res, nil return res, nil
}
} }
return res, nil return res, nil
} }
// processVouchers converts holdings into formatted strings // ProcessVouchers formats the holdings into symbol and balance lists.
func processVouchers(holdings []struct { func ProcessVouchers(holdings []struct {
ContractAddress string `json:"contractAddress"` ContractAddress string `json:"contractAddress"`
TokenSymbol string `json:"tokenSymbol"` TokenSymbol string `json:"tokenSymbol"`
TokenDecimals string `json:"tokenDecimals"` TokenDecimals string `json:"tokenDecimals"`
Balance string `json:"balance"` Balance string `json:"balance"`
}) VoucherMetadata { }) (string, string) {
var data VoucherMetadata var numberedSymbols, numberedBalances []string
var symbols, balances, decimals, addresses []string
for i, h := range holdings { for i, voucher := range holdings {
symbols = append(symbols, fmt.Sprintf("%d:%s", i+1, h.TokenSymbol)) numberedSymbols = append(numberedSymbols, fmt.Sprintf("%d:%s", i+1, voucher.TokenSymbol))
balances = append(balances, fmt.Sprintf("%d:%s", i+1, h.Balance)) numberedBalances = append(numberedBalances, fmt.Sprintf("%d:%s", i+1, voucher.Balance))
decimals = append(decimals, fmt.Sprintf("%d:%s", i+1, h.TokenDecimals))
addresses = append(addresses, fmt.Sprintf("%d:%s", i+1, h.ContractAddress))
} }
data.Symbol = strings.Join(symbols, "\n") voucherSymbolList := strings.Join(numberedSymbols, "\n")
data.Balance = strings.Join(balances, "\n") voucherBalanceList := strings.Join(numberedBalances, "\n")
data.Decimal = strings.Join(decimals, "\n")
data.Address = strings.Join(addresses, "\n")
return data return voucherSymbolList, voucherBalanceList
} }
// GetVoucherList fetches the list of vouchers and formats them // GetVoucherList fetches the list of vouchers and formats them
@ -1178,6 +1162,7 @@ func (h *Handlers) ViewVoucher(ctx context.Context, sym string, input []byte) (r
flag_incorrect_voucher, _ := h.flagManager.GetFlag("flag_incorrect_voucher") flag_incorrect_voucher, _ := h.flagManager.GetFlag("flag_incorrect_voucher")
inputStr := string(input) inputStr := string(input)
if inputStr == "0" || inputStr == "99" { if inputStr == "0" || inputStr == "99" {
res.FlagReset = append(res.FlagReset, flag_incorrect_voucher) res.FlagReset = append(res.FlagReset, flag_incorrect_voucher)
return res, nil return res, nil
@ -1185,185 +1170,118 @@ func (h *Handlers) ViewVoucher(ctx context.Context, sym string, input []byte) (r
prefixdb := storage.NewSubPrefixDb(store, []byte("vouchers")) prefixdb := storage.NewSubPrefixDb(store, []byte("vouchers"))
// Retrieve the voucher metadata // Retrieve the voucher symbol list
metadata, err := getVoucherData(ctx, prefixdb, inputStr) voucherSymbolList, err := prefixdb.Get(ctx, []byte("sym"))
if err != nil { if err != nil {
return res, fmt.Errorf("failed to retrieve voucher data: %v", err) return res, fmt.Errorf("failed to retrieve voucher symbol list: %v", err)
} }
if metadata == nil { // Retrieve the voucher balance list
voucherBalanceList, err := prefixdb.Get(ctx, []byte("bal"))
if err != nil {
return res, fmt.Errorf("failed to retrieve voucher balance list: %v", err)
}
// match the voucher symbol and balance with the input
matchedSymbol, matchedBalance := MatchVoucher(inputStr, string(voucherSymbolList), string(voucherBalanceList))
// If a match is found, write the temporary sym and balance
if matchedSymbol != "" && matchedBalance != "" {
err = store.WriteEntry(ctx, sessionId, utils.DATA_TEMPORARY_SYM, []byte(matchedSymbol))
if err != nil {
return res, err
}
err = store.WriteEntry(ctx, sessionId, utils.DATA_TEMPORARY_BAL, []byte(matchedBalance))
if err != nil {
return res, err
}
res.FlagReset = append(res.FlagReset, flag_incorrect_voucher)
res.Content = fmt.Sprintf("%s\n%s", matchedSymbol, matchedBalance)
} else {
res.FlagSet = append(res.FlagSet, flag_incorrect_voucher) res.FlagSet = append(res.FlagSet, flag_incorrect_voucher)
return res, nil
} }
if err := h.storeTemporaryVoucher(ctx, sessionId, metadata); err != nil {
return resource.Result{}, err
}
res.FlagReset = append(res.FlagReset, flag_incorrect_voucher)
res.Content = fmt.Sprintf("%s\n%s", metadata.Symbol, metadata.Balance)
return res, nil return res, nil
} }
// getVoucherData retrieves and matches voucher data // MatchVoucher finds the matching voucher symbol and balance based on the input.
func getVoucherData(ctx context.Context, db *storage.SubPrefixDb, input string) (*VoucherMetadata, error) { func MatchVoucher(inputStr string, voucherSymbols, voucherBalances string) (string, string) {
keys := []string{"sym", "bal", "deci", "addr"} // Split the lists into slices for processing
data := make(map[string]string) symbols := strings.Split(voucherSymbols, "\n")
balances := strings.Split(voucherBalances, "\n")
for _, key := range keys { var matchedSymbol, matchedBalance string
value, err := db.Get(ctx, []byte(key))
if err != nil {
return nil, fmt.Errorf("failed to get %s: %v", key, err)
}
data[key] = string(value)
}
symbol, balance, decimal, address := matchVoucher(input, for i, symbol := range symbols {
data["sym"], symbolParts := strings.SplitN(symbol, ":", 2)
data["bal"], if len(symbolParts) != 2 {
data["deci"],
data["addr"])
if symbol == "" {
return nil, nil
}
return &VoucherMetadata{
Symbol: symbol,
Balance: balance,
Decimal: decimal,
Address: address,
}, nil
}
// MatchVoucher finds the matching voucher symbol, balance, decimals and contract address based on the input.
func matchVoucher(input, symbols, balances, decimals, addresses string) (symbol, balance, decimal, address string) {
symList := strings.Split(symbols, "\n")
balList := strings.Split(balances, "\n")
decList := strings.Split(decimals, "\n")
addrList := strings.Split(addresses, "\n")
for i, sym := range symList {
parts := strings.SplitN(sym, ":", 2)
if len(parts) != 2 {
continue continue
} }
voucherNum := symbolParts[0]
voucherSymbol := symbolParts[1]
if input == parts[0] || strings.EqualFold(input, parts[1]) { // Check if input matches either the number or the symbol
symbol = parts[1] if inputStr == voucherNum || strings.EqualFold(inputStr, voucherSymbol) {
if i < len(balList) { matchedSymbol = voucherSymbol
balance = strings.SplitN(balList[i], ":", 2)[1] // Ensure there's a corresponding balance
} if i < len(balances) {
if i < len(decList) { matchedBalance = strings.SplitN(balances[i], ":", 2)[1]
decimal = strings.SplitN(decList[i], ":", 2)[1]
}
if i < len(addrList) {
address = strings.SplitN(addrList[i], ":", 2)[1]
} }
break break
} }
} }
return
} return matchedSymbol, matchedBalance
func (h *Handlers) storeTemporaryVoucher(ctx context.Context, sessionId string, data *VoucherMetadata) error {
entries := map[utils.DataTyp][]byte{
utils.DATA_TEMPORARY_SYM: []byte(data.Symbol),
utils.DATA_TEMPORARY_BAL: []byte(data.Balance),
utils.DATA_TEMPORARY_DECIMAL: []byte(data.Decimal),
utils.DATA_TEMPORARY_ADDRESS: []byte(data.Address),
}
for key, value := range entries {
if err := h.userdataStore.WriteEntry(ctx, sessionId, key, value); err != nil {
return err
}
}
return nil
} }
// SetVoucher retrieves the temporary sym and balance,
// sets them as the active data and
// clears the temporary data
func (h *Handlers) SetVoucher(ctx context.Context, sym string, input []byte) (resource.Result, error) { func (h *Handlers) SetVoucher(ctx context.Context, sym string, input []byte) (resource.Result, error) {
var res resource.Result var res resource.Result
var err error var err error
store := h.userdataStore
sessionId, ok := ctx.Value("SessionId").(string) sessionId, ok := ctx.Value("SessionId").(string)
if !ok { if !ok {
return res, fmt.Errorf("missing session") return res, fmt.Errorf("missing session")
} }
// Get temporary data // get the current temporary symbol
tempData, err := h.getTemporaryVoucherData(ctx, sessionId) temporarySym, err := store.ReadEntry(ctx, sessionId, utils.DATA_TEMPORARY_SYM)
if err != nil { if err != nil {
return resource.Result{}, err return res, err
}
// get the current temporary balance
temporaryBal, err := store.ReadEntry(ctx, sessionId, utils.DATA_TEMPORARY_BAL)
if err != nil {
return res, err
} }
// Set as active and clear temporary // set the active symbol
if err := h.updateVoucherData(ctx, sessionId, tempData); err != nil { err = store.WriteEntry(ctx, sessionId, utils.DATA_ACTIVE_SYM, []byte(temporarySym))
return resource.Result{}, err if err != nil {
return res, err
}
// set the active balance
err = store.WriteEntry(ctx, sessionId, utils.DATA_ACTIVE_BAL, []byte(temporaryBal))
if err != nil {
return res, err
} }
return resource.Result{Content: tempData.Symbol}, nil // reset the temporary symbol
} err = store.WriteEntry(ctx, sessionId, utils.DATA_TEMPORARY_SYM, []byte(""))
if err != nil {
func (h *Handlers) getTemporaryVoucherData(ctx context.Context, sessionId string) (*VoucherMetadata, error) { return res, err
store := h.userdataStore }
// reset the temporary balance
keys := []utils.DataTyp{ err = store.WriteEntry(ctx, sessionId, utils.DATA_TEMPORARY_BAL, []byte(""))
utils.DATA_TEMPORARY_SYM, if err != nil {
utils.DATA_TEMPORARY_BAL, return res, err
utils.DATA_TEMPORARY_DECIMAL, }
utils.DATA_TEMPORARY_ADDRESS,
} res.Content = string(temporarySym)
data := &VoucherMetadata{} return res, nil
values := make([][]byte, len(keys))
for i, key := range keys {
value, err := store.ReadEntry(ctx, sessionId, key)
if err != nil {
return nil, err
}
values[i] = value
}
data.Symbol = string(values[0])
data.Balance = string(values[1])
data.Decimal = string(values[2])
data.Address = string(values[3])
return data, nil
}
func (h *Handlers) updateVoucherData(ctx context.Context, sessionId string, data *VoucherMetadata) error {
// Set active voucher data
activeEntries := map[utils.DataTyp][]byte{
utils.DATA_ACTIVE_SYM: []byte(data.Symbol),
utils.DATA_ACTIVE_BAL: []byte(data.Balance),
utils.DATA_ACTIVE_DECIMAL: []byte(data.Decimal),
utils.DATA_ACTIVE_ADDRESS: []byte(data.Address),
}
// Clear temporary voucher data
tempEntries := map[utils.DataTyp][]byte{
utils.DATA_TEMPORARY_SYM: []byte(""),
utils.DATA_TEMPORARY_BAL: []byte(""),
utils.DATA_TEMPORARY_DECIMAL: []byte(""),
utils.DATA_TEMPORARY_ADDRESS: []byte(""),
}
// Write all entries
for key, value := range activeEntries {
if err := h.userdataStore.WriteEntry(ctx, sessionId, key, value); err != nil {
return err
}
}
for key, value := range tempEntries {
if err := h.userdataStore.WriteEntry(ctx, sessionId, key, value); err != nil {
return err
}
}
return nil
} }

View File

@ -28,10 +28,6 @@ const (
DATA_ACTIVE_SYM DATA_ACTIVE_SYM
DATA_TEMPORARY_BAL DATA_TEMPORARY_BAL
DATA_ACTIVE_BAL DATA_ACTIVE_BAL
DATA_TEMPORARY_DECIMAL
DATA_ACTIVE_DECIMAL
DATA_TEMPORARY_ADDRESS
DATA_ACTIVE_ADDRESS
) )
func typToBytes(typ DataTyp) []byte { func typToBytes(typ DataTyp) []byte {