Skip to content

Commit

Permalink
ethrpc: add WithJWTAuthorization option to provider
Browse files Browse the repository at this point in the history
  • Loading branch information
pkieltyka committed Nov 8, 2023
1 parent 4db4eaa commit 927a4b4
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
7 changes: 6 additions & 1 deletion ethrpc/ethrpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type Provider struct {
nodeURL string
httpClient httpClient
br breaker.Breaker
jwtToken string // optional

chainID *big.Int
// cache cachestore.Store[[]byte] // NOTE: unused for now
Expand Down Expand Up @@ -90,6 +91,10 @@ func (p *Provider) Do(ctx context.Context, calls ...Call) ([]byte, error) {
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/json")

if p.jwtToken != "" {
req.Header.Set("Authorization", fmt.Sprintf("BEARER %s", p.jwtToken))
}

res, err := p.httpClient.Do(req)
if err != nil {
return nil, superr.Wrap(ErrRequestFail, fmt.Errorf("failed to send request: %w", err))
Expand All @@ -101,7 +106,7 @@ func (p *Provider) Do(ctx context.Context, calls ...Call) ([]byte, error) {
return nil, superr.Wrap(ErrRequestFail, fmt.Errorf("failed to read resposne body: %w", err))
}

if res.StatusCode < 200 || res.StatusCode > 299 {
if (res.StatusCode < 200 || res.StatusCode > 299) && res.StatusCode != 401 {
if len(body) > 100 {
body = body[:100]
}
Expand Down
10 changes: 10 additions & 0 deletions ethrpc/ethrpc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,13 @@ func TestRaw(t *testing.T) {
require.Empty(t, payload)
}
}

// func TestJWTAuth(t *testing.T) {
// p, err := ethrpc.NewProvider("https://dev-nodes.sequence.app/polygon", ethrpc.WithJWTAuthorization("xx"))
// require.NoError(t, err)

// block, err := p.BlockByNumber(context.Background(), big.NewInt(1_000_000))
// require.NoError(t, err)
// require.NotNil(t, block)
// require.Equal(t, uint64(1_000_000), block.NumberU64())
// }
6 changes: 6 additions & 0 deletions ethrpc/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,9 @@ func WithBreaker(br breaker.Breaker) Option {
// p.cache = cache
// }
// }

func WithJWTAuthorization(jwtToken string) Option {
return func(p *Provider) {
p.jwtToken = jwtToken
}
}

0 comments on commit 927a4b4

Please sign in to comment.