Skip to main content

API Methods

Complete reference documentation for all Hashinal Wallet Connect SDK methods.

Method Categories

The SDK provides methods organized into functional categories:

Connection Management

init()

Initializes the SDK with WalletConnect configuration.

ParameterTypeRequiredDescription
projectIdstring✅ YesWalletConnect Cloud Project ID
metadataSignClientTypes.Metadata✅ YesApplication metadata
networkLedgerId❌ NoNetwork selection (default: MAINNET)

Metadata Structure:

interface Metadata {
name: string; // Your app name
description: string; // App description
url: string; // App URL
icons: string[]; // App icon URLs
}

Examples:

UMD (Inscribed HTML)
await window.HashinalsWalletConnectSDK.init(
'your_project_id',
{
name: 'My Hashinal App',
description: 'Inscribed application on Hedera',
url: window.location.href,
icons: ['https://example.com/icon.png']
}
);
ESM (Modern JS)
import { HashinalsWalletConnectSDK } from '@hashgraphonline/hashinal-wc';
import { LedgerId } from '@hashgraph/sdk';

const sdk = HashinalsWalletConnectSDK.getInstance();
await sdk.init(
process.env.WALLETCONNECT_PROJECT_ID,
{
name: 'My dApp',
description: 'Modern Hedera application',
url: 'https://myapp.com',
icons: ['https://myapp.com/icon.png']
},
LedgerId.TESTNET // Optional: specify network
);

connect()

Opens the WalletConnect modal for wallet connection.

ReturnsDescription
Promise<SessionTypes.Struct>WalletConnect session object

Session Object Contains:

  • topic: Unique session identifier
  • namespaces: Connected blockchain namespaces
  • acknowledged: Connection acknowledgment status
  • peer: Connected wallet metadata

Examples:

Complete Connection Flow
try {
// Connect wallet
const session = await sdk.connect();

if (session) {
console.log('Connected to:', session.peer.metadata.name);
console.log('Session topic:', session.topic);

// Get account details
const accountInfo = await sdk.getAccountInfo();
console.log('Account:', accountInfo.accountId);
console.log('Network:', accountInfo.network);
}
} catch (error) {
console.error('Connection failed:', error);
}

disconnect()

Terminates all active wallet connections.

ReturnsDescription
Promise<void>Resolves when disconnection is complete

Example:

await sdk.disconnect();
console.log('Wallet disconnected');

Account Operations

getAccountInfo()

Retrieves the connected account's information.

ReturnsDescription
Promise<{accountId: string, network: string}>Account ID and network

Example:

const info = await sdk.getAccountInfo();
console.log(`Connected: ${info.accountId} on ${info.network}`);
// Output: Connected: 0.0.123456 on mainnet

getAccountBalance()

Gets the HBAR balance of the connected account.

ReturnsDescription
Promise<string>Balance in HBAR (as string)

Example:

const balance = await sdk.getAccountBalance();
console.log(`Balance: ${balance} HBAR`);
// Output: Balance: 150.5 HBAR

createAccount()

Creates a new Hedera account with initial balance.

ParameterTypeRequiredDescription
initialBalancenumber✅ YesInitial balance in HBAR
ReturnsDescription
Promise<TransactionReceipt>Transaction receipt with new account ID

Example:

const receipt = await sdk.createAccount(100); // 100 HBAR initial balance
console.log('New account:', receipt.accountId.toString());

updateAccount()

Updates account properties.

ParameterTypeRequiredDescription
accountIdstring✅ YesAccount to update
maxAutomaticTokenAssociationsnumber✅ YesMax auto token associations

Example:

await sdk.updateAccount('0.0.123456', 10);
console.log('Account updated with 10 automatic token associations');

Transfer Operations

transferHbar()

Transfers HBAR between accounts.

ParameterTypeRequiredDescription
fromAccountIdstring✅ YesSender account
toAccountIdstring✅ YesRecipient account
amountnumber✅ YesAmount in HBAR

Example:

const receipt = await sdk.transferHbar(
'0.0.123456', // from
'0.0.789012', // to
25.5 // amount in HBAR
);
console.log('Transfer complete:', receipt.status);

transferToken()

Transfers fungible tokens between accounts.

ParameterTypeRequiredDescription
tokenIdstring✅ YesToken ID
fromAccountIdstring✅ YesSender account
toAccountIdstring✅ YesRecipient account
amountnumber✅ YesAmount to transfer

Example:

await sdk.transferToken(
'0.0.456789', // token ID
'0.0.123456', // from account
'0.0.789012', // to account
1000 // amount
);

Topic & Messaging

createTopic()

Creates a new HCS topic.

