Browse Source

Make portal crypto tx submission retry-safe

main
def 6 days ago
parent
commit
7a06680250
  1. 213
      templates/portal_invoice_detail.html

213
templates/portal_invoice_detail.html

@ -517,108 +517,155 @@ Reference: ${invoiceRef}`;
} }
const walletButton = document.getElementById("walletPayButton"); const walletButton = document.getElementById("walletPayButton");
function pendingTxStorageKey(invoiceId, paymentId) {
return `otb_pending_tx_${invoiceId}_${paymentId}`;
}
async function submitTxHash(invoiceId, paymentId, asset, txHash) {
const res = await fetch(`/portal/invoice/${invoiceId}/submit-crypto-tx`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify({
payment_id: paymentId,
asset: asset,
tx_hash: txHash
})
});
let data = {};
try {
data = await res.json();
} catch (err) {
data = { ok: false, error: "invalid_json_response" };
}
if (!res.ok || !data.ok) {
throw new Error(data.error || `submit_failed_http_${res.status}`);
}
return data;
}
async function tryRecoverPendingTxFromStorage() {
const invoiceId = "{{ invoice.id }}";
const paymentId = "{{ pending_crypto_payment.id if pending_crypto_payment else '' }}";
const asset = "{{ selected_crypto_option.symbol if selected_crypto_option else '' }}";
if (!invoiceId || !paymentId || !asset) return;
{% if pending_crypto_payment and pending_crypto_payment.txid %}
return;
{% endif %}
const key = pendingTxStorageKey(invoiceId, paymentId);
const savedTx = localStorage.getItem(key);
if (!savedTx || !savedTx.startsWith("0x")) return;
const walletStatus = document.getElementById("walletStatusText");
try {
if (walletStatus) walletStatus.textContent = "Retrying saved transaction submission...";
await submitTxHash(invoiceId, paymentId, asset, savedTx);
localStorage.removeItem(key);
const url = new URL(window.location.href);
url.searchParams.set("pay", "crypto");
url.searchParams.set("asset", asset);
url.searchParams.set("payment_id", paymentId);
window.location.href = url.toString();
} catch (err) {
if (walletStatus) walletStatus.textContent = `Saved tx retry failed: ${err.message}`;
}
}
if (walletButton) { if (walletButton) {
walletButton.addEventListener("click", async function() { walletButton.addEventListener("click", async function() {
const statusEl = document.getElementById("walletStatusText"); const walletStatus = document.getElementById("walletStatusText");
const originalText = walletButton.textContent; const invoiceId = this.dataset.invoiceId;
walletButton.disabled = true; const paymentId = this.dataset.paymentId;
if (statusEl) statusEl.textContent = "Opening wallet…"; const asset = this.dataset.asset;
const chainId = this.dataset.chainId;
const assetType = this.dataset.assetType;
const to = this.dataset.to;
const amount = this.dataset.amount;
const decimals = Number(this.dataset.decimals || "18");
const tokenContract = this.dataset.tokenContract || "";
const setStatus = (msg) => {
if (walletStatus) walletStatus.textContent = msg;
};
if (!window.ethereum || !window.ethereum.request) {
setStatus("No browser wallet detected. Use MetaMask/Rabby or MetaMask Mobile.");
return;
}
try { try {
if (!window.ethereum) { this.disabled = true;
throw new Error("No wallet detected in this browser. Use 'Open in MetaMask Mobile' or copy the payment details."); setStatus("Opening wallet...");
}
await window.ethereum.request({ method: "eth_requestAccounts" });
const invoiceId = walletButton.dataset.invoiceId;
const paymentId = walletButton.dataset.paymentId; if (chainId && chainId !== "None" && chainId !== "") {
const asset = walletButton.dataset.asset; try {
const chainId = walletButton.dataset.chainId; await switchChain(Number(chainId));
const assetType = walletButton.dataset.assetType; } catch (err) {
const to = walletButton.dataset.to; setStatus(`Chain switch failed: ${err.message || err}`);
const amount = walletButton.dataset.amount; this.disabled = false;
const decimals = Number(walletButton.dataset.decimals || "18"); return;
const tokenContract = walletButton.dataset.tokenContract || ""; }
const accounts = await window.ethereum.request({ method: "eth_requestAccounts" });
const from = Array.isArray(accounts) && accounts.length ? accounts[0] : "";
if (!from) {
throw new Error("Wallet did not return an account address.");
} }
await switchChain(chainId); let txParams;
if (assetType === "token" && tokenContract) {
let txHash; txParams = {
if (assetType === "native") { from: (await window.ethereum.request({ method: "eth_accounts" }))[0],
txHash = await window.ethereum.request({ to: tokenContract,
method: "eth_sendTransaction", data: erc20TransferData(to, amount, decimals),
params: [{ value: "0x0"
from: from, };
to: to,
value: toHexBigIntFromDecimal(amount, decimals)
}]
});
} else { } else {
txHash = await window.ethereum.request({ txParams = {
method: "eth_sendTransaction", from: (await window.ethereum.request({ method: "eth_accounts" }))[0],
params: [{ to: to,
from: from, value: toHexBigIntFromDecimal(amount, decimals)
to: tokenContract, };
data: erc20TransferData(to, amount, decimals)
}]
});
} }
if (statusEl) statusEl.textContent = "Submitting transaction hash to portal…"; setStatus("Waiting for wallet confirmation...");
const txHash = await window.ethereum.request({
async function submitTxHashWithRetry() { method: "eth_sendTransaction",
const maxAttempts = 12; // about 60 seconds total params: [txParams]
const waitMs = 5000; });
for (let attempt = 1; attempt <= maxAttempts; attempt++) { if (!txHash || !String(txHash).startsWith("0x")) {
if (statusEl) { throw new Error("wallet did not return a tx hash");
statusEl.textContent = `Checking RPC for transaction… attempt ${attempt}/${maxAttempts}`; }
}
const resp = await fetch(`/portal/invoice/${invoiceId}/submit-crypto-tx`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
payment_id: paymentId,
asset: asset,
tx_hash: txHash
})
});
const data = await resp.json();
if (resp.ok && data.ok) { const storageKey = pendingTxStorageKey(invoiceId, paymentId);
window.location.href = data.redirect_url; localStorage.setItem(storageKey, String(txHash));
return;
}
const detail = String((data && (data.detail || data.error)) || ""); setStatus(`Wallet submitted tx: ${txHash}. Sending to billing server...`);
const retryable = detail.toLowerCase().includes("not found on rpc");
if (!retryable || attempt === maxAttempts) { await submitTxHash(invoiceId, paymentId, asset, txHash);
throw new Error(detail || "Portal rejected tx hash");
}
if (statusEl) { localStorage.removeItem(storageKey);
statusEl.textContent = `Transaction sent. Waiting for RPC to see it… retrying in ${Math.floor(waitMs / 1000)}s`;
}
await new Promise(resolve => setTimeout(resolve, waitMs)); setStatus("Transaction submitted. Reloading into processing view...");
} const url = new URL(window.location.href);
} url.searchParams.set("pay", "crypto");
url.searchParams.set("asset", asset);
await submitTxHashWithRetry(); url.searchParams.set("payment_id", paymentId);
window.location.href = url.toString();
} catch (err) { } catch (err) {
if (statusEl) statusEl.textContent = String(err.message || err); setStatus(`Wallet submit failed: ${err.message || err}`);
walletButton.disabled = false; this.disabled = false;
walletButton.textContent = originalText;
} }
}); });
} }
tryRecoverPendingTxFromStorage();
})(); })();
</script> </script>

Loading…
Cancel
Save