suix_getBalance
Returns the total balance of a specific coin type for a given address on the Sui network.
Overview
The suix_getBalance
method provides a simple way to query the total balance of any coin type owned by an address. This includes native SUI tokens and any custom fungible tokens created on the Sui blockchain. The method aggregates all coin objects of the specified type and returns the total balance.
Parameters
Parameter | Type | Required | Description |
---|---|---|---|
owner | string | Yes | The Sui address to query (66-character hex string with 0x prefix) |
coinType | string | No | The coin type to query (defaults to "0x2::sui::SUI") |
Coin Type Format
The coin type follows the format: packageId::module::type
Common examples:
- SUI:
0x2::sui::SUI
- USDC:
0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC
- Custom tokens:
0xpackage::module::COIN_NAME
Returns
Returns an object containing the total balance information.
Field | Type | Description |
---|---|---|
coinType | string | The type of coin queried |
coinObjectCount | number | Number of coin objects of this type |
totalBalance | string | Total balance across all coin objects (in base units) |
lockedBalance | object | Locked balance information (if applicable) |
Balance Units
- Balances are returned in the smallest unit (e.g., MIST for SUI)
- 1 SUI = 1,000,000,000 MIST (10^9)
- Check coin metadata for decimal places of custom tokens
Code Examples
- cURL
- JavaScript
- Python
# Query SUI balance
curl -X POST https://sui-mainnet.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "suix_getBalance",
"params": [
"0xd77955e670601c2c2e6e8637e383695c166aac0a86b741c266bdfb23c2e3369f",
"0x2::sui::SUI"
],
"id": 1
}'
# Query custom token balance
curl -X POST https://sui-mainnet.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "suix_getBalance",
"params": [
"0xd77955e670601c2c2e6e8637e383695c166aac0a86b741c266bdfb23c2e3369f",
"0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC"
],
"id": 1
}'
import { SuiClient } from '@mysten/sui.js/client';
const client = new SuiClient({
url: 'https://sui-mainnet.dwellir.com/YOUR_API_KEY'
});
// Query SUI balance
async function getSuiBalance(address) {
const balance = await client.getBalance({
owner: address,
coinType: '0x2::sui::SUI' // Optional, defaults to SUI
});
console.log('SUI Balance:', {
total: balance.totalBalance,
inSUI: Number(balance.totalBalance) / 1_000_000_000,
coinCount: balance.coinObjectCount
});
return balance;
}
// Query any token balance
async function getTokenBalance(address, coinType) {
const balance = await client.getBalance({
owner: address,
coinType: coinType
});
return balance;
}
// Example usage
const address = '0xd77955e670601c2c2e6e8637e383695c166aac0a86b741c266bdfb23c2e3369f';
// Get SUI balance
const suiBalance = await getSuiBalance(address);
// Get USDC balance
const usdcBalance = await getTokenBalance(
address,
'0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC'
);
// Convert to human-readable format
function formatBalance(balance, decimals = 9) {
return Number(balance.totalBalance) / Math.pow(10, decimals);
}
console.log(`SUI: ${formatBalance(suiBalance)} SUI`);
console.log(`USDC: ${formatBalance(usdcBalance, 6)} USDC`);
import requests
import json
from decimal import Decimal
class SuiBalanceChecker:
def __init__(self, rpc_url):
self.rpc_url = rpc_url
def get_balance(self, address, coin_type="0x2::sui::SUI"):
"""Query balance for a specific coin type"""
payload = {
"jsonrpc": "2.0",
"method": "suix_getBalance",
"params": [address, coin_type],
"id": 1
}
response = requests.post(
self.rpc_url,
headers={'Content-Type': 'application/json'},
data=json.dumps(payload)
)
result = response.json()
if 'error' in result:
raise Exception(f"RPC Error: {result['error']}")
return result['result']
def format_balance(self, balance_str, decimals=9):
"""Convert balance to human-readable format"""
balance = Decimal(balance_str)
divisor = Decimal(10 ** decimals)
return balance / divisor
# Usage
checker = SuiBalanceChecker('https://sui-mainnet.dwellir.com/YOUR_API_KEY')
# Get SUI balance
address = '0xd77955e670601c2c2e6e8637e383695c166aac0a86b741c266bdfb23c2e3369f'
sui_balance = checker.get_balance(address)
print(f"SUI Balance: {sui_balance['totalBalance']} MIST")
print(f"SUI Balance: {checker.format_balance(sui_balance['totalBalance'])} SUI")
print(f"Coin Objects: {sui_balance['coinObjectCount']}")
# Get USDC balance
usdc_type = '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC'
usdc_balance = checker.get_balance(address, usdc_type)
print(f"USDC Balance: {checker.format_balance(usdc_balance['totalBalance'], 6)} USDC")
Response Example
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"coinType": "0x2::sui::SUI",
"coinObjectCount": 5,
"totalBalance": "12580000000",
"lockedBalance": {
"epochId": 251,
"number": "1000000000"
}
}
}
Practical Examples
Portfolio Balance Tracker
async function getPortfolioBalances(address) {
const tokens = [
{
type: '0x2::sui::SUI',
symbol: 'SUI',
decimals: 9
},
{
type: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC',
symbol: 'USDC',
decimals: 6
},
{
type: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT',
symbol: 'wUSDT',
decimals: 6
}
];
const balances = {};
for (const token of tokens) {
try {
const balance = await client.getBalance({
owner: address,
coinType: token.type
});
balances[token.symbol] = {
raw: balance.totalBalance,
formatted: Number(balance.totalBalance) / Math.pow(10, token.decimals),
coinCount: balance.coinObjectCount
};
} catch (error) {
balances[token.symbol] = {
raw: '0',
formatted: 0,
coinCount: 0
};
}
}
return balances;
}
Balance Monitoring with Threshold Alerts
async function monitorBalance(address, threshold, coinType = '0x2::sui::SUI') {
const balance = await client.getBalance({
owner: address,
coinType: coinType
});
const balanceInSUI = Number(balance.totalBalance) / 1_000_000_000;
if (balanceInSUI < threshold) {
console.warn(`⚠️ Low balance alert!`);
console.warn(`Current balance: ${balanceInSUI} SUI`);
console.warn(`Threshold: ${threshold} SUI`);
// Send notification
await sendLowBalanceNotification(address, balanceInSUI, threshold);
}
return {
isLow: balanceInSUI < threshold,
current: balanceInSUI,
threshold: threshold
};
}
Multi-Address Balance Aggregation
async function getAggregatedBalance(addresses, coinType = '0x2::sui::SUI') {
let totalBalance = BigInt(0);
let totalCoinCount = 0;
const addressBalances = [];
for (const address of addresses) {
const balance = await client.getBalance({
owner: address,
coinType: coinType
});
totalBalance += BigInt(balance.totalBalance);
totalCoinCount += balance.coinObjectCount;
addressBalances.push({
address: address,
balance: balance.totalBalance,
coinCount: balance.coinObjectCount
});
}
return {
totalBalance: totalBalance.toString(),
totalCoinCount: totalCoinCount,
addressBalances: addressBalances,
averageBalance: (totalBalance / BigInt(addresses.length)).toString()
};
}
Working with Different Coin Types
Discovering Coin Types
// First get all coins owned by address
const coins = await client.getAllCoins({
owner: address
});
// Extract unique coin types
const coinTypes = [...new Set(coins.data.map(coin => coin.coinType))];
// Get balance for each type
for (const coinType of coinTypes) {
const balance = await client.getBalance({
owner: address,
coinType: coinType
});
console.log(`${coinType}: ${balance.totalBalance}`);
}
Handling Coin Metadata
async function getBalanceWithMetadata(address, coinType) {
// Get balance
const balance = await client.getBalance({
owner: address,
coinType: coinType
});
// Get coin metadata for decimals and symbol
const metadata = await client.getCoinMetadata({
coinType: coinType
});
// Calculate formatted balance
const formatted = Number(balance.totalBalance) /
Math.pow(10, metadata.decimals);
return {
...balance,
metadata: metadata,
formattedBalance: formatted,
displayString: `${formatted} ${metadata.symbol}`
};
}
Locked Balance Information
The lockedBalance
field appears when tokens are locked (e.g., in staking):
const balance = await client.getBalance({
owner: address,
coinType: '0x2::sui::SUI'
});
if (balance.lockedBalance) {
console.log('Locked Balance:', {
amount: balance.lockedBalance.number,
epochId: balance.lockedBalance.epochId,
unlockEpoch: balance.lockedBalance.epochId + 1
});
const availableBalance =
BigInt(balance.totalBalance) - BigInt(balance.lockedBalance.number);
console.log('Available balance:', availableBalance.toString());
}
Error Handling
async function safeGetBalance(address, coinType) {
try {
const balance = await client.getBalance({
owner: address,
coinType: coinType
});
return {
success: true,
data: balance
};
} catch (error) {
// Handle specific errors
if (error.message.includes('Invalid address')) {
return {
success: false,
error: 'Invalid Sui address format'
};
}
if (error.message.includes('Invalid coin type')) {
return {
success: false,
error: 'Invalid coin type format'
};
}
// Return zero balance for non-existent coin types
return {
success: true,
data: {
coinType: coinType,
coinObjectCount: 0,
totalBalance: '0'
}
};
}
}
Performance Optimization
Batch Balance Queries
async function batchGetBalances(address, coinTypes) {
// Use Promise.all for parallel queries
const balancePromises = coinTypes.map(coinType =>
client.getBalance({ owner: address, coinType })
.catch(err => ({
coinType: coinType,
totalBalance: '0',
coinObjectCount: 0,
error: err.message
}))
);
const balances = await Promise.all(balancePromises);
return balances.reduce((acc, balance, index) => {
acc[coinTypes[index]] = balance;
return acc;
}, {});
}
Related Methods
- sui_executeTransactionBlock - Execute transactions with coins
- sui_getObject - Get detailed object information
Best Practices
- Cache coin metadata to avoid repeated calls for decimals and symbols
- Handle zero balances gracefully for non-existent coin types
- Use BigInt for arithmetic operations to avoid precision loss
- Implement retry logic for network failures
- Batch queries when checking multiple coin types
Need help? Contact our support team or check the Sui documentation.