1+ import { Box , Button } from '@chakra-ui/react' ;
2+ import { createCoinbaseWalletSDK } from '@coinbase/wallet-sdk' ;
3+ import { useCallback , useState } from 'react' ;
4+
5+ type GetSubAccountsProps = {
6+ sdk : ReturnType < typeof createCoinbaseWalletSDK > ;
7+ } ;
8+
9+ export function GetSubAccounts ( { sdk } : GetSubAccountsProps ) {
10+ const [ subAccounts , setSubAccounts ] = useState < any > ( ) ;
11+ const [ isLoading , setIsLoading ] = useState ( false ) ;
12+
13+ const handleGetSubAccounts = useCallback ( async ( ) => {
14+ if ( ! sdk ) {
15+ return ;
16+ }
17+
18+ setIsLoading ( true ) ;
19+ try {
20+ const provider = sdk . getProvider ( ) ;
21+ const accounts = await provider . request ( {
22+ method : 'eth_requestAccounts' ,
23+ } ) as string [ ] ;
24+ if ( accounts . length < 2 ) {
25+ throw new Error ( 'Create a sub account first by clicking the Add Address button' ) ;
26+ }
27+ const response = await provider . request ( {
28+ method : 'wallet_getSubAccounts' ,
29+ params : [ {
30+ account : accounts [ 1 ] ,
31+ domain : window . location . origin ,
32+ } ] ,
33+ } ) ;
34+
35+ console . info ( 'getSubAccounts response' , response ) ;
36+ setSubAccounts ( response ) ;
37+ } catch ( error ) {
38+ console . error ( 'Error getting sub accounts:' , error ) ;
39+ setSubAccounts ( { error : error instanceof Error ? error . message : 'Unknown error' } ) ;
40+ } finally {
41+ setIsLoading ( false ) ;
42+ }
43+ } , [ sdk ] ) ;
44+
45+ return (
46+ < >
47+ < Button w = "full" onClick = { handleGetSubAccounts } isLoading = { isLoading } loadingText = "Getting Sub Accounts..." >
48+ Get Sub Accounts
49+ </ Button >
50+ { subAccounts && (
51+ < Box
52+ as = "pre"
53+ w = "full"
54+ p = { 2 }
55+ bg = "gray.900"
56+ borderRadius = "md"
57+ border = "1px solid"
58+ borderColor = "gray.700"
59+ overflow = "auto"
60+ whiteSpace = "pre-wrap"
61+ >
62+ { JSON . stringify ( subAccounts , null , 2 ) }
63+ </ Box >
64+ ) }
65+ </ >
66+ ) ;
67+ }
0 commit comments