Merge pull request #7 from status-im/snt-voting-form-handling

Snt voting form handling
This commit is contained in:
Richard Ramos 2018-05-31 12:57:40 -08:00 committed by GitHub
commit 0356daef09
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 270 additions and 125 deletions

4
.babelrc Normal file
View File

@ -0,0 +1,4 @@
{
"plugins": ["transform-object-rest-spread"],
"presets": ["stage-2"]
}

View File

@ -2,139 +2,139 @@ import EmbarkJS from 'Embark/EmbarkJS';
import ERC20Token from 'Embark/contracts/ERC20Token';
import ProposalCuration from 'Embark/contracts/ProposalCuration';
import SNT from 'Embark/contracts/SNT';
import React, { Component, Fragment } from 'react';
import React, { PureComponent, Fragment } from 'react';
import { Form, FormGroup, FormControl, HelpBlock, Button, Alert } from 'react-bootstrap';
import web3 from "Embark/web3"
import web3 from "Embark/web3";
import { withFormik } from 'formik';
import FieldGroup from '../standard/FieldGroup';
import TokenPermissions from '../standard/TokenPermission'
class ProposalManager extends Component {
const { setSubmitPrice } = ProposalCuration.methods;
class InnerForm extends PureComponent {
constructor(props) {
super(props);
this.state = {
submitPrice: "Loading...",
url: "",
title: "",
description: "",
canSubmit: true
};
}
constructor(props) {
super(props);
this.state = {
submitPrice: "Loading...",
canSubmit: true
};
}
componentDidMount(){
this.loadPrice();
}
componentDidMount(){
this.loadPrice();
}
componentWillReceiveProps(){
this.loadPrice();
}
componentWillReceiveProps(){
this.loadPrice();
}
async loadPrice(){
__embarkContext.execWhenReady(async () => {
try {
let _b = await ProposalCuration.methods.getSubmitPrice(web3.eth.defaultAccount).call();
this.setState({
submitPrice: _b,
canSubmit: true
});
} catch(err){
this.setState({
canSubmit: false,
submitPrice: "-"
});
}
async loadPrice(){
__embarkContext.execWhenReady(async () => {
try {
let _b = await ProposalCuration.methods.getSubmitPrice(web3.eth.defaultAccount).call();
this.setState({
submitPrice: _b,
canSubmit: true
});
}
} catch(err){
this.setState({
canSubmit: false,
submitPrice: "-"
});
}
});
}
async handleClick(){
let description = {
"url": this.state.url,
"title": this.state.title,
"description": this.state.description
};
setPrice = (address = web3.eth.defaultAccount, allowed = true, stakeValue = 1) => {
setSubmitPrice(address, allowed, stakeValue)
.send()
.then(res => {
this.setState({ ...state, canSubmit: true });
console.log(res);
})
.catch(err => { console.log(err) })
}
EmbarkJS.Storage.saveText(JSON.stringify(description))
.then(async (hash) => {
let hexHash = web3.utils.toHex(hash);
let receipt = await SNT.methods.approve(
ProposalCuration.options.address,
this.state.submitPrice)
.send({from: web3.eth.defaultAccount, gasLimit: 1000000});
console.log(receipt);
receipt = await ProposalCuration.methods.submitProposal(
"0x00",
"0x0000000000000000000000000000000000000000",
0,
"0x00",
hexHash
)
.send({from: web3.eth.defaultAccount, gasLimit: 1000000});
console.log(receipt);
})
.catch((err) => {
if(err){
// TODO show error
console.log("Storage saveText Error => " + err.message);
}
});
}
render(){
return (
<Fragment>
{
!this.state.canSubmit ?
<Alert bsStyle="warning">
Account not allowed to submit proposals
</Alert>
: ''
}
<h2>Add proposal</h2>
<p>Execute this on the console if proposal submit is not allowed</p>
<code>await ProposalCuration.methods.setSubmitPrice(web3.eth.defaultAccount, true, 1).send();</code>
<h3>Price: {this.state.submitPrice}</h3>
<Form>
<FormGroup>
<label>
Title:
<FormControl
type="text"
defaultValue={this.state.title}
onChange={(e) => this.setState({title: e.target.value }) } />
</label>
</FormGroup>
<FormGroup>
<label>
Description:
<FormControl
type="text"
defaultValue={this.state.description}
onChange={(e) => this.setState({description: e.target.value }) } />
</label>
</FormGroup>
<FormGroup>
<label>
URL:
<FormControl
type="text"
defaultValue={this.state.url}
onChange={(e) => this.setState({url: e.target.value }) } />
</label>
</FormGroup>
{
this.state.canSubmit ?
<FormGroup>
<Button onClick={(e) => this.handleClick(e)}>Submit</Button>
</FormGroup>
: ''
}
</Form>
</Fragment>
)
}
render() {
const { values, errors, touched, handleChange, handleBlur, handleSubmit, isSubmitting, setFieldValue } = this.props;
const { canSubmit } = this.state;
return (
<Fragment>
{!canSubmit &&
<Alert bsStyle="warning">
Account not allowed to submit proposals <Button onClick={(e) => this.setPrice()}>Click to enable (Admin only)</Button>
</Alert>
}
<TokenPermissions methods={SNT.methods} spender={ProposalCuration._address} symbol='SNT' />
<hr/>
<h2>Add proposal</h2>
<h3>Price: {this.state.submitPrice}</h3>
<Form onSubmit={handleSubmit}>
<FieldGroup
id="title"
name="title"
type="text"
label="Title"
onChange={handleChange}
onBlur={handleBlur}
value={values.title}
/>
<FieldGroup
id="description"
name="description"
type="text"
label="Description"
onChange={handleChange}
onBlur={handleBlur}
value={values.description}
/>
<FieldGroup
id="url"
name="url"
type="text"
label="URL"
onChange={handleChange}
onBlur={handleBlur}
value={values.url}
/>
<Button type="submit" disabled={!canSubmit || isSubmitting}>{isSubmitting ? 'Submission in progress' : 'Submit'}</Button>
</Form>
</Fragment>
)
}
}
const ProposalManager = withFormik({
mapPropsToValues: props => ({ title: '', description: '', url: '' }),
validate(values) {},
handleSubmit(values, { setSubmitting}){
const { title, description, url } = values;
const { saveText } = EmbarkJS.Storage;
const { toHex } = web3.utils;
const { submitProposal } = ProposalCuration.methods;
saveText(JSON.stringify(description))
.then(hash => {
const hexHash = toHex(hash);
//TODO create toggle for address approval
submitProposal(
"0x00",
"0x0000000000000000000000000000000000000000",
0,
"0x00",
hexHash
)
.send({from: web3.eth.defaultAccount, gasLimit: 1000000})
.then(res => {
setSubmitting(false);
console.log(res);
})
.catch(err => {
setSubmitting(false);
//TODO show error
console.log('Storage saveText Error: ', err.message)
});
})
}
})(InnerForm)
export default ProposalManager;

View File

@ -0,0 +1,20 @@
import React from 'react';
import { FormGroup, FormControl, HelpBlock, ControlLabel, InputGroup } from 'react-bootstrap';
const FieldGroup = ({ id, label, button, error, ...props }) => (
<FormGroup controlId={id} validationState={error ? 'error' : null}>
<ControlLabel>{label}</ControlLabel>
{button
? <InputGroup>
<InputGroup.Button>
{button}
</InputGroup.Button>
<FormControl {...props} />
</InputGroup>
: <FormControl {...props} />
}
{error && <HelpBlock>{error}</HelpBlock>}
</FormGroup>
)
export default FieldGroup;

View File

@ -0,0 +1,107 @@
import React, { Fragment, PureComponent } from 'react';
import { Tooltip, OverlayTrigger } from 'react-bootstrap';
import web3 from "Embark/web3"
import Toggle from 'react-toggle';
import { BigNumber } from './utils'
import "react-toggle/style.css";
// We set an allowance to be "unlimited" by setting it to
// it's maximum possible value -- namely, 2^256 - 1.
const unlimitedAllowance = new BigNumber(2).pow(256).sub(1);
const getDefaultAccount = () => web3.eth.defaultAccount;
const SUPPORTED_TOKENS = ['SNT'];
const commaize = (str) => Number(str).toLocaleString();
const balanceTooltip = (balance, approved) => (
<Tooltip id="balanceTooltip">
{`Your balance of ${commaize(balance)} is ${approved ? 'approved' : 'not approved'} for spending by the contract`}
</Tooltip>
);
class TokenHandle extends PureComponent {
constructor(props){
super(props);
this.state = { balance: 0, approved: 0 };
}
componentDidMount() {
setTimeout(() => {
this.getBalance();
this.getAllowance();
}, 1000)
}
getBalance = () => {
this.props.methods.balanceOf(getDefaultAccount())
.call()
.then(balance => { this.setState({ ...this.state, balance }) });
}
getAllowance = () => {
const { methods, spender } = this.props;
methods.allowance(getDefaultAccount(), spender)
.call()
.then(approved => {
this.setState({ ...this.state, approved })
})
}
toggleApproved = () => {
const { approved } = this.state;
const { methods: { approve }, spender } = this.props;
const isApproved = !!Number(approved);
let amountToApprove = isApproved ? 0 : unlimitedAllowance;
console.log("approve(\""+spender+"\",\"" +amountToApprove +"\")")
approve(
spender,
amountToApprove
)
.send()
.then(approval => {
const { events: { Approval: { returnValues: { _value, _amount } } } } = approval
console.log('value',_value, approval)
this.setState({ ...this.state, approved: _value || _amount })
}).catch(err => {
console.log("Approve failed: " + err);
})
}
render() {
const { symbol } = this.props;
const { balance, approved } = this.state;
const balanceTooltip = (
<Tooltip id="balanceTooltip">
{`Your balance of ${commaize(balance)} is ${approved ? 'approved' : 'not approved'} for spending by the contract`}
</Tooltip>
);
return (
<OverlayTrigger placement="top" overlay={balanceTooltip}>
<div style={{ display: 'flex' }}>
<Toggle
checked={!!Number(approved)}
name={symbol}
onChange={this.toggleApproved} />
<label style={{ margin: '2px 0px 0px 10px', fontWeight: 400 }}>{`${Number(balance).toLocaleString()} ${symbol.toUpperCase()}`}</label>
</div>
</OverlayTrigger>
)
}
}
const tooltip = (
<Tooltip id="tooltip">
Turn on permissions for a token to enable its use with the ENS subdomain registry.
</Tooltip>
);
const TokenPermissions = (props) => (
<Fragment>
<OverlayTrigger placement="right" overlay={tooltip}>
<h3>Token Permissions</h3>
</OverlayTrigger>
<hr/>
<TokenHandle {...props} />
</Fragment>
)
export default TokenPermissions;

View File

@ -0,0 +1,9 @@
import BigNumber from 'bignumber.js';
// By default BigNumber's `toString` method converts to exponential notation if the value has
// more then 20 digits. We want to avoid this behavior, so we set EXPONENTIAL_AT to a high number
BigNumber.config({
EXPONENTIAL_AT: 1000,
});
export { BigNumber };

View File

@ -17,10 +17,15 @@
},
"homepage": "https://github.com/status-im/contracts#readme",
"dependencies": {
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-stage-2": "^6.24.1",
"bignumber.js": "^5.0.0",
"formik": "^0.11.11",
"jquery": "^3.3.1",
"react": "^16.3.2",
"react-blockies": "^1.3.0",
"react-bootstrap": "^0.32.1",
"react-dom": "^16.3.2"
"react-dom": "^16.3.2",
"react-toggle": "^4.0.2"
}
}