// One-time Spotlights through YPBShop. The server builds the signed buy() call for the signed-in member (POST /api/my/order: the hub // sponsor line + the packet); the member's own wallet sends it. After it confirms the page waits for the watcher to record it. window.YPBBuy = (function () { const fmtPol = (wei, d) => { const k = d || 4; const s = (BigInt(wei) * 10n ** BigInt(k) / 10n ** 18n).toString().padStart(k + 1, '0'); return s.slice(0, -k) + '.' + s.slice(-k); }; async function quote(qty) { return YPB.getJSON('/api/quote?qty=' + (qty || 1)); } async function run(o) { const say = o.say || YPB.status; const c = await YPB.getConfig(); if (!c.shop || !c.shop.live) throw new Error('Spotlights are not on sale yet.'); const me = await YPB.getJSON('/api/me'); if (!me.signedIn) throw new Error('Sign in on My packets first.'); say('Connecting your wallet...'); const addr = String(await YPBWallet.activeAddress(await YPBWallet.connect()) || '').toLowerCase(); if (!addr) throw new Error('No wallet connected. Tap Buy again and pick SafePal or any other crypto wallet.'); if (addr !== me.address) throw new Error('Your wallet is connected as ' + YPB.short(addr) + ', but your YourProgramBuilder account is ' + YPB.short(me.address) + '. Switch your wallet app to ' + YPB.short(me.address) + ', or sign out and sign in with ' + YPB.short(addr) + '.'); const od = await YPB.post('/api/my/order', { qty: o.qty || 1, packetId: o.packetId }); if (od.error) throw new Error(od.error); const value = BigInt(od.value); try { const bal = await YPBWallet.balance(addr); if (bal < value) throw new Error('This wallet holds ' + fmtPol(bal) + ' POL. The Spotlight needs about ' + fmtPol(value) + ' POL plus a little gas. Add POL on Polygon and try again.'); } catch (e) { if (/holds/.test(e.message)) throw e; } say('Confirm the payment in your wallet: about ' + fmtPol(value) + ' POL ($' + od.usd + '). Anything above the exact price comes straight back in the same transaction.'); const hash = await YPBWallet.sendTx(od.to, od.data, od.value); const link = c.explorer ? c.explorer + '/tx/' + hash : ''; say('Payment sent. Waiting for the Polygon network to confirm it...'); const r = await YPBWallet.waitTx(hash); if (r.status !== '0x1') throw new Error('The transaction did not go through, so nothing was charged except gas. ' + (link ? 'Details: ' + link : '')); YPB.post('/api/my/paid', {}).catch(() => {}); say('Confirmed on Polygon. Your Spotlight shows on My packets within about a minute.', 'ok'); for (let i = 0; i < 72; i++) { await new Promise(res => setTimeout(res, 5000)); if (i % 4 === 3) YPB.post('/api/my/paid', {}).catch(() => {}); try { if (await o.done()) return { hash, link, recorded: true }; } catch (e) {} } return { hash, link, recorded: false }; } return { run, quote, fmtPol }; })();