Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Take minimum_makers config var value into account on Send page #116

Merged
5 commits merged into from
Feb 22, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
92 changes: 46 additions & 46 deletions src/components/Send.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,46 +27,25 @@ const isValidAmount = (candidate) => {
return !isNaN(parsed) && parsed > 0
}

const isValidNumCollaborators = (candidate) => {
const isValidNumCollaborators = (candidate, minNumCollaborators) => {
const parsed = parseInt(candidate, 10)
return !isNaN(parsed) && parsed >= 1 && parsed <= 99
return !isNaN(parsed) && parsed >= minNumCollaborators && parsed <= 99
}

const extractErrorMessage = async (response, fallbackReason = 'Unknown Error - No exact reasons are available : (') => {
// The server will answer with a html response instead of json on certain errors.
// The situation is mitigated by parsing the returned html till a fix is available.
// Tracked here: https://github.com/JoinMarket-Org/joinmarket-clientserver/issues/1170 (last checked: 2022-02-11)
const isHtmlErrorMessage = response.headers.get('content-type') === 'text/html'

if (isHtmlErrorMessage) {
return await response
.text()
.then((html) => {
var parser = new DOMParser()
var doc = parser.parseFromString(html, 'text/html')
return doc.title || fallbackReason
})
.then((reason) => `The server reported a problem: ${reason}`)
}

const { message } = await response.json()
return message || fallbackReason
}

const CollaboratorsSelector = ({ numCollaborators, setNumCollaborators }) => {
const CollaboratorsSelector = ({ numCollaborators, setNumCollaborators, minNumCollaborators }) => {
const settings = useSettings()

const [usesCustomNumCollaborators, setUsesCustomNumCollaborators] = useState(false)

const validateAndSetCustomNumCollaborators = (candidate) => {
if (isValidNumCollaborators(candidate)) {
if (isValidNumCollaborators(candidate, minNumCollaborators)) {
setNumCollaborators(candidate)
} else {
setNumCollaborators(null)
}
}

const defaultCollaboratorsSelection = [3, 5, 6, 7, 9]
const defaultCollaboratorsSelection = [0, 2, 3, 4, 6].map((val) => val + minNumCollaborators)

return (
<rb.Form noValidate className="collaborators-selector">
Expand Down Expand Up @@ -101,9 +80,9 @@ const CollaboratorsSelector = ({ numCollaborators, setNumCollaborators }) => {
})}
<rb.Form.Control
type="number"
min={1}
min={minNumCollaborators}
max={99}
isInvalid={!isValidNumCollaborators(numCollaborators)}
isInvalid={!isValidNumCollaborators(numCollaborators, minNumCollaborators)}
placeholder="Other"
defaultValue=""
className={`p-2 border border-1 rounded text-center${
Expand All @@ -122,7 +101,7 @@ const CollaboratorsSelector = ({ numCollaborators, setNumCollaborators }) => {
/>
{usesCustomNumCollaborators && (
<rb.Form.Control.Feedback type="invalid">
Please use between 1 and 99 collaborators.
Please use between {minNumCollaborators} and 99 collaborators.
</rb.Form.Control.Feedback>
)}
</div>
Expand All @@ -139,22 +118,24 @@ export default function Send({ makerRunning, coinjoinInProcess }) {

const location = useLocation()
const [alert, setAlert] = useState(null)
const [isLoading, setIsLoading] = useState(true)
const [isSending, setIsSending] = useState(false)
const [isCoinjoin, setIsCoinjoin] = useState(false)
const [isCoinjoinOptionEnabled, setIsCoinjoinOptionEnabled] = useState(!makerRunning && !coinjoinInProcess)
const [minNumCollaborators, setMinNumCollaborators] = useState(4) // default value from an unchanged joinmarket.cfg (last check 2022-02-20)

const initialDestination = null
const initialAccount = 0
const initialAmount = null
const initialNumCollaborators = () => {
return pseudoRandomNumber(5, 7)
const initialNumCollaborators = (minValue) => {
return minValue + pseudoRandomNumber(1, 3)
This conversation was marked as resolved.
Show resolved Hide resolved
}

const [destination, setDestination] = useState(initialDestination)
const [account, setAccount] = useState(parseInt(location.state?.account, 10) || initialAccount)
const [amount, setAmount] = useState(initialAmount)
// see https://github.com/JoinMarket-Org/joinmarket-clientserver/blob/master/docs/USAGE.md#try-out-a-coinjoin-using-sendpaymentpy
const [numCollaborators, setNumCollaborators] = useState(initialNumCollaborators())
const [numCollaborators, setNumCollaborators] = useState(initialNumCollaborators(minNumCollaborators))
const [formIsValid, setFormIsValid] = useState(false)

useEffect(() => {
Expand All @@ -171,29 +152,44 @@ export default function Send({ makerRunning, coinjoinInProcess }) {
isValidAddress(destination) &&
isValidAccount(account) &&
isValidAmount(amount) &&
(isCoinjoin ? isValidNumCollaborators(numCollaborators) : true)
(isCoinjoin ? isValidNumCollaborators(numCollaborators, minNumCollaborators) : true)
) {
setFormIsValid(true)
} else {
setFormIsValid(false)
}
}, [destination, account, amount, numCollaborators, isCoinjoin])
}, [destination, account, amount, numCollaborators, minNumCollaborators, isCoinjoin])

useEffect(() => {
// Reload wallet info if not already available.
if (walletInfo) return

const abortCtrl = new AbortController()

setAlert(null)
setIsLoading(true)

Api.getWalletDisplay({ walletName: wallet.name, token: wallet.token, signal: abortCtrl.signal })
.then((res) => (res.ok ? res.json() : Promise.reject(new Error(res.message || 'Loading wallet failed.'))))
.then((data) => setWalletInfo(data.walletinfo))
const requestContext = { walletName: wallet.name, token: wallet.token, signal: abortCtrl.signal }
// Reload wallet info if not already available.
const loadingWalletInfo = walletInfo
? Promise.resolve()
: Api.getWalletDisplay(requestContext)
.then((res) => (res.ok ? res.json() : Promise.reject(new Error(res.message || 'Loading wallet failed.'))))
.then((data) => setWalletInfo(data.walletinfo))
.catch((err) => {
!abortCtrl.signal.aborted && setAlert({ variant: 'danger', message: err.message })
})

const loadingMinimumMakerConfig = Api.postConfigGet(requestContext, { section: 'POLICY', field: 'minimum_makers' })
.then((res) => (res.ok ? res.json() : Promise.reject(new Error(res.message || 'Loading config value failed.'))))
.then((data) => {
const minimumMakers = parseInt(data.configvalue, 10)
setMinNumCollaborators(minimumMakers)
setNumCollaborators(initialNumCollaborators(minimumMakers))
})
.catch((err) => {
!abortCtrl.signal.aborted && setAlert({ variant: 'danger', message: err.message })
})

Promise.all([loadingWalletInfo, loadingMinimumMakerConfig]).finally(() => setIsLoading(false))

return () => abortCtrl.abort()
}, [wallet, setWalletInfo, walletInfo])

Expand All @@ -216,7 +212,7 @@ export default function Send({ makerRunning, coinjoinInProcess }) {
})
success = true
} else {
const message = await extractErrorMessage(res)
const { message } = await res.json()
setAlert({ variant: 'danger', message })
}
} catch (e) {
Expand All @@ -242,7 +238,7 @@ export default function Send({ makerRunning, coinjoinInProcess }) {
setAlert({ variant: 'success', message: 'Collaborative transaction started' })
success = true
} else {
const message = await extractErrorMessage(res)
const { message } = await res.json()
setAlert({ variant: 'danger', message })
}
} catch (e) {
Expand All @@ -261,7 +257,7 @@ export default function Send({ makerRunning, coinjoinInProcess }) {
const isValid = formIsValid

if (isValid) {
const counterparties = parseInt(numCollaborators)
const counterparties = parseInt(numCollaborators, 10)

const success = isCoinjoin
? await startCoinjoin(account, destination, amount, counterparties)
Expand All @@ -271,7 +267,7 @@ export default function Send({ makerRunning, coinjoinInProcess }) {
setDestination(initialDestination)
setAccount(initialAccount)
setAmount(initialAmount)
setNumCollaborators(initialNumCollaborators())
setNumCollaborators(initialNumCollaborators(minNumCollaborators))
setIsCoinjoin(false)
form.reset()
}
Expand All @@ -280,7 +276,7 @@ export default function Send({ makerRunning, coinjoinInProcess }) {

return (
<>
{!walletInfo ? (
{isLoading ? (
<rb.Row className="justify-content-center">
<rb.Col className="flex-grow-0">
<div className="d-flex justify-content-center align-items-center">
Expand Down Expand Up @@ -374,7 +370,11 @@ export default function Send({ makerRunning, coinjoinInProcess }) {
)}
</rb.Form>
{isCoinjoin && (
<CollaboratorsSelector numCollaborators={numCollaborators} setNumCollaborators={setNumCollaborators} />
<CollaboratorsSelector
numCollaborators={numCollaborators}
setNumCollaborators={setNumCollaborators}
minNumCollaborators={minNumCollaborators}
/>
)}
<rb.Button
variant="dark"
Expand Down
18 changes: 18 additions & 0 deletions src/libs/JmWalletApi.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,23 @@ const postFreeze = async ({ walletName, token }, { utxo, freeze = true }) => {
})
}

/**
* Get the value of a specific config setting. Note values are always returned as string.
theborakompanioni marked this conversation as resolved.
Show resolved Hide resolved
*
* @returns an object with property `configvalue` as string
*/
const postConfigGet = async ({ walletName, token, signal }, { section, field }) => {
theborakompanioni marked this conversation as resolved.
Show resolved Hide resolved
return await fetch(`/api/v1/wallet/${walletName}/configget`, {
method: 'POST',
headers: { ...Authorization(token) },
signal,
body: JSON.stringify({
section,
field,
}),
})
}

export {
postMakerStart,
getMakerStop,
Expand All @@ -170,4 +187,5 @@ export {
getWalletUtxos,
getYieldgenReport,
postFreeze,
postConfigGet,
}