From a7453ace94fccb65a5547317a99ba5f7ba84f5c0 Mon Sep 17 00:00:00 2001 From: GoudanWoo <155265132+GoudanWoo@users.noreply.github.com> Date: Sat, 23 Mar 2024 07:49:00 +0800 Subject: [PATCH] fix: Add `ShortID` option for some WebSocket RPC which not support int63/uint64 ID --- rpc/ws/client.go | 9 +++++++-- rpc/ws/types.go | 11 +++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/rpc/ws/client.go b/rpc/ws/client.go index 261b4532..871da06b 100644 --- a/rpc/ws/client.go +++ b/rpc/ws/client.go @@ -43,6 +43,7 @@ type Client struct { subscriptionByRequestID map[uint64]*Subscription subscriptionByWSSubID map[uint64]*Subscription reconnectOnErr bool + shortID bool } const ( @@ -76,6 +77,10 @@ func ConnectWithOptions(ctx context.Context, rpcEndpoint string, opt *Options) ( EnableCompression: true, } + if opt != nil && opt.ShortID { + c.shortID = opt.ShortID + } + if opt != nil && opt.HandshakeTimeout > 0 { dialer.HandshakeTimeout = opt.HandshakeTimeout } @@ -285,7 +290,7 @@ func (c *Client) closeSubscription(reqID uint64, err error) { } func (c *Client) unsubscribe(subID uint64, method string) error { - req := newRequest([]interface{}{subID}, method, nil) + req := newRequest([]interface{}{subID}, method, nil, c.shortID) data, err := req.encode() if err != nil { return fmt.Errorf("unable to encode unsubscription message for subID %d and method %s", subID, method) @@ -309,7 +314,7 @@ func (c *Client) subscribe( c.lock.Lock() defer c.lock.Unlock() - req := newRequest(params, subscriptionMethod, conf) + req := newRequest(params, subscriptionMethod, conf, c.shortID) data, err := req.encode() if err != nil { return nil, fmt.Errorf("subscribe: unable to encode subsciption request: %w", err) diff --git a/rpc/ws/types.go b/rpc/ws/types.go index fbed960e..26f94243 100644 --- a/rpc/ws/types.go +++ b/rpc/ws/types.go @@ -32,15 +32,21 @@ type request struct { ID uint64 `json:"id"` } -func newRequest(params []interface{}, method string, configuration map[string]interface{}) *request { +func newRequest(params []interface{}, method string, configuration map[string]interface{}, shortID bool) *request { if params != nil && configuration != nil { params = append(params, configuration) } + var ID uint64 + if !shortID { + ID = uint64(rand.Int63()) + } else { + ID = uint64(rand.Int31()) + } return &request{ Version: "2.0", Method: method, Params: params, - ID: uint64(rand.Int63()), + ID: ID, } } @@ -66,6 +72,7 @@ type params struct { type Options struct { HttpHeader http.Header HandshakeTimeout time.Duration + ShortID bool // some RPC do not support int63/uint64 id, so need to enable it to rand a int31/uint32 id } var DefaultHandshakeTimeout = 45 * time.Second