ParameterTypeRequiredDescription
memostring❌ NoTopic memo/description
adminKeystring | PrivateKey❌ NoAdmin key for topic management
submitKeystring | PrivateKey❌ NoSubmit key for access control
ReturnsDescription
Promise<string>New topic ID

Examples:

Public Topic (No Keys)
const topicId = await sdk.createTopic('Public discussion topic');
console.log('Created public topic:', topicId);
Private Topic (With Keys)
import { PrivateKey } from '@hashgraph/sdk';

const adminKey = PrivateKey.generate();
const submitKey = PrivateKey.generate();

const topicId = await sdk.createTopic(
'Private topic',
adminKey.toString(),
submitKey.toString()
);
console.log('Created private topic:', topicId);

submitMessageToTopic()

Submits a message to an HCS topic.

ParameterTypeRequiredDescription
topicIdstring✅ YesTarget topic ID
messagestring✅ YesMessage content
submitKeyPrivateKey❌ NoRequired for private topics

Examples:

Public Topic Message
await sdk.submitMessageToTopic(
'0.0.123456',
JSON.stringify({ type: 'greeting', text: 'Hello Hedera!' })
);
Private Topic Message
import { PrivateKey } from '@hashgraph/sdk';

const submitKey = PrivateKey.fromString('your-submit-key');
await sdk.submitMessageToTopic(
'0.0.123456',
'Private message',
submitKey
);

getMessages()

Retrieves messages from a topic.

ParameterTypeRequiredDescription
topicIdstring✅ YesTopic to query
lastTimestampnumber❌ NoStart timestamp (ms)
disableTimestampFilterboolean❌ NoDisable filtering
ReturnsDescription
Promise<{messages: Array}>Array of topic messages

Message Structure:

interface Message {
consensus_timestamp: string;
message: string; // Base64 encoded
payer_account_id: string;
running_hash: string;
sequence_number: number;
}

Example:

const result = await sdk.getMessages('0.0.123456');
result.messages.forEach(msg => {
const decoded = atob(msg.message);
console.log(`Message #${msg.sequence_number}: ${decoded}`);
});

Token Management

createToken()

Creates a new fungible token.

ParameterTypeRequiredDescription
namestring✅ YesToken name
symbolstring✅ YesToken symbol
initialSupplynumber✅ YesInitial supply
decimalsnumber✅ YesDecimal places
treasuryAccountIdstring✅ YesTreasury account
adminKeystring | PrivateKey✅ YesAdmin key
supplyKeystring | PrivateKey✅ YesSupply key

Example:

const tokenId = await sdk.createToken(
'My Token', // name
'MTK', // symbol
1000000, // initial supply
2, // decimals
'0.0.123456', // treasury
adminKey, // admin key
supplyKey // supply key
);
console.log('Created token:', tokenId);

associateTokenToAccount()

Associates a token with an account.

ParameterTypeRequiredDescription
accountIdstring✅ YesAccount ID
tokenIdstring✅ YesToken ID

Example:

await sdk.associateTokenToAccount('0.0.123456', '0.0.789012');
console.log('Token associated with account');

dissociateTokenFromAccount()

Removes token association from an account.

ParameterTypeRequiredDescription
accountIdstring✅ YesAccount ID
tokenIdstring✅ YesToken ID

Example:

await sdk.dissociateTokenFromAccount('0.0.123456', '0.0.789012');
console.log('Token dissociated from account');

getAccountTokens()

Lists all tokens associated with an account.

ParameterTypeRequiredDescription
accountIdstring✅ YesAccount to query
ReturnsDescription
Promise<Array>Array of token balances

Example:

const tokens = await sdk.getAccountTokens('0.0.123456');
tokens.forEach(token => {
console.log(`Token ${token.token_id}: ${token.balance}`);
});

NFT Operations

mintNFT()

Mints a new NFT for an existing token.

ParameterTypeRequiredDescription
tokenIdstring✅ YesNFT collection token ID
metadatastring✅ YesNFT metadata (URI or data)
supplyKeyPrivateKey✅ YesToken supply key

Example:

import { PrivateKey } from '@hashgraph/sdk';

const supplyKey = PrivateKey.fromString('your-supply-key');
const receipt = await sdk.mintNFT(
'0.0.123456',
'ipfs://QmXxx...', // or 'hcs://1/0.0.xxxxx' for Hashinals
supplyKey
);
console.log('Minted NFT serial:', receipt.serials[0]);

getAccountNFTs()

Retrieves NFTs owned by an account.

ParameterTypeRequiredDescription
accountIdstring✅ YesAccount to query
tokenIdstring❌ NoFilter by specific token

Example:

// Get all NFTs
const allNFTs = await sdk.getAccountNFTs('0.0.123456');

