ReactiveDOT Documentation

website·Indexed 32 days ago

https://reactivedot.dev

Documentation for @reactive-dot/core and @reactive-dot/react, featuring a query builder with Query<TInstructions, TDescriptor>, wallet management via Wallet<TOptions, TStorageKey>, and React hooks such as useAccounts(), useChainId(), and useLazyLoadQuery().

Tokens
38.9K
Snippets
293
Records
344
Agent score
64%

What's inside ReactiveDOT

  1. Fetch the latest block information with useBlock()

    The useBlock() composable retrieves information about the latest block on the chain. You can specify whether to target the 'finalized' block (default) or the 'best' block.
    function useBlock(tag?, options?): PromiseLikeAsyncState<BlockInfo>;
  2. LocalWallet class overview

    The LocalWallet class is an experimental implementation of a wallet that manages accounts locally. It extends the base Wallet class and provides mechanisms for converting accounts to and from JSON for storage. It utilizes an AccountStore to manage the state of local accounts.
    new LocalWallet<TAccount, TJsonAccount, TOptions, TStorageKey>(options?): LocalWallet<TAccount, TJsonAccount, TOptions, TStorageKey>;
  3. Manage wallet connections in Vue

    Wallet and account connections are managed using three primary composables from @reactive-dot/vue: useWallets (to list available wallets), useConnectedWallets (to track currently connected wallets), and useAccounts (to retrieve account details). For a pre-built UI experience, the documentation recommends using DOTConnect.
  4. Fetch latest block information with useBlock()

    The useBlock() hook is used to fetch information about the latest block. It allows targeting either the 'best' or 'finalized' block via the tag parameter. It returns a When type containing the BlockInfo or a promise for it, supporting suspense options.
    // Example: Fetch the latest finalized block (default)
    const block = useBlock();
    
    // Example: Fetch the best block with specific options
    const block = useBlock('best', { /* options */ });
  5. Use the LocalWallet class for local account management

    The LocalWallet class is an experimental implementation of a wallet that manages accounts locally. It extends the base Wallet class and provides mechanisms for serializing accounts to and from JSON for storage. It utilizes an AccountStore to manage the state of local accounts.
    // Basic instantiation
    const wallet = new LocalWallet(options);
  6. Get chain native token details using useNativeToken()

    The useNativeToken() composable retrieves information about the blockchain's native token, including its symbol (code), decimal precision, and helper functions to convert numbers or plancks into DenominatedNumber formats.
    function useNativeToken(options?): PromiseLikeAsyncState<{ 
      amountFromNumber: (number) => DenominatedNumber;
      amountFromPlanck: (planck) => DenominatedNumber;
      code: string | undefined;
      decimals: number | undefined;
    }>;
  7. Query and mutate blockchain data with @reactive-dot/react hooks

    Use these hooks for data fetching and transactions:

    • useBlock: Fetch information about the latest block.
    • useChainSpecData: Fetch the JSON-RPC spec.
    • useContractEventListener: Listen to contract events.
    • useContractMutation: Mutate (write to) a contract.
    • useLazyLoadQuery: Query data from the chain and return the response.
    • useMutation: Send transactions to chains.
    • useMutationListener: Watch for mutation events.
    • useSpendableBalance: Get a specific account's spendable balance.
    • useSpendableBalances: Get multiple accounts' spendable balances.
    • useTypedApi: Get the Polkadot-API typed API.
  8. Install ReactiveDOT and Polkadot-API dependencies

    To use ReactiveDOT in a Vue project, install the core library, the Vue integration plugin, and the polkadot-api package.
    # Using npm
    npm install @reactive-dot/core @reactive-dot/vue polkadot-api
    
    # Using yarn
    yarn add @reactive-dot/core @reactive-dot/vue polkadot-api
    
    # Using pnpm
    pnpm add @reactive-dot/core @reactive-dot/vue polkadot-api
    
    # Using bun
    bun add @reactive-dot/core @reactive-dot/vue polkadot-api
  9. Write data to Ink! contracts

    The useContractMutation composable is used to execute payable or non-payable (write) messages on a smart contract. It provides a status state to track the transaction progress (idle, pending, error, or success with a txHash).
    <script setup lang="ts">
    import { myContract } from "./contracts.ts";
    import { useContractMutation } from "@reactive-dot/vue";
    
    const { status, execute } = useContractMutation((mutate) =>
      mutate(myContract, CONTRACT_ADDRESS, "mint", {
        data: { id: 1 },
        value: 10_000n,
      }),
    );
    </script>
    
    <template>
      <button @click="execute()">Mint</button>
      <div v-if="status === 'pending'">Submitting...</div>
      <div v-else-if="status === 'error'">Error!</div>
      <div v-else-if="status !== 'idle'">Hash: {{ status.txHash }}</div>
    </template>
  10. Read data from Ink! contracts

    Use the useQuery composable with the Query.contract instruction to read from contract storage or execute read-only (view) messages. You can perform single queries or multi-queries to fetch data from multiple contracts or storage keys in parallel.
    <script setup lang="ts">
    import { myContract } from "./contracts.ts";
    import { useQuery } from "@reactive-dot/vue";
    import { toRefs } from "vue";
    
    // Single contract query
    const { data } = await useQuery((builder) =>
      builder.contract(myContract, CONTRACT_ADDRESS, (builder) =>
        builder
          .rootStorage()
          .storage("balance", ACCOUNT_ADDRESS)
          .message("free_balance", ACCOUNT_ADDRESS),
      ),
    );
    const [metadata, balance, freeBalance] = toRefs(data);
    
    // Multi-query example
    const { data: multiData } = useQuery((builder) =>
      builder.contracts(myContract, [ADDR_1, ADDR_2], (builder) =>
        builder
          .storage("symbol")
          .storages("balance", [ACC_1, ACC_2])
          .messages("free_balance", [ACC_1, ACC_2]),
      ),
    );
    </script>
  11. De-prioritize queries using the defer directive

    The defer: true option can be passed to a query to de-prioritize it. This causes the data to be in a pending state in the initial response and delivered as a subsequent response. When defer: true is used, the result will be either the resolved value or the pending symbol from @reactive-dot/core.
    <script setup lang="ts">
    import { useQuery } from "@reactive-dot/vue";
    import { pending } from "@reactive-dot/core";
    
    const { data: tvl } = await useQuery((query) =>
      query.storage("NominationPools", "TotalValueLocked", [], { defer: true }),
    );
    </script>
    
    <template>
      <progress v-if="tvl === pending" />
      <p v-else>Total staked: {{ tvl }}</p>
    </template>
  12. Handle async data with Suspense or Promise mode

    ReactiveDOT hooks support two async modes:

    1. Suspense mode (Default): Hooks suspend the component until data is loaded. Wrap the component in a <Suspense> boundary.
    2. Promise mode: Pass { use: false } to the hook to receive a stable, reactive Promise. This allows you to use React 19's use() function for manual suspension or usePromiseValue for non-suspending UIs.
    import { useSpendableBalance } from "@reactive-dot/react";
    import { use, Suspense } from "react";
    
    // 1. Suspense Mode (Default)
    function UserBalanceSuspense({ address }: { address: string }) {
      const balance = useSpendableBalance(address); // Suspends automatically
      return <div>Balance: {balance.toLocaleString()}</div>;
    }
    
    // 2. Promise Mode with React 19 'use'
    function UserBalancePromise({ address }: { address: string }) {
      const balancePromise = useSpendableBalance(address, { use: false });
      const balance = use(balancePromise); // Suspends here
      return <div>Balance: {balance.toLocaleString()}</div>;
    }