github.com/nspcc-dev/neo-go@v0.105.2-0.20240517133400-6be757af3eba/pkg/core/mempoolevent/event.go (about)

     1  package mempoolevent
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  
     7  	"github.com/nspcc-dev/neo-go/pkg/core/transaction"
     8  )
     9  
    10  // Type represents mempool event type.
    11  type Type byte
    12  
    13  const (
    14  	// TransactionAdded marks transaction addition mempool event.
    15  	TransactionAdded Type = 0x01
    16  	// TransactionRemoved marks transaction removal mempool event.
    17  	TransactionRemoved Type = 0x02
    18  )
    19  
    20  // Event represents one of mempool events: transaction was added or removed from the mempool.
    21  type Event struct {
    22  	Type Type
    23  	Tx   *transaction.Transaction
    24  	Data any
    25  }
    26  
    27  // String is a Stringer implementation.
    28  func (e Type) String() string {
    29  	switch e {
    30  	case TransactionAdded:
    31  		return "added"
    32  	case TransactionRemoved:
    33  		return "removed"
    34  	default:
    35  		return "unknown"
    36  	}
    37  }
    38  
    39  // GetEventTypeFromString converts the input string into the Type if it's possible.
    40  func GetEventTypeFromString(s string) (Type, error) {
    41  	switch s {
    42  	case "added":
    43  		return TransactionAdded, nil
    44  	case "removed":
    45  		return TransactionRemoved, nil
    46  	default:
    47  		return 0, errors.New("invalid event type name")
    48  	}
    49  }
    50  
    51  // MarshalJSON implements the json.Marshaler interface.
    52  func (e Type) MarshalJSON() ([]byte, error) {
    53  	return json.Marshal(e.String())
    54  }
    55  
    56  // UnmarshalJSON implements the json.Unmarshaler interface.
    57  func (e *Type) UnmarshalJSON(b []byte) error {
    58  	var s string
    59  
    60  	err := json.Unmarshal(b, &s)
    61  	if err != nil {
    62  		return err
    63  	}
    64  	id, err := GetEventTypeFromString(s)
    65  	if err != nil {
    66  		return err
    67  	}
    68  	*e = id
    69  	return nil
    70  }