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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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;
};
13 changes: 12 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 Down Expand Up @@ -149,6 +159,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
79 changes: 79 additions & 0 deletions utils/balances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
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 @@

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 (axios.isAxiosError(error)) {

Check warning on line 859 in utils/balances.ts

View workflow job for this annotation

GitHub Actions / build

Caution: `axios` also has a named export `isAxiosError`. Check if you meant to write `import {isAxiosError} from 'axios'` instead
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 [];
}
};