From 2397d931d521679ba2ab3627eb626638ad1bcac6 Mon Sep 17 00:00:00 2001 From: thanhpp Date: Thu, 11 Jul 2024 17:00:51 +0700 Subject: [PATCH] =?UTF-8?q?refactor:=20=E2=99=BB=EF=B8=8F=20mev:=20handle?= =?UTF-8?q?=20nil=20result?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: thanhpp --- pkg/mev/pkg.go | 18 ++++++++++++++++++ pkg/mev/pkg_test.go | 23 +++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 pkg/mev/pkg_test.go diff --git a/pkg/mev/pkg.go b/pkg/mev/pkg.go index b2a4ebd..16c4865 100644 --- a/pkg/mev/pkg.go +++ b/pkg/mev/pkg.go @@ -205,6 +205,24 @@ type SendBundleResult struct { Message string `json:"message,omitempty"` } +func (r *SendBundleResult) UnmarshalJSON(b []byte) error { + if str := string(b); (str == "\"nil\"" || str == "\"null\"") && r != nil { + *r = SendBundleResult{} + return nil + } + + // Otherwise, unmarshal the data as usual + // disable this UnmarshalJSON function + type Alias SendBundleResult + alias := &struct { + *Alias + }{ + Alias: (*Alias)(r), + } + + return json.Unmarshal(b, &alias) +} + type SendBundleResults struct { GasUsed int `json:"gasUsed,omitempty"` TxHash string `json:"txHash,omitempty"` diff --git a/pkg/mev/pkg_test.go b/pkg/mev/pkg_test.go new file mode 100644 index 0000000..ceaf9c9 --- /dev/null +++ b/pkg/mev/pkg_test.go @@ -0,0 +1,23 @@ +package mev_test + +import ( + "encoding/json" + "testing" + + "github.com/KyberNetwork/tradinglib/pkg/mev" + "github.com/test-go/testify/require" +) + +func TestUnmarshalSendBundleResponse1(t *testing.T) { + raws := []string{ + "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"nil\"}", + "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{}}", + "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"bundleHash\": \"0x0\"}}", + } + + for _, raw := range raws { + var resp mev.SendBundleResponse + require.NoError(t, json.Unmarshal([]byte(raw), &resp)) + t.Logf("%+v\n", resp) + } +}