Compare commits

...

17 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
9 changed files with 217 additions and 149 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

@ -12,65 +12,67 @@ import (
"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"
"git.grassecon.net/grassrootseconomics/sarafu-api/models" "git.defalsify.org/vise.git/logging"
"git.grassecon.net/grassrootseconomics/sarafu-api/event"
"git.grassecon.net/grassrootseconomics/common/phone" "git.grassecon.net/grassrootseconomics/common/phone"
"git.grassecon.net/grassrootseconomics/sarafu-api/event"
"git.grassecon.net/grassrootseconomics/sarafu-api/models"
"git.grassecon.net/grassrootseconomics/visedriver/storage" "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\\-_]+$") aliasRegex = regexp.MustCompile("^\\+?[a-zA-Z0-9\\-_]+$")
searchDomain = ".sarafu.local"
) )
const ( const (
pubKeyLen int = 20 pubKeyLen int = 20
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 {
Track string `json: "track"` Track string `json: "track"`
Hsh string `json:"hash"` Hsh string `json:"hash"`
To string `json:"to"` To string `json:"to"`
From string `json: "from"` From string `json: "from"`
Voucher string `json: "voucher"` Voucher string `json: "voucher"`
Value int `json: "value"` Value int `json: "value"`
When time.Time `json: "when"` When time.Time `json: "when"`
} }
func (t *Tx) ToTransferEvent() event.EventTokenTransfer { func (t *Tx) ToTransferEvent() event.EventTokenTransfer {
return event.EventTokenTransfer{ return event.EventTokenTransfer{
To: t.To, To: t.To,
Value: t.Value, Value: t.Value,
VoucherAddress: t.Voucher, VoucherAddress: t.Voucher,
TxHash: t.Hsh, TxHash: t.Hsh,
From: t.From, From: t.From,
} }
} }
func (t *Tx) ToMintEvent() event.EventTokenMint { func (t *Tx) ToMintEvent() event.EventTokenMint {
return event.EventTokenMint{ return event.EventTokenMint{
To: t.To, To: t.To,
Value: t.Value, Value: t.Value,
VoucherAddress: t.Voucher, VoucherAddress: t.Voucher,
TxHash: t.Hsh, 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"`
Nonce int `json: "nonce"` Nonce int `json: "nonce"`
DefaultVoucher string `json: "defaultVoucher"` DefaultVoucher string `json: "defaultVoucher"`
Balances map[string]int `json: "balances"` Balances map[string]int `json: "balances"`
Alias string Alias string
Txs []string `json: "txs"` Txs []string `json: "txs"`
} }
func (a *Account) ToRegistrationEvent() event.EventCustodialRegistration { func (a *Account) ToRegistrationEvent() event.EventCustodialRegistration {
@ -80,45 +82,44 @@ func (a *Account) ToRegistrationEvent() event.EventCustodialRegistration {
} }
type Voucher struct { type Voucher struct {
Name string `json: "name"` Name string `json: "name"`
Address string `json: "address"` Address string `json: "address"`
Symbol string `json: "symbol"` Symbol string `json: "symbol"`
Decimals int `json: "decimals"` Decimals int `json: "decimals"`
Sink string `json: "sink"` Sink string `json: "sink"`
Commodity string `json: "commodity"` Commodity string `json: "commodity"`
Location string `json: "location"` Location string `json: "location"`
} }
type DevAccountService struct { type DevAccountService struct {
db db.Db db db.Db
accounts map[string]Account accounts map[string]Account
accountsTrack map[string]string accountsTrack map[string]string
accountsAlias map[string]string accountsAlias map[string]string
vouchers map[string]Voucher vouchers map[string]Voucher
vouchersAddress map[string]string vouchersAddress map[string]string
txs map[string]Tx txs map[string]Tx
txsTrack map[string]string txsTrack map[string]string
toAutoCreate bool toAutoCreate bool
autoVouchers []string autoVouchers []string
autoVoucherValue map[string]int autoVoucherValue map[string]int
defaultAccount string defaultAccount string
emitterFunc event.EmitterFunc emitterFunc event.EmitterFunc
pfx []byte pfx []byte
// accountsSession map[string]string
} }
func NewDevAccountService(ctx context.Context, ss storage.StorageService) *DevAccountService { func NewDevAccountService(ctx context.Context, ss storage.StorageService) *DevAccountService {
svc := &DevAccountService{ svc := &DevAccountService{
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),
vouchers: make(map[string]Voucher), vouchers: make(map[string]Voucher),
vouchersAddress: make(map[string]string), vouchersAddress: make(map[string]string),
txs: make(map[string]Tx), txs: make(map[string]Tx),
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("__"), pfx: []byte("__"),
} }
if ss != nil { if ss != nil {
var err error var err error
@ -151,7 +152,7 @@ func (das *DevAccountService) WithPrefix(pfx []byte) *DevAccountService {
} }
func (das *DevAccountService) prefixKeyFor(k string, v string) []byte { func (das *DevAccountService) prefixKeyFor(k string, v string) []byte {
return append(das.pfx, []byte(k + "_" + v)...) 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 {
@ -183,6 +184,15 @@ 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)
@ -194,6 +204,8 @@ 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 { } else {
logg.ErrorCtxf(ctx, "unknown double underscore key", "key", ss[0]) logg.ErrorCtxf(ctx, "unknown double underscore key", "key", ss[0])
} }
@ -225,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)
@ -265,8 +277,8 @@ func (das *DevAccountService) AddVoucher(ctx context.Context, symbol string) err
z := h.Sum(nil) z := h.Sum(nil)
address := fmt.Sprintf("0x%x", z) address := fmt.Sprintf("0x%x", z)
das.vouchers[symbol] = Voucher{ das.vouchers[symbol] = Voucher{
Name: symbol, Name: symbol,
Symbol: symbol, Symbol: symbol,
Address: address, Address: address,
} }
das.vouchersAddress[address] = symbol das.vouchersAddress[address] = symbol
@ -288,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)
@ -312,6 +324,10 @@ 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 {
if das.db == nil { if das.db == nil {
return nil return nil
@ -326,6 +342,23 @@ func (das *DevAccountService) saveAccount(ctx context.Context, acc Account) erro
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()
@ -341,7 +374,7 @@ func (das *DevAccountService) CreateAccount(ctx context.Context) (*models.Accoun
} }
pubKey := fmt.Sprintf("0x%x", b) pubKey := fmt.Sprintf("0x%x", b)
acc := Account{ acc := Account{
Track: uid.String(), Track: uid.String(),
Address: pubKey, Address: pubKey,
} }
@ -363,7 +396,7 @@ func (das *DevAccountService) CreateAccount(ctx context.Context) (*models.Accoun
if das.emitterFunc != nil { if das.emitterFunc != nil {
msg := event.Msg{ msg := event.Msg{
Typ: event.EventRegistrationTag, Typ: event.EventRegistrationTag,
Item: acc, Item: acc,
} }
err = das.emitterFunc(ctx, msg) err = das.emitterFunc(ctx, msg)
@ -374,7 +407,7 @@ func (das *DevAccountService) CreateAccount(ctx context.Context) (*models.Accoun
logg.TraceCtxf(ctx, "account created", "account", acc) logg.TraceCtxf(ctx, "account created", "account", acc)
return &models.AccountResult{ return &models.AccountResult{
PublicKey: pubKey, PublicKey: pubKey,
TrackingId: uid.String(), TrackingId: uid.String(),
}, nil }, nil
} }
@ -392,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
} }
@ -417,24 +448,24 @@ 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
} }
voucher, ok := das.vouchers[mytx.Voucher] voucher, ok := das.vouchers[mytx.Voucher]
if !ok { if !ok {
return nil, fmt.Errorf("voucher %s in tx list but not found in voucher list", mytx.Voucher) return nil, fmt.Errorf("voucher %s in tx list but not found in voucher list", mytx.Voucher)
} }
lasttx = append(lasttx, dataserviceapi.Last10TxResponse{ lasttx = append(lasttx, dataserviceapi.Last10TxResponse{
Sender: mytx.From, Sender: mytx.From,
Recipient: mytx.To, Recipient: mytx.To,
TransferValue: strconv.Itoa(mytx.Value), TransferValue: strconv.Itoa(mytx.Value),
ContractAddress: voucher.Address, ContractAddress: voucher.Address,
TxHash: mytx.Hsh, TxHash: mytx.Hsh,
DateBlock: mytx.When, DateBlock: mytx.When,
TokenSymbol: voucher.Symbol, TokenSymbol: voucher.Symbol,
TokenDecimals: strconv.Itoa(voucher.Decimals), TokenDecimals: strconv.Itoa(voucher.Decimals),
}) })
} }
return lasttx, nil return lasttx, nil
@ -450,13 +481,12 @@ func (das *DevAccountService) VoucherData(ctx context.Context, address string) (
return nil, fmt.Errorf("voucher address %v found but does not resolve", address) return nil, fmt.Errorf("voucher address %v found but does not resolve", address)
} }
return &models.VoucherDataResult{ return &models.VoucherDataResult{
TokenName: voucher.Name, TokenName: voucher.Name,
TokenSymbol: voucher.Symbol, TokenSymbol: voucher.Symbol,
TokenDecimals: voucher.Decimals, TokenDecimals: voucher.Decimals,
SinkAddress: voucher.Sink, SinkAddress: voucher.Sink,
TokenCommodity: voucher.Commodity, TokenCommodity: voucher.Commodity,
TokenLocation: voucher.Location, TokenLocation: voucher.Location,
}, nil }, nil
} }
@ -481,12 +511,12 @@ func (das *DevAccountService) TokenTransfer(ctx context.Context, amount, from, t
} }
accFrom, ok := das.accounts[from] accFrom, ok := das.accounts[from]
if !ok { if !ok {
return nil, fmt.Errorf("sender account %v not found", from) return nil, fmt.Errorf("sender account %v not found", from)
} }
accTo, ok := das.accounts[to] accTo, ok := das.accounts[to]
if !ok { if !ok {
if !das.toAutoCreate { if !das.toAutoCreate {
return nil, fmt.Errorf("recipient account %v not found, and not creating", from) return nil, fmt.Errorf("recipient account %v not found, and not creating", from)
} }
} }
@ -512,13 +542,13 @@ func (das *DevAccountService) TokenTransfer(ctx context.Context, amount, from, t
} }
hsh := fmt.Sprintf("0x%x", b) hsh := fmt.Sprintf("0x%x", b)
mytx := Tx{ mytx := Tx{
Hsh: hsh, Hsh: hsh,
To: accTo.Address, To: accTo.Address,
From: accFrom.Address, From: accFrom.Address,
Voucher: voucher.Symbol, Voucher: voucher.Symbol,
Value: value, Value: value,
Track: uid.String(), Track: uid.String(),
When: time.Now(), When: time.Now(),
} }
err = das.saveTokenTransfer(ctx, mytx) err = das.saveTokenTransfer(ctx, mytx)
if err != nil { if err != nil {
@ -527,7 +557,7 @@ func (das *DevAccountService) TokenTransfer(ctx context.Context, amount, from, t
das.txs[hsh] = mytx das.txs[hsh] = mytx
if das.emitterFunc != nil { if das.emitterFunc != nil {
msg := event.Msg{ msg := event.Msg{
Typ: event.EventTokenTransferTag, Typ: event.EventTokenTransferTag,
Item: mytx, Item: mytx,
} }
err = das.emitterFunc(ctx, msg) err = das.emitterFunc(ctx, msg)
@ -568,12 +598,22 @@ func (das *DevAccountService) applyPhoneAlias(ctx context.Context, publicKey str
func (das *DevAccountService) RequestAlias(ctx context.Context, publicKey string, hint string) (*models.RequestAliasResult, error) { func (das *DevAccountService) RequestAlias(ctx context.Context, publicKey string, hint string) (*models.RequestAliasResult, error) {
var alias string var alias string
uid, err := uuid.NewV4()
if !aliasRegex.MatchString(hint) { if !aliasRegex.MatchString(hint) {
return nil, fmt.Errorf("alias hint does not match: %s", publicKey) return nil, fmt.Errorf("alias hint does not match: %s", publicKey)
} }
acc, ok := das.accounts[publicKey] acc, ok := das.accounts[publicKey]
if !ok { if !ok {
return nil, fmt.Errorf("address %s not found", publicKey) //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 alias = hint
isPhone, err := das.applyPhoneAlias(ctx, publicKey, alias) isPhone, err := das.applyPhoneAlias(ctx, publicKey, alias)
@ -592,7 +632,12 @@ func (das *DevAccountService) RequestAlias(ctx context.Context, publicKey string
alias += "x" alias += "x"
} }
acc.Alias = alias acc.Alias = alias
alias = alias + searchDomain
das.accountsAlias[alias] = publicKey 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) logg.DebugCtxf(ctx, "set alias", "addr", publicKey, "alias", alias)
return &models.RequestAliasResult{ return &models.RequestAliasResult{

View File

@ -9,6 +9,7 @@ import (
func TestApiRequestAlias(t *testing.T) { func TestApiRequestAlias(t *testing.T) {
ctx := context.Background() ctx := context.Background()
ctx = context.WithValue(ctx, "SessionId", "+25471234565")
storageService := mocks.NewMemStorageService(ctx) storageService := mocks.NewMemStorageService(ctx)
svc := NewDevAccountService(ctx, storageService) svc := NewDevAccountService(ctx, storageService)
ra, err := svc.CreateAccount(ctx) ra, err := svc.CreateAccount(ctx)
@ -16,10 +17,10 @@ func TestApiRequestAlias(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
addr := ra.PublicKey addr := ra.PublicKey
_, err = svc.RequestAlias(ctx, addr, "+254f00") _, err = svc.RequestAlias(ctx, addr, "+254f00")
if err == nil { if err == nil {
t.Fatalf("expected error") t.Fatalf("expected error")
} }
alias := "+254712345678" alias := "+254712345678"
rb, err := svc.RequestAlias(ctx, addr, alias) rb, err := svc.RequestAlias(ctx, addr, alias)
@ -39,6 +40,7 @@ func TestApiRequestAlias(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
alias = "foo.sarafu.local"
if rb.Alias != alias { if rb.Alias != alias {
t.Fatalf("expected '%s', got '%s'", alias, rb.Alias) t.Fatalf("expected '%s', got '%s'", alias, rb.Alias)
} }
@ -56,12 +58,12 @@ func TestApiRequestAlias(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
addr = ra.PublicKey addr = ra.PublicKey
alias = "foox"
rb, err = svc.RequestAlias(ctx, addr, alias) rb, err = svc.RequestAlias(ctx, addr, alias)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
alias = "foox" alias = "foox.sarafu.local"
if rb.Alias != alias { if rb.Alias != alias {
t.Fatalf("expected '%s', got '%s'", alias, rb.Alias) t.Fatalf("expected '%s', got '%s'", alias, rb.Alias)
} }

View File

@ -8,12 +8,12 @@ import (
const ( const (
// TODO: integrate with sarafu-vise-events // TODO: integrate with sarafu-vise-events
EventTokenTransferTag = "TOKEN_TRANSFER" EventTokenTransferTag = "TOKEN_TRANSFER"
EventTokenMintTag = "TOKEN_MINT" EventTokenMintTag = "TOKEN_MINT"
EventRegistrationTag = "CUSTODIAL_REGISTRATION" EventRegistrationTag = "CUSTODIAL_REGISTRATION"
) )
type Msg struct { type Msg struct {
Typ string Typ string
Item any Item any
} }
@ -26,17 +26,17 @@ type EventCustodialRegistration struct {
// fields used for handling token transfer event. // fields used for handling token transfer event.
type EventTokenTransfer struct { type EventTokenTransfer struct {
To string To string
Value int Value int
VoucherAddress string VoucherAddress string
TxHash string TxHash string
From string From string
} }
type EventTokenMint struct { type EventTokenMint struct {
To string To string
Value int Value int
TxHash string TxHash string
VoucherAddress string VoucherAddress string
} }

6
go.mod
View File

@ -3,9 +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.20250114225117-3b5fc85b650b git.defalsify.org/vise.git v0.2.3-0.20250120121301-10739fb4a8c9
git.grassecon.net/grassrootseconomics/common v0.0.0-20250113174703-6afccefd1f05 git.grassecon.net/grassrootseconomics/common v0.0.0-20250121134736-ba8cbbccea7d
git.grassecon.net/grassrootseconomics/visedriver v0.8.0-beta.10.0.20250115003256-c0534ede1b63 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

12
go.sum
View File

@ -1,9 +1,9 @@
git.defalsify.org/vise.git v0.2.3-0.20250114225117-3b5fc85b650b h1:rwWXMtNSn7aqhb4p1oVZkCA1vC7pVdohwW61QQM8fUs= git.defalsify.org/vise.git v0.2.3-0.20250120121301-10739fb4a8c9 h1:sPcqXQcywxA8W3W+9qQncLPmsrgqTIlec7vmD4/7vyA=
git.defalsify.org/vise.git v0.2.3-0.20250114225117-3b5fc85b650b/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/common v0.0.0-20250113174703-6afccefd1f05 h1:BenzGx6aDHKDwE23/mWIFD2InYIXyzHroZWV3MF5WUk= git.grassecon.net/grassrootseconomics/common v0.0.0-20250121134736-ba8cbbccea7d h1:5mzLas+jxTUtusOKx4XvU+n2QvrV/mH17MnJRy46siQ=
git.grassecon.net/grassrootseconomics/common v0.0.0-20250113174703-6afccefd1f05/go.mod h1:wgQJZGIS6QuNLHqDhcsvehsbn5PvgV7aziRebMnJi60= 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.20250115003256-c0534ede1b63 h1:bX7klKZpX+ZZu1LKbtOXDAhV/KK0YwExehiIi0jusAM= 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.20250115003256-c0534ede1b63/go.mod h1:Syw9TZyigPAM7t9FvicOm36iUnidt45f0SxzT2JniQ8= 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/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=

View File

@ -3,21 +3,30 @@ package http
import ( import (
"bytes" "bytes"
"context" "context"
"fmt"
"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:
@ -204,24 +213,39 @@ func (as *HTTPAccountService) TokenTransfer(ctx context.Context, amount, from, t
// Parameters: // Parameters:
// - alias: The alias of the user. // - alias: The alias of the user.
func (as *HTTPAccountService) CheckAliasAddress(ctx context.Context, alias string) (*models.AliasAddress, error) { func (as *HTTPAccountService) CheckAliasAddress(ctx context.Context, alias string) (*models.AliasAddress, error) {
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 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) { func (as *HTTPAccountService) RequestAlias(ctx context.Context, publicKey string, hint string) (*models.RequestAliasResult, error) {
return nil, fmt.Errorf("not yet implemented") 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

View File

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

View File

@ -53,7 +53,7 @@ func (m *MockAccountService) CheckAliasAddress(ctx context.Context, alias string
return args.Get(0).(*models.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) { func (m MockAccountService) RequestAlias(ctx context.Context, publicKey string, hint string) (*models.RequestAliasResult, error) {
args := m.Called(publicKey, hint) args := m.Called(publicKey, hint)
return args.Get(0).(*models.RequestAliasResult), args.Error(1) return args.Get(0).(*models.RequestAliasResult), args.Error(1)
} }