Сделаны переводы другим пользователям

This commit is contained in:
AidarKC
2026-11-18 12:07:13 +03:00
parent fc86c6190e
commit 780ca53931
19 changed files with 1387 additions and 215 deletions
@@ -0,0 +1,324 @@
/** Jupiter Swap API V2: beta, SOL <-> canonical USDT Mainnet only.
* No third-party script or private-key transmission. Jupiter supplies *instructions*;
* SHiNE validates and compiles them, signs locally, and sends via its current Solana RPC.
* This is not a security audit. Unknown instruction shapes are rejected (fail closed).
*/
import { getSolanaCluster, confirmSolanaTransactionHttp } from './solana-rpc-gateway.js';
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
import { associatedTokenAddress, USDT_MAINNET_MINT, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID, toAtomicAmount, formatAtomicAmount } from './solana-usdt-service.js';
import { bytesToBase58 } from './crypto-utils.js';
export const JUPITER_API_BASE = 'https://api.jup.ag/swap/v2';
export const WSOL_MINT = 'So11111111111111111111111111111111111111112';
export const JUPITER_ROUTER_PROGRAM = 'JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4';
export const SWAP_SLIPPAGE_BPS = 50; // Max slippage: 0.5%
export const SWAP_BETA_MAX_SOL_LAMPORTS = 20_000_000n; // 0.02 SOL
export const SWAP_BETA_MAX_USDT_ATOMIC = 5_000_000n; // 5 USDT
const MAX_CU_PRICE = 50_000n; // micro-lamports per compute unit
const MAX_CU = 1_400_000;
const SYSTEM_PROGRAM_ID = '11111111111111111111111111111111';
const COMPUTE_PROGRAM_ID = 'ComputeBudget111111111111111111111111111111';
const REQUEST_TIMEOUT_MS = 15_000;
function assertMainnet() {
if (getSolanaCluster() !== 'mainnet-beta') throw new Error('Jupiter работает только в Solana Mainnet. Обмен на Devnet отключён.');
}
export function swapPair(inputCurrency) {
if (inputCurrency === 'SOL') return {
inputCurrency: 'SOL', outputCurrency: 'USDT', inputMint: WSOL_MINT, outputMint: USDT_MAINNET_MINT,
inputDecimals: 9, outputDecimals: 6, maxInput: SWAP_BETA_MAX_SOL_LAMPORTS,
};
if (inputCurrency === 'USDT') return {
inputCurrency: 'USDT', outputCurrency: 'SOL', inputMint: USDT_MAINNET_MINT, outputMint: WSOL_MINT,
inputDecimals: 6, outputDecimals: 9, maxInput: SWAP_BETA_MAX_USDT_ATOMIC,
};
throw new Error('Для тестового обмена доступны только SOL и USDT');
}
export function validateSwapInput(currency, text, balances = {}) {
const pair = swapPair(currency);
const amount = toAtomicAmount(text, pair.inputDecimals);
if (amount > pair.maxInput) throw new Error(`Бета-лимит за один обмен: ${formatAtomicAmount(pair.maxInput, pair.inputDecimals)} ${currency}`);
const available = currency === 'SOL' ? balances.solLamports : balances.usdtAtomic;
if (available != null && amount > BigInt(available)) throw new Error(`Недостаточно ${currency}`);
// Even USDT -> SOL requires a little SOL for tx fees and ATA rent.
if (balances.solLamports != null && BigInt(balances.solLamports) < amount * (currency === 'SOL' ? 1n : 0n) + 10_000_000n) {
throw new Error('Оставьте не менее 0,01 SOL для сетевых комиссий и создания токеновых счетов');
}
return { pair, amount };
}
async function fetchJson(url) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
try {
const response = await fetch(url, { method: 'GET', signal: controller.signal, headers: { Accept: 'application/json' }, cache: 'no-store' });
if (!response.ok) throw new Error(`Jupiter API: HTTP ${response.status}. ${response.status === 429 ? 'Превышен лимит запросов, попробуйте позже.' : 'Котировка недоступна.'}`);
return await response.json();
} catch (e) {
if (e?.name === 'AbortError') throw new Error('Jupiter не ответил вовремя');
throw e;
} finally { clearTimeout(timer); }
}
/** Fetch real Metis instructions (not an opaque transaction) and verify the quoted amounts. */
export async function requestSwapBuild({ inputCurrency, amountAtomic, walletAddress }) {
assertMainnet();
const pair = swapPair(inputCurrency);
const amount = BigInt(amountAtomic);
if (amount <= 0n || amount > pair.maxInput) throw new Error('Сумма вне лимита бета-обмена');
if (!walletAddress) throw new Error('Кошелёк не выбран');
const params = new URLSearchParams({
inputMint: pair.inputMint, outputMint: pair.outputMint,
amount: amount.toString(), taker: walletAddress,
slippageBps: String(SWAP_SLIPPAGE_BPS), wrapAndUnwrapSol: 'true', transactionVersion: '0',
});
const response = await fetchJson(`${JUPITER_API_BASE}/build?${params}`);
validateSwapBuildResponse(response, pair, amount);
return { pair, amount, response, fetchedAt: Date.now() };
}
function readAtomic(value) {
if (!/^(0|[1-9]\d*)$/.test(String(value))) throw new Error('Jupiter вернул некорректную целочисленную сумму');
return BigInt(value);
}
export function validateSwapBuildResponse(build, pair, amountAtomic) {
if (!build || typeof build !== 'object' ||
build.inputMint !== pair.inputMint || build.outputMint !== pair.outputMint ||
readAtomic(build.inAmount) !== BigInt(amountAtomic) ||
build.swapMode !== 'ExactIn' || !Number.isInteger(build.slippageBps) ||
build.slippageBps < 0 || build.slippageBps > SWAP_SLIPPAGE_BPS ||
!Array.isArray(build.routePlan) || !build.routePlan.length ||
!build.swapInstruction || build.transactionVersion != null && String(build.transactionVersion) !== '0') {
throw new Error('Jupiter вернул неожиданные параметры обмена');
}
const expected = readAtomic(build.outAmount);
const minimum = readAtomic(build.otherAmountThreshold);
if (expected <= 0n || minimum <= 0n || minimum > expected ||
minimum < expected * BigInt(10_000 - SWAP_SLIPPAGE_BPS) / 10_000n) {
throw new Error('Jupiter вернул недопустимый минимум получения');
}
// Protect against extra fees, additional instructions, and unexpected router contracts.
if ((build.otherInstructions?.length || 0) !== 0 || build.tipInstruction ||
build.swapInstruction.programId !== JUPITER_ROUTER_PROGRAM) {
throw new Error('Неподдерживаемый маршрут Jupiter: дополнительные инструкции или другая программа');
}
return { expected, minimum };
}
function fromBase64(encoded) {
if (typeof encoded !== 'string' || !/^[A-Za-z0-9+/]*={0,2}$/.test(encoded)) throw new Error('Неверные данные инструкции Jupiter');
const binary = atob(encoded);
return Uint8Array.from(binary, (c) => c.charCodeAt(0));
}
function accountStrings(ix) { return ix.accounts.map((a) => String(a.pubkey)); }
function validateIxShape(ix, walletAddress) {
if (!ix || typeof ix.programId !== 'string' || !Array.isArray(ix.accounts) || typeof ix.data !== 'string') throw new Error('Некорректная инструкция Jupiter');
if (ix.accounts.length > 64) throw new Error('Слишком много аккаунтов в инструкции Jupiter');
for (const a of ix.accounts) {
if (!a || typeof a.pubkey !== 'string' || typeof a.isSigner !== 'boolean' || typeof a.isWritable !== 'boolean') throw new Error('Некорректный аккаунт инструкции');
if (a.isSigner && a.pubkey !== walletAddress) throw new Error('Jupiter требует неизвестного подписанта');
}
}
function checkedIx(apiIx, walletAddress, solana) {
validateIxShape(apiIx, walletAddress);
return new solana.TransactionInstruction({
programId: new solana.PublicKey(apiIx.programId),
keys: apiIx.accounts.map((a) => ({ pubkey: new solana.PublicKey(a.pubkey), isSigner: a.isSigner, isWritable: a.isWritable })),
data: fromBase64(apiIx.data),
});
}
function u64le(bytes, from = 1) {
if (bytes.length < from + 8) throw new Error('Неожиданная длина инструкции');
let value = 0n;
for (let i = 0; i < 8; i++) value |= BigInt(bytes[from + i]) << (BigInt(i) * 8n);
return value;
}
/** The instructions are *untrusted*. Only safe setup/cleanup for the user's USDT/WSOL ATAs. */
export function validateSwapInstructions(build, pair, amountAtomic, walletAddress, solana) {
const token = TOKEN_PROGRAM_ID;
const wsolAta = associatedTokenAddress(solana, walletAddress, WSOL_MINT).toBase58();
const usdtAta = associatedTokenAddress(solana, walletAddress, USDT_MAINNET_MINT).toBase58();
const permittedAtas = new Set([wsolAta, usdtAta]);
const setup = Array.isArray(build.setupInstructions) ? build.setupInstructions : [];
const cleanup = build.cleanupInstruction ? [build.cleanupInstruction] : [];
if (setup.length > 8 || cleanup.length > 1 || (build.computeBudgetInstructions || []).length > 4) throw new Error('Слишком много инструкций Jupiter');
let wrappedLamports = 0n;
const checked = (ix) => {
const validated = checkedIx(ix, walletAddress, solana);
const bytes = validated.data;
const ac = accountStrings(ix);
if (ix.programId === ASSOCIATED_TOKEN_PROGRAM_ID) {
if (![0, 1].includes(bytes[0]) || bytes.length > 1 || ac.length < 6 ||
ac[0] !== walletAddress || ac[2] !== walletAddress ||
!permittedAtas.has(ac[1]) ||
(ac[3] === WSOL_MINT ? ac[1] !== wsolAta : ac[3] !== USDT_MAINNET_MINT || ac[1] !== usdtAta) ||
ac[5] !== token) throw new Error('Jupiter пытается создать посторонний токеновый счёт');
} else if (ix.programId === SYSTEM_PROGRAM_ID) {
// Only wrapping SOL into the user's canonical WSOL ATA is allowed.
if (bytes.length !== 12 || new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0, true) !== 2 ||
ac[0] !== walletAddress || ac[1] !== wsolAta) throw new Error('Недопустимый системный перевод Jupiter');
wrappedLamports += u64le(bytes, 4);
if (pair.inputCurrency !== 'SOL' || wrappedLamports > BigInt(amountAtomic)) throw new Error('Jupiter запрашивает лишние SOL');
} else if (ix.programId === token) {
if (bytes[0] === 17) { // SyncNative
if (bytes.length !== 1 || ac[0] !== wsolAta) throw new Error('Jupiter синхронизирует чужой WSOL');
} else if (bytes[0] === 9) { // CloseAccount
if (bytes.length !== 1 || ac[0] !== wsolAta || ac[1] !== walletAddress || ac[2] !== walletAddress) throw new Error('Jupiter закрывает чужой токеновый счёт');
} else throw new Error('Небезопасная операция SPL в Jupiter');
} else throw new Error(`Недопустимая программа в Jupiter: ${ix.programId}`);
return validated;
};
const setupIxs = setup.map(checked);
const cleanupIxs = cleanup.map(checked);
const swapIx = checkedIx(build.swapInstruction, walletAddress, solana);
if (swapIx.programId.toBase58() !== JUPITER_ROUTER_PROGRAM ||
!build.swapInstruction.accounts.some((a) => a.pubkey === walletAddress && a.isSigner)) {
throw new Error('Jupiter не использует ожидаемый on-chain router');
}
return { setupIxs, swapIx, cleanupIxs };
}
async function verifiedLookupTables(conn, build, solana) {
const tables = build.addressesByLookupTableAddress || {};
const items = Object.entries(tables);
if (items.length > 4) throw new Error('Слишком много таблиц адресов в Jupiter');
const result = [];
for (const [address, expected] of items) {
if (!Array.isArray(expected) || expected.length > 256) throw new Error('Некорректная таблица Jupiter');
const key = new solana.PublicKey(address);
const account = await conn.getAccountInfo(key, 'confirmed');
if (!account || !account.owner.equals(solana.AddressLookupTableProgram.programId)) throw new Error('Таблица адресов Jupiter отсутствует в Solana');
const parsed = solana.AddressLookupTableAccount.deserialize(account.data);
const actual = parsed.addresses.map((x) => x.toBase58());
// Never trust a list of addresses given by Jupiter without checking on-chain data.
if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error('Таблица адресов Jupiter не соответствует Solana');
if (parsed.deactivationSlot !== 18_446_744_073_709_551_615n) throw new Error('Таблица адресов Jupiter отключена');
result.push(new solana.AddressLookupTableAccount({ key, state: parsed }));
}
return result;
}
/** SPL Token account data: mint(32), owner(32), amount(u64 LE); fail closed. */
function parseUsdtTokenAccount(data, walletAddress) {
if (!data) return 0n;
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
if (bytes.length < 72 || bytesToBase58(bytes.subarray(0, 32)) !== USDT_MAINNET_MINT ||
bytesToBase58(bytes.subarray(32, 64)) !== walletAddress) {
throw new Error('В симуляции обнаружен посторонний токеновый счёт');
}
return u64le(bytes, 64);
}
function limitedComputeBudget(build, solana, walletAddress) {
let price = 0n;
for (const raw of build.computeBudgetInstructions || []) {
const ix = checkedIx(raw, walletAddress, solana);
if (ix.programId.toBase58() !== COMPUTE_PROGRAM_ID || ix.data.length !== 9 || ix.data[0] !== 3) {
throw new Error('Неожиданная настройка комиссии Jupiter');
}
const candidate = u64le(ix.data);
if (candidate > price) price = candidate;
}
price = price > MAX_CU_PRICE ? MAX_CU_PRICE : price;
return solana.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: Number(price) });
}
export async function buildVerifiedSwapTransaction({ endpoint, walletAddress, build, pair, amountAtomic }) {
assertMainnet();
validateSwapBuildResponse(build, pair, amountAtomic);
const solana = await loadSolanaWeb3();
const conn = new solana.Connection(endpoint, 'confirmed');
const { setupIxs, swapIx, cleanupIxs } = validateSwapInstructions(build, pair, amountAtomic, walletAddress, solana);
const lookups = await verifiedLookupTables(conn, build, solana);
const priceIx = limitedComputeBudget(build, solana, walletAddress);
const latest = await conn.getLatestBlockhash('confirmed');
const buildTx = (units) => new solana.VersionedTransaction(new solana.TransactionMessage({
payerKey: new solana.PublicKey(walletAddress), recentBlockhash: latest.blockhash,
instructions: [
solana.ComputeBudgetProgram.setComputeUnitLimit({ units }), priceIx,
...setupIxs, swapIx, ...cleanupIxs,
],
}).compileToV0Message(lookups));
// Snapshot the wallet and canonical USDT ATA before and *after* simulation.
// Do not rely exclusively on the untrusted Jupiter JSON quote for the actual spend.
const usdtAta = associatedTokenAddress(solana, walletAddress, USDT_MAINNET_MINT);
const [beforeSol, beforeUsdtInfo] = await Promise.all([
conn.getBalance(new solana.PublicKey(walletAddress), 'confirmed'),
conn.getAccountInfo(usdtAta, 'confirmed'),
]);
if (beforeUsdtInfo && beforeUsdtInfo.owner.toBase58() !== TOKEN_PROGRAM_ID) throw new Error('USDT ATA управляется неизвестной программой');
const beforeUsdt = parseUsdtTokenAccount(beforeUsdtInfo?.data, walletAddress);
const simulated = await conn.simulateTransaction(buildTx(MAX_CU), {
sigVerify: false, replaceRecentBlockhash: true, commitment: 'confirmed',
accounts: { encoding: 'base64', addresses: [walletAddress, usdtAta.toBase58()] },
});
if (simulated?.value?.err) throw new Error(`Обмен не прошёл проверку Solana: ${JSON.stringify(simulated.value.err)}`);
if (!simulated?.value || !Array.isArray(simulated.value.accounts) || simulated.value.accounts.length !== 2 || !simulated.value.accounts[0]) {
throw new Error('Solana не предоставила итоговые балансы симуляции');
}
const afterSol = BigInt(simulated.value.accounts[0].lamports);
const tokenSnapshot = simulated.value.accounts[1];
if (!tokenSnapshot) throw new Error('После симуляции USDT-счёт отсутствует');
if (tokenSnapshot.owner !== TOKEN_PROGRAM_ID) throw new Error('После симуляции USDT-счёт управляется неизвестной программой');
const afterUsdtBytes = typeof tokenSnapshot.data === 'string' ? fromBase64(tokenSnapshot.data)
: Array.isArray(tokenSnapshot.data) ? fromBase64(tokenSnapshot.data[0]) : tokenSnapshot.data;
const afterUsdt = parseUsdtTokenAccount(afterUsdtBytes, walletAddress);
const minOut = readAtomic(build.otherAmountThreshold);
const maxFeeAndRent = 15_000_000n; // 0.015 SOL; actual fees/rent generally much lower.
if (pair.inputCurrency === 'SOL') {
if (afterUsdt - beforeUsdt < minOut || BigInt(beforeSol) - afterSol > BigInt(amountAtomic) + maxFeeAndRent) {
throw new Error('Симуляция показывает неожиданные списания или недостачу USDT');
}
} else if (beforeUsdt - afterUsdt !== BigInt(amountAtomic) ||
afterSol - BigInt(beforeSol) < minOut - maxFeeAndRent) {
throw new Error('Симуляция показывает неожиданные списания или недостачу SOL');
}
const consumed = Number(simulated.value.unitsConsumed);
const limit = Number.isFinite(consumed) && consumed > 0 ? Math.min(MAX_CU, Math.max(200_000, Math.ceil(consumed * 1.25))) : MAX_CU;
return { transaction: buildTx(limit), conn, latest, solana };
}
/** The caller must have shown the exact quote and obtained explicit user consent before this. */
export async function executeJupiterSwap({ endpoint, fromKeypair, prepared }) {
assertMainnet();
if (!prepared || Date.now() - prepared.fetchedAt > 30_000) throw new Error('Котировка устарела. Получите новую перед подтверждением.');
const address = fromKeypair.publicKey.toBase58();
const { transaction, conn, latest } = await buildVerifiedSwapTransaction({
endpoint, walletAddress: address, build: prepared.response, pair: prepared.pair, amountAtomic: prepared.amount,
});
// Keys stay inside the running SHiNE client; never passed to Jupiter or SHiNE server.
transaction.sign([fromKeypair]);
const signature = bytesToBase58(transaction.signatures[0]);
let submitted = false;
try {
// Mark the signed signature before the network call to avoid accidental duplicate swaps on RPC timeouts.
if (typeof sessionStorage !== 'undefined') sessionStorage.setItem('shine_swap_beta_pending_signature', signature);
submitted = true;
await conn.sendRawTransaction(transaction.serialize(), { skipPreflight: false, maxRetries: 0 });
await confirmSolanaTransactionHttp(conn, signature, { lastValidBlockHeight: latest.lastValidBlockHeight, timeoutMs: 100_000 });
if (typeof sessionStorage !== 'undefined') sessionStorage.removeItem('shine_swap_beta_pending_signature');
return { signature };
} catch (error) {
if (submitted) {
const uncertain = new Error(`Статус обмена не подтверждён. Он мог выполниться! Проверьте ${signature} в Solana Explorer, прежде чем повторять. ${error?.message || error}`);
uncertain.signature = signature;
throw uncertain;
}
throw error;
}
}
export async function getPendingSwapSignature(endpoint) {
const signature = typeof sessionStorage === 'undefined' ? '' : String(sessionStorage.getItem('shine_swap_beta_pending_signature') || '');
if (!signature) return '';
const solana = await loadSolanaWeb3();
const conn = new solana.Connection(endpoint, 'confirmed');
const status = (await conn.getSignatureStatuses([signature], { searchTransactionHistory: true }))?.value?.[0];
if (status?.confirmationStatus === 'confirmed' || status?.confirmationStatus === 'finalized' || status?.err) {
sessionStorage.removeItem('shine_swap_beta_pending_signature');
return '';
}
return signature;
}
+127
View File
@@ -0,0 +1,127 @@
/** 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() };
}