github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/gnovm/stdlibs/std/emit_event.go (about)

     1  package std
     2  
     3  // ref: https://github.com/gnolang/gno/pull/575
     4  // ref: https://github.com/gnolang/gno/pull/1833
     5  
     6  import (
     7  	"errors"
     8  
     9  	gno "github.com/gnolang/gno/gnovm/pkg/gnolang"
    10  )
    11  
    12  var errInvalidGnoEventAttrs = errors.New("cannot pair attributes due to odd count")
    13  
    14  func X_emit(m *gno.Machine, typ string, attrs []string) {
    15  	eventAttrs, err := attrKeysAndValues(attrs)
    16  	if err != nil {
    17  		m.Panic(typedString(err.Error()))
    18  	}
    19  
    20  	pkgPath := CurrentRealmPath(m)
    21  	fnIdent := getPrevFunctionNameFromTarget(m, "Emit")
    22  
    23  	evt := gnoEvent{
    24  		Type:       typ,
    25  		PkgPath:    pkgPath,
    26  		Func:       fnIdent,
    27  		Attributes: eventAttrs,
    28  	}
    29  	ctx := m.Context.(ExecContext)
    30  	ctx.EventLogger.EmitEvent(evt)
    31  }
    32  
    33  func attrKeysAndValues(attrs []string) ([]gnoEventAttribute, error) {
    34  	attrLen := len(attrs)
    35  	if attrLen%2 != 0 {
    36  		return nil, errInvalidGnoEventAttrs
    37  	}
    38  	eventAttrs := make([]gnoEventAttribute, attrLen/2)
    39  	for i := 0; i < attrLen-1; i += 2 {
    40  		eventAttrs[i/2] = gnoEventAttribute{
    41  			Key:   attrs[i],
    42  			Value: attrs[i+1],
    43  		}
    44  	}
    45  	return eventAttrs, nil
    46  }
    47  
    48  type gnoEvent struct {
    49  	Type       string              `json:"type"`
    50  	PkgPath    string              `json:"pkg_path"`
    51  	Func       string              `json:"func"`
    52  	Attributes []gnoEventAttribute `json:"attrs"`
    53  }
    54  
    55  func (e gnoEvent) AssertABCIEvent() {}
    56  
    57  type gnoEventAttribute struct {
    58  	Key   string `json:"key"`
    59  	Value string `json:"value"`
    60  }