Initia 백서

Initia

원문

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

enable and manage it in your application using the `autoSign` object from `useInterwovenKit()`. This guide covers how to use autosign in your code. <Note> This page assumes autosign is already configured on `InterwovenKitProvider`. See [Configuration](./configuration) and [Provider Setup](../../references/setup/providers) first. </Note> ## Accessing Autosign The `autoSign` object is available via the `useInterwovenKit()` hook: ```tsx theme={null} import { useInterwovenKit } from '@initia/interwovenkit-react' function MyComponent() { const { autoSign } = useInterwovenKit() // Use autoSign.enable(), autoSign.disable(), etc. } ``` ## Enabling Autosign To enable autosign, call the `enable()` method. This opens a drawer where users confirm the autosign setup and select an expiration duration. The following examples show client components for enabling and disabling autosign. You can adapt this logic to your own UI or component structure. ### Example: ToggleAutosignButton ```tsx theme={null} import { useMutation } from '@tanstack/react-query' import { useInterwovenKit } from '@initia/interwovenkit-react' const chainId = 'your-chain-id' export default function ToggleAutosignButton() { const { autoSign, address } = useInterwovenKit() const enable = useMutation({ mutationFn: () => autoSign.enable(chainId), onError: (error) => console.error('Failed to enable:', error), }) const disable = useMutation({ mutationFn: () => autoSign.disable(chainId), onError: (error) => console.error('Failed to disable:', error), }) if (!address) return null if (autoSign.isEnabledByChain[chainId]) { return ( <button onClick={() => disable.mutate()} disabled={autoSign.isLoading || disable.isPending} > Disable Autosign </button> ) } return ( <button onClick={() => enable.mutate()} disabled={autoSign.isLoading || enable.isPending} > Enable Autosign </button> ) } ``` ### Enabling for a Specific Chain Specify a chain ID to enable autosign for a particular chain: ```tsx theme={null} await autoSign.enable('interwoven-1') ``` ### What Happens When Enabled When `autoSign.enable()` is called: <Steps> <Step title="Drawer Opens"> A drawer appears asking the user to confirm autosign setup, showing which permissions will be granted. </Step> <Step title="Expiration Selection"> The user can select an expiration duration from available defaults or use a custom duration. </Step> <Step title="Wallet Derivation"> InterwovenKit requests a signature from the connected wallet and derives a dedicated AutoSign wallet for the current app origin. </Step> <Step title="Permission Grant"> The user signs a single transaction to grant `authz` and `feegrant` permissions to the AutoSign wallet. </Step> <Step title="Activation"> Autosign becomes active for the specified chain and message types. The Promise resolves on success. </Step> </Steps> The method returns a Promise that resolves when autosign is successfully enabled or rejects if the user cancels or an error occurs. ## Sending Transactions with Autosign Once autosign is enabled, you can send transactions without user confirmation using `submitTxBlock`. This method signs and broadcasts transactions directly using the AutoSign wallet when the transaction matches the configured grants. ```tsx theme={null} import { calculateFee, GasPrice } from '@cosmjs/stargate' import { MsgSend } from 'cosmjs-types/cosmos/bank/v1beta1/tx' import { useMutation } from '@tanstack/react-query' import { useInterwovenKit } from '@initia/interwovenkit-react' function SendWithAutosign() { const { initiaAddress, submitTxBlock, estimateGas } = useInterwovenKit() const { mutate, isPending } = useMutation({ mutationFn: async () => { const messages = [ { typeUrl: '/cosmos.bank.v1beta1.MsgSend', value: MsgSend.fromPartial({ fromAddress: initiaAddress, toAddress: 'init1...', // recipient address amount: [{ amount: '1000000', denom: 'uinit' }], }), }, ] // Estimate gas and calculate fee const gasEstimate = await estimateGas({ messages }) const fee = calculateFee( Math.ceil(gasEstimate * 1.4), GasPrice.fromString('0.015uinit'), ) // Submit transaction directly (no modal) const { transactionHash } = await submitTxBlock({ messages, fee }) return transactionHash }, }) return ( <button onClick={() => mutate()} disabled={isPending}> Send </button> ) } ``` <Tip> Use `submitTxBlock` for seamless transactions with autosign. For transactions requiring user confirmation, use `requestTxBlock` instead. </Tip> ## Disabling Autosign Users can disable autosign at any time. This revokes all grants for the selected chain and prevents further automatic signing. ### Checking Autosign Status Use the `isEnabledByChain` property to check if autosign is active for a chain: ```tsx theme={null} import { useInterwovenKit } from '@initia/interwovenkit-react' function AutosignStatus({ chainId }: { chainId: string }) { const { autoSign } = useInterwovenKit() if (autoSign.isLoading) { return <span>Loading...</span> } const isEnabled = autoSign.isEnabledByChain[chainId] const expiration = autoSign.expiredAtByChain[chainId] if (!isEnabled) { return <span>Autosign disabled</span> } return ( <span> Autosign enabled {expiration && ` (expires ${expiration.toLocaleString()})`} </span> ) } ``` # Deposit and Withdraw Source: https://docs.initia.xyz/interwovenkit/features/transfers/deposit-withdraw Open deposit and withdraw modals for cross-chain transfers. ## Overview Use `openDeposit` and `openWithdraw` from `useInterwovenKit()` to launch the built-in deposit and withdraw flows. These modals guide users through moving assets between chains without you rebuilding the UI. ## Basic Usage ```tsx theme={null} import { useInterwovenKit } from '@initia/interwovenkit-react' function TransferButtons() { 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> </> ) } ``` ## Defaults and Requirements * `chainId` defaults to the current chain. * `recipientAddress` defaults to your connected wallet address. * `srcOptions` and `dstOptions` default to assets that match the selected symbol across supported chains. * A wallet must be connected, or the call throws an error. * `denoms` must be a non-empty array. ## Optional Asset Options Use `srcOptions` or `dstOptions` to limit the asset list shown in the modal. ## Full Example ```tsx theme={null} import { useInterwovenKit } from '@initia/interwovenkit-react' function ScopedTransferButtons() { const { address, openDeposit, openWithdraw } = useInterwovenKit() const assetOptions = [ { denom: 'uinit', chainId: 'interwoven-1', }, { denom: 'uinit', chainId: 'my-rollup-1', }, ] if (!address) return null return ( <> <button onClick={() => openDeposit({ denoms: ['uinit'], chainId: 'interwoven-1', srcOptions: assetOptions, recipientAddress: address, }) } > Deposit INIT </button> <button onClick={() => openWithdraw({ denoms: ['uinit'], chainId: 'interwoven-1', dstOptions: assetOptions, recipientAddress: address, }) } > Withdraw INIT </button> </> ) } ``` ## Related Reference See [`useInterwovenKit`](../../references/hooks/use-interwovenkit) for parameter signatures and types. # Getting Started Source: https://docs.initia.xyz/interwovenkit/getting-started Integrate Initia Wallet into your React application with InterwovenKit ## Overview InterwovenKit is a React library that provides seamless integration with Initia Wallet. It enables you to connect wallets, manage accounts, and interact with the Initia blockchain directly from your React applications. It offers a complete wallet connection experience with built-in support for transactions, bridging, and account management. ## New Projects The fastest way to get started is by cloning our example project: ```bash theme={null} git clone https://github.com/initia-labs/examples.git cd examples/frontend/interwovenkit-react ``` <CodeGroup> ```bash npm theme={null} npm install npm run dev ``` ```bash yarn theme={null} yarn install yarn dev ``` ```bash pnpm theme={null} pnpm install pnpm dev ``` ```bash bun theme={null} bun install bun dev ``` </CodeGroup> The app will be available at [http://localhost:3000](http://localhost:3000/). This example demonstrates all core InterwovenKit features and serves as a reference implementation. ## Existing Projects <CardGroup> <Card title="Native Integration" icon="wallet" href="/interwovenkit/integrations/native"> Set up InterwovenKit as the default wallet connection option for your application </Card> <Card title="EVM Integration" icon="ethereum" href="/interwovenkit/integrations/evm"> Integrate InterwovenKit with an existing EVM application </Card> <Card title="RainbowKit Integration" icon="rainbow" href="/interwovenkit/integrations/rainbowkit"> Integrate InterwovenKit with an existing RainbowKit application </Card> </CardGroup> # EVM Integration Source: https://docs.initia.xyz/interwovenkit/integrations/evm ## Overview When working with EVM-based chains, you can configure [wagmi](https://wagmi.sh/) to connect directly to your custom EVM network instead of Ethereum mainnet. This approach allows you to: * Use wagmi for direct interaction with your EVM chain * Leverage Initia Wallet for interwoven rollup balance viewing and bridging * Maintain seamless connectivity between different blockchain environments <Info> **Non-EVM chains**: If your chain is not EVM-based, you can leave the default chain set to mainnet. Initia Wallet won't actually connect to Ethereum—it only uses an arbitrary signer to sign amino messages. </Info> ## Setup Guide <Steps> <Step title="Configure Providers"> Set up your providers to connect wagmi to your custom EVM chain. This configuration includes your chain details, wagmi config, and the InterwovenKit provider. ```tsx theme={null} // providers.tsx 'use client' import { PropsWithChildren, useEffect } from 'react' import { createConfig, http, WagmiProvider } from 'wagmi' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { initiaPrivyWalletConnector, injectStyles, InterwovenKitProvider, TESTNET, } from '@initia/interwovenkit-react' import interwovenKitStyles from '@initia/interwovenkit-react/styles.js' const minievm = { id: 4303131403034904, name: 'Minievm', nativeCurrency: { name: 'GAS', symbol: 'GAS', decimals: 18 }, rpcUrls: { default: { http: ['https://jsonrpc-evm-1.anvil.asia-southeast.initia.xyz'], }, }, } const wagmiConfig = createConfig({ connectors: [initiaPrivyWalletConnector], chains: [minievm], transports: { [minievm.id]: http() }, }) const queryClient = new QueryClient() export default function Providers({ children }: PropsWithChildren) { useEffect(() => { // Inject styles into the shadow DOM used by Initia Wallet injectStyles(interwovenKitStyles) }, []) return ( <QueryClientProvider client={queryClient}> <WagmiProvider config={wagmiConfig}> <InterwovenKitProvider {...TESTNET} defaultChainId="minievm-2"> {children} </InterwovenKitProvider> </WagmiProvider> </QueryClientProvider> ) } ``` **Key Configuration Elements:** * **Chain Definition**: Define your custom EVM chain with its ID, name, native currency, and RPC endpoints * **Wagmi Config**: Set up wagmi to use your custom chain and the Initia Privy wallet connector * **Style Injection**: Use `injectStyles()` to ensure proper styling within Initia Wallet's shadow DOM * **Provider Hierarchy**: Wrap your app with QueryClient, WagmiProvider, and InterwovenKitProvider * **Default Chain ID**: Set to your target rollup chain ID (e.g., `"minievm-2"` for Minievm testnet) <Info> **Chain ID Configuration**: The `defaultChainId` parameter sets the primary blockchain for Initia Wallet operations. For EVM rollups, use your rollup's chain ID (like `"minievm-2"`), not the EVM chain ID. This ensures proper balance display and bridging functionality. See [InterwovenKitProvider reference](/interwovenkit/references/components/interwovenkit-provider) for more details. </Info> </Step> <Step title="Install Dependencies"> To follow the implementation example, install `viem` for Ethereum utilities: <CodeGroup> <CodeBlock> npm install viem </CodeBlock> <CodeBlock> yarn add viem </CodeBlock> <CodeBlock> pnpm add viem </CodeBlock> <CodeBlock> bun add viem </CodeBlock> </CodeGroup> </Step> <Step title="Implementation Example"> The following React component demonstrates a complete integration that combines wagmi's EVM functionality with InterwovenKit features. This example shows how to: * Send transactions on your custom EVM chain using wagmi * Access Initia Wallet features for bridging and account management * Handle wallet connection states and user interactions ```tsx theme={null} // page.tsx 'use client' import { parseEther } from 'viem' import { useAccount, useChainId, useSendTransaction, useSwitchChain, } from 'wagmi' import { truncate } from '@initia/utils' import { useInterwovenKit } from '@initia/interwovenkit-react' export default function Home() { const chainId = useChainId() const { address } = useAccount() const { switchChainAsync } = useSwitchChain() const { sendTransactionAsync } = useSendTransaction() const { username, openConnect, openWallet, openBridge } = useInterwovenKit() const send = async () => { await switchChainAsync({ chainId }) const transactionHash = await sendTransactionAsync({ to: address, value: parseEther('0.01'), chainId: chainId, }) console.log('Transaction sent:', transactionHash) } const bridgeTransferDetails = { srcChainId: 'SOURCE_CHAIN_ID', srcDenom: 'SOURCE_ASSET_DENOM', dstChainId: 'DESTINATION_CHAIN_ID', dstDenom: 'DESTINATION_ASSET_DENOM', } if (!address) { return <button onClick={openConnect}>Connect</button> } return ( <> <button onClick={send}>Send</button> <button onClick={() => openBridge(bridgeTransferDetails)}>Bridge</button> <button onClick={openWallet}>{truncate(username ?? address)}</button> </> ) } ``` **Component Features:** * **Transaction Handling**: The `send()` function switches to the correct chain and sends a value transfer using wagmi's `useSendTransaction` * **Bridge Integration**: The `bridgeTransferDetails` object defines parameters for cross-chain bridging operations * **Wallet Management**: Conditional rendering based on connection status, with buttons for connecting, sending transactions, bridging, and accessing the wallet interface * **User Experience**: Displays truncated usernames or addresses for connected users </Step> </Steps> # Native Integration Source: https://docs.initia.xyz/interwovenkit/integrations/native InterwovenKit provides a native React integration for connecting and interacting with Initia wallets. This guide covers everything from basic setup to advanced features like transaction handling and cross-chain bridging. ## Prerequisites Before integrating InterwovenKit, ensure you have: * A React application (Next.js or Vite) * Node.js 22+ installed * Basic familiarity with React hooks and TypeScript ## Installation & Setup Follow these steps to set up InterwovenKit in your application: <Steps> <Step title="Install InterwovenKit"> Install the core InterwovenKit package and its peer dependencies: <CodeGroup> ```bash npm theme={null} npm install @initia/interwovenkit-react wagmi viem @tanstack/react-query ``` ```bash yarn theme={null} yarn add @initia/interwovenkit-react wagmi viem @tanstack/react-query ``` ```bash pnpm theme={null} pnpm add @initia/interwovenkit-react wagmi viem @tanstack/react-query ``` ```bash bun theme={null} bun add @initia/interwovenkit-react wagmi viem @tanstack/react-query ``` </CodeGroup> These packages provide: * **@initia/interwovenkit-react**: React hooks and components for Initia wallet integration * **wagmi**: Ethereum wallet infrastructure (required for cross-chain compatibility) * **viem**: Low-level Ethereum interaction library * **@tanstack/react-query**: Data fetching and state management </Step> <Step title="Configure Providers"> Create a providers component to set up the required React contexts. This component wraps your app with the necessary providers for wallet functionality: ```tsx providers.tsx theme={null} 'use client' import { PropsWithChildren, useEffect } from 'react' import { createConfig, http, WagmiProvider } from 'wagmi' import { mainnet } from 'wagmi/chains' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { initiaPrivyWalletConnector, injectStyles, InterwovenKitProvider, } from '@initia/interwovenkit-react' import interwovenKitStyles from '@initia/interwovenkit-react/styles.js' const wagmiConfig = createConfig({ connectors: [initiaPrivyWalletConnector], chains: [mainnet], transports: { [mainnet.id]: http() }, }) const queryClient = new QueryClient() export default function Providers({ children }: PropsWithChildren) { useEffect(() => { // Inject styles into the shadow DOM used by Initia Wallet injectStyles(interwovenKitStyles) }, []) return ( <QueryClientProvider client={queryClient}> <WagmiProvider config={wagmiConfig}> <InterwovenKitProvider defaultChainId="YOUR_CHAIN_ID"> {children} </InterwovenKitProvider> </WagmiProvider> </QueryClientProvider> ) } ``` <Info> **Chain Configuration**: Replace `YOUR_CHAIN_ID` with your target blockchain network: - `"interwoven-1"` for Initia mainnet (default) - `"initiation-2"` for Initia testnet - Or any valid chain ID from the [initia-registry](https://registry.initia.xyz) This sets the primary network for transactions, balance queries, and serves as the default for all operations. See the [InterwovenKitProvider reference](/interwovenkit/references/components/interwovenkit-provider) for details. </Info> </Step> <Step title="Wrap Your Application"> Import and use the providers in your application root: ```tsx layout.tsx theme={null} import Providers from './providers' export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode }>) { return ( <html lang="en"> <body> <Providers>{children}</Providers> </body> </html> ) } ``` For other React frameworks, wrap your app component with the `Providers` component at the highest level possible. </Step> <Step title="Implement Wallet Connection"> Create a basic component that demonstrates wallet connection. This component showcases the core wallet connection functionality using InterwovenKit's hooks: ```tsx components/WalletConnection.tsx theme={null} 'use client' import { truncate } from '@initia/utils' import { useInterwovenKit } from '@initia/interwovenkit-react' export default function WalletConnection() { const { address, username, isConnected, openConnect, openWallet } = useInterwovenKit() if (!isConnected) { return ( <div> <h2>Connect Your Wallet</h2> <p>Connect your Initia wallet to get started</p> <button onClick={openConnect}>Connect Wallet</button> </div> ) } return ( <div> <h2>Wallet Connected</h2> <p>Address: {address}</p> {username && <p>Username: {username}</p>} <button onClick={openWallet}>{truncate(username ?? address)}</button> </div> ) } ``` </Step> <Step title="Add Transaction Functionality"> Extend your component to handle transactions. This example demonstrates how to send a basic token transfer: ```tsx components/TransactionExample.tsx theme={null} 'use client' import { useState } from 'react' import { MsgSend } from 'cosmjs-types/cosmos/bank/v1beta1/tx' import { useInterwovenKit } from '@init
프로젝트로 돌아가기