Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
* develop:
  fix: bump toolkit typeset version (#1240)
  fix: add auth query profile (#1239)
  fix: wrong compare address onchain asset (#1238)
  fix: return id wallet onchain (#1237)
  fix: enrich token price moniker (#1236)
  • Loading branch information
trkhoi committed Nov 20, 2023
2 parents 21f2497 + 64e0f05 commit c95896b
Show file tree
Hide file tree
Showing 17 changed files with 104 additions and 23 deletions.
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,8 @@ require (

require (
cloud.google.com/go/storage v1.28.1
github.com/consolelabs/mochi-toolkit v0.0.0-20231018042507-12bf9ab24131
github.com/consolelabs/mochi-typeset v0.0.0-20230913195508-ff7f4f4c725c
github.com/consolelabs/mochi-toolkit v0.0.0-20231120101425-c7a48fbcdee8
github.com/consolelabs/mochi-typeset v0.0.0-20231120101232-7743776c4c84
github.com/gammazero/workerpool v1.1.3
github.com/getsentry/sentry-go v0.18.0
github.com/shopspring/decimal v1.2.0
Expand Down
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6 h1:fLjPD/aNc3UIOA6tDi6QXUemppXK3P9BI7mr2hd6gx8=
github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=
github.com/VictoriaMetrics/fastcache v1.6.0 h1:C/3Oi3EiBCqufydp1neRZkqcwmEiuRT9c3fqvvgKm5o=
Expand Down Expand Up @@ -163,8 +165,12 @@ github.com/consensys/bavard v0.1.8-0.20210406032232-f3452dc9b572/go.mod h1:Bpd0/
github.com/consensys/gnark-crypto v0.4.1-0.20210426202927-39ac3d4b3f1f/go.mod h1:815PAHg3wvysy0SyIqanF8gZ0Y1wjk/hrDHD/iT88+Q=
github.com/consolelabs/mochi-toolkit v0.0.0-20231018042507-12bf9ab24131 h1:WxC+3iRaVDqmu1y/CHzSAdLrNNaukn1553V72un6cQs=
github.com/consolelabs/mochi-toolkit v0.0.0-20231018042507-12bf9ab24131/go.mod h1:RWI49mYrrMk5tdL7y3fRqG87Vd1PLIwfQm//DOS8eGM=
github.com/consolelabs/mochi-toolkit v0.0.0-20231120101425-c7a48fbcdee8 h1:lSkRVxmLrranDE54JspZ0MFIPyRkEVbrT23+shI0CIk=
github.com/consolelabs/mochi-toolkit v0.0.0-20231120101425-c7a48fbcdee8/go.mod h1:RWI49mYrrMk5tdL7y3fRqG87Vd1PLIwfQm//DOS8eGM=
github.com/consolelabs/mochi-typeset v0.0.0-20230913195508-ff7f4f4c725c h1:y4flqwiIQclJzgjgOEA7/rnNKzRWG8cfyww3ROe4AZ0=
github.com/consolelabs/mochi-typeset v0.0.0-20230913195508-ff7f4f4c725c/go.mod h1:HSKMB2HqQKHgeVpG/QZAs2nHulZbLA8PreLeujm2Ups=
github.com/consolelabs/mochi-typeset v0.0.0-20231120101232-7743776c4c84 h1:kynajC+geXm8et3ww/JiRLfE1WpRUVzCPKDnS4ErKWo=
github.com/consolelabs/mochi-typeset v0.0.0-20231120101232-7743776c4c84/go.mod h1:HSKMB2HqQKHgeVpG/QZAs2nHulZbLA8PreLeujm2Ups=
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@

-- +migrate Up
alter table offchain_tip_bot_tokens add column chain_id text;
-- +migrate Down
alter table offchain_tip_bot_tokens drop column chain_id;
4 changes: 4 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,8 @@ type Config struct {
KrystalBaseUrl string
KrystalApiKey string

BirdEyeApiKey string

MochiAppPrivateKey string

FriendScanAPI string
Expand Down Expand Up @@ -320,6 +322,7 @@ func generateConfigFromViper(v *viper.Viper) Config {
BlockChainAPISecretKey: v.GetString("BLOCKCHAIN_API_SECRET_KEY"),

CoinGeckoAPIKey: v.GetString("COINGECKO_API_KEY"),
BirdEyeApiKey: v.GetString("BIRDEYE_API_KEY"),

CentralizedWalletPrivateKey: v.GetString("CENTRALIZED_WALLET_PRIVATE_KEY"),
CentralizedWalletAddress: v.GetString("CENTRALIZED_WALLET_ADDRESS"),
Expand Down Expand Up @@ -442,6 +445,7 @@ func LoadConfig(loaders []Loader) Config {
v.SetDefault("CENTRALIZED_WALLET_ADDRESS", "0x4ec16127e879464bef6ab310084facec1e4fe465")
v.SetDefault("BLUEMOVE_SUI_MAINNET_URL", "https://3rd.console.so/sui/api")
v.SetDefault("SOLSCAN_TOKEN", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjcmVhdGVkQXQiOjE2NzU3NzcyODYxMjgsImVtYWlsIjoibmdvdHJvbmdraG9pMTEyQGdtYWlsLmNvbSIsImFjdGlvbiI6InRva2VuLWFwaSIsImlhdCI6MTY3NTc3NzI4Nn0.DCT8Fh8j9uWVpnQSMnq0uuzqeBngNLxc4r8a1Aa2C4Q")
v.SetDefault("BIRDEYE_API_KEY", "bc1bdb09bc434a3bb88885fa0ea1a6d1")
v.SetDefault("SUI_JSON_RPC", "https://fullnode.mainnet.sui.io")
v.SetDefault("SKY_MAVIS_API_BASE_URL", "https://api-gateway.skymavis.com")
v.SetDefault("FRIEND_SCAN_API", "https://api.friendscan.tech")
Expand Down
3 changes: 2 additions & 1 deletion pkg/entities/configs.go
Original file line number Diff line number Diff line change
Expand Up @@ -587,10 +587,11 @@ func (e *Entity) GetDefaultMoniker() ([]response.MonikerConfigData, error) {
}

res := []response.MonikerConfigData{}
for _, config := range configs {
for i, config := range configs {
var configData response.MonikerConfigData
configData.Moniker = config
configData.Value = config.Amount * prices[config.Token.CoinGeckoID]
configs[i].Token.TokenPrice = prices[config.Token.CoinGeckoID]
res = append(res, configData)
}
return res, nil
Expand Down
2 changes: 1 addition & 1 deletion pkg/entities/swap_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ func (e *Entity) EnrichTokenMochiPay(route *response.SwapRouteResponse) error {
toTokenAddress = quoteResp.OutputMint
}

err := e.svc.MochiPay.CreateBatchToken(mochipayrequest.CreateBatchTokenRequest{
_, err := e.svc.MochiPay.CreateBatchToken(mochipayrequest.CreateBatchTokenRequest{
Tokens: []mochipayrequest.CreateTokenRequest{
{
Id: uuid.New().String(),
Expand Down
4 changes: 2 additions & 2 deletions pkg/entities/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ func (e *Entity) GetTopUsers(req request.GetTopUsersRequest) (*response.TopUser,
item := &leaderboard[i]

if item.User == nil {
profile, err := e.svc.MochiProfile.GetByID(item.ProfileID)
profile, err := e.svc.MochiProfile.GetByID(item.ProfileID, e.cfg.MochiBotSecret)
if err != nil {
return
}
Expand Down Expand Up @@ -544,7 +544,7 @@ func (e *Entity) GetUserBalance(profileId string) (*response.UserBalanceResponse
}

// get all onchain account
profile, err := e.svc.MochiProfile.GetByID(profileId)
profile, err := e.svc.MochiProfile.GetByID(profileId, e.cfg.MochiBotSecret)
if err != nil {
e.log.Fields(logger.Fields{"profileId": profileId}).Error(err, "[entity.GetUserBalance] - e.svc.MochiProfile.GetByID failed")
return nil, err
Expand Down
4 changes: 2 additions & 2 deletions pkg/entities/vault.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func (e *Entity) CreateVault(req *request.CreateVaultRequest) (*model.Vault, err
}

userDiscordID := ""
profile, err := e.svc.MochiProfile.GetByID(req.VaultCreator)
profile, err := e.svc.MochiProfile.GetByID(req.VaultCreator, e.cfg.MochiBotSecret)
if err != nil {
e.log.Fields(logger.Fields{"req": req}).Errorf(err, "[entity.GetVaults] svc.MochiProfile.GetByID() failed")
return nil, err
Expand Down Expand Up @@ -229,7 +229,7 @@ func (e *Entity) CreateConfigThreshold(req *request.CreateConfigThresholdRequest

func (e *Entity) AddTreasurerToVault(req *request.AddTreasurerToVaultRequest) (*model.VaultTreasurer, error) {
userDiscordID := ""
profile, err := e.svc.MochiProfile.GetByID(req.UserProfileID)
profile, err := e.svc.MochiProfile.GetByID(req.UserProfileID, "")
if err != nil {
e.log.Fields(logger.Fields{"req": req}).Errorf(err, "[entity.GetVaults] svc.MochiProfile.GetByID() failed")
return nil, err
Expand Down
20 changes: 18 additions & 2 deletions pkg/entities/wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,12 @@ func (e *Entity) listEvmWalletAssets(req request.ListWalletAssetsRequest) ([]res
price = 1.5
}

// enrich token data into pay database
address := bal.Token.Address
if bal.TokenType == "NATIVE" {
address = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"
}

assets = append(assets, response.WalletAssetData{
ChainID: item.ChainId,
ContractName: bal.Token.Name,
Expand All @@ -404,6 +410,7 @@ func (e *Entity) listEvmWalletAssets(req request.ListWalletAssetsRequest) ([]res
Name: bal.Token.Name,
Symbol: bal.Token.Symbol,
Decimal: int64(bal.Token.Decimals),
Address: address,
Price: price,
Native: bal.TokenType == "NATIVE",
Chain: response.AssetTokenChain{
Expand All @@ -416,6 +423,8 @@ func (e *Entity) listEvmWalletAssets(req request.ListWalletAssetsRequest) ([]res
}
}

assets = e.enrichDataWalletAsset(assets)

baseAsset, err := e.listBaseWalletAssets(req)
if err != nil {
e.log.Fields(logger.Fields{"req": req}).Error(err, "[entity.listEvmWalletAssets] entity.listBaseWalletAssets() failed")
Expand Down Expand Up @@ -520,6 +529,10 @@ func (e *Entity) listSolWalletAssets(req request.ListWalletAssetsRequest) ([]res
continue
}

address := item.ContractAddress
if item.NativeToken {
address = "So11111111111111111111111111111111111111112"
}
assets = append(assets, response.WalletAssetData{
ChainID: chainID,
ContractName: item.ContractName,
Expand All @@ -529,6 +542,7 @@ func (e *Entity) listSolWalletAssets(req request.ListWalletAssetsRequest) ([]res
Token: response.AssetToken{
Name: item.ContractName,
Symbol: item.ContractTickerSymbol,
Address: address,
Decimal: decimals,
Price: tokenPrice.Data.Value,
Native: item.NativeToken,
Expand All @@ -541,6 +555,8 @@ func (e *Entity) listSolWalletAssets(req request.ListWalletAssetsRequest) ([]res
})
}

assets = e.enrichDataWalletAsset(assets)

// calculate pnl
pnl, latestSnapshotBal, err := e.calculateWalletSnapshot(req.Address, false, assets)
if err != nil {
Expand Down Expand Up @@ -1043,7 +1059,7 @@ func (e *Entity) SumarizeBinanceAsset(req request.BinanceRequest) (*response.Wal
}

func (e *Entity) GetBinanceAssets(req request.GetBinanceAssetsRequest) (*response.GetBinanceAsset, error) {
profile, err := e.svc.MochiProfile.GetByID(req.Id)
profile, err := e.svc.MochiProfile.GetByID(req.Id, e.cfg.MochiBotSecret)
if err != nil {
e.log.Fields(logger.Fields{"req": req}).Error(err, "[entities.GetBinanceAssets] Failed to get profile")
return nil, err
Expand Down Expand Up @@ -1463,7 +1479,7 @@ func (e *Entity) parseSkymavisInternalTxnsData(data *response.WalletTransactionD
}

func (e *Entity) GetBinanceFuturePosition(req request.GetBinanceFutureRequest) ([]response.BinanceFuturePositionInformation, error) {
profile, err := e.svc.MochiProfile.GetByID(req.Id)
profile, err := e.svc.MochiProfile.GetByID(req.Id, e.cfg.MochiBotSecret)
if err != nil {
e.log.Fields(logger.Fields{"req": req}).Error(err, "[entities.GetBinanceFuturePosition] Failed to get profile")
return nil, err
Expand Down
34 changes: 34 additions & 0 deletions pkg/entities/wallet_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"strconv"
"strings"
"time"

"github.com/defipod/mochi/pkg/logger"
Expand Down Expand Up @@ -387,3 +388,36 @@ func formatOffchainBalance(offchainBalance mochipay.GetBalanceDataResponse) []re
}
return resp
}

// add tokens into mochi-pay database
func (e *Entity) enrichDataWalletAsset(assets []response.WalletAssetData) []response.WalletAssetData {
reqCreateMochiPayTokens := make([]mochipay.CreateTokenRequest, 0)
for _, asset := range assets {
reqCreateMochiPayTokens = append(reqCreateMochiPayTokens, mochipay.CreateTokenRequest{
Name: asset.Token.Name,
Symbol: asset.Token.Symbol,
Decimal: asset.Token.Decimal,
ChainId: fmt.Sprint(asset.ChainID),
Address: asset.Token.Address,
})
}

// create tokens
tokens, err := e.svc.MochiPay.CreateBatchToken(mochipay.CreateBatchTokenRequest{Tokens: reqCreateMochiPayTokens})
if err != nil {
e.log.Error(err, "[entities.enrichDataWalletAsset] Failed to create tokens")
return assets
}

// enrich id into assets
for i, asset := range assets {
for _, token := range tokens {
if strings.EqualFold(token.Symbol, asset.Token.Symbol) && token.ChainId == fmt.Sprint(asset.ChainID) && strings.EqualFold(token.Address, asset.Token.Address) {
assets[i].Token.Id = token.Id
break
}
}
}

return assets
}
2 changes: 2 additions & 0 deletions pkg/model/offchain_tip_bot_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ type OffchainTipBotToken struct {
DeletedAt *time.Time `json:"-"`
CoinGeckoID string `json:"coin_gecko_id"`
ServiceFee float64 `json:"service_fee"`
TokenPrice float64 `json:"token_price" gorm:"-"`
ChainId string `json:"chain_id"`
}

func (OffchainTipBotToken) TableName() string {
Expand Down
2 changes: 2 additions & 0 deletions pkg/response/wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ type WalletAssetData struct {
}

type AssetToken struct {
Id string `json:"id"`
Address string `json:"address"`
Name string `json:"name"`
Symbol string `json:"symbol"`
Decimal int64 `json:"decimal"`
Expand Down
2 changes: 1 addition & 1 deletion pkg/service/birdeye/birdeye.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func (b *birdeye) fetchBirdeyeData(url string, v any) error {
req := util.SendRequestQuery{
URL: url,
ParseForm: &v,
Headers: map[string]string{"Content-Type": "application/json"},
Headers: map[string]string{"Content-Type": "application/json", "X-API-KEY": b.config.BirdEyeApiKey},
}

statusCode, err := util.SendRequest(req)
Expand Down
27 changes: 19 additions & 8 deletions pkg/service/mochipay/mochipay.go
Original file line number Diff line number Diff line change
Expand Up @@ -407,10 +407,10 @@ func (m *MochiPay) GetToken(symbol, chainId string) (*Token, error) {
return res.Data, nil
}

func (m *MochiPay) CreateBatchToken(req CreateBatchTokenRequest) error {
func (m *MochiPay) CreateBatchToken(req CreateBatchTokenRequest) ([]Token, error) {
payload, err := json.Marshal(req)
if err != nil {
return err
return nil, err
}

jsonBody := bytes.NewBuffer(payload)
Expand All @@ -419,32 +419,43 @@ func (m *MochiPay) CreateBatchToken(req CreateBatchTokenRequest) error {
url := fmt.Sprintf("%s/api/v1/tokens", m.config.MochiPayServerHost)
request, err := http.NewRequest("POST", url, jsonBody)
if err != nil {
return err
return nil, err
}
request.Header.Add("Content-Type", "application/json")

response, err := client.Do(request)
if err != nil {
return err
return nil, err
}

if response.StatusCode != http.StatusOK {
errBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
return nil, err
}

errResponse := &ErrorResponse{}
err = json.Unmarshal(errBody, &errResponse)
if err != nil {
return err
return nil, err
}

err = fmt.Errorf(errResponse.Msg)
return err
return nil, err
}

return nil
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}

res := &ListTokensResponse{}
err = json.Unmarshal(responseBody, res)
if err != nil {
return nil, err
}

return res.Data, nil
}

func (m *MochiPay) GetTokenByProperties(req TokenProperties) (*Token, error) {
Expand Down
2 changes: 1 addition & 1 deletion pkg/service/mochipay/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ type Service interface {
ListTokens(symbol string) ([]Token, error)
GetToken(symbol, chainId string) (*Token, error)
TransferVaultMochiPay(req request.MochiPayVaultRequest) (*VaultResponse, error)
CreateBatchToken(req CreateBatchTokenRequest) error
CreateBatchToken(req CreateBatchTokenRequest) ([]Token, error)
GetTokenByProperties(req TokenProperties) (*Token, error)
GetListBalances(profileId string) (*GetBalanceDataResponse, error)
GetListChains() (*GetChainDataResponse, error)
Expand Down
4 changes: 2 additions & 2 deletions pkg/service/mochiprofile/mochiprofile.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,14 +168,14 @@ func (m *MochiProfile) CreateProfileApiKey(profileAccessToken string) (*ProfileA
return &res.Data, nil
}

func (m *MochiProfile) GetByID(profileID string) (*GetProfileResponse, error) {
func (m *MochiProfile) GetByID(profileID, authorization string) (*GetProfileResponse, error) {
url := fmt.Sprintf("%s/api/v1/profiles/%s", m.config.MochiProfileServerHost, profileID)

res := GetProfileResponse{}
req := util.SendRequestQuery{
URL: url,
ParseForm: &res,
Headers: map[string]string{"Content-Type": "application/json"},
Headers: map[string]string{"Content-Type": "application/json", "Authorization": "Bearer " + authorization},
}
statusCode, err := util.SendRequest(req)
if err != nil || statusCode != http.StatusOK {
Expand Down
2 changes: 1 addition & 1 deletion pkg/service/mochiprofile/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ type Service interface {
GetByDiscordID(discordID string, noFetchAmount bool) (*GetProfileResponse, error)
GetApiKeyByProfileID(profileID string) (*ProfileApiKeyResponse, error)
CreateProfileApiKey(profileAccessToken string) (*ProfileApiKeyResponse, error)
GetByID(profileID string) (*GetProfileResponse, error)
GetByID(profileID, authorization string) (*GetProfileResponse, error)
GetByIds(profileIds []string) ([]GetProfileResponse, error)
GetByDiscordIds(discordIds []string) ([]GetProfileResponse, error)
GetAllEvmAccount() ([]*EvmAssociatedAccount, error)
Expand Down

0 comments on commit c95896b

Please sign in to comment.