@bigmi/react 包包含 React hooks 和组件,让你能够轻松地在 React 中构建 Bitcoin 应用。
开始之前,请安装最新版本的所有 bigmi 包。
安装
pnpm add @bigmi/core @bigmi/client @bigmi/react
快速开始
将你的应用包裹在BigmiProvider 中,以在 React 应用中启用 Bigmi 功能。
import { BigmiProvider } from '@bigmi/react'
import { config } from './config.ts'
function Main() {
return (
<BigmiProvider
config={config}
reconnectOnMount={false}
>
<YourApp />
</BigmiProvider>
)
}
import { bitcoin, http, createClient } from '@bigmi/core'
import { binance, xverse, phantom, createConfig } from '@bigmi/client'
// Create wallet connectors
const connectors = [
binance(),
xverse(),
phantom()
]
// Create configuration
export const config = createConfig({
chains: [bitcoin],
connectors,
client: ({ chain }) => createClient({ chain, transport: http() }),
ssr: true // if using Next.js or SSR
})
Hooks
在设置好 config 和 providers 之后,你就可以使用@bigmi/react 提供的 hooks。
连接到钱包
Bigmi 提供了useConnect hook 来处理连接钱包。useAccount hook 也可用于获取钱包账户的所有信息。
import { useAccount } from '@bigmi/react'
import { ConnectWallet } from './ConnectWallet.tsx'
function App() {
const { account, isConnected, connector } = useAccount()
const handleDisconnect = () => connector.disconnect()
return (
<div>
{isConnected ? (
<>
<p>Connected: {account.address}</p>
<button onClick={handleDisconnect}>Disconnect</button>
</>
) : (
<ConnectWallet />
)}
</div>
)
}
import { useConnect } from '@bigmi/react'
export function ConnectWallet() {
const { connect, connectors } = useConnect()
return (
<div>
{connectors.map((connector) => (
<button
key={connector.id}
onClick={() => connect({connector})}
>
Connect {connector.name}
</button>
))}
</div>
)
}
import { BigmiProvider } from '@bigmi/react'
import { App } from './App.tsx'
import { config } from './config.ts'
function Main() {
return (
<BigmiProvider
config={config}
>
<App />
</BigmiProvider>
)
}
import { bitcoin, http, createClient } from '@bigmi/core'
import { binance, xverse, phantom, createConfig } from '@bigmi/client'
// Create wallet connectors
const connectors = [
binance(),
xverse(),
phantom()
]
// Create configuration
export const config = createConfig({
chains: [bitcoin],
connectors,
client: ({ chain }) => createClient({ chain, transport: http() }),
ssr: true // if using Next.js or SSR
})
签署 PSBT
useConfig hook 可用于获取 config 的 client 对象,该对象可用于执行各种操作。
SignTransaction.tsx
import { getConnectorClient } from '@bigmi/client'
import { useConfig, useAccount } from '@bigmi/react'
import { signPsbt } from '@bigmi/core'
function SignTransaction() {
const config = useConfig()
const { account } = useAccount()
const handleSign = async () => {
const client = await getConnectorClient(config)
// send a transaction to the wallet for the user to sign
const signedPsbt = await signPsbt(client, {
psbt: 'base64_encoded_psbt',
account
})
}
return (
<button onClick={handleSign}>Sign Transaction </button>
)
}

