|
| 1 | +'use client' |
| 2 | +import { Balance } from '@xchainjs/xchain-client' |
| 3 | +import { generatePhrase } from '@xchainjs/xchain-crypto' |
| 4 | +import { Client as DashClient, defaultDashParams } from '@xchainjs/xchain-dash' |
| 5 | +import { assetToString, baseToAsset } from '@xchainjs/xchain-util' |
| 6 | +import { useRequest } from 'ahooks' |
| 7 | +import { useRef, useState } from 'react' |
| 8 | + |
| 9 | +export function ClientComponent() { |
| 10 | + const dashClient = useRef<DashClient>() |
| 11 | + const [balance, setBalance] = useState<Balance[]>() |
| 12 | + const { run: getBalance, loading } = useRequest( |
| 13 | + async () => { |
| 14 | + if (!dashClient.current) return undefined |
| 15 | + return dashClient.current.getBalance(await dashClient.current.getAddressAsync()) |
| 16 | + }, |
| 17 | + { |
| 18 | + pollingInterval: 60 * 1000, |
| 19 | + manual: true, |
| 20 | + onSuccess: setBalance, |
| 21 | + }, |
| 22 | + ) |
| 23 | + |
| 24 | + return ( |
| 25 | + <div className="flex flex-col items-center gap-y-5"> |
| 26 | + <p className="text-xl">Client component</p> |
| 27 | + {!dashClient.current && ( |
| 28 | + <button |
| 29 | + className="text-2xl bg-slate-400 p-2 rounded-xl" |
| 30 | + onClick={() => { |
| 31 | + dashClient.current = new DashClient({ |
| 32 | + ...defaultDashParams, |
| 33 | + phrase: process.env.NEXT_PUBLIC_PHRASE || generatePhrase(), |
| 34 | + }) |
| 35 | + getBalance() |
| 36 | + }} |
| 37 | + > |
| 38 | + Init DASH client with {process.env.NEXT_PUBLIC_PHRASE ? 'your phrase' : 'random phrase'} |
| 39 | + </button> |
| 40 | + )} |
| 41 | + {dashClient.current && ( |
| 42 | + <div className="flex flex-col items-center"> |
| 43 | + <p>Your address</p> |
| 44 | + <p>{dashClient.current.getAddress()}</p> |
| 45 | + </div> |
| 46 | + )} |
| 47 | + {loading && <p>Loading balance...</p>} |
| 48 | + {balance && ( |
| 49 | + <div className="flex flex-col items-center"> |
| 50 | + <p>Your balance</p> |
| 51 | + {balance.map((balance, index) => { |
| 52 | + return ( |
| 53 | + <div key={index}> |
| 54 | + {assetToString(balance.asset)} {baseToAsset(balance.amount).amount().toString()} |
| 55 | + </div> |
| 56 | + ) |
| 57 | + })} |
| 58 | + </div> |
| 59 | + )} |
| 60 | + {dashClient.current && ( |
| 61 | + <button |
| 62 | + className="text-2xl bg-slate-400 p-2 rounded-xl" |
| 63 | + onClick={() => { |
| 64 | + dashClient.current?.purgeClient() |
| 65 | + dashClient.current = undefined |
| 66 | + setBalance(undefined) |
| 67 | + }} |
| 68 | + > |
| 69 | + Disconnect client |
| 70 | + </button> |
| 71 | + )} |
| 72 | + </div> |
| 73 | + ) |
| 74 | +} |
0 commit comments