Skip to content

feat(balances): TON support #341

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/client/src/getBalances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
getSolanaBalances,
getSplTokenBalances,
getSuiBalances,
getTonBalances,
prepareMulticallContexts,
} from "../../../utils/balances";
import { ZetaChainClient } from "./client";
Expand All @@ -23,6 +24,7 @@ import { ZetaChainClient } from "./client";
* @param options.btcAddress Bitcoin address
* @param options.solanaAddress Solana address
* @param options.suiAddress Sui address
* @param options.tonAddress TON address
* @returns Array of token balances
*/
export const getBalances = async function (
Expand All @@ -32,11 +34,13 @@ export const getBalances = async function (
btcAddress,
solanaAddress,
suiAddress,
tonAddress,
}: {
btcAddress?: string;
evmAddress?: string;
solanaAddress?: string;
suiAddress?: string;
tonAddress?: string;
}
): Promise<TokenBalance[]> {
const foreignCoins = await this.getForeignCoins();
Expand Down Expand Up @@ -140,5 +144,11 @@ export const getBalances = async function (
balances.push(...suiBalances);
}

// Get TON balances
if (tonAddress) {
const tonBalances = await getTonBalances(allTokens, tonAddress);
balances.push(...tonBalances);
}

return balances;
};
14 changes: 13 additions & 1 deletion packages/commands/src/query/balances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const balancesOptionsSchema = z.object({
network: z.enum(["mainnet", "testnet"]).default("testnet"),
solana: z.string().optional(),
sui: z.string().optional(),
ton: z.string().optional(),
});

type BalancesOptions = z.infer<typeof balancesOptionsSchema>;
Expand Down Expand Up @@ -91,7 +92,15 @@ const main = async (options: BalancesOptions) => {
suiAddress: options.sui,
});

if (!evmAddress && !btcAddress && !solanaAddress && !suiAddress) {
const tonAddress = options.ton;

if (
!evmAddress &&
!btcAddress &&
!solanaAddress &&
!suiAddress &&
!tonAddress
) {
spinner.fail("No addresses provided or derivable from account name");
console.error(chalk.red(WALLET_ERROR));
return;
Expand All @@ -108,6 +117,7 @@ const main = async (options: BalancesOptions) => {
evmAddress,
solanaAddress,
suiAddress,
tonAddress,
});

spinner.succeed("Successfully fetched balances");
Expand All @@ -122,6 +132,7 @@ const main = async (options: BalancesOptions) => {
evm: evmAddress,
solana: solanaAddress,
sui: suiAddress,
ton: tonAddress,
});

if (addressesInfo) {
Expand Down Expand Up @@ -149,6 +160,7 @@ export const balancesCommand = new Command("balances")
"Fetch balances for a specific Bitcoin address"
)
.option("--sui <address>", "Fetch balances for a specific Sui address")
.option("--ton <address>", "Fetch balances for a specific TON address")
.option("--name <name>", "Account name")
.addOption(
new Option("--network <network>", "Network to use")
Expand Down
81 changes: 80 additions & 1 deletion utils/balances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { getFullnodeUrl, SuiClient } from "@mysten/sui/client";
import ERC20_ABI from "@openzeppelin/contracts/build/contracts/ERC20.json";
import { getAddress, ParamChainName } from "@zetachain/protocol-contracts";
import ZRC20 from "@zetachain/protocol-contracts/abi/ZRC20.sol/ZRC20.json";
import axios from "axios";
import axios, { AxiosError } from "axios";
import { AbiCoder, ethers } from "ethers";

import {
Expand All @@ -18,6 +18,9 @@ import { ForeignCoin } from "../types/foreignCoins.types";
import { ObserverSupportedChain } from "../types/supportedChains.types";
import { handleError } from "./handleError";

export const TON_MAINNET_API = "https://tonapi.io/v2/accounts";
export const TON_TESTNET_API = "https://testnet.tonapi.io/v2/accounts";

export interface UTXO {
txid: string;
value: number;
Expand Down Expand Up @@ -791,3 +794,79 @@ export const hasSufficientBalanceEvm = async (

return { balance, decimals, hasEnoughBalance };
};

interface TonApiResponse {
address: string;
balance: string | number;
get_methods: string[];
interfaces: string[];
is_wallet: boolean;
last_activity: number;
status: string;
}

/**
* Gets TON native token balances
*/
export const getTonBalances = async (
tokens: Token[],
tonAddress: string
): Promise<TokenBalance[]> => {
const tonToken = tokens.find(
(token) =>
token.coin_type === "Gas" &&
token.chain_name &&
["ton_mainnet", "ton_testnet"].includes(token.chain_name)
);

if (!tonToken) {
return [];
}

try {
const network = tonToken.chain_name?.replace("ton_", "") || "testnet";
const API = network === "mainnet" ? TON_MAINNET_API : TON_TESTNET_API;

const response = await axios.get<TonApiResponse>(`${API}/${tonAddress}`, {
headers: {
Accept: "application/json",
},
});

// Validate response structure
if (!response.data) {
throw new Error("Empty response from TON API");
}

const { balance } = response.data;
if (balance === undefined || balance === null) {
throw new Error(
`Missing balance in TON API response: ${JSON.stringify(response.data)}`
);
}

// TON API returns balance in nanoTON (1 TON = 10^9 nanoTON)
const formattedBalance = ethers.formatUnits(BigInt(balance.toString()), 9);

return [
{
...tonToken,
balance: formattedBalance,
id: parseTokenId(tonToken.chain_id?.toString() || "", tonToken.symbol),
},
];
} catch (error) {
if (error instanceof AxiosError) {
console.error(
`Failed to get TON balance for ${tonToken.chain_name}:`,
error.response?.data || error.message
);
} else {
console.error(
`Failed to get TON balance for ${tonToken.chain_name}:`,
error instanceof Error ? error.message : String(error)
);
}
return [];
}
};
12 changes: 9 additions & 3 deletions utils/formatting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,19 @@ export interface FormatAddressesOptions {
evm?: string;
solana?: string;
sui?: string;
ton?: string;
}

export const formatAddresses = (options: FormatAddressesOptions): string => {
const parts = [];

if (options.evm) {
const evmStr = `EVM: \x1b[36m${options.evm}\x1b[0m`;
const evmStr = `EVM: \x1b[96m${options.evm}\x1b[0m`;
parts.push(evmStr);
}

if (options.bitcoin) {
const btcStr = `Bitcoin: \x1b[33m${options.bitcoin}\x1b[0m`;
const btcStr = `Bitcoin: \x1b[91m${options.bitcoin}\x1b[0m`;
parts.push(btcStr);
}

Expand All @@ -63,10 +64,15 @@ export const formatAddresses = (options: FormatAddressesOptions): string => {
}

if (options.sui) {
const suiStr = `Sui: \x1b[32m${options.sui}\x1b[0m`;
const suiStr = `Sui: \x1b[36m${options.sui}\x1b[0m`;
parts.push(suiStr);
}

if (options.ton) {
const tonStr = `TON: \x1b[94m${options.ton}\x1b[0m`;
parts.push(tonStr);
}

return parts.join("\n");
};

Expand Down