Skip to content

Commit

Permalink
Allow UIA reg to use custom amount
Browse files Browse the repository at this point in the history
  • Loading branch information
1aerostorm committed Nov 18, 2023
1 parent 63c197a commit 5a9c0fe
Show file tree
Hide file tree
Showing 6 changed files with 158 additions and 30 deletions.
39 changes: 39 additions & 0 deletions src/elements/forms/AmountField.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import React from 'react'
import { Field, ErrorMessage, } from 'formik'
import { AssetEditor } from 'golos-lib-js/lib/utils'

class AmountField extends React.Component {
static defaultProps = {
name: 'amount',
}

_renderInput = ({ field, form }) => {
// TODO: is it right to pass all props to input
const { placeholder, name, ...rest } = this.props
const { value, } = field
const { values, setFieldTouched, setFieldValue } = form
return <input type='text' value={value.amountStr} placeholder={placeholder}
{...rest} onChange={(e) => this.onChange(e, values, setFieldTouched, setFieldValue)}
/>
}

onChange = (e, values, setFieldTouched, setFieldValue) => {
const { name } = this.props
const newAmount = values[name].withChange(e.target.value)
if (newAmount.hasChange && newAmount.asset.amount >= 0) {
setFieldValue(name, newAmount)
setFieldTouched(name, true, false)
}
}

render() {
const { placeholder, name, ...rest } = this.props
return (<Field name={name} type='text'
placeholder={placeholder}
autoComplete='off' autoCorrect='off' spellCheck='false' {...rest}>
{this._renderInput}
</Field>)
}
}

export default AmountField
6 changes: 4 additions & 2 deletions src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@
"deposit_unavailable": " - deposit temporarily unavailable.",
"cmc_error": " - cannot get min amount from CoinMarketCap.",
"transfer_not_supported": " - not yet supported.",
"req_amount": "Amount should be strictly equal to ",
"min_amount": "Minimal amount is ",
"enter_amount": "Exact amount, which will be transferred by gate: ",
"slot_is_used": "Try another amount.",
"fee": "Fee",
"memo_fixed": "Memo",
"to": "Send tokens to address/account",
Expand Down Expand Up @@ -384,7 +386,7 @@
"close": "Close",
"collapse": "Collapse",
"comments": "Comments",
"continue": "continue",
"continue": "Continue",
"convert": "Convert",
"date": "Date",
"delete": "Delete",
Expand Down
6 changes: 4 additions & 2 deletions src/locales/ru-RU.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@
"deposit_unavailable": " - депозит временно недоступен.",
"cmc_error": " - не удается получить минимальную сумму с CoinMarketCap.",
"transfer_not_supported": " - пока не поддерживается.",
"req_amount": "Сумма токенов должна равняться ",
"min_amount": "Минимальная сумма - ",
"enter_amount": "Точная сумма, которую отправит шлюз: ",
"slot_is_used": "Введите другую сумму.",
"fee": "Комиссия",
"memo_fixed": "Заметка/memo",
"to": "Отправьте токены на адрес/аккаунт",
Expand Down Expand Up @@ -385,7 +387,7 @@
"close": "Закрыть",
"collapse": "Свернуть",
"comments": "Комментарии",
"continue": "продолжить",
"continue": "Продолжить",
"convert": "Конвертировать",
"created": "Сначала новые",
"old": "Сначала старые",
Expand Down
18 changes: 9 additions & 9 deletions src/modules/register/TransferWaiter.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@ class TransferWaiter extends React.Component {
super(props)
}

poll = async (minAmount) => {
poll = async (amount) => {
const retry = async () => {
await delay(1000)
if (!this.stopped)
this.poll(minAmount)
this.poll(amount)
else
this.stoppedPolling = true
}
try {
let res = await callApi('/api/reg/wait_for_transfer/' + minAmount.toString())
let res = await callApi('/api/reg/wait_for_transfer/' + amount.toString())
res = await res.json()
if (res.status === 'ok') {
const { onTransfer } = this.props
Expand Down Expand Up @@ -57,9 +57,9 @@ class TransferWaiter extends React.Component {
})
}, 1000)

const { minAmount, } = this.props
const { amount, } = this.props

this.poll(minAmount)
this.poll(amount)
}

