SHA256
128 lines
7.0 KiB
JavaScript
128 lines
7.0 KiB
JavaScript
/** SPL USDT wallet operations. Only the user's blockchainKey signs; never the DM key. */
|
|
import { getSolanaCluster, sendAndConfirmSolanaHttp } from './solana-rpc-gateway.js';
|
|
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
|
import { devnetTestUsdtMint } from '../deploy-config.js';
|
|
|
|
export const USDT_MAINNET_MINT = 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB';
|
|
export const TOKEN_PROGRAM_ID = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
|
|
export const ASSOCIATED_TOKEN_PROGRAM_ID = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';
|
|
const USDT_DECIMALS = 6;
|
|
|
|
/** Devnet has no official circulating USDT. For testing, explicitly supply a 6-decimal SPL mint. */
|
|
export function getUsdtAsset() {
|
|
const cluster = getSolanaCluster();
|
|
if (cluster === 'mainnet-beta') return { mint: USDT_MAINNET_MINT, label: 'USDT', test: false };
|
|
const mint = cluster === 'devnet' ? String(devnetTestUsdtMint || '').trim() : '';
|
|
return { mint, label: 'Тестовый USDT', test: true };
|
|
}
|
|
|
|
export function toAtomicAmount(text, decimals = USDT_DECIMALS) {
|
|
const normalized = String(text ?? '').trim().replace(',', '.');
|
|
if (!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(normalized)) throw new Error('Введите положительную сумму числом');
|
|
const [whole, fraction = ''] = normalized.split('.');
|
|
if (fraction.length > decimals) throw new Error(`Допустимо не больше ${decimals} знаков после запятой`);
|
|
const value = BigInt(whole) * (10n ** BigInt(decimals)) + BigInt(fraction.padEnd(decimals, '0') || '0');
|
|
if (value <= 0n || value > 18_446_744_073_709_551_615n) throw new Error('Сумма вне допустимого диапазона');
|
|
return value;
|
|
}
|
|
|
|
export function formatAtomicAmount(amount, decimals = USDT_DECIMALS) {
|
|
const value = BigInt(amount);
|
|
const factor = 10n ** BigInt(decimals);
|
|
const fraction = String(value % factor).padStart(decimals, '0').replace(/0+$/, '');
|
|
return `${value / factor}${fraction ? `.${fraction}` : ''}`;
|
|
}
|
|
|
|
export function associatedTokenAddress(solana, ownerAddress, mintAddress) {
|
|
const tokenProgram = new solana.PublicKey(TOKEN_PROGRAM_ID);
|
|
const owner = new solana.PublicKey(ownerAddress);
|
|
const mint = new solana.PublicKey(mintAddress);
|
|
return solana.PublicKey.findProgramAddressSync(
|
|
[owner.toBuffer(), tokenProgram.toBuffer(), mint.toBuffer()],
|
|
new solana.PublicKey(ASSOCIATED_TOKEN_PROGRAM_ID),
|
|
)[0];
|
|
}
|
|
|
|
async function verifyMint(conn, solana, mintAddress) {
|
|
const info = await conn.getParsedAccountInfo(new solana.PublicKey(mintAddress), 'confirmed');
|
|
if (!info?.value || info.value.owner.toBase58() !== TOKEN_PROGRAM_ID ||
|
|
info.value.data?.parsed?.type !== 'mint' ||
|
|
info.value.data.parsed.info?.decimals !== USDT_DECIMALS) {
|
|
throw new Error('Токен USDT недоступен в этой сети или имеет неверный формат (нужен SPL с 6 знаками)');
|
|
}
|
|
}
|
|
|
|
export async function getUsdtBalance({ endpoint, address }) {
|
|
const asset = getUsdtAsset();
|
|
if (!asset.mint) return { available: false, atomic: 0n, text: '—', asset };
|
|
const solana = await loadSolanaWeb3();
|
|
const conn = new solana.Connection(endpoint, 'confirmed');
|
|
await verifyMint(conn, solana, asset.mint);
|
|
const ata = associatedTokenAddress(solana, address, asset.mint);
|
|
const info = await conn.getAccountInfo(ata, 'confirmed');
|
|
if (!info) return { available: true, atomic: 0n, text: '0', asset };
|
|
if (info.owner.toBase58() !== TOKEN_PROGRAM_ID) throw new Error('У токенового счёта неверный владелец программы');
|
|
const parsed = await conn.getTokenAccountBalance(ata, 'confirmed');
|
|
const atomic = BigInt(parsed.value.amount);
|
|
return { available: true, atomic, text: formatAtomicAmount(atomic), asset, ata: ata.toBase58() };
|
|
}
|
|
|
|
export function encodeTransferChecked(amountAtomic) {
|
|
const bytes = new Uint8Array(10);
|
|
bytes[0] = 12; // SPL Token TransferChecked
|
|
let v = BigInt(amountAtomic);
|
|
for (let i = 1; i <= 8; i += 1) { bytes[i] = Number(v & 255n); v >>= 8n; }
|
|
bytes[9] = USDT_DECIMALS;
|
|
return bytes;
|
|
}
|
|
|
|
/** Sends real USDT in Mainnet, or an explicitly configured *test* SPL token in Devnet. */
|
|
export async function transferUsdt({ endpoint, fromKeypair, toAddress, amountAtomic }) {
|
|
const asset = getUsdtAsset();
|
|
if (!asset.mint) throw new Error('Для Devnet укажите тестовый SPL-mint с 6 знаками (не настоящий USDT)');
|
|
const amount = BigInt(amountAtomic);
|
|
if (amount <= 0n || amount > 18_446_744_073_709_551_615n) throw new Error('Недопустимая сумма');
|
|
const solana = await loadSolanaWeb3();
|
|
const conn = new solana.Connection(endpoint, 'confirmed');
|
|
const sender = fromKeypair.publicKey;
|
|
const recipient = new solana.PublicKey(String(toAddress || '').trim());
|
|
if (sender.equals(recipient)) throw new Error('Нельзя перевести средства самому себе');
|
|
await verifyMint(conn, solana, asset.mint);
|
|
const mint = new solana.PublicKey(asset.mint);
|
|
const fromAta = associatedTokenAddress(solana, sender, mint);
|
|
const toAta = associatedTokenAddress(solana, recipient, mint);
|
|
const balance = await conn.getTokenAccountBalance(fromAta, 'confirmed').catch(() => null);
|
|
if (!balance || BigInt(balance.value.amount) < amount) throw new Error('Недостаточно USDT на связанном токеновом счёте');
|
|
const transaction = new solana.Transaction();
|
|
const destInfo = await conn.getAccountInfo(toAta, 'confirmed');
|
|
if (!destInfo) {
|
|
// CreateAssociatedTokenAccountIdempotent; payer is the sender, owner is the recipient.
|
|
transaction.add(new solana.TransactionInstruction({
|
|
programId: new solana.PublicKey(ASSOCIATED_TOKEN_PROGRAM_ID),
|
|
keys: [
|
|
{ pubkey: sender, isSigner: true, isWritable: true },
|
|
{ pubkey: toAta, isSigner: false, isWritable: true },
|
|
{ pubkey: recipient, isSigner: false, isWritable: false },
|
|
{ pubkey: mint, isSigner: false, isWritable: false },
|
|
{ pubkey: solana.SystemProgram.programId, isSigner: false, isWritable: false },
|
|
{ pubkey: new solana.PublicKey(TOKEN_PROGRAM_ID), isSigner: false, isWritable: false },
|
|
],
|
|
data: Uint8Array.of(1),
|
|
}));
|
|
} else if (destInfo.owner.toBase58() !== TOKEN_PROGRAM_ID) {
|
|
throw new Error('Адрес токенового счёта получателя занят другой программой');
|
|
}
|
|
transaction.add(new solana.TransactionInstruction({
|
|
programId: new solana.PublicKey(TOKEN_PROGRAM_ID),
|
|
keys: [
|
|
{ pubkey: fromAta, isSigner: false, isWritable: true },
|
|
{ pubkey: mint, isSigner: false, isWritable: false },
|
|
{ pubkey: toAta, isSigner: false, isWritable: true },
|
|
{ pubkey: sender, isSigner: true, isWritable: false },
|
|
],
|
|
data: encodeTransferChecked(amount),
|
|
}));
|
|
const signature = await sendAndConfirmSolanaHttp(conn, transaction, [fromKeypair]);
|
|
return { signature, amountAtomic: amount, asset, destination: recipient.toBase58() };
|
|
}
|