In-Depth Tria SDK Usage Guide for React

This comprehensive guide covers all aspects of using the Tria SDK in a React application, including detailed configurations, hooks, and components.

1. Installation

Install the package:

npm install @tria-sdk/authenticate-react @wagmi/[email protected] @wagmi/[email protected] axios

2. TriaProvider Configuration

Wrap your app with TriaProvider and import the css file:

import { TriaProvider } from '@tria-sdk/authenticate-react'
import '@tria-sdk/authenticate-react/dist/style.css'
function App() {
  return (
    <TriaProvider
      initialConfig={{
        analyticsKeys: {
          clientId: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
          projectId: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
        },
        chain: 'FUSE',
      }}
      initialUIConfig={{
        modalMode: true,
        darkMode: true,
        dappName: 'Tria Demo',
      }}
      initialWalletUIConfig={{
        darkMode: true,
      }}
    >
      {/* Your app components */}
    </TriaProvider>
  )
}

Configuration Objects

TriaConfigOptions(initialConfig)

initialConfig object for TriaProvider

PropertyTypeDescriptionDefault
analyticsKeys{ clientId: string, projectId: string }Required keys for analytics-
chainstringBlockchain network (e.g., 'FUSE', 'POLYGON')-
customChainobjectCustom chain configuration-
environment'testnet' | 'mainnet'Network environment'mainnet'
dappDetails{ dappDomain: string, dappLogo: string }Dapp-specific details-
aaobjectAccount Abstraction details-
aaSolanaobjectSolana Account Abstraction details-
rpcUrlstringCustom RPC URL-
triaStagingstring | booleanStaging environment flagfalse
supportedChainsstring[]List of supported chains[]
didDomainstringsuffix for did name eg: mydid@tria@tria
UIConfig(initialUIConfig)

initialUIConfig object for TriaProvider

PropertyTypeDescriptionDefault
modalModebooleanEnable modal mode for authtrue
darkModebooleanEnable dark modetrue
dappNamestringName of your dapp'My Dapp'
headerTextstringHeader text for auth modal'Get Started'
showHeaderbooleanShow header in auth modaltrue
showPoweredByTriabooleanShow 'Powered by Tria'true
googleButtonTextstringText for Google login button'Continue with Gmail'
twitterButtonTextstringText for Twitter login button'Continue with X'
appleButtonTextstringText for Apple login button'Continue with Apple'
phoneOtpButtonTextstringText for phone/email login button'Continue with Email/Phone'
showDividerbooleanShow divider in auth modaltrue
showHeadingPillbooleanShow heading pilltrue
OtpHeaderstringHeader for OTP screen'Enter OTP'
OtpSubHeaderstringSub-header for OTP screen'Verify your account using 6-digit code sent to:'
OtpRetryCaptionstringText for OTP resend button'Resend'
usernameHeadingTextstringHeader for username creation'Create Tria name'
usernameSubHeadingTextstringSub-header for username creation'This will be your in-game name.'
otpBgColorstringBackground color for OTP input'#ffffff00'
otpTextColorstringText color for OTP input'#FFFFFF'
otpBoxBgColorstringBackground color for OTP input boxes'#00000066'
otpBorderColorstringBorder color for OTP input boxes'#FFFFFF66'
passwordInputBgColorstringBackground color for password input'rgba(255, 255, 255, 0.05)'
passwordInputTextColorstringText color for password input'#ffffff'
passwordInputBorderColorstringBorder color for password input'rgba(255, 255, 255, 0.25)'
showCloseButtonbooleanShow close button in auth modaltrue
layoutstring[]Order of auth options['email-phone', 'web2', 'divider', 'web3']
emailPhoneLoginMethodsstring[]Enabled email/phone login methods['email', 'phone']
web2LoginMethodsstring[]Enabled Web2 login methods['google', 'twitter', 'apple', 'discord']
web3LoginMethodsstring[]Enabled Web3 login methods['metamask', 'walletconnect']
enablePasswordLoginbooleanEnable password-based loginfalse
WalletUIConfig(initialWalletUIConfig)

initialWalletUIConfig object for TriaProvider

