Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 13 additions & 14 deletions src/community/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -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}}),
Expand Down Expand Up @@ -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}}),
Expand Down
33 changes: 9 additions & 24 deletions src/community/components/CommentThread.jsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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';

Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 3 additions & 1 deletion src/community/components/GameMarketplaceModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
48 changes: 2 additions & 46 deletions src/community/credits.js
Original file line number Diff line number Diff line change
Expand Up @@ -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') ||
Expand Down Expand Up @@ -44,39 +38,16 @@ 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};
delete next.scope;
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()}`;
Expand All @@ -87,28 +58,13 @@ 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'],
body: '{}'
});

export {
isInsufficientFunds,
randomIdempotencyKey,
sendCommercePayment,
listCommerceBounties,
createCommerceBounty,
cancelCommerceBounty
};
45 changes: 1 addition & 44 deletions src/community/pages/Admin.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -561,26 +538,8 @@ const StatsOverview = ({view}) => {
{view === 'storage' && storageError ? <Notice variant="error" className={styles.notice}>{storageError}</Notice> : null}

{(!view || view === 'overview') ? <React.Fragment>
{(stats.pendingPayouts > 0 || (quota && (quota.used / quota.limit) * 100 >= 80)) ? (
{quota && (quota.used / quota.limit) * 100 >= 80 ? (
<div className={styles.alerts} aria-label={communityText('Items needing attention')}>
{stats.pendingPayouts > 0 ? (
<Notice
variant="warning"
action={(
<Button
busy={payoutBusy}
busyLabel={communityText('Retrying…')}
onClick={retryPayouts}
>{communityText('Retry now')}</Button>
)}
>
{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 ? <span className={styles.alertNote}>{payoutNote}</span> : null}
</Notice>
) : null}
{quota && (quota.used / quota.limit) * 100 >= 80 ? (
<Notice variant="warning">
{communityText('Your projects use {value1}% of your storage.', {value1: Math.round((quota.used / quota.limit) * 100)})}
Expand Down Expand Up @@ -811,8 +770,6 @@ const StatsOverview = ({view}) => {
);
};

export {StatsOverview};

const ProjectManager = () => {
const {text: communityText} = useCommunityText();
const [query, setQuery] = useState('');
Expand Down
77 changes: 6 additions & 71 deletions src/community/pages/ManageProject.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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('');

Expand All @@ -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('');
Expand All @@ -1136,44 +1107,10 @@ const BountiesPanel = ({project}) => {
return (
<div className={styles.stack}>
<div className={styles.card}>
<SectionHeading as="h3" icon={Gift} title={communityText('Create a bounty')} lead={communityText('Offer credits for one clear change. Contributors can choose the bounty before they fork, then link it to their pull request.')} />
<form className={styles.form} onSubmit={create}>
<input
disabled={busy}
maxLength={120}
value={form.title}
placeholder={communityText('Short task, such as Add keyboard controls')}
onChange={event => {
const {value} = event.currentTarget;
setForm(current => ({...current, title: value}));
}}
/>
<textarea
disabled={busy}
maxLength={2000}
value={form.description}
placeholder={communityText('What should change? Include anything you will check before merging.')}
onChange={event => {
const {value} = event.currentTarget;
setForm(current => ({...current, description: value}));
}}
/>
<label className={`${styles.field} ${styles.priceField}`}>
<span>{communityText('Reward in credits')}</span>
<input
disabled={busy}
type="number"
min="0.01"
step="0.01"
value={form.amount}
onChange={event => {
const {value} = event.currentTarget;
setForm(current => ({...current, amount: value}));
}}
/>
</label>
<Button type="submit" variant="primary" busy={busy} busyLabel={communityText('Funding…')}><Coins size={15} />{communityText('Fund bounty')}</Button>
</form>
<SectionHeading as="h3" icon={Gift} title={communityText('Create a bounty')} />
<Notice variant="info">
{communityText('New bounties are paused while MistWarp moves payments to Rotur. Bounties already funded still pay out when you merge a linked pull request, and you can cancel them for a refund.')}
</Notice>
{status ? <p className={styles.formStatus}>{status}</p> : null}
</div>
<div className={styles.card}>
Expand All @@ -1192,9 +1129,7 @@ const BountiesPanel = ({project}) => {
))}
</ul>
) : (
<EmptyState compact icon={Gift} title={communityText('No bounties yet')}>
{communityText('Fund a bounty to pay contributors for a specific change.')}
</EmptyState>
<EmptyState compact icon={Gift} title={communityText('No bounties yet')} />
)}
</div>
</div>
Expand Down
Loading
Loading