SHA256
90 lines
5.6 KiB
JavaScript
90 lines
5.6 KiB
JavaScript
/**
|
|
* SHiNE Stars / Pyth Core: local price quote through SHiNE's existing authenticated
|
|
* Solana RPC endpoint. No Hermes, private API keys or server-side prices.
|
|
* Pyth price feed account format: PriceUpdateV2 (Anchor / Borsh).
|
|
*/
|
|
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
|
|
|
|
export const PYTH_SOL_USD_FEED_ID = 'ef0d8b6fda2ceba41da15d4095d1da392a0d2f8ed0c6c7bc0f4cfac8c280b56d';
|
|
export const PYTH_USDT_USD_FEED_ID = '2b89b9dc8fdf9f34709a5b106b472f0f39bb6ca9ce04b0fd7f2e971688e2e53b';
|
|
export const PYTH_PUSH_ORACLE_PROGRAM_ID = 'pythWSnswVUd12oZpeFP8e9CVaEqJg25g1Vtc2biRsT';
|
|
export const PYTH_RECEIVER_PROGRAM_ID = 'rec5EKMGg6MxZYaMdyBfgwp4d5rB9T1VQH5pJv5LtFJ';
|
|
const PYTH_PRICE_UPDATE_DISCRIMINATOR = [34, 241, 35, 99, 157, 126, 244, 205];
|
|
// Devnet допускает более редкие обновления Pyth; production-лимит должен быть строже.
|
|
export const MAX_PYTH_PRICE_AGE_SECONDS = 3_600;
|
|
export const MAX_PYTH_CONFIDENCE_PPM = 10_000n; // 1%, same as shine_users.
|
|
const MAX_SIGNED_FUTURE_SECONDS = 15;
|
|
|
|
function bytesFromHex(hex) {
|
|
if (!/^[0-9a-f]{64}$/i.test(hex)) throw new Error('Invalid Pyth price feed ID');
|
|
return Uint8Array.from(hex.match(/../g), (b) => parseInt(b, 16));
|
|
}
|
|
function hexFromBytes(bytes) { return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); }
|
|
|
|
/** Pyth's getPriceFeedAccountForProgram(shard=0, feedId): PDA([u16LE(shard), feedId], pushOracle). */
|
|
export function deriveStarsPythOracleAccounts(solana) {
|
|
const program = new solana.PublicKey(PYTH_PUSH_ORACLE_PROGRAM_ID);
|
|
const shardZero = Uint8Array.of(0, 0);
|
|
const derive = (id) => solana.PublicKey.findProgramAddressSync([shardZero, bytesFromHex(id)], program)[0];
|
|
return { solUsd: derive(PYTH_SOL_USD_FEED_ID).toBase58(), usdtUsd: derive(PYTH_USDT_USD_FEED_ID).toBase58() };
|
|
}
|
|
|
|
/**
|
|
* Parse verified Pyth PriceUpdateV2. The contract independently enforces identical
|
|
* owner/feed/age/confidence checks; this preflight parser is for UX, not security.
|
|
* Returns exact USD price * 10^8 as BigInt (same normalization as the Rust program).
|
|
*/
|
|
export function parseVerifiedPythPriceAccount(account, expectedFeedId, nowSeconds = Math.floor(Date.now() / 1000)) {
|
|
if (!account?.data || account.owner?.toBase58?.() !== PYTH_RECEIVER_PROGRAM_ID) {
|
|
throw new Error('Pyth: ценовой аккаунт отсутствует или имеет неверного владельца');
|
|
}
|
|
const bytes = account.data instanceof Uint8Array ? account.data : new Uint8Array(account.data);
|
|
if (bytes.length < 133 || PYTH_PRICE_UPDATE_DISCRIMINATOR.some((b, i) => bytes[i] !== b)) {
|
|
throw new Error('Pyth: неверный формат ценового аккаунта');
|
|
}
|
|
// Anchor discriminator (8), write authority (32), Borsh enum Full = 1 (Partial = 0 + signatures byte).
|
|
if (bytes[40] !== 1) throw new Error('Pyth: цена не прошла полную проверку подписей');
|
|
const start = 41;
|
|
if (hexFromBytes(bytes.subarray(start, start + 32)) !== expectedFeedId) {
|
|
throw new Error('Pyth: аккаунт содержит другую валютную пару');
|
|
}
|
|
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
const price = view.getBigInt64(start + 32, true);
|
|
const confidence = view.getBigUint64(start + 40, true);
|
|
const exponent = view.getInt32(start + 48, true);
|
|
const publishedAt = view.getBigInt64(start + 52, true);
|
|
if (price <= 0n || price * MAX_PYTH_CONFIDENCE_PPM < confidence * 1_000_000n) {
|
|
throw new Error('Pyth: некорректная цена или высокий доверительный интервал');
|
|
}
|
|
const now = BigInt(Math.floor(nowSeconds));
|
|
if (publishedAt > now + BigInt(MAX_SIGNED_FUTURE_SECONDS) ||
|
|
now - publishedAt > BigInt(MAX_PYTH_PRICE_AGE_SECONDS)) {
|
|
throw new Error('Pyth: цена устарела или имеет некорректное время');
|
|
}
|
|
const power = exponent + 8;
|
|
if (power < -18 || power > 18) throw new Error('Pyth: неподдерживаемая точность цены');
|
|
const priceE8 = power >= 0 ? price * 10n ** BigInt(power) : price / (10n ** BigInt(-power));
|
|
if (priceE8 <= 0n) throw new Error('Pyth: цена слишком мала');
|
|
return { priceE8, publishTimeSeconds: Number(publishedAt), confidence, exponent };
|
|
}
|
|
|
|
/** Always read BOTH feeds in the same Solana RPC request; no cached/off-chain quote accepted. */
|
|
export async function getStarsQuoteFromRpc({ solanaEndpoint, solana = null, connection = null, nowSeconds } = {}) {
|
|
const endpoint = String(solanaEndpoint || '').trim();
|
|
if (!connection && !endpoint) throw new Error('Solana RPC для SHiNE не подключён');
|
|
const web3 = solana || await loadSolanaWeb3();
|
|
const conn = connection || new web3.Connection(endpoint, 'confirmed');
|
|
const oracleAccounts = deriveStarsPythOracleAccounts(web3);
|
|
const keys = [new web3.PublicKey(oracleAccounts.solUsd), new web3.PublicKey(oracleAccounts.usdtUsd)];
|
|
const infos = await conn.getMultipleAccountsInfo(keys, 'confirmed');
|
|
if (!infos || infos.length !== 2) throw new Error('Pyth: не получены цены SOL и USDT из Solana');
|
|
const now = nowSeconds ?? Math.floor(Date.now() / 1000);
|
|
const sol = parseVerifiedPythPriceAccount(infos[0], PYTH_SOL_USD_FEED_ID, now);
|
|
const usdt = parseVerifiedPythPriceAccount(infos[1], PYTH_USDT_USD_FEED_ID, now);
|
|
return {
|
|
solUsdE8: sol.priceE8.toString(), usdtUsdE8: usdt.priceE8.toString(),
|
|
solOracleAccount: oracleAccounts.solUsd, usdtOracleAccount: oracleAccounts.usdtUsd,
|
|
publishedAtSeconds: Math.min(sol.publishTimeSeconds, usdt.publishTimeSeconds),
|
|
};
|
|
}
|