diff --git a/service/cachemdw/cache.go b/service/cachemdw/cache.go index d2ff2b7..fe7e3db 100644 --- a/service/cachemdw/cache.go +++ b/service/cachemdw/cache.go @@ -41,8 +41,8 @@ func NewServiceCache( } } -func (c *ServiceCache) IsCacheable(ctx context.Context, req *decode.EVMRPCRequestEnvelope) bool { - blockNumber, err := req.ExtractBlockNumberFromEVMRPCRequest(ctx, c.evmClient) +func IsCacheable(ctx context.Context, evmClient EVMClient, req *decode.EVMRPCRequestEnvelope) bool { + blockNumber, err := req.ExtractBlockNumberFromEVMRPCRequest(ctx, evmClient) if err != nil { return false } @@ -83,7 +83,7 @@ func (c *ServiceCache) CacheQueryResponse( req *decode.EVMRPCRequestEnvelope, response []byte, ) error { - if !c.IsCacheable(ctx, req) { + if !IsCacheable(ctx, c.evmClient, req) { return errors.New("query isn't cacheable") } diff --git a/service/cachemdw/cache_test.go b/service/cachemdw/cache_test.go new file mode 100644 index 0000000..378c7ee --- /dev/null +++ b/service/cachemdw/cache_test.go @@ -0,0 +1,65 @@ +package cachemdw + +import ( + "context" + "math/big" + "testing" + + "github.com/ethereum/go-ethereum/common" + ethctypes "github.com/ethereum/go-ethereum/core/types" + "github.com/stretchr/testify/require" + + "github.com/kava-labs/kava-proxy-service/decode" +) + +type MockEVMClient struct{} + +func NewMockEVMClient() *MockEVMClient { + return &MockEVMClient{} +} + +var _ EVMClient = (*MockEVMClient)(nil) + +func (c *MockEVMClient) BlockByHash(ctx context.Context, hash common.Hash) (*ethctypes.Block, error) { + panic("not implemented") +} + +func (c *MockEVMClient) ChainID(ctx context.Context) (*big.Int, error) { + panic("not implemented") +} + +func TestUnitTestIsCacheable(t *testing.T) { + evmClient := NewMockEVMClient() + + for _, tc := range []struct { + desc string + req *decode.EVMRPCRequestEnvelope + cacheable bool + }{ + { + desc: "test case #1", + req: &decode.EVMRPCRequestEnvelope{ + JSONRPCVersion: "2.0", + ID: 1, + Method: "eth_getBalance", + Params: []interface{}{"0x1234", "42"}, + }, + cacheable: true, + }, + { + desc: "test case #2", + req: &decode.EVMRPCRequestEnvelope{ + JSONRPCVersion: "2.0", + ID: 1, + Method: "eth_getBalance", + Params: []interface{}{"0x1234", "0"}, + }, + cacheable: false, + }, + } { + t.Run(tc.desc, func(t *testing.T) { + cacheable := IsCacheable(context.Background(), evmClient, tc.req) + require.Equal(t, tc.cacheable, cacheable) + }) + } +} diff --git a/service/cachemdw/middleware.go b/service/cachemdw/middleware.go index b04de38..e0258f6 100644 --- a/service/cachemdw/middleware.go +++ b/service/cachemdw/middleware.go @@ -38,7 +38,7 @@ func (c *ServiceCache) Middleware( return } - cacheable := c.IsCacheable(r.Context(), decodedReq) + cacheable := IsCacheable(r.Context(), c.evmClient, decodedReq) if !cacheable { next.ServeHTTP(w, r.WithContext(uncachedContext)) return