Skip to content

Commit

Permalink
feat: add session event parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
zoruka committed Dec 13, 2024
1 parent 9d2dd25 commit d336417
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
15 changes: 15 additions & 0 deletions packages/appkit/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ import UniversalProvider from '@walletconnect/universal-provider'
import type { SessionTypes } from '@walletconnect/types'
import type { UniversalProviderOpts } from '@walletconnect/universal-provider'
import { W3mFrameProviderSingleton } from './auth-provider/W3MFrameProviderSingleton.js'
import { WcHelpersUtil } from './utils/HelpersUtil.js'

declare global {
interface Window {
Expand Down Expand Up @@ -1294,6 +1295,20 @@ export class AppKit {
this.setCaipNetwork(caipNetwork)
}
})

this.universalProvider.on('session_event', (callbackData: unknown) => {
if (WcHelpersUtil.isSessionEventData(callbackData)) {
const { name, data } = callbackData.params.event

if (name === 'accountsChanged' && Array.isArray(data)) {
const caipAddress = CoreHelperUtil.parseCaipAddress(data[0])

if (caipAddress) {
this.syncAccount(caipAddress)
}
}
}
})
}
}

Expand Down
23 changes: 23 additions & 0 deletions packages/appkit/src/tests/utils/HelpersUtil.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,4 +205,27 @@ describe('WcHelpersUtil', () => {
])
})
})

describe('isSessionEventData', () => {
test.each([
[undefined, false],
[{}, false],
[
{
id: 1734112958243866,
topic: 'b2cb2748499532d9c307846c444b364dd881c959d9a080e30d63b6a76270a0f8',
params: {
event: {
name: 'accountsChanged',
data: ['eip155:1:0x53F31e8972Ebddac1553E37887C25C1b748485A6']
},
chainId: 'eip155:1'
}
},
true
]
])('should validate session event data', (data, expected) => {
expect(WcHelpersUtil.isSessionEventData(data)).toBe(expected)
})
})
})
24 changes: 24 additions & 0 deletions packages/appkit/src/utils/HelpersUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,5 +101,29 @@ export const WcHelpersUtil = {

return Array.from(new Set([...chains, ...accountsChains]))
})
},

isSessionEventData(data: unknown): data is WcHelpersUtil.SessionEventData {
return (
typeof data === 'object' &&
data !== null &&
'id' in data &&
'topic' in data &&
'params' in data &&
typeof data.params === 'object' &&
data.params !== null &&
'chainId' in data.params &&
'event' in data.params &&
typeof data.params.event === 'object' &&
data.params.event !== null
)
}
}

export namespace WcHelpersUtil {
export type SessionEventData = {
id: string
topic: string
params: { chainId: string; event: { data: unknown; name: string } }
}
}

0 comments on commit d336417

Please sign in to comment.