Skip to content

Commit 960e9a2

Browse files
fix the context canceled error
1 parent 4fef929 commit 960e9a2

File tree

2 files changed

+42
-60
lines changed

2 files changed

+42
-60
lines changed

pkg/rates/market.go

Lines changed: 29 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package rates
22

33
import (
4+
"bytes"
45
"context"
56
"encoding/csv"
67
"encoding/json"
@@ -70,11 +71,11 @@ type Market struct {
7071
UsdPrice float64
7172
URL string
7273
// Converter for calculating the TON to USD price
73-
TonPriceConverter func(closer io.ReadCloser) (float64, error)
74+
TonPriceConverter func(respBody []byte) (float64, error)
7475
// Converter for calculating fiat prices
75-
FiatPriceConverter func(closer io.ReadCloser) (map[string]float64, error)
76+
FiatPriceConverter func(respBody []byte) (map[string]float64, error)
7677
// Converter for calculating jetton prices within pools
77-
PoolResponseConverter func(closer io.ReadCloser) ([]Assets, []LpAsset, error)
78+
PoolResponseConverter func(respBody []byte) ([]Assets, []LpAsset, error)
7879
DateUpdate time.Time
7980
}
8081

@@ -149,12 +150,11 @@ func (m *Mock) GetCurrentMarketsTonPrice() ([]Market, error) {
149150
return markets, nil
150151
}
151152

152-
func convertedTonGateIOResponse(respBody io.ReadCloser) (float64, error) {
153-
defer respBody.Close()
153+
func convertedTonGateIOResponse(respBody []byte) (float64, error) {
154154
var data []struct {
155155
Last string `json:"last"`
156156
}
157-
if err := json.NewDecoder(respBody).Decode(&data); err != nil {
157+
if err := json.Unmarshal(respBody, &data); err != nil {
158158
return 0, fmt.Errorf("[convertedTonGateIOResponse] failed to decode response: %v", err)
159159
}
160160
if len(data) == 0 {
@@ -167,8 +167,7 @@ func convertedTonGateIOResponse(respBody io.ReadCloser) (float64, error) {
167167
return price, nil
168168
}
169169

170-
func convertedTonBybitResponse(respBody io.ReadCloser) (float64, error) {
171-
defer respBody.Close()
170+
func convertedTonBybitResponse(respBody []byte) (float64, error) {
172171
var data struct {
173172
RetMsg string `json:"retMsg"`
174173
Result struct {
@@ -177,7 +176,7 @@ func convertedTonBybitResponse(respBody io.ReadCloser) (float64, error) {
177176
} `json:"list"`
178177
} `json:"result"`
179178
}
180-
if err := json.NewDecoder(respBody).Decode(&data); err != nil {
179+
if err := json.Unmarshal(respBody, &data); err != nil {
181180
return 0, fmt.Errorf("[convertedTonBybitResponse] failed to decode response: %v", err)
182181
}
183182
if data.RetMsg != "OK" {
@@ -193,10 +192,9 @@ func convertedTonBybitResponse(respBody io.ReadCloser) (float64, error) {
193192
return price, nil
194193
}
195194

196-
func convertedTonBitFinexResponse(respBody io.ReadCloser) (float64, error) {
197-
defer respBody.Close()
195+
func convertedTonBitFinexResponse(respBody []byte) (float64, error) {
198196
var prices []float64
199-
if err := json.NewDecoder(respBody).Decode(&prices); err != nil {
197+
if err := json.Unmarshal(respBody, &prices); err != nil {
200198
return 0, fmt.Errorf("[convertedTonBitFinexResponse] failed to decode response: %v", err)
201199
}
202200
if len(prices) == 0 {
@@ -209,15 +207,14 @@ func convertedTonBitFinexResponse(respBody io.ReadCloser) (float64, error) {
209207
return prices[0], nil
210208
}
211209

212-
func convertedTonKuCoinResponse(respBody io.ReadCloser) (float64, error) {
213-
defer respBody.Close()
210+
func convertedTonKuCoinResponse(respBody []byte) (float64, error) {
214211
var data struct {
215212
Success bool `json:"success"`
216213
Data []struct {
217214
LastTradedPrice string `json:"lastTradedPrice"`
218215
} `json:"data"`
219216
}
220-
if err := json.NewDecoder(respBody).Decode(&data); err != nil {
217+
if err := json.Unmarshal(respBody, &data); err != nil {
221218
return 0, fmt.Errorf("[convertedTonKuCoinResponse] failed to decode response: %v", err)
222219
}
223220
if !data.Success {
@@ -233,15 +230,14 @@ func convertedTonKuCoinResponse(respBody io.ReadCloser) (float64, error) {
233230
return price, nil
234231
}
235232

236-
func convertedTonOKXResponse(respBody io.ReadCloser) (float64, error) {
237-
defer respBody.Close()
233+
func convertedTonOKXResponse(respBody []byte) (float64, error) {
238234
var data struct {
239235
Code string `json:"code"`
240236
Data []struct {
241237
Last string `json:"last"`
242238
} `json:"data"`
243239
}
244-
if err := json.NewDecoder(respBody).Decode(&data); err != nil {
240+
if err := json.Unmarshal(respBody, &data); err != nil {
245241
return 0, fmt.Errorf("[convertedTonOKXResponse] failed to decode response: %v", err)
246242
}
247243
if data.Code != "0" {
@@ -259,8 +255,7 @@ func convertedTonOKXResponse(respBody io.ReadCloser) (float64, error) {
259255
return price, nil
260256
}
261257

262-
func convertedTonHuobiResponse(respBody io.ReadCloser) (float64, error) {
263-
defer respBody.Close()
258+
func convertedTonHuobiResponse(respBody []byte) (float64, error) {
264259
var data struct {
265260
Status string `json:"status"`
266261
Tick struct {
@@ -271,7 +266,7 @@ func convertedTonHuobiResponse(respBody io.ReadCloser) (float64, error) {
271266
} `json:"data"`
272267
} `json:"tick"`
273268
}
274-
if err := json.NewDecoder(respBody).Decode(&data); err != nil {
269+
if err := json.Unmarshal(respBody, &data); err != nil {
275270
return 0, fmt.Errorf("[convertedTonHuobiResponse] failed to decode response: %v", err)
276271
}
277272
if data.Status != "ok" {
@@ -316,14 +311,13 @@ func getFiatPrices(tonPrice float64) map[string]float64 {
316311
return prices
317312
}
318313

319-
func convertedCoinBaseFiatPricesResponse(respBody io.ReadCloser) (map[string]float64, error) {
320-
defer respBody.Close()
314+
func convertedCoinBaseFiatPricesResponse(respBody []byte) (map[string]float64, error) {
321315
var data struct {
322316
Data struct {
323317
Rates map[string]string `json:"rates"`
324318
} `json:"data"`
325319
}
326-
if err := json.NewDecoder(respBody).Decode(&data); err != nil {
320+
if err := json.Unmarshal(respBody, &data); err != nil {
327321
return map[string]float64{}, fmt.Errorf("[convertedCoinBaseFiatPricesResponse] failed to decode response: %v", err)
328322
}
329323
prices := make(map[string]float64)
@@ -432,9 +426,8 @@ func (m *Mock) getJettonPricesFromDex(pools map[ton.AccountID]float64) map[ton.A
432426
return pools
433427
}
434428

435-
func convertedStonFiPoolResponse(respBody io.ReadCloser) ([]Assets, []LpAsset, error) {
436-
defer respBody.Close()
437-
reader := csv.NewReader(respBody)
429+
func convertedStonFiPoolResponse(respBody []byte) ([]Assets, []LpAsset, error) {
430+
reader := csv.NewReader(bytes.NewReader(respBody))
438431
records, err := reader.ReadAll()
439432
if err != nil {
440433
return nil, nil, err
@@ -546,9 +539,8 @@ func convertedStonFiPoolResponse(respBody io.ReadCloser) ([]Assets, []LpAsset, e
546539
return actualAssets, maps.Values(actualLpAssets), nil
547540
}
548541

549-
func convertedDeDustPoolResponse(respBody io.ReadCloser) ([]Assets, []LpAsset, error) {
550-
defer respBody.Close()
551-
reader := csv.NewReader(respBody)
542+
func convertedDeDustPoolResponse(respBody []byte) ([]Assets, []LpAsset, error) {
543+
reader := csv.NewReader(bytes.NewReader(respBody))
552544
records, err := reader.ReadAll()
553545
if err != nil {
554546
return nil, nil, err
@@ -795,8 +787,7 @@ func calculatePoolPrice(firstAsset, secondAsset Asset, pools map[ton.AccountID]f
795787
return calculatedAccount, price
796788
}
797789

798-
// Note: You must close resp.Body in the handler function; here, it is closed ONLY in case of a bad status_code
799-
func sendRequest(url, token string) (io.ReadCloser, error) {
790+
func sendRequest(url, token string) ([]byte, error) {
800791
ctx, cancel := context.WithTimeout(context.Background(), time.Second*15)
801792
defer cancel()
802793

@@ -812,10 +803,14 @@ func sendRequest(url, token string) (io.ReadCloser, error) {
812803
if err != nil {
813804
return nil, err
814805
}
806+
defer resp.Body.Close()
815807
if resp.StatusCode != http.StatusOK {
816-
resp.Body.Close()
817808
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
818809
}
810+
body, err := io.ReadAll(resp.Body)
811+
if err != nil {
812+
return nil, fmt.Errorf("failed to read response body: %w", err)
813+
}
819814

820-
return resp.Body, nil
815+
return body, nil
821816
}

pkg/rates/sources.go

Lines changed: 13 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -141,14 +141,12 @@ type ExecutionResult struct {
141141
// getBemoPrice fetches BEMO price by smart contract data
142142
func (m *Mock) getBemoPrice(_ float64, _ map[ton.AccountID]float64) (map[ton.AccountID]float64, error) {
143143
url := fmt.Sprintf("https://tonapi.io/v2/blockchain/accounts/%v/methods/get_full_data", references.BemoAccount.ToRaw())
144-
resp, err := sendRequest(url, m.TonApiToken)
144+
respBody, err := sendRequest(url, m.TonApiToken)
145145
if err != nil {
146146
return nil, err
147147
}
148-
defer resp.Close()
149-
150148
var result ExecutionResult
151-
if err = json.NewDecoder(resp).Decode(&result); err != nil {
149+
if err = json.Unmarshal(respBody, &result); err != nil {
152150
return nil, err
153151
}
154152
if !result.Success || len(result.Stack) < 2 {
@@ -170,12 +168,10 @@ func (m *Mock) getBemoPrice(_ float64, _ map[ton.AccountID]float64) (map[ton.Acc
170168
// getTonstakersPrice fetches Tonstakers price by smart contract data
171169
func (m *Mock) getTonstakersPrice(_ float64, _ map[ton.AccountID]float64) (map[ton.AccountID]float64, error) {
172170
url := fmt.Sprintf("https://tonapi.io/v2/blockchain/accounts/%v/methods/get_pool_full_data", references.TonstakersAccountPool.ToRaw())
173-
resp, err := sendRequest(url, m.TonApiToken)
171+
respBody, err := sendRequest(url, m.TonApiToken)
174172
if err != nil {
175173
return nil, err
176174
}
177-
defer resp.Close()
178-
179175
var result struct {
180176
Success bool `json:"success"`
181177
Decoded struct {
@@ -184,7 +180,7 @@ func (m *Mock) getTonstakersPrice(_ float64, _ map[ton.AccountID]float64) (map[t
184180
ProjectedSupply int64 `json:"projected_supply"`
185181
}
186182
}
187-
if err = json.NewDecoder(resp).Decode(&result); err != nil {
183+
if err = json.Unmarshal(respBody, &result); err != nil {
188184
return nil, err
189185
}
190186
if !result.Success || result.Decoded.ProjectBalance == 0 || result.Decoded.ProjectedSupply == 0 {
@@ -208,14 +204,12 @@ func (m *Mock) getBeetrootPrice(tonPrice float64, _ map[ton.AccountID]float64) (
208204
account := ton.MustParseAccountID("EQAFGhmx199oH6kmL78PGBHyAx4d5CiJdfXwSjDK5F5IFyfC")
209205

210206
url := fmt.Sprintf("https://tonapi.io/v2/blockchain/accounts/%v/methods/get_price_data", contract)
211-
resp, err := sendRequest(url, m.TonApiToken)
207+
respBody, err := sendRequest(url, m.TonApiToken)
212208
if err != nil {
213209
return nil, err
214210
}
215-
defer resp.Close()
216-
217211
var result ExecutionResult
218-
if err = json.NewDecoder(resp).Decode(&result); err != nil {
212+
if err = json.Unmarshal(respBody, &result); err != nil {
219213
return nil, err
220214
}
221215
if !result.Success || len(result.Stack) == 0 {
@@ -237,17 +231,15 @@ func (m *Mock) getTsUSDePrice(tonPrice float64, _ map[ton.AccountID]float64) (ma
237231
}
238232
contract := ton.MustParseAccountID("EQChGuD1u0e7KUWHH5FaYh_ygcLXhsdG2nSHPXHW8qqnpZXW")
239233
account := ton.MustParseAccountID("EQDQ5UUyPHrLcQJlPAczd_fjxn8SLrlNQwolBznxCdSlfQwr")
240-
refShare := decimal.NewFromInt(1_000_000)
234+
refShare := decimal.NewFromInt(1_000_000_000)
241235

242236
url := fmt.Sprintf("https://tonapi.io/v2/blockchain/accounts/%v/methods/convertToAssets?args=%v", contract, refShare)
243-
resp, err := sendRequest(url, m.TonApiToken)
237+
respBody, err := sendRequest(url, m.TonApiToken)
244238
if err != nil {
245239
return nil, err
246240
}
247-
defer resp.Close()
248-
249241
var result ExecutionResult
250-
if err = json.NewDecoder(resp).Decode(&result); err != nil {
242+
if err = json.Unmarshal(respBody, &result); err != nil {
251243
return nil, err
252244
}
253245
if !result.Success || len(result.Stack) != 1 || result.Stack[0].Type != "num" {
@@ -270,12 +262,10 @@ func (m *Mock) getUsdEPrice(tonPrice float64, _ map[ton.AccountID]float64) (map[
270262
account := ton.MustParseAccountID("EQAIb6KmdfdDR7CN1GBqVJuP25iCnLKCvBlJ07Evuu2dzP5f")
271263

272264
url := "https://api.bybit.com/v5/market/tickers?category=spot&symbol=USDEUSDT"
273-
resp, err := sendRequest(url, "")
265+
respBody, err := sendRequest(url, "")
274266
if err != nil {
275267
return nil, err
276268
}
277-
defer resp.Close()
278-
279269
result := struct {
280270
RetMsg string `json:"retMsg"`
281271
Result struct {
@@ -284,7 +274,7 @@ func (m *Mock) getUsdEPrice(tonPrice float64, _ map[ton.AccountID]float64) (map[
284274
} `json:"list"`
285275
}
286276
}{}
287-
if err = json.NewDecoder(resp).Decode(&result); err != nil {
277+
if err = json.Unmarshal(respBody, &result); err != nil {
288278
return nil, err
289279
}
290280
if result.RetMsg != "OK" || len(result.Result.List) == 0 {
@@ -308,17 +298,14 @@ func (m *Mock) getSlpTokensPrice(tonPrice float64, pools map[ton.AccountID]float
308298
result := make(map[tongo.AccountID]float64)
309299
for slpType, account := range references.SlpAccounts {
310300
url := fmt.Sprintf("https://tonapi.io/v2/blockchain/accounts/%v/methods/get_vault_data", account.ToRaw())
311-
resp, err := sendRequest(url, m.TonApiToken)
301+
respBody, err := sendRequest(url, m.TonApiToken)
312302
if err != nil {
313303
continue
314304
}
315305
var data ExecutionResult
316-
if err = json.NewDecoder(resp).Decode(&data); err != nil {
317-
resp.Close()
306+
if err = json.Unmarshal(respBody, &data); err != nil {
318307
continue
319308
}
320-
resp.Close()
321-
322309
if len(data.Stack) < 2 {
323310
continue
324311
}

0 commit comments

Comments
 (0)