### Install Sui SDK Dependency Source: https://kit.suiet.app/docs/QuickStart Installs the `@mysten/sui` package, which is a required dependency for interacting with the Sui blockchain. Ensure this is installed alongside the wallet kit. ```shell npm install @mysten/sui ``` ```shell yarn add @mysten/sui ``` ```shell pnpm install @mysten/sui ``` -------------------------------- ### Install Suiet Wallet Kit Source: https://kit.suiet.app/docs/QuickStart Installs the `@suiet/wallet-kit` npm package using npm, yarn, or pnpm. This is the first step to integrate Suiet Wallet Kit into your project. ```shell npm install @suiet/wallet-kit ``` ```shell yarn add @suiet/wallet-kit ``` ```shell pnpm install @suiet/wallet-kit ``` -------------------------------- ### Interact with Wallet Capabilities Source: https://kit.suiet.app/docs/QuickStart Shows how to use the `useWallet` hook to access connected wallet information and perform actions like signing messages or executing transactions. It includes examples for `signAndExecuteTransaction` and `signPersonalMessage`. ```javascript import { useWallet } from '@suiet/wallet-kit'; import { Transaction } from "@mysten/sui/transactions"; import { useEffect } from 'react'; const App = () => { const wallet = useWallet(); useEffect(() => { if (!wallet.connected) return; console.log('connected wallet name: ', wallet.name); console.log('account address: ', wallet.account?.address); console.log('account publicKey: ', wallet.account?.publicKey); }, [wallet.connected]); // Launch a move call for the connected account via wallet async function handleMoveCall() { const tx = new Transaction(); const packageObjectId = "0x1"; tx.moveCall({ target: `${packageObjectId}::nft::mint`, arguments: [tx.pure.string("Example NFT")], }); await wallet.signAndExecuteTransaction({ transaction: tx }); } // Launch a move call for the connected account via wallet async function handleSignMessage() { await wallet.signPersonalMessage({ message: new TextEncoder().encode("Hello World"), }); } return ( <> {/* Your UI elements */} ); }; ``` -------------------------------- ### Install Suiet Wallet Kit and Sui SDK Source: https://kit.suiet.app/docs/tutorial/connect-dapp-with-wallets Installs the necessary packages for Suiet Wallet Kit and the official Typescript SDK `@mysten/sui` using npm. This is a prerequisite for integrating wallet functionality into a DApp. ```bash npm install @mysten/sui @suiet/wallet-kit ``` -------------------------------- ### Install Suiet Wallet Kit v0.1.0 Source: https://kit.suiet.app/docs/category/migration Command to install version 0.1.0 of the Suiet Wallet Kit. This is useful for users needing to revert to or test compatibility with this specific older version. ```bash npm install @suiet/wallet-kit@0.1 ``` -------------------------------- ### Basic ConnectButton Usage in React Source: https://kit.suiet.app/docs/components/ConnectButton Demonstrates the basic integration of the `ConnectButton` component within a `WalletProvider` context. This setup allows users to initiate wallet connections easily. Ensure `@suiet/wallet-kit` is installed and imported correctly. ```javascript import { ConnectButton, WalletProvider } from '@suiet/wallet-kit'; function App() { return ( Connect Wallet ); } ``` -------------------------------- ### Use ConnectButton Component Source: https://kit.suiet.app/docs/QuickStart Demonstrates how to easily integrate the `ConnectButton` component into your React application's UI. This button handles wallet connection and disconnection flows. ```javascript import { ConnectButton } from '@suiet/wallet-kit'; const App = () => { return ( <>
{/* ... rest of your app */} ); }; ``` -------------------------------- ### Wrap App with WalletProvider Source: https://kit.suiet.app/docs/QuickStart Wraps your main React application component with `WalletProvider` to enable wallet functionalities. It also includes importing the default Suiet CSS for styling. ```javascript import { WalletProvider } from '@suiet/wallet-kit'; import '@suiet/wallet-kit/style.css'; // For React 18 projects ReactDOM.createRoot(document.getElementById('root')).render( ); ``` -------------------------------- ### Wrap App with WalletProvider Source: https://kit.suiet.app/docs/tutorial/hooks-only Demonstrates how to wrap the main application component with `WalletProvider` to provide context for wallet data and functions. This is the initial setup step for using Suiet Kit hooks. ```javascript import{WalletProvider}from'@suiet/wallet-kit'; functionRootComponent(){ return( ); } ``` -------------------------------- ### ConnectModal Usage Example Source: https://kit.suiet.app/docs/components/ConnectModal Demonstrates how to use the ConnectModal component with a custom trigger button. It shows how to manage the modal's open state and handle connection events. This example assumes you have a custom button component named 'YourOwnButton'. ```javascript import { useWallet, ConnectModal } from '@suiet/wallet-kit'; import { useState } from 'react'; function App() { const { connected } = useWallet(); const [showModal, setShowModal] = useState(false); if (connected) { return ; } return ( // wrap your own button as the trigger of the modal setShowModal(open)} > ); } ``` -------------------------------- ### Setup WalletProvider in React App Source: https://kit.suiet.app/docs/tutorial/connect-dapp-with-wallets Wraps the main React application with the `WalletProvider` from `@suiet/wallet-kit`. This makes wallet states and functions accessible throughout the application, enabling wallet interactions. ```javascript import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { WalletProvider } from "@suiet/wallet-kit"; import App from "./App"; const rootElement = document.getElementById("root"); const root = createRoot(rootElement); // wrap your app with WalletProvider root.render( ); ``` -------------------------------- ### Comprehensive Error Handling Example Source: https://kit.suiet.app/docs/Hooks/useSuinsName An example combining the retrieval of the default name, loading state, and error handling. It prioritizes displaying an error message if resolution fails, otherwise shows the loading state or the resolved name. ```javascript const{ defaultName, loading, error }=useSuinsName({ address, chain }); if(error){ // Log error for debugging but show user-friendly message console.error('SuiNS resolution failed:', error); returnName unavailable; } if(loading){ return Loading...; } return {defaultName || 'No name found'}; ``` -------------------------------- ### IDefaultWallet Example Source: https://kit.suiet.app/docs/Types Demonstrates how to create a custom wallet object conforming to the IDefaultWallet interface. It shows importing the type and assigning values to its properties. ```typescript import IDefaultWallet from"@suiet/wallet-kit"; const myWallet: IDefaultWallet ={ name:"myWallet", iconUrl:"external url or data url", downloadUrl:{ browserExtension:"chrome extension store url...", }, }; ``` -------------------------------- ### Basic Usage: WalletProvider in React Source: https://kit.suiet.app/docs/components/WalletProvider Demonstrates the fundamental way to integrate the WalletProvider into a React application. It shows how to import the provider and wrap the root component to make wallet functionalities available throughout the dApp. This setup is essential before using any other Suiet Kit hooks or components. ```javascript import ReactDOM from 'react-dom'; import { WalletProvider } from '@suiet/wallet-kit'; function App() { // Your application components return (

