Files
SHiNE-server/shine-UI/js/services/jupiter-swap-service.js
T

325 lines
20 KiB
JavaScript

/** 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;
}