@@ -2,21 +2,42 @@ import type { GatewayName, XyoGatewayProvider } from '@xyo-network/xl1-protocol'
22
33const localGatewayName = 'local' as GatewayName
44
5+ const GATEWAY_LISTENER_TIMEOUT = 5000
6+
57export const hasXyoWalletGateway = ( ) => {
68 return 'client' in globalThis . xyo
79}
810
9- export function getXyoGateway ( options : { assert : true } ) : XyoGatewayProvider
10- export function getXyoGateway ( options ?: { assert ?: boolean } ) : XyoGatewayProvider | undefined {
11+ export const listenForWalletInjection = ( onPluginReady : ( ) => void , onTimeout : ( ) => void ) => {
12+ let resolved = false
13+ const listener : EventListener = ( e ) => {
14+ onPluginReady ( )
15+ resolved = true
16+ }
17+ globalThis . addEventListener ( 'xyo:plugin-ready' , listener )
18+ setTimeout ( ( ) => {
19+ if ( ! resolved ) {
20+ onTimeout ( )
21+ }
22+ } , GATEWAY_LISTENER_TIMEOUT )
23+ }
24+
25+ export async function getXyoGateway ( options : { assert : true } ) : Promise < XyoGatewayProvider >
26+ export async function getXyoGateway ( options ?: { assert ?: boolean } ) : Promise < XyoGatewayProvider | undefined > {
1127 const { assert } = options ?? { }
1228 if ( hasXyoWalletGateway ( ) ) {
1329 return globalThis . xyo . client ?. gateways ?. [ localGatewayName ]
1430 } else {
15- console . error ( 'XYO Wallet not installed' )
16- if ( assert ) {
17- throw new Error ( 'XYO Wallet not installed' )
18- } else {
19- return undefined
20- }
31+ // listen for the XyoWallet to be injected
32+ return await new Promise < XyoGatewayProvider | undefined > ( ( resolve , reject ) => {
33+ listenForWalletInjection (
34+ ( ) => {
35+ resolve ( globalThis . xyo . client ?. gateways ?. [ localGatewayName ] )
36+ } ,
37+ ( ) => {
38+ reject ( new Error ( 'XYO Wallet not installed' ) )
39+ }
40+ )
41+ } )
2142 }
2243}
0 commit comments