Skip to content

Commit

Permalink
the graph dev
Browse files Browse the repository at this point in the history
  • Loading branch information
mohaijiang committed Jul 18, 2022
1 parent 680c7b3 commit 1aa5a4d
Show file tree
Hide file tree
Showing 6 changed files with 332 additions and 208 deletions.
95 changes: 12 additions & 83 deletions core/modules/chain/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,79 +24,8 @@ func NewChainClient(cm *config.ConfigManager, api *gsrpc.SubstrateAPI) (*ChainCl
}, nil
}

//func (cc *ChainClient) call(c types.Call, meta *types.Metadata) error {
//
// cf, err := cc.cm.GetConfig()
//
// // Create the extrinsic
// ext := types.NewExtrinsic(c)
// genesisHash, err := cc.api.RPC.Chain.GetBlockHash(0)
// if err != nil {
// return err
// }
//
// rv, err := cc.api.RPC.State.GetRuntimeVersionLatest()
// if err != nil {
// return err
// }
//
// keypair, err := signature.KeyringPairFromSecret(cf.SeedOrPhrase, 42)
// if err != nil {
// return err
// }
//
// // Get the nonce for Account
// key, err := types.CreateStorageKey(meta, "System", "Account", keypair.PublicKey)
// if err != nil {
// return err
// }
//
// var accountInfo types.AccountInfo
// ok, err := cc.api.RPC.State.GetStorageLatest(key, &accountInfo)
// if err != nil {
// return err
// }
// if !ok {
// return errors.New("GetStorageLatest fail")
// }
//
// nonce := uint32(accountInfo.Nonce)
// o := types.SignatureOptions{
// BlockHash: genesisHash,
// Era: types.ExtrinsicEra{IsMortalEra: false},
// GenesisHash: genesisHash,
// Nonce: types.NewUCompactFromUInt(uint64(nonce)),
// SpecVersion: rv.SpecVersion,
// Tip: types.NewUCompactFromUInt(0),
// TransactionVersion: rv.TransactionVersion,
// }
//
// // Sign the transaction using User's default account
// err = ext.Sign(keypair, o)
// if err != nil {
// return err
// }
//
// res, err := cc.api.RPC.Author.SubmitExtrinsic(ext)
// if err != nil {
// logrus.Errorf("extrinsic submit failed: %v", err)
// return err
// }
//
// hex, err := types.Hex(res)
// if err != nil {
// return err
// }
// if hex == "" {
// return errors.New("hex is empty")
// }
// return nil
//}

