Skip to content

Commit

Permalink
UIA register - Multi-step exchange
Browse files Browse the repository at this point in the history
  • Loading branch information
1aerostorm committed Jan 8, 2024
1 parent de3c172 commit 52044ae
Show file tree
Hide file tree
Showing 8 changed files with 274 additions and 112 deletions.
7 changes: 5 additions & 2 deletions config/default.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"rest_api": "https://dev.golos.app",
"rest_api": "http://89.22.173.104:3000",
"allowed_clients": [
"dev.golos.app",
"devnotify.golos.app",
Expand All @@ -14,7 +14,10 @@
"signing_key": "5K67PNheLkmxkgJ5UjvR8Nyt3GVPoLEN1dMZjFuNETzrNyMecPG",
"delegation": "75000.000000 GESTS",
"free_regs_per_day": 10,
"uias": ["YMUSDT", "YMPZM", "YMHIVE", "TESTF"]
"uias": {
"assets": ["YMUSDT", "YMPZM", "YMHIVE", "YMXMR", "TESTF"],
"YMXMR": ["YMXHR/YMPZM", "YMPZM/YMUSDT", "YMUSDT/GOLOS"]
}
},
"server_session_secret": "exiKdyF+IwRIXJDmtGIl4vWUz4i3eVSISpfZoeYc0s4=",
"session_cookie_key": "X-Reg-ISession",
Expand Down
7 changes: 4 additions & 3 deletions src/elements/forms/AmountField.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,19 @@ class AmountField extends React.Component {
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)}
{...rest} onChange={(e) => this.onChange(e, values, form)}
/>
}

