github.com/0xPolygon/supernets2-node@v0.0.0-20230711153321-2fe574524eaa/jsonrpc/client/client.go (about) 1 package client 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io" 8 "net/http" 9 10 "github.com/0xPolygon/supernets2-node/jsonrpc/types" 11 ) 12 13 // Client defines typed wrappers for the zkEVM RPC API. 14 type Client struct { 15 url string 16 } 17 18 // NewClient creates an instance of client 19 func NewClient(url string) *Client { 20 return &Client{ 21 url: url, 22 } 23 } 24 25 // JSONRPCCall executes a 2.0 JSON RPC HTTP Post Request to the provided URL with 26 // the provided method and parameters, which is compatible with the Ethereum 27 // JSON RPC Server. 28 func JSONRPCCall(url, method string, parameters ...interface{}) (types.Response, error) { 29 const jsonRPCVersion = "2.0" 30 31 params, err := json.Marshal(parameters) 32 if err != nil { 33 return types.Response{}, err 34 } 35 36 req := types.Request{ 37 JSONRPC: jsonRPCVersion, 38 ID: float64(1), 39 Method: method, 40 Params: params, 41 } 42 43 reqBody, err := json.Marshal(req) 44 if err != nil { 45 return types.Response{}, err 46 } 47 48 reqBodyReader := bytes.NewReader(reqBody) 49 httpReq, err := http.NewRequest(http.MethodPost, url, reqBodyReader) 50 if err != nil { 51 return types.Response{}, err 52 } 53 54 httpReq.Header.Add("Content-type", "application/json") 55 56 httpRes, err := http.DefaultClient.Do(httpReq) 57 if err != nil { 58 return types.Response{}, err 59 } 60 61 if httpRes.StatusCode != http.StatusOK { 62 return types.Response{}, fmt.Errorf("Invalid status code, expected: %v, found: %v", http.StatusOK, httpRes.StatusCode) 63 } 64 65 resBody, err := io.ReadAll(httpRes.Body) 66 if err != nil { 67 return types.Response{}, err 68 } 69 defer httpRes.Body.Close() 70 71 var res types.Response 72 err = json.Unmarshal(resBody, &res) 73 if err != nil { 74 return types.Response{}, err 75 } 76 77 return res, nil 78 }