diff --git a/src/community/api.js b/src/community/api.js index 831d5e4865c..2a3f4d89242 100644 --- a/src/community/api.js +++ b/src/community/api.js @@ -234,25 +234,26 @@ const api = { publish: id => request(`/projects/${id}/publish`, {method: 'POST'}), unpublish: id => request(`/projects/${id}/unpublish`, {method: 'POST'}), setVisibility: (id, visibility) => request(`/projects/${id}/visibility`, {method: 'POST', body: {visibility}}), - purchaseIntent: id => request(`/projects/${id}/purchase/intent`, {method: 'POST'}), - purchaseConfirm: (id, key, paymentId) => request(`/projects/${id}/purchase/confirm`, { - method: 'POST', body: {key, paymentId} - }), + purchaseIntent: (id, returnUrl) => request(`/projects/${id}/purchase/intent`, {method: 'POST', body: {returnUrl}}), + purchaseConfirm: (id, key) => request(`/projects/${id}/purchase/confirm`, {method: 'POST', body: {key}}), gameProducts: id => request(`/projects/${id}/products`, {cache: false}), ownsGameProduct: (id, product) => request(`/projects/${id}/products/${encodeURIComponent(product)}/owns`, { cache: false }), - gameProductIntent: (id, product) => request(`/projects/${id}/products/${encodeURIComponent(product)}/purchase/intent`, { - method: 'POST' + gameProductIntent: (id, product, returnUrl) => request(`/projects/${id}/products/${encodeURIComponent(product)}/purchase/intent`, { + method: 'POST', body: {returnUrl} + }), + gameProductConfirm: (id, product, key) => request(`/projects/${id}/products/${encodeURIComponent(product)}/purchase/confirm`, { + method: 'POST', body: {key} }), - gameProductConfirm: (id, product, key, paymentId) => request(`/projects/${id}/products/${encodeURIComponent(product)}/purchase/confirm`, { - method: 'POST', body: {key, paymentId} + gameProductRefundIntent: (id, product, username, returnUrl) => request(`/projects/${id}/products/${encodeURIComponent(product)}/refund/intent`, { + method: 'POST', body: {username, returnUrl} }), grantGameProduct: (id, product, username) => request(`/projects/${id}/products/${encodeURIComponent(product)}/grant`, { method: 'POST', body: {username} }), - revokeGameProduct: (id, product, {username, paymentId, noRefund}) => request(`/projects/${id}/products/${encodeURIComponent(product)}/revoke`, { - method: 'POST', body: {username, paymentId, noRefund} + revokeGameProduct: (id, product, {username, refundKey, noRefund}) => request(`/projects/${id}/products/${encodeURIComponent(product)}/revoke`, { + method: 'POST', body: {username, refundKey, noRefund} }), createGameDataCapability: (id, context) => request(`/projects/${id}/data-capability`, { method: 'POST', body: {context} @@ -281,8 +282,8 @@ const api = { getComments: (id, options) => request(`/projects/${id}/comments?${commentQuery(options)}`), addComment: (id, content, parent, kind = 'comment', donation = null) => request(`/projects/${id}/comments`, {method: 'POST', body: {content, parent, kind, donation}}), - commentDonationIntent: (id, amount) => request(`/projects/${id}/comments/donation/intent`, { - method: 'POST', body: {amount} + commentDonationIntent: (id, amount, returnUrl) => request(`/projects/${id}/comments/donation/intent`, { + method: 'POST', body: {amount, returnUrl} }), deleteComment: (id, commentId) => request(`/projects/${id}/comments/${commentId}`, {method: 'DELETE'}), editComment: (id, commentId, content) => request(`/projects/${id}/comments/${commentId}`, {method: 'PUT', body: {content}}), @@ -333,8 +334,6 @@ const api = { `/admin/users?q=${encodeURIComponent(q)}&offset=${encodeURIComponent(offset)}` + `&limit=${encodeURIComponent(limit)}&sort=${encodeURIComponent(sort)}` ), - payouts: () => request('/admin/payouts'), - retryPayouts: () => request('/admin/payouts/retry', {method: 'POST'}), extensions: () => request('/admin/extensions', {cache: false}), setExtensionPolicy: (hash, status) => request('/admin/extensions/policy', {method: 'POST', body: {hash, status}}), diff --git a/src/community/components/CommentThread.jsx b/src/community/components/CommentThread.jsx index 7e48d0517dc..a6df5ac1caa 100644 --- a/src/community/components/CommentThread.jsx +++ b/src/community/components/CommentThread.jsx @@ -1,4 +1,4 @@ -import {formatCommunityMessage, getCommunityLocale} from '../locale.js'; +import {getCommunityLocale} from '../locale.js'; import {useCommunityIntl as useCommunityText} from '../i18n.jsx'; import React, {useEffect, useState, useCallback, useMemo, useRef} from 'react'; import {Link} from 'react-router-dom'; @@ -18,7 +18,7 @@ import RichText from './RichText.jsx'; import GroupTag from './GroupTag.jsx'; import Dropdown, {DropdownItem} from './ui/Dropdown.jsx'; import {timeAgo, sameUser, formatPlaytime} from '../format'; -import {sendCommercePayment, isInsufficientFunds} from '../credits'; +import {payWithRotur} from '../../lib/rotur/payment-window.js'; import useLatest from '../use-latest.js'; import styles from './CommentThread.module.css'; @@ -46,28 +46,13 @@ export const parseCommentDonation = value => { const amount = Math.round(Number(value) * 100) / 100; return Number.isFinite(amount) && amount >= 0.01 && amount <= 100000 ? amount : null; }; +// The donation is paid on Rotur, then the comment is posted with its key. export const postCommentDonation = async ({source, text, kind, amount}) => { - const intent = await source.donationIntent(amount); - const paid = await sendCommercePayment({ - amount: intent.amount, - source: 'mistwarp', - kind: 'comment_donation', - resourceType: 'project', - resourceId: intent.projectId, - note: `MistWarp comment donation: ${intent.title || intent.projectId}`, - splits: intent.splits + const {result} = await payWithRotur({ + start: returnUrl => source.donationIntent(amount, returnUrl), + confirm: ({key}) => source.add(text, null, kind, {key}) }); - let lastError = null; - for (let attempt = 0; attempt < 5; attempt++) { - try { - return await source.add(text, null, kind, {key: intent.key, paymentId: paid.payment.id}); - } catch (e) { - if (e.status !== 402 || !e.data || !e.data.pending) throw e; - lastError = e; - await new Promise(resolve => window.setTimeout(resolve, 1500)); - } - } - throw lastError || new Error(formatCommunityMessage('Donation could not be confirmed.')); + return result; }; export const addCreatedComment = (comments, comment) => { const previous = (comments || []).find(item => sameUser(item.author, comment.author)); @@ -617,8 +602,8 @@ const CommentThread = ({ setReplyTo(null); } catch (e) { if (sourceRef.current === actionSource && viewerRef.current === actionViewer) { - setError(isInsufficientFunds(e) ? - communityText('You do not have enough credits for this donation.') : + setError(e.cancelled ? + communityText('Payment cancelled.') : (e.message || communityText('Could not post comment.'))); } } finally { diff --git a/src/community/components/GameMarketplaceModal.jsx b/src/community/components/GameMarketplaceModal.jsx index d0e501419ad..9c0630a90a4 100644 --- a/src/community/components/GameMarketplaceModal.jsx +++ b/src/community/components/GameMarketplaceModal.jsx @@ -152,7 +152,9 @@ const GameMarketplaceModal = ({projectId, productId, isDraft, vm, username, onBl } } catch (e) { if (mounted.current && currentProjectId.current === actionProjectId) { - setError(e.message || communityText('Could not complete the purchase.')); + setError(e.cancelled ? + communityText('Payment cancelled.') : + (e.message || communityText('Could not complete the purchase.'))); } } finally { releasePurchase(); diff --git a/src/community/credits.js b/src/community/credits.js index 5a078b1baf6..066e69d93fb 100644 --- a/src/community/credits.js +++ b/src/community/credits.js @@ -2,12 +2,6 @@ import {ensureScopes, getAccessToken} from '../lib/rotur/client.js'; const ROTUR_API = 'https://api.rotur.dev/v2'; -// Detect an "insufficient funds" failure from a Rotur transfer error. -const isInsufficientFunds = error => { - const message = String((error && error.message) || error || '').toLowerCase(); - return message.includes('insufficient') || message.includes('not enough') || message.includes('balance'); -}; - const isPermissionError = message => { const text = String(message || '').toLowerCase(); return text.includes('permission') || @@ -44,15 +38,9 @@ const billingRequest = async (path, init = {}) => { return data; }; -const randomIdempotencyKey = prefix => { - const id = typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : - `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`; - return `${prefix}:${id}`; -}; - const commerceRequest = async (path, init = {}) => { - // Every call says which permission it needs. Spending is asked for when - // someone pays, from their click. + // Every call says which permission it needs. Anything more than viewing + // is asked for from the person's click. const {scope} = init; await ensureScopes(scope, {prompt: scope.some(name => !name.endsWith(':view'))}); const next = {...init}; @@ -60,23 +48,6 @@ const commerceRequest = async (path, init = {}) => { return billingRequest(`/commerce${path}`, next); }; -const sendCommercePayment = ({to, amount, source = 'mistwarp', kind, resourceType, resourceId, note, splits}) => - commerceRequest('/payments', { - method: 'POST', - scope: ['credits:transfer'], - body: JSON.stringify({ - to, - amount, - source, - kind, - resource_type: resourceType, - resource_id: resourceId, - note, - splits, - idempotency_key: randomIdempotencyKey(`${source}:${kind}:${resourceId || 'general'}`) - }) - }); - const listCommerceBounties = async (filters = {}) => { const query = new URLSearchParams(filters); const path = `/bounties?${query.toString()}`; @@ -87,17 +58,6 @@ const listCommerceBounties = async (filters = {}) => { return data; }; -const createCommerceBounty = bounty => commerceRequest('/bounties', { - method: 'POST', - scope: ['credits:transfer'], - body: JSON.stringify({ - ...bounty, - idempotency_key: bounty.idempotency_key || randomIdempotencyKey( - `${bounty.source}:${bounty.resource_type}:${bounty.resource_id}` - ) - }) -}); - const cancelCommerceBounty = id => commerceRequest(`/bounties/${encodeURIComponent(id)}/cancel`, { method: 'POST', scope: ['credits:manage'], @@ -105,10 +65,6 @@ const cancelCommerceBounty = id => commerceRequest(`/bounties/${encodeURICompone }); export { - isInsufficientFunds, - randomIdempotencyKey, - sendCommercePayment, listCommerceBounties, - createCommerceBounty, cancelCommerceBounty }; diff --git a/src/community/pages/Admin.jsx b/src/community/pages/Admin.jsx index 4d4072842d9..68133935e05 100644 --- a/src/community/pages/Admin.jsx +++ b/src/community/pages/Admin.jsx @@ -335,9 +335,6 @@ const StatsOverview = ({view}) => { const [days, setDays] = useState(30); const [statsBusy, setStatsBusy] = useState(false); const [showDailyData, setShowDailyData] = useState(false); - const [payoutBusy, setPayoutBusy] = useState(false); - const [payoutNote, setPayoutNote] = useState(''); - const payoutLocks = useRef(new Set()); const mounted = useRef(true); const currentDays = useRef(days); currentDays.current = days; @@ -399,26 +396,6 @@ const StatsOverview = ({view}) => { }; }, []); - const retryPayouts = async () => { - if (payoutLocks.current.has('retry')) return; - payoutLocks.current.add('retry'); - setPayoutBusy(true); - setPayoutNote(''); - try { - const result = await api.admin.retryPayouts(); - if (!mounted.current) return; - setPayoutNote(`Paid ${result.paid}, ${result.remaining} still pending.`); - const refreshDays = currentDays.current; - const fresh = await api.admin.stats(refreshDays); - if (mounted.current && currentDays.current === refreshDays) setStats(fresh); - } catch (e) { - if (mounted.current) setPayoutNote(e.message || 'Could not retry payouts.'); - } finally { - payoutLocks.current.delete('retry'); - if (mounted.current) setPayoutBusy(false); - } - }; - const syncR2Storage = async () => { if (storageSyncBusy) return; setStorageSyncBusy(true); @@ -561,26 +538,8 @@ const StatsOverview = ({view}) => { {view === 'storage' && storageError ? {storageError} : null} {(!view || view === 'overview') ? - {(stats.pendingPayouts > 0 || (quota && (quota.used / quota.limit) * 100 >= 80)) ? ( + {quota && (quota.used / quota.limit) * 100 >= 80 ? (
- {stats.pendingPayouts > 0 ? ( - {communityText('Retry now')} - )} - > - {communityText('{value1, plural, one {# creator payout} other {# creator payouts}} failed. {value2} credits are still owed.', { - value1: stats.pendingPayouts, - value2: Math.round((stats.pendingPayoutAmount || 0) * 100) / 100 - })} - {payoutNote ? {payoutNote} : null} - - ) : null} {quota && (quota.used / quota.limit) * 100 >= 80 ? ( {communityText('Your projects use {value1}% of your storage.', {value1: Math.round((quota.used / quota.limit) * 100)})} @@ -811,8 +770,6 @@ const StatsOverview = ({view}) => { ); }; -export {StatsOverview}; - const ProjectManager = () => { const {text: communityText} = useCommunityText(); const [query, setQuery] = useState(''); diff --git a/src/community/pages/ManageProject.jsx b/src/community/pages/ManageProject.jsx index 6198c588c95..3ef35dfcf4f 100644 --- a/src/community/pages/ManageProject.jsx +++ b/src/community/pages/ManageProject.jsx @@ -28,7 +28,7 @@ import UserLink from '../components/UserLink.jsx'; import {SwitchRow} from '../components/ui/Switch.jsx'; import useLatest from '../use-latest.js'; import {formatDate, formatDateTime, formatPlaytime} from '../format.js'; -import {createCommerceBounty, listCommerceBounties, cancelCommerceBounty} from '../credits'; +import {listCommerceBounties, cancelCommerceBounty} from '../credits'; import styles from './ManageProject.module.css'; const roundCredits = value => Math.round((Number(value) || 0) * 100) / 100; @@ -1075,7 +1075,6 @@ const ManageProject = () => { const BountiesPanel = ({project}) => { const {text: communityText} = useCommunityText(); const [items, setItems] = useState(null); - const [form, setForm] = useState({title: '', description: '', amount: '10'}); const [busy, setBusy] = useState(false); const [status, setStatus] = useState(''); @@ -1091,34 +1090,6 @@ const BountiesPanel = ({project}) => { useEffect(load, [load]); - const create = async event => { - event.preventDefault(); - const amount = Math.round(Number(form.amount) * 100) / 100; - if (!form.title.trim() || !Number.isFinite(amount) || amount < 0.01) { - setStatus('Add a title and an amount greater than 0.'); - return; - } - setBusy(true); - setStatus(''); - try { - await createCommerceBounty({ - title: form.title.trim(), - description: form.description.trim(), - amount, - source: 'mistwarp', - resource_type: 'project', - resource_id: project.id - }); - setForm({title: '', description: '', amount: '10'}); - setStatus('Bounty published. MistWarp will pay it when you merge a pull request linked to it.'); - load(); - } catch (error) { - setStatus(error.message || 'Could not create the bounty.'); - } finally { - setBusy(false); - } - }; - const cancel = async id => { setBusy(true); setStatus(''); @@ -1136,44 +1107,10 @@ const BountiesPanel = ({project}) => { return (
- -
- { - const {value} = event.currentTarget; - setForm(current => ({...current, title: value})); - }} - /> -