Files
instantadpay/public/assets/join.js
T
martbost 03284aa281 Conversion linkage, InstantAdPay side (Marty 2026-11-07, "Yes ship these"): a LinkSpin click stays with the account, and its sign-up, wallet link and each package purchase are reported to LinkSpin. Reporting only: no sponsor, payout, credit or chain path changes; accounts.js only gains a notification after a wallet is linked.
lsreport.js. A click id (lsclk or lsid) arriving on any page is kept in a first-party cookie iap.lsclk, 30 days, last click wins, like the sponsor cookie. The join page also sends its own copy with the code request and verify (the cookie is refused in traffic-exchange frames and never crosses browsers, the 2026-09-29 lesson) and it is remembered per email. It is stored in its own table ls_account_clicks when the account is created or a waiting LinkSpin shell is claimed, on /api/signup, email sign-in and in-game sign-in (a game may pass lsclk; none does yet).

Reports queue in ls_events, whose primary key is the idempotency key (join:<hash>, wallet:<hash>, purchase:<tx>:<log index>), so two app copies in a deploy cannot double a row, and LinkSpin dedupes on the same key. A background loop sends them signed, retrying up to every 5 minutes; a sign-up or a purchase never waits on LinkSpin. The purchase hook runs after the existing ev: claim and its value is the USD price on the chain event. A first purchase finds its buyer through the contract's wallet for that member id, since member_id may not be stored yet. Linked positions count as the account's purchases. Past 30 days from the sign-up nothing is queued (LinkSpin's window is from the click).

Campaigns > Conversion tracking lists everything the member's clicks led to, and joins, wallets and purchases on each campaign row. Guide, privacy page and chatbot (CANNED + FACTS) updated; common.js, join.js and my.js tags bumped.

QA: bash qa/run.sh netconv (54 checks: local InstantAdPay + local LinkSpin + a mock Polygon RPC, a real Purchase log through the real event fan-out, LinkSpin down, two copies racing).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 07:48:36 -06:00

145 lines
17 KiB
JavaScript

// Invite / lead-capture page: /join/<token>[?v=<angle>]
// Email first (code sign-in creates the account), wallet later inside the
// member area. The angle only changes the hook copy; the sponsor cookie was
// set by the server when this page was served.
(function () {
const $ = id => document.getElementById(id);
const LEG = (brand, seg) => seg === 'adv'
? { eyebrow: 'For former ' + brand + ' advertisers', h: 'Your next ad budget <em>pays you back.</em>',
lead: brand + ' is closed. The people who bought ads there are exactly who InstantAdPay was built for: real ad packages from $5, seven formats, and every package in your line paid out by a verified contract on Polygon in the same transaction.',
points: ['Welcome-back credits land the moment your account exists: enough to run a real banner or text campaign today, on us.', 'Seven formats: banners, text ads, login ads, solo ads to member inboxes, video, featured links and verified visits. Views are timed on the server, so a real person saw your ad.', 'When anyone in your line buys ads, the contract pays you in that same transaction. Public on Polygonscan, nothing held, nothing to withdraw.'],
cta: 'Claim your welcome-back credits', sub: 'Free account by email. No password, no wallet today. Use the email you had on ' + brand + ': the credits are tied to it.', video: false }
: { eyebrow: 'For former ' + brand + ' members', h: 'Same daily habit. <em>Real payouts on-chain.</em>',
lead: 'You viewed ads on ' + brand + '. Here you view ads to earn credits, run your own campaign with them for free, and when anyone in your line buys ads you are paid in POL to your own wallet in the same transaction.',
points: ['Welcome-back credits on day one, so your first campaign runs before you have viewed a single ad.', 'Join with just an email. No password, no wallet today. Link a wallet later, only when you want payouts switched on.', 'Every payout is a public transaction on Polygon. Nothing is held, so there is nothing to withdraw and nothing to wait for.'],
cta: 'Claim your welcome-back credits', sub: 'Free account by email. Use the email you had on ' + brand + ': the credits are tied to it.', video: false };
const ANGLES = {
'fw-adv': LEG('Faucet Wave', 'adv'), 'fw-earn': LEG('Faucet Wave', 'earn'), 't1-adv': LEG('Tier One Ads', 'adv'), 't1-earn': LEG('Tier One Ads', 'earn'),
play: { eyebrow: 'If you have time to play', h: 'If you have time to play a game, <em>you have time to build a business.</em>', lead: 'You play games on your phone anyway. These free games pay real Polygon to your wallet, on chain, where anyone can check it. That is the trust tool: people believe what they see paid.',
points: ['A whole collection of free games on one page: a brick breaker, a word puzzle, match three, a cyberpunk battler, a runner and more.', 'First clears and wins pay real Polygon to the wallet on your InstantAdPay account, and every payout is a public transaction anyone can check.', 'Share your games link instead of just playing. When a friend plays, gets paid and joins, they join your team.'],
cta: 'Join free and get your own games link', sub: 'Free account by email. No password, no wallet today. Your games link and invite link are live the moment you are in.', games: true },
instant: { eyebrow: 'Same-transaction payouts', h: 'Paid before the page <em>reloads.</em>', lead: 'What if your commission landed before the thank-you page finished loading? On InstantAdPay that is not a metaphor. A smart contract on Polygon splits every ad package the moment it sells.',
points: ['A verified contract splits every package in the same transaction it sells: 50 percent to the sponsor, 20 and 10 up the line, 20 to the platform.', 'It lands in your own wallet in seconds. There is no balance to withdraw because nothing is ever held.', 'Every payment is public on Polygonscan, so you can check the claim before you spend a dollar.'],
cta: 'See a payout land in seconds', sub: 'Free account by email. No password, no wallet today. Your invite link is live the moment you are in.' },
adspend: { eyebrow: 'For marketers who buy traffic', h: 'You were buying <em>ads anyway.</em>', lead: 'Every ad dollar you ever spent went one direction: out. Here the ad spend in your line pays you, in the same transaction, on a public ledger. Seven formats, dwell-timed views, packages from $5.',
points: ['Seven formats: banners, text ads, login ads, solo ads to member inboxes, video, featured links and verified visits.', 'Views are timed on the server, so a real person saw your ad. Banners and text also run across a partner ad network.', 'When anyone in your line buys ads, the contract pays you in that same transaction.'],
cta: 'Put your next ad dollar where it pays you back', sub: 'Free account by email. See every format and the live rates before you buy anything.' },
free: { eyebrow: 'Costs nothing to try', h: 'Watch first. <em>Spend never.</em>', lead: 'Join free, view a few ads, earn credits, and run your first campaign for zero dollars. Upgrade only if you want more reach.',
points: ['Join with just an email. No password, no wallet today.', 'View a few ads each day and earn credits you can spend on your own banner or text campaign.', 'Buy a package only if you want more reach. They start at $5, and every payout on them is public.'],
cta: 'Start for free. No card, no wallet.', sub: 'Type your email and we send a 6-digit code. That is the whole signup.' },
ledger: { eyebrow: 'No back office', h: 'No back office. <em>No payday.</em>', lead: 'Your last program paid you on the 15th, if it paid you. Here every payout is a public transaction on Polygon you can read yourself, and nothing is ever held.',
points: ['Every payout is a public transaction on Polygon. Click it, read it, verify it yourself.', 'The contract holds zero balance. It splits and sends in the same transaction, with no pause switch and no upgrade path.', 'No back office means nobody can delay, reverse or review your commission.'],
cta: 'Check the ledger yourself, then decide', sub: 'Free account by email. The public ledger and the verified contract are one click from your dashboard.' },
two: { eyebrow: 'The referral side, exactly as coded', h: 'Two buyers open <em>level two.</em>', lead: 'Every direct buyer pays you 50 percent from their first package. Two qualifying buyers open level two, five open level three. Written as constants in a verified contract.',
points: ['Every direct buyer pays you 50 percent from their very first package.', 'Two qualifying buyers open level two at 20 percent. Five open level three at 10 percent. Constants in a verified contract.', 'Until a level opens, its share climbs to the next qualified member above, so the plan rewards the people who build.'],
cta: 'Start your line. Two buyers is the target.', sub: 'Free account by email. Your invite link and the team-building plays are waiting inside.' },
// Build Wide (2026-10-15): the buildwide promo video, vertical on phones and 16:9 on wider screens
wide: { eyebrow: 'Build wide', h: 'Width unlocks <em>depth.</em>', lead: 'Watch the fifty percent land, then the deeper levels open.', file: 'buildwide', portraitOnPhones: true,
points: ['Every direct buyer pays you 50 percent of their package, in the same transaction it sells.', 'Two direct buyers of $20 or more open level two at 20 percent. Five open level three at 10 percent.', 'A level you have not opened yet passes its share up the line. Going wide first is what opens the deeper levels.'],
cta: 'Start wide. Join free.', sub: 'Free account by email. No password, no wallet today. Your invite link is live the moment you are in.' }
};
// ?name=First personalises the page (site-owner links, Marty 2026-09-12): letters, spaces, hyphens,
// apostrophes only, 30 chars. On the company placement links it says the top spot is reserved.
const who = String(new URLSearchParams(location.search).get('name') || '').replace(/[^A-Za-z\u00C0-\u024F' -]/g, '').trim().slice(0, 30);
if (who) {
const top = /^\/join\/(company|top)$/i.test(location.pathname);
const h = $('jnHello');
if (h) { h.textContent = who + (top ? ', your spot directly under the company at the top is reserved for you. Activate with the $20 package to claim it.' : ', this invitation is for you.'); h.hidden = false; }
}
const v = new URLSearchParams(location.search).get('v') || (document.cookie.match(/(?:^|; )iap\.angle=([^;]+)/) || [])[1] || '';
const a = v && ANGLES[v];
if (a) {
document.body.classList.add('squeeze'); // server sets it too; this covers cached HTML
$('jnEyebrow').textContent = '· ' + a.eyebrow; $('jnHead').innerHTML = a.h; $('jnLead').textContent = a.lead;
if (a.cta) { $('jnCapH').textContent = a.cta; $('jnCapSub').textContent = a.sub || ''; }
// the matching hook video + this angle's three points replace the worked example
const VID = 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/';
const vid = $('jnVideo');
if (a.video === false) vid.hidden = true;
else {
const file = a.file || v; // a hook whose uploaded video carries another name (wide -> promo/buildwide.*)
const tall = a.portraitOnPhones && window.matchMedia && window.matchMedia('(max-width: 640px)').matches;
vid.src = VID + file + (tall ? '-portrait' : '') + '.mp4'; vid.poster = VID + file + (tall ? '-portrait' : '') + '.jpg';
if (tall) { vid.style.aspectRatio = '9/16'; vid.style.maxWidth = '380px'; vid.style.margin = '0 auto'; vid.style.maxHeight = '78vh'; }
}
$('jnPoints').innerHTML = (a.points || []).map(t => '<li>' + t.replace(/[&<>]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c])) + '</li>').join('');
$('jnMock').hidden = true; $('jnAngle').hidden = false; $('jnPoints').hidden = false;
// play angle (2026-10-13): a big button to the public games page, carrying this page's invite token as ?ref
if (a.games && !document.getElementById('jnGames')) {
const tok = (location.pathname.match(/^\/join\/([^/?#]+)/) || [])[1] || '';
const g = document.createElement('p'); g.id = 'jnGames'; g.style.cssText = 'margin:14px 0 4px;text-align:center';
const btn = document.createElement('a'); btn.className = 'btn'; btn.href = '/games' + (tok && !/^(company|top)$/i.test(tok) ? '?ref=' + encodeURIComponent(tok) : '');
btn.target = '_blank'; btn.rel = 'noopener'; btn.textContent = 'Play the free games'; btn.style.cssText = 'display:inline-block;font-size:1.1em;padding:14px 28px';
const note = document.createElement('div'); note.className = 'small muted'; note.style.marginTop = '8px'; note.textContent = 'Opens the games page. Play free, then join below to get paid and get your own link.';
g.appendChild(btn); g.appendChild(note); vid.after(g);
}
}
async function api(path, body) {
const r = await (await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json();
if (r.error) throw new Error(r.error);
return r;
}
const err = m => { const e = $('jnErr'); e.textContent = m || ''; e.hidden = !m; };
function busy(btn, fn) {
return async () => { if (btn.disabled) return; btn.disabled = true; err(''); try { await fn(); } catch (e) { err(e.message || 'Something went wrong.'); } finally { btn.disabled = false; } };
}
const pageClick = (() => { const q = new URLSearchParams(location.search); return q.get('lsclk') || q.get('lsid') || ''; })(); // the LinkSpin click in this page's address: travels with the requests, the cookie may be refused in a frame (reporting only)
const codeOpts = () => ({ honeypot: $('jnWebsite'), host: $('jnCheck'), ref: linkTok, angle: v || '', lsclk: pageClick }); // the page's own token rides with the code request (cookie may be blocked in a frame)
const send = busy($('jnSend'), async () => {
const r = await IAP.requestCode($('jnEmail').value, codeOpts());
$('jnCodeRow').hidden = false; $('jnVerify').hidden = false; $('jnSend').hidden = true; $('jnResend').hidden = false;
if (r.devCode) $('jnCode').value = r.devCode;
// the last thing they see before the account is created: who they are joining under
if (sponsorName) { $('jnUnder').textContent = 'Joining under ' + sponsorName + '. Not who invited you? Open their invite link first, then come back for the code.'; $('jnUnder').hidden = false; }
IAP.status(r.sent ? 'Code sent. Check your inbox (and spam, the first time).' : 'Dev mode: code filled in.', 'ok');
$('jnCode').focus();
});
// framed: the code would arrive but the sign-in cookie would be refused, so the sign-up continues in a full window
// with the email filled in (the link carries the invite token, so the sponsor holds)
let framed = false; try { framed = window.top !== window.self; } catch (e) { framed = true; }
$('jnSend').addEventListener('click', framed ? () => { const t = new URL(location.href); const em = ($('jnEmail').value || '').trim(); if (em) t.searchParams.set('email', em); window.open(t.toString(), '_blank', 'noopener'); IAP.status('Opened InstantAdPay in a new tab. Finish joining there.', 'ok'); } : send);
try { const em = new URLSearchParams(location.search).get('email'); if (em && $('jnEmail') && !$('jnEmail').value) $('jnEmail').value = em.slice(0, 120); } catch (e) {}
$('jnResend').addEventListener('click', busy($('jnResend'), async () => {
const r = await IAP.requestCode($('jnEmail').value, codeOpts());
if (r.devCode) $('jnCode').value = r.devCode;
IAP.status('Fresh code sent.', 'ok');
}));
$('jnVerify').addEventListener('click', busy($('jnVerify'), async () => {
await api('/api/auth/email/verify', { email: $('jnEmail').value, code: $('jnCode').value, newsletter: !!$('jnNews').checked, followups: !!$('jnNews').checked, ref: linkTok, lsclk: pageClick });
IAP.status('You are in. Taking you to your dashboard…', 'ok');
location.href = '/my?welcome=1'; // dashboard runs the username step + welcome tour on arrival
}));
$('jnEmail').addEventListener('keydown', e => { if (e.key === 'Enter') ($('jnVerify').hidden ? $('jnSend') : $('jnVerify')).click(); });
$('jnCode').addEventListener('keydown', e => { if (e.key === 'Enter') $('jnVerify').click(); });
// sponsor line (the link opened most recently sets the sponsor; it locks at account creation)
let sponsorName = '';
const linkTok = (location.pathname.match(/^\/join\/([^/?#]+)/) || [])[1] || '';
// Shown inside another site (a traffic-exchange frame)? Browsers refuse our cookies there, so the invitation
// could be lost. Offer the full window; the link carries the token, so the top-level visit sets the cookie.
try { if (window.top !== window.self) { const n = document.createElement('p'); n.className = 'small'; n.style.cssText = 'margin:0 0 10px;padding:10px 12px;border:1px solid var(--line-strong);border-radius:10px;background:var(--mint-soft)';
n.innerHTML = '<b>Viewing this inside another site?</b> <a href="' + location.href.replace(/"/g, '') + '" target="_top" rel="noopener">Open InstantAdPay in a full window</a> so your invitation stays attached to your account.';
const row = $('jnEmail') && $('jnEmail').closest('p'); if (row) row.parentNode.insertBefore(n, row); } } catch (e) {}
fetch('/api/sponsor' + (linkTok ? '?ref=' + encodeURIComponent(linkTok) : '')).then(r => r.json()).then(sp => {
if (sp && sp.invited && sp.name) {
sponsorName = sp.name;
$('jnSponName').textContent = sp.name + (sp.own ? ' (this is your own invite page; visitors see your name here)' : '');
if (sp.avatarUrl) { $('jnSponImg').src = sp.avatarUrl; $('jnSponImg').hidden = false; }
if (sp.cobrand && sp.bio && $('jnSponBio')) { $('jnSponBio').textContent = sp.bio; $('jnSponBio').hidden = false; $('jnSpon').classList.add('cobrand'); }
$('jnSpon').hidden = false;
}
}).catch(() => {});
// package ladder (dollar constants + live POL quote)
const NAMES = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader', 6: 'Starter', 7: 'Elite' };
fetch('/api/catalog').then(r => r.json()).then(c => {
const wrap = $('jnLadder'); if (!wrap || !c.products) return;
wrap.innerHTML = c.products.filter(p => p.active !== false).sort((a, b) => a.priceCents - b.priceCents).map(p =>
'<div class="jn-pk"><div class="n">' + (NAMES[p.id] || 'Package ' + p.id) + '</div><div class="p">' + IAP.fmtUsd(p.priceCents) + '</div><div class="c">' + Number(p.creditAmount).toLocaleString() + ' credits</div>'
+ (p.costWei ? '<div class="small muted">' + IAP.fmtPol(p.costWei) + ' POL now</div>' : '') + '</div>').join('');
}).catch(() => {});
fetch('/api/stats').then(r => r.json()).then(s => {
if (s && s.onchainMembers) $('jnStats').textContent = s.onchainMembers.toLocaleString() + (s.onchainMembers === 1 ? ' member' : ' members') + ' on-chain so far.';
}).catch(() => {});
})();