33 BlockTimestamp ,
44 BlockHook ,
55 HookType ,
6+ Account ,
67} from '../generated/graphql-server/model'
78
89// run 'NODE_URL=<RPC_ENDPOINT> EVENTS=<comma separated list of events> yarn codegen:mappings-types'
@@ -14,13 +15,30 @@ import {
1415 EventContext ,
1516 BlockContext ,
1617 StoreContext ,
18+ DatabaseManager ,
1719} from '@dzlzv/hydra-common'
1820
1921const start = Date . now ( )
2022let blockTime = 0
2123let totalEvents = 0
2224let totalBlocks = 0
2325
26+ async function getOrCreate < T > (
27+ e : { new ( ...args : any [ ] ) : T } ,
28+ id : string ,
29+ store : DatabaseManager
30+ ) : Promise < T > {
31+ let entity : T | undefined = await store . get < T > ( e , {
32+ where : { id } ,
33+ } )
34+
35+ if ( entity === undefined ) {
36+ entity = new e ( ) as T
37+ ; ( < any > entity ) . id = id
38+ }
39+ return entity
40+ }
41+
2442export async function balancesTransfer ( {
2543 store,
2644 event,
@@ -29,10 +47,25 @@ export async function balancesTransfer({
2947} : EventContext & StoreContext ) {
3048 const transfer = new Transfer ( )
3149 const [ from , to , value ] = new Balances . TransferEvent ( event ) . params
32- transfer . from = Buffer . from ( from . toHex ( ) )
33- transfer . to = Buffer . from ( to . toHex ( ) )
50+ const fromAcc = await getOrCreate < Account > ( Account , from . toString ( ) , store )
51+ fromAcc . hex = from . toHex ( )
52+ const toAcc = await getOrCreate < Account > ( Account , to . toString ( ) , store )
53+ toAcc . hex = to . toHex ( )
54+
3455 transfer . value = value . toBn ( )
3556 transfer . tip = extrinsic ? new BN ( extrinsic . tip . toString ( 10 ) ) : new BN ( 0 )
57+
58+ fromAcc . balance = fromAcc . balance . sub ( value )
59+ fromAcc . balance = fromAcc . balance . sub ( transfer . tip )
60+
61+ await store . save < Account > ( fromAcc )
62+
63+ toAcc . balance = toAcc . balance . add ( value )
64+ await store . save < Account > ( toAcc )
65+
66+ transfer . from = fromAcc
67+ transfer . to = toAcc
68+
3669 transfer . insertedAt = new Date ( block . timestamp )
3770 transfer . block = block . height
3871 transfer . comment = `Transferred ${ transfer . value } from ${ transfer . from } to ${ transfer . to } `
0 commit comments