PropertyTypeDescriptionDefault
darkModebooleanEnable dark mode for wallettrue
primaryColorstringPrimary color for wallet UI'#7D40FF'
customTriggerIDstringCustom ID for wallet trigger element-
walletPositionstringPosition of wallet UI-
transactionsUIConfigobjectConfiguration for transaction UI-
TelegramConfig(telegramConfig)

telegramConfig object for TriaProvider

PropertyTypeDescriptionDefaultMore info
botusernamestringTelegram bot name-Deep Linking in Telegram Bot
appnamestringTelegram mini app name-Telegram Mini Apps
startappstringTelegram mini app name command-Deep Linking in Telegram Mini Apps

3. Add Tria Modal to Your App

Add the TriaAuthModal component to your app. This component will render on screen if modalMode is set to true and will be hidden if modalMode is set to false. In modalMode the showAuthModal method must be used to show the modal and closeAuthModal to close the modal.

function AuthComponent() {
  return (
    <div>
      <TriaAuthModal />
    </div>
  )
}

4. useTriaAuth Hook

import { useTriaAuth } from '@your-org/react-tria-sdk'

export default function AuthComponent() {
  const {
    showAuthModal,
    closeAuthModal,
    logout,
    getAccount,
    isAuthenticated,
    userState,
    checkForTelegramMiniApp,
    configure,
    configureUI,
    configureWalletUI,
    isReady,
  } = useTriaAuth()

  if (!isReady) return <div>Loading...</div>

  return (
    <div>
      <TriaAuthModal />
      {isAuthenticated ? (
        <button onClick={logout}>Logout</button>
      ) : (
        <button onClick={showAuthModal}>Login</button>
      )}
    </div>
  )
}
Available Functions and States
NameTypeDescription
showAuthModalfunctionDisplay the auth modal (modal mode only)
closeAuthModalfunctionClose the auth modal (modal mode only)
logoutfunctionLog out the current user
getAccountfunctionGet the current user's account details
isAuthenticatedbooleanWhether a user is currently authenticated
userStateobjectCurrent user state information
checkForTelegramMiniAppfunctionCheck if running as a Telegram Mini App
configurefunctionUpdate SDK configuration
configureUIfunctionUpdate UI configuration
configureWalletUIfunctionUpdate wallet UI configuration

5. useTriaWallet Hook

The code below showcases the usage of the tria wallet functions. This component on clicking a button will show the modal, once authenticated the modal will be closed. Once the authentication is completed the isAuthenticated flag will be set to true and the userState will be updated with the user details. The isAuthenticated flag will persist as true across refreshes. It may take one or two renders to update this. A logout function can also be called to log the user out. The example show cases the use of signMessage and send functions. Additional functions will be detailed below. The signMessage function can be used to return a verification signature as well.

import React, { useEffect, useState } from "react";
import { useTriaAuth, useTriaWallet } from "../src";
import SocialAuthComponent from "./headless/SocialAuthComponent";

const TriaComponent: React.FC = () => {

  // authentication functions
  const {
    userState,
    logout,
    getAccount,
    isAuthenticated,
  } = useTriaAuth();

  // wallet functions
  const {
    signMessage,
    send,
    isReady
  } = useTriaWallet();

  // local component state
  const [message, setMessage] = useState("");

  // handle logout
  const handleDisconnect = async () => {
    try {
      await logout();
    } catch (error) {
      console.error("Logout failed", error);
    }
  };

  // get user account details
  const handleGetAccount = () => {
    console.log(getAccount());
  };

  // send transaction
  const handleSend = () => {
    const amount = 0.01;
    const recipientAddress = "0x59f7843B267E79ea51B687a04Ef497bA240E7B26";
    send(amount, recipientAddress).then((result) => {
      console.log("Transaction sent:", result);
    });
  };

  const handleSignMessage = () => {
    signMessage(message).then((result) => {
      console.log("Message signed:", result);
    });
  };

  // upon login. a login response is updated to the user state. initially it will be null until after login
  useEffect(() => {
    console.log("login:", userState);
  }, [userState]);


  return (
    <div >
      <h2>Tria Interface</h2>

      <button onClick={showAuthModal}>
        Show Auth Modal
      </button>

      <button
        onClick={handleDisconnect}
      >
        Disconnect
      </button>

      <input
        style={inputStyle}
        value={message}
        onChange={(e) => {
          console.log(e.target.value);
          setMessage(e.target.value);
        }}
        placeholder="Enter message to sign"
      />

      <button style={buttonStyle} onClick={handleSignMessage}>
        Sign Message
      </button>

      <button
        style={{ ...buttonStyle, backgroundColor: "#2196F3" }}
        onClick={handleGetAccount}
      >
        Get Account
      </button>

      <button
        style={{ ...buttonStyle, backgroundColor: "#FF9800" }}
        onClick={handleSend}
      >
        Send Transaction
      </button>

    </div>
  );
};

