Initia 백서

Initia

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 38쪽 중 32쪽

turn <span>{address || 'Not connected'}</span> } ``` <Note> This example assumes providers are already set up. For complete setup configurations, see [Provider Setup](../setup/providers). </Note> ## Return Value ```ts theme={null} function useInitiaAddress(): string ``` Converts the connected hex wallet address into an Initia bech32 address. Returns an empty string when there is no connected address. ## Notes * Always returns bech32 format, unlike `useAddress` which adapts to the default chain's format. * Use for Initia-specific integrations or when you need a consistent bech32 format regardless of chain type. # useInterwovenKit Source: https://docs.initia.xyz/interwovenkit/references/hooks/use-interwovenkit ## Overview The `useInterwovenKit` hook provides access to wallet connection state, account information, UI controls, transaction utilities, and AutoSign functionality for interacting with the Initia blockchain. <Note> This hook must be used within a component wrapped by `InterwovenKitProvider` to access wallet functionality. For simple reads, prefer smaller hooks (`useAddress`, `useUsernameQuery`) to avoid overhead. </Note> ## Prerequisites * Must be rendered within `InterwovenKitProvider`. * Must be used within a React Query `QueryClientProvider`. * Must be used within a wagmi `WagmiProvider`. * Client-only (no SSR): Put this in a `use client` provider tree, or use a dynamic import in Next.js. ## Quickstart ```tsx theme={null} 'use client' import { useInterwovenKit } from '@initia/interwovenkit-react' function ConnectButton() { const { isConnected, openConnect, openWallet } = useInterwovenKit() return ( <button onClick={isConnected ? openWallet : openConnect}> {isConnected ? 'Open wallet' : 'Connect'} </button> ) } ``` <Note> This example assumes providers are already set up. For complete setup configurations, see [Provider Setup](../setup/providers). </Note> ## Account Information The hook provides multiple address formats and account details for the currently connected wallet: <ParamField type="string"> Current address in either Bech32 or hex format, depending on the configured chain type (hex for `minievm`, bech32 for others). Returns an empty string when not connected. </ParamField> <ParamField type="string"> Bech32-formatted Initia wallet address of the connected account. Returns an empty string when not connected. </ParamField> <ParamField type="string"> Hex-encoded Ethereum-compatible address of the connected account. Returns an empty string when not connected. </ParamField> <ParamField type="string | null | undefined"> Optional username linked to the account. Returns `null` if no username is associated, or `undefined` before the query has produced a value. </ParamField> <ParamField type="OfflineAminoSigner"> Offline signer for Cosmos transactions. </ParamField> <ParamField type="boolean"> Whether a wallet is currently connected. </ParamField> <ParamField type="boolean"> Whether the InterwovenKit drawer/modal is currently open. </ParamField> ```tsx theme={null} function AccountInfo() { const { address, initiaAddress, hexAddress, username, isConnected } = useInterwovenKit() if (!isConnected) return <div>Not connected</div> return ( <div> <div>Address: {address}</div> <div>Initia Address: {initiaAddress}</div> <div>Hex Address: {hexAddress}</div> {username && <div>Username: {username}</div>} </div> ) } ``` ## UI Controls The hook provides methods for controlling wallet-related UI components: <ParamField type="() => void"> Opens a drawer for connecting an external wallet. </ParamField> <ParamField type="() => void"> Opens the main wallet drawer showing balances for the connected account. </ParamField> <ParamField type="(defaultValues?: Partial<FormValues>) => void"> Opens the bridge drawer to onboard assets with optional pre-populated values. </ParamField> <ParamField type="(params: { denoms: string[]; chainId?: string; srcOptions?: AssetOption[]; recipientAddress?: string }) => void"> Opens a modal to deposit assets from another chain to the current chain. </ParamField> <ParamField type="(params: { denoms: string[]; chainId?: string; dstOptions?: AssetOption[]; recipientAddress?: string }) => void"> Opens a modal to withdraw assets from the current chain to another chain. </ParamField> <ParamField type="() => void"> Disconnects the current wallet connection. </ParamField> ### Bridge Form Values The `openBridge` method accepts optional `FormValues` to pre-populate the bridge form: <ParamField type="string"> Source chain ID for the bridge transaction. </ParamField> <ParamField type="string"> Source token denomination to bridge from. </ParamField> <ParamField type="string"> Destination chain ID for the bridge transaction. </ParamField> <ParamField type="string"> Destination token denomination to bridge to. </ParamField> <ParamField type="string"> Initial bridge amount (use human-readable values, e.g., "1" for 1 INIT). </ParamField> <ParamField type="string"> Sender address. </ParamField> <ParamField type="string"> Recipient address. </ParamField> <ParamField type="string"> Slippage tolerance percentage. </ParamField> <ParamField type="string"> Optional Cosmos wallet name. </ParamField> <Tip> All bridge form values are optional. You can pre-populate any subset of fields to improve the user experience. </Tip> ```tsx theme={null} function BridgeButton() { const { openBridge } = useInterwovenKit() return ( <button onClick={() => openBridge({ srcChainId: 'interwoven-1', srcDenom: 'uinit', dstChainId: 'my-rollup-1', dstDenom: 'uinit', quantity: '100', }) } > Bridge Assets </button> ) } ``` ### Deposit and Withdraw Example ```tsx theme={null} import { useInterwovenKit } from '@initia/interwovenkit-react' function DepositWithdrawButtons() { const { openDeposit, openWithdraw } = useInterwovenKit() return ( <> <button onClick={() => openDeposit({ denoms: ['uinit'], chainId: 'interwoven-1', }) } > Open deposit </button> <button onClick={() => openWithdraw({ denoms: ['uinit'], chainId: 'interwoven-1', }) } > Open withdraw </button> </> ) } ``` For a full walkthrough, see [Deposit and Withdraw](../../features/transfers/deposit-withdraw). ## Transaction Methods The hook provides utilities for estimating, simulating, signing, and sending transactions on the blockchain: <ParamField type="(tx: Pick<TxRequest, 'messages' | 'memo' | 'chainId'>) => Promise<number>"> Estimates the gas required for a transaction before execution. </ParamField> <ParamField type="(tx: Pick<TxRequest, 'messages' | 'memo' | 'chainId'>) => Promise<unknown>"> Simulates a transaction without broadcasting, returning the transaction result. </ParamField> <ParamField type="(tx: TxRequest) => Promise<string>"> Signs and broadcasts a transaction, returning the transaction hash immediately without waiting for block inclusion. Shows transaction approval UI before signing. </ParamField> <ParamField type="(tx: TxRequest, timeoutMs?: number, intervalMs?: number) => Promise<DeliverTxResponse>"> Signs, broadcasts, and waits for block inclusion, returning the complete transaction response. Shows transaction approval UI before signing. Defaults to `timeoutMs: 30000` (30 seconds) and `intervalMs: 500` (0.5 seconds). </ParamField> <ParamField type="(tx: TxParams) => Promise<string>"> Signs and broadcasts a transaction with pre-calculated fee, returning the transaction hash immediately without waiting for block inclusion. Does not show UI. </ParamField> <ParamField type="(tx: TxParams, timeoutMs?: number, intervalMs?: number) => Promise<DeliverTxResponse>"> Signs, broadcasts, and waits for block inclusion with pre-calculated fee, returning the complete transaction response. Does not show UI. Defaults to `timeoutMs: 30000` (30 seconds) and `intervalMs: 500` (0.5 seconds). </ParamField> <ParamField type="(options: WaitForTxOptions) => Promise<IndexedTx>"> Polls for transaction confirmation on-chain using a transaction hash. </ParamField> <Tip> Use `requestTxSync` for better UX when you want to show immediate feedback, then use `waitForTxConfirmation` to track the final transaction status. Use `requestTxBlock` when you need the complete transaction result immediately. </Tip> ### Transaction Request Interface The `TxRequest` interface defines parameters for transaction operations that include gas estimation: <ParamField type="EncodeObject[]"> Array of encoded transaction messages to include in the transaction. </ParamField> <ParamField type="string"> Optional memo to attach to the transaction. </ParamField> <ParamField type="string"> Target chain ID for the transaction. Defaults to the provider's `defaultChainId`. </ParamField> <ParamField type="number"> Multiplier applied to the estimated gas amount for safety margin. </ParamField> <ParamField type="number"> Explicit gas limit for the transaction. If provided, skips gas estimation. </ParamField> <ParamField type="Coin[] | null"> Explicit gas prices. If provided, skips the fee denomination selection UI. </ParamField> <ParamField type="Coin[]"> Coins to spend for the transaction fee. </ParamField> ### Transaction Params Interface The `TxParams` interface defines parameters for transactions with pre-calculated fees: <ParamField type="EncodeObject[]"> Array of encoded transaction messages to include in the transaction. </ParamField> <ParamField type="string"> Optional memo to attach to the transaction. </ParamField> <ParamField type="string"> Target chain ID for the transaction. Defaults to the provider's `defaultChainId`. </ParamField> <ParamField type="StdFee"> Pre-calculated fee for the transaction. </ParamField> ### Transaction Confirmation Options The `WaitForTxOptions` interface defines parameters for tracking transaction confirmation: <ParamField type="string"> Hash of the transaction to track for confirmation. </ParamField> <ParamField type="string"> Chain ID where the transaction was broadcast. </ParamField> <ParamField type="number"> Maximum time in milliseconds to wait for transaction confirmation before failing. Defaults to 30000 (30 seconds). </ParamField> <ParamField type="number"> Polling interval in milliseconds for checking transaction status. Defaults to 500 (0.5 seconds). </ParamField> ### Transaction Examples ```tsx theme={null} import { useInterwovenKit } from '@initia/interwovenkit-react' import type { EncodeObject, StdFee } from '@cosmjs/stargate' function SendTransaction() { const { requestTxBlock, submitTxSync, waitForTxConfirmation } = useInterwovenKit() // Example: Request transaction with UI approval const handleRequestTx = async (messages: EncodeObject[]) => { try { const response = await requestTxBlock({ messages }) console.log('Transaction confirmed:', response.transactionHash) } catch (error) { console.error('Transaction failed:', error) } } // Example: Submit transaction directly without UI const handleSubmitTx = async (messages: EncodeObject[], fee: StdFee) => { try { const txHash = await submitTxSync({ messages, fee }) console.log('Transaction hash:', txHash) // Optionally wait for confirmation const confirmed = await waitForTxConfirmation({ txHash }) console.log('Transaction confirmed:', confirmed) } catch (error) { console.error('Transaction failed:', error) } } return ( <div> <button onClick={() => handleRequestTx([ /* messages */ ]) } > Send with UI </button> <button onClick={() => handleSubmitTx( [ /* messages */ ], { /* fee */ }, ) } > Send without UI </button> </div> ) } ``` ## AutoSign The hook provides AutoSign state and control methods for automatic transaction signing: <ParamField type="Record<string, Date | null | undefined>"> Expiration dates for AutoSign permissions by chain ID. </ParamField> <ParamField type="Record<string, boolean>"> Whether AutoSign is enabled for each chain. </ParamField> <ParamField type="boolean"> Whether AutoSign status is being loaded. </ParamField> <ParamField type="(chainId?: string) => Promise<void>"> Opens UI to enable AutoSign for a chain. Optionally specify a chain ID, or defaults to the provider's `defaultChainId` if omitted. </ParamField> <ParamField type="(chainId?: string) => Promise<void>"> Disables AutoSign for a chain. Optionally specify a chain ID, or defaults to the provider's `defaultChainId` if omitted. </ParamField> <Tip> AutoSign is configured directly on `InterwovenKitProvider` with `enableAutoSign`. See [Provider Setup](../setup/providers) for the current setup flow. </Tip> ```tsx theme={null} function AutoSignControls() { const { autoSign } = useInterwovenKit() const chainId = 'interwoven-1' return ( <div> {autoSign.isLoading ? ( <div>Loading AutoSign status...</div> ) : ( <> <div> AutoSign enabled:{' '} {autoSign.isEnabledByChain[chainId] ? 'Yes' : 'No'} </div> {autoSign.expiredAtByChain[chainId] && ( <div> Expires: {autoSign.expiredAtByChain[chainId]?.toLocaleString()} </div> )} <button onClick={() => autoSign.enable(chainId)}> Enable AutoSign </button> <button onClick={() => autoSign.disable(chainId)}> Disable AutoSign </button> </> )} </div> ) } ``` ## Notes * Transaction helpers throw `MoveError` on Move VM errors (see [MoveError](../errors/move-error)). * `requestTx*` methods show a transaction approval UI before signing. * `submitTx*` methods sign and broadcast directly without UI. * `waitForTxConfirmation` polls until confirmed or timeout. ## Type Reference (Advanced) ```ts theme={null} function useInterwovenKit(): InterwovenKitResult type InterwovenKitResult = { address: string initiaAddress: string hexAddress: string username: string | null | undefined offlineSigner: OfflineAminoSigner isConnected: boolean isOpen: boolean openConnect: () => void openWallet: () => void openBridge: (defaultValues?: Partial<FormValues>) => void openDeposit: (params: OpenDepositParams) => void openWithdraw: (params: OpenWithdrawParams) => void disconnect: () => void autoSign: AutoSignState estimateGas: ( tx: Pick<TxRequest, 'messages' | 'memo' | 'chainId'>, ) => Promise<number> simulateTx: ( tx: Pick<TxRequest, 'messages' | 'memo' | 'chainId'>, ) => Promise<unknown> requestTxSync: (tx: TxRequest) => Promise<string> requestTxBlock: ( tx: TxRequest, timeoutMs?: number, intervalMs?: number, ) => Promise<DeliverTxResponse> submitTxSync: (tx: TxParams) => Promise<string> submitTxBlock: ( tx: TxParams, timeoutMs?: number, intervalMs?: number, ) => Promise<DeliverTxResponse> waitForTxConfirmation: (options: WaitForTxOptions) => Promise<IndexedTx> } type FormValues = { srcChainId: string srcDenom: string dstChainId: string dstDenom: string quantity: string sender: string cosmosWalletName?: string recipient: string slippagePercent: string } type AssetOption = { denom: string chainId: string } type OpenDepositParams = { denoms: string[] chainId?: string srcOptions?: AssetOption[] recipientAddress?: string } type OpenWithdrawParams = { denoms: string[] chainId?: string dstOptions?: AssetOption[] recipientAddress?: string } type TxRequest = { messages: EncodeObject[] memo?: string chainId?: string gas?: number gasAdjustment?: number gasPrices?: Coin[] | null spendCoins?: Coin[] } type TxParams = { messages: EncodeObject[] memo?: string chainId?: string fee: StdFee } type WaitForTxOptions = { txHash: string chainId?: string timeoutMs?: number intervalMs?: number } type AutoSignState = { expiredAtByChain: Record<string, Date | null | undefined> isEnabledByChain: Record<string, boolean> granteeByChain: Record<string, string | undefined> isLoading: boolean enable: (chainId?: string) => Promise<void> disable: (chainId?: string) => Promise<void> } ``` Types `OfflineAminoSigner`, `EncodeObject`, `Coin`, `StdFee`, `DeliverTxResponse`, and `IndexedTx` are from external packages. See `@cosmjs/amino`, `@cosmjs/proto-signing`, `cosmjs-types`, `@cosmjs/stargate` for details. # usePortfolio Source: https://docs.initia.xyz/interwovenkit/references/hooks/use-portfolio ## Overview * Aggregates balances, asset metadata, and prices across all chains in the Initia registry into a single portfolio view. * Groups assets by symbol and computes per-chain and total portfolio value. * Tracks loading state and provides manual refetching for all underlying queries. ## Prerequisites * Must be rendered within `InterwovenKitProvider`. * Must be used within a React Query `QueryClientProvider`. * Must be used within a wagmi `WagmiProvider`. * Client-only (no SSR): Put this in a `use client` provider tree, or use a dynamic import in Next.js. ## Quickstart ```tsx theme={null} 'use client' import { usePortfolio } from '@initia/interwovenkit-react' function PortfolioValue() { const { totalValue, isLoading } = usePortfolio() if (isLoading) return <span>Loading…</span> return <span>${totalValue.toFixed(2)}</span> } ``` <Note> This example assumes providers are already set up. For complete setup configurations, see [Provider Setup](../setup/providers). </Note> ## Return Value The hook returns an object with aggregated portfolio data, grouped assets, and control methods: **Aggregated values:** <ParamField type="number"> Estimated total USD value across all chains. </ParamField> <ParamField type="PortfolioChainItem[]"> List of chains sorted by portfolio value on each chain. </ParamField> **Grouped assets:** <ParamField type="PortfolioAssetGroup[]"> Aggregated assets grouped by symbol across chains. </ParamField> <ParamField type="PortfolioAssetItem[]"> Assets without registry metadata, kept separate from grouped assets. </ParamField> **Loading and control:** <ParamField type="boolean"> `true` while any underlying query is loading. </ParamField> <ParamField type="() => void"> Manually refetches all balances, assets, and prices. </ParamField> ## Notes * The portfolio view only includes chains and assets that have non‑zero balances. * `totalValue` sums listed asset groups. Assets in `unlistedAssets` are returned separately and are not included in that total. ## Type Reference (Advanced) ```ts theme={null} function usePortfolio(): PortfolioResult type PortfolioResult = { chainsByValue: PortfolioChainItem[] assetGroups: PortfolioAssetGroup[] unlistedAssets: PortfolioAssetItem[] totalValue: number isLoading: boolean refetch: () => void } type PortfolioChainItem = { chainId: string name: string logoUrl: string value: number } type PortfolioAssetGroup = { symbol: string logoUrl: string assets: PortfolioAssetItem[] totalValue: number totalAmount: number } type PortfolioAssetItem = { symbol: string logoUrl: string amount: string denom: string decimals: number quantity: string price?: number value?: number address?: string unlisted?: boolean chain: PortfolioChainInfo } type PortfolioChainInfo = { chainId: string name: string logoUrl: string } ``` # useUsernameQuery Source: https://docs.initia.xyz/interwovenkit/references/hooks/use-username-query ## Overview * React Query hook that fetches the Initia (`.init`) username for a provided address, or for the connected address when no argument is passed. * Automatically re-runs when the target address changes. * Exposes standard React Query state (`isLoading`, `error`, etc.). ## Prerequisites * Must be rendered within `InterwovenKitProvider`. * Must be used within a React Query `QueryClientProvider`. * Must be used within a wagmi `WagmiProvider`. * Client-only (no SSR): Put this in a `use client` provider tree, or use a dynamic import in Next.js. ## Quickstart ### Connected Wallet Call `useUsernameQuery()` with no arguments to resolve the username for the currently connected wallet. ```tsx theme={null} 'use client' import { useUsernameQuery } from '@initia/interwovenkit
프로젝트로 돌아가기