@goodsdks/identity-sdk
v1.0.5
Published
`identity-sdk` is a comprehensive library designed to interact seamlessly with GoodDollar's Identity smart contracts. It leverages both **Viem** and **Wagmi** SDKs to provide robust functionalities for managing a user's G$ identity on the blockchain. Whet
Readme
Identity SDK
identity-sdk is a comprehensive library designed to interact seamlessly with GoodDollar's Identity smart contracts. It leverages both Viem and Wagmi SDKs to provide robust functionalities for managing a user's G$ identity on the blockchain. Whether you're building a frontend application or integrating backend services, identity-sdk offers the tools you need to handle identity verification and work with a uniquely identified user in your dapp or service.
Table of Contents
Installation
To integrate identity-sdk into your project, you can easily install it from npm:
npm install @goodsdks/identity-sdkor if you prefer using Yarn:
yarn add @goodsdks/identity-sdkGetting Started
Using the Wagmi SDK
The Identity SDK is built on top of Wagmi and provides a React hook for interacting with the Identity smart contracts. It abstracts the complexity of blockchain interactions, making it easier to integrate identity functionalities into your React applications.
Initialization
First, ensure that you have set up Wagmi in your React application. Then, import and use the useIdentitySDK hook as shown below.
import React from 'react';
import { WagmiProvider } from 'wagmi';
import { useIdentitySDK } from './wagmi-sdk';
const IdentityComponent = () => {
const identitySDK = useIdentitySDK('production');
const checkWhitelistedRoot = async (account: string) => {
try {
const { isWhitelisted, root } = await identitySDK.getWhitelistedRoot(account);
console.log(`Is Whitelisted: ${isWhitelisted}, Root: ${root}`);
} catch (error) {
console.error(error);
}
};
return (
<div>
<button onClick={() => checkWhitelistedRoot('0xYourEthereumAddress')}>
Check Whitelisted Root
</button>
</div>
);
};
const App = () => (
<WagmiProvider>
<IdentityComponent />
</WagmiProvider>
);
export default App;Using the Viem SDK
The Viem SDK provides a set of utility functions to interact directly with the Identity smart contracts. It is suitable for backend services or environments where React is not used.
Initialization
import { PublicClient, WalletClient } from "viem"
import { initializeIdentityContract, IdentitySDK } from "./viem-sdk"
const publicClient = new PublicClient({
/* configuration */
})
const walletClient = new WalletClient({
/* configuration */
})
const contractAddress = "0xYourContractAddress"
const identitySDK = new IdentitySDK(publicClient, walletClient, "production")API Reference
Wagmi SDK
useIdentitySDK
A React hook that provides various identity-related functionalities.
Usage:
const identitySDK = useIdentitySDK(env?: contractEnv);Parameters:
env(optional): The environment to use ('production'by default).
Returns:
An IdentitySDK instance or null if the required clients are not available.
Available Methods in the Identity SDK:
getWhitelistedRoot(account: Address): Promise<{ isWhitelisted: boolean; root: Address }>getIdentityExpiryData(account: Address): Promise<IdentityExpiryData>generateFVLink(popupMode?: boolean, callbackUrl?: string, chainId?: number): Promise<string>submitAndWait(params: SimulateContractParameters, onHash?: (hash:0x${string}) => void): Promise<any>calculateIdentityExpiry(lastAuthenticated: bigint, authPeriod: bigint): IdentityExpiry
Viem SDK
initializeIdentityContract
Initializes the Identity contract instance.
Usage:
const identityContract = initializeIdentityContract(
publicClient,
contractAddress,
)Parameters:
publicClient: An instance ofPublicClientfrom Viem.contractAddress: The address of the Identity contract.
Returns:
An IdentityContract object encapsulating the contract address and client.
IdentitySDK Class
Handles interactions with the Identity Contract.
Constructor:
new IdentitySDK(publicClient: PublicClient, walletClient: WalletClient & WalletActions, env?: contractEnv)Parameters:
publicClient: ThePublicClientinstance.walletClient: TheWalletClientwith wallet actions.env(optional): The environment to use ("production" | "staging" | "development"), defaults to"production".
Methods:
submitAndWaitSubmits a transaction and waits for its receipt.
Usage:
const receipt = await identitySDK.submitAndWait(params, onHashCallback)Parameters:
params: Parameters for simulating the contract call (SimulateContractParameters).onHash(optional): A callback function that receives the transaction hash.
Returns:
A transaction receipt upon successful submission.
getWhitelistedRootReturns the whitelist status of a main account or any connected account.
Usage:
const { isWhitelisted, root } = await identitySDK.getWhitelistedRoot(accountAddress)Parameters:
account: The account address to check.
Returns:
An object containing:
isWhitelisted:booleanindicating if the account is whitelisted.root: The root address associated with the account.
getIdentityExpiryDataRetrieves identity expiry data for a given account.
Usage:
const expiryData = await identitySDK.getIdentityExpiryData(accountAddress)Parameters:
account: The account address.
Returns:
An
IdentityExpiryDataobject containing:lastAuthenticated: The timestamp of last authentication.authPeriod: The authentication period.
generateFVLinkGenerates a Face Verification Link.
Usage:
const fvLink = await identitySDK.generateFVLink( popupMode, callbackUrl, chainId, )Parameters:
popupMode(optional):booleanindicating whether to generate a popup link.callbackUrl(optional): The URL to callback after verification.chainId(optional): The blockchain network ID.
Returns:
A
stringcontaining the generated Face Verification link.calculateIdentityExpiryCalculates the identity expiry timestamp.
Usage:
const identityExpiry = identitySDK.calculateIdentityExpiry( lastAuthenticated, authPeriod, )Parameters:
lastAuthenticated: The timestamp of last authentication (bigint).authPeriod: The authentication period (bigint).
Returns:
An
IdentityExpiryobject containing:expiryTimestamp: The calculated expiry timestamp.
Example Usage
Wagmi SDK Example
Below is a practical example demonstrating how to use the Wagmi SDK to check if a user is whitelisted, retrieve identity expiry data, and generate a Face Verification link.
import React, { useState } from 'react';
import { WagmiProvider } from 'wagmi';
import { useIdentitySDK } from './wagmi-sdk';
const IdentityExample = () => {
const identitySDK = useIdentitySDK('production');
const [account, setAccount] = useState<string>('');
const [whitelistStatus, setWhitelistStatus] = useState<{ isWhitelisted: boolean; root: string } | null>(null);
const [expiryData, setExpiryData] = useState<IdentityExpiryData | null>(null);
const [fvLink, setFvLink] = useState<string>('');
const handleCheckWhitelist = async () => {
try {
const result = await identitySDK.getWhitelistedRoot(account);
setWhitelistStatus(result);
console.log(`Whitelisted: ${result.isWhitelisted}, Root: ${result.root}`);
} catch (error) {
console.error(error);
}
};
const handleGetExpiryData = async () => {
try {
const data = await identitySDK.getIdentityExpiryData(account);
setExpiryData(data);
console.log(`Last Authenticated: ${data.lastAuthenticated}, Auth Period: ${data.authPeriod}`);
} catch (error) {
console.error(error);
}
};
const handleGenerateFVLink = async () => {
try {
const link = await identitySDK.generateFVLink(false, 'https://yourapp.com/callback', 1);
setFvLink(link);
console.log(`Face Verification Link: ${link}`);
} catch (error) {
console.error(error);
}
};
return (
<div>
<h1>Identity SDK Example</h1>
<input
type="text"
placeholder="Enter Ethereum Address"
value={account}
onChange={(e) => setAccount(e.target.value)}
/>
<button onClick={handleCheckWhitelist}>Check Whitelist Status</button>
{whitelistStatus && (
<p>
{whitelistStatus.isWhitelisted
? `User is whitelisted. Root: ${whitelistStatus.root}`
: 'User is not whitelisted.'}
</p>
)}
<button onClick={handleGetExpiryData}>Get Identity Expiry Data</button>
{expiryData && (
<p>
Last Authenticated: {expiryData.lastAuthenticated.toString()}, Auth Period: {expiryData.authPeriod.toString()} seconds
</p>
)}
<button onClick={handleGenerateFVLink}>Generate Face Verification Link</button>
{fvLink && (
<p>
<a href={fvLink} target="_blank" rel="noopener noreferrer">
Verify Your Identity
</a>
</p>
)}
</div>
);
};
const App = () => (
<WagmiProvider>
<IdentityExample />
</WagmiProvider>
);
export default App;