Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EVM-437 Batch calls over websockets not working properly #1588

Merged
merged 4 commits into from
Jun 7, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 // ,
igorcrevar marked this conversation as resolved.
Show resolved Hide resolved
)

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

// batch output should look like:
// [ { "requestId": "1", "status": 200 }, { "requestId": "2", "status": 200 } ]
buf.WriteByte(openSquareBracket) // [
buf.Write(bytes.Join(responses, []byte{comma})) // join responses with the comma separator
buf.WriteByte(closeSquareBracket) // ]

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