// Get NFTs from specific collection
const collectionNFTs = await sdk.getAccountNFTs('0.0.123456', '0.0.789012');

console.log(`Account owns ${allNFTs.length} NFTs`);

validateNFTOwnership()

Verifies NFT ownership.

ParameterTypeRequiredDescription
serialNumberstring✅ YesNFT serial number
accountIdstring✅ YesAccount to verify
tokenIdstring✅ YesToken ID
ReturnsDescription
Promise<NFT | null>NFT details if owned, null otherwise

Example:

const nft = await sdk.validateNFTOwnership('1', '0.0.123456', '0.0.789012');
if (nft) {
console.log('NFT verified:', nft);
} else {
console.log('Account does not own this NFT');
}

Smart Contract Operations

executeSmartContract()

Executes a smart contract function.

ParameterTypeRequiredDescription
contractIdstring✅ YesContract ID
functionNamestring✅ YesFunction to call
parametersContractFunctionParameters✅ YesFunction parameters
gasnumber❌ NoGas limit (default: 100000)

Example:

import { ContractFunctionParameters } from '@hashgraph/sdk';

const params = new ContractFunctionParameters()
.addString('Hello')
.addUint256(42);

const receipt = await sdk.executeSmartContract(
'0.0.123456', // contract ID
'myFunction', // function name
params, // parameters
150000 // gas limit
);
console.log('Contract executed:', receipt.status);

readSmartContract()

Makes a read-only contract call via mirror node.

ParameterTypeRequiredDescription
datastring✅ YesEncoded function call data
fromAccountAccountId✅ YesCalling account
contractIdContractId✅ YesContract to call
estimateboolean❌ NoEstimate gas only
valuenumber❌ NoHBAR to send

Example:

import { AccountId, ContractId } from '@hashgraph/sdk';

const result = await sdk.readSmartContract(
'0x...', // encoded function call
AccountId.fromString('0.0.123456'),
ContractId.fromString('0.0.789012')
);
console.log('Contract state:', result);

Query Operations

getTransaction()

Retrieves transaction details by ID.

ParameterTypeRequiredDescription
transactionIdstring✅ YesTransaction ID

Example:

const tx = await sdk.getTransaction('0.0.123456@1234567890.000000000');
console.log('Transaction:', tx);

getTransactionByTimestamp()

Retrieves transaction by consensus timestamp.

ParameterTypeRequiredDescription
timestampstring✅ YesConsensus timestamp

Example:

const tx = await sdk.getTransactionByTimestamp('1234567890.000000000');
console.log('Transaction:', tx);

Error Handling

The SDK throws descriptive errors that should be handled appropriately:

try {
await sdk.transferHbar(from, to, amount);
} catch (error) {
if (error.message.includes('INSUFFICIENT_PAYER_BALANCE')) {
console.error('Insufficient balance for transfer');
} else if (error.message.includes('USER_REJECTED')) {
console.error('User rejected the transaction');
} else {
console.error('Transaction failed:', error.message);
}
}

Common Error Types

ErrorDescriptionSolution
USER_REJECTEDUser declined in walletHandle gracefully
INSUFFICIENT_PAYER_BALANCENot enough HBARCheck balance first
INVALID_ACCOUNT_IDMalformed account IDValidate format
TOKEN_NOT_ASSOCIATEDToken not associatedAssociate token first
INVALID_SIGNATUREKey mismatchVerify keys

Best Practices

1. Always Initialize First

// ✅ Good
await sdk.init(projectId, metadata);
const session = await sdk.connect();

// ❌ Bad - not initialized
const session = await sdk.connect(); // Will fail

2. Handle Connection State

let isConnected = false;

async function ensureConnected() {
if (!isConnected) {
const session = await sdk.connect();
isConnected = !!session;
}
return isConnected;
}

3. Validate Inputs

function validateAccountId(accountId) {
const pattern = /^\d+\.\d+\.\d+$/;
if (!pattern.test(accountId)) {
throw new Error('Invalid account ID format');
}
}

4. Use Environment Variables

const PROJECT_ID = process.env.VITE_WALLETCONNECT_PROJECT_ID;
if (!PROJECT_ID) {
throw new Error('WalletConnect Project ID not configured');
}

TypeScript Support

The SDK includes full TypeScript definitions:

import { 
HashinalsWalletConnectSDK,
TransactionReceipt,
SessionTypes
} from '@hashgraphonline/hashinal-wc';

const sdk: HashinalsWalletConnectSDK = HashinalsWalletConnectSDK.getInstance();

async function typedExample(): Promise<void> {
const session: SessionTypes.Struct = await sdk.connect();
const receipt: TransactionReceipt = await sdk.transferHbar(
'0.0.123456',
'0.0.789012',
10
);
}