Skip to content

Commit e9ecb87

Browse files
committed
add retry mechanic
1 parent ea49377 commit e9ecb87

File tree

1 file changed

+41
-21
lines changed

1 file changed

+41
-21
lines changed

protocol/lighter/api.go

Lines changed: 41 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@ import (
99
)
1010

1111
const (
12-
LIGHTER_URL = "https://mainnet.zklighter.elliot.ai/api"
12+
LIGHTER_URL = "https://mainnet.zklighter.elliot.ai/api"
13+
TX_NOT_FOUND_RETRIES = 3
14+
TX_NOT_FOUND_RETRY_TIMEOUT = 1 * time.Second
15+
TX_NOT_FOUND_ERROR_CODE = 21500
1316
)
1417

1518
type TxType uint64
@@ -76,30 +79,47 @@ func NewLighterAPI() *LighterAPI {
7679

7780
// GetTx fetches transaction from the lighter API
7881
func (a *LighterAPI) GetTx(hash string) (*LighterTx, error) {
79-
url := fmt.Sprintf("%s/v1/tx?by=hash&value=%s", LIGHTER_URL, hash)
80-
resp, err := a.HTTPClient.Get(url)
81-
if err != nil {
82-
return nil, fmt.Errorf("request failed: %w", err)
83-
}
84-
defer resp.Body.Close()
82+
var lastErr error
8583

86-
if resp.StatusCode != http.StatusOK {
87-
return nil, fmt.Errorf("unexpected status code: %d, %s", resp.StatusCode, url)
88-
}
84+
for attempt := 0; attempt < TX_NOT_FOUND_RETRIES; attempt++ {
85+
if attempt > 0 {
86+
time.Sleep(TX_NOT_FOUND_RETRY_TIMEOUT)
87+
}
8988

90-
body, err := io.ReadAll(resp.Body)
91-
if err != nil {
92-
return nil, fmt.Errorf("failed to read response body: %w", err)
93-
}
89+
url := fmt.Sprintf("%s/v1/tx?by=hash&value=%s", LIGHTER_URL, hash)
90+
resp, err := a.HTTPClient.Get(url)
91+
if err != nil {
92+
return nil, fmt.Errorf("request failed: %w", err)
93+
}
94+
defer resp.Body.Close()
95+
96+
if resp.StatusCode != http.StatusOK {
97+
return nil, fmt.Errorf("unexpected status code: %d, %s", resp.StatusCode, url)
98+
}
99+
100+
body, err := io.ReadAll(resp.Body)
101+
if err != nil {
102+
return nil, fmt.Errorf("failed to read response body: %w", err)
103+
}
94104

95-
s := new(LighterTx)
96-
if err := json.Unmarshal(body, s); err != nil {
97-
e := new(LighterError)
98-
if err := json.Unmarshal(body, e); err != nil {
99-
return nil, fmt.Errorf("failed to unmarshal response body: %s, with error: %w", string(body), err)
105+
s := new(LighterTx)
106+
if err := json.Unmarshal(body, s); err != nil {
107+
e := new(LighterError)
108+
if err := json.Unmarshal(body, e); err != nil {
109+
return nil, fmt.Errorf("failed to unmarshal response body: %s, with error: %w", string(body), err)
110+
}
111+
112+
// Retry if transaction not found
113+
if e.Code == TX_NOT_FOUND_ERROR_CODE {
114+
lastErr = e.Error()
115+
continue
116+
}
117+
118+
return nil, e.Error()
100119
}
101-
return nil, e.Error()
120+
121+
return s, nil
102122
}
103123

104-
return s, nil
124+
return nil, lastErr
105125
}

0 commit comments

Comments
 (0)