export default TriaComponent;

Available Functions
NameTypeDescription
isReadybooleanWhether the wallet is ready for operations
sendfunctionSend a transaction
signMessagefunctionSign a message
writeContractfunctionWrite to a smart contract
readContractfunctionRead from a smart contract
sendNftfunctionSend an NFT
checkBiofunctionCheck biometric authentication (for Telegram Mini Apps)
Sign Message
import React, { useEffect, useState } from "react";
import {  useTriaWallet } from "../src";

const TriaWalletFunctions: React.FC = () => {
  const {
    signMessage,
    send,
    writeContract,
    readContract,
    signAndSendTransaction,
  } = useTriaWallet();
  const [message, setMessage] = useState("");

  const handleSignMessage = () => {
    signMessage(message).then((result) => {
      console.log("Message signed:", result);
    });
  };


  return (
    <div>
      <h2 style={{ marginBottom: "20px" }}>Tria Interface</h2>

      <input
        value={message}
        onChange={(e) => {
          console.log(e.target.value);
          setMessage(e.target.value);
        }}
        placeholder="Enter message to sign"
      />
      <button onClick={handleSignMessage}>Sign Message</button>
    </div>
  );
};
Send Transaction
import React, { useEffect, useState } from "react";
import { useTriaAuth, useTriaWallet } from "../src";
const TriaWalletFunctions: React.FC = () => {
  const {
    send,
    signAndSendTransaction,
  } = useTriaWallet();

  const handleSend = () => {
    const amount = 0.01;
    const recipientAddress = "0x59f7843B267E79ea51B687a04Ef497bA240E7B26";
    send(amount, recipientAddress).then((result) => {
      console.log("Transaction sent:", result);
    });
  };

  const handleSignandSend = async () => {
    const walletStore = localStorage.getItem("tria.wallet.store");
    let address = "";
    if (walletStore) {
      address = JSON.parse(walletStore)?.nonEvm[0]?.address;
      console.log("check for mint address", address);
    }
    const payerAddress = "6cQe9dKDiXsSAumxr42y2Gp93LFPDyL9p6kpZ9EL4D9P";
    const apiBaseUrl = "https://dev.tria.so";
    // const apiBaseUrl = "http://localhost:8000"
    const config = {
      method: "get",
      maxBodyLength: Infinity,
      url: `${apiBaseUrl}/api/v2/test/solana/mint?recipientAddress=${address}&mintQuantity=1&payerAddress=${payerAddress}`,
    };

    fetch(config.url, {
      method: config.method,
    })
      .then((response: Response) => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then((data: any) => {
        console.log("first", data);
        signAndSendTransaction({
          encodedTransaction: data.data.encodedTransaction,
        });
      })
      .catch((error: Error) => {
        console.log(error);
      });
  };

  return (
    <div>
      <h2 style={{ marginBottom: "20px" }}>Tria Interface</h2>

      <button onClick={handleSignandSend}>Sign and Send Txn</button>

      <button onClick={handleSend}>Send Transaction</button>
    </div>
  );
};
Mint NFT
import React, { useEffect, useState } from "react";
import { useTriaAuth, useTriaWallet } from "../src";
const TriaWalletFunctions: React.FC = () => {
  const {
    writeContract,
    readContract,
  } = useTriaWallet();


  const handleMint = () => {
    const walletStore = localStorage.getItem("tria.wallet.store");
    let aa;
    if (walletStore) {
      const store = JSON.parse(walletStore);
      aa = store?.aa?.address;
    }
    const contractDetails = {
      contractAddress: "0xFfC6F3186985e963821D3E30Cdb2ec4c0bE110e5",
      abi: [
        {
          inputs: [
            { internalType: "uint256", name: "_tokenId", type: "uint256" },
            { internalType: "uint256", name: "_amount", type: "uint256" },
            { internalType: "address", name: "_claimer", type: "address" },
          ],
          name: "airdropCoupon",
          outputs: [],
          stateMutability: "nonpayable",
          type: "function",
        },
      ],
      functionName: "airdropCoupon",
      args: [1, 1, aa],
    };
    writeContract(contractDetails).then((result) => {
      console.log("Contract written:", result);
    });
  };

  const handleReadNft = () => {
    const contractDetails = {
      contractAddress: "0xFfC6F3186985e963821D3E30Cdb2ec4c0bE110e5",
      abi: [
        {
          inputs: [
            { internalType: "uint256", name: "tokenId", type: "uint256" },
          ],
          name: "uri",
          outputs: [{ internalType: "string", name: "", type: "string" }],
          stateMutability: "view",
          type: "function",
        },
      ],
      functionName: "uri",
      args: ["1"],
    };
    readContract(contractDetails).then((result) => {
      console.log("Contract read:", result);
    });
  };


  return (
    <div>
      <h2 style={{ marginBottom: "20px" }}>Tria Interface</h2>

      <button onClick={handleMint}>Mint NFT</button>

      <button onClick={handleReadNft}>Read NFT</button>
    </div>
  );
};
useEffect(() => {
  if (isReady) {
    // Now you can safely call writeContract
    writeContract(someContractDetails).catch(console.error)
  }
}, [isReady, writeContract])

6. TriaAuthModal Component

For non-modal mode, you can directly render the TriaAuthModal component and set the modalMode prop to false in the initial UI configuration of the TriaProvider. This means that the modal will be rendered automatically as a component and will not be hidden after authentication. You will have to depend on the isAuthenticated flag to ascertain the logged in state to show and hide the modal yourself.

import { TriaAuthModal } from '@tria-sdk/authenticate-react'

function AuthComponent() {
  return (
    <div>
      <TriaAuthModal />
    </div>
  )
}

7. Advanced Configurations

Account Abstraction (AA) Configuration

Configure AA in the triaConfig object:

const triaConfig = {
  // ... other config options
  aa: {
    pimlicoApiKey: 'YOUR_PIMLICO_API_KEY',
    isSponsored: true,
    sponsorshipPolicyIds: {
      FUSE: 'sp_cheerful_thing',
      POLYGON: 'sp_slim_namor',
    },
    accountType: 'Etherspot',
    supportAa: true,
  },
}

Custom Chain Configuration

For custom chains, use the customChain property in triaConfig:

const triaConfig = {
  // ... other config options
  customChain: {
    type: 'EVM',
    chainId: 42161,
    rpcUrl: 'https://arbitrum.llamarpc.com',
    currencySymbol: 'ARB',
    currencyName: 'ARB',
    chainName: 'Arbitrum One',
  },
}

Dynamic Configuration Updates

You can update configurations dynamically using the functions from useTriaAuth:

const { configure, configureUI, configureWalletUI } = useTriaAuth()

// Update SDK configuration
configure({
  chain: 'POLYGON',
  environment: 'mainnet',
})

// Update UI configuration
configureUI({
  darkMode: false,
  showPoweredByTria: false,
})

// Update wallet UI configuration
configureWalletUI({
  darkMode: false,
  primaryColor: '#FF5733',
})

Telegram Mini Apps

To use the sdk in miniapp environment make sure the app is initialised properly according to steps mentioned here https://core.telegram.org/bots/webapps

This in-depth guide covers the major aspects of using the Tria SDK in a React application. Always refer to the latest documentation for any updates or additional features.

Was this page helpful?