import {createElement, Fragment, useEffect, useRef, useState} from './wp-element-shim'; import {getAddress, isAddress} from 'viem'; import WalletAccessGuide from './WalletAccessGuide'; type Config = {ajaxUrl: string; nonce: string; portalUrl: string; retentionDays?: number; gatewayId?: string; gatewaySettingsUrl?: string}; declare global {interface Window {VCCPWalletSetup: Config}} export const adminConfig = window.VCCPWalletSetup; type Gateway = {id: string; label: string; wallet: string; enabled: boolean; blank: boolean; error?: string}; type Result = {id: string; status: string}; type Replacement = {before: string; after: string}; type Selectable = {address: string; gateways: string[]; connectedAt?: number}; type Reply = {gateways?: Gateway[]; excluded?: Record; selectable?: Selectable[]; retryProof?: string; state?: string; url?: string; expires?: number; token?: string; proof?: string; address?: string; results?: Result[]; replacements?: Record; review?: string; confirmNonce?: string; rows?: Record[]}; async function request(op: string, fields: Record = {}): Promise { const response = await fetch(adminConfig.ajaxUrl, {method: 'POST', credentials: 'same-origin', cache: 'no-store', headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}, body: new URLSearchParams({action: 'vccp_wallet_manager', nonce: adminConfig.nonce, op, ...fields}), signal: AbortSignal.timeout(30000)}); const body = await response.json().catch(() => null); if (!response.ok || !body?.success) throw new Error(body?.data?.message ?? 'Wallet setup did not complete. Reload this admin page and review current gateway values before retrying.'); return body.data; } export default function AdminApp() { const [method, setMethod] = useState<'privy' | 'manual' | 'reuse'>('privy'); const [reuseAddress, setReuseAddress] = useState(''); const [gateways, setGateways] = useState([]); const [inventoryLoaded, setInventoryLoaded] = useState(false); const [selected, setSelected] = useState([]); const [manual, setManual] = useState(''); const [proof, setProof] = useState(''); const [address, setAddress] = useState(''); const [review, setReview] = useState(''); const [confirmNonce, setConfirmNonce] = useState(''); const [replacements, setReplacements] = useState>({}); const [approved, setApproved] = useState([]); const [confirmed, setConfirmed] = useState(false); const [results, setResults] = useState([]); const [audit, setAudit] = useState[]>([]); const [auditLoaded, setAuditLoaded] = useState(false); const [excluded, setExcluded] = useState>({}); const [selectable, setSelectable] = useState([]); // A small inline notice was easy to miss after returning from the wallet window. const [connected, setConnected] = useState(''); const connectedDialog = useRef(null); // Replacing a saved receiving address is consequential, so it is confirmed in a modal // rather than a panel further down the page that is easy to miss. const reviewDialog = useRef(null); const openReview = useRef(''); openReview.current = review; const [link, setLink] = useState<{token: string; url: string; expires: number} | null>(null); const polling = useRef(false); const activeLink = useRef(''); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [notice, setNotice] = useState(''); const inFlight = useRef(false); const contextGateway = gateways.find((gateway) => gateway.id === adminConfig.gatewayId); function loadRows(rows: Gateway[], reset = false) { setGateways(rows); setInventoryLoaded(true); if (reset) setSelected(rows.filter((gateway) => gateway.blank && !gateway.error && (!adminConfig.gatewayId || gateway.id === adminConfig.gatewayId)).map((gateway) => gateway.id)); } useEffect(() => { let active = true; void request('inventory').then((reply) => {if (active) {loadRows(reply.gateways ?? [], true); setExcluded(reply.excluded ?? {}); setSelectable(reply.selectable ?? []);}}).catch((cause) => {if (active) setError(cause.message);}); return () => {active = false;}; }, []); useEffect(() => { if (!link) return; const timer = window.setInterval(() => {if (document.visibilityState === 'visible') void checkLink(link);}, 7000); return () => {window.clearInterval(timer);}; }, [link]); async function checkLink(current = link) { if (!current || polling.current || activeLink.current !== current.token) return; if (Date.now() >= current.expires * 1000) {activeLink.current = ''; setLink(null); setError('Wallet setup expired. Open a new wallet window to continue.'); return;} polling.current = true; try { const reply = await request('hosted_status', {token: current.token}); if (activeLink.current !== current.token) return; if (reply.state === 'ready' && reply.proof && reply.address) { activeLink.current = ''; setLink(null); setProof(reply.proof); setAddress(reply.address); setResults([]); setConnected(reply.address); setNotice('The wallet window returned a receiving wallet. Check it, then select gateways below and apply it.'); } } catch (cause) {if (activeLink.current === current.token) setError(cause instanceof Error ? cause.message : 'Connection check failed. Try checking again.');} finally {polling.current = false;} } function openWallet() { if (inFlight.current) return; // Open during the user's click; navigate only after a server-created session exists. const popup = window.open('about:blank', '_blank', 'popup,width=600,height=820'); if (popup) {popup.opener = null; popup.document.title = 'Opening VERIFIED wallet setup…';} void run(async () => { try { const reply = await request('hosted_begin'); if (!reply.token || !reply.url || !reply.expires || !reply.url.startsWith(adminConfig.portalUrl + '#session=')) throw new Error('Invalid wallet setup link.'); const current = {token: reply.token, url: reply.url, expires: reply.expires}; activeLink.current = current.token; setLink(current); setProof(''); setAddress(''); if (popup) popup.location.replace(current.url); setNotice('Complete wallet setup in the VERIFIED window. This page will check for your chosen address.'); } catch (cause) {popup?.close(); throw cause;} }); } async function cancelLink() { if (!link) return; await run(async () => { const current = link; activeLink.current = ''; setLink(null); await request('hosted_cancel', {token: current.token}); setNotice('Wallet connection cancelled. Gateway settings were not changed.'); }); } useEffect(() => { const dialog = connectedDialog.current; if (!dialog) return; if (connected && !dialog.open) { if (typeof dialog.showModal === 'function') dialog.showModal(); else dialog.setAttribute('open', ''); } if (!connected && dialog.open) { if (typeof dialog.close === 'function') dialog.close(); else dialog.removeAttribute('open'); } }, [connected]); useEffect(() => { const dialog = reviewDialog.current; if (!dialog) return; if (review && !dialog.open) { if (typeof dialog.showModal === 'function') dialog.showModal(); else dialog.setAttribute('open', ''); } if (!review && dialog.open) { if (typeof dialog.close === 'function') dialog.close(); else dialog.removeAttribute('open'); } }, [review]); async function run(action: () => Promise) { if (inFlight.current) return; inFlight.current = true; setBusy(true); setError(''); setNotice(''); try {await action();} catch (cause) {setError(cause instanceof Error ? cause.message : 'Wallet setup did not complete.');} finally {inFlight.current = false; setBusy(false);} } function resetMethod(value: 'privy' | 'manual' | 'reuse') {setMethod(value); setError(''); setProof(''); setAddress(''); setResults([]);} // Addresses already saved on a gateway, plus Privy wallets connected here but not yet // assigned anywhere — otherwise a freshly created wallet is invisible. const knownAddresses = selectable; const chosenReuse = knownAddresses.find((entry) => entry.address === reuseAddress)?.address ?? knownAddresses[0]?.address ?? ''; const chosenEntry = knownAddresses.find((entry) => entry.address === chosenReuse); const describeEntry = (entry: Selectable) => entry.gateways.length ? `used by ${entry.gateways.join(', ')}` : 'connected with Privy, not yet assigned'; async function prepareReuse() { await run(async () => { if (!chosenReuse) throw new Error('No address is saved on another gateway yet.'); const reply = await request('manual', {address: chosenReuse, origin: chosenEntry && !chosenEntry.gateways.length ? 'connected' : 'reused'}); setProof(reply.proof ?? ''); setAddress(reply.address ?? ''); setResults([]); const current = await request('inventory'); loadRows(current.gateways ?? [], true); setNotice('Using an address already saved on another gateway. Select gateways below and apply it.'); }); } function toggle(id: string, list: string[], setter: (next: string[]) => void) {setter(list.includes(id) ? list.filter((value) => value !== id) : [...list, id]);} function label(id: string) {return gateways.find((gateway) => gateway.id === id)?.label ?? id;} async function prepare() { await run(async () => { const entered = manual.trim(); if (!isAddress(entered, {strict: true})) throw new Error('Enter a valid EVM address. Mixed-case addresses must have a valid checksum.'); const reply = await request('manual', {address: getAddress(entered)}); setProof(reply.proof ?? ''); setAddress(reply.address ?? ''); setResults([]); const current = await request('inventory'); loadRows(current.gateways ?? [], true); setNotice('Manual address prepared. Check that you control this wallet before applying it.'); }); } async function apply() { await run(async () => { const currentProof = proof; setProof(''); const reply = await request('apply', {proof: currentProof, ids: JSON.stringify(selected)}); setResults(reply.results ?? []); loadRows(reply.gateways ?? []); // Retrying failed or conflicted gateways needs no new Privy session. if (reply.retryProof) {setProof(reply.retryProof); setAddress(reply.address ?? address); setSelected((reply.results ?? []).filter((item) => item.status === 'Failed' || item.status === 'Conflict').map((item) => item.id));} if (reply.review) { setReview(reply.review); setConfirmNonce(reply.confirmNonce ?? ''); setReplacements(reply.replacements ?? {}); setApproved(Object.keys(reply.replacements ?? {})); setConfirmed(false); setNotice('Some selected gateways already have a different address. Approve or cancel those replacements in the confirmation dialog.'); } else setNotice('Assignment finished. Review the per-gateway results below. Start a fresh review to change additional gateways.'); }); } async function finishReview(cancel: boolean) { await run(async () => { const reply = await request(cancel ? 'cancel' : 'confirm', {review, confirmNonce, ids: JSON.stringify(approved), confirmReplacements: confirmed ? 'yes' : 'no'}); setReview(''); setReplacements({}); setConfirmed(false); loadRows(reply.gateways ?? []); if (reply.retryProof) {setProof(reply.retryProof); setAddress(reply.address ?? address); setSelected((reply.results ?? []).filter((item) => item.status === 'Failed' || item.status === 'Conflict').map((item) => item.id));} if (!cancel) setResults((previous) => [...previous.filter((item) => !(reply.results ?? []).some((next) => next.id === item.id)), ...(reply.results ?? [])]); else setResults((previous) => previous.map((item) => item.status === 'Replacement review required' ? {...item, status: 'Skipped'} : item)); setNotice(cancel ? 'Replacement review cancelled. Any successful wallet assignments remain saved.' : 'Replacement review finished. Conflicts require a new review of current values.'); }); } return

Create or reconnect your merchant wallet, then apply its receiving address to the VERIFIED gateways you choose.

{contextGateway &&

Setting up {contextGateway.label}. Back to gateway settings

}
{!!knownAddresses.length && }
{error &&

{error}

} {notice &&

{notice}

}

1. Choose your receiving wallet

{method === 'reuse' ? <>

{chosenEntry && !chosenEntry.gateways.length ? 'This wallet was connected with Privy on this site but is not assigned to any gateway yet.' : 'This reuses an address this store already receives to.'} It is recorded as an administrator action, not as a new Privy wallet connection.

: method === 'manual' ? <> {setManual(event.target.value); setProof(''); setAddress('');}} />

Enter a public receiving address you control. Never enter a private key or recovery phrase.

: <>

Create or reconnect a wallet in the VERIFIED window, powered by Privy. Return here to apply its address to your gateways.

By continuing, you connect to the VERIFIED wallet service and Privy. The service receives your store origin, a temporary setup reference and the public wallet address you choose. Your Privy sign-in stays in that window.

Wallet service privacy · Wallet service terms

{!link ? : <>

Waiting for your wallet selection. Keep this admin page open.

Open wallet window ↗

If the window did not open, use “Open wallet window”. Setup allows fifteen minutes for sign-in and reading the guide. If it expires, open a fresh connection and choose your existing wallet. Starting a connection does not create another wallet.

}

Open wallet access and recovery ↗

Keep access to your sign-in and recovery methods. Export through Privy before receiving significant funds. An EVM address does not change the network or token used by your payment provider.

}