componentDidMount() {
Expand All @@ -80,10 +80,10 @@ class TransferWaiter extends React.Component {
}

async componentDidUpdate(prevProps) {
const { minAmount } = this.props
if (minAmount && (!prevProps.minAmount ||
minAmount.symbol !== prevProps.minAmount.symbol ||
minAmount.amount !== prevProps.minAmount.amount)) {
const { amount } = this.props
if (amount && (!prevProps.amount ||
amount.symbol !== prevProps.amount.symbol ||
amount.amount !== prevProps.amount.amount)) {
await this.stop()
this.start()
}
Expand Down
115 changes: 98 additions & 17 deletions src/modules/register/UIARegister.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ import CopyToClipboard from 'react-copy-to-clipboard'
import tt from 'counterpart'
import cn from 'classnames'
import golos, { api, } from 'golos-lib-js'
import { Asset } from 'golos-lib-js/lib/utils';
import { Asset, AssetEditor } from 'golos-lib-js/lib/utils';
import { key_utils, PrivateKey } from 'golos-lib-js/lib/auth/ecc'
import Link from 'next/link'
import { Formik, ErrorMessage, } from 'formik'

import LoadingIndicator from '@/elements/LoadingIndicator'
import AmountField from '@/elements/forms/AmountField'
import AccountName from '@/elements/register/AccountName'
import VerifyWayTabs from '@/elements/register/VerifyWayTabs'
import TransferWaiter from '@/modules/register/TransferWaiter'
Expand Down Expand Up @@ -153,6 +155,9 @@ class UIARegister extends React.Component {
this.setState({
rules: { ...deposit, creator: asset.creator, telegram },
minAmount,
initialForm: {
amount: AssetEditor(minAmount),
},
registrar,
sym,
copied_addr: false,
Expand Down Expand Up @@ -282,25 +287,25 @@ class UIARegister extends React.Component {
}

_renderParams = () => {
const { rules, sym, registrar, minAmount } = this.state
const { rules, sym, registrar, minAmount, waiting } = this.state
const username = registrar.name
const { memo_fixed } = rules
let details = rules.details
if (memo_fixed) {
details = details.split('<account>').join(username)
}
return <div style={{fontSize: "90%"}}>
<hr />
{details && <div style={{ whiteSpace: 'pre-line', }}>
{waiting && <hr />}
{waiting && details && <div style={{ whiteSpace: 'pre-line', }}>
{details}
<br/><br/></div>}
{minAmount && <div>
{tt('uia_register_jsx.req_amount')} <b>{minAmount.floatString}</b></div>}
{!waiting && minAmount && <div>
{tt('uia_register_jsx.min_amount')} <b>{minAmount.floatString}</b>.</div>}
</div>;
}

_renderApi = () => {
const { sym, apiLoaded } = this.state
const { sym, apiLoaded, waiting } = this.state
if (!apiLoaded) {
return (<div>
<br />
Expand Down Expand Up @@ -334,14 +339,14 @@ class UIARegister extends React.Component {
}
const { address } = apiLoaded
return (<div>
{this._renderTo(address, null)}
{waiting && this._renderTo(address, null)}
{this._renderParams(false)}
{this._renderWaiter()}
{waiting ? this._renderWaiter() : this._renderForm()}
</div>)
}

_renderWaiter = () => {
const { minAmount, registrar, onTransfer } = this.state
const { waitAmount, registrar, onTransfer } = this.state
if (!onTransfer) {
onTransfer = async (deposited) => {
this.setState({
Expand Down Expand Up @@ -372,9 +377,85 @@ class UIARegister extends React.Component {
})
}
}
return <TransferWaiter
username={registrar.name}
minAmount={minAmount} title={''} onTransfer={onTransfer} />
return <div>
<div style={{ fontSize: '90%', marginTop: '0.5rem', marginBottom: '0.25rem' }}>
{tt('uia_register_jsx.enter_amount')}<b>{waitAmount.floatString}</b>.
</div>
<TransferWaiter
username={registrar.name}
amount={waitAmount} title={''} onTransfer={onTransfer} />
</div>
}

amountValidate = (values) => {
const errors = {}
const { minAmount } = this.state
if (values.amount.asset.lt(minAmount)) {
errors.amount = tt('uia_register_jsx.min_amount') + minAmount.floatString
}
this.setState({
amountSubmitError: ''
})
return errors
}

_onAmountSubmit = async (values) => {
const waitAmount = values.amount.asset
try {
let fp = await callApi('/api/reg/get_free_poller/' + waitAmount.toString())
fp = await fp.json()
if (fp.status !== 'ok') {
throw new Error(fp.error || 'Unknown error')
}
if (fp.amount !== waitAmount.toString()) {
throw new Error('Slot is used')
}
} catch (err) {
this.setState({
amountSubmitError: err.message === 'Slot is used' ? tt('uia_register_jsx.slot_is_used') : err.message
})
return
}
this.setState({
waiting: true,
waitAmount
})
}

_renderForm = () => {
const { initialForm, amountSubmitError } = this.state
return <Formik
initialValues={initialForm}
validate={this.amountValidate}
onSubmit={this._onAmountSubmit}
>
{({
handleSubmit, isSubmitting, isValid, dirty, errors, touched, values, handleChange, setFieldValue,
}) => (
<form
onSubmit={handleSubmit}
autoComplete='off'
>
<div style={{ fontSize: '90%', marginTop: '0.5rem', marginBottom: '0.25rem' }}>
{tt('uia_register_jsx.enter_amount')}
</div>
<div className='input-group'>
<AmountField
name='amount'
className='input-group-field'
/>
</div>
<ErrorMessage name='amount' component='div' className='error' />
{amountSubmitError && <div className='error'>{amountSubmitError}</div>}

{isSubmitting && <LoadingIndicator type='circle' />}
<button className={'button ' + (isSubmitting || !isValid ? ' disabled' : '')}
type='submit' disabled={isSubmitting || !isValid}>
{tt('g.continue')}
</button>
</form>
)}
</Formik>
}

render() {
Expand All @@ -385,7 +466,7 @@ class UIARegister extends React.Component {
if (loading) {
content = <LoadingIndicator type='circle' />
} else {
const { assets, sym } = this.state
const { assets, sym, waiting } = this.state

const path = this.getPath()[0]

Expand Down Expand Up @@ -431,8 +512,8 @@ class UIARegister extends React.Component {
memo_fixed = memo_fixed.split('<account>').join(username)
}
form = <div>
{this._renderTo(to, to_fixed)}
{memo_fixed ? <div>
{waiting && this._renderTo(to, to_fixed)}
{(waiting && memo_fixed) ? <div>
{tt('uia_register_jsx.memo_fixed')}:<br/>
<span style={{wordWrap: 'break-word', color: '#4BA2F2', fontSize: '120%'}}>
{memo_fixed}
Expand All @@ -445,7 +526,7 @@ class UIARegister extends React.Component {
<br/>
</div> : null}
{this._renderParams()}
{this._renderWaiter()}
{waiting ? this._renderWaiter() : this._renderForm()}
</div>
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/modules/register/UIARegister.scss
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,8 @@
background-color: rgba(208,208,208,0.45);
border: 1px solid rgba(128,128,128,0.45);
}

.error {
margin-bottom: 0.75rem;
}
}

0 comments on commit 5a9c0fe

Please sign in to comment.