Skip to content

Getting Started With JavaScript/TypeScript

Install

Using a package manager

npm
npm install @happychain/js

Using a CDN

<script src="https://unpkg.com/@happychain/js@latest/umd/index.umd.js"></script>

Setup

Wallet Component

Once you have installed the SDK, you will need to register the wallet component on the page. The easiest way to acomplish this is by using our provided register method.

Package Manager
import { register } from '@happychain/js'
 
register()

Usage

Web3 Integration

Next you will want to setup your web3 integration using the happyProvider. The HappyProvider is an EIP-1193 EVM provider. This means you can use it to initialize any standard web3 library as you normally would. The most common examples are below, but it should be fully compatible with most libraries.

Viem
import { happyProvider } from '@happychain/js' 
import { createPublicClient, createWalletClient, custom } from "viem"
 
const transport = custom(happyProvider) 
const publicClient = createPublicClient({ transport }) 
const walletClient = createWalletClient({ transport }) 

Getting the Active User

User changes, such as when a user logs in or out, can be subscribed to the onUserUpdate listener. If the user is undefined, then they are not currently logged in have or have logged out. If the user is a HappyUser then it will be populated with all their shared info, such as wallet address and name.

import { onUserUpdate } from '@happychain/js'
 
onUserUpdate((user) => {
    console.log("HappyChain User:", user)
})

Alternatively, the current user Is always exposed via the getCurrentUser call.

import { getCurrentUser } from '@happychain/js'
 
const user = getCurrentUser()
console.log("HappyChain User:", user)

onUserUpdate only fires whenever the user changes, so if you want to have something depend on the current user, you should write your code as follows:

import { type HappyUser, getCurrentUser, onUserUpdate } from '@happychain/js'
 
const doSomethingWithUser = (user?: HappyUser) => {
    console.log("HappyChain User:", user)
}
 
doSomethingWithUser(getCurrentUser())
onUserUpdate(doSomethingWithUser)