import React, { Fragment, PureComponent } from 'react';
import web3 from 'web3';
import EmbarkJS from 'Embark/EmbarkJS';
import { connect } from 'react-redux';
import { actions as accountActions, getDefaultAccount } from '../../reducers/accounts';
import { hash } from 'eth-ens-namehash';
import { isNil } from 'lodash';
import Hidden from '@material-ui/core/Hidden';
import Typography from '@material-ui/core/Typography';
import ENSSubdomainRegistry from 'Embark/contracts/ENSSubdomainRegistry';
import ENSRegistry from 'Embark/contracts/ENSRegistry';
import { Button, Field, TextInput, MobileSearch, MobileButton, Card, Info, Text } from '../../ui/components'
import { IconCheck } from '../../ui/icons'
import { keyFromXY } from '../../utils/ecdsa';
import EditOptions from './EditOptions';
import ReleaseDomainAlert from './ReleaseDomain';
import theme from '../../ui/theme'
import { withFormik } from 'formik';
import PublicResolver from 'Embark/contracts/PublicResolver';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import RegisterSubDomain from '../ens/registerSubDomain';
import StatusLogo from '../../ui/icons/components/StatusLogo'
import EnsLogo from '../../ui/icons/logos/ens.png';
import { formatPrice } from '../ens/utils';
import CheckCircle from '../../ui/icons/components/baseline_check_circle_outline.png';
const { getPrice, getExpirationTime, release } = ENSSubdomainRegistry.methods;
import NotInterested from '@material-ui/icons/NotInterested';
import Face from '@material-ui/icons/Face';
import Copy from './copy';
import IDNANormalizer from 'idna-normalize';
const normalizer = new IDNANormalizer();
const invalidSuffix = '0000000000000000000000000000000000000000'
const nullAddress = '0x0000000000000000000000000000000000000000'
const validAddress = address => address != nullAddress;
const validStatusAddress = address => !address.includes(invalidSuffix);
const formatName = domainName => domainName.includes('.') ? normalizer.normalize(domainName) : normalizer.normalize(`${domainName}.stateofus.eth`);
const getDomain = fullDomain => formatName(fullDomain).split('.').slice(1).join('.');
const hashedDomain = domainName => hash(getDomain(domainName));
const registryIsOwner = address => address == ENSSubdomainRegistry._address;
const { soliditySha3, fromWei } = web3.utils;
const cardStyle = {
width: '100%',
padding: '30px',
height: '425px'
}
const addressStyle = {
fontSize: '18px',
fontWeight: 400,
cursor: 'copy',
wordWrap: 'break-word',
}
const backButton = {
fontSize: '40px',
color: theme.accent,
cursor: 'pointer'
}
const generatePrettyDate = (timestamp) => new Date(timestamp * 1000).toDateString();
const DisplayBox = ({ displayType, pubKey }) => (
);
const MobileAddressDisplay = ({ domainName, address, statusAccount, expirationTime, defaultAccount, isOwner, edit, onSubmit }) => (
{isOwner ? : }
{formatName(domainName)}
{expirationTime && Locked until {generatePrettyDate(expirationTime)}}
{isOwner
? edit ? 'Edit Contact Code' : 'You\'re the owner of this name'
: 'Name is unavailable'}
{edit ? 'The contact code connects the domain with a unique Status account' : 'registered to the addresses below'}
{edit && }
{!edit && }
{!edit && validStatusAddress(statusAccount) && }
)
class RenderAddresses extends PureComponent {
state = { copied: false, editMenu: false, editAction: false }
render() {
const { domainName, address, statusAccount, expirationTime, defaultAccount, ownerAddress, setStatus, registryOwnsDomain } = this.props
const { copied, editMenu, editAction, submitted } = this.state
const markCopied = (v) => { this.setState({ copied: v }) }
const isCopied = address => address == copied;
const renderCopied = address => isCopied(address) && Copied!;
const onClose = value => { this.setState({ editAction: value, editMenu: false }) }
const isOwner = defaultAccount === ownerAddress;
const closeReleaseAlert = value => {
if (!isNil(value)) {
this.setState({ submitted: true })
release(
soliditySha3(domainName),
hash('stateofus.eth'),
)
.send()
} else {
this.setState({ editAction: null })
}
}
return (
{formatName(domainName)}{expirationTime && (Expires {generatePrettyDate(expirationTime)})} Resolves To:
{address &&
Ethereum Address {renderCopied(address)}}
{address}
{validStatusAddress(statusAccount) &&
Status Address {renderCopied(statusAccount)}}
{validStatusAddress(statusAccount) &&
{statusAccount}
}
{submitted ? : { this.setState({ submitted: true}) }}/>}
{isOwner && !editAction && { this.setState({ editMenu: true }) } }/>}
)
}
}
const RegisterInfoCard = ({ formattedDomain, domainPrice, registryOwnsDomain }) => (
{formattedDomain.toLowerCase()} can be registered for {!!domainPrice && formatPrice(fromWei(domainPrice))} SNT
{formattedDomain.toLowerCase()}
{!!domainPrice && formatPrice(fromWei(domainPrice))} SNT / 1 year
{registryOwnsDomain ?
'This name will be pointed to the wallet address and contact code below' :
'This domain is not owned by the registy'}
)
const TransactionComplete = ({ type, setStatus }) => (
{Copy[type]['title']['sub']}
{Copy[type]['title']['body']}
{Copy[type]['subheading']}
{ setStatus(null) } } />
);
class Register extends PureComponent {
state = { domainPrice: null };
componentDidMount() {
const { domainName } = this.props;
getPrice(hashedDomain(domainName))
.call()
.then((res) => { this.setState({ domainPrice: res })});
}
onRegistered = (address, statusAccount) => {
const { domainPrice } = this.state;
const { subtractFromBalance } = this.props;
subtractFromBalance(domainPrice);
this.setState({ registered: { address, statusAccount } });
}
render() {
const { domainName, setStatus, style, registryOwnsDomain } = this.props;
const { domainPrice, registered, submitted } = this.state;
const formattedDomain = formatName(domainName);
const formattedDomainArray = formattedDomain.split('.');
return (
{!registered && !submitted ?
{registryOwnsDomain &&
{ this.setState({ submitted: true }) }}
registeredCallbackFn={this.onRegistered} />}
:
submitted && !registered ? : }
)
}
}
const mapDispatchToProps = dispatch => ({
subtractFromBalance(amount) {
dispatch(accountActions.subtractfromSntTokenBalance(amount));
},
});
const mapStateToProps = state => ({
defaultAccount: getDefaultAccount(state)
})
const ConnectedRegister = connect(mapStateToProps, mapDispatchToProps)(Register);
const DisplayAddress = connect(mapStateToProps)((props) => (
{validAddress(props.address) ?
:
{props.domainName}
}
))
const LookupForm = ({ handleSubmit, values, handleChange, justSearch }) => (
)
const InnerForm = ({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
status,
setStatus,
}) => (
{!status
?
: validAddress(status.address) ?
:
}
)
const NameLookup = withFormik({
mapPropsToValues: props => ({ domainName: '' }),
async handleSubmit(values, { status, setSubmitting, setStatus }) {
const { domainName } = values;
const { methods: { owner, resolver } } = ENSRegistry;
const lookupHash = hash(formatName(domainName));
const resolverAddress = await resolver(lookupHash).call();
const resolverContract = resolverAddress !== nullAddress
? new EmbarkJS.Contract({ abi: PublicResolver._jsonInterface, address: resolverAddress })
: PublicResolver;
const { addr, pubkey } = resolverContract.methods;
const address = addr(lookupHash).call();
const keys = pubkey(lookupHash).call();
const ownerAddress = owner(lookupHash).call();
const suffixOwner = owner(hash(getDomain(domainName))).call();
const expirationTime = getExpirationTime(lookupHash).call();
Promise.all([address, keys, ownerAddress, expirationTime, suffixOwner])
.then(([ address, keys, ownerAddress, expirationTime, suffixOwner ]) => {
const statusAccount = keyFromXY(keys[0], keys[1]);
const registryOwnsDomain = registryIsOwner(suffixOwner)
setStatus({ address, statusAccount, expirationTime, ownerAddress, registryOwnsDomain });
})
}
})(InnerForm)
export default NameLookup;