Compare commits

..

7 Commits

10 changed files with 375 additions and 77 deletions

View File

@ -15,15 +15,16 @@ const (
voucherHoldingsPathPrefix = "/api/v1/holdings"
voucherTransfersPathPrefix = "/api/v1/transfers/last10"
voucherDataPathPrefix = "/api/v1/token"
AliasPrefix = "api/v1/alias"
AliasEnsPrefix = "/api/v1/bypass"
aliasPrefix = "api/v1/alias"
poolDepositPrefix = "/api/v2/pool/deposit"
poolSwapQoutePrefix = "/api/v2/pool/quote"
poolSwapPrefix = "/api/v2/pool/swap"
)
var (
custodialURLBase string
dataURLBase string
BearerToken string
aliasEnsURLBase string
)
var (
@ -36,7 +37,9 @@ var (
VoucherTransfersURL string
VoucherDataURL string
CheckAliasURL string
AliasEnsURL string
PoolDepositURL string
PoolSwapQuoteURL string
PoolSwapURL string
)
func setBase() error {
@ -44,7 +47,6 @@ func setBase() error {
custodialURLBase = env.GetEnv("CUSTODIAL_URL_BASE", "http://localhost:5003")
dataURLBase = env.GetEnv("DATA_URL_BASE", "http://localhost:5006")
aliasEnsURLBase = env.GetEnv("ALIAS_ENS_BASE", "http://localhost:5015")
BearerToken = env.GetEnv("BEARER_TOKEN", "")
_, err = url.Parse(custodialURLBase)
@ -72,7 +74,10 @@ func LoadConfig() error {
VoucherHoldingsURL, _ = url.JoinPath(dataURLBase, voucherHoldingsPathPrefix)
VoucherTransfersURL, _ = url.JoinPath(dataURLBase, voucherTransfersPathPrefix)
VoucherDataURL, _ = url.JoinPath(dataURLBase, voucherDataPathPrefix)
CheckAliasURL, _ = url.JoinPath(dataURLBase, AliasPrefix)
AliasEnsURL, _ = url.JoinPath(aliasEnsURLBase, AliasEnsPrefix)
CheckAliasURL, _ = url.JoinPath(dataURLBase, aliasPrefix)
PoolDepositURL, _ = url.JoinPath(custodialURLBase, poolDepositPrefix)
PoolSwapQuoteURL, _ = url.JoinPath(custodialURLBase, poolSwapQoutePrefix)
PoolSwapURL, _ = url.JoinPath(custodialURLBase, poolSwapPrefix)
return nil
}

View File

@ -6,7 +6,9 @@ import (
"crypto/sha1"
"encoding/json"
"fmt"
"log"
"math/rand"
"os"
"regexp"
"strconv"
"strings"
@ -91,6 +93,11 @@ type Voucher struct {
Location string `json: "location"`
}
type Pool struct {
vouchers []Voucher
poolLimit map[string]string
}
type DevAccountService struct {
db db.Db
accounts map[string]Account
@ -106,6 +113,7 @@ type DevAccountService struct {
defaultAccount string
emitterFunc event.EmitterFunc
pfx []byte
pool Pool
}
func NewDevAccountService(ctx context.Context, ss storage.StorageService) *DevAccountService {
@ -118,6 +126,7 @@ func NewDevAccountService(ctx context.Context, ss storage.StorageService) *DevAc
txs: make(map[string]Tx),
txsTrack: make(map[string]string),
autoVoucherValue: make(map[string]int),
pool: Pool{},
defaultAccount: zeroAddress,
pfx: []byte("__"),
}
@ -171,6 +180,15 @@ func (das *DevAccountService) loadAccount(ctx context.Context, pubKey string, v
return nil
}
func (p *Pool) hasVoucher(voucherAddress string) bool {
for _, value := range p.vouchers {
if value.Address == voucherAddress {
return true
}
}
return false
}
func (das *DevAccountService) loadTx(ctx context.Context, hsh string, v []byte) error {
var mytx Tx
@ -415,6 +433,74 @@ func (das *DevAccountService) CreateAccount(ctx context.Context) (*models.Accoun
}, nil
}
func (das *DevAccountService) PoolDeposit(ctx context.Context, amount, from, poolAddress, tokenAddress string) (*models.PoolDepositResult, error) {
sym, ok := das.vouchersAddress[tokenAddress]
if !ok {
return nil, fmt.Errorf("voucher address %v not found", tokenAddress)
}
uid, err := uuid.NewV4()
if err != nil {
return nil, err
}
voucher, ok := das.vouchers[sym]
if !ok {
return nil, fmt.Errorf("voucher address %v found but does not resolve", tokenAddress)
}
das.pool = Pool{
vouchers: append(das.pool.vouchers, voucher),
poolLimit: map[string]string{tokenAddress: amount},
}
return &models.PoolDepositResult{
TrackingId: uid.String(),
}, nil
}
func (das *DevAccountService) GetPoolSwapQuote(ctx context.Context, amount, from, fromTokenAddress, poolAddress, toTokenAddress string) (*models.PoolSwapQuoteResult, error) {
_, ok := das.accounts[from]
if !ok {
return nil, fmt.Errorf("account not found (publickey): %v", from)
}
//resolve the token address you are trying to swap from(fromTokenAddress)
_, ok = das.vouchersAddress[fromTokenAddress]
if !ok {
return nil, fmt.Errorf("voucher address %v not found", fromTokenAddress)
}
p := das.pool
//check if pool has voucher to swap to
if !p.hasVoucher(toTokenAddress) {
return nil, fmt.Errorf("Voucher with address: %v not found in the pool", toTokenAddress)
}
//Return a a quote that is equal to the amount enter
return &models.PoolSwapQuoteResult{IncludesFeesDeduction: false, OutValue: amount}, nil
}
func (das *DevAccountService) PoolSwap(ctx context.Context, amount, from, fromTokenAddress, poolAddress, toTokenAddress string) (*models.PoolSwapResult, error) {
uid, err := uuid.NewV4()
if err != nil {
return nil, err
}
_, ok := das.accounts[from]
if !ok {
return nil, fmt.Errorf("account not found (publickey): %v", from)
}
_, ok = das.vouchersAddress[fromTokenAddress]
if !ok {
return nil, fmt.Errorf("voucher address %v not found", fromTokenAddress)
}
p := das.pool
//check if pool has voucher to swap to
if !p.hasVoucher(toTokenAddress) {
return nil, fmt.Errorf("Voucher with address: %v not found in the pool", toTokenAddress)
}
return &models.PoolSwapResult{TrackingId: uid.String()}, nil
}
func (das *DevAccountService) TrackAccountStatus(ctx context.Context, publicKey string) (*models.TrackStatusResult, error) {
var ok bool
_, ok = das.accounts[publicKey]
@ -653,3 +739,72 @@ func (das *DevAccountService) RequestAlias(ctx context.Context, publicKey string
Alias: alias,
}, nil
}
func (das *DevAccountService) FetchTopPools(ctx context.Context) ([]models.Pool, error) {
var (
r struct {
OK bool `json:"ok"`
Description string `json:"description"`
Result struct {
Pools []models.Pool `json:"topPools"`
} `json:"result"`
}
)
data, err := os.ReadFile("./data/top_pools.json")
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(data, &r)
if err != nil {
log.Fatal(err)
}
return r.Result.Pools, nil
}
func (das *DevAccountService) GetPoolSwappableFromVouchers(ctx context.Context) ([]models.SwappableVoucher, error) {
var (
r struct {
OK bool `json:"ok"`
Description string `json:"description"`
Result struct {
SwappableVouchers []models.SwappableVoucher `json:"filtered"`
} `json:"result"`
}
)
data, err := os.ReadFile("./data/swap_from.json")
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(data, &r)
if err != nil {
log.Fatal(err)
}
return r.Result.SwappableVouchers, nil
}
func (das *DevAccountService) GetPoolSwappableVouchers(ctx context.Context) ([]models.SwappableVoucher, error) {
var (
r struct {
OK bool `json:"ok"`
Description string `json:"description"`
Result struct {
SwappableVouchers []models.SwappableVoucher `json:"filtered"`
} `json:"result"`
}
)
data, err := os.ReadFile("./data/swap_to.json")
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(data, &r)
if err != nil {
log.Fatal(err)
}
return r.Result.SwappableVouchers, nil
}

32
dev/data/swap_from.json Normal file
View File

@ -0,0 +1,32 @@
{
"ok": true,
"description": "Swap from list",
"result": {
"filtered": [
{
"contractAddress": "0xc7B78Ac9ACB9E025C8234621FC515bC58179dEAe",
"tokenSymbol": "AMANI",
"tokenDecimals": "6",
"balance": ""
},
{
"contractAddress": "0xF0C3C7581b8b96B59a97daEc8Bd48247cE078674",
"tokenSymbol": "AMUA",
"tokenDecimals": "6",
"balance": ""
},
{
"contractAddress": "0x371455a30fc62736145Bd8429Fcc6481186f235F",
"tokenSymbol": "BAHARI",
"tokenDecimals": "6",
"balance": ""
},
{
"contractAddress": "0x7cA6113b59c24a880F382C7E12d609a6Eb05246b",
"tokenSymbol": "BANGLA",
"tokenDecimals": "6",
"balance": ""
}
]
}
}

14
dev/data/swap_to.json Normal file
View File

@ -0,0 +1,14 @@
{
"ok": true,
"description": "Swap to list",
"result": {
"filtered": [
{
"contractAddress": "0x765DE816845861e75A25fCA122bb6898B8B1282a",
"tokenSymbol": "cUSD",
"tokenDecimals": "18",
"balance": ""
}
]
}
}

43
dev/data/top_pools.json Normal file
View File

@ -0,0 +1,43 @@
{
"ok": true,
"description": "Top 5 pools sorted by swaps",
"result": {
"topPools": [
{
"poolName": "Kenya ROLA Pool",
"poolSymbol": "ROLA",
"poolContractAddress": "0x48a953cA5cf5298bc6f6Af3C608351f537AAcb9e",
"limiterAddress": "",
"voucherRegistry": ""
},
{
"poolName": "Nairobi ROLA Pool",
"poolSymbol": "NAIROBI",
"poolContractAddress": "0xB0660Ac1Ee3d32ea35bc728D7CA1705Fa5A37528",
"limiterAddress": "",
"voucherRegistry": ""
},
{
"poolName": "Friends of Kiriba Ecosystem ",
"poolSymbol": "FRIENDS",
"poolContractAddress": "0xC4848263821FA02baB2181910A2eFb9CECb2c21C",
"limiterAddress": "",
"voucherRegistry": ""
},
{
"poolName": "Resilient Community Waqfs",
"poolSymbol": "REZILIENS",
"poolContractAddress": "0x1e40951d7a28147D8B4A554C60c42766C92e2Fc6",
"limiterAddress": "",
"voucherRegistry": ""
},
{
"poolName": "GrE Tech",
"poolSymbol": "GRET",
"poolContractAddress": "0xb7B9d0A264eD1a8E2418571B7AC5933C79C9c2B8",
"limiterAddress": "",
"voucherRegistry": ""
}
]
}
}

View File

@ -7,13 +7,3 @@ type RequestAliasResult struct {
type AliasAddress struct {
Address string
}
type AliasEnsResult struct {
Address string `json:"address"`
AutoChoose bool `json:"autoChoose"`
Name string `json:"name"`
}
type AliasEnsAddressResult struct {
Address string `json:"address"`
}

10
models/pool.go Normal file
View File

@ -0,0 +1,10 @@
package models
type Pool struct {
PoolName string `json:"poolName"`
PoolSymbol string `json:"poolSymbol"`
PoolContractAddress string `json:"poolContractAddress"`
LimiterAddress string `json:"limiterAddress"`
VoucherRegistry string `json:"voucherRegistry"`
}

View File

@ -0,0 +1,14 @@
package models
type PoolDepositResult struct {
TrackingId string `json:"trackingId"`
}
type PoolSwapQuoteResult struct {
IncludesFeesDeduction bool `json:"includesFeesDeduction"`
OutValue string `json:"outValue"`
}
type PoolSwapResult struct {
TrackingId string `json:"trackingId"`
}

View File

@ -8,3 +8,10 @@ type VoucherDataResult struct {
TokenCommodity string `json:"tokenCommodity"`
TokenLocation string `json:"tokenLocation"`
}
type SwappableVoucher struct {
ContractAddress string `json:"contractAddress"`
TokenSymbol string `json:"tokenSymbol"`
TokenDecimals string `json:"tokenDecimals"`
Balance string `json:"balance"`
}

View File

@ -11,9 +11,7 @@ import (
"net/http"
"net/url"
"regexp"
"strings"
"git.defalsify.org/vise.git/logging"
"git.grassecon.net/grassrootseconomics/sarafu-api/config"
"git.grassecon.net/grassrootseconomics/sarafu-api/dev"
"git.grassecon.net/grassrootseconomics/sarafu-api/models"
@ -24,7 +22,6 @@ import (
var (
aliasRegex = regexp.MustCompile("^\\+?[a-zA-Z0-9\\-_]+$")
logg = logging.NewVanilla().WithDomain("sarafu-api.devapi")
)
type HTTPAccountService struct {
@ -62,10 +59,6 @@ func (as *HTTPAccountService) TrackAccountStatus(ctx context.Context, publicKey
return &r, nil
}
func (as *HTTPAccountService) ToFqdn(alias string) string {
return alias + ".sarafu.eth"
}
// CheckBalance retrieves the balance for a given public key from the custodial balance API endpoint.
// Parameters:
// - publicKey: The public key associated with the account whose balance needs to be checked.
@ -223,10 +216,8 @@ func (as *HTTPAccountService) CheckAliasAddress(ctx context.Context, alias strin
if as.SS == nil {
return nil, fmt.Errorf("The storage service cannot be nil")
}
logg.InfoCtxf(ctx, "resolving alias before formatting", "alias", alias)
svc := dev.NewDevAccountService(ctx, as.SS)
if as.UseApi {
logg.InfoCtxf(ctx, "resolving alias to address", "alias", alias)
return resolveAliasAddress(ctx, alias)
} else {
return svc.CheckAliasAddress(ctx, alias)
@ -234,85 +225,122 @@ func (as *HTTPAccountService) CheckAliasAddress(ctx context.Context, alias strin
}
func resolveAliasAddress(ctx context.Context, alias string) (*models.AliasAddress, error) {
var (
aliasEnsResult models.AliasEnsAddressResult
)
var r models.AliasAddress
ep, err := url.JoinPath(config.AliasEnsURL, "/resolve")
ep, err := url.JoinPath(config.CheckAliasURL, alias)
if err != nil {
return nil, err
}
u, err := url.Parse(ep)
req, err := http.NewRequest("GET", ep, nil)
if err != nil {
return nil, err
}
query := u.Query()
query.Set("name", alias)
u.RawQuery = query.Encode()
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, err
}
_, err = doRequest(ctx, req, &aliasEnsResult)
if err != nil {
return nil, err
}
return &models.AliasAddress{Address: aliasEnsResult.Address}, err
_, err = doRequest(ctx, req, &r)
return &r, err
}
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")
}
if as.UseApi {
if !strings.Contains(hint, ".") {
hint = as.ToFqdn(hint)
}
enr, err := requestEnsAlias(ctx, publicKey, hint)
if err != nil {
return nil, err
}
return &models.RequestAliasResult{Alias: enr.Name}, nil
} else {
svc := dev.NewDevAccountService(ctx, as.SS)
return svc.RequestAlias(ctx, publicKey, hint)
}
func (as *HTTPAccountService) FetchTopPools(ctx context.Context) ([]models.Pool, error) {
svc := dev.NewDevAccountService(ctx, as.SS)
return svc.FetchTopPools(ctx)
}
func requestEnsAlias(ctx context.Context, publicKey string, hint string) (*models.AliasEnsResult, error) {
var r models.AliasEnsResult
func (as *HTTPAccountService) PoolDeposit(ctx context.Context, amount, from, poolAddress, tokenAddress string) (*models.PoolDepositResult, error) {
var r models.PoolDepositResult
ep, err := url.JoinPath(config.AliasEnsURL, "/register")
if err != nil {
return nil, err
}
logg.InfoCtxf(ctx, "requesting alias", "endpoint", ep, "hint", hint)
//Payload with the address and hint to derive an ENS name
//pool deposit payload
payload := map[string]string{
"address": publicKey,
"hint": hint,
"amount": amount,
"from": from,
"poolAddress": poolAddress,
"tokenAddress": tokenAddress,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", ep, bytes.NewBuffer(payloadBytes))
req, err := http.NewRequest("POST", config.TokenTransferURL, bytes.NewBuffer(payloadBytes))
if err != nil {
return nil, err
}
// Log the request body
logg.InfoCtxf(ctx, "request body", "payload", string(payloadBytes))
_, err = doRequest(ctx, req, &r)
if err != nil {
return nil, err
}
logg.InfoCtxf(ctx, "alias successfully assigned", "alias", r.Name)
return &r, nil
}
func (as *HTTPAccountService) GetPoolSwapQuote(ctx context.Context, amount, from, fromTokenAddress, poolAddress, toTokenAddress string) (*models.PoolSwapQuoteResult, error) {
var r models.PoolSwapQuoteResult
//pool swap quote payload
payload := map[string]string{
"amount": amount,
"from": from,
"fromTokenAddress": fromTokenAddress,
"poolAddress": poolAddress,
"toTokenAddress": toTokenAddress,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", config.PoolSwapQuoteURL, bytes.NewBuffer(payloadBytes))
if err != nil {
return nil, err
}
_, err = doRequest(ctx, req, &r)
if err != nil {
return nil, err
}
return &r, nil
}
func (as *HTTPAccountService) GetPoolSwappableFromVouchers(ctx context.Context) ([]models.SwappableVoucher, error) {
return as.GetPoolSwappableFromVouchers(ctx)
}
func (as *HTTPAccountService) GetPoolSwappableVouchers(ctx context.Context) ([]models.SwappableVoucher, error) {
return as.GetPoolSwappableVouchers(ctx)
}
func (as *HTTPAccountService) PoolSwap(ctx context.Context, amount, from, fromTokenAddress, poolAddress, toTokenAddress string) (*models.PoolSwapResult, error) {
var r models.PoolSwapResult
//swap payload
payload := map[string]string{
"amount": amount,
"from": from,
"fromTokenAddress": fromTokenAddress,
"poolAddress": poolAddress,
"toTokenAddress": toTokenAddress,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", config.PoolSwapQuoteURL, bytes.NewBuffer(payloadBytes))
if err != nil {
return nil, err
}
_, err = doRequest(ctx, req, &r)
if err != nil {
return nil, err
}
return &r, nil
}
// 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
func doRequest(ctx context.Context, req *http.Request, rcpt any) (*api.OKResponse, error) {
var okResponse api.OKResponse