onChange = (e, values, setFieldTouched, setFieldValue) => {
onChange = (e, values, form) => {
const { name } = this.props
const newAmount = values[name].withChange(e.target.value)
if (newAmount.hasChange && newAmount.asset.amount >= 0) {
const { setFieldTouched, setFieldValue } = form
setFieldValue(name, newAmount)
setFieldTouched(name, true, false)
if (this.props.onChange) {
this.props.onChange(newAmount.asset)
this.props.onChange(newAmount.asset, form)
}
}
}
Expand Down
10 changes: 8 additions & 2 deletions src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,15 @@
"api_error_details": "and send the error details:",
"free_poller": "Cannot calculate minimal amount. Try again later, please. Or try another currency.",
"deposited": "Received ",
"deposited2": ". Placing limit order to exchange it to GOLOS to register your account.",
"deposited2_SYM": ". Placing limit order to exchange it to %(SYM)s to register your account.",
"cannot_place_order": "Cannot place order: ",
"you_will_receive": "You will receive "
"you_will_receive": "You will receive ",
"cannot_check_orders": "Cannot check exchange ability. Try again later. Or try another currency. Error details: ",
"no_orders": "No orders in ",
"cannot_register_with_it": ", cannot register.",
"too_low_orders": "Too low orders in ",
"unknown_error": " - error in ",
"too_low_amount_to_register": "Too low amount to register."
},
"invites_jsx": {
"claim_wrong_secret": "Wrong secret",
Expand Down
10 changes: 8 additions & 2 deletions src/locales/ru-RU.json
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,15 @@
"api_error_details": "и сообщите подробности ошибки:",
"free_poller": "Не удается рассчитать минимальную сумму. Попробуйте позже, или другую валюту.",
"deposited": "Получено ",
"deposited2": ". Размещаем ордер для обмена их на GOLOS для регистрации вашего аккаунта...",
"deposited2_SYM": ". Размещаем ордер для обмена их на %(SYM)s для регистрации вашего аккаунта...",
"cannot_place_order": "Не удается разместить ордер: ",
"you_will_receive": "Вы получите примерно "
"you_will_receive": "Вы получите примерно ",
"cannot_check_orders": "Не удается проверить возможность обмена. Попробуйте позже, или другую валюту. Подробнее об ошибке: ",
"no_orders": "Нет ордеров по направлению ",
"cannot_register_with_it": ", не можем зарегистрировать за такую сумму.",
"too_low_orders": "Слишком мало ордеров по направлению ",
"unknown_error": " - ошибка по направлению ",
"too_low_amount_to_register": "Слишком малая сумма для регистрации."
},
"invites_jsx": {
"claim_wrong_secret": "Неверно указан ключ",
Expand Down
203 changes: 130 additions & 73 deletions src/modules/register/UIARegister.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import AmountField from '@/elements/forms/AmountField'
import AccountName from '@/elements/register/AccountName'
import VerifyWayTabs from '@/elements/register/VerifyWayTabs'
import TransferWaiter from '@/modules/register/TransferWaiter'
import { apidexGetPrices, apidexExchange } from '@/utils/ApidexApiClient'
import { apidexGetPrices } from '@/utils/ApidexApiClient'
import KeyFile from '@/utils/KeyFile'
import { delay, } from '@/utils/misc'
import { emptyAuthority } from '@/utils/RecoveryUtils'
Expand Down Expand Up @@ -57,6 +57,10 @@ class UIARegister extends React.Component {
error: '',
}

constructor(props) {
super(props)
}

async componentDidMount() {
const { clientCfg } = this.props

Expand All @@ -66,17 +70,18 @@ class UIARegister extends React.Component {

const { apidex_service } = clientCfg.config
const { uias } = clientCfg.config.registrar
const syms = uias.assets

const path = this.getPath()
if (path[1]) {
const params = new URLSearchParams(path[1])
const sym = params.get('uia')
if (sym) {
let assets
assets = await golos.api.getAssetsAsync('', uias)
assets = await golos.api.getAssetsAsync('', syms)

let error
if (!uias.includes(sym)) {
if (!syms.includes(sym)) {
error = sym + tt('uia_register_jsx.no_such_asset')
} else {
for (const asset of assets) {
Expand Down Expand Up @@ -188,8 +193,8 @@ class UIARegister extends React.Component {
}

let assets = []
if (uias.length) {
assets = await golos.api.getAssetsAsync('', uias)
if (syms.length) {
assets = await golos.api.getAssetsAsync('', syms)
}
this.setState({
loading: false,
Expand Down Expand Up @@ -354,32 +359,63 @@ class UIARegister extends React.Component {
const { waitAmount, registrar, onTransfer } = this.state
if (!onTransfer) {
onTransfer = async (deposited) => {
this.setState({
deposited
})
let order_receipts
try {
let mor = await callApi('/api/reg/make_order_receipt/' + deposited.toString() + '/true')
mor = await mor.json()
if (mor.status !== 'ok' || mor.error) {
throw new Error(mor.error || 'Unknown error')
}

let error
for (let tr = 1; tr <= 10; ++tr) {
try {
let orr = await callApi('/api/reg/place_order/' + deposited.toString(), {})
orr = await orr.json()
if (orr.status === 'ok') {
console.log(orr)
this.props.updateApiState(orr)
return
order_receipts = mor.order_receipts
this.setState({
deposited,
depositedToSym: order_receipts[0][1].split(' ')[1]
})
} catch (err) {
console.error(err)
this.setState({
deposited,
error: err.message || err.toString()
})
return
}

while (order_receipts.length) {
let error
for (let tr = 1; tr <= 10; ++tr) {
try {
let orr = await callApi('/api/reg/place_order', {})
orr = await orr.json()
if (orr.status === 'ok') {
console.log(orr)
if (orr.order_receipts && orr.order_receipts[0]) {
order_receipts = orr.order_receipts
this.setState({
depositedToSym: order_receipts[0][1].split(' ')[1]
})
} else {
this.props.updateApiState(orr)
return
}
break
}
console.error('place_order', orr)
throw new Error(orr.error)
} catch (err) {
console.error('place_order throws', err)
error = (err && err.toString) && err.toString()
}
console.error('place_order', orr)
throw new Error(orr.error)
} catch (err) {
console.error('place_order throws', err)
error = (err && err.toString) && err.toString()
await delay(3000)
}
await delay(3000)
}

this.setState({
error: tt('uia_register_jsx.cannot_place_order') + error
})
if (error) {
this.setState({
error: tt('uia_register_jsx.cannot_place_order') + error
})
break
}
}
}
}
return <div>
Expand All @@ -392,7 +428,7 @@ class UIARegister extends React.Component {
</div>
}

amountValidate = (values) => {
amountValidate = async (values) => {
const errors = {}
const { minAmount } = this.state
if (values.amount.asset.lt(minAmount)) {
Expand All @@ -401,23 +437,39 @@ class UIARegister extends React.Component {
this.setState({
amountSubmitError: ''
})

if (!errors.amount) {
try {
let fp = await callApi('/api/reg/make_order_receipt/' + values.amount.asset.toString() + '/false')
fp = await fp.json()
let receive
if (fp.error) {
errors.amount = fp.error
} else {
receive = await Asset(fp.result)

const cprops = await golos.api.getChainPropertiesAsync()
let { create_account_min_golos_fee } = cprops
create_account_min_golos_fee = await Asset(create_account_min_golos_fee)
if (create_account_min_golos_fee.gt(receive)) {
errors.amount = tt('uia_register_jsx.too_low_amount_to_register')
}
}
if (receive)
this.setState({
receive,
})
} catch (err) {
console.error(err)
errors.amount = 'Internal error'
return
}
}

return errors
}

_onAmountChange = async (amount) => {
const { clientCfg } = this.props
const { apidex_service } = clientCfg.config
let res
try {
res = await apidexExchange(apidex_service, amount, 'GOLOS')
} catch (err) {
console.error(err)
}
if (res) {
this.setState({
receive: res
})
}
_onAmountChange = async (amount, form) => {
}

_onAmountSubmit = async (values) => {
Expand Down Expand Up @@ -449,37 +501,40 @@ class UIARegister extends React.Component {
initialValues={initialForm}
validate={this.amountValidate}
onSubmit={this._onAmountSubmit}
validateOnMount={true}
>
{({
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'
onChange={this._onAmountChange}
/>
</div>
<ErrorMessage name='amount' component='div' className='error' />
{amountSubmitError && <div className='error'>{amountSubmitError}</div>}
{!errors.amount && !amountSubmitError && receive ? <div style={{marginBottom:'0.5rem'}}>
{tt('uia_register_jsx.you_will_receive')}<b>~{receive.floatString}.</b>
</div> : null}

{isSubmitting && <LoadingIndicator type='circle' />}
<button className={'button ' + (isSubmitting || !isValid ? ' disabled' : '')}
type='submit' disabled={isSubmitting || !isValid}>
{tt('g.continue')}
</button>
</form>
)}
handleSubmit, isSubmitting, isValid, dirty, errors, touched, values, handleChange, setFieldValue, setFieldError,
}) => {
return (
<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'
onChange={this._onAmountChange}
/>
</div>
{errors.amount && <div className='error'>{errors.amount}</div>}
{amountSubmitError && <div className='error'>{amountSubmitError}</div>}
{!errors.amount && !amountSubmitError && receive ? <div style={{marginBottom:'0.5rem'}}>
{tt('uia_register_jsx.you_will_receive')}<b>~{receive.floatString}.</b>
</div> : null}

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

Expand Down Expand Up @@ -514,13 +569,15 @@ class UIARegister extends React.Component {
if (error) {
form = <div className='error'>{error}</div>
} else if (sym) {
const { deposited } = this.state
const { deposited, depositedToSym } = this.state
if (deposited) {
form = <div>
<center>
{tt('uia_register_jsx.deposited')}
<b>{deposited.floatString}</b>
{tt('uia_register_jsx.deposited2')}
{tt('uia_register_jsx.deposited2_SYM', {
SYM: depositedToSym || 'GOLOS'
})}
<br />
<LoadingIndicator type='circle' />
</center>
Expand Down
Loading

0 comments on commit 52044ae

Please sign in to comment.