github.com/nspcc-dev/neo-go@v0.105.2-0.20240517133400-6be757af3eba/pkg/neorpc/result/tx_raw_output.go (about)

     1  package result
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  
     7  	"github.com/nspcc-dev/neo-go/pkg/core/transaction"
     8  	"github.com/nspcc-dev/neo-go/pkg/util"
     9  )
    10  
    11  // TransactionOutputRaw is used as a wrapper to represents
    12  // a Transaction.
    13  type TransactionOutputRaw struct {
    14  	transaction.Transaction
    15  	TransactionMetadata
    16  }
    17  
    18  // TransactionMetadata is an auxiliary struct for proper TransactionOutputRaw marshaling.
    19  type TransactionMetadata struct {
    20  	Blockhash     util.Uint256 `json:"blockhash,omitempty"`
    21  	Confirmations int          `json:"confirmations,omitempty"`
    22  	Timestamp     uint64       `json:"blocktime,omitempty"`
    23  	VMState       string       `json:"vmstate,omitempty"`
    24  }
    25  
    26  // MarshalJSON implements the json.Marshaler interface.
    27  func (t TransactionOutputRaw) MarshalJSON() ([]byte, error) {
    28  	output, err := json.Marshal(t.TransactionMetadata)
    29  	if err != nil {
    30  		return nil, err
    31  	}
    32  	txBytes, err := json.Marshal(&t.Transaction)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  
    37  	// We have to keep both transaction.Transaction and tranactionOutputRaw at the same level in json
    38  	// in order to match C# API, so there's no way to marshall Tx correctly with standard json.Marshaller tool.
    39  	if output[len(output)-1] != '}' || txBytes[0] != '{' {
    40  		return nil, errors.New("can't merge internal jsons")
    41  	}
    42  	output[len(output)-1] = ','
    43  	output = append(output, txBytes[1:]...)
    44  	return output, nil
    45  }
    46  
    47  // UnmarshalJSON implements the json.Marshaler interface.
    48  func (t *TransactionOutputRaw) UnmarshalJSON(data []byte) error {
    49  	// As transaction.Transaction and tranactionOutputRaw are at the same level in json,
    50  	// do unmarshalling separately for both structs.
    51  	output := new(TransactionMetadata)
    52  	err := json.Unmarshal(data, output)
    53  	if err != nil {
    54  		return err
    55  	}
    56  	t.TransactionMetadata = *output
    57  	return json.Unmarshal(data, &t.Transaction)
    58  }