Open wallet access / secure export ↗

Your WordPress administrator login does not grant access to a Privy private key. Sign in separately in the wallet window. This panel never displays or stores a key.

2. Select gateways and apply

{address &&

Proposed receiving address: {address}{method === 'manual' ? ' (entered manually)' : method === 'reuse' ? (chosenEntry && !chosenEntry.gateways.length ? ' (connected with Privy on this site earlier)' : ' (already used by this store)') : ' (connected through the wallet window)'}

}

{contextGateway ? contextGateway.blank ? 'This gateway is selected because it has no wallet saved. You can select additional gateways below.' : 'This gateway already has a saved wallet. Select it below if you want to replace that address; a separate confirmation will be required.' : 'Gateways with no wallet saved are selected automatically, including disabled gateways. Select or deselect any gateway below.'} Selecting a gateway does not enable or disable it. Existing different addresses require the replacement review below.

{selected.length} selected
{!inventoryLoaded ?

Loading current gateway settings…

: !gateways.length ?

No eligible gateways are registered. Complete the plugin’s existing terms setup and check that the verified gateway files match this build.

:
{gateways.map((gateway) => )}
SelectGatewayStatusCurrent wallet
toggle(gateway.id, selected, setSelected)} />{gateway.label}{gateway.error ? 'Unavailable' : gateway.enabled ? 'Enabled' : 'Disabled'}{gateway.error ?? (gateway.blank ? 'No wallet saved' :
{gateway.wallet.slice(0, 6)}…{gateway.wallet.slice(-4)} — view{gateway.wallet}
)}
}

