From 9134f07fec4ac05f64b41397f5f5688ccea84804 Mon Sep 17 00:00:00 2001 From: Ezerous Date: Mon, 23 Apr 2018 15:43:38 +0300 Subject: [PATCH 1/6] Initial attempt --- .gitignore | 12 ++++--- contracts/Forum.sol | 7 +++- contracts/Migrations.sol | 2 +- package.json | 4 +++ src/index.js | 42 ++++++++++-------------- src/layouts/home/HomeContainer.js | 14 ++++++++ src/reducer.js | 4 +-- src/store.js | 26 +++++++++++---- src/util/drizzle/drizzleOptions.js | 18 +++++++++++ src/util/drizzle/rootSaga.js | 8 +++++ src/util/web3/getWeb3.js | 51 ------------------------------ src/util/web3/web3Reducer.js | 16 ---------- 12 files changed, 97 insertions(+), 107 deletions(-) create mode 100644 src/layouts/home/HomeContainer.js create mode 100644 src/util/drizzle/drizzleOptions.js create mode 100644 src/util/drizzle/rootSaga.js delete mode 100644 src/util/web3/getWeb3.js delete mode 100644 src/util/web3/web3Reducer.js diff --git a/.gitignore b/.gitignore index dd40e6f..ac47e30 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,9 @@ /node_modules package-lock.json +# Yarn +yarn.lock + # Testing /coverage @@ -11,6 +14,11 @@ package-lock.json /build /src/build +# Logs +npm-debug.log* +yarn-debug.log* +yarn-error.log* + # Misc .DS_Store .env.local @@ -18,9 +26,5 @@ package-lock.json .env.test.local .env.production.local -npm-debug.log* -yarn-debug.log* -yarn-error.log* - # Jetbrains .idea diff --git a/contracts/Forum.sol b/contracts/Forum.sol index 3732646..eef2e82 100644 --- a/contracts/Forum.sol +++ b/contracts/Forum.sol @@ -1,4 +1,4 @@ -pragma solidity ^0.4.17; +pragma solidity ^0.4.21; contract Forum { @@ -13,10 +13,15 @@ contract Forum { mapping (address => User) users; mapping (string => address) userAddresses; + event UserSignedUp( + string userName + ); + function signUp(string userName) public returns (bool) { // Also allows user to update his name - TODO: his previous name will appear as taken require(!isUserNameTaken(userName)); users[msg.sender] = User(userName, new uint[](0), new uint[](0)); userAddresses[userName] = msg.sender; + emit UserSignedUp(userName); return true; } diff --git a/contracts/Migrations.sol b/contracts/Migrations.sol index 26d7ce9..27598ad 100644 --- a/contracts/Migrations.sol +++ b/contracts/Migrations.sol @@ -1,4 +1,4 @@ -pragma solidity ^0.4.19; +pragma solidity ^0.4.21; contract Migrations { address public owner; diff --git a/package.json b/package.json index 6ffc6e6..108b889 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,9 @@ "truffle-contract": "^3.0.4" }, "dependencies": { + "drizzle": "^1.1.4", + "drizzle-react": "^1.1.1", + "drizzle-react-components": "^1.1.0", "react": "^16.3.0", "react-dom": "^16.3.0", "react-scripts": "1.1.1", @@ -18,6 +21,7 @@ "react-router-redux": "^4.0.8", "redux": "^3.7.2", "redux-auth-wrapper": "1.1.0", + "redux-saga": "0.16.0", "redux-thunk": "^2.2.0" }, "scripts": { diff --git a/src/index.js b/src/index.js index 0c2ee1b..16f0ed1 100644 --- a/src/index.js +++ b/src/index.js @@ -1,22 +1,23 @@ import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, IndexRoute, browserHistory } from 'react-router' -import { Provider } from 'react-redux' +import { DrizzleProvider } from 'drizzle-react' import { syncHistoryWithStore } from 'react-router-redux' import { UserIsAuthenticated, UserIsNotAuthenticated } from './util/wrappers.js' -import getWeb3 from "./util/web3/getWeb3"; // Layouts import App from './App' -import Home from './layouts/home/Home' +import HomeContainer from './layouts/home/HomeContainer' import Dashboard from './layouts/dashboard/Dashboard' import SignUp from './user/layouts/signup/SignUp' import Profile from './user/layouts/profile/Profile' - +import {LoadingContainer} from 'drizzle-react-components' import './index.css'; //??? + // Redux Store import store from './store' +import drizzleOptions from './util/drizzle/drizzleOptions' // ServiceWorker import registerServiceWorker from './registerServiceWorker'; @@ -24,28 +25,19 @@ import registerServiceWorker from './registerServiceWorker'; // Initialize react-router-redux. const history = syncHistoryWithStore(browserHistory, store); -// Initialize web3 and set in Redux. -getWeb3 - .then(results => { - console.log('Web3 initialized!') - }) - .catch(() => { - console.log('Error in web3 initialization.') - }); - - - ReactDOM.render(( - - - - - - - - - - + + + + + + + + + + + + ), document.getElementById('root') ); diff --git a/src/layouts/home/HomeContainer.js b/src/layouts/home/HomeContainer.js new file mode 100644 index 0000000..ac699a5 --- /dev/null +++ b/src/layouts/home/HomeContainer.js @@ -0,0 +1,14 @@ +import Home from './Home' +import { drizzleConnect } from 'drizzle-react' + +// May still need this even with data function to refresh component on updates for this contract. +const mapStateToProps = state => { + return { + Forum: state.contracts.Forum, + drizzleStatus: state.drizzleStatus + } +}; + +const HomeContainer = drizzleConnect(Home, mapStateToProps); + +export default HomeContainer diff --git a/src/reducer.js b/src/reducer.js index 2af2517..4c54292 100644 --- a/src/reducer.js +++ b/src/reducer.js @@ -1,12 +1,12 @@ import { combineReducers } from 'redux' import { routerReducer } from 'react-router-redux' import userReducer from './user/userReducer' -import web3Reducer from './util/web3/web3Reducer' +import { drizzleReducers } from 'drizzle' const reducer = combineReducers({ routing: routerReducer, user: userReducer, - web3: web3Reducer + ...drizzleReducers }); export default reducer diff --git a/src/store.js b/src/store.js index 0c98744..5f73ee5 100644 --- a/src/store.js +++ b/src/store.js @@ -1,22 +1,34 @@ -import { browserHistory } from 'react-router' -import { createStore, applyMiddleware, compose } from 'redux' +import {browserHistory} from 'react-router' +import {createStore, applyMiddleware, compose} from 'redux' import thunkMiddleware from 'redux-thunk' -import { routerMiddleware } from 'react-router-redux' +import {routerMiddleware} from 'react-router-redux' import reducer from './reducer' +import rootSaga from './util/drizzle/rootSaga' +import createSagaMiddleware from 'redux-saga' +import {generateContractsInitialState} from 'drizzle' +import drizzleOptions from './util/drizzle/drizzleOptions' // Redux DevTools (see also https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup) const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const routingMiddleware = routerMiddleware(browserHistory); +const sagaMiddleware = createSagaMiddleware(); + +const initialState = { + contracts: generateContractsInitialState(drizzleOptions) +}; const store = createStore( - reducer, - composeEnhancers( + reducer, + initialState, + composeEnhancers( applyMiddleware( - thunkMiddleware, - routingMiddleware + thunkMiddleware, + routingMiddleware, + sagaMiddleware ) ) ); +sagaMiddleware.run(rootSaga); export default store diff --git a/src/util/drizzle/drizzleOptions.js b/src/util/drizzle/drizzleOptions.js new file mode 100644 index 0000000..798ab7d --- /dev/null +++ b/src/util/drizzle/drizzleOptions.js @@ -0,0 +1,18 @@ +import Forum from './../../build/contracts/Forum.json' + +const drizzleOptions = { + web3: { + fallback: { + type: 'ws', + url: 'ws://127.0.0.1:8545' + } + }, + contracts: [ + Forum + ], + events: { + Forum: ['UserSignedUp'] + } +}; + +export default drizzleOptions \ No newline at end of file diff --git a/src/util/drizzle/rootSaga.js b/src/util/drizzle/rootSaga.js new file mode 100644 index 0000000..d9f654b --- /dev/null +++ b/src/util/drizzle/rootSaga.js @@ -0,0 +1,8 @@ +import { all, fork } from 'redux-saga/effects' +import { drizzleSagas } from 'drizzle' + +export default function* root() { + yield all( + drizzleSagas.map(saga => fork(saga)) + ) +} \ No newline at end of file diff --git a/src/util/web3/getWeb3.js b/src/util/web3/getWeb3.js deleted file mode 100644 index 33d0ca7..0000000 --- a/src/util/web3/getWeb3.js +++ /dev/null @@ -1,51 +0,0 @@ -import store from '../../store' -import Web3 from 'web3' - -export const WEB3_INITIALIZED = 'WEB3_INITIALIZED'; -function web3Initialized(results) { - return { - type: WEB3_INITIALIZED, - payload: results - } -} - -let getWeb3 = new Promise(function(resolve, reject) { - // Wait for loading completion to avoid race conditions with web3 injection timing. - window.addEventListener('load', function(dispatch) { - var results; - var web3 = window.web3; - - // Checking if Web3 has been injected by the browser (Mist/MetaMask) - if (typeof web3 !== 'undefined') { - // Use Mist/MetaMask's provider. - web3 = new Web3(web3.currentProvider); - - results = { - web3Instance: web3 - }; - - console.log('Injected web3 detected.'); - - resolve(store.dispatch(web3Initialized(results))) - } else { - - // Fallback to localhost if no web3 injection. - - var provider = new Web3.providers.HttpProvider('http://localhost:8545'); - - web3 = new Web3(provider); - - results = { - web3Instance: web3 - }; - - console.log('No web3 instance injected, using Local web3.'); - - resolve(store.dispatch(web3Initialized(results))) - } - - // TODO: Error checking. - }) -}); - -export default getWeb3 \ No newline at end of file diff --git a/src/util/web3/web3Reducer.js b/src/util/web3/web3Reducer.js deleted file mode 100644 index be08027..0000000 --- a/src/util/web3/web3Reducer.js +++ /dev/null @@ -1,16 +0,0 @@ -const initialState = { - web3Instance: null -}; - -const web3Reducer = (state = initialState, action) => { - if (action.type === 'WEB3_INITIALIZED') - { - return Object.assign({}, state, { - web3Instance: action.payload.web3Instance - }) - } - - return state -}; - -export default web3Reducer From f377798acf38e5c3df4a7129b34f777c53ae6867 Mon Sep 17 00:00:00 2001 From: Ezerous Date: Fri, 27 Apr 2018 21:19:23 +0300 Subject: [PATCH 2/6] Minor fixes --- package.json | 10 ++++---- src/index.js | 24 +++++++++---------- src/reducer.js | 4 ++-- .../ui/loginbutton/LoginButtonContainer.js | 7 ++---- .../ui/profileform/ProfileFormContainer.js | 8 +++---- src/user/ui/signupform/SignUpFormContainer.js | 7 ++---- 6 files changed, 27 insertions(+), 33 deletions(-) diff --git a/package.json b/package.json index 108b889..fdf13de 100644 --- a/package.json +++ b/package.json @@ -10,11 +10,12 @@ "truffle-contract": "^3.0.4" }, "dependencies": { - "drizzle": "^1.1.4", + "drizzle": "^1.1.5", "drizzle-react": "^1.1.1", "drizzle-react-components": "^1.1.0", - "react": "^16.3.0", - "react-dom": "^16.3.0", + "eth-block-tracker-es5": "^2.3.2", + "react": "^16.3.2", + "react-dom": "^16.3.2", "react-scripts": "1.1.1", "react-redux": "^5.0.7", "react-router": "3.2.1", @@ -22,7 +23,8 @@ "redux": "^3.7.2", "redux-auth-wrapper": "1.1.0", "redux-saga": "0.16.0", - "redux-thunk": "^2.2.0" + "redux-thunk": "^2.2.0", + "web3":"^1.0.0-beta.34" }, "scripts": { "start": "react-scripts start", diff --git a/src/index.js b/src/index.js index 16f0ed1..c969cef 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,5 @@ import React from 'react'; -import ReactDOM from 'react-dom'; +import { render } from 'react-dom' import { Router, Route, IndexRoute, browserHistory } from 'react-router' import { DrizzleProvider } from 'drizzle-react' import { syncHistoryWithStore } from 'react-router-redux' @@ -25,18 +25,18 @@ import registerServiceWorker from './registerServiceWorker'; // Initialize react-router-redux. const history = syncHistoryWithStore(browserHistory, store); -ReactDOM.render(( +render(( - - - - - - - - - - + + + + + + + + + + ), document.getElementById('root') diff --git a/src/reducer.js b/src/reducer.js index 4c54292..cdb38c4 100644 --- a/src/reducer.js +++ b/src/reducer.js @@ -1,12 +1,12 @@ import { combineReducers } from 'redux' import { routerReducer } from 'react-router-redux' -import userReducer from './user/userReducer' import { drizzleReducers } from 'drizzle' +import userReducer from './user/userReducer' const reducer = combineReducers({ routing: routerReducer, + ...drizzleReducers, user: userReducer, - ...drizzleReducers }); export default reducer diff --git a/src/user/ui/loginbutton/LoginButtonContainer.js b/src/user/ui/loginbutton/LoginButtonContainer.js index 244876c..91a721a 100644 --- a/src/user/ui/loginbutton/LoginButtonContainer.js +++ b/src/user/ui/loginbutton/LoginButtonContainer.js @@ -1,4 +1,4 @@ -import { connect } from 'react-redux' +import { drizzleConnect } from 'drizzle-react' import LoginButton from './LoginButton' import { loginUser } from './LoginButtonActions' @@ -15,9 +15,6 @@ const mapDispatchToProps = (dispatch) => { } }; -const LoginButtonContainer = connect( - mapStateToProps, - mapDispatchToProps -)(LoginButton); +const LoginButtonContainer = drizzleConnect(LoginButton, mapStateToProps, mapDispatchToProps); export default LoginButtonContainer diff --git a/src/user/ui/profileform/ProfileFormContainer.js b/src/user/ui/profileform/ProfileFormContainer.js index bda66a9..37dc860 100644 --- a/src/user/ui/profileform/ProfileFormContainer.js +++ b/src/user/ui/profileform/ProfileFormContainer.js @@ -1,4 +1,5 @@ -import { connect } from 'react-redux' +import { drizzleConnect } from 'drizzle-react' + import ProfileForm from './ProfileForm' import { updateUser } from './ProfileFormActions' @@ -17,9 +18,6 @@ const mapDispatchToProps = (dispatch) => { } }; -const ProfileFormContainer = connect( - mapStateToProps, - mapDispatchToProps -)(ProfileForm); +const ProfileFormContainer = drizzleConnect(ProfileForm, mapStateToProps, mapDispatchToProps); export default ProfileFormContainer diff --git a/src/user/ui/signupform/SignUpFormContainer.js b/src/user/ui/signupform/SignUpFormContainer.js index 358db7d..0378cee 100644 --- a/src/user/ui/signupform/SignUpFormContainer.js +++ b/src/user/ui/signupform/SignUpFormContainer.js @@ -1,4 +1,4 @@ -import { connect } from 'react-redux' +import {drizzleConnect} from "drizzle-react"; import SignUpForm from './SignUpForm' import { signUpUser } from './SignUpFormActions' @@ -14,9 +14,6 @@ const mapDispatchToProps = (dispatch) => { } }; -const SignUpFormContainer = connect( - mapStateToProps, - mapDispatchToProps -)(SignUpForm); +const SignUpFormContainer = drizzleConnect(SignUpForm, mapStateToProps, mapDispatchToProps); export default SignUpFormContainer From 30e3c1e03f8dad06db09e599491d5651191482ac Mon Sep 17 00:00:00 2001 From: Ezerous Date: Mon, 30 Apr 2018 14:30:26 +0300 Subject: [PATCH 3/6] Simplified/ Overhauled --- public/manifest.json | 15 --- src/App.css | 50 +++++++- src/App.js | 47 ++----- src/App.test.js | 1 - src/drizzleOptions.js | 18 +++ src/index.js | 46 +++---- src/layouts/dashboard/Dashboard.js | 23 ---- src/layouts/home/Home.js | 14 ++- src/layouts/home/HomeContainer.js | 1 + src/reducer.js | 4 +- src/registerServiceWorker.js | 117 ------------------ src/{util/drizzle => }/rootSaga.js | 0 src/store.js | 31 ++--- src/user/layouts/profile/Profile.js | 20 --- src/user/layouts/signup/SignUp.js | 20 --- src/user/ui/loginbutton/LoginButton.js | 11 -- src/user/ui/loginbutton/LoginButtonActions.js | 69 ----------- .../ui/loginbutton/LoginButtonContainer.js | 20 --- src/user/ui/profileform/ProfileForm.js | 42 ------- src/user/ui/profileform/ProfileFormActions.js | 56 --------- .../ui/profileform/ProfileFormContainer.js | 23 ---- src/user/ui/signupform/SignUpForm.js | 44 ------- src/user/ui/signupform/SignUpFormActions.js | 45 ------- src/user/ui/signupform/SignUpFormContainer.js | 19 --- src/user/userReducer.js | 22 ---- src/util/drizzle/drizzleOptions.js | 18 --- src/util/wrappers.js | 34 ----- 27 files changed, 115 insertions(+), 695 deletions(-) delete mode 100644 public/manifest.json create mode 100644 src/drizzleOptions.js delete mode 100644 src/layouts/dashboard/Dashboard.js delete mode 100644 src/registerServiceWorker.js rename src/{util/drizzle => }/rootSaga.js (100%) delete mode 100644 src/user/layouts/profile/Profile.js delete mode 100644 src/user/layouts/signup/SignUp.js delete mode 100644 src/user/ui/loginbutton/LoginButton.js delete mode 100644 src/user/ui/loginbutton/LoginButtonActions.js delete mode 100644 src/user/ui/loginbutton/LoginButtonContainer.js delete mode 100644 src/user/ui/profileform/ProfileForm.js delete mode 100644 src/user/ui/profileform/ProfileFormActions.js delete mode 100644 src/user/ui/profileform/ProfileFormContainer.js delete mode 100644 src/user/ui/signupform/SignUpForm.js delete mode 100644 src/user/ui/signupform/SignUpFormActions.js delete mode 100644 src/user/ui/signupform/SignUpFormContainer.js delete mode 100644 src/user/userReducer.js delete mode 100644 src/util/drizzle/drizzleOptions.js delete mode 100644 src/util/wrappers.js diff --git a/public/manifest.json b/public/manifest.json deleted file mode 100644 index 0bcfdd4..0000000 --- a/public/manifest.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "short_name": "Apella", - "name": "Apella", - "icons": [ - { - "src": "favicon.ico", - "sizes": "64x64 32x32 24x24 16x16", - "type": "image/x-icon" - } - ], - "start_url": "./index.html", - "display": "standalone", - "theme_color": "#000000", - "background_color": "#ffffff" -} diff --git a/src/App.css b/src/App.css index d6e66c0..2346633 100644 --- a/src/App.css +++ b/src/App.css @@ -5,21 +5,26 @@ body, font-family: 'Open Sans', sans-serif; } +.header { + text-align: center; +} + h1, h2, h3 { font-family: 'Oswald', 'Arial Narrow', sans-serif; } code { - display: block; - margin: 20px 0 15px 0; - padding: 10px; + padding: .25rem; + margin: 0 .25rem; background: #eee; } .container { box-sizing: border-box; - width: 100%; + width: calc(100% - 60px); + max-width: 600px; padding: 45px 20px; + margin: 0 auto; } .pure-button-primary { @@ -34,6 +39,15 @@ code { border-color: #0c1a2b; } +ul { + list-style-type: none; + padding-left: 0; +} + +ul li:not(:last-child) { + margin-bottom: 15px; +} + /* NAVBAR */ .navbar { @@ -66,3 +80,31 @@ code { height: 16px; margin-right: 10px; } + +/* LOADING SCREEN */ + +.loading-screen { + opacity: 1; + visibility: visible; + transition: all .25s ease-in-out; +} + +.loading-screen.loaded { + opacity: 0; + visibility: hidden; +} + +/* FORMS */ + +.pure-form { + display: inline-block; +} + +/* ALERTS */ + +.alert { + padding: .5rem; + color: darkgreen; + background: darkseagreen; + border: 1px solid darkgreen; +} \ No newline at end of file diff --git a/src/App.js b/src/App.js index 41c5ef9..45d9e02 100644 --- a/src/App.js +++ b/src/App.js @@ -1,9 +1,4 @@ import React, { Component } from 'react' -import { Link } from 'react-router' -import { HiddenOnlyAuth, VisibleOnlyAuth } from './util/wrappers.js' - -// UI Components -import LoginButtonContainer from './user/ui/loginbutton/LoginButtonContainer' // Styles import './css/oswald.css' @@ -12,41 +7,13 @@ import './css/pure-min.css' import './App.css' class App extends Component { - render() { - const OnlyAuthLinks = VisibleOnlyAuth(() => - -
  • - Dashboard -
  • -
  • - Profile -
  • -
    - ); - - const OnlyGuestLinks = HiddenOnlyAuth(() => - -
  • - Sign Up -
  • - -
    - ); - - return ( -
    - - - {this.props.children} -
    - ); - } + render() { + return ( +
    + {this.props.children} +
    + ); + } } export default App diff --git a/src/App.test.js b/src/App.test.js index a754b20..b84af98 100644 --- a/src/App.test.js +++ b/src/App.test.js @@ -5,5 +5,4 @@ import App from './App'; it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(, div); - ReactDOM.unmountComponentAtNode(div); }); diff --git a/src/drizzleOptions.js b/src/drizzleOptions.js new file mode 100644 index 0000000..e6889d8 --- /dev/null +++ b/src/drizzleOptions.js @@ -0,0 +1,18 @@ +import Forum from './build/contracts/Forum.json' + +const drizzleOptions = { + web3: { + fallback: { + type: 'ws', + url: 'ws://127.0.0.1:8545' + } + }, + contracts: [ + Forum + ], + events: { + Forum: ['UserSignedUp'] + } +}; + +export default drizzleOptions \ No newline at end of file diff --git a/src/index.js b/src/index.js index c969cef..2ffbcc6 100644 --- a/src/index.js +++ b/src/index.js @@ -1,46 +1,30 @@ import React from 'react'; -import { render } from 'react-dom' +import { render } from 'react-dom'; import { Router, Route, IndexRoute, browserHistory } from 'react-router' -import { DrizzleProvider } from 'drizzle-react' import { syncHistoryWithStore } from 'react-router-redux' -import { UserIsAuthenticated, UserIsNotAuthenticated } from './util/wrappers.js' +import { DrizzleProvider } from 'drizzle-react' // Layouts import App from './App' import HomeContainer from './layouts/home/HomeContainer' -import Dashboard from './layouts/dashboard/Dashboard' -import SignUp from './user/layouts/signup/SignUp' -import Profile from './user/layouts/profile/Profile' -import {LoadingContainer} from 'drizzle-react-components' - -import './index.css'; //??? +import { LoadingContainer } from 'drizzle-react-components' -// Redux Store import store from './store' -import drizzleOptions from './util/drizzle/drizzleOptions' - -// ServiceWorker -import registerServiceWorker from './registerServiceWorker'; +import drizzleOptions from './drizzleOptions' // Initialize react-router-redux. const history = syncHistoryWithStore(browserHistory, store); render(( - - - - - - - - - - - - - ), - document.getElementById('root') + + + + + + + + + + ), + document.getElementById('root') ); - -registerServiceWorker(); - diff --git a/src/layouts/dashboard/Dashboard.js b/src/layouts/dashboard/Dashboard.js deleted file mode 100644 index b2ae92d..0000000 --- a/src/layouts/dashboard/Dashboard.js +++ /dev/null @@ -1,23 +0,0 @@ -import React, { Component } from 'react' - -class Dashboard extends Component { - constructor(props, { authData }) { - super(props); - authData = this.props - } - - render() { - return( -
    -
    -
    -

    Dashboard

    -

    Congratulations {this.props.authData.name}! If you're seeing this page, you've logged in with your own smart contract successfully.

    -
    -
    -
    - ) - } -} - -export default Dashboard diff --git a/src/layouts/home/Home.js b/src/layouts/home/Home.js index eb409e1..4ee67a7 100644 --- a/src/layouts/home/Home.js +++ b/src/layouts/home/Home.js @@ -1,13 +1,21 @@ import React, { Component } from 'react' +import { AccountData, ContractData, ContractForm } from 'drizzle-react-components' class Home extends Component { render() { - return( + return (
    +
    +

    Apella

    +

    +
    -

    Welcome!

    -

    Lorem ipsum dolor sit amet, tempor vitae vivamus senectus id risus, nulla in, urna sed vitae at ac. Parturient fringilla vestibulum, vitae metus tempus, augue sollicitudin, faucibus scelerisque suspendisse, consectetuer massa fermentum tellus interdum neque. Luctus euismod, nam sodales, non aliquam luctus lorem tellus, habitasse porttitor fusce sed mauris omnis massa, mauris felis pede sodales ligula semper. Amet ut id voluptatum. Nunc amet sem, fusce wisi interdum, et a. Fusce dolor augue in non aliquam, id vestibulum, lacinia diam ante sit felis et, viverra velit, nulla sociosqu autem.

    +

    Account

    + +

    Username:

    + +

    diff --git a/src/layouts/home/HomeContainer.js b/src/layouts/home/HomeContainer.js index ac699a5..1eb73eb 100644 --- a/src/layouts/home/HomeContainer.js +++ b/src/layouts/home/HomeContainer.js @@ -4,6 +4,7 @@ import { drizzleConnect } from 'drizzle-react' // May still need this even with data function to refresh component on updates for this contract. const mapStateToProps = state => { return { + accounts: state.accounts, Forum: state.contracts.Forum, drizzleStatus: state.drizzleStatus } diff --git a/src/reducer.js b/src/reducer.js index cdb38c4..9db9303 100644 --- a/src/reducer.js +++ b/src/reducer.js @@ -1,12 +1,10 @@ import { combineReducers } from 'redux' import { routerReducer } from 'react-router-redux' import { drizzleReducers } from 'drizzle' -import userReducer from './user/userReducer' const reducer = combineReducers({ routing: routerReducer, - ...drizzleReducers, - user: userReducer, + ...drizzleReducers }); export default reducer diff --git a/src/registerServiceWorker.js b/src/registerServiceWorker.js deleted file mode 100644 index a3e6c0c..0000000 --- a/src/registerServiceWorker.js +++ /dev/null @@ -1,117 +0,0 @@ -// In production, we register a service worker to serve assets from local cache. - -// This lets the app load faster on subsequent visits in production, and gives -// it offline capabilities. However, it also means that developers (and users) -// will only see deployed updates on the "N+1" visit to a page, since previously -// cached resources are updated in the background. - -// To learn more about the benefits of this model, read https://goo.gl/KwvDNy. -// This link also includes instructions on opting out of this behavior. - -const isLocalhost = Boolean( - window.location.hostname === 'localhost' || - // [::1] is the IPv6 localhost address. - window.location.hostname === '[::1]' || - // 127.0.0.1/8 is considered localhost for IPv4. - window.location.hostname.match( - /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ - ) -); - -export default function register() { - if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { - // The URL constructor is available in all browsers that support SW. - const publicUrl = new URL(process.env.PUBLIC_URL, window.location); - if (publicUrl.origin !== window.location.origin) { - // Our service worker won't work if PUBLIC_URL is on a different origin - // from what our page is served on. This might happen if a CDN is used to - // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374 - return; - } - - window.addEventListener('load', () => { - const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; - - if (isLocalhost) { - // This is running on localhost. Lets check if a service worker still exists or not. - checkValidServiceWorker(swUrl); - - // Add some additional logging to localhost, pointing developers to the - // service worker/PWA documentation. - navigator.serviceWorker.ready.then(() => { - console.log( - 'This web app is being served cache-first by a service ' + - 'worker. To learn more, visit https://goo.gl/SC7cgQ' - ); - }); - } else { - // Is not local host. Just register service worker - registerValidSW(swUrl); - } - }); - } -} - -function registerValidSW(swUrl) { - navigator.serviceWorker - .register(swUrl) - .then(registration => { - registration.onupdatefound = () => { - const installingWorker = registration.installing; - installingWorker.onstatechange = () => { - if (installingWorker.state === 'installed') { - if (navigator.serviceWorker.controller) { - // At this point, the old content will have been purged and - // the fresh content will have been added to the cache. - // It's the perfect time to display a "New content is - // available; please refresh." message in your web app. - console.log('New content is available; please refresh.'); - } else { - // At this point, everything has been precached. - // It's the perfect time to display a - // "Content is cached for offline use." message. - console.log('Content is cached for offline use.'); - } - } - }; - }; - }) - .catch(error => { - console.error('Error during service worker registration:', error); - }); -} - -function checkValidServiceWorker(swUrl) { - // Check if the service worker can be found. If it can't reload the page. - fetch(swUrl) - .then(response => { - // Ensure service worker exists, and that we really are getting a JS file. - if ( - response.status === 404 || - response.headers.get('content-type').indexOf('javascript') === -1 - ) { - // No service worker found. Probably a different app. Reload the page. - navigator.serviceWorker.ready.then(registration => { - registration.unregister().then(() => { - window.location.reload(); - }); - }); - } else { - // Service worker found. Proceed as normal. - registerValidSW(swUrl); - } - }) - .catch(() => { - console.log( - 'No internet connection found. App is running in offline mode.' - ); - }); -} - -export function unregister() { - if ('serviceWorker' in navigator) { - navigator.serviceWorker.ready.then(registration => { - registration.unregister(); - }); - } -} diff --git a/src/util/drizzle/rootSaga.js b/src/rootSaga.js similarity index 100% rename from src/util/drizzle/rootSaga.js rename to src/rootSaga.js diff --git a/src/store.js b/src/store.js index 5f73ee5..bb1080d 100644 --- a/src/store.js +++ b/src/store.js @@ -1,34 +1,35 @@ -import {browserHistory} from 'react-router' -import {createStore, applyMiddleware, compose} from 'redux' +import { browserHistory } from 'react-router' +import { createStore, applyMiddleware, compose } from 'redux' import thunkMiddleware from 'redux-thunk' -import {routerMiddleware} from 'react-router-redux' +import { routerMiddleware } from 'react-router-redux' import reducer from './reducer' -import rootSaga from './util/drizzle/rootSaga' +import rootSaga from './rootSaga' import createSagaMiddleware from 'redux-saga' -import {generateContractsInitialState} from 'drizzle' -import drizzleOptions from './util/drizzle/drizzleOptions' +import { generateContractsInitialState } from 'drizzle' +import drizzleOptions from './drizzleOptions' -// Redux DevTools (see also https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup) +// Redux DevTools const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const routingMiddleware = routerMiddleware(browserHistory); const sagaMiddleware = createSagaMiddleware(); const initialState = { - contracts: generateContractsInitialState(drizzleOptions) + contracts: generateContractsInitialState(drizzleOptions) }; const store = createStore( - reducer, - initialState, - composeEnhancers( + reducer, + initialState, + composeEnhancers( applyMiddleware( - thunkMiddleware, - routingMiddleware, - sagaMiddleware + thunkMiddleware, + routingMiddleware, + sagaMiddleware ) ) ); sagaMiddleware.run(rootSaga); -export default store + +export default store \ No newline at end of file diff --git a/src/user/layouts/profile/Profile.js b/src/user/layouts/profile/Profile.js deleted file mode 100644 index 6dfb688..0000000 --- a/src/user/layouts/profile/Profile.js +++ /dev/null @@ -1,20 +0,0 @@ -import React, { Component } from 'react' -import ProfileFormContainer from '../../ui/profileform/ProfileFormContainer' - -class Profile extends Component { - render() { - return( -
    -
    -
    -

    Profile

    -

    Edit your account details here.

    - -
    -
    -
    - ) - } -} - -export default Profile diff --git a/src/user/layouts/signup/SignUp.js b/src/user/layouts/signup/SignUp.js deleted file mode 100644 index 069e379..0000000 --- a/src/user/layouts/signup/SignUp.js +++ /dev/null @@ -1,20 +0,0 @@ -import React, { Component } from 'react' -import SignUpFormContainer from '../../ui/signupform/SignUpFormContainer' - -class SignUp extends Component { - render() { - return( -
    -
    -
    -

    Sign Up

    -

    We've got your wallet information, simply input your name and your account is made!

    - -
    -
    -
    - ) - } -} - -export default SignUp diff --git a/src/user/ui/loginbutton/LoginButton.js b/src/user/ui/loginbutton/LoginButton.js deleted file mode 100644 index 6ba658b..0000000 --- a/src/user/ui/loginbutton/LoginButton.js +++ /dev/null @@ -1,11 +0,0 @@ -import React from 'react' - -const LoginButton = ({ onLoginUserClick }) => { - return( -
  • - onLoginUserClick(event)}>Login -
  • - ) -}; - -export default LoginButton diff --git a/src/user/ui/loginbutton/LoginButtonActions.js b/src/user/ui/loginbutton/LoginButtonActions.js deleted file mode 100644 index 994cedc..0000000 --- a/src/user/ui/loginbutton/LoginButtonActions.js +++ /dev/null @@ -1,69 +0,0 @@ -import ForumContract from '../../../build/contracts/Forum.json' -import { browserHistory } from 'react-router' -import store from '../../../store' - -const contract = require('truffle-contract'); - -export const USER_LOGGED_IN = 'USER_LOGGED_IN'; -function userLoggedIn(user) { - return { - type: USER_LOGGED_IN, - payload: user - } -} - -export function loginUser() { - let web3 = store.getState().web3.web3Instance; - - // Double-check web3's status. - if (typeof web3 !== 'undefined') { - - return function(dispatch) { - // Using truffle-contract we create the authentication object. - const authentication = contract(ForumContract); - authentication.setProvider(web3.currentProvider); - - // Declaring this for later so we can chain functions on Authentication. - let authenticationInstance; - - // Get current ethereum wallet. - web3.eth.getCoinbase((error, coinbase) => { - // Log errors, if any. - if (error) { - console.error(error); - } - - authentication.deployed().then(function(instance) { - authenticationInstance = instance; - - // Attempt to login user. - authenticationInstance.login({from: coinbase}) - .then(function(result) { - // If no error, login user. - console.log("Login successful: " + JSON.parse(result)); - dispatch(userLoggedIn({"name": JSON.parse(result)})); - - // Used a manual redirect here as opposed to a wrapper. - // This way, once logged in a user can still access the home page. - let currentLocation = browserHistory.getCurrentLocation(); - - if ('redirect' in currentLocation.query) - return browserHistory.push(decodeURIComponent(currentLocation.query.redirect)); - - - return browserHistory.push('/dashboard') - }) - .catch(function(result) { - // If error, go to signup page. - console.error('Wallet ' + coinbase + ' does not have an account!'); - console.error('Error: ' + result); - - return browserHistory.push('/signup') - }) - }) - }) - } - } else { - console.error('Web3 is not initialized.'); - } -} diff --git a/src/user/ui/loginbutton/LoginButtonContainer.js b/src/user/ui/loginbutton/LoginButtonContainer.js deleted file mode 100644 index 91a721a..0000000 --- a/src/user/ui/loginbutton/LoginButtonContainer.js +++ /dev/null @@ -1,20 +0,0 @@ -import { drizzleConnect } from 'drizzle-react' -import LoginButton from './LoginButton' -import { loginUser } from './LoginButtonActions' - -const mapStateToProps = (state, ownProps) => { - return {} -}; - -const mapDispatchToProps = (dispatch) => { - return { - onLoginUserClick: (event) => { - event.preventDefault(); - dispatch(loginUser()); - } - } -}; - -const LoginButtonContainer = drizzleConnect(LoginButton, mapStateToProps, mapDispatchToProps); - -export default LoginButtonContainer diff --git a/src/user/ui/profileform/ProfileForm.js b/src/user/ui/profileform/ProfileForm.js deleted file mode 100644 index 2ec114c..0000000 --- a/src/user/ui/profileform/ProfileForm.js +++ /dev/null @@ -1,42 +0,0 @@ -import React, { Component } from 'react' - -class ProfileForm extends Component { - constructor(props) { - super(props); - - this.state = { - name: this.props.name - } - } - - onInputChange(event) { - this.setState({ name: event.target.value }) - } - - handleSubmit(event) { - event.preventDefault(); - - if (this.state.name.length < 2) - return alert('Please fill in your name.'); - - this.props.onProfileFormSubmit(this.state.name, event) - } - - render() { - return( -
    -
    - - - This is a required field. - -
    - - -
    -
    - ) - } -} - -export default ProfileForm diff --git a/src/user/ui/profileform/ProfileFormActions.js b/src/user/ui/profileform/ProfileFormActions.js deleted file mode 100644 index a895303..0000000 --- a/src/user/ui/profileform/ProfileFormActions.js +++ /dev/null @@ -1,56 +0,0 @@ -import ForumContract from '../../../build/contracts/Forum.json' -import store from '../../../store' - -const contract = require('truffle-contract'); - -export const USER_UPDATED = 'USER_UPDATED'; -function userUpdated(user) { - return { - type: USER_UPDATED, - payload: user - } -} - -export function updateUser(name) { - let web3 = store.getState().web3.web3Instance; - - // Double-check web3's status. - if (typeof web3 !== 'undefined') { - - return function(dispatch) { - // Using truffle-contract we create the authentication object. - const authentication = contract(ForumContract); - authentication.setProvider(web3.currentProvider); - - // Declaring this for later so we can chain functions on Authentication. - let authenticationInstance; - - // Get current ethereum wallet. - web3.eth.getCoinbase((error, coinbase) => { - // Log errors, if any. - if (error) { - console.error(error); - } - - authentication.deployed().then(function(instance) { - authenticationInstance = instance; - - // Attempt to login user. - authenticationInstance.signUp(JSON.stringify(name), {from: coinbase}) - .then(function(result) { - console.log("SignUp/name update successful: " + name); - // If no error, update user. - dispatch(userUpdated({"name": name})); - - return alert('Name updated!') - }) - .catch(function(result) { - // If error... - }) - }) - }) - } - } else { - console.error('Web3 is not initialized.'); - } -} diff --git a/src/user/ui/profileform/ProfileFormContainer.js b/src/user/ui/profileform/ProfileFormContainer.js deleted file mode 100644 index 37dc860..0000000 --- a/src/user/ui/profileform/ProfileFormContainer.js +++ /dev/null @@ -1,23 +0,0 @@ -import { drizzleConnect } from 'drizzle-react' - -import ProfileForm from './ProfileForm' -import { updateUser } from './ProfileFormActions' - -const mapStateToProps = (state, ownProps) => { - return { - name: state.user.data.name - } -}; - -const mapDispatchToProps = (dispatch) => { - return { - onProfileFormSubmit: (name, event) => { - event.preventDefault(); - dispatch(updateUser(name)) - } - } -}; - -const ProfileFormContainer = drizzleConnect(ProfileForm, mapStateToProps, mapDispatchToProps); - -export default ProfileFormContainer diff --git a/src/user/ui/signupform/SignUpForm.js b/src/user/ui/signupform/SignUpForm.js deleted file mode 100644 index c5f6cc8..0000000 --- a/src/user/ui/signupform/SignUpForm.js +++ /dev/null @@ -1,44 +0,0 @@ -import React, { Component } from 'react' - -class SignUpForm extends Component { - constructor(props) { - super(props); - - this.state = { - name: '' - } - } - - onInputChange(event) { - this.setState({ name: event.target.value }) - } - - handleSubmit(event) { - event.preventDefault(); - - if (this.state.name.length < 2) - { - return alert('Please fill in your name.') - } - - this.props.onSignUpFormSubmit(this.state.name) - } - - render() { - return( -
    -
    - - - This is a required field. - -
    - - -
    -
    - ) - } -} - -export default SignUpForm diff --git a/src/user/ui/signupform/SignUpFormActions.js b/src/user/ui/signupform/SignUpFormActions.js deleted file mode 100644 index 3fcdb09..0000000 --- a/src/user/ui/signupform/SignUpFormActions.js +++ /dev/null @@ -1,45 +0,0 @@ -import ForumContract from '../../../build/contracts/Forum.json' -import { loginUser } from '../loginbutton/LoginButtonActions' -import store from '../../../store' - -const contract = require('truffle-contract'); - -export function signUpUser(name) { - let web3 = store.getState().web3.web3Instance; - - // Double-check web3's status. - if (typeof web3 !== 'undefined') { - - return function(dispatch) { - // Using truffle-contract we create the authentication object. - const authentication = contract(ForumContract); - authentication.setProvider(web3.currentProvider); - - // Declaring this for later so we can chain functions on Authentication. - let authenticationInstance; - - // Get current ethereum wallet. - web3.eth.getCoinbase((error, coinbase) => { - // Log errors, if any. - if (error) - console.error(error); - - authentication.deployed().then(function(instance) { - authenticationInstance = instance; - - // Attempt to sign up user. - authenticationInstance.signUp(JSON.stringify(name), {from: coinbase}) - .then(function(result) { - // If no error, login user. - return dispatch(loginUser()) - }) - .catch(function(result) { - console.log("SignUp error: " + result); - }) - }) - }) - } - } else { - console.error('Web3 is not initialized.'); - } -} diff --git a/src/user/ui/signupform/SignUpFormContainer.js b/src/user/ui/signupform/SignUpFormContainer.js deleted file mode 100644 index 0378cee..0000000 --- a/src/user/ui/signupform/SignUpFormContainer.js +++ /dev/null @@ -1,19 +0,0 @@ -import {drizzleConnect} from "drizzle-react"; -import SignUpForm from './SignUpForm' -import { signUpUser } from './SignUpFormActions' - -const mapStateToProps = (state, ownProps) => { - return {} -}; - -const mapDispatchToProps = (dispatch) => { - return { - onSignUpFormSubmit: (name) => { - dispatch(signUpUser(name)) - } - } -}; - -const SignUpFormContainer = drizzleConnect(SignUpForm, mapStateToProps, mapDispatchToProps); - -export default SignUpFormContainer diff --git a/src/user/userReducer.js b/src/user/userReducer.js deleted file mode 100644 index 0904126..0000000 --- a/src/user/userReducer.js +++ /dev/null @@ -1,22 +0,0 @@ -const initialState = { - data: null -}; - -const userReducer = (state = initialState, action) => { - if (action.type === 'USER_LOGGED_IN' || action.type === 'USER_UPDATED') - { - return Object.assign({}, state, { - data: action.payload - }) - } - - if (action.type === 'USER_LOGGED_OUT') - { - return Object.assign({}, state, { - data: null - }) - } - return state; -}; - -export default userReducer diff --git a/src/util/drizzle/drizzleOptions.js b/src/util/drizzle/drizzleOptions.js deleted file mode 100644 index 798ab7d..0000000 --- a/src/util/drizzle/drizzleOptions.js +++ /dev/null @@ -1,18 +0,0 @@ -import Forum from './../../build/contracts/Forum.json' - -const drizzleOptions = { - web3: { - fallback: { - type: 'ws', - url: 'ws://127.0.0.1:8545' - } - }, - contracts: [ - Forum - ], - events: { - Forum: ['UserSignedUp'] - } -}; - -export default drizzleOptions \ No newline at end of file diff --git a/src/util/wrappers.js b/src/util/wrappers.js deleted file mode 100644 index 04a1571..0000000 --- a/src/util/wrappers.js +++ /dev/null @@ -1,34 +0,0 @@ -import { UserAuthWrapper } from 'redux-auth-wrapper' -import { routerActions } from 'react-router-redux' - -// Layout Component Wrappers -export const UserIsAuthenticated = UserAuthWrapper({ - authSelector: state => state.user.data, - redirectAction: routerActions.replace, - failureRedirectPath: '/', // '/login' by default. - wrapperDisplayName: 'UserIsAuthenticated' -}); - -export const UserIsNotAuthenticated = UserAuthWrapper({ - authSelector: state => state.user, - redirectAction: routerActions.replace, - failureRedirectPath: (state, ownProps) => ownProps.location.query.redirect || '/dashboard', - wrapperDisplayName: 'UserIsNotAuthenticated', - predicate: user => user.data === null, - allowRedirectBack: false -}); - -// UI Component Wrappers -export const VisibleOnlyAuth = UserAuthWrapper({ - authSelector: state => state.user, - wrapperDisplayName: 'VisibleOnlyAuth', - predicate: user => user.data, - FailureComponent: null -}); - -export const HiddenOnlyAuth = UserAuthWrapper({ - authSelector: state => state.user, - wrapperDisplayName: 'HiddenOnlyAuth', - predicate: user => user.data === null, - FailureComponent: null -}); From c4931a05a0e674818f62ef7a9b7e2a7da1f24dba Mon Sep 17 00:00:00 2001 From: Ezerous Date: Mon, 30 Apr 2018 15:25:36 +0300 Subject: [PATCH 4/6] Removed unused imports --- contracts/Migrations.sol | 20 ++++++++++---------- package.json | 4 ---- src/store.js | 2 -- 3 files changed, 10 insertions(+), 16 deletions(-) diff --git a/contracts/Migrations.sol b/contracts/Migrations.sol index 27598ad..4b532ee 100644 --- a/contracts/Migrations.sol +++ b/contracts/Migrations.sol @@ -8,16 +8,16 @@ contract Migrations { if (msg.sender == owner) _; } - function Migrations() public { - owner = msg.sender; - } +constructor() public { +owner = msg.sender; +} - function setCompleted(uint completed) public restricted { - last_completed_migration = completed; - } +function setCompleted(uint completed) public restricted { +last_completed_migration = completed; +} - function upgrade(address new_address) public restricted { - Migrations upgraded = Migrations(new_address); - upgraded.setCompleted(last_completed_migration); - } +function upgrade(address new_address) public restricted { +Migrations upgraded = Migrations(new_address); +upgraded.setCompleted(last_completed_migration); +} } diff --git a/package.json b/package.json index fdf13de..04af20b 100644 --- a/package.json +++ b/package.json @@ -6,9 +6,6 @@ "type": "git", "url": "https://gitlab.com/Ezerous/Apella.git" }, - "devDependencies": { - "truffle-contract": "^3.0.4" - }, "dependencies": { "drizzle": "^1.1.5", "drizzle-react": "^1.1.1", @@ -23,7 +20,6 @@ "redux": "^3.7.2", "redux-auth-wrapper": "1.1.0", "redux-saga": "0.16.0", - "redux-thunk": "^2.2.0", "web3":"^1.0.0-beta.34" }, "scripts": { diff --git a/src/store.js b/src/store.js index bb1080d..bc333fe 100644 --- a/src/store.js +++ b/src/store.js @@ -1,6 +1,5 @@ import { browserHistory } from 'react-router' import { createStore, applyMiddleware, compose } from 'redux' -import thunkMiddleware from 'redux-thunk' import { routerMiddleware } from 'react-router-redux' import reducer from './reducer' import rootSaga from './rootSaga' @@ -23,7 +22,6 @@ const store = createStore( initialState, composeEnhancers( applyMiddleware( - thunkMiddleware, routingMiddleware, sagaMiddleware ) From 5833b7605d6e08d859fbfa6b04e3c5e223d5bb94 Mon Sep 17 00:00:00 2001 From: Ezerous Date: Mon, 30 Apr 2018 21:39:39 +0300 Subject: [PATCH 5/6] SingUp recognition container --- contracts/Migrations.sol | 22 ++++++------- package.json | 5 +-- src/containers/Menu.js | 69 ++++++++++++++++++++++++++++++++++++++++ src/layouts/home/Home.js | 2 ++ 4 files changed, 85 insertions(+), 13 deletions(-) create mode 100644 src/containers/Menu.js diff --git a/contracts/Migrations.sol b/contracts/Migrations.sol index 4b532ee..184150a 100644 --- a/contracts/Migrations.sol +++ b/contracts/Migrations.sol @@ -8,16 +8,16 @@ contract Migrations { if (msg.sender == owner) _; } -constructor() public { -owner = msg.sender; -} + constructor() public { + owner = msg.sender; + } -function setCompleted(uint completed) public restricted { -last_completed_migration = completed; -} + function setCompleted(uint completed) public restricted { + last_completed_migration = completed; + } -function upgrade(address new_address) public restricted { -Migrations upgraded = Migrations(new_address); -upgraded.setCompleted(last_completed_migration); -} -} + function upgrade(address new_address) public restricted { + Migrations upgraded = Migrations(new_address); + upgraded.setCompleted(last_completed_migration); + } +} \ No newline at end of file diff --git a/package.json b/package.json index 04af20b..159cbbf 100644 --- a/package.json +++ b/package.json @@ -11,11 +11,12 @@ "drizzle-react": "^1.1.1", "drizzle-react-components": "^1.1.0", "eth-block-tracker-es5": "^2.3.2", + "prop-types": "^15.6.1", "react": "^16.3.2", "react-dom": "^16.3.2", - "react-scripts": "1.1.1", + "react-scripts": "^1.1.4", "react-redux": "^5.0.7", - "react-router": "3.2.1", + "react-router": "^3.2.1", "react-router-redux": "^4.0.8", "redux": "^3.7.2", "redux-auth-wrapper": "1.1.0", diff --git a/src/containers/Menu.js b/src/containers/Menu.js new file mode 100644 index 0000000..e4be872 --- /dev/null +++ b/src/containers/Menu.js @@ -0,0 +1,69 @@ +import { drizzleConnect } from 'drizzle-react' +import React, { Component } from 'react' +import PropTypes from 'prop-types' + +const contract = "Forum"; +const method = "hasUserSignedUp"; + +class Menu extends Component { + constructor(props, context) { + super(props); + + this.contracts = context.drizzle.contracts; + + // Get the contract ABI + const abi = this.contracts[contract].abi; + + // Fetch initial value from chain and return cache key for reactive updates. + let methodArgs = this.props.methodArgs ? this.props.methodArgs : []; + this.dataKey = this.contracts[contract].methods[method].cacheCall(...methodArgs); + + // Iterate over abi for correct function. + for (let i = 0; i < abi.length; i++) { + if (abi[i].name === this.props.method) { + this.fnABI = abi[i]; + break + } + } + } + + render() { + // Contract is not yet intialized. + if(!this.props.contracts[contract].initialized) { + return ( + + ) + } + + // If the cache key we received earlier isn't in the store yet; the initial value is still being fetched. + if(!(this.dataKey in this.props.contracts[contract][method])) { + return ( + + ) + } + + let displayData = this.props.contracts[contract][method][this.dataKey].value; + + if (displayData) { + return( + User has signed up! + ) + } + + return( + User doesn't exist! + ) + } +} + +Menu.contextTypes = { + drizzle: PropTypes.object +}; + +const mapStateToProps = state => { + return { + contracts: state.contracts + } +}; + +export default drizzleConnect(Menu, mapStateToProps) \ No newline at end of file diff --git a/src/layouts/home/Home.js b/src/layouts/home/Home.js index 4ee67a7..eade9af 100644 --- a/src/layouts/home/Home.js +++ b/src/layouts/home/Home.js @@ -1,5 +1,6 @@ import React, { Component } from 'react' import { AccountData, ContractData, ContractForm } from 'drizzle-react-components' +import Menu from './../../containers/Menu' class Home extends Component { render() { @@ -15,6 +16,7 @@ class Home extends Component {

    Username:

    +

    From 3440165fda83aca4611298bbe9159be280bc2c6a Mon Sep 17 00:00:00 2001 From: Ezerous Date: Wed, 2 May 2018 17:27:05 +0300 Subject: [PATCH 6/6] Added AuthWrapperContainer, improved contract --- contracts/Forum.sol | 52 ++++++------ src/App.js | 2 +- src/containers/AuthWrapperContainer.js | 48 +++++++++++ src/containers/Menu.js | 69 ---------------- src/containers/UsernameFormContainer.js | 103 ++++++++++++++++++++++++ src/{ => css}/App.css | 0 src/{ => css}/index.css | 0 src/index.js | 2 + src/layouts/home/Home.js | 7 +- 9 files changed, 186 insertions(+), 97 deletions(-) create mode 100644 src/containers/AuthWrapperContainer.js delete mode 100644 src/containers/Menu.js create mode 100644 src/containers/UsernameFormContainer.js rename src/{ => css}/App.css (100%) rename src/{ => css}/index.css (100%) diff --git a/contracts/Forum.sol b/contracts/Forum.sol index eef2e82..0fc71f3 100644 --- a/contracts/Forum.sol +++ b/contracts/Forum.sol @@ -1,56 +1,62 @@ -pragma solidity ^0.4.21; +pragma solidity ^0.4.23; contract Forum { - //----------------------------------------USER---------------------------------------- + //----------------------------------------AUTHENTICATION---------------------------------------- struct User { - string userName; // TODO: set an upper bound instead of arbitrary string + string username; // TODO: set an upper bound instead of arbitrary string // TODO: orbitDBAddress; uint[] topicIDs; // IDs of the topics the user created uint[] postIDs; // IDs of the posts the user created + bool signedUp; // Helper variable for hasUserSignedUp() } mapping (address => User) users; mapping (string => address) userAddresses; - event UserSignedUp( - string userName - ); + event UserSignedUp(string username, address userAddress); + event UsernameUpdated(string newName, string oldName,address userAddress); - function signUp(string userName) public returns (bool) { // Also allows user to update his name - TODO: his previous name will appear as taken - require(!isUserNameTaken(userName)); - users[msg.sender] = User(userName, new uint[](0), new uint[](0)); - userAddresses[userName] = msg.sender; - emit UserSignedUp(userName); + function signUp(string username) public returns (bool) { + require (!hasUserSignedUp(msg.sender), "User has already signed up."); + require(!isUserNameTaken(username), "Username is already taken."); + users[msg.sender] = User(username, new uint[](0), new uint[](0), true); + userAddresses[username] = msg.sender; + emit UserSignedUp(username, msg.sender); return true; } - function login() public view returns (string) { - require (hasUserSignedUp(msg.sender)); - return users[msg.sender].userName; + function updateUsername(string newUsername) public returns (bool) { + require (hasUserSignedUp(msg.sender), "User hasn't signed up yet."); + require(!isUserNameTaken(newUsername), "Username is already taken."); + string memory oldUsername = getUsername(msg.sender); + delete userAddresses[users[msg.sender].username]; + users[msg.sender].username = newUsername; + userAddresses[newUsername] = msg.sender; + emit UsernameUpdated(newUsername, oldUsername, msg.sender); + return true; } function getUsername(address userAddress) public view returns (string) { - return users[userAddress].userName; + return users[userAddress].username; } - function getUserAddress(string userName) public view returns (address) { - return userAddresses[userName]; + function getUserAddress(string username) public view returns (address) { + return userAddresses[username]; } function hasUserSignedUp(address userAddress) public view returns (bool) { - if (bytes(getUsername(userAddress)).length!=0) - return true; - return false; + return users[userAddress].signedUp; } - function isUserNameTaken(string userName) public view returns (bool) { - if (getUserAddress(userName)!=0) + function isUserNameTaken(string username) public view returns (bool) { + if (getUserAddress(username)!=address(0)) return true; return false; } - //----------------------------------------TOPIC---------------------------------------- + + //----------------------------------------POSTING---------------------------------------- struct Topic { uint topicID; address author; diff --git a/src/App.js b/src/App.js index 45d9e02..f51c726 100644 --- a/src/App.js +++ b/src/App.js @@ -4,7 +4,7 @@ import React, { Component } from 'react' import './css/oswald.css' import './css/open-sans.css' import './css/pure-min.css' -import './App.css' +import './css/App.css' class App extends Component { render() { diff --git a/src/containers/AuthWrapperContainer.js b/src/containers/AuthWrapperContainer.js new file mode 100644 index 0000000..ce2ad11 --- /dev/null +++ b/src/containers/AuthWrapperContainer.js @@ -0,0 +1,48 @@ +import { drizzleConnect } from 'drizzle-react' +import React, { Component } from 'react' +import PropTypes from 'prop-types' + +const contract = "Forum"; +const method = "hasUserSignedUp"; + +class AuthWrapperContainer extends Component { + constructor(props, context) { + super(props); + + this.contracts = context.drizzle.contracts; + + this.dataKey = this.contracts[contract].methods[method].cacheCall(...[this.props.accounts[0]]); + } + + render() { + // Contract is not yet intialized. + if(!this.props.contracts[contract].initialized) + return (null); + + // If the cache key we received earlier isn't in the store yet; the initial value is still being fetched. + if(!(this.dataKey in this.props.contracts[contract][method])) + return (null); + + let userHasSignedUp = this.props.contracts[contract][method][this.dataKey].value; + const authRender = this.props.authRender; + const guestRender = this.props.guestRender; + + if (userHasSignedUp) + return(
    {authRender}
    ); + + return(
    {guestRender}
    ); + } +} + +AuthWrapperContainer.contextTypes = { + drizzle: PropTypes.object +}; + +const mapStateToProps = state => { + return { + accounts: state.accounts, + contracts: state.contracts, + } +}; + +export default drizzleConnect(AuthWrapperContainer, mapStateToProps) \ No newline at end of file diff --git a/src/containers/Menu.js b/src/containers/Menu.js deleted file mode 100644 index e4be872..0000000 --- a/src/containers/Menu.js +++ /dev/null @@ -1,69 +0,0 @@ -import { drizzleConnect } from 'drizzle-react' -import React, { Component } from 'react' -import PropTypes from 'prop-types' - -const contract = "Forum"; -const method = "hasUserSignedUp"; - -class Menu extends Component { - constructor(props, context) { - super(props); - - this.contracts = context.drizzle.contracts; - - // Get the contract ABI - const abi = this.contracts[contract].abi; - - // Fetch initial value from chain and return cache key for reactive updates. - let methodArgs = this.props.methodArgs ? this.props.methodArgs : []; - this.dataKey = this.contracts[contract].methods[method].cacheCall(...methodArgs); - - // Iterate over abi for correct function. - for (let i = 0; i < abi.length; i++) { - if (abi[i].name === this.props.method) { - this.fnABI = abi[i]; - break - } - } - } - - render() { - // Contract is not yet intialized. - if(!this.props.contracts[contract].initialized) { - return ( - - ) - } - - // If the cache key we received earlier isn't in the store yet; the initial value is still being fetched. - if(!(this.dataKey in this.props.contracts[contract][method])) { - return ( - - ) - } - - let displayData = this.props.contracts[contract][method][this.dataKey].value; - - if (displayData) { - return( - User has signed up! - ) - } - - return( - User doesn't exist! - ) - } -} - -Menu.contextTypes = { - drizzle: PropTypes.object -}; - -const mapStateToProps = state => { - return { - contracts: state.contracts - } -}; - -export default drizzleConnect(Menu, mapStateToProps) \ No newline at end of file diff --git a/src/containers/UsernameFormContainer.js b/src/containers/UsernameFormContainer.js new file mode 100644 index 0000000..469a47f --- /dev/null +++ b/src/containers/UsernameFormContainer.js @@ -0,0 +1,103 @@ +import { drizzleConnect } from 'drizzle-react' +import React, { Component } from 'react' +import PropTypes from 'prop-types' +import AuthWrapperContainer from './AuthWrapperContainer' + +const contract = "Forum"; +const signUpMethod = "signUp"; +const updateUsernameMethod ="updateUsername"; + +class UsernameFormContainer extends Component { + constructor(props, context) { + super(props); + + this.handleSignUp = this.handleSignUp.bind(this); + this.handleSignUpInputChange = this.handleSignUpInputChange.bind(this); + + this.handleUsernameUpdate = this.handleUsernameUpdate.bind(this); + this.handleUpdateUsernameInputChange = this.handleUpdateUsernameInputChange.bind(this); + + this.contracts = context.drizzle.contracts; + + // Get the contract ABI + const abi = this.contracts[contract].abi; + + + this.inputs = {signUp:[], updateUsername:[]}; + let initialState = {signUp:{}, updateUsername:{}}; + + // Iterate over abi for correct function. + for (let i = 0; i < abi.length; i++) { + if ((abi[i].name === signUpMethod)) { + this.inputs.signUp = abi[i].inputs; + + for (let i = 0; i < this.inputs.signUp.length; i++) { + initialState.signUp[this.inputs.signUp[i].name] = ''; + } + + } + else if ((abi[i].name === updateUsernameMethod)) { + this.inputs.updateUsername = abi[i].inputs; + + for (let i = 0; i < this.inputs.updateUsername.length; i++) { + initialState.updateUsername[this.inputs.updateUsername[i].name] = ''; + } + + } + } + console.dir(initialState); + this.state = initialState; + } + + handleSignUp() { + this.contracts[contract].methods[signUpMethod].cacheSend(...Object.values(this.state.signUp)); + } + + handleUsernameUpdate() { + this.contracts[contract].methods[updateUsernameMethod].cacheSend(...Object.values(this.state.updateUsername)); + } + + handleSignUpInputChange(event) { + this.setState({ signUp: { ...this.state.signUp, [event.target.name]: event.target.value} }); + } + + handleUpdateUsernameInputChange(event) { + this.setState({ updateUsername: { ...this.state.updateUsername, [event.target.name]: event.target.value} }); + } + + + render() { + let signUp = this.inputs.signUp[0].name; //username + let updateUsername = this.inputs.updateUsername[0].name; //newUsername + return ( + + + + + } + guestRender={ +
    + + +
    + } + /> + + + ) + } +} + +UsernameFormContainer.contextTypes = { + drizzle: PropTypes.object +}; + +const mapStateToProps = state => { + return { + contracts: state.contracts + } +}; + +export default drizzleConnect(UsernameFormContainer, mapStateToProps) \ No newline at end of file diff --git a/src/App.css b/src/css/App.css similarity index 100% rename from src/App.css rename to src/css/App.css diff --git a/src/index.css b/src/css/index.css similarity index 100% rename from src/index.css rename to src/css/index.css diff --git a/src/index.js b/src/index.js index 2ffbcc6..7877e8d 100644 --- a/src/index.js +++ b/src/index.js @@ -12,6 +12,8 @@ import { LoadingContainer } from 'drizzle-react-components' import store from './store' import drizzleOptions from './drizzleOptions' +import './css/index.css' + // Initialize react-router-redux. const history = syncHistoryWithStore(browserHistory, store); diff --git a/src/layouts/home/Home.js b/src/layouts/home/Home.js index eade9af..2b68cc5 100644 --- a/src/layouts/home/Home.js +++ b/src/layouts/home/Home.js @@ -1,6 +1,6 @@ import React, { Component } from 'react' -import { AccountData, ContractData, ContractForm } from 'drizzle-react-components' -import Menu from './../../containers/Menu' +import { AccountData, ContractData } from 'drizzle-react-components' +import UsernameFormContainer from '../../containers/UsernameFormContainer' class Home extends Component { render() { @@ -15,8 +15,7 @@ class Home extends Component {

    Account

    Username:

    - - +