func (cc *ChainClient) callAndWatch(c types.Call, meta *types.Metadata, hook func(header *types.Header) error) error {

cf, err := cc.cm.GetConfig()

// Create the extrinsic
ext := types.NewExtrinsic(c)
genesisHash, err := cc.api.RPC.Chain.GetBlockHash(0)
Expand All @@ -109,6 +38,7 @@ func (cc *ChainClient) callAndWatch(c types.Call, meta *types.Metadata, hook fun
return err
}

cf, err := cc.cm.GetConfig()
keypair, err := signature.KeyringPairFromSecret(cf.SeedOrPhrase, 42)
if err != nil {
return err
Expand Down Expand Up @@ -231,10 +161,13 @@ func (cc *ChainClient) GetEvent(blockNumber uint64) (*MyEventRecords, error) {
// Decode the event records
events := MyEventRecords{}

//eventsRecordRow := types.EventRecordsRaw(*raw)
//err = DecodeEventRecordsWithIgnoreError(eventsRecordRow,meta,&events)
eventsRecordRow := types.EventRecordsRaw(*raw)

//err = DecodeEventRecordsWithInoreError(eventsRecordRow,meta,&events)
err = eventsRecordRow.DecodeEventRecords(meta, &events)

fmt.Println(err)

err = types.EventRecordsRaw(*raw).DecodeEventRecords(meta, &events)
return &events, err
}

Expand All @@ -249,6 +182,7 @@ func (cc *ChainClient) Register(localhostAddress string) error {
c, err := types.NewCall(meta, "Gateway.register_gateway_node", localhostAddress)

if err != nil {
fmt.Println(err)
return err
}

Expand All @@ -259,22 +193,17 @@ func (cc *ChainClient) Register(localhostAddress string) error {
// }
// if len(events.Gateway_RegisterGatewayNodeSuccess) > 0 {
// for _, e := range events.Gateway_RegisterGatewayNodeSuccess {
// for i := range e.PeerId {
// byte, _ := e.PeerId[i].MarshalJSON()
// fmt.Println(byte)
// }
// cf,_ := cc.cm.GetConfig()
// if utils.TypeU8ToStr(e.PeerId) == cf.PeerId {
// cf, _ := cc.cm.GetConfig()
// keypair, _ := signature.KeyringPairFromSecret(cf.SeedOrPhrase, 42)
// if keypair.Address == utils.AccountIdToAddress(e.AccountId) {
// return nil
// }
// fmt.Println(e)
// return nil
// }
// }
//
// return errors.New("cannot get Order Index")
//}

//
return cc.callAndWatch(c, meta, nil)
}

Expand Down
21 changes: 17 additions & 4 deletions core/modules/chain/chain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,27 @@ func TestResource(t *testing.T) {

func TestGetEventRecord(t *testing.T) {
cm := config.NewConfigManager()
cfg, _ := cm.GetConfig()
substrateApi, err := gsrpc.NewSubstrateAPI(cfg.ChainApi)
//cfg, _ := cm.GetConfig()
substrateApi, err := gsrpc.NewSubstrateAPI("ws://192.168.1.105:9944")
cc, err := NewChainClient(cm, substrateApi)
assert.NoError(t, err)

events, err := cc.GetEvent(4)
events, err := cc.GetEvent(202)

fmt.Println(err)

fmt.Println(events)
fmt.Println(len(events.Gateway_RegisterGatewayNodeSuccess))

assert.NoError(t, err)
}

func TestGetState(t *testing.T) {
cm := config.NewConfigManager()
//cfg, _ := cm.GetConfig()
substrateApi, err := gsrpc.NewSubstrateAPI("ws://127.0.0.1:9944")
cc, err := NewChainClient(cm, substrateApi)
assert.NoError(t, err)
marketUser, err := cc.GetMarketUser()
fmt.Println(marketUser)
assert.NoError(t, err)
}
159 changes: 53 additions & 106 deletions core/modules/chain/events.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
package chain

import (
"bytes"
"errors"
"fmt"
"github.com/centrifuge/go-substrate-rpc-client/v4/scale"
"github.com/centrifuge/go-substrate-rpc-client/v4/types"
"github.com/ethereum/go-ethereum/log"
"reflect"
)

type EventProviderRegisterResourceSuccess struct {
Expand Down Expand Up @@ -95,7 +91,6 @@ type EventRegisterGatewayNodeSuccess struct {
Phase types.Phase
AccountId types.AccountID
BlockNumber types.BlockNumber
PeerId []types.U8
Topics []types.Hash
}

Expand All @@ -110,117 +105,69 @@ type MyEventRecords struct {
ResourceOrder_FreeResourceProcessed []EventResourceOrderFreeResourceProcessed
ResourceOrder_FreeResourceApplied []EventResourceOrderFreeResourceApplied
ElectionProviderMultiPhase_SignedPhaseStarted []EventElectionProviderMultiPhase_SignedPhaseStarted
Market_Money []EventMarketMoney
Market_StakingSuccess []EventMarket_StakingSuccess
}

func DecodeEventRecordsWithIgnoreError(e types.EventRecordsRaw, m *types.Metadata, t interface{}) error {
fmt.Println(fmt.Sprintf("will decode event records from raw hex: %#x", e))
type EventMarket_StakingSuccess struct {
Phase types.Phase
AccountId types.AccountID
MarketUserStatus types.U8
BalanceOf types.U128
Topics []types.Hash
}

// 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))
type EventMarket_YES struct {
Phase types.Phase
Yes types.U8
Topics []types.Hash
}

type EventMarket_Money struct {
Phase types.Phase
BalanceOf types.U128
Topics []types.Hash
}

type MarketUserStatus struct {
IsProvider bool
IsGateway bool
IsClient bool
}

func (m *MarketUserStatus) Decode(decoder scale.Decoder) error {
b, err := decoder.ReadOneByte()
fmt.Println(b)

if err != nil {
return err
}

decoder := scale.NewDecoder(bytes.NewReader(e))
if b == 0 {
m.IsProvider = true
} else if b == 1 {
m.IsGateway = true
} else if b == 2 {
m.IsClient = true
}

// determine number of events
n, err := decoder.DecodeUintCompact()
if err != nil {
return err
}

fmt.Println(fmt.Sprintf("found %v events", n))

// iterate over events
for i := uint64(0); i < n.Uint64(); i++ {
fmt.Println(fmt.Sprintf("decoding event #%v", i))

// decode Phase
phase := types.Phase{}
err := decoder.Decode(&phase)
if err != nil {
return fmt.Errorf("unable to decode Phase for event #%v: %v", i, err)
}

// decode EventID
id := types.EventID{}
err = decoder.Decode(&id)
if err != nil {
return fmt.Errorf("unable to decode EventID for event #%v: %v", i, err)
}

fmt.Println(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.Warn("unable to find event with EventID %v in metadata for event #%v: %s", id, i, err)
continue
}

fmt.Println(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() {
fmt.Println(fmt.Sprintf("unable to find field %v_%v for event #%v with EventID %v ", moduleName, eventName, i, id))
continue
}

// 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([]types.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()))

fmt.Println(fmt.Sprintf("decoded event #%v", i))
return nil
}

func (m *MarketUserStatus) Encode(encoder scale.Encoder) error {
var err1 error
if m.IsProvider {
err1 = encoder.PushByte(0)
} else if m.IsGateway {
err1 = encoder.PushByte(1)
} else if m.IsClient {
err1 = encoder.PushByte(2)
}
if err1 != nil {
return err1
}
return nil
}
Loading

0 comments on commit 1aa5a4d

Please sign in to comment.