Skip to content

Commit

Permalink
EVM-437 Batch calls over websockets not working properly
Browse files Browse the repository at this point in the history
  • Loading branch information
igorcrevar committed Jun 6, 2023
1 parent 2c2c45d commit 95eab42
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
2 changes: 2 additions & 0 deletions jsonrpc/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ type Request struct {
Params json.RawMessage `json:"params,omitempty"`
}

type BatchRequest []Request

// Response is a jsonrpc response interface
type Response interface {
GetID() interface{}
Expand Down
34 changes: 34 additions & 0 deletions jsonrpc/dispatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,11 +231,45 @@ func (d *Dispatcher) RemoveFilterByWs(conn wsConn) {
}

func (d *Dispatcher) HandleWs(reqBody []byte, conn wsConn) ([]byte, error) {
// first try to unmarshal to batch request
// if there is an error try to unmarshal to single request
var batchReq BatchRequest
if err := json.Unmarshal(reqBody, &batchReq); err == nil {
const (
openSquareBracket = 91 // [
closeSquareBracket = 93 // ]
comma = 44 // ,
)

responses := make([][]byte, len(batchReq))

for i, req := range batchReq {
responses[i], err = d.handleWs(req, conn)
if err != nil {
return nil, err
}
}

var buf bytes.Buffer

buf.WriteByte(openSquareBracket) // Write the start byte
buf.Write(bytes.Join(responses, []byte{comma})) // Write the original byte slice
buf.WriteByte(closeSquareBracket) // Write the end byte

// batch output should look like
// [ { "requestId": "1", "status": 200 }, { "requestId": "2", "status": 200 } ]
return buf.Bytes(), nil
}

var req Request
if err := json.Unmarshal(reqBody, &req); err != nil {
return NewRPCResponse(req.ID, "2.0", nil, NewInvalidRequestError("Invalid json request")).Bytes()
}

return d.handleWs(req, conn)
}

func (d *Dispatcher) handleWs(req Request, conn wsConn) ([]byte, error) {
// if the request method is eth_subscribe we need to create a
// new filter with ws connection
if req.Method == "eth_subscribe" {
Expand Down

0 comments on commit 95eab42

Please sign in to comment.