My Suiet App

{/* Other components using Suiet Kit */}
); } function Root() { // Wrap your app component with WalletProvider return ( ); } ReactDOM.render(, document.getElementById('root')); ``` -------------------------------- ### Sign Transaction with useWallet Hook Source: https://kit.suiet.app/docs/migration/upgradeTo0.2 Demonstrates how to use the new `signTransaction` method from the `useWallet` hook to sign a transaction block. This feature allows Dapp developers to obtain signatures for transactions. ```javascript async function handleSignTransaction() { const tx = new TransactionBlock(); tx.moveCall({ target: '0x2::nft::mint', arguments: [ tx.pure('name'), tx.pure('capy'), tx.pure('https://cdn.britannica.com/94/194294-138-B2CF7780/overview-capybara.jpg?w=800&h=450&c=crop'), ], }); // get the signature of the transaction const { signature, transactionBytes } = await wallet.signTransactionBlock({ transactionBlock: tx, }); } ``` -------------------------------- ### Sign and Verify Personal Message Source: https://kit.suiet.app/docs/Hooks/useWallet Demonstrates how to sign a personal message using the wallet and then verify the signature. It highlights the use of TextEncoder for converting strings to Uint8Array, which is the required input format for signing operations. The example includes error handling for failed operations. ```javascript import { useWallet } from '@suiet/wallet-kit'; import * as tweetnacl from 'tweetnacl'; function App() { const wallet = useWallet(); async function handleSignMsg() { try { const msg = 'Hello world!'; // convert string to Uint8Array const msgBytes = new TextEncoder().encode(msg); const result = await wallet.signPersonalMessage({ message: msgBytes }); // directly input the signed result for verification const verifyResult = await wallet.verifySignedPersonalMessage(result); if (!verifyResult) { console.log('signPersonalMessage succeed, but verify signedMessage failed'); } else { console.log('signPersonalMessage succeed, and verify signedMessage succeed!'); } } catch (e) { console.error('signPersonalMessage failed', e); } } return ( ); } ``` -------------------------------- ### Get Wallet Info with useWallet Source: https://kit.suiet.app/docs/Hooks/useWallet Demonstrates how to use the `useWallet` hook to retrieve the connection status, name, and account details of a connected Sui wallet. This is a fundamental step for interacting with the Sui blockchain via Suiet Kit. ```typescript import { useWallet } from '@suiet/wallet-kit'; function App() { const wallet = useWallet(); console.log('wallet status', wallet.status); console.log('connected wallet name', wallet.name); console.log('connected account info', wallet.account); } ``` -------------------------------- ### Executing Transactions with JsonRpcProvider Source: https://kit.suiet.app/docs/Hooks/useSuiprovider Illustrates a practical example of using the useSuiProvider hook to execute a transaction block. It shows how to call the executeTransactionBlock method with transaction details such as the transaction block data and signature, and how to handle the RPC response. ```typescript function YourComponent() { const { executeTransactionBlock } = useSuiProvider(); return ( ); } ``` -------------------------------- ### Customize Suiet Wallet Kit Styles with CSS Source: https://kit.suiet.app/docs/styling/customize Provides examples of CSS rules to override default styles for components like buttons and account modals. These rules target specific class names provided by the Suiet Wallet Kit, allowing for granular control over the UI. ```css .wkit-button { height:64px; /* For example, override the height of the button */ } /* Customize AccountModal */ .wkit-account-modal__content { padding:24px0; /* Increase padding */ } .wkit-account-modal__name { color:#2563eb; /* Change name color to blue */ font-size:20px; /* Increase font size */ } .wkit-account-modal__action-button { border-radius:8px; /* Make buttons more rounded */ padding:12px16px; /* Increase button padding */ } .wkit-account-modal__action-button--disconnect { background-color:rgba(220,38,38,0.1); /* Custom disconnect button color */ } ``` -------------------------------- ### Get Primary SuiNS Name Source: https://kit.suiet.app/docs/Hooks/useSuinsName Retrieves the primary SuiNS name for an address. This is the first name in the 'names' array or null if none are found. The example shows how to display this name or a fallback to the address itself. ```javascript const{ defaultName }=useSuinsName({ address, chain }); // Display primary name or fallback to address const displayName = defaultName ||`${address.slice(0,8)}...`; ``` -------------------------------- ### Get All SuiNS Names Source: https://kit.suiet.app/docs/Hooks/useSuinsName Fetches an array containing all SuiNS names associated with the address. The first item in the array is considered the primary name. The example demonstrates checking if an address has multiple names. ```javascript const{ names }=useSuinsName({ address, chain }); // Check if address has multiple names if(names.length>1){ console.log('This address has multiple SuiNS names:', names); } ``` -------------------------------- ### Define New Wallet with Suiet Wallet Kit Source: https://kit.suiet.app/docs/tutorial/customize-wallet-list This snippet demonstrates how to define a custom wallet using the `defineWallet` function from the `@suiet/wallet-kit`. It shows how to provide wallet details like name, icon, and download URL, and then integrate it into the `WalletProvider` for use in your DApp. This is useful when the default wallet presets do not cover the wallets you need. ```typescript import{ WalletProvider, defineWallet, }from'@suiet/wallet-kit'; // customized wallet must support @mysten/wallet-standard constCustomizeWallet=defineWallet({ name:"myWallet", iconUrl:"external url or data url", downloadUrl:{ browserExtension:'download page url of chrome extension...' }, }) ReactDOM.createRoot(document.getElementById('root')as HTMLElement).render( ) ``` -------------------------------- ### Suiet Wallet Kit API References Source: https://kit.suiet.app/docs/Hooks/useWallet Comprehensive API references for the Suiet Wallet Kit hooks, covering wallet connection status, account management, transaction signing, and message verification. ```APIDOC useWallet Hook: Properties: - name: string Description: The name of the connected wallet adapter. - connection status: boolean Description: Indicates if the wallet is currently connected. - account: object | null Description: Information about the connected account, including address and public key. - address: string | null Description: The address of the connected wallet account. - chains: Array Description: List of chains supported by the wallet adapter. - chain: object | null Description: The currently selected chain. - adapter: object Description: The wallet adapter instance. Methods: - select(): Promise Description: Prompts the user to select a wallet to connect. - getAccounts(): Promise> Description: Retrieves a list of all available account addresses. - switchAccount(): Promise Description: Prompts the user to switch to a different connected account. - signTransaction(transaction: object): Promise Description: Signs a given transaction object. Parameters: - transaction: The transaction object to sign. Returns: The signed transaction. - signAndExecuteTransaction(transaction: object): Promise Description: Signs and executes a given transaction object. Parameters: - transaction: The transaction object to sign and execute. Returns: The result of the executed transaction. - signPersonalMessage(message: string): Promise Description: Signs a personal message using the connected wallet. Parameters: - message: The personal message to sign. Returns: An object containing the signed message and signature. - verifySignedPersonalMessage(message: string, signature: string): Promise Description: Verifies a signed personal message. Parameters: - message: The original personal message. - signature: The signature to verify. Returns: True if the signature is valid, false otherwise. - verifySignedTransactoin(signedTransaction: object): Promise Description: Verifies a signed transaction. Parameters: - signedTransaction: The signed transaction to verify. Returns: True if the transaction is valid, false otherwise. - on(event: string, listener: Function): void Description: Subscribes to wallet events. Parameters: - event: The name of the event to listen for (e.g., 'chainChanged', 'accountChanged'). - listener: The callback function to execute when the event occurs. ``` ```APIDOC Deprecated APIs: - verifySignedMessage(message: string, signature: string): Promise Description: Deprecated. Use verifySignedPersonalMessage instead. Parameters: - message: The message to verify. - signature: The signature to verify. Returns: True if the signature is valid, false otherwise. - signAndExecuteTransactionBlock(transactionBlock: object): Promise Description: Deprecated. Use signAndExecuteTransaction instead. - signTransactionBlock(transactionBlock: object): Promise Description: Deprecated. Use signTransaction instead. - executeMoveCall and executeSerializedMoveCall(payload: object): Promise Description: Deprecated methods for executing Move calls. - wallet: object Description: Deprecated. Access wallet functionalities through hook methods directly. - getPublicKey(): Promise Description: Deprecated. Use account.publicKey instead. - signMessage(message: string): Promise Description: Deprecated. Use signPersonalMessage instead. ``` -------------------------------- ### Conditional Query Execution Source: https://kit.suiet.app/docs/Hooks/useSuinsName Shows how to use the 'enabled' parameter to control when the hook's query runs. This example ensures the query only executes when both the 'address' and 'chain' parameters are truthy. ```javascript // Only query when we have both address and chain const{ defaultName }=useSuinsName({ address, chain, enabled:!!address &&!!chain, }); ``` -------------------------------- ### UseWallet Hook API References Source: https://kit.suiet.app/docs/Hooks/useWallet Provides details on the properties and methods available through the `useWallet` hook for interacting with connected wallets. ```APIDOC name: Description: The name of the connected wallet. Type: string Default: undefined connection status: Description: The connection status of the wallet. Properties: connecting: boolean (Default: false) connected: boolean (Default: false) status: 'disconnected' | 'connecting' | 'connected' (Default: 'disconnected') Example: const { status, connected, connecting } = useWallet(); // assert expressions are equally the same assert(status === 'disconnected', !connecting && !connected); // not connect to wallet assert(status === 'connecting', connecting); // now connecting to the wallet assert(status === 'connected', connected); // connected to the wallet account: Description: The account information in the connected wallet, including address, publicKey, etc. Type: [WalletAccountExtended](https://kit.suiet.app/docs/Types#walletaccountextended) Default: undefined Example: const { connected, account } = useWallet(); function printAccountInfo() { if (!connected) return; console.log(account?.address); console.log(account?.suinsName); // should enableSuiNS first console.log(account?.publicKey); } address: Description: Alias for `account.address`. Type: string select: Description: Selects a wallet to connect to by its name. Signature: (WalletName: string) => void ``` -------------------------------- ### Handle Error State Source: https://kit.suiet.app/docs/Hooks/useSuinsName Contains error information if the SuiNS name resolution failed. This example shows how to check for an error and display a user-friendly message while logging the detailed error for debugging. ```javascript const{ error, defaultName }=useSuinsName({ address, chain }); if(error){ // Log error for debugging but show user-friendly message console.error('SuiNS resolution failed:', error); returnName unavailable; } ``` -------------------------------- ### Connect Wallet using select Method Source: https://kit.suiet.app/docs/tutorial/hooks-only Illustrates using the `select` method from the `useWallet` hook to initiate wallet connection. It accesses wallet information like `configuredWallets`, `detectedWallets`, and `allAvailableWallets` to present connection options. ```javascript import{ useWallet }from'@suiet/wallet-kit'; functionWalletSelector(){ const{ select, // select configuredWallets, // default wallets detectedWallets, // Sui-standard wallets detected from browser env allAvailableWallets, // all the installed Sui-standard wallets }=useWallet(); return[...configuredWallets,...detectedWallets].map((wallet)=>( )); } ``` -------------------------------- ### Customize Cache Duration Source: https://kit.suiet.app/docs/Hooks/useSuinsName Demonstrates how to customize the cache duration for the hook's data using React Query. This example sets the cache to 10 minutes, overriding the default 5 minutes. ```javascript // Cache for 10 minutes instead of default 5 minutes const{ defaultName }=useSuinsName({ address, chain, cacheDuration:10*60*1000, }); ``` -------------------------------- ### Suiet Wallet Kit API Reference Source: https://kit.suiet.app/docs/Hooks/useWallet Provides an overview of key properties and methods available through the Suiet Wallet Kit's useWallet hook, adhering to the @mysten/wallet-standard. This includes access to the wallet adapter, supported chains, and transaction signing capabilities. ```APIDOC useWallet(): WalletContextState // Properties: connected: boolean // Indicates if a wallet is currently connected. accounts: WalletAccount[] // An array of connected and authorized accounts. chain: Chain | null // The currently active chain connected to the wallet. chains: Chain[] // An array of chains supported by the wallet provider. adapter: IWalletAdapter | undefined // The normalized wallet adapter conforming to @mysten/wallet-standard. // Methods: getAccounts(): string[] // Returns an array of permitted account addresses. switchAccount(address: string): Promise // Switches the current main account to the one with the given address. // Requires the address to be available in wallet.getAccounts(). // Returns the newly switched WalletAccount. signTransaction(input: { transaction: Transaction }): Promise // Signs a transaction object. signAndExecuteTransaction(input: { transactionBlock: TransactionBlock; requestType?: ExecuteTransactionRequestType; options?: SuiTransactionBlockResponseOptions; }): Promise // Signs and executes a transaction block, submitting it to a specified fullnode RPC. // Offers DApp-side control over execution. signPersonalMessage(input: { message: Uint8Array }): Promise<{ signature: string; bytes: string }> // Signs a personal message, returning the signature and message bytes in base64. connect(): Promise // Initiates the wallet connection process. disconnect(): Promise // Disconnects the wallet. // Events: // The wallet object may emit events for connection status changes, account changes, etc. // Refer to @mysten/wallet-standard for specific event details. ``` -------------------------------- ### Deprecated: Get Public Key Source: https://kit.suiet.app/docs/Hooks/useWallet This method is deprecated; access the public key via `account.publicKey` instead. It was used to retrieve the user's public key. ```typescript const wallet = useWallet(); // Deprecated: // console.log(wallet.getPublicKey()); // Use account.publicKey instead: console.log(wallet.account.publicKey); ``` -------------------------------- ### Connect to Wallets and Display Status with useWallet Source: https://kit.suiet.app/docs/tutorial/connect-dapp-with-wallets Demonstrates connecting to Sui wallets using Suiet Wallet Kit and displaying the connection status. It utilizes the `ConnectButton` component and the `useWallet` hook to access wallet properties. Requires `@suiet/wallet-kit`. ```javascript import { ConnectButton, useWallet } from "@suiet/wallet-kit"; export default function App() { const wallet = useWallet(); return (

Hello, Suiet Wallet Kit

Wallet status:{wallet.status}

); } ``` -------------------------------- ### Integrate Wallet with Suiet Kit (TypeScript) Source: https://kit.suiet.app/docs/CanIUse This snippet demonstrates how wallet developers can integrate their custom wallets into the Suiet Kit. It involves defining the wallet using `defineWallet` in `presets.ts` and registering it in the `AllDefaultWallets` array in `index.ts`. ```typescript // packages/kit/src/wallet/preset-wallets/presets.ts export enum PresetWallet { // ... resgisted wallet enum // note that this name should match with your wallet adapter's name // for auto detection and display purposes YOUR_WALLET = "Your Wallet", } export const YourWallet = defineWallet({ name: PresetWallet.YOUR_WALLET, iconUrl: 'base64 encoded image (recommended, optimize the size!!) / external url', downloadUrl: { browserExtension: 'chrome extension installation url', }, }) ``` ```typescript // packages/kit/src/wallet/preset-wallets/index.ts export const AllDefaultWallets = [ ...[ // ... registed wallets presets.YourWallet, ].sort((a, b) => a.name < b.name ? -1 : 1), ] ``` -------------------------------- ### Handle Loading State Source: https://kit.suiet.app/docs/Hooks/useSuinsName Indicates whether the SuiNS name resolution is currently in progress. This example shows how to conditionally render UI elements based on the loading state, displaying a 'Loading...' message or the resolved name. ```javascript const{ loading, defaultName }=useSuinsName({ address, chain }); return(
{loading ?( Loading... ):( {defaultName ||'No name found'} )}
); ``` -------------------------------- ### WalletProvider API Props Source: https://kit.suiet.app/docs/components/WalletProvider Details the configurable properties for the WalletProvider component. These props allow customization of wallet lists, supported networks, connection behavior, and more. Understanding these props is key to tailoring the Suiet Kit experience to your dApp's specific requirements. ```APIDOC WalletProvider Props: defaultWallets: IDefaultWallet[] | undefined Description: Configures the list of wallets displayed in the connection modal. By default, it loads all preset wallets available in Suiet Kit. Type: Array of wallet configurations or undefined. Default: [...[AllPresetWallets](https://kit.suiet.app/docs/CanIUse#preset-wallets)] chains: Chain[] Description: Defines the supported blockchain networks (chains) for your dApp. This prop dictates which networks users can connect to. Type: Array of Chain objects. Default: [DefaultChains](https://kit.suiet.app/docs/Types#Chain) autoConnect: boolean Description: Enables or disables the automatic connection to the last connected wallet when the dApp is launched. Type: boolean Default: true enableSuiNS: boolean Description: Controls whether Sui Name Service (SuiNS) is enabled for displaying user addresses. If true, it will show the SuiNS domain if one exists for the address. Type: boolean Default: true useLegacyDisconnectDropdown: boolean Description: Provides backward compatibility for the disconnection UI. Setting this to true uses an older style of the disconnect dropdown. Type: boolean Default: false reactQueryClient: QueryClient | undefined Description: Allows you to provide a custom QueryClient instance from '@tanstack/react-query'. This is useful for unifying the QueryClient instance between your dApp and Suiet Kit. Type: QueryClient object or undefined. Default: undefined ``` -------------------------------- ### Integrate Slush Web Wallet Source: https://kit.suiet.app/docs/tutorial/customize-wallet-list Shows how to integrate the Slush Web Wallet by defining its configuration using `defineSlushWallet` and adding it to the `defaultWallets` array in `WalletProvider`. This allows custom wallets to be included alongside presets, displaying your DApp name when connecting. ```typescript import { WalletProvider, defineSlushWallet, AllDefaultWallets } from "@suiet/wallet-kit"; const slushWebWalletConfig = defineSlushWallet({ appName: "Your DApp Name", }); export default function App() { return ( ); } ``` -------------------------------- ### Get Suiet Wallet Accounts Source: https://kit.suiet.app/docs/Hooks/useWallet Retrieves all accessible accounts provided by the connected wallet. This function returns an array of strings, where each string is a permitted account address. Ensure the wallet is connected before calling this method. ```javascript import { useWallet } from '@suiet/wallet-kit'; function YourComponent() { const wallet = useWallet(); function handleGetAccounts() { if (!wallet.connected) return; const accounts = wallet.getAccounts(); console.log('Permitted accounts of this wallet:', accounts); } } ``` -------------------------------- ### Create and Execute Sui NFT Mint Transaction Source: https://kit.suiet.app/docs/tutorial/connect-dapp-with-wallets Demonstrates creating a Sui `TransactionBlock` for minting an NFT using the Sui TS SDK and executing it via a connected wallet using `@suiet/wallet-kit`. It covers defining contract calls, arguments, and handling the transaction signing and execution flow. ```typescript import{Transaction}from"@mysten/sui"; functioncreateMintNftTxnBlock(){ // define a programmable transaction block const txb =newTransaction(); // note that this is a devnet contract address const contractAddress = "0xe146dbd6d33d7227700328a9421c58ed34546f998acdc42a1d05b4818b49faa2"; const contractModule ="nft"; const contractMethod ="mint"; const nftName ="Suiet NFT"; const nftDescription ="Hello, Suiet NFT"; const nftImgUrl = "https://xc6fbqjny4wfkgukliockypoutzhcqwjmlw2gigombpp2ynufaxa.arweave.net/uLxQwS3HLFUailocJWHupPJxQsli7aMgzmBe_WG0KC4"; txb.moveCall({ target:`${contractAddress}::${contractModule}::${contractMethod}`, arguments:[ tx.pure(nftName), tx.pure(nftDescription), tx.pure(nftImgUrl), ], }); return txb; } ``` ```typescript import{ useWallet }from"@suiet/wallet-kit"; import{Transaction}from"@mysten/sui"; functioncreateMintNftTxnBlock(){ // ... } exportdefaultfunctionApp(){ const wallet =useWallet(); asyncfunctionmintNft(){ if(!wallet.connected)return; const txb =createMintNftTxnBlock(); try{ // call the wallet to sign and execute the transaction const res =await wallet.signAndExecuteTransactionBlock({ transactionBlock: txb, }); console.log("nft minted successfully!", res); alert("Congrats! your nft is minted!"); }catch(e){ alert("Oops, nft minting failed"); console.error("nft mint failed", e); } } return( {/* ... */} {wallet.status==="connected"&& Mint Your NFT ! } {/* ... */} ); } ``` -------------------------------- ### Upgrade signMessage output type Source: https://kit.suiet.app/docs/migration/upgradeTo0.2 The `signMessage` method, now a standard feature in `@mysten/wallet-standard` v0.5.0, has updated its output type. The previous `signedMessage` and `signature` fields, which were `number[]`, have been changed to `messageBytes` and `signature` respectively, both of type `string`. ```APIDOC // output type of signMessage { - signedMessage: number[]; + messageBytes: string; - signature: number[]; + signature: string; } ``` -------------------------------- ### Switch Account with Suiet Wallet Kit Source: https://kit.suiet.app/docs/tutorial/hooks-only This JavaScript code snippet demonstrates how to use the `switchAccount` method from the `@suiet/wallet-kit` library to allow users to switch between connected wallet accounts. It includes error handling and displays the current accounts. ```javascript import { useWallet } from '@suiet/wallet-kit'; function AccountSwitcher() { const wallet = useWallet(); async function handleSwitchAccount(address) { if (!wallet.connected) return; try { const newAccount = await wallet.switchAccount(address); console.log('Successfully switched to account:', newAccount); } catch (e) { console.error('Failed to switch account:', e); } } const renderWalletAccounts = () => { if (!wallet.connected) return null; const accounts = wallet.getAccounts(); if (!accounts?.length) return null; return (
    {accounts.map((account) => (
  1. handleSwitchAccount(account.address)} style={{ cursor: "pointer" }} >

    address: {account.address}

    publicKey: {account.publicKey ?? "not supported"}

  2. ))}
); }; return (

Your Accounts

{renderWalletAccounts()}
); } ``` -------------------------------- ### Transaction Execution API Comparison Source: https://kit.suiet.app/docs/tutorial/sign-and-execute-transactions Compares the execution behavior, FullNode dependency, and GraphQL API support for Suiet's transaction signing and execution methods. ```APIDOC signAndExecuteTransactionBlock: Description: Executes a transaction block. Execution: on Wallet FullNode for Execution: Specified by Wallet GraphQL API support: Depend on wallet's implementation signAndExecuteTransaction: Description: Executes a transaction. Execution: on DApp FullNode for Execution: Specified by DApp GraphQL API support: Can be done by customizing the execute function ``` -------------------------------- ### Configure Default Wallets with WalletProvider Source: https://kit.suiet.app/docs/tutorial/customize-wallet-list Demonstrates how to set a custom list of default wallets using the `WalletProvider` component. This configures the wallets displayed in the popular section of the wallet-select modal, allowing you to define the order or include specific wallets. ```typescript import { WalletProvider, SuietWallet, SuiWallet, EthosWallet, IDefaultWallet } from '@suiet/wallet-kit'; ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render( {/* or just leave it as default which contains all preset wallets */} {/**/} ) ``` -------------------------------- ### useAccountBalance with useEffect for Calculations Source: https://kit.suiet.app/docs/Hooks/useAccountBalance An example demonstrating how to use the `useAccountBalance` hook within a React component. It includes a `useEffect` hook to perform actions based on the fetched balance, such as checking if the balance exceeds a certain threshold. The balance is provided as a string and needs conversion for numerical operations. ```typescript import { useEffect } from 'react'; interface AccountBalanceResponse { error: Error | null; loading: boolean; balance: string; } import { useAccountBalance } from '@suiet/wallet'; function App() { const { error, loading, balance } = useAccountBalance(); useEffect(() => { // if you want to do comparison or calculation with balance, // use Number or BigInt to convert the balance string if (Number(balance) > 1000000) { console.log('You are a millionare!'); } }, [balance]); return (
fetch balance loading status: {loading}
account balance: {balance}
); } ``` -------------------------------- ### Sign and Execute Sui Transactions with useWallet Source: https://kit.suiet.app/docs/Hooks/useWallet Shows how to define and execute a Sui Programmable Transaction using the `useWallet` hook. It includes signing a transaction block for operations like NFT minting and handling the response or errors. ```typescript import { useWallet } from '@suiet/wallet-kit'; import { TransactionBlock } from '@mysten/sui.js'; function App() { const wallet = useWallet(); async function handleSignAndExecuteTxBlock() { if (!wallet.connected) return; // define a programmable transaction const tx = new TransactionBlock(); const packageObjectId = "0xXXX"; tx.moveCall({ target: `${packageObjectId}::nft::mint`, arguments: [tx.pure("Example NFT")], }); try { // execute the programmable transaction const resData = await wallet.signAndExecuteTransactionBlock({ transactionBlock: tx }); console.log('nft minted successfully!', resData); alert('Congrats! your nft is minted!'); } catch (e) { console.error('nft mint failed', e); } } return ( ) } ``` -------------------------------- ### Upgrade signAndExecuteTransaction to signAndExecuteTransactionBlock Source: https://kit.suiet.app/docs/migration/upgradeTo0.2 The `signAndExecuteTransaction` method in `useWallet` has been renamed to `signAndExecuteTransactionBlock` to align with changes in the Sui SDK and RPC API. The input type has also been updated from `SignableTransaction` to `TransactionBlock`. This snippet demonstrates the updated usage for executing transaction blocks. ```javascript + import {TransactionBlock} from "@mysten/sui.js"; async function handleMintNftMoveCall() { - const data = { - packageObjectId: '0x2', - module: 'devnet_nft', - function: 'mint', - typeArguments: [], - arguments: [ - 'name', - 'capy', - 'https://cdn.britannica.com/94/194294-138-B2CF7780/overview-capybara.jpg?w=800&h=450&c=crop', - ], - }; + const tx = new TransactionBlock(); + tx.moveCall({ + target: '0x2::devnet_nft::mint', + arguments: [ + tx.pure('name'), + tx.pure('capy'), + tx.pure('https://cdn.britannica.com/94/194294-138-B2CF7780/overview-capybara.jpg?w=800&h=450&c=crop'), + ], + }) - await wallet.signAndExecuteTransaction({ - transaction: { - kind: 'moveCall', - data - } + await wallet.signAndExecuteTransactionBlock({ + transactionBlock: tx + }); } ``` -------------------------------- ### Override Suiet Kit CSS Variables Source: https://kit.suiet.app/docs/styling/customize This example shows how to override the default CSS variables to customize the Suiet Kit theme. It's recommended to define your custom variables in a separate CSS file and ensure it's imported after the default Suiet Kit stylesheet. ```css :root { --wkit-accent-hs:110,100%; /* Redefine the hs (the first two components of hsl) of the accent color */ /* ... other CSS variables */ } ``` -------------------------------- ### Basic Usage of useAccountBalance Source: https://kit.suiet.app/docs/Hooks/useAccountBalance Demonstrates the basic usage of the `useAccountBalance` hook to fetch and display an account's balance. It shows how to handle loading states and display the balance. The hook returns an object containing `error`, `loading`, and `balance` properties. ```javascript import { useAccountBalance } from '@suiet/wallet'; function App() { const { error, loading, balance } = useAccountBalance(); return (
{loading && }
{balance}
); } ```