Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Gifting skills: gift-toggle styles, notification rendering, tests, changelog
nirholas909adb9ac248
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0c6bb533c..4bc408573 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Forge always reaches for a free 3D engine first** — Text-to-3D and image-to-3D generation now exhaust the free engines before any paid one. A prompt is rendered on the free NVIDIA lane; if that's busy, the reference image is reconstructed into a mesh on a free engine too — the platform only reaches for a paid engine as a genuine last resort. And if every engine is briefly out of reach, you now get an honest "temporarily unavailable, try again shortly" instead of a confusing technical billing message. Same Forge, fewer dead ends, no surprise costs. (`/forge`) `[improvement, fix]`- **Forge checkout no longer dead-ends when generation is briefly busy** — When the 3D generator was momentarily rate-limited mid-checkout, Forge could show a raw technical error and look like the payment had failed for good. Now a brief upstream slowdown shows a clear message — your payment was not taken, and the generation retries in a few seconds — and the checkout auto-retries on its own before ever asking you to try again. Your payment only settles once the model is actually produced, so a busy moment never costs you anything. (`/forge`) `[fix]`- **Gasless checkout — buy skills and assets with no SOL in your wallet** — Buying a skill, time-pass, or whole asset no longer requires you to hold SOL for the network fee. When your Solana wallet is connected, three.ws now sponsors the transaction fee: the platform builds and pre-signs the payment, and your wallet only adds your own approval. You still pay the USDC price (and sellers still receive their split), but the tiny gas fee is on us — one fewer thing to top up before you check out. If sponsorship is ever unavailable, checkout falls back to the normal pay-your-own-gas flow automatically, so a purchase never gets blocked. `[feature, improvement]`+- **Gift a skill to anyone — pay once, they get the access** — Buying a skill on an agent page now has a Gift option. Tick "Gift this skill to someone," enter the recipient's username or wallet address, and we confirm exactly who you're sending it to before you pay. You approve the same single USDC payment from your wallet (gas still on us), and the moment it settles on-chain the skill lands in the recipient's library — not yours — with a notification telling them who it's from; you get a delivery confirmation too. It works for permanent unlocks and timed access passes, and if the person already owns the skill we tell you up front so you never pay for nothing. (`/marketplace`) `[feature]`- **Graduated coins show a live price on agent and community cards** — The bonding-curve card — the compact one on agent profiles, community coin pages, and embeddable widgets — used to go blank with a “No active bonding curve” message the moment a coin graduated to a DEX. Now it reads the coin's live on-chain price instead, marks it “Graduated” at 100%, and shows a real market cap, so $THREE and any other migrated coin display a refreshing price rather than empty space. Those cards also stopped opening a background websocket that could never connect — it had been silently retrying and logging errors on every load. Vault balances now refresh by polling directly and update within seconds. `[improvement, fix]`- **Holding $THREE now unlocks a premium feature** — $THREE gets its first hard utility: High-quality 3D generation on Forge — the 200k-polygon, PBR-textured tier — is now reserved for $THREE holders. Reach the Bronze holder tier (the entry tier) by holding $THREE and the High tier unlocks automatically, with no payment step. Draft and Standard generation stay free forever, and bring-your-own-key generation is unaffected. Sign in, link your Solana wallet, and the economy page shows your live holder tier and exactly what it unlocks. (`/three`) `[feature]`- **Leaving a review on an agent profile works again** — Submitting or updating a star rating on an agent's profile was quietly failing for signed-in users — the form said “Save failed” no matter what, because the security token that protects the save was being read incorrectly and never attached. Reviews now save on the first try. Signed-out visitors who tap Submit get a clear “Sign in to leave a review” prompt instead of a dead button, and agent profiles no longer log errors for agents that have no on-chain trading record — the track-record card simply stays hidden. `[fix]`diff --git a/api/_lib/purchase-confirm.js b/api/_lib/purchase-confirm.jsindex 476f356dd..b4276ba1c 100644--- a/api/_lib/purchase-confirm.js+++ b/api/_lib/purchase-confirm.js@@ -541,13 +541,15 @@ async function finalizeSkillConfirmation(pur, txSignature, payoutAddress, platfogetUserDisplay(pur.user_id),getUserDisplay(beneficiaryId),]);+ // No tx_signature here on purpose: the recipient didn't pay, so the+ // notification links to the agent page (where they can use the skill)+ // rather than an on-chain payment they have nothing to do with.await insertNotification(beneficiaryId, 'skill_gift_received', {agent_id: pur.agent_id,skill: pur.skill,from: gifterName,from_user_id: pur.user_id,currency_mint: pur.currency_mint,- tx_signature: txSignature,purchase_id: pur.id,});await insertNotification(pur.user_id, 'skill_gift_sent', {diff --git a/data/changelog.json b/data/changelog.jsonindex 4c61ab247..ea30494d6 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws \u2014 the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-18",+ "title": "Gift a skill to anyone — pay once, they get the access",+ "summary": "Buying a skill on an agent page now has a Gift option. Tick \"Gift this skill to someone,\" enter the recipient's username or wallet address, and we confirm exactly who you're sending it to before you pay. You approve the same single USDC payment from your wallet (gas still on us), and the moment it settles on-chain the skill lands in the recipient's library — not yours — with a notification telling them who it's from; you get a delivery confirmation too. It works for permanent unlocks and timed access passes, and if the person already owns the skill we tell you up front so you never pay for nothing.",+ "tags": [+ "feature"+ ],+ "link": "/marketplace"+ },{"date": "2026-06-18","title": "Forge always reaches for a free 3D engine first",diff --git a/prompts/monetization/18-gifting-skills.md b/prompts/monetization/18-gifting-skills.mddeleted file mode 100644index d0697882a..000000000--- a/prompts/monetization/18-gifting-skills.md+++ /dev/null@@ -1,37 +0,0 @@-----status: not-started------# Prompt 18: Gifting Skills--## Objective-Allow users to purchase a skill and gift it to another user.--## Explanation-Gifting is a great way to encourage user engagement and introduce new users to the platform.--## Instructions-1. **Update the UI:**- * Add a "Gift" option to the purchase modal.- * If selected, an input field will appear for the user to enter the recipient's wallet address or username.--2. **Modify the Backend:**- * The payment processing endpoint will need to accept an optional `recipient_id`.- * When the purchase is recorded in the `user_skill_purchases` table, it will be associated with the recipient's user ID instead of the sender's.--3. **Notifications:**- * Implement a notification system to inform the recipient that they have received a gift.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/18-gifting-skills.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/public/changelog.json b/public/changelog.jsonindex 4eb0c83af..a65b01fa2 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-18T08:03:07.735Z",+ "generated_at": "2026-06-18T08:27:05.363Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -91,6 +91,16 @@"improvement"]},+ {+ "date": "2026-06-18",+ "type": "update",+ "title": "Gift a skill to anyone — pay once, they get the access",+ "summary": "Buying a skill on an agent page now has a Gift option. Tick \"Gift this skill to someone,\" enter the recipient's username or wallet address, and we confirm exactly who you're sending it to before you pay. You approve the same single USDC payment from your wallet (gas still on us), and the moment it settles on-chain the skill lands in the recipient's library — not yours — with a notification telling them who it's from; you get a delivery confirmation too. It works for permanent unlocks and timed access passes, and if the person already owns the skill we tell you up front so you never pay for nothing.",+ "link": "/marketplace",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-18","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex cf901aace..db6704e27 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -70,6 +70,14 @@<category>feature</category><description>Buying a skill, time-pass, or whole asset no longer requires you to hold SOL for the network fee. When your Solana wallet is connected, three.ws now sponsors the transaction fee: the platform builds and pre-signs the payment, and your wallet only adds your own approval. You still pay the USDC price (and sellers still receive their split), but the tiny gas fee is on us — one fewer thing to top up before you check out. If sponsorship is ever unavailable, checkout falls back to the normal pay-your-own-gas flow automatically, so a purchase never gets blocked.</description></item>+ <item>+ <title>Gift a skill to anyone — pay once, they get the access</title>+ <link>https://three.ws/marketplace</link>+ <guid isPermaLink="false">2026-06-18:Gift a skill to anyone — pay once, they get the access</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Buying a skill on an agent page now has a Gift option. Tick "Gift this skill to someone," enter the recipient's username or wallet address, and we confirm exactly who you're sending it to before you pay. You approve the same single USDC payment from your wallet (gas still on us), and the moment it settles on-chain the skill lands in the recipient's library — not yours — with a notification telling them who it's from; you get a delivery confirmation too. It works for permanent unlocks and timed access passes, and if the person already owns the skill we tell you up front so you never pay for nothing.</description>+ </item><item><title>Graduated coins show a live price on agent and community cards</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex 3f6a31fc3..350051958 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-18T08:03:07.716Z",+ "generated_at": "2026-06-18T08:27:05.341Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/agent-detail.css b/src/agent-detail.cssindex 6244af940..9d3f90370 100644--- a/src/agent-detail.css+++ b/src/agent-detail.css@@ -2026,6 +2026,67 @@ model-viewer.ad-hero-avatar {font-size: 18px;color: var(--ad-text);}+.payment-gift {+ margin-bottom: 14px;+}+.payment-gift-toggle {+ display: flex;+ align-items: center;+ gap: 9px;+ cursor: pointer;+ font-size: 13px;+ color: var(--ad-muted);+ user-select: none;+}+.payment-gift-toggle:hover {+ color: var(--ad-text);+}+.payment-gift-toggle input[type='checkbox'] {+ width: 16px;+ height: 16px;+ margin: 0;+ cursor: pointer;+ accent-color: var(--ad-text);+ flex-shrink: 0;+}+.payment-gift-toggle-text {+ line-height: 1.4;+}+.payment-gift-recipient {+ margin-top: 10px;+ display: flex;+ flex-direction: column;+ gap: 6px;+}+.payment-gift-input {+ width: 100%;+ padding: 9px 12px;+ border-radius: 9px;+ border: 1px solid var(--ad-line);+ background: var(--ad-bg-2);+ color: var(--ad-text);+ font: inherit;+ font-size: 13px;+ box-sizing: border-box;+}+.payment-gift-input::placeholder {+ color: var(--ad-dim);+}+.payment-gift-input:focus {+ outline: none;+ border-color: var(--ad-text);+}+.payment-gift-status {+ font-size: 12px;+ min-height: 14px;+ color: var(--ad-muted);+}+.payment-gift-status.ok {+ color: var(--ad-green);+}+.payment-gift-status.err {+ color: #ff6b6b;+}.payment-wallet-area {display: flex;flex-direction: column;diff --git a/src/notifications.js b/src/notifications.jsindex 218afd132..3031d3410 100644--- a/src/notifications.js+++ b/src/notifications.js@@ -62,6 +62,8 @@ function tryAcquireFetchLock() {const TYPE_ICON = {skill_purchased: '💵',skill_purchase_confirmed: '✅',+ skill_gift_received: '🎁',+ skill_gift_sent: '🎁',asset_purchased: '💵',asset_purchase_confirmed: '✅',asset_payment_mismatch: '⚠️',@@ -83,6 +85,14 @@ function notifLabel(n) {return `Payment received for skill "${p.skill || 'unknown'}"`;case 'skill_purchase_confirmed':return `Your purchase of "${p.skill || 'unknown'}" is confirmed`;+ case 'skill_gift_received':+ return p.from+ ? `${p.from} gifted you the skill "${p.skill || 'unknown'}"`+ : `You received the skill "${p.skill || 'unknown'}" as a gift`;+ case 'skill_gift_sent':+ return p.to+ ? `Your gift of "${p.skill || 'unknown'}" was delivered to ${p.to}`+ : `Your gift of "${p.skill || 'unknown'}" was delivered`;case 'asset_purchased':return `Someone purchased your ${p.item_type || 'asset'}`;case 'asset_purchase_confirmed':diff --git a/tests/api/resolve-recipient.test.js b/tests/api/resolve-recipient.test.jsnew file mode 100644index 000000000..d631d4cd6--- /dev/null+++ b/tests/api/resolve-recipient.test.js@@ -0,0 +1,69 @@+// resolveRecipient — turns a public identifier (username / wallet / user id) a+// gifter typed into a real account, and ONLY a public profile. Each branch is+// identifier-shaped, so this pins which query runs for which input and that a+// miss returns null (never throws).++import { describe, it, expect, beforeEach, vi } from 'vitest';++// Content-addressed db mock: `hit` is the row each branch returns (null = miss).+const state = { hit: { id: 'u1', username: 'alice', display_name: 'Alice', avatar_url: null } };+let calls = [];++vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ const q = strings.join(' ? ');+ calls.push({ q, values });+ return state.hit ? [state.hit] : [];+ }),+}));++const { resolveRecipient } = await import('../../api/_lib/resolve-recipient.js');++const lastQuery = () => calls[calls.length - 1]?.q || '';+const lastValues = () => calls[calls.length - 1]?.values || [];++beforeEach(() => {+ calls = [];+ state.hit = { id: 'u1', username: 'alice', display_name: 'Alice', avatar_url: null };+});++describe('resolveRecipient', () => {+ it('returns null for empty / non-string input without touching the db', async () => {+ expect(await resolveRecipient('')).toBeNull();+ expect(await resolveRecipient(' ')).toBeNull();+ expect(await resolveRecipient(null)).toBeNull();+ expect(await resolveRecipient(undefined)).toBeNull();+ expect(calls).toHaveLength(0);+ });++ it('resolves a raw user id via the users.id lookup', async () => {+ const out = await resolveRecipient('123e4567-e89b-42d3-a456-426614174000');+ expect(out).toEqual(state.hit);+ expect(lastQuery()).toMatch(/WHERE id =/i);+ });++ it('resolves an EVM wallet case-insensitively across login + linked wallets', async () => {+ await resolveRecipient('0xAbCdef0123456789012345678901234567890ABC');+ expect(lastQuery()).toMatch(/lower\(u\.wallet_address\)/i);+ // the address is lowercased before matching+ expect(lastValues()[0]).toBe('0xabcdef0123456789012345678901234567890abc');+ });++ it('resolves a Solana wallet against linked solana wallets (case-sensitive)', async () => {+ const addr = '7EYnhQoR9YM3N7UoaKRoA44Uy8JeaZV3qyouov87awMs';+ await resolveRecipient(addr);+ expect(lastQuery()).toMatch(/chain_type = 'solana'/i);+ expect(lastValues()[0]).toBe(addr); // verbatim, not lowercased+ });++ it('resolves a username case-insensitively and strips a leading @', async () => {+ await resolveRecipient('@Alice');+ expect(lastQuery()).toMatch(/lower\(username\) = lower/i);+ expect(lastValues()[0]).toBe('Alice');+ });++ it('returns null when nothing matches', async () => {+ state.hit = null;+ expect(await resolveRecipient('nobody')).toBeNull();+ });+});diff --git a/tests/api/skill-gift-confirm.test.js b/tests/api/skill-gift-confirm.test.jsnew file mode 100644index 000000000..5fab8c24d--- /dev/null+++ b/tests/api/skill-gift-confirm.test.js@@ -0,0 +1,102 @@+// Gifting — finalizeSkillConfirmation routes access to the recipient.+//+// When a confirmed purchase carries recipient_user_id, the skill_access_grants+// row (the authoritative access record) must be created for the RECIPIENT, not+// the payer — and both parties get a gift notification (received / sent) instead+// of the ordinary purchase-confirmed one. Drives the EVM path so finalize is+// reached without the Solana-Pay reference dance. Queries are routed by content.++import { describe, it, expect, beforeEach, vi } from 'vitest';++const SELLER_ADDR = '0x000000000000000000000000000000000000dEaD';+const SELLER_USER = 'seller-user-1';+let calls = [];++vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ const q = strings.join(' ? ');+ calls.push({ q, values });+ if (/agent_payout_wallets/i.test(q)) return [{ address: SELLER_ADDR }];+ if (/select\s+user_id\s+from\s+agent_identities/i.test(q)) return [{ user_id: SELLER_USER }];+ if (/select\s+username,\s+display_name\s+from\s+users/i.test(q)) return [{ username: 'alice', display_name: 'Alice' }];+ if (/select\s+id\s+from\s+skill_purchases/i.test(q)) return []; // idempotency dupe pre-check+ if (/from\s+user_wallets/i.test(q)) return [{ ok: 1 }]; // payer binding+ if (/set\s+status\s*=\s*'confirmed'/i.test(q)) return [{ id: PUR.id, kind: 'permanent', valid_until: null }];+ if (/update\s+skill_purchases\s+set\s+tx_signature/i.test(q)) return [{ id: PUR.id }];+ return [];+ }),+}));++vi.mock('../../api/_lib/evm-payment-verify.js', () => ({+ verifyEvmUsdcPayment: vi.fn(async () => ({ status: 'match', from: '0xPAYER' })),+ evmChainId: vi.fn((chain) => (chain === 'base' ? 8453 : null)),+}));++const notify = vi.fn(async () => {});+vi.mock('../../api/_lib/notify.js', () => ({ insertNotification: notify }));+vi.mock('../../api/_lib/solana/rpc-fallback.js', () => ({+ rpcFallbackFromEnv: vi.fn(() => ({ withFallback: vi.fn() })),+}));++const { confirmSkillPurchase } = await import('../../api/_lib/purchase-confirm.js');++const BUYER = '22222222-2222-2222-2222-222222222222';+const RECIPIENT = '44444444-4444-4444-4444-444444444444';+const PUR = {+ id: '11111111-1111-1111-1111-111111111111',+ user_id: BUYER,+ recipient_user_id: RECIPIENT,+ agent_id: '33333333-3333-3333-3333-333333333333',+ skill: 'translate',+ amount: '1000000',+ currency_mint: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',+ chain: 'base',+ mint_decimals: 6,+ status: 'pending',+ expires_at: null,+ referrer_user_id: null,+};++const grantInsert = () => calls.find((c) => /insert\s+into\s+skill_access_grants/i.test(c.q));+const notifyTypes = () => notify.mock.calls.map((c) => `${c[0]}:${c[1]}`);++beforeEach(() => {+ calls = [];+ notify.mockClear();+});++describe('finalizeSkillConfirmation — gift', () => {+ it('grants access to the recipient, not the payer', async () => {+ const out = await confirmSkillPurchase({ ...PUR }, { txHash: '0xTX' });+ expect(out.status).toBe('confirmed');+ const ins = grantInsert();+ expect(ins, 'a skill_access_grants INSERT must be issued').toBeTruthy();+ // VALUES (user_id, agent_id, skill_name, purchase_id, expires_at)+ expect(ins.values[0]).toBe(RECIPIENT);+ expect(ins.values).toEqual([RECIPIENT, PUR.agent_id, PUR.skill, PUR.id, null]);+ });++ it('notifies the recipient (received) and the buyer (sent), not purchase_confirmed', async () => {+ await confirmSkillPurchase({ ...PUR }, { txHash: '0xTX' });+ const received = notify.mock.calls.find((c) => c[1] === 'skill_gift_received');+ const sent = notify.mock.calls.find((c) => c[1] === 'skill_gift_sent');+ expect(received, 'recipient gets skill_gift_received').toBeTruthy();+ expect(received[0]).toBe(RECIPIENT);+ expect(received[2]).toMatchObject({ skill: PUR.skill, from: 'alice' });+ expect(sent, 'buyer gets skill_gift_sent').toBeTruthy();+ expect(sent[0]).toBe(BUYER);+ expect(sent[2]).toMatchObject({ skill: PUR.skill, to: 'alice' });+ // The ordinary self-purchase confirmation must NOT fire for a gift.+ expect(notifyTypes()).not.toContain(`${BUYER}:skill_purchase_confirmed`);+ // Seller still gets paid-notification.+ expect(notify.mock.calls.find((c) => c[1] === 'skill_purchased')[0]).toBe(SELLER_USER);+ });++ it('a non-gift purchase still grants to the payer and sends purchase_confirmed', async () => {+ const selfPur = { ...PUR, recipient_user_id: null };+ await confirmSkillPurchase(selfPur, { txHash: '0xTX' });+ expect(grantInsert().values[0]).toBe(BUYER);+ expect(notifyTypes()).toContain(`${BUYER}:skill_purchase_confirmed`);+ expect(notifyTypes().some((t) => t.includes('skill_gift'))).toBe(false);+ });+});diff --git a/tests/api/skill-gift-service.test.js b/tests/api/skill-gift-service.test.jsnew file mode 100644index 000000000..7c4058da0--- /dev/null+++ b/tests/api/skill-gift-service.test.js@@ -0,0 +1,121 @@+// Gifting — MonetizationService.preparePurchaseTransaction with a recipient.+//+// Pins the gift business rules layered onto the purchase quote: the payer stays+// in user_id while the resolved recipient lands in recipient_user_id, the+// already-owned short-circuit checks the BENEFICIARY (not the payer), and+// gifting yourself is rejected. Lower-level primitives are mocked; the service's+// own SQL runs through a content-addressed mock so call order can't desync.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const state = {+ price: null,+ existing: null, // active-access (confirmed/trial) row for the beneficiary | null+ pending: null,+ inserted: null,+};+let calls = [];++function respond(q) {+ if (/FROM agent_skill_prices/i.test(q) && /AND skill =/i.test(q)) return state.price ? [state.price] : [];+ if (/FROM skill_purchases/i.test(q) && /status IN \('confirmed', 'trial'\)/i.test(q))+ return state.existing ? [state.existing] : [];+ if (/FROM skill_purchases/i.test(q) && /status = 'pending'/i.test(q))+ return state.pending ? [state.pending] : [];+ if (/INSERT INTO skill_purchases/i.test(q)) return state.inserted ? [state.inserted] : [];+ return [];+}++const sqlMock = vi.fn((strings, ...values) => {+ const q = Array.isArray(strings) ? strings.join(' ? ') : String(strings);+ calls.push({ q, values });+ return Promise.resolve(respond(q));+});+sqlMock.transaction = vi.fn((queries) => Promise.all(queries));+vi.mock('../../api/_lib/db.js', () => ({ sql: sqlMock }));++const purchaseConfirm = {+ confirmSkillPurchase: vi.fn(async () => ({ status: 'confirmed', tx_signature: 'SIG' })),+ resolvePayoutAddress: vi.fn(async () => 'PAYOUT'),+ logEvent: vi.fn(async () => {}),+};+vi.mock('../../api/_lib/purchase-confirm.js', () => purchaseConfirm);+vi.mock('../../api/_lib/skill-access.js', () => ({ hasSkillAccess: vi.fn(async () => ({ owned: false })) }));+vi.mock('../../api/_lib/monetization.js', () => ({ getAvailableBalance: vi.fn(async () => ({})) }));+vi.mock('../../api/_lib/marketplace-platform-fee.js', () => ({+ resolveMarketplaceFee: vi.fn(async () => ({ bps: 250, feeAtomics: 25000n, recipient: { toBase58: () => 'TREASURY' } })),+}));+vi.mock('../../api/_lib/skill-price-cache.js', () => ({ invalidateSkillPriceCache: vi.fn(() => {}) }));++const { MonetizationService } = await import('../../api/_lib/services/MonetizationService.js');+const svc = (user) => new MonetizationService(user, { sql: sqlMock });++const BUYER = 'buyer-0000';+const RECIPIENT = 'recip-0000';++beforeEach(() => {+ calls = [];+ Object.assign(state, { price: null, existing: null, pending: null, inserted: null });+ vi.clearAllMocks();+});++const findCall = (re) => calls.find((c) => re.test(c.q));++describe('preparePurchaseTransaction — gifting', () => {+ const PRICE = { amount: 1000000, currency_mint: 'MINT', chain: 'solana', mint_decimals: 6 };+ const INSERTED = {+ reference: 'REF', amount: '1000000', currency_mint: 'MINT', chain: 'solana',+ expires_at: 'soon', valid_until: null, platform_fee_amount: '25000', platform_fee_wallet: 'TREASURY',+ };++ it('rejects gifting yourself with 400 cannot_gift_self', async () => {+ state.price = PRICE;+ await expect(+ svc({ id: BUYER }).preparePurchaseTransaction('a1', 'echo', { recipientUserId: BUYER }),+ ).rejects.toMatchObject({ status: 400, code: 'cannot_gift_self' });+ expect(findCall(/INSERT INTO skill_purchases/i)).toBeUndefined();+ });++ it('records the recipient on the inserted purchase row, payer stays the buyer', async () => {+ state.price = PRICE;+ state.inserted = INSERTED;+ const out = await svc({ id: BUYER }).preparePurchaseTransaction('a1', 'echo', { recipientUserId: RECIPIENT });++ expect(out.already_owned).toBe(false);+ expect(out.is_gift).toBe(true);+ expect(out.gift_recipient_id).toBe(RECIPIENT);++ const ins = findCall(/INSERT INTO skill_purchases/i);+ expect(ins, 'a skill_purchases INSERT must be issued').toBeTruthy();+ expect(ins.values[0]).toBe(BUYER); // user_id = payer+ expect(ins.values.at(-1)).toBe(RECIPIENT); // recipient_user_id = beneficiary+ expect(purchaseConfirm.logEvent).toHaveBeenCalledWith('REF', 'created', expect.objectContaining({ gift: true }));+ });++ it('checks the BENEFICIARY for already-owned: returns recipient_owns without a reference leak', async () => {+ state.price = PRICE;+ state.existing = { reference: 'RECIP-OLD', status: 'confirmed', tx_signature: 'T', confirmed_at: 'now', valid_until: null, trial_remaining: null, kind: 'purchase' };+ const out = await svc({ id: BUYER }).preparePurchaseTransaction('a1', 'echo', { recipientUserId: RECIPIENT });++ expect(out).toEqual({ already_owned: true, recipient_owns: true });+ // The recipient's own purchase reference/tx must NOT be handed to the buyer.+ expect(out.reference).toBeUndefined();+ expect(out.tx_signature).toBeUndefined();+ // The already-owned query keys on the beneficiary, not the payer.+ const ownedQuery = findCall(/status IN \('confirmed', 'trial'\)/i);+ expect(ownedQuery.values).toContain(RECIPIENT);+ expect(ownedQuery.values).not.toContain(BUYER);+ expect(findCall(/INSERT INTO skill_purchases/i)).toBeUndefined();+ });++ it('a normal (non-gift) purchase is unchanged: no recipient, no gift flags', async () => {+ state.price = PRICE;+ state.inserted = INSERTED;+ const out = await svc({ id: BUYER }).preparePurchaseTransaction('a1', 'echo');+ expect(out.is_gift).toBeUndefined();+ expect(out.gift_recipient_id).toBeUndefined();+ const ins = findCall(/INSERT INTO skill_purchases/i);+ expect(ins.values[0]).toBe(BUYER);+ expect(ins.values.at(-1)).toBeNull(); // recipient_user_id null for a self-purchase+ });+});