diff --git a/fees/dimension.go b/fees/dimension.go index 3a408b7388..8e85f26e1a 100644 --- a/fees/dimension.go +++ b/fees/dimension.go @@ -5,6 +5,7 @@ package fees import ( "encoding/binary" + "encoding/json" "errors" "fmt" "strconv" @@ -140,6 +141,38 @@ func (d *Dimensions) UnmarshalText(b []byte) error { return nil } +type DimensionJSON struct { + Bandwidth uint64 `json:"bandwidth"` + Compute uint64 `json:"compute"` + StorageRead uint64 `json:"storageRead"` + StorageAllocate uint64 `json:"storageAllocate"` + StorageWrite uint64 `json:"storageWrite"` +} + +func (d Dimensions) MarshalJSON() ([]byte, error) { + dimensionJSON := DimensionJSON{ + Bandwidth: d[Bandwidth], + Compute: d[Compute], + StorageRead: d[StorageRead], + StorageAllocate: d[StorageAllocate], + StorageWrite: d[StorageWrite], + } + return json.Marshal(dimensionJSON) +} + +func (d *Dimensions) UnmarshalJSON(b []byte) error { + dimensionJSON := DimensionJSON{} + if err := json.Unmarshal(b, &dimensionJSON); err != nil { + return err + } + d[Bandwidth] = dimensionJSON.Bandwidth + d[Compute] = dimensionJSON.Compute + d[StorageRead] = dimensionJSON.StorageRead + d[StorageAllocate] = dimensionJSON.StorageAllocate + d[StorageWrite] = dimensionJSON.StorageWrite + return nil +} + func UnpackDimensions(raw []byte) (Dimensions, error) { if len(raw) != DimensionsLen { return Dimensions{}, fmt.Errorf("%w: found=%d wanted=%d", ErrWrongDimensionSize, len(raw), DimensionsLen) diff --git a/fees/dimension_test.go b/fees/dimension_test.go index 566a753cf6..92c77f0b73 100644 --- a/fees/dimension_test.go +++ b/fees/dimension_test.go @@ -25,3 +25,21 @@ func TestDimensionsMarshalText(t *testing.T) { require.NoError(parsedDimText.UnmarshalText(dimTextBytes)) require.Equal(dim, parsedDimText) } + +func TestDimensionsMarshalJSON(t *testing.T) { + require := require.New(t) + var dim Dimensions + dim[Bandwidth] = 1 + dim[Compute] = 2 + dim[StorageRead] = 3 + dim[StorageAllocate] = 4 + dim[StorageWrite] = 5 + + dimJSONBytes, err := dim.MarshalJSON() + require.NoError(err) + require.JSONEq(`{"bandwidth":1,"compute":2,"storageRead":3,"storageAllocate":4,"storageWrite":5}`, string(dimJSONBytes)) + + var parsedDimJSON Dimensions + require.NoError(parsedDimJSON.UnmarshalJSON(dimJSONBytes)) + require.Equal(dim, parsedDimJSON) +}