From 40f51e75b09a621b9fddaf63991842a8b091b610 Mon Sep 17 00:00:00 2001 From: Haiss2 Date: Wed, 7 Aug 2024 14:03:55 +0700 Subject: [PATCH] Import ks-setting token if not found --- pkg/pricefiller/ks_client.go | 41 ++++++++++++++++++++++++++++++++ pkg/pricefiller/price_fillter.go | 19 +++++++++++++-- 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/pkg/pricefiller/ks_client.go b/pkg/pricefiller/ks_client.go index 02dff50..38dba3c 100644 --- a/pkg/pricefiller/ks_client.go +++ b/pkg/pricefiller/ks_client.go @@ -103,3 +103,44 @@ func (c *KsClient) GetTokenCatalog(address string) (TokenCatalogResp, error) { return resp, nil } + +type ImportedToken struct { + ChainID string `json:"chainId"` + Address string `json:"address"` +} + +type ImportTokenParam struct { + Tokens []ImportedToken `json:"tokens"` +} + +type ImportTokenResp struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data struct { + Tokens []struct { + Data TokenCatalog `json:"data"` + } `json:"tokens"` + } `json:"data"` +} + +func (c *KsClient) ImportToken(chainID, address string) (ImportTokenResp, error) { + param := ImportTokenParam{ + Tokens: []ImportedToken{ + { + ChainID: chainID, + Address: address, + }, + }, + } + var resp ImportTokenResp + err := c.DoRequest(context.Background(), http.MethodPost, c.baseURL+"/tokens/import", param, &resp) + if err != nil { + return ImportTokenResp{}, err + } + + if resp.Code != 0 { + return ImportTokenResp{}, fmt.Errorf("invalid response code: %d", resp.Code) + } + + return resp, nil +} diff --git a/pkg/pricefiller/price_fillter.go b/pkg/pricefiller/price_fillter.go index 786e39b..8fa8550 100644 --- a/pkg/pricefiller/price_fillter.go +++ b/pkg/pricefiller/price_fillter.go @@ -15,6 +15,7 @@ import ( const ( NetworkETHChanID = 1 + NetworkETHChanIDString = "1" NetworkETH = "ETH" updateAllCoinInfoInterval = time.Hour backfillTradeLogsPriceInterval = 10 * time.Minute @@ -248,10 +249,24 @@ func (p *PriceFiller) getDecimals(address string) (int64, error) { return 0, err } - if len(resp.Data.Tokens) != 1 { + if len(resp.Data.Tokens) == 1 { + return resp.Data.Tokens[0].Decimals, nil + } + if len(resp.Data.Tokens) > 1 { p.l.Warnw("Weird token catalog response", "resp", resp) return 0, ErrWeirdTokenCatalogResp } - return resp.Data.Tokens[0].Decimals, nil + // try to import token if token is not found. + newResp, err := p.ksClient.ImportToken(NetworkETHChanIDString, address) + if err != nil { + p.l.Errorw("Failed to ImportToken", "err", err) + return 0, err + } + if len(newResp.Data.Tokens) == 1 { + return newResp.Data.Tokens[0].Data.Decimals, nil + } + + p.l.Warnw("Weird ImportToken response", "resp", newResp) + return 0, ErrWeirdTokenCatalogResp }