fix: resolve solana sync verification issues and improve logging
This commit is contained in:
@@ -41,109 +41,132 @@ export async function syncPendingPayments() {
|
||||
for (const tx of pendingTxs) {
|
||||
try {
|
||||
const metadata = tx.metadata || {};
|
||||
const intentNetwork = metadata.intent_network || 'POLYGON';
|
||||
const intentToken = metadata.intent_token || 'USDT';
|
||||
|
||||
console.log(`[SyncWorker] Syncing TX ${tx.id} | Intent: ${intentNetwork}/${intentToken}`);
|
||||
|
||||
// Re-use logic from crypto-sweep but optimized for background
|
||||
const wallets = metadata.wallets || {};
|
||||
const tempWalletConfig = wallets[intentNetwork] || wallets['EVM'];
|
||||
|
||||
if (!tempWalletConfig) continue;
|
||||
|
||||
const depositAddress = typeof tempWalletConfig === 'string' ? tempWalletConfig : tempWalletConfig.address;
|
||||
const depositPrivateKey = tempWalletConfig.privateKey;
|
||||
|
||||
if (!depositPrivateKey) continue;
|
||||
const scanningMatrix = [
|
||||
{ network: 'SOLANA', tokens: ['SOL', 'USDT', 'USDC'] },
|
||||
{ network: 'POLYGON', tokens: ['MATIC', 'USDT', 'USDC'] },
|
||||
{ network: 'TRON', tokens: ['TRX', 'USDT', 'USDC'] }
|
||||
];
|
||||
|
||||
const cryptoEngine = new CryptoEngine(intentNetwork);
|
||||
|
||||
// Get expected amount logic
|
||||
let expectedCryptoAmount = tx.amount.toString();
|
||||
try {
|
||||
const coinIdMap: Record<string, string> = {
|
||||
'SOL': 'solana', 'USDC': 'usd-coin', 'USDT': 'tether', 'TRX': 'tron', 'BTC': 'bitcoin'
|
||||
};
|
||||
const coinId = coinIdMap[intentToken] || 'solana';
|
||||
const priceUrl = `https://api.coingecko.com/api/v3/simple/price?ids=${coinId}&vs_currencies=usd,try`;
|
||||
const priceRes = await fetch(priceUrl);
|
||||
const priceData = await priceRes.json();
|
||||
const currencyKey = (tx.currency || 'TRY').toLowerCase();
|
||||
const priceInCurrency = priceData[coinId][currencyKey] || priceData[coinId]['usd'];
|
||||
|
||||
if (priceInCurrency) {
|
||||
const rawExpected = parseFloat(tx.amount) / priceInCurrency;
|
||||
expectedCryptoAmount = (rawExpected * 0.98).toFixed(6);
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
// Verify
|
||||
const verification = await cryptoEngine.verifyPayment(depositAddress, expectedCryptoAmount, intentToken);
|
||||
|
||||
if (verification.success) {
|
||||
console.log(`[SyncWorker] Payment DETECTED for TX ${tx.id}. Sweeping...`);
|
||||
|
||||
let platformAddress = sysSettings.evm;
|
||||
if (intentNetwork === 'SOLANA') platformAddress = sysSettings.sol;
|
||||
else if (intentNetwork === 'TRON') platformAddress = sysSettings.tron;
|
||||
else if (intentNetwork === 'BITCOIN') platformAddress = sysSettings.btc;
|
||||
|
||||
// Sweep
|
||||
const sweepResult = await cryptoEngine.sweepFunds(depositPrivateKey, platformAddress, intentToken);
|
||||
|
||||
if (sweepResult.success) {
|
||||
// Update Balances & Transaction (Same as crypto-sweep logic)
|
||||
const merchantResult = await db.query('SELECT * FROM merchants WHERE id = $1', [tx.merchant_id]);
|
||||
const merchant = merchantResult.rows[0];
|
||||
const feePercent = merchant?.fee_percent !== undefined && merchant?.fee_percent !== null ? parseFloat(merchant.fee_percent) : sysSettings.fee;
|
||||
|
||||
const grossAmount = parseFloat(tx.amount);
|
||||
const feeAmount = (grossAmount * feePercent) / 100;
|
||||
const merchantNetCredit = grossAmount - feeAmount;
|
||||
|
||||
const cryptoAmount = parseFloat(expectedCryptoAmount);
|
||||
const cryptoFee = (cryptoAmount * feePercent) / 100;
|
||||
const cryptoNetCredit = cryptoAmount - cryptoFee;
|
||||
|
||||
// Execute DB updates in transaction if possible, or sequential
|
||||
await db.query(`UPDATE merchants SET available_balance = available_balance + $1 WHERE id = $2`, [merchantNetCredit, tx.merchant_id]);
|
||||
|
||||
await db.query(`
|
||||
INSERT INTO merchant_balances (merchant_id, network, token, balance, total_gross)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (merchant_id, network, token)
|
||||
DO UPDATE SET
|
||||
balance = merchant_balances.balance + $4,
|
||||
total_gross = merchant_balances.total_gross + $5
|
||||
`, [tx.merchant_id, intentNetwork, intentToken, cryptoNetCredit, cryptoAmount]);
|
||||
|
||||
await db.query(`
|
||||
UPDATE transactions
|
||||
SET status = 'succeeded', paid_network = $2, paid_token = $3, paid_amount_crypto = $4
|
||||
WHERE id = $1`, [tx.id, intentNetwork, intentToken, expectedCryptoAmount]);
|
||||
|
||||
// Webhook
|
||||
if (tx.callback_url) {
|
||||
fetch(tx.callback_url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
status: 'success',
|
||||
txId: tx.stripe_pi_id,
|
||||
orderRef: tx.source_ref_id,
|
||||
hashes: { txHash: sweepResult.txHash }
|
||||
})
|
||||
}).catch(() => {});
|
||||
if (metadata.intent_network && metadata.intent_token) {
|
||||
const intentIdx = scanningMatrix.findIndex(m => m.network === metadata.intent_network);
|
||||
if (intentIdx > -1) {
|
||||
const intentItem = scanningMatrix.splice(intentIdx, 1)[0];
|
||||
const tokenIdx = intentItem.tokens.indexOf(metadata.intent_token);
|
||||
if (tokenIdx > -1) {
|
||||
intentItem.tokens.splice(tokenIdx, 1);
|
||||
intentItem.tokens.unshift(metadata.intent_token);
|
||||
}
|
||||
|
||||
results.push({ id: tx.id, status: 'synced', txHash: sweepResult.txHash });
|
||||
scanningMatrix.unshift(intentItem);
|
||||
}
|
||||
} else {
|
||||
results.push({ id: tx.id, status: 'no_payment' });
|
||||
}
|
||||
|
||||
let foundPayment = false;
|
||||
|
||||
for (const scan of scanningMatrix) {
|
||||
if (foundPayment) break;
|
||||
|
||||
const networkId = scan.network;
|
||||
const walletConfig = wallets[networkId] || (networkId === 'POLYGON' ? wallets['EVM'] : null);
|
||||
|
||||
if (!walletConfig) continue;
|
||||
|
||||
const depositAddress = typeof walletConfig === 'string' ? walletConfig : walletConfig.address;
|
||||
const depositPrivateKey = walletConfig.privateKey;
|
||||
|
||||
if (!depositPrivateKey) continue;
|
||||
|
||||
// Create engine with explicit network and ensured config
|
||||
const cryptoEngine = new CryptoEngine(networkId);
|
||||
|
||||
for (const tokenSymbol of scan.tokens) {
|
||||
if (foundPayment) break;
|
||||
|
||||
console.log(`[SyncWorker] Checking TX ${tx.id.slice(0,8)} | Network: ${networkId} | Token: ${tokenSymbol} | Address: ${depositAddress}`);
|
||||
|
||||
let expectedCryptoAmount = tx.amount.toString();
|
||||
try {
|
||||
const coinIdMap: Record<string, string> = {
|
||||
'SOL': 'solana', 'MATIC': 'matic-network', 'POLYGON': 'matic-network',
|
||||
'USDC': 'usd-coin', 'USDT': 'tether', 'TRX': 'tron', 'BTC': 'bitcoin'
|
||||
};
|
||||
const coinId = coinIdMap[tokenSymbol] || 'solana';
|
||||
const priceUrl = `https://api.coingecko.com/api/v3/simple/price?ids=${coinId}&vs_currencies=usd,try`;
|
||||
const priceRes = await fetch(priceUrl);
|
||||
const priceData = await priceRes.json();
|
||||
const currencyKey = (tx.currency || 'TRY').toLowerCase();
|
||||
const priceInCurrency = priceData[coinId][currencyKey] || priceData[coinId]['usd'];
|
||||
|
||||
if (priceInCurrency) {
|
||||
const rawExpected = parseFloat(tx.amount) / priceInCurrency;
|
||||
expectedCryptoAmount = (rawExpected * 0.98).toFixed(6);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn(`[SyncWorker] Price fetch failed for ${tokenSymbol}, using raw amount.`);
|
||||
}
|
||||
|
||||
const verification = await cryptoEngine.verifyPayment(depositAddress, expectedCryptoAmount, tokenSymbol);
|
||||
|
||||
if (verification.success) {
|
||||
console.log(`[SyncWorker] Found ${tokenSymbol} matching ~${expectedCryptoAmount} on ${networkId}`);
|
||||
|
||||
let platformAddress = sysSettings.evm;
|
||||
if (networkId === 'SOLANA') platformAddress = sysSettings.sol;
|
||||
else if (networkId === 'TRON') platformAddress = sysSettings.tron;
|
||||
|
||||
const sweepResult = await cryptoEngine.sweepFunds(depositPrivateKey, platformAddress, tokenSymbol);
|
||||
|
||||
if (sweepResult.success) {
|
||||
const merchantResult = await db.query('SELECT * FROM merchants WHERE id = $1', [tx.merchant_id]);
|
||||
const merchant = merchantResult.rows[0];
|
||||
const feePercent = merchant?.fee_percent !== undefined && merchant?.fee_percent !== null ? parseFloat(merchant.fee_percent) : sysSettings.fee;
|
||||
|
||||
const grossAmount = parseFloat(tx.amount);
|
||||
const feeAmount = (grossAmount * feePercent) / 100;
|
||||
const merchantNetCredit = grossAmount - feeAmount;
|
||||
|
||||
const cryptoAmount = parseFloat(expectedCryptoAmount);
|
||||
const cryptoFee = (cryptoAmount * feePercent) / 100;
|
||||
const cryptoNetCredit = cryptoAmount - cryptoFee;
|
||||
|
||||
await db.query(`UPDATE merchants SET available_balance = available_balance + $1 WHERE id = $2`, [merchantNetCredit, tx.merchant_id]);
|
||||
|
||||
await db.query(`
|
||||
INSERT INTO merchant_balances (merchant_id, network, token, balance, total_gross)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (merchant_id, network, token)
|
||||
DO UPDATE SET
|
||||
balance = merchant_balances.balance + $4,
|
||||
total_gross = merchant_balances.total_gross + $5
|
||||
`, [tx.merchant_id, networkId, tokenSymbol, cryptoNetCredit, cryptoAmount]);
|
||||
|
||||
await db.query(`
|
||||
UPDATE transactions
|
||||
SET status = 'succeeded', paid_network = $2, paid_token = $3, paid_amount_crypto = $4
|
||||
WHERE id = $1`, [tx.id, networkId, tokenSymbol, expectedCryptoAmount]);
|
||||
|
||||
if (tx.callback_url) {
|
||||
fetch(tx.callback_url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
status: 'success', txId: tx.stripe_pi_id,
|
||||
orderRef: tx.source_ref_id, hashes: { txHash: sweepResult.txHash }
|
||||
})
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
results.push({ id: tx.id, status: 'synced', network: networkId, token: tokenSymbol });
|
||||
foundPayment = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!foundPayment) results.push({ id: tx.id, status: 'no_payment' });
|
||||
|
||||
} catch (err: any) {
|
||||
console.error(`[SyncWorker] Error processing TX ${tx.id}:`, err.message);
|
||||
console.error(`[SyncWorker] Error processing TX ${tx.id}:`, err);
|
||||
results.push({ id: tx.id, status: 'error', error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user