npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@tria-sdk/authenticate-react

v2.0.8

Published

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

Downloads

605

Readme

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]

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

initialConfig object for TriaProvider

| Property | Type | Description | Default | | --------------- | ----------------------------------------- | -------------------------------------------- | --------- | | analyticsKeys | { clientId: string, projectId: string } | Required keys for analytics | - | | chain | string | Blockchain network (e.g., 'FUSE', 'POLYGON') | - | | customChain | object | Custom chain configuration | - | | environment | 'testnet' | 'mainnet' | Network environment | 'mainnet' | | dappDetails | { dappDomain: string, dappLogo: string } | Dapp-specific details | - | | aa | object | Account Abstraction details | - | | rpcUrl | string | Custom RPC URL | - | | triaStaging | string | boolean | Staging environment flag | false | | supportedChains | string[] | List of supported chains | [] |

initialUIConfig object for TriaProvider

| Property | Type | Description | Default | | ------------------------ | -------- | ------------------------------------ | ------------------------------------------------- | | modalMode | boolean | Enable modal mode for auth | true | | darkMode | boolean | Enable dark mode | true | | dappName | string | Name of your dapp | 'My Dapp' | | headerText | string | Header text for auth modal | 'Get Started' | | showHeader | boolean | Show header in auth modal | true | | showPoweredByTria | boolean | Show 'Powered by Tria' | true | | googleButtonText | string | Text for Google login button | 'Continue with Gmail' | | twitterButtonText | string | Text for Twitter login button | 'Continue with X' | | appleButtonText | string | Text for Apple login button | 'Continue with Apple' | | phoneOtpButtonText | string | Text for phone/email login button | 'Continue with Email/Phone' | | showDivider | boolean | Show divider in auth modal | true | | showHeadingPill | boolean | Show heading pill | true | | OtpHeader | string | Header for OTP screen | 'Enter OTP' | | OtpSubHeader | string | Sub-header for OTP screen | 'Verify your account using 6-digit code sent to:' | | OtpRetryCaption | string | Text for OTP resend button | 'Resend' | | usernameHeadingText | string | Header for username creation | 'Create Tria name' | | usernameSubHeadingText | string | Sub-header for username creation | 'This will be your in-game name.' | | otpBgColor | string | Background color for OTP input | '#ffffff00' | | otpTextColor | string | Text color for OTP input | '#FFFFFF' | | otpBoxBgColor | string | Background color for OTP input boxes | '#00000066' | | otpBorderColor | string | Border color for OTP input boxes | '#FFFFFF66' | | passwordInputBgColor | string | Background color for password input | 'rgba(255, 255, 255, 0.05)' | | passwordInputTextColor | string | Text color for password input | '#ffffff' | | passwordInputBorderColor | string | Border color for password input | 'rgba(255, 255, 255, 0.25)' | | showCloseButton | boolean | Show close button in auth modal | true | | layout | string[] | Order of auth options | ['email-phone', 'web2', 'divider', 'web3'] | | emailPhoneLoginMethods | string[] | Enabled email/phone login methods | ['email', 'phone'] | | web2LoginMethods | string[] | Enabled Web2 login methods | ['google', 'twitter', 'apple', 'discord'] | | web3LoginMethods | string[] | Enabled Web3 login methods | ['metamask', 'walletconnect'] | | enablePasswordLogin | boolean | Enable password-based login | false |

initialWalletUIConfig object for TriaProvider

| Property | Type | Description | Default | | -------------------- | ------- | ------------------------------------ | --------- | | darkMode | boolean | Enable dark mode for wallet | true | | primaryColor | string | Primary color for wallet UI | '#7D40FF' | | customTriggerID | string | Custom ID for wallet trigger element | - | | walletPosition | string | Position of wallet UI | - | | transactionsUIConfig | object | Configuration for transaction UI | - |

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 "@tria-sdk/authenticate-react";

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>
  );
}

| Name | Type | Description | | ----------------------- | -------- | ----------------------------------------- | | showAuthModal | function | Display the auth modal (modal mode only) | | closeAuthModal | function | Close the auth modal (modal mode only) | | logout | function | Log out the current user | | getAccount | function | Get the current user's account details | | isAuthenticated | boolean | Whether a user is currently authenticated | | userState | object | Current user state information | | checkForTelegramMiniApp | function | Check if running as a Telegram Mini App | | configure | function | Update SDK configuration | | configureUI | function | Update UI configuration | | configureWalletUI | function | Update 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 { useTriaWallet, useTriaAuth } from "@tria-sdk/authenticate-react";

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;

| Name | Type | Description | | ------------- | -------- | ------------------------------------------------------- | | isReady | boolean | Whether the wallet is ready for operations | | send | function | Send a transaction | | signMessage | function | Sign a message | | writeContract | function | Write to a smart contract | | readContract | function | Read from a smart contract | | sendNft | function | Send an NFT | | checkBio | function | Check biometric authentication (for Telegram Mini Apps) |

import React, { useEffect, useState } from "react";
import { useTriaWallet } from "@tria-sdk/authenticate-react";

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>
  );
};
import React, { useEffect, useState } from "react";
import { useTriaWallet, useTriaAuth } from "@tria-sdk/authenticate-react";

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>
  );
};
import React, { useEffect, useState } from "react";
import { useTriaWallet, useTriaAuth } from "@tria-sdk/authenticate-react";

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",
});

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.