NuxtJS Guide: Using Tria SDK in Nuxt.js (2.x and 3.x)

This guide explains how to integrate the Tria SDK into both Nuxt.js 2.x and 3.x applications. The setup process differs slightly between versions, particularly regarding babel configuration and TypeScript support.

Nuxt.js 2.x Setup

1. Install necessary dependencies

If your Nuxt.js 2.x project doesn't handle optional chaining or nullish coalescing operators, install these Babel plugins:

npm install --save-dev @babel/plugin-proposal-nullish-coalescing-operator @babel/plugin-proposal-optional-chaining

2. Create a plugin

Create a file named auth-manager.js in your plugins folder:

import { AuthManager } from '@tria-sdk/authenticate-web'

export default ({ app }, inject) => {
  const authManager = new AuthManager({
    analyticsKey: {
      clientId: 'YOUR_CLIENT_ID',
      projectId: 'YOUR_PROJECT_ID',
    },
  })

  authManager.configure({
    chain: 'SEPOLIA',
    environment: 'mainnet',
  })

  inject('authManager', authManager)
}

3. Update nuxt.config.js

Add the following to your nuxt.config.js:

export default {
  plugins: [{ src: '~/plugins/auth-manager.js', mode: 'client' }],

  build: {
    babel: {
      plugins: [
        '@babel/plugin-proposal-nullish-coalescing-operator',
        '@babel/plugin-proposal-optional-chaining',
      ],
    },
    transpile: ['@tria-sdk/authenticate-web'],
  },
}

Nuxt.js 3.x Setup

1. Create a plugin

Create a file named auth-manager.ts (or .js if not using TypeScript) in your plugins folder:

import { AuthManager } from '@tria-sdk/authenticate-web'

export default defineNuxtPlugin((nuxtApp) => {
  const authManager = new AuthManager({
    analyticsKey: {
      clientId: 'YOUR_CLIENT_ID',
      projectId: 'YOUR_PROJECT_ID',
    },
  })

  authManager.configure({
    chain: 'SEPOLIA',
    environment: 'mainnet',
  })

  return {
    provide: {
      authManager: authManager,
    },
  }
})

2. Update nuxt.config.ts

Add the following to your nuxt.config.ts:

export default defineNuxtConfig({
  plugins: ['~/plugins/auth-manager'],

  build: {
    transpile: ['@tria-sdk/authenticate-web'],
  },
})

Note: If you're using TypeScript in Nuxt 3.x, you don't need to add the Babel plugins for optional chaining and nullish coalescing as TypeScript handles these features natively.

Usage in Components (Both Versions)

Here's an example of how to use the Tria SDK in a Nuxt.js component:

<template>
  <div class="login-container">
    <button v-if="!isLoggedIn" @click="login" class="login-btn">Login</button>
    <div v-else class="actions-container">
      <div class="action">
        <input
          v-model="message"
          type="text"
          placeholder="Enter a message to sign"
          class="input"
        />
        <button @click="signMessage" class="action-btn">Sign Message</button>
      </div>
      <div class="action">
        <input
          v-model.number="amount"
          type="number"
          placeholder="Enter amount to send"
          class="input"
        />
        <input
          v-model="recipientAddress"
          type="text"
          placeholder="Enter recipient address"
          class="input"
        />
        <button @click="sendTransaction" class="action-btn">
          Send Transaction
        </button>
      </div>
      <div class="action">
        <button @click="writeContract" class="action-btn">
          Write Contract
        </button>
        <button @click="readContract" class="action-btn">Read Contract</button>
      </div>
      <div class="action">
        <button @click="disconnect" class="action-btn">Disconnect</button>
      </div>
      <div class="action">
        <button @click="getAccountInfo" class="action-btn">Get Account</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isLoggedIn: false,
      message: '',
      amount: 0,
      recipientAddress: '',
      account: null,
    }
  },
  mounted() {
    this.checkLoginStatus()
    this.getAccountInfo()
    this.logoutListen()
    this.loginListen()
  },
  methods: {
    checkLoginStatus() {
      console.log('login status', this.$authManager.getAccount())
      if (this.$authManager.getAccount()) {
        console.log('login state', this.$authManager.isLoggedIn)

        this.isLoggedIn = true
      } else {
        this.isLoggedIn = false
      }
    },
    async login() {
        const handleLogin = (): void => {
              console.log("calling handleLogin");
              const resp = authManager.getAccount();
              console.log(resp);
            };

        authManager.subscribe("LOGIN_SUCCESS", handleLogin);
    },
    loginListen() {
      this.$authManager.addEventListener('TRIA_LOGIN', () => {
        console.log('setting login state')
        this.isLoggedIn = true
      })
    },
    logoutListen() {
      this.$authManager.addEventListener('TRIA_LOGOUT', () => {
        this.isLoggedIn = false
      })
    },
    async disconnect() {
      await this.$authManager.disconnect()
      this.isLoggedIn = false
    },
    async signMessage() {
      if (this.message) {
        const result = await this.$authManager.signMessage(this.message)
        console.log('Signed message:', result)
      }
    },
    async sendTransaction() {
      if (this.amount && this.recipientAddress) {
        const result = await this.$authManager.send(
          this.amount,
          this.recipientAddress,
        )
        console.log('Transaction sent:', result)
      }
    },
    async writeContract() {
      const contractDetails = {
        contractAddress: '0x9f5033463b31D213462Ce03A81610364aa80Ba14',
        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: [2, 1, '0xCA679c7e0a1E88C950F71A57dd457A39872DE640'],
      }
      const result = await this.$authManager.writeContract(contractDetails)
      console.log('Contract written:', result)
    },
    async readContract() {
      const contractDetails = {
        contractAddress: '0x9f5033463b31D213462Ce03A81610364aa80Ba14',
        abi: [
          {
            inputs: [
              { internalType: 'uint256', name: 'tokenId', type: 'uint256' },
            ],
            name: 'uri',
            outputs: [{ internalType: 'string', name: '', type: 'string' }],
            stateMutability: 'view',
            type: 'function',
          },
        ],
        functionName: 'uri',
        args: [
          '0xd3b267e459b2dd2d06cad080b75e12cf0ecf35807bb0719ce28f5dd9ae1516cc',
        ],
      }
      const result = await this.$authManager.readContract(contractDetails)
      console.log('Contract read:', result)
    },
    getAccountInfo() {
      this.account = this.$authManager.getAccount()
      console.log('Account:', this.account)
    },
  },
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-btn {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}

.actions-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.action {
  margin-bottom: 20px;
}

.input {
  margin-right: 10px;
  padding: 10px;
  font-size: 14px;
}

.action-btn {
  padding: 10px 20px;
  font-size: 14px;
  cursor: pointer;
}
</style>

Important Notes

  1. For Nuxt.js 2.x, ensure you have the necessary Babel plugins installed and configured if you're using newer JavaScript features.

  2. For Nuxt.js 3.x with TypeScript, you don't need the Babel plugins for optional chaining and nullish coalescing.

  3. In both versions, you need to transpile the @tria-sdk/authenticate-web package.

  4. The plugin setup is slightly different between versions, with Nuxt 3.x using the defineNuxtPlugin helper.

  5. Usage in components remains largely the same across versions, but be aware of potential TypeScript differences if you're using it in Nuxt 3.x.

By following this updated guide, you should be able to successfully integrate the Tria SDK into both Nuxt.js 2.x and 3.x applications, taking into account the specific requirements of each version.

Was this page helpful?