492 lines
17 KiB
TypeScript
492 lines
17 KiB
TypeScript
/**
|
|
* Wallet read-only operations across chains: balance + tx history.
|
|
* Server-side signing now lives in `wallet-signer.service.ts` (custodial).
|
|
*/
|
|
import { ethers } from 'ethers';
|
|
import { env } from '../config/env';
|
|
|
|
export type ChainCode = 'ETH' | 'BTC' | 'SOL' | 'TRX' | 'BSC';
|
|
|
|
const TIMEOUT_MS = 15_000;
|
|
|
|
// ── External APIs ──
|
|
const BLOCKSTREAM = 'https://blockstream.info/api';
|
|
const TRONGRID = 'https://api.trongrid.io';
|
|
const BSC_RPC = 'https://bsc-dataseed.binance.org';
|
|
const ETH_RPC = 'https://ethereum-rpc.publicnode.com';
|
|
const SOL_RPC = 'https://api.mainnet-beta.solana.com';
|
|
|
|
const USDT_TRC20 = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
|
|
const USDT_BEP20 = '0x55d398326f99059fF775485246999027B3197955';
|
|
const USDT_ERC20 = '0xdAC17F958D2ee523a2206206994597C13D831ec7';
|
|
|
|
const ERC20_ABI = [
|
|
'function balanceOf(address owner) view returns (uint256)',
|
|
'function transfer(address to, uint256 amount) returns (bool)',
|
|
'function decimals() view returns (uint8)',
|
|
];
|
|
|
|
// ─────────────────────── BALANCE ───────────────────────
|
|
|
|
export interface BalanceResult {
|
|
chain: ChainCode;
|
|
address: string;
|
|
native: string; // в smallest units (satoshi/wei/lamports/sun)
|
|
tokens?: Record<string, string>; // например { USDT: "12345678" }
|
|
}
|
|
|
|
export async function getBalance(chain: ChainCode, address: string): Promise<BalanceResult> {
|
|
switch (chain) {
|
|
case 'BTC':
|
|
return { chain, address, native: await btcBalance(address) };
|
|
case 'TRX': {
|
|
const { trx, usdt } = await trxBalance(address);
|
|
return { chain, address, native: trx, tokens: { USDT: usdt } };
|
|
}
|
|
case 'BSC': {
|
|
const { native, tokens } = await evmBalance(BSC_RPC, address, [{ symbol: 'USDT', addr: USDT_BEP20 }]);
|
|
return { chain, address, native, tokens };
|
|
}
|
|
case 'ETH': {
|
|
const { native, tokens } = await evmBalance(ETH_RPC, address, [{ symbol: 'USDT', addr: USDT_ERC20 }]);
|
|
return { chain, address, native, tokens };
|
|
}
|
|
case 'SOL':
|
|
return { chain, address, native: await solBalance(address) };
|
|
}
|
|
}
|
|
|
|
async function btcBalance(address: string): Promise<string> {
|
|
const res = await fetchJson(`${BLOCKSTREAM}/address/${address}`);
|
|
const stats = res.chain_stats;
|
|
const sat = BigInt(stats.funded_txo_sum) - BigInt(stats.spent_txo_sum);
|
|
return sat.toString();
|
|
}
|
|
|
|
async function trxBalance(address: string): Promise<{ trx: string; usdt: string }> {
|
|
const headers: Record<string, string> = { Accept: 'application/json' };
|
|
if (env.tronApiKey) headers['TRON-PRO-API-KEY'] = env.tronApiKey;
|
|
|
|
const accRes = await fetchJson(`${TRONGRID}/v1/accounts/${address}`, { headers });
|
|
const trx = accRes.data?.[0]?.balance ? String(accRes.data[0].balance) : '0';
|
|
|
|
// USDT TRC20 balance
|
|
const usdtRes = await fetchJson(`${TRONGRID}/wallet/triggerconstantcontract`, {
|
|
method: 'POST',
|
|
headers: { ...headers, 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
owner_address: address,
|
|
contract_address: USDT_TRC20,
|
|
function_selector: 'balanceOf(address)',
|
|
parameter: tronAddressToHex(address).padStart(64, '0'),
|
|
visible: true,
|
|
}),
|
|
});
|
|
const usdtHex = usdtRes.constant_result?.[0];
|
|
const usdt = usdtHex && !/^0+$/.test(usdtHex) ? BigInt('0x' + usdtHex).toString() : '0';
|
|
|
|
return { trx, usdt };
|
|
}
|
|
|
|
async function evmBalance(
|
|
rpc: string,
|
|
address: string,
|
|
tokens: { symbol: string; addr: string }[],
|
|
): Promise<{ native: string; tokens: Record<string, string> }> {
|
|
const provider = new ethers.providers.StaticJsonRpcProvider(rpc);
|
|
const native = await withTimeout(provider.getBalance(address), TIMEOUT_MS, 'EVM balance timeout');
|
|
|
|
const tokenBalances: Record<string, string> = {};
|
|
await Promise.all(
|
|
tokens.map(async ({ symbol, addr }) => {
|
|
try {
|
|
const c = new ethers.Contract(addr, ERC20_ABI, provider);
|
|
const bal: ethers.BigNumber = await withTimeout(c.balanceOf(address), TIMEOUT_MS, `${symbol} balance timeout`);
|
|
tokenBalances[symbol] = bal.toString();
|
|
} catch {
|
|
tokenBalances[symbol] = '0';
|
|
}
|
|
}),
|
|
);
|
|
|
|
return { native: native.toString(), tokens: tokenBalances };
|
|
}
|
|
|
|
async function solBalance(address: string): Promise<string> {
|
|
const res = await fetchJson(SOL_RPC, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 1,
|
|
method: 'getBalance',
|
|
params: [address],
|
|
}),
|
|
});
|
|
return String(res.result?.value ?? 0);
|
|
}
|
|
|
|
// ─────────────────────── TRANSACTIONS ───────────────────────
|
|
|
|
export interface TxItem {
|
|
txid: string;
|
|
timestamp: number | null; // unix seconds
|
|
direction: 'in' | 'out' | 'self';
|
|
amount?: string;
|
|
token?: string;
|
|
to?: string;
|
|
from?: string;
|
|
}
|
|
|
|
export async function getTransactions(chain: ChainCode, address: string, limit: number): Promise<TxItem[]> {
|
|
switch (chain) {
|
|
case 'BTC':
|
|
return btcTransactions(address, limit);
|
|
case 'TRX':
|
|
return trxTransactions(address, limit);
|
|
case 'BSC':
|
|
return scanTransactions('https://api.bscscan.com/api', env.bscscanApiKey, address, limit);
|
|
case 'ETH':
|
|
return scanTransactions('https://api.etherscan.io/api', env.etherscanApiKey, address, limit);
|
|
case 'SOL':
|
|
return solTransactions(address, limit);
|
|
}
|
|
}
|
|
|
|
async function scanTransactions(
|
|
apiBase: string,
|
|
apiKey: string | null,
|
|
address: string,
|
|
limit: number,
|
|
): Promise<TxItem[]> {
|
|
if (!apiKey) return [];
|
|
|
|
const url = new URL(apiBase);
|
|
url.searchParams.set('module', 'account');
|
|
url.searchParams.set('action', 'txlist');
|
|
url.searchParams.set('address', address);
|
|
url.searchParams.set('startblock', '0');
|
|
url.searchParams.set('endblock', '99999999');
|
|
url.searchParams.set('page', '1');
|
|
url.searchParams.set('offset', String(Math.min(limit, 100)));
|
|
url.searchParams.set('sort', 'desc');
|
|
url.searchParams.set('apikey', apiKey);
|
|
|
|
const res = await fetchJson(url.toString());
|
|
if (res.status !== '1' || !Array.isArray(res.result)) return [];
|
|
|
|
return (res.result as any[]).slice(0, limit).map((tx) => {
|
|
const isOut = String(tx.from).toLowerCase() === address.toLowerCase();
|
|
return {
|
|
txid: tx.hash,
|
|
timestamp: tx.timeStamp ? parseInt(tx.timeStamp, 10) : null,
|
|
direction: (isOut ? 'out' : 'in') as TxItem['direction'],
|
|
amount: tx.value || undefined,
|
|
from: tx.from,
|
|
to: tx.to,
|
|
};
|
|
});
|
|
}
|
|
|
|
async function btcTransactions(address: string, limit: number): Promise<TxItem[]> {
|
|
const txs = await fetchJson(`${BLOCKSTREAM}/address/${address}/txs`);
|
|
return (txs as any[]).slice(0, limit).map((tx) => {
|
|
const inSelf = tx.vin.some((v: any) => v.prevout?.scriptpubkey_address === address);
|
|
const outSelf = tx.vout.some((v: any) => v.scriptpubkey_address === address);
|
|
const direction: TxItem['direction'] = inSelf && outSelf ? 'self' : inSelf ? 'out' : 'in';
|
|
return {
|
|
txid: tx.txid,
|
|
timestamp: tx.status?.block_time ?? null,
|
|
direction,
|
|
amount: String(
|
|
tx.vout
|
|
.filter((v: any) => (direction === 'in' ? v.scriptpubkey_address === address : v.scriptpubkey_address !== address))
|
|
.reduce((s: bigint, v: any) => s + BigInt(v.value), 0n),
|
|
),
|
|
};
|
|
});
|
|
}
|
|
|
|
async function trxTransactions(address: string, limit: number): Promise<TxItem[]> {
|
|
const headers: Record<string, string> = { Accept: 'application/json' };
|
|
if (env.tronApiKey) headers['TRON-PRO-API-KEY'] = env.tronApiKey;
|
|
|
|
const res = await fetchJson(
|
|
`${TRONGRID}/v1/accounts/${address}/transactions?limit=${limit}`,
|
|
{ headers },
|
|
);
|
|
return ((res.data as any[]) || []).slice(0, limit).map((tx) => {
|
|
const contract = tx.raw_data?.contract?.[0];
|
|
const value = contract?.parameter?.value;
|
|
const fromAddr = value?.owner_address ? hexToTron(value.owner_address) : '';
|
|
const toAddr = value?.to_address ? hexToTron(value.to_address) : '';
|
|
const isOut = fromAddr === address;
|
|
return {
|
|
txid: tx.txID,
|
|
timestamp: tx.block_timestamp ? Math.floor(tx.block_timestamp / 1000) : null,
|
|
direction: (isOut ? 'out' : 'in') as TxItem['direction'],
|
|
amount: value?.amount ? String(value.amount) : undefined,
|
|
from: fromAddr || undefined,
|
|
to: toAddr || undefined,
|
|
};
|
|
});
|
|
}
|
|
|
|
async function solTransactions(address: string, limit: number): Promise<TxItem[]> {
|
|
const res = await fetchJson(SOL_RPC, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 1,
|
|
method: 'getSignaturesForAddress',
|
|
params: [address, { limit }],
|
|
}),
|
|
});
|
|
return ((res.result as any[]) || []).map((sig) => ({
|
|
txid: sig.signature,
|
|
timestamp: sig.blockTime ?? null,
|
|
direction: 'self' as const, // без deep parsing — направление неизвестно
|
|
}));
|
|
}
|
|
|
|
// ─────────────────────── HELPERS ───────────────────────
|
|
// (buildSend + chain-specific builders deleted — server signs custodially via wallet-signer.service.ts)
|
|
|
|
/* deleted-marker-begin
|
|
export interface BuildSendParams {
|
|
chain: ChainCode;
|
|
from: string;
|
|
to: string;
|
|
amount: string;
|
|
token?: string;
|
|
}
|
|
|
|
export type UnsignedTx =
|
|
| { kind: 'btc'; from: string; to: string; amountSat: string; utxos: any[]; feeRateSatPerVb: number }
|
|
| { kind: 'tron'; transaction: any }
|
|
| { kind: 'evm'; to: string; data: string; value: string; chainId: number; gasLimit?: string }
|
|
| { kind: 'solana'; instructions: any; recentBlockhash: string };
|
|
|
|
export async function buildSend(p: BuildSendParams): Promise<UnsignedTx> {
|
|
switch (p.chain) {
|
|
case 'BTC':
|
|
return buildBtcSend(p);
|
|
case 'TRX':
|
|
return buildTrxSend(p);
|
|
case 'BSC':
|
|
return buildEvmSend(p, BSC_RPC, 56, USDT_BEP20);
|
|
case 'ETH':
|
|
return buildEvmSend(p, ETH_RPC, 1, USDT_ERC20);
|
|
case 'SOL':
|
|
return buildSolSend(p);
|
|
}
|
|
}
|
|
|
|
async function buildBtcSend(p: BuildSendParams): Promise<UnsignedTx> {
|
|
if (p.token) throw new Error('BTC tokens not supported');
|
|
const utxos = await fetchJson(`${BLOCKSTREAM}/address/${p.from}/utxo`);
|
|
const fees = await fetchJson(`${BLOCKSTREAM}/fee-estimates`);
|
|
const confirmed = ((utxos as any[]) || []).filter((u) => u.status?.confirmed);
|
|
|
|
return {
|
|
kind: 'btc',
|
|
from: p.from,
|
|
to: p.to,
|
|
amountSat: p.amount,
|
|
utxos: confirmed.map((u) => ({ txid: u.txid, vout: u.vout, value: u.value })),
|
|
feeRateSatPerVb: Math.ceil((fees as any)['3'] ?? (fees as any)['6'] ?? 5),
|
|
};
|
|
}
|
|
|
|
async function buildTrxSend(p: BuildSendParams): Promise<UnsignedTx> {
|
|
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
|
if (env.tronApiKey) headers['TRON-PRO-API-KEY'] = env.tronApiKey;
|
|
|
|
if (!p.token) {
|
|
// Native TRX
|
|
const res = await fetchJson(`${TRONGRID}/wallet/createtransaction`, {
|
|
method: 'POST',
|
|
headers,
|
|
body: JSON.stringify({ owner_address: p.from, to_address: p.to, amount: Number(p.amount), visible: true }),
|
|
});
|
|
return { kind: 'tron', transaction: res };
|
|
}
|
|
|
|
if (p.token.toUpperCase() === 'USDT') {
|
|
// TRC20 USDT
|
|
const param = tronAddressToHex(p.to).padStart(64, '0') + BigInt(p.amount).toString(16).padStart(64, '0');
|
|
const res = await fetchJson(`${TRONGRID}/wallet/triggersmartcontract`, {
|
|
method: 'POST',
|
|
headers,
|
|
body: JSON.stringify({
|
|
owner_address: p.from,
|
|
contract_address: USDT_TRC20,
|
|
function_selector: 'transfer(address,uint256)',
|
|
parameter: param,
|
|
fee_limit: 100_000_000,
|
|
call_value: 0,
|
|
visible: true,
|
|
}),
|
|
});
|
|
return { kind: 'tron', transaction: res };
|
|
}
|
|
|
|
throw new Error(`Token ${p.token} not supported on TRX`);
|
|
}
|
|
|
|
async function buildEvmSend(p: BuildSendParams, rpc: string, chainId: number, usdtAddr: string): Promise<UnsignedTx> {
|
|
if (!ethers.utils.isAddress(p.to)) throw new Error('Invalid recipient address');
|
|
|
|
if (!p.token) {
|
|
return { kind: 'evm', to: p.to, data: '0x', value: ethers.BigNumber.from(p.amount).toHexString(), chainId };
|
|
}
|
|
|
|
if (p.token.toUpperCase() === 'USDT') {
|
|
const iface = new ethers.utils.Interface(ERC20_ABI);
|
|
const data = iface.encodeFunctionData('transfer', [p.to, p.amount]);
|
|
return { kind: 'evm', to: usdtAddr, data, value: '0x0', chainId };
|
|
}
|
|
|
|
throw new Error(`Token ${p.token} not supported on ${chainId === 56 ? 'BSC' : 'ETH'}`);
|
|
}
|
|
|
|
async function buildSolSend(p: BuildSendParams): Promise<UnsignedTx> {
|
|
const {
|
|
Connection,
|
|
PublicKey,
|
|
SystemProgram,
|
|
Transaction,
|
|
} = await import('@solana/web3.js');
|
|
|
|
const conn = new Connection(SOL_RPC, 'confirmed');
|
|
|
|
let fromPk: InstanceType<typeof PublicKey>;
|
|
let toPk: InstanceType<typeof PublicKey>;
|
|
try {
|
|
fromPk = new PublicKey(p.from);
|
|
toPk = new PublicKey(p.to);
|
|
} catch {
|
|
throw new Error('Invalid Solana address');
|
|
}
|
|
|
|
const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash();
|
|
const tx = new Transaction({
|
|
feePayer: fromPk,
|
|
blockhash,
|
|
lastValidBlockHeight,
|
|
});
|
|
|
|
if (!p.token) {
|
|
// Native SOL transfer
|
|
tx.add(
|
|
SystemProgram.transfer({
|
|
fromPubkey: fromPk,
|
|
toPubkey: toPk,
|
|
lamports: BigInt(p.amount),
|
|
}),
|
|
);
|
|
} else {
|
|
// SPL token transfer (manual instruction — не тянем @solana/spl-token)
|
|
const TOKEN_PROGRAM_ID = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
|
|
const ASSOCIATED_TOKEN_PROGRAM_ID = new PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL');
|
|
|
|
const mint = solMintFor(p.token);
|
|
if (!mint) throw new Error(`Unsupported SOL token: ${p.token}`);
|
|
|
|
const fromAta = await deriveAta(new PublicKey(mint), fromPk, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);
|
|
const toAta = await deriveAta(new PublicKey(mint), toPk, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);
|
|
|
|
// Transfer instruction (instruction tag = 3 для SPL Token Transfer)
|
|
const data = Buffer.alloc(9);
|
|
data.writeUInt8(3, 0);
|
|
data.writeBigUInt64LE(BigInt(p.amount), 1);
|
|
|
|
tx.add({
|
|
programId: TOKEN_PROGRAM_ID,
|
|
keys: [
|
|
{ pubkey: fromAta, isSigner: false, isWritable: true },
|
|
{ pubkey: toAta, isSigner: false, isWritable: true },
|
|
{ pubkey: fromPk, isSigner: true, isWritable: false },
|
|
],
|
|
data,
|
|
});
|
|
}
|
|
|
|
// Сериализуем сообщение (без подписей) для клиента
|
|
const serialized = tx.serialize({ requireAllSignatures: false, verifySignatures: false });
|
|
|
|
return {
|
|
kind: 'solana',
|
|
instructions: serialized.toString('base64'),
|
|
recentBlockhash: blockhash,
|
|
};
|
|
}
|
|
|
|
function solMintFor(symbol: string): string | null {
|
|
const map: Record<string, string> = {
|
|
USDT: 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB',
|
|
USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
|
|
};
|
|
return map[symbol] ?? null;
|
|
}
|
|
|
|
async function deriveAta(
|
|
mint: any,
|
|
owner: any,
|
|
tokenProgramId: any,
|
|
associatedTokenProgramId: any,
|
|
): Promise<any> {
|
|
const { PublicKey } = await import('@solana/web3.js');
|
|
const [pda] = await PublicKey.findProgramAddress(
|
|
[owner.toBuffer(), tokenProgramId.toBuffer(), mint.toBuffer()],
|
|
associatedTokenProgramId,
|
|
);
|
|
return pda;
|
|
}
|
|
deleted-marker-end */
|
|
|
|
const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
|
|
|
|
function tronAddressToHex(address: string): string {
|
|
let num = 0n;
|
|
for (const ch of address) {
|
|
const i = BASE58_ALPHABET.indexOf(ch);
|
|
if (i === -1) throw new Error('Invalid base58 character in TRON address');
|
|
num = num * 58n + BigInt(i);
|
|
}
|
|
const hex = num.toString(16).padStart(50, '0');
|
|
return hex.slice(2, 42); // 20 bytes без префикса 0x41
|
|
}
|
|
|
|
function hexToTron(hex: string): string {
|
|
// Формат TronGrid: 41xxxx (20 bytes after prefix). Это base58check.
|
|
// Для простоты возвращаем как есть hex (можно улучшить на full base58check если нужно).
|
|
return hex;
|
|
}
|
|
|
|
async function fetchJson(url: string, init?: RequestInit): Promise<any> {
|
|
const controller = new AbortController();
|
|
const t = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
|
try {
|
|
const res = await fetch(url, { ...init, signal: controller.signal });
|
|
if (!res.ok) {
|
|
const body = await res.text().catch(() => '');
|
|
throw new Error(`Upstream ${res.status}: ${body.slice(0, 200)}`);
|
|
}
|
|
return await res.json();
|
|
} finally {
|
|
clearTimeout(t);
|
|
}
|
|
}
|
|
|
|
function withTimeout<T>(promise: Promise<T>, ms: number, msg: string): Promise<T> {
|
|
return new Promise<T>((resolve, reject) => {
|
|
const t = setTimeout(() => reject(new Error(msg)), ms);
|
|
promise.then(
|
|
(v) => { clearTimeout(t); resolve(v); },
|
|
(e) => { clearTimeout(t); reject(e); },
|
|
);
|
|
});
|
|
}
|