Compare commits

...

28 Commits

Author SHA1 Message Date
2181388f5b Merge pull request 'dev-api-aliases-v2' (#6) from dev-api-aliases-v2 into master
Reviewed-on: #6
2025-01-23 15:28:05 +01:00
448fdffbd0
untie session id to saved aliases 2025-01-23 12:05:23 +03:00
4ae0a484f4
run go mod tidy 2025-01-23 10:43:19 +03:00
3f9dc89a40
resolve alias address based on UseApi field 2025-01-22 17:19:46 +03:00
bc7afa50a4
dep: downgrade vise-driver 2025-01-22 15:53:28 +03:00
9c75109b75
use dev storage service 2025-01-22 15:35:16 +03:00
lash
ee574908d4
Gofmt 2025-01-21 15:30:22 +00:00
lash
e0b5398098 Merge remote-tracking branch 'origin/master' into lash/alias-deps 2025-01-21 13:51:50 +00:00
lash
b7e53609a9
Upgrade deps 2025-01-21 13:51:07 +00:00
a4cc7d2a98 Merge pull request 'dev-api-aliases' (#5) from dev-api-aliases into master
Reviewed-on: #5
2025-01-21 07:17:09 +01:00
a63164bcf5
fix failing test 2025-01-21 08:45:03 +03:00
fa355e3729
handle accounts created via the api,add getter for the account aliases 2025-01-20 22:28:16 +03:00
99c704f6ff
implement request alias based on dev implementation 2025-01-20 20:12:56 +03:00
ed549cba70
bind session id for aliases,soft code voucher balance 2025-01-20 20:11:08 +03:00
8a47d1d674
implement request alias 2025-01-20 17:28:03 +03:00
23b4180e50
persist aliases,construct the fqdn 2025-01-20 17:27:19 +03:00
b22ff1e7f0 Merge pull request 'Implement alias handling dev api' (#3) from lash/alias into master
Reviewed-on: #3
2025-01-15 08:37:53 +01:00
lash
bca7c5de96
Make prefix settable in dev api 2025-01-15 07:22:14 +00:00
lash
c128678f4a
Upgrade dep 2025-01-15 00:33:59 +00:00
lash
7001d1f828
Use storage service and db dumper in dev api 2025-01-15 00:12:38 +00:00
lash
9645a2af7b
Correct result structs for mock/test api implementations 2025-01-14 14:20:51 +00:00
lash
7a96b85b28
Correct alias result struct 2025-01-14 13:57:18 +00:00
lash
18a30a0065
Add dev api for alias handling' 2025-01-14 13:53:29 +00:00
lash
a4976e6c52
Move api mock from sarafu vise events 2025-01-14 07:29:12 +00:00
lash
7c697394b5
Add token mint event tag 2025-01-13 21:36:45 +00:00
lash
37bb460561
Import event handling 2025-01-13 20:17:55 +00:00
lash
5511955438
Add dev event converters 2025-01-13 18:13:51 +00:00
lash
25149ff265
Move in events specs from vise events 2025-01-13 16:33:55 +00:00
12 changed files with 613 additions and 134 deletions

View File

@ -71,4 +71,3 @@ func LoadConfig() error {
CheckAliasURL, _ = url.JoinPath(dataURLBase, AliasPrefix) CheckAliasURL, _ = url.JoinPath(dataURLBase, AliasPrefix)
return nil return nil
} }

View File

@ -1,26 +1,31 @@
package dev package dev
import ( import (
"bytes"
"context" "context"
"crypto/sha1" "crypto/sha1"
"encoding/json" "encoding/json"
"fmt" "fmt"
"math/rand" "math/rand"
"os" "regexp"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/gofrs/uuid"
"git.defalsify.org/vise.git/logging"
"git.defalsify.org/vise.git/db" "git.defalsify.org/vise.git/db"
fsdb "git.defalsify.org/vise.git/db/fs" "git.defalsify.org/vise.git/logging"
"git.grassecon.net/grassrootseconomics/common/phone"
"git.grassecon.net/grassrootseconomics/sarafu-api/event"
"git.grassecon.net/grassrootseconomics/sarafu-api/models" "git.grassecon.net/grassrootseconomics/sarafu-api/models"
"git.grassecon.net/grassrootseconomics/visedriver/storage"
"github.com/gofrs/uuid"
dataserviceapi "github.com/grassrootseconomics/ussd-data-service/pkg/api" dataserviceapi "github.com/grassrootseconomics/ussd-data-service/pkg/api"
) )
var ( var (
logg = logging.NewVanilla().WithDomain("sarafu-api.devapi") logg = logging.NewVanilla().WithDomain("sarafu-api.devapi")
aliasRegex = regexp.MustCompile("^\\+?[a-zA-Z0-9\\-_]+$")
searchDomain = ".sarafu.local"
) )
const ( const (
@ -28,6 +33,7 @@ const (
hashLen int = 32 hashLen int = 32
defaultDecimals = 6 defaultDecimals = 6
zeroAddress string = "0x0000000000000000000000000000000000000000" zeroAddress string = "0x0000000000000000000000000000000000000000"
defaultVoucherBalance float64 = 500.00
) )
type Tx struct { type Tx struct {
@ -40,6 +46,25 @@ type Tx struct {
When time.Time `json: "when"` When time.Time `json: "when"`
} }
func (t *Tx) ToTransferEvent() event.EventTokenTransfer {
return event.EventTokenTransfer{
To: t.To,
Value: t.Value,
VoucherAddress: t.Voucher,
TxHash: t.Hsh,
From: t.From,
}
}
func (t *Tx) ToMintEvent() event.EventTokenMint {
return event.EventTokenMint{
To: t.To,
Value: t.Value,
VoucherAddress: t.Voucher,
TxHash: t.Hsh,
}
}
type Account struct { type Account struct {
Track string `json: "track"` Track string `json: "track"`
Address string `json: "address"` Address string `json: "address"`
@ -50,6 +75,12 @@ type Account struct {
Txs []string `json: "txs"` Txs []string `json: "txs"`
} }
func (a *Account) ToRegistrationEvent() event.EventCustodialRegistration {
return event.EventCustodialRegistration{
Account: a.Address,
}
}
type Voucher struct { type Voucher struct {
Name string `json: "name"` Name string `json: "name"`
Address string `json: "address"` Address string `json: "address"`
@ -61,7 +92,6 @@ type Voucher struct {
} }
type DevAccountService struct { type DevAccountService struct {
dir string
db db.Db db db.Db
accounts map[string]Account accounts map[string]Account
accountsTrack map[string]string accountsTrack map[string]string
@ -74,13 +104,12 @@ type DevAccountService struct {
autoVouchers []string autoVouchers []string
autoVoucherValue map[string]int autoVoucherValue map[string]int
defaultAccount string defaultAccount string
// accountsSession map[string]string emitterFunc event.EmitterFunc
pfx []byte
} }
func NewDevAccountService(ctx context.Context, d string) *DevAccountService { func NewDevAccountService(ctx context.Context, ss storage.StorageService) *DevAccountService {
svc := &DevAccountService{ svc := &DevAccountService{
dir: d,
db: fsdb.NewFsDb(),
accounts: make(map[string]Account), accounts: make(map[string]Account),
accountsTrack: make(map[string]string), accountsTrack: make(map[string]string),
accountsAlias: make(map[string]string), accountsAlias: make(map[string]string),
@ -90,23 +119,42 @@ func NewDevAccountService(ctx context.Context, d string) *DevAccountService {
txsTrack: make(map[string]string), txsTrack: make(map[string]string),
autoVoucherValue: make(map[string]int), autoVoucherValue: make(map[string]int),
defaultAccount: zeroAddress, defaultAccount: zeroAddress,
pfx: []byte("__"),
}
if ss != nil {
var err error
svc.db, err = ss.GetUserdataDb(ctx)
if err != nil {
panic(err)
}
svc.db.SetSession("")
svc.db.SetPrefix(db.DATATYPE_USERDATA)
err = svc.loadAll(ctx)
if err != nil {
logg.DebugCtxf(ctx, "loadall error", "err", err)
}
} }
acc := Account{ acc := Account{
Address: zeroAddress, Address: zeroAddress,
} }
svc.accounts[acc.Address] = acc svc.accounts[acc.Address] = acc
err := svc.db.Connect(ctx, d)
if err != nil {
panic(err)
}
svc.db.SetPrefix(db.DATATYPE_USERDATA)
err = svc.loadAll(ctx)
if err != nil {
panic(err)
}
return svc return svc
} }
func (das *DevAccountService) WithEmitter(fn event.EmitterFunc) *DevAccountService {
das.emitterFunc = fn
return das
}
func (das *DevAccountService) WithPrefix(pfx []byte) *DevAccountService {
das.pfx = pfx
return das
}
func (das *DevAccountService) prefixKeyFor(k string, v string) []byte {
return append(das.pfx, []byte(k+"_"+v)...)
}
func (das *DevAccountService) loadAccount(ctx context.Context, pubKey string, v []byte) error { func (das *DevAccountService) loadAccount(ctx context.Context, pubKey string, v []byte) error {
var acc Account var acc Account
@ -136,10 +184,19 @@ func (das *DevAccountService) loadTx(ctx context.Context, hsh string, v []byte)
return nil return nil
} }
func (das *DevAccountService) loadAlias(ctx context.Context, alias string, key []byte) error {
result, err := das.db.Get(ctx, key)
if err != nil {
return err
}
das.accountsAlias[alias] = strings.ReplaceAll(string(result), `"`, "")
return nil
}
func (das *DevAccountService) loadItem(ctx context.Context, k []byte, v []byte) error { func (das *DevAccountService) loadItem(ctx context.Context, k []byte, v []byte) error {
var err error var err error
s := string(k) s := string(k)
ss := strings.SplitN(s, "_", 2) ss := strings.SplitN(s[2:], "_", 2)
if len(ss) != 2 { if len(ss) != 2 {
return fmt.Errorf("malformed key: %s", s) return fmt.Errorf("malformed key: %s", s)
} }
@ -147,6 +204,10 @@ func (das *DevAccountService) loadItem(ctx context.Context, k []byte, v []byte)
err = das.loadAccount(ctx, ss[1], v) err = das.loadAccount(ctx, ss[1], v)
} else if ss[0] == "tx" { } else if ss[0] == "tx" {
err = das.loadTx(ctx, ss[1], v) err = das.loadTx(ctx, ss[1], v)
} else if ss[0] == "alias" {
err = das.loadAlias(ctx, ss[1], k)
} else {
logg.ErrorCtxf(ctx, "unknown double underscore key", "key", ss[0])
} }
return err return err
} }
@ -154,18 +215,19 @@ func (das *DevAccountService) loadItem(ctx context.Context, k []byte, v []byte)
// TODO: Add connect tx and account // TODO: Add connect tx and account
// TODO: update balance // TODO: update balance
func (das *DevAccountService) loadAll(ctx context.Context) error { func (das *DevAccountService) loadAll(ctx context.Context) error {
d, err := os.ReadDir(das.dir) dumper, err := das.db.Dump(ctx, []byte{})
if err != nil { if err != nil {
return err return err
} }
for _, v := range(d) { for true {
// TODO: move decoding to vise k, v := dumper.Next(ctx)
fp := v.Name() if k == nil {
k := []byte(fp[1:]) break
v, err := das.db.Get(ctx, k)
if err != nil {
return err
} }
if !bytes.HasPrefix(k, das.pfx) {
continue
}
err = das.loadItem(ctx, k, v) err = das.loadItem(ctx, k, v)
if err != nil { if err != nil {
return err return err
@ -175,7 +237,7 @@ func (das *DevAccountService) loadAll(ctx context.Context) error {
} }
func (das *DevAccountService) indexAll(ctx context.Context) error { func (das *DevAccountService) indexAll(ctx context.Context) error {
for k, v := range(das.txs) { for k, v := range das.txs {
acc := das.accounts[v.From] acc := das.accounts[v.From]
acc.Txs = append(acc.Txs, k) acc.Txs = append(acc.Txs, k)
logg.TraceCtxf(ctx, "add tx to sender index", "from", v.From, "tx", k) logg.TraceCtxf(ctx, "add tx to sender index", "from", v.From, "tx", k)
@ -238,14 +300,14 @@ func (das *DevAccountService) CheckBalance(ctx context.Context, publicKey string
if !ok { if !ok {
return nil, fmt.Errorf("balance not found for default token %s pubkey %v", acc.DefaultVoucher, publicKey) return nil, fmt.Errorf("balance not found for default token %s pubkey %v", acc.DefaultVoucher, publicKey)
} }
return &models.BalanceResult { return &models.BalanceResult{
Balance: strconv.Itoa(bal), Balance: strconv.Itoa(bal),
Nonce: json.Number(strconv.Itoa(acc.Nonce)), Nonce: json.Number(strconv.Itoa(acc.Nonce)),
}, nil }, nil
} }
func (das *DevAccountService) balanceAuto(ctx context.Context, pubKey string) error { func (das *DevAccountService) balanceAuto(ctx context.Context, pubKey string) error {
for _, v := range(das.autoVouchers) { for _, v := range das.autoVouchers {
voucher, ok := das.vouchers[v] voucher, ok := das.vouchers[v]
if !ok { if !ok {
return fmt.Errorf("balance auto voucher set but not resolved: %s", v) return fmt.Errorf("balance auto voucher set but not resolved: %s", v)
@ -262,15 +324,41 @@ func (das *DevAccountService) balanceAuto(ctx context.Context, pubKey string) er
return nil return nil
} }
func (das *DevAccountService) GetAliases(ctx context.Context) map[string]string {
return das.accountsAlias
}
func (das *DevAccountService) saveAccount(ctx context.Context, acc Account) error { func (das *DevAccountService) saveAccount(ctx context.Context, acc Account) error {
k := "account_" + acc.Address if das.db == nil {
return nil
}
k := das.prefixKeyFor("account", acc.Address)
v, err := json.Marshal(acc) v, err := json.Marshal(acc)
if err != nil { if err != nil {
return err return err
} }
das.db.SetSession("")
das.db.SetPrefix(db.DATATYPE_USERDATA)
return das.db.Put(ctx, []byte(k), v) return das.db.Put(ctx, []byte(k), v)
} }
func (das *DevAccountService) saveAlias(ctx context.Context, alias map[string]string) error {
if das.db == nil {
return fmt.Errorf("Db cannot be nil")
}
for k, v := range alias {
k_ := das.prefixKeyFor("alias", k)
v_, err := json.Marshal(v)
if err != nil {
return err
}
das.db.SetSession("")
das.db.SetPrefix(db.DATATYPE_USERDATA)
return das.db.Put(ctx, []byte(k_), v_)
}
return nil
}
func (das *DevAccountService) CreateAccount(ctx context.Context) (*models.AccountResult, error) { func (das *DevAccountService) CreateAccount(ctx context.Context) (*models.AccountResult, error) {
var b [pubKeyLen]byte var b [pubKeyLen]byte
uid, err := uuid.NewV4() uid, err := uuid.NewV4()
@ -306,7 +394,17 @@ func (das *DevAccountService) CreateAccount(ctx context.Context) (*models.Accoun
das.defaultAccount = pubKey das.defaultAccount = pubKey
} }
logg.InfoCtxf(ctx, "account created", "account", acc) if das.emitterFunc != nil {
msg := event.Msg{
Typ: event.EventRegistrationTag,
Item: acc,
}
err = das.emitterFunc(ctx, msg)
if err != nil {
logg.ErrorCtxf(ctx, "emitter returned error", "err", err, "msg", msg)
}
}
logg.TraceCtxf(ctx, "account created", "account", acc)
return &models.AccountResult{ return &models.AccountResult{
PublicKey: pubKey, PublicKey: pubKey,
@ -327,22 +425,20 @@ func (das *DevAccountService) TrackAccountStatus(ctx context.Context, publicKey
func (das *DevAccountService) FetchVouchers(ctx context.Context, publicKey string) ([]dataserviceapi.TokenHoldings, error) { func (das *DevAccountService) FetchVouchers(ctx context.Context, publicKey string) ([]dataserviceapi.TokenHoldings, error) {
var holdings []dataserviceapi.TokenHoldings var holdings []dataserviceapi.TokenHoldings
acc, ok := das.accounts[publicKey] _, ok := das.accounts[publicKey]
if !ok { if !ok {
return nil, fmt.Errorf("account not found (publickey): %v", publicKey) return nil, fmt.Errorf("account not found (publickey): %v", publicKey)
} }
for k, v := range(acc.Balances) { //TODO: Iterate over the account acc.Balances object
voucher, ok := das.vouchers[k] for _, voucher := range das.vouchers {
if !ok {
return nil, fmt.Errorf("voucher has balance but object not found: %v", k)
}
holdings = append(holdings, dataserviceapi.TokenHoldings{ holdings = append(holdings, dataserviceapi.TokenHoldings{
ContractAddress: voucher.Address, ContractAddress: voucher.Address,
TokenSymbol: voucher.Symbol, TokenSymbol: voucher.Symbol,
TokenDecimals: strconv.Itoa(voucher.Decimals), TokenDecimals: strconv.Itoa(voucher.Decimals),
Balance: strconv.Itoa(v), Balance: strconv.Itoa(int(defaultVoucherBalance)),
}) })
} }
return holdings, nil return holdings, nil
} }
@ -352,7 +448,7 @@ func (das *DevAccountService) FetchTransactions(ctx context.Context, publicKey s
if !ok { if !ok {
return nil, fmt.Errorf("account not found (publickey): %v", publicKey) return nil, fmt.Errorf("account not found (publickey): %v", publicKey)
} }
for i, v := range(acc.Txs) { for i, v := range acc.Txs {
mytx := das.txs[v] mytx := das.txs[v]
if i == 10 { if i == 10 {
break break
@ -391,16 +487,17 @@ func (das *DevAccountService) VoucherData(ctx context.Context, address string) (
SinkAddress: voucher.Sink, SinkAddress: voucher.Sink,
TokenCommodity: voucher.Commodity, TokenCommodity: voucher.Commodity,
TokenLocation: voucher.Location, TokenLocation: voucher.Location,
}, nil }, nil
} }
func (das *DevAccountService) saveTokenTransfer(ctx context.Context, mytx Tx) error { func (das *DevAccountService) saveTokenTransfer(ctx context.Context, mytx Tx) error {
k := "tx_" + mytx.Hsh k := das.prefixKeyFor("tx", mytx.Hsh)
v, err := json.Marshal(mytx) v, err := json.Marshal(mytx)
if err != nil { if err != nil {
return err return err
} }
das.db.SetSession("")
das.db.SetPrefix(db.DATATYPE_USERDATA)
return das.db.Put(ctx, []byte(k), v) return das.db.Put(ctx, []byte(k), v)
} }
@ -458,13 +555,23 @@ func (das *DevAccountService) TokenTransfer(ctx context.Context, amount, from, t
return nil, err return nil, err
} }
das.txs[hsh] = mytx das.txs[hsh] = mytx
logg.InfoCtxf(ctx, "token transfer created", "tx", mytx) if das.emitterFunc != nil {
msg := event.Msg{
Typ: event.EventTokenTransferTag,
Item: mytx,
}
err = das.emitterFunc(ctx, msg)
if err != nil {
logg.ErrorCtxf(ctx, "emitter returned error", "err", err, "msg", msg)
}
}
logg.TraceCtxf(ctx, "token transfer created", "tx", mytx)
return &models.TokenTransferResponse{ return &models.TokenTransferResponse{
TrackingId: uid.String(), TrackingId: uid.String(),
}, nil }, nil
} }
func (das *DevAccountService) CheckAliasAddress(ctx context.Context, alias string) (*dataserviceapi.AliasAddress, error) { func (das *DevAccountService) CheckAliasAddress(ctx context.Context, alias string) (*models.AliasAddress, error) {
addr, ok := das.accountsAlias[alias] addr, ok := das.accountsAlias[alias]
if !ok { if !ok {
return nil, fmt.Errorf("alias %s not found", alias) return nil, fmt.Errorf("alias %s not found", alias)
@ -473,7 +580,67 @@ func (das *DevAccountService) CheckAliasAddress(ctx context.Context, alias strin
if !ok { if !ok {
return nil, fmt.Errorf("alias %s found but does not resolve", alias) return nil, fmt.Errorf("alias %s found but does not resolve", alias)
} }
return &dataserviceapi.AliasAddress{ return &models.AliasAddress{
Address: acc.Address, Address: acc.Address,
}, nil }, nil
} }
func (das *DevAccountService) applyPhoneAlias(ctx context.Context, publicKey string, phoneNumber string) (bool, error) {
if phoneNumber[0] == '+' {
if !phone.IsValidPhoneNumber(phoneNumber) {
return false, fmt.Errorf("Invalid phoneNumber number: %v", phoneNumber)
}
logg.DebugCtxf(ctx, "matched phoneNumber alias", "phoneNumber", phoneNumber, "address", publicKey)
return true, nil
}
return false, nil
}
func (das *DevAccountService) RequestAlias(ctx context.Context, publicKey string, hint string) (*models.RequestAliasResult, error) {
var alias string
uid, err := uuid.NewV4()
if !aliasRegex.MatchString(hint) {
return nil, fmt.Errorf("alias hint does not match: %s", publicKey)
}
acc, ok := das.accounts[publicKey]
if !ok {
//Handle accounts created via the api
acc = Account{
Track: uid.String(),
Address: publicKey,
}
err = das.saveAccount(ctx, acc)
if err != nil {
return nil, err
}
das.accounts[publicKey] = acc
}
alias = hint
isPhone, err := das.applyPhoneAlias(ctx, publicKey, alias)
if err != nil {
return nil, fmt.Errorf("phone parser error: %v", err)
}
if !isPhone {
for true {
addr, ok := das.accountsAlias[alias]
if !ok {
break
}
if addr == publicKey {
break
}
alias += "x"
}
acc.Alias = alias
alias = alias + searchDomain
das.accountsAlias[alias] = publicKey
err := das.saveAlias(ctx, map[string]string{alias: publicKey})
if err != nil {
return nil, fmt.Errorf("Failed to save the account alias with error: %s", err.Error())
}
}
logg.DebugCtxf(ctx, "set alias", "addr", publicKey, "alias", alias)
return &models.RequestAliasResult{
Alias: alias,
}, nil
}

77
dev/api_test.go Normal file
View File

@ -0,0 +1,77 @@
package dev
import (
"context"
"testing"
"git.grassecon.net/grassrootseconomics/visedriver/testutil/mocks"
)
func TestApiRequestAlias(t *testing.T) {
ctx := context.Background()
ctx = context.WithValue(ctx, "SessionId", "+25471234565")
storageService := mocks.NewMemStorageService(ctx)
svc := NewDevAccountService(ctx, storageService)
ra, err := svc.CreateAccount(ctx)
if err != nil {
t.Fatal(err)
}
addr := ra.PublicKey
_, err = svc.RequestAlias(ctx, addr, "+254f00")
if err == nil {
t.Fatalf("expected error")
}
alias := "+254712345678"
rb, err := svc.RequestAlias(ctx, addr, alias)
if err != nil {
t.Fatal(err)
}
if rb.Alias != alias {
t.Fatalf("expected '%s', got '%s'", alias, rb.Alias)
}
_, err = svc.CheckAliasAddress(ctx, alias)
if err == nil {
t.Fatalf("expected error")
}
alias = "foo"
rb, err = svc.RequestAlias(ctx, addr, alias)
if err != nil {
t.Fatal(err)
}
alias = "foo.sarafu.local"
if rb.Alias != alias {
t.Fatalf("expected '%s', got '%s'", alias, rb.Alias)
}
rc, err := svc.CheckAliasAddress(ctx, alias)
if err != nil {
t.Fatal(err)
}
if rc.Address != addr {
t.Fatalf("expected '%s', got '%s'", addr, rc.Address)
}
// create a second account
ra, err = svc.CreateAccount(ctx)
if err != nil {
t.Fatal(err)
}
addr = ra.PublicKey
alias = "foox"
rb, err = svc.RequestAlias(ctx, addr, alias)
if err != nil {
t.Fatal(err)
}
alias = "foox.sarafu.local"
if rb.Alias != alias {
t.Fatalf("expected '%s', got '%s'", alias, rb.Alias)
}
rc, err = svc.CheckAliasAddress(ctx, alias)
if err != nil {
t.Fatal(err)
}
if rc.Address != addr {
t.Fatalf("expected '%s', got '%s'", addr, rc.Address)
}
}

66
event/msg.go Normal file
View File

@ -0,0 +1,66 @@
package event
import (
"context"
"fmt"
)
const (
// TODO: integrate with sarafu-vise-events
EventTokenTransferTag = "TOKEN_TRANSFER"
EventTokenMintTag = "TOKEN_MINT"
EventRegistrationTag = "CUSTODIAL_REGISTRATION"
)
type Msg struct {
Typ string
Item any
}
type EmitterFunc func(context.Context, Msg) error
// fields used for handling custodial registration event.
type EventCustodialRegistration struct {
Account string
}
// fields used for handling token transfer event.
type EventTokenTransfer struct {
To string
Value int
VoucherAddress string
TxHash string
From string
}
type EventTokenMint struct {
To string
Value int
TxHash string
VoucherAddress string
}
type EventsHandlerFunc func(context.Context, any) error
type EventsHandler struct {
handlers map[string]EventsHandlerFunc
}
func NewEventsHandler() *EventsHandler {
return &EventsHandler{
handlers: make(map[string]EventsHandlerFunc),
}
}
func (eh *EventsHandler) WithHandler(tag string, fn EventsHandlerFunc) *EventsHandler {
eh.handlers[tag] = fn
return eh
}
func (eh *EventsHandler) Handle(ctx context.Context, tag string, o any) error {
fn, ok := eh.handlers[tag]
if !ok {
return fmt.Errorf("Handler not registered for tag: %s", tag)
}
return fn(ctx, o)
}

19
go.mod
View File

@ -3,8 +3,9 @@ module git.grassecon.net/grassrootseconomics/sarafu-api
go 1.23.4 go 1.23.4
require ( require (
git.defalsify.org/vise.git v0.2.3-0.20250103172917-3e190a44568d git.defalsify.org/vise.git v0.2.3-0.20250120121301-10739fb4a8c9
git.grassecon.net/grassrootseconomics/visedriver v0.8.0-beta.10.0.20250113103142-5bf0a0e85893 git.grassecon.net/grassrootseconomics/common v0.0.0-20250121134736-ba8cbbccea7d
git.grassecon.net/grassrootseconomics/visedriver v0.8.0-beta.10.0.20250122123424-6749c632b0a2
github.com/gofrs/uuid v4.4.0+incompatible github.com/gofrs/uuid v4.4.0+incompatible
github.com/grassrootseconomics/eth-custodial v1.3.0-beta github.com/grassrootseconomics/eth-custodial v1.3.0-beta
github.com/grassrootseconomics/ussd-data-service v1.2.0-beta github.com/grassrootseconomics/ussd-data-service v1.2.0-beta
@ -14,8 +15,22 @@ require (
require ( require (
github.com/barbashov/iso639-3 v0.0.0-20211020172741-1f4ffb2d8d1c // indirect github.com/barbashov/iso639-3 v0.0.0-20211020172741-1f4ffb2d8d1c // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/fxamacker/cbor/v2 v2.4.0 // indirect
github.com/graygnuorg/go-gdbm v0.0.0-20220711140707-71387d66dce4 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.7.1 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/joho/godotenv v1.5.1 // indirect github.com/joho/godotenv v1.5.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/mattn/kinako v0.0.0-20170717041458-332c0a7e205a // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/rogpeppe/go-internal v1.13.1 // indirect
github.com/stretchr/objx v0.5.2 // indirect github.com/stretchr/objx v0.5.2 // indirect
github.com/x448/float16 v0.8.4 // indirect
golang.org/x/crypto v0.32.0 // indirect
golang.org/x/sync v0.10.0 // indirect
golang.org/x/text v0.21.0 // indirect
gopkg.in/leonelquinteros/gotext.v1 v1.3.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
) )

54
go.sum
View File

@ -1,26 +1,70 @@
git.defalsify.org/vise.git v0.2.3-0.20250103172917-3e190a44568d h1:bPAOVZOX4frSGhfOdcj7kc555f8dc9DmMd2YAyC2AMw= git.defalsify.org/vise.git v0.2.3-0.20250120121301-10739fb4a8c9 h1:sPcqXQcywxA8W3W+9qQncLPmsrgqTIlec7vmD4/7vyA=
git.defalsify.org/vise.git v0.2.3-0.20250103172917-3e190a44568d/go.mod h1:jyBMe1qTYUz3mmuoC9JQ/TvFeW0vTanCUcPu3H8p4Ck= git.defalsify.org/vise.git v0.2.3-0.20250120121301-10739fb4a8c9/go.mod h1:jyBMe1qTYUz3mmuoC9JQ/TvFeW0vTanCUcPu3H8p4Ck=
git.grassecon.net/grassrootseconomics/visedriver v0.8.0-beta.10.0.20250113103142-5bf0a0e85893 h1:MyDINzwY1sjfXkIFoc+6T5lXF/1xdFV6yjHrpSNZzWM= git.grassecon.net/grassrootseconomics/common v0.0.0-20250121134736-ba8cbbccea7d h1:5mzLas+jxTUtusOKx4XvU+n2QvrV/mH17MnJRy46siQ=
git.grassecon.net/grassrootseconomics/visedriver v0.8.0-beta.10.0.20250113103142-5bf0a0e85893/go.mod h1:E6W7ZOa7ZvVr0Bc5ot0LNSwpSPYq4hXlAIvEPy3AJ7U= git.grassecon.net/grassrootseconomics/common v0.0.0-20250121134736-ba8cbbccea7d/go.mod h1:wgQJZGIS6QuNLHqDhcsvehsbn5PvgV7aziRebMnJi60=
git.grassecon.net/grassrootseconomics/visedriver v0.8.0-beta.10.0.20250122123424-6749c632b0a2 h1:ON77G5K0JNuwPb5JT/hRfF6G6+xstlBQgEIEzWydnhg=
git.grassecon.net/grassrootseconomics/visedriver v0.8.0-beta.10.0.20250122123424-6749c632b0a2/go.mod h1:pjKp9L/ZsWW3kMB0UoIl1yv9TBIuU33mn9Aghxp7vGk=
github.com/barbashov/iso639-3 v0.0.0-20211020172741-1f4ffb2d8d1c h1:H9Nm+I7Cg/YVPpEV1RzU3Wq2pjamPc/UtHDgItcb7lE= github.com/barbashov/iso639-3 v0.0.0-20211020172741-1f4ffb2d8d1c h1:H9Nm+I7Cg/YVPpEV1RzU3Wq2pjamPc/UtHDgItcb7lE=
github.com/barbashov/iso639-3 v0.0.0-20211020172741-1f4ffb2d8d1c/go.mod h1:rGod7o6KPeJ+hyBpHfhi4v7blx9sf+QsHsA7KAsdN6U= github.com/barbashov/iso639-3 v0.0.0-20211020172741-1f4ffb2d8d1c/go.mod h1:rGod7o6KPeJ+hyBpHfhi4v7blx9sf+QsHsA7KAsdN6U=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fxamacker/cbor/v2 v2.4.0 h1:ri0ArlOR+5XunOP8CRUowT0pSJOwhW098ZCUyskZD88=
github.com/fxamacker/cbor/v2 v2.4.0/go.mod h1:TA1xS00nchWmaBnEIxPSE5oHLuJBAVvqrtAnWBwBCVo=
github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA= github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA=
github.com/gofrs/uuid v4.4.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gofrs/uuid v4.4.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
github.com/grassrootseconomics/eth-custodial v1.3.0-beta h1:twrMBhl89GqDUL9PlkzQxMP/6OST1BByrNDj+rqXDmU= github.com/grassrootseconomics/eth-custodial v1.3.0-beta h1:twrMBhl89GqDUL9PlkzQxMP/6OST1BByrNDj+rqXDmU=
github.com/grassrootseconomics/eth-custodial v1.3.0-beta/go.mod h1:7uhRcdnJplX4t6GKCEFkbeDhhjlcaGJeJqevbcvGLZo= github.com/grassrootseconomics/eth-custodial v1.3.0-beta/go.mod h1:7uhRcdnJplX4t6GKCEFkbeDhhjlcaGJeJqevbcvGLZo=
github.com/grassrootseconomics/ussd-data-service v1.2.0-beta h1:fn1gwbWIwHVEBtUC2zi5OqTlfI/5gU1SMk0fgGixIXk= github.com/grassrootseconomics/ussd-data-service v1.2.0-beta h1:fn1gwbWIwHVEBtUC2zi5OqTlfI/5gU1SMk0fgGixIXk=
github.com/grassrootseconomics/ussd-data-service v1.2.0-beta/go.mod h1:omfI0QtUwIdpu9gMcUqLMCG8O1XWjqJGBx1qUMiGWC0= github.com/grassrootseconomics/ussd-data-service v1.2.0-beta/go.mod h1:omfI0QtUwIdpu9gMcUqLMCG8O1XWjqJGBx1qUMiGWC0=
github.com/graygnuorg/go-gdbm v0.0.0-20220711140707-71387d66dce4 h1:U4kkNYryi/qfbBF8gh7Vsbuz+cVmhf5kt6pE9bYYyLo=
github.com/graygnuorg/go-gdbm v0.0.0-20220711140707-71387d66dce4/go.mod h1:zpZDgZFzeq9s0MIeB1P50NIEWDFFHSFBohI/NbaTD/Y=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.1 h1:x7SYsPBYDkHDksogeSmZZ5xzThcTgRz++I5E+ePFUcs=
github.com/jackc/pgx/v5 v5.7.1/go.mod h1:e7O26IywZZ+naJtWWos6i6fvWK+29etgITqrqHLfoZA=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mattn/kinako v0.0.0-20170717041458-332c0a7e205a h1:0Q3H0YXzMHiciXtRcM+j0jiCe8WKPQHoRgQiRTnfcLY=
github.com/mattn/kinako v0.0.0-20170717041458-332c0a7e205a/go.mod h1:CdTTBOYzS5E4mWS1N8NWP6AHI19MP0A2B18n3hLzRMk=
github.com/pashagolub/pgxmock/v4 v4.3.0 h1:DqT7fk0OCK6H0GvqtcMsLpv8cIwWqdxWgfZNLeHCb/s=
github.com/pashagolub/pgxmock/v4 v4.3.0/go.mod h1:9VoVHXwS3XR/yPtKGzwQvwZX1kzGB9sM8SviDcHDa3A=
github.com/peteole/testdata-loader v0.3.0 h1:8jckE9KcyNHgyv/VPoaljvKZE0Rqr8+dPVYH6rfNr9I=
github.com/peteole/testdata-loader v0.3.0/go.mod h1:Mt0ZbRtb56u8SLJpNP+BnQbENljMorYBpqlvt3cS83U=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/leonelquinteros/gotext.v1 v1.3.1 h1:8d9/fdTG0kn/B7NNGV1BsEyvektXFAbkMsTZS2sFSCc=
gopkg.in/leonelquinteros/gotext.v1 v1.3.1/go.mod h1:X1WlGDeAFIYsW6GjgMm4VwUwZ2XjI7Zan2InxSUQWrU=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

9
models/alias_response.go Normal file
View File

@ -0,0 +1,9 @@
package models
type RequestAliasResult struct {
Alias string
}
type AliasAddress struct {
Address string
}

View File

@ -15,5 +15,6 @@ type AccountService interface {
FetchTransactions(ctx context.Context, publicKey string) ([]dataserviceapi.Last10TxResponse, error) FetchTransactions(ctx context.Context, publicKey string) ([]dataserviceapi.Last10TxResponse, error)
VoucherData(ctx context.Context, address string) (*models.VoucherDataResult, error) VoucherData(ctx context.Context, address string) (*models.VoucherDataResult, error)
TokenTransfer(ctx context.Context, amount, from, to, tokenAddress string) (*models.TokenTransferResponse, error) TokenTransfer(ctx context.Context, amount, from, to, tokenAddress string) (*models.TokenTransferResponse, error)
CheckAliasAddress(ctx context.Context, alias string) (*dataserviceapi.AliasAddress, error) CheckAliasAddress(ctx context.Context, alias string) (*models.AliasAddress, error)
RequestAlias(ctx context.Context, hint string, publicKey string) (*models.RequestAliasResult, error)
} }

View File

@ -5,18 +5,28 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt"
"io" "io"
"log" "log"
"net/http" "net/http"
"net/url" "net/url"
"regexp"
"git.grassecon.net/grassrootseconomics/sarafu-api/config" "git.grassecon.net/grassrootseconomics/sarafu-api/config"
"git.grassecon.net/grassrootseconomics/sarafu-api/dev"
"git.grassecon.net/grassrootseconomics/sarafu-api/models" "git.grassecon.net/grassrootseconomics/sarafu-api/models"
"git.grassecon.net/grassrootseconomics/visedriver/storage"
"github.com/grassrootseconomics/eth-custodial/pkg/api" "github.com/grassrootseconomics/eth-custodial/pkg/api"
dataserviceapi "github.com/grassrootseconomics/ussd-data-service/pkg/api" dataserviceapi "github.com/grassrootseconomics/ussd-data-service/pkg/api"
) )
var (
aliasRegex = regexp.MustCompile("^\\+?[a-zA-Z0-9\\-_]+$")
)
type HTTPAccountService struct { type HTTPAccountService struct {
SS storage.StorageService
UseApi bool
} }
// Parameters: // Parameters:
@ -202,23 +212,42 @@ func (as *HTTPAccountService) TokenTransfer(ctx context.Context, amount, from, t
// CheckAliasAddress retrieves the address of an alias from the API endpoint. // CheckAliasAddress retrieves the address of an alias from the API endpoint.
// Parameters: // Parameters:
// - alias: The alias of the user. // - alias: The alias of the user.
func (as *HTTPAccountService) CheckAliasAddress(ctx context.Context, alias string) (*dataserviceapi.AliasAddress, error) { func (as *HTTPAccountService) CheckAliasAddress(ctx context.Context, alias string) (*models.AliasAddress, error) {
var r dataserviceapi.AliasAddress if as.SS == nil {
return nil, fmt.Errorf("The storage service cannot be nil")
}
svc := dev.NewDevAccountService(ctx, as.SS)
if as.UseApi {
return resolveAliasAddress(ctx, alias)
} else {
return svc.CheckAliasAddress(ctx, alias)
}
}
func resolveAliasAddress(ctx context.Context, alias string) (*models.AliasAddress, error) {
var r models.AliasAddress
ep, err := url.JoinPath(config.CheckAliasURL, alias) ep, err := url.JoinPath(config.CheckAliasURL, alias)
if err != nil { if err != nil {
return nil, err return nil, err
} }
req, err := http.NewRequest("GET", ep, nil) req, err := http.NewRequest("GET", ep, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
_, err = doRequest(ctx, req, &r) _, err = doRequest(ctx, req, &r)
return &r, err return &r, err
} }
// TODO: Use actual custodial api to request available alias
func (as *HTTPAccountService) RequestAlias(ctx context.Context, publicKey string, hint string) (*models.RequestAliasResult, error) {
if as.SS == nil {
return nil, fmt.Errorf("The storage service cannot be nil")
}
svc := dev.NewDevAccountService(ctx, as.SS)
return svc.RequestAlias(ctx, publicKey, hint)
}
// TODO: remove eth-custodial api dependency // TODO: remove eth-custodial api dependency
func doRequest(ctx context.Context, req *http.Request, rcpt any) (*api.OKResponse, error) { func doRequest(ctx context.Context, req *http.Request, rcpt any) (*api.OKResponse, error) {
var okResponse api.OKResponse var okResponse api.OKResponse

View File

@ -0,0 +1,63 @@
package mocks
import (
"context"
"git.defalsify.org/vise.git/logging"
"git.grassecon.net/grassrootseconomics/sarafu-api/models"
dataserviceapi "github.com/grassrootseconomics/ussd-data-service/pkg/api"
)
var (
logg = logging.NewVanilla().WithDomain("sarafu-vise-events.testutil")
)
const (
AliceChecksum = "0xeae046BF396e91f5A8D74f863dC57c107c8a4a70"
BobChecksum = "0xB3117202371853e24B725d4169D87616A7dDb127"
AliceSession = "5553425"
)
type MockApi struct {
TransactionsContent []dataserviceapi.Last10TxResponse
VouchersContent []dataserviceapi.TokenHoldings
VoucherDataContent *models.VoucherDataResult
}
func (m MockApi) CheckBalance(ctx context.Context, publicKey string) (*models.BalanceResult, error) {
return nil, nil
}
func (m MockApi) CreateAccount(ctx context.Context) (*models.AccountResult, error) {
return nil, nil
}
func (m MockApi) TrackAccountStatus(ctx context.Context, publicKey string) (*models.TrackStatusResult, error) {
return nil, nil
}
func (m MockApi) FetchVouchers(ctx context.Context, publicKey string) ([]dataserviceapi.TokenHoldings, error) {
logg.DebugCtxf(ctx, "mockapi fetchvouchers", "key", publicKey)
return m.VouchersContent, nil
}
func (m MockApi) FetchTransactions(ctx context.Context, publicKey string) ([]dataserviceapi.Last10TxResponse, error) {
logg.DebugCtxf(ctx, "mockapi fetchtransactions", "key", publicKey)
return m.TransactionsContent, nil
}
func (m MockApi) VoucherData(ctx context.Context, address string) (*models.VoucherDataResult, error) {
return m.VoucherDataContent, nil
}
func (m MockApi) CheckAliasAddress(ctx context.Context, alias string) (*models.AliasAddress, error) {
return nil, nil
}
func (m MockApi) RequestAlias(ctx context.Context, publicKey string, hint string) (*models.RequestAliasResult, error) {
return nil, nil
}
func (m MockApi) TokenTransfer(ctx context.Context, amount, from, to, tokenAddress string) (*models.TokenTransferResponse, error) {
return nil, nil
}

View File

@ -48,7 +48,12 @@ func (m *MockAccountService) TokenTransfer(ctx context.Context, amount, from, to
return args.Get(0).(*models.TokenTransferResponse), args.Error(1) return args.Get(0).(*models.TokenTransferResponse), args.Error(1)
} }
func (m *MockAccountService) CheckAliasAddress(ctx context.Context, alias string) (*dataserviceapi.AliasAddress, error) { func (m *MockAccountService) CheckAliasAddress(ctx context.Context, alias string) (*models.AliasAddress, error) {
args := m.Called(alias) args := m.Called(alias)
return args.Get(0).(*dataserviceapi.AliasAddress), args.Error(1) return args.Get(0).(*models.AliasAddress), args.Error(1)
}
func (m MockAccountService) RequestAlias(ctx context.Context, publicKey string, hint string) (*models.RequestAliasResult, error) {
args := m.Called(publicKey, hint)
return args.Get(0).(*models.RequestAliasResult), args.Error(1)
} }

View File

@ -57,6 +57,10 @@ func (tas *TestAccountService) TokenTransfer(ctx context.Context, amount, from,
}, nil }, nil
} }
func (m TestAccountService) CheckAliasAddress(ctx context.Context, alias string) (*dataserviceapi.AliasAddress, error) { func (m TestAccountService) CheckAliasAddress(ctx context.Context, alias string) (*models.AliasAddress, error) {
return &dataserviceapi.AliasAddress{}, nil return &models.AliasAddress{}, nil
}
func (m TestAccountService) RequestAlias(ctx context.Context, publicKey string, hint string) (*models.RequestAliasResult, error) {
return &models.RequestAliasResult{}, nil
} }