forked from centrifuge/go-substrate-rpc-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event_record.go
346 lines (305 loc) · 15.9 KB
/
event_record.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
// Go Substrate RPC Client (GSRPC) provides APIs and types around Polkadot and any Substrate-based chain RPC calls
//
// Copyright 2019 Centrifuge GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"bytes"
"errors"
"fmt"
"io"
"reflect"
"github.com/centrifuge/go-substrate-rpc-client/scale"
"github.com/ethereum/go-ethereum/log"
)
// EventRecordsRaw is a raw record for a set of events, represented as the raw bytes. It exists since
// decoding of events can only be done with metadata, so events can't follow the static way of decoding
// other types do. It exposes functions to decode events using metadata and targets.
// Be careful using this in your own structs – it only works as the last value in a struct since it will consume the
// remainder of the encoded data. The reason for this is that it does not contain any length encoding, so it would
// not know where to stop.
type EventRecordsRaw []byte
// Encode implements encoding for Data, which just unwraps the bytes of Data
func (e EventRecordsRaw) Encode(encoder scale.Encoder) error {
return encoder.Write(e)
}
// Decode implements decoding for Data, which just reads all the remaining bytes into Data
func (e *EventRecordsRaw) Decode(decoder scale.Decoder) error {
for i := 0; true; i++ {
b, err := decoder.ReadOneByte()
if err == io.EOF {
break
}
if err != nil {
return err
}
*e = append((*e)[:i], b)
}
return nil
}
// EventRecords is a default set of possible event records that can be used as a target for
// `func (e EventRecordsRaw) Decode(...`
type EventRecords struct {
Balances_Endowed []EventBalancesEndowed //nolint:stylecheck,golint
Balances_DustLost []EventBalancesDustLost //nolint:stylecheck,golint
Balances_Transfer []EventBalancesTransfer //nolint:stylecheck,golint
Balances_BalanceSet []EventBalancesBalanceSet //nolint:stylecheck,golint
Balances_Deposit []EventBalancesDeposit //nolint:stylecheck,golint
Grandpa_NewAuthorities []EventGrandpaNewAuthorities //nolint:stylecheck,golint
Grandpa_Paused []EventGrandpaPaused //nolint:stylecheck,golint
Grandpa_Resumed []EventGrandpaResumed //nolint:stylecheck,golint
ImOnline_HeartbeatReceived []EventImOnlineHeartbeatReceived //nolint:stylecheck,golint
ImOnline_AllGood []EventImOnlineAllGood //nolint:stylecheck,golint
ImOnline_SomeOffline []EventImOnlineSomeOffline //nolint:stylecheck,golint
Indices_IndexAssigned []EventIndicesIndexAssigned //nolint:stylecheck,golint
Indices_IndexFreed []EventIndicesIndexFreed //nolint:stylecheck,golint
Offences_Offence []EventOffencesOffence //nolint:stylecheck,golint
Session_NewSession []EventSessionNewSession //nolint:stylecheck,golint
Staking_Reward []EventStakingReward //nolint:stylecheck,golint
Staking_Slash []EventStakingSlash //nolint:stylecheck,golint
Staking_OldSlashingReportDiscarded []EventStakingOldSlashingReportDiscarded //nolint:stylecheck,golint
System_ExtrinsicSuccess []EventSystemExtrinsicSuccess //nolint:stylecheck,golint
System_ExtrinsicFailed []EventSystemExtrinsicFailed //nolint:stylecheck,golint
System_CodeUpdated []EventSystemCodeUpdated //nolint:stylecheck,golint
System_NewAccount []EventSystemNewAccount //nolint:stylecheck,golint
System_KilledAccount []EventSystemKilledAccount //nolint:stylecheck,golint
Assets_Issued []EventAssetIssued //nolint:stylecheck,golint
Assets_Transferred []EventAssetTransferred //nolint:stylecheck,golint
Assets_Destroyed []EventAssetDestroyed //nolint:stylecheck,golint
Democracy_Proposed []EventDemocracyProposed //nolint:stylecheck,golint
Democracy_Tabled []EventDemocracyTabled //nolint:stylecheck,golint
Democracy_ExternalTabled []EventDemocracyExternalTabled //nolint:stylecheck,golint
Democracy_Started []EventDemocracyStarted //nolint:stylecheck,golint
Democracy_Passed []EventDemocracyPassed //nolint:stylecheck,golint
Democracy_NotPassed []EventDemocracyNotPassed //nolint:stylecheck,golint
Democracy_Cancelled []EventDemocracyCancelled //nolint:stylecheck,golint
Democracy_Executed []EventDemocracyExecuted //nolint:stylecheck,golint
Democracy_Delegated []EventDemocracyDelegated //nolint:stylecheck,golint
Democracy_Undelegated []EventDemocracyUndelegated //nolint:stylecheck,golint
Democracy_Vetoed []EventDemocracyVetoed //nolint:stylecheck,golint
Democracy_PreimageNoted []EventDemocracyPreimageNoted //nolint:stylecheck,golint
Democracy_PreimageUsed []EventDemocracyPreimageUsed //nolint:stylecheck,golint
Democracy_PreimageInvalid []EventDemocracyPreimageInvalid //nolint:stylecheck,golint
Democracy_PreimageMissing []EventDemocracyPreimageMissing //nolint:stylecheck,golint
Democracy_PreimageReaped []EventDemocracyPreimageReaped //nolint:stylecheck,golint
Democracy_Unlocked []EventDemocracyUnlocked //nolint:stylecheck,golint
Elections_NewTerm []EventElectionsNewTerm //nolint:stylecheck,golint
Elections_EmptyTerm []EventElectionsEmptyTerm //nolint:stylecheck,golint
Elections_MemberKicked []EventElectionsMemberKicked //nolint:stylecheck,golint
Elections_MemberRenounced []EventElectionsMemberRenounced //nolint:stylecheck,golint
Elections_VoterReported []EventElectionsVoterReported //nolint:stylecheck,golint
Identity_IdentitySet []EventIdentitySet //nolint:stylecheck,golint
Identity_IdentityCleared []EventIdentityCleared //nolint:stylecheck,golint
Identity_IdentityKilled []EventIdentityKilled //nolint:stylecheck,golint
Identity_JudgementRequested []EventIdentityJudgementRequested //nolint:stylecheck,golint
Identity_JudgementUnrequested []EventIdentityJudgementUnrequested //nolint:stylecheck,golint
Identity_JudgementGiven []EventIdentityJudgementGiven //nolint:stylecheck,golint
Identity_RegistrarAdded []EventIdentityRegistrarAdded //nolint:stylecheck,golint
Recovery_RecoveryCreated []EventRecoveryCreated //nolint:stylecheck,golint
Recovery_RecoveryInitiated []EventRecoveryInitiated //nolint:stylecheck,golint
Recovery_RecoveryVouched []EventRecoveryVouched //nolint:stylecheck,golint
Recovery_RecoveryClosed []EventRecoveryClosed //nolint:stylecheck,golint
Recovery_AccountRecovered []EventRecoveryAccountRecovered //nolint:stylecheck,golint
Recovery_RecoveryRemoved []EventRecoveryRemoved //nolint:stylecheck,golint
Sudo_Sudid []EventSudoSudid //nolint:stylecheck,golint
Sudo_KeyChanged []EventSudoKeyChanged //nolint:stylecheck,golint
Sudo_SudoAsDone []EventSudoAsDone //nolint:stylecheck,golint
Treasury_Proposed []EventTreasuryProposed //nolint:stylecheck,golint
Treasury_Spending []EventTreasurySpending //nolint:stylecheck,golint
Treasury_Awarded []EventTreasuryAwarded //nolint:stylecheck,golint
Treasury_Rejected []EventTreasuryRejected //nolint:stylecheck,golint
Treasury_Burnt []EventTreasuryBurnt //nolint:stylecheck,golint
Treasury_Rollover []EventTreasuryRollover //nolint:stylecheck,golint
Treasury_Deposit []EventTreasuryDeposit //nolint:stylecheck,golint
Treasury_NewTip []EventTreasuryNewTip //nolint:stylecheck,golint
Treasury_TipClosing []EventTreasuryTipClosing //nolint:stylecheck,golint
Treasury_TipClosed []EventTreasuryTipClosed //nolint:stylecheck,golint
Treasury_TipRetracted []EventTreasuryTipRetracted //nolint:stylecheck,golint
Utility_BatchInterrupted []EventUtilityBatchInterrupted //nolint:stylecheck,golint
Utility_BatchCompleted []EventUtilityBatchCompleted //nolint:stylecheck,golint
Utility_NewMultisig []EventUtilityNewMultisig //nolint:stylecheck,golint
Utility_MultisigApproval []EventUtilityMultisigApproval //nolint:stylecheck,golint
Utility_MultisigExecuted []EventUtilityMultisigExecuted //nolint:stylecheck,golint
Utility_MultisigCancelled []EventUtilityMultisigCancelled //nolint:stylecheck,golint
}
// DecodeEventRecords decodes the events records from an EventRecordRaw into a target t using the given Metadata m
// If this method returns an error like `unable to decode Phase for event #x: EOF`, it is likely that you have defined
// a custom event record with a wrong type. For example your custom event record has a field with a length prefixed
// type, such as types.Bytes, where your event in reallity contains a fixed width type, such as a types.U32.
func (e EventRecordsRaw) DecodeEventRecords(m *Metadata, t interface{}) error {
log.Debug(fmt.Sprintf("will decode event records from raw hex: %#x", e))
// ensure t is a pointer
ttyp := reflect.TypeOf(t)
if ttyp.Kind() != reflect.Ptr {
return errors.New("target must be a pointer, but is " + fmt.Sprint(ttyp))
}
// ensure t is not a nil pointer
tval := reflect.ValueOf(t)
if tval.IsNil() {
return errors.New("target is a nil pointer")
}
val := tval.Elem()
typ := val.Type()
// ensure val can be set
if !val.CanSet() {
return fmt.Errorf("unsettable value %v", typ)
}
// ensure val points to a struct
if val.Kind() != reflect.Struct {
return fmt.Errorf("target must point to a struct, but is " + fmt.Sprint(typ))
}
decoder := scale.NewDecoder(bytes.NewReader(e))
// determine number of events
n, err := decoder.DecodeUintCompact()
if err != nil {
return err
}
log.Debug(fmt.Sprintf("found %v events", n))
// iterate over events
for i := uint64(0); i < n.Uint64(); i++ {
log.Debug(fmt.Sprintf("decoding event #%v", i))
// decode Phase
phase := Phase{}
err := decoder.Decode(&phase)
if err != nil {
return fmt.Errorf("unable to decode Phase for event #%v: %v", i, err)
}
// decode EventID
id := EventID{}
err = decoder.Decode(&id)
if err != nil {
return fmt.Errorf("unable to decode EventID for event #%v: %v", i, err)
}
log.Debug(fmt.Sprintf("event #%v has EventID %v", i, id))
// ask metadata for method & event name for event
moduleName, eventName, err := m.FindEventNamesForEventID(id)
// moduleName, eventName, err := "System", "ExtrinsicSuccess", nil
if err != nil {
return fmt.Errorf("unable to find event with EventID %v in metadata for event #%v: %s", id, i, err)
}
log.Debug(fmt.Sprintf("event #%v is in module %v with event name %v", i, moduleName, eventName))
// check whether name for eventID exists in t
field := val.FieldByName(fmt.Sprintf("%v_%v", moduleName, eventName))
if !field.IsValid() {
return fmt.Errorf("unable to find field %v_%v for event #%v with EventID %v", moduleName, eventName, i, id)
}
// create a pointer to with the correct type that will hold the decoded event
holder := reflect.New(field.Type().Elem())
// ensure first field is for Phase, last field is for Topics
numFields := holder.Elem().NumField()
if numFields < 2 {
return fmt.Errorf("expected event #%v with EventID %v, field %v_%v to have at least 2 fields "+
"(for Phase and Topics), but has %v fields", i, id, moduleName, eventName, numFields)
}
phaseField := holder.Elem().FieldByIndex([]int{0})
if phaseField.Type() != reflect.TypeOf(phase) {
return fmt.Errorf("expected the first field of event #%v with EventID %v, field %v_%v to be of type "+
"types.Phase, but got %v", i, id, moduleName, eventName, phaseField.Type())
}
topicsField := holder.Elem().FieldByIndex([]int{numFields - 1})
if topicsField.Type() != reflect.TypeOf([]Hash{}) {
return fmt.Errorf("expected the last field of event #%v with EventID %v, field %v_%v to be of type "+
"[]types.Hash for Topics, but got %v", i, id, moduleName, eventName, topicsField.Type())
}
// set the phase we decoded earlier
phaseField.Set(reflect.ValueOf(phase))
// set the remaining fields
for j := 1; j < numFields; j++ {
err = decoder.Decode(holder.Elem().FieldByIndex([]int{j}).Addr().Interface())
if err != nil {
return fmt.Errorf("unable to decode field %v event #%v with EventID %v, field %v_%v: %v", j, i, id, moduleName,
eventName, err)
}
}
// add the decoded event to the slice
field.Set(reflect.Append(field, holder.Elem()))
log.Debug(fmt.Sprintf("decoded event #%v", i))
}
return nil
}
// Phase is an enum describing the current phase of the event (applying the extrinsic or finalized)
type Phase struct {
IsApplyExtrinsic bool
AsApplyExtrinsic uint32
IsFinalization bool
}
func (p *Phase) Decode(decoder scale.Decoder) error {
b, err := decoder.ReadOneByte()
if err != nil {
return err
}
if b == 0 {
p.IsApplyExtrinsic = true
err = decoder.Decode(&p.AsApplyExtrinsic)
} else if b == 1 {
p.IsFinalization = true
}
if err != nil {
return err
}
return nil
}
func (p Phase) Encode(encoder scale.Encoder) error {
var err1, err2 error
if p.IsApplyExtrinsic {
err1 = encoder.PushByte(0)
err2 = encoder.Encode(p.AsApplyExtrinsic)
} else if p.IsFinalization {
err1 = encoder.PushByte(1)
}
if err1 != nil {
return err1
}
if err2 != nil {
return err2
}
return nil
}
// DispatchError is an error occurring during extrinsic dispatch
type DispatchError struct {
HasModule bool
Module uint8
Error uint8
}
func (d *DispatchError) Decode(decoder scale.Decoder) error {
b, err := decoder.ReadOneByte()
if err != nil {
return err
}
if b == 1 {
d.HasModule = true
err = decoder.Decode(&d.Module)
}
if err != nil {
return err
}
return decoder.Decode(&d.Error)
}
func (d DispatchError) Encode(encoder scale.Encoder) error {
var err error
if d.HasModule {
err = encoder.PushByte(1)
if err != nil {
return err
}
err = encoder.Encode(d.Module)
} else {
err = encoder.PushByte(0)
}
if err != nil {
return err
}
return encoder.Encode(&d.Error)
}
type EventID [2]byte