diff --git a/chains/substrate/connection/connection.go b/chains/substrate/connection/connection.go index 48f59147..da6a4364 100644 --- a/chains/substrate/connection/connection.go +++ b/chains/substrate/connection/connection.go @@ -4,13 +4,17 @@ package connection import ( + "bytes" "math/big" "sync" + "time" "github.com/centrifuge/go-substrate-rpc-client/v4/client" + "github.com/centrifuge/go-substrate-rpc-client/v4/registry" "github.com/centrifuge/go-substrate-rpc-client/v4/registry/parser" "github.com/centrifuge/go-substrate-rpc-client/v4/registry/retriever" "github.com/centrifuge/go-substrate-rpc-client/v4/registry/state" + "github.com/vedhavyas/go-subkey/scale" "github.com/centrifuge/go-substrate-rpc-client/v4/rpc" "github.com/centrifuge/go-substrate-rpc-client/v4/rpc/chain" @@ -85,9 +89,48 @@ func (c *Connection) GetBlockEvents(hash types.Hash) ([]*parser.Event, error) { if err != nil { return nil, err } + + timestamp, err := c.GetBlockTimestamp(hash) + if err != nil { + return nil, err + } + + for _, e := range evts { + e.Fields = append(e.Fields, ®istry.DecodedField{ + Value: timestamp, + Name: "block_timestamp", + }) + } return evts, nil } +func (c *Connection) GetBlockTimestamp(hash types.Hash) (time.Time, error) { + callIndex, err := c.meta.FindCallIndex("Timestamp.set") + if err != nil { + return time.Now(), err + } + + block, err := c.GetBlock(hash) + if err != nil { + return time.Now(), err + } + + timestamp := new(big.Int) + for _, extrinsic := range block.Block.Extrinsics { + if extrinsic.Method.CallIndex != callIndex { + continue + } + timeDecoder := scale.NewDecoder(bytes.NewReader(extrinsic.Method.Args)) + timestamp, err = timeDecoder.DecodeUintCompact() + if err != nil { + return time.Now(), err + } + break + } + msec := timestamp.Int64() + return time.Unix(msec/1e3, (msec%1e3)*1e6), nil +} + func (c *Connection) FetchEvents(startBlock, endBlock *big.Int) ([]*parser.Event, error) { evts := make([]*parser.Event, 0) for i := new(big.Int).Set(startBlock); i.Cmp(endBlock) <= 0; i.Add(i, big.NewInt(1)) { diff --git a/go.mod b/go.mod index 5fab6f7f..f9080a86 100644 --- a/go.mod +++ b/go.mod @@ -10,6 +10,7 @@ require ( github.com/rs/zerolog v1.25.0 github.com/stretchr/testify v1.8.3 github.com/syndtr/goleveldb v1.0.1-0.20220614013038-64ee5596c38a + github.com/vedhavyas/go-subkey v1.0.4 go.opentelemetry.io/otel v1.16.0 go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v0.39.0 go.opentelemetry.io/otel/metric v1.16.0 @@ -45,7 +46,6 @@ require ( github.com/rs/cors v1.8.2 // indirect github.com/stretchr/objx v0.5.0 // indirect github.com/supranational/blst v0.3.11 // indirect - github.com/vedhavyas/go-subkey v1.0.4 // indirect go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.16.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlpmetric v0.39.0 // indirect golang.org/x/crypto v0.12.0 // indirect