{!!Object.keys(excluded).length &&
{Object.keys(excluded).length} allowlisted gateway(s) are not available on this site{Object.entries(excluded).map(([id, reason]) => )}
GatewayReason
{id}{reason}
}

PayPal is excluded pending review of its PYUSD setting. Existing orders, old receiving addresses, gateway enablement, fees, recovery preferences and unrelated settings are preserved.

setConnected('')}> {!!connected &&

Wallet connected

The wallet window returned this receiving wallet for your store:

{connected}

Only apply this address if you finished the wallet window yourself just now. If the wallet window said this setup was already finished before you finished it, someone else used your setup link: close this, press Cancel connection and do not apply it.

Nothing has been saved to a gateway yet. Choose which gateways should receive to this address, then press Apply wallet to selected gateways. Gateways that already have a different address will ask you to confirm.

}
{if (openReview.current) void finishReview(true);}}> {!!review &&

Confirm specific replacements

These gateways already have a different receiving address saved. Nothing has changed yet. Replacing an address only affects future payment sessions.

These gateways already have different receiving addresses. Only future payment-session configuration changes. Funds at prior addresses are not moved; keep access to those wallets for earlier or pending payments.

{Object.entries(replacements).map(([id, replacement]) => )}
ApproveGatewayCurrent addressNew address
{toggle(id, approved, setApproved); setConfirmed(false);}} />{label(id)}{replacement.before}{replacement.after}

Cancelling keeps every existing address unchanged. Any gateways that had no address saved were already updated.

}
{!!results.length &&

Assignment results

{results.map((item) => )}
GatewayResult
{label(item.id)}{item.status}

{proof ? 'Failed and conflicted gateways are reselected above with the same verified address. Check their current values, then apply again.' : 'Successful assignments are saved. Prepare the wallet again to change further gateways.'}

}
Recent wallet assignment audit

Administrator-only records of public-address changes. Entries older than {adminConfig.retentionDays ?? 30} days are removed by the daily scheduled task, and in small batches when this page is opened; if scheduled tasks are disabled on this site, removal can lag. This view shows the latest 50 actions.

{auditLoaded && (audit.length ?
{audit.map((row, index) => )}
UTC timeAdmin IDGatewayOld / new public addressResultAcceptance
{row.created_at}{row.actor_id}{row.gateway_id}{row.old_address || 'No wallet saved'}
{row.new_address}
{row.result}{row.consent || '—'}
:

No wallet assignment records.

)}
{busy &&

Completing wallet setup…

}
; }