OSDN Git Service

update the dapp demo to fit the latest bycoin and byone
authorZhiting Lin <zlin035@uottawa.ca>
Wed, 12 Jun 2019 06:54:50 +0000 (14:54 +0800)
committerZhiting Lin <zlin035@uottawa.ca>
Wed, 12 Jun 2019 06:54:50 +0000 (14:54 +0800)
16 files changed:
README.md
src/components/App.js
src/components/action.js [new file with mode: 0644]
src/components/constants.js
src/components/layout/account/index.jsx
src/components/layout/bytomWrap.jsx
src/components/layout/header/NetworkInfo.jsx
src/components/layout/profit/action.js
src/components/layout/profit/index.jsx
src/components/layout/save/action.js
src/components/layout/save/index.jsx
src/components/util/api.js
src/components/util/submitContract.js
src/index.js
src/reducers/rotateReducer.js
src/store.js

index a0a7107..d6e1839 100644 (file)
--- a/README.md
+++ b/README.md
@@ -23,7 +23,7 @@ Under the `./src/components/util/submitContract.js`, you will see the basic and
 - list utxo from buffer server
 - create the custom contract transaction
 - lock utxo
-- call `window.bytom.advancedTransfer` to create the advanced Transaction
+- call `window.bytom.send_advanced_transaction` to create the advanced Transaction
 - update balance if success.
 
 ### Input and Output Object
index 566a2f8..327aedd 100644 (file)
@@ -1,28 +1,76 @@
 import React, { Component } from "react";
 import '../styles/App.css';
-import { Switch, Route } from 'react-router-dom';
+import { Switch, Route, withRouter } from 'react-router-dom';
 import  Profit  from './layout/profit'
 import Saving from './layout/save'
 import Footer from './layout/footer'
 import Header from './layout/header'
 import Account from './layout/account'
+import action from './action'
 import bytomWrap from './layout/bytomWrap'
-
+import {connect} from "react-redux";
 
 import GetContractArgs from "./constants";
+import Bytom from 'bytom-js-sdk'
+
+class App extends Component {
+  componentDidMount(){
+    const { bytom, setBytom } = this.props;
+    if(!bytom){
+      document.addEventListener('chromeBytomLoaded', bytomExtension => {
+        console.log('bytomloaded');
+        const bytom = window.bytom;
+        setBytom(bytom);
+        this.bytomLoaded(bytom);
+      });
+    }else {
+      this.bytomLoaded(bytom);
+    }
+  }
+
+  bytomLoaded (bytom){
+    let bytomPollInterval = 3 * 1000;
+    let networks = {
+      solonet: 'http://app.bycoin.io:3000/',
+      testnet: 'http://app.bycoin.io:3020/',
+      mainnet: 'https://api.bycoin.im:8000/'
+    };
+
+    try {
+      const BYTOM_ACCOUNT = bytom.default_account
+
+      const bytomAPI = new Bytom(networks, '')
+      bytomAPI.setNetType(bytom.net)
+
+      global.bytomAPI = bytomAPI
 
-const App = () => (
-  <div>
-    <Header />
-    <Constants />
-    <section className="portfolio" id="portfolio">
-      <div className="container">
-        <Main />
+      // Check to see if the user has signed in/out of their
+      // bytom wallet or switched accounts
+      let accountInterval = setInterval(function () {
+        if (BYTOM_ACCOUNT.accountId !== bytom.default_account.accountId) {
+          location.reload(true);
+        }
+      }, bytomPollInterval);
+    } catch (err) {
+      console.log(err);
+    }
+  }
+
+  render() {
+    return  (
+      <div>
+        <Header />
+        <Constants />
+        <section className="portfolio" id="portfolio">
+          <div className="container">
+            <Main />
+          </div>
+        </section>
+        <Footer />
       </div>
-    </section>
-    <Footer />
-  </div>
-);
+    )
+  }
+}
 
 const Constants = () =>(
   <header className="masthead bg-primary text-white">
@@ -55,4 +103,13 @@ const Main = () => (
   </Switch>
 );
 
-export default App;
+
+const mapStateToProps = state => ({
+  bytom: state.bytom,
+})
+
+const mapDispatchToProps = dispatch => ({
+  setBytom: (bytom) => dispatch(action.setBytom(bytom)),
+})
+
+export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App))
\ No newline at end of file
diff --git a/src/components/action.js b/src/components/action.js
new file mode 100644 (file)
index 0000000..eb31889
--- /dev/null
@@ -0,0 +1,14 @@
+const setBytom = (bytom) => {
+  return (dispatch) => {
+    dispatch({
+      type: "UPDATE_BYTOM",
+      bytom
+    })
+  }
+}
+
+let actions = {
+  setBytom,
+}
+
+export default actions
index 0823b8d..1c44bb6 100644 (file)
@@ -14,8 +14,8 @@ let gas
 let radio
 
 const GetContractArgs = function() {
-  if(window.bytom && window.bytom.defaultAccount && window.bytom.defaultAccount.net){
-    let network = window.bytom.defaultAccount.net
+  if(window.bytom && window.bytom.default_account && window.bytom.net){
+    let network = window.bytom.net
 
     const object = config[network]
     if(object){
index 80f54e3..d6bffc6 100644 (file)
@@ -19,14 +19,15 @@ class Account extends Component {
   }
 
   componentDidMount() {
+    const bytom = this.props.bytom
     if (
-      window.bytom
-      && window.bytom.defaultAccount
+      bytom
+      && bytom.default_account
     ) {
-      const account = window.bytom.defaultAccount
+      const account = bytom.default_account
       this.setState({ account })
       if(account){
-        this.props.updateBalances(account.guid)
+        this.props.updateBalances(account.accountId)
         this.listBalance(account, GetContractArgs().assetDeposited)
       }
     }
@@ -119,7 +120,8 @@ class Account extends Component {
 
 const mapStateToProps = state => ({
   depositAssetBalance: state.depositAssetBalance,
-  billAssetBalance: state.billAssetBalance
+  billAssetBalance: state.billAssetBalance,
+  bytom: state.bytom
 })
 
 const mapDispatchToProps = dispatch => ({
index 32ed29b..77f8024 100644 (file)
@@ -1,4 +1,5 @@
 import React, { Component } from 'react'
+import {connect} from "react-redux";
 
 // This is a Higher Order Component (HOC) that wraps up any components that require
 // an unlocked Bytom account instance
@@ -10,9 +11,10 @@ export default function(WrappedComponent) {
     render () {
       let contents = <div />
 
+      const bytom = this.props.bytom
       if (
-        window.bytom
-        && window.bytom.defaultAccount
+        bytom
+        && bytom.default_account
       ) {
         return <WrappedComponent {...this.props} />
       }
@@ -58,7 +60,8 @@ export default function(WrappedComponent) {
     }
 
   }
-
-  return BytomWrap;
-
+  const mapStateToProps = state => ({
+    bytom: state.bytom,
+  })
+  return connect(mapStateToProps)(BytomWrap)
 }
index f395cb6..a08ed06 100644 (file)
@@ -14,9 +14,9 @@ const NetworkInfo = class extends Component {
   componentDidMount() {
     if (
       window.bytom
-      && window.bytom.defaultAccount
+      && window.bytom.default_account
     ) {
-      this.setState({ account: window.bytom.defaultAccount })
+      this.setState({ account: bytom.default_account })
     }
   }
 
@@ -24,7 +24,8 @@ const NetworkInfo = class extends Component {
     const account = this.state.account
 
     if (
-      account
+      window.bytom
+      && window.bytom.default_account
     ) {
       const svg = jdenticon.toSvg(account.alias, 40)
       return (
@@ -32,7 +33,7 @@ const NetworkInfo = class extends Component {
           <div className="nav-item  d-flex ">
             <NavLink  exact activeClassName="active" className="d-flex nav-link rounded js-scroll-trigger" to='/account'>
               <div className="mr-2" dangerouslySetInnerHTML={{__html:svg}} />
-              <div className="mt-auto mb-auto ">{account.alias}</div>
+              <div className="mt-auto mb-auto ">{window.bytom.default_account.alias}</div>
             </NavLink>
           </div>
         </div>
@@ -43,4 +44,5 @@ const NetworkInfo = class extends Component {
   }
 }
 
+
 export default NetworkInfo
index f67958e..741fddd 100644 (file)
@@ -86,7 +86,7 @@ function createContractTransaction(resp, amountBill, saver) {
 }
 
 function updateDatatbaseBalance(resp, saver, amountBill, account){
-  const transactionHash = resp.message.result.data.transaction_hash
+  const transactionHash = resp.transaction_hash
   const radio = BigNumber( GetContractArgs().radio )
   const profitAmount = radio.multipliedBy(amountBill).toNumber()
   return updateBalances({
index c851275..b75f27c 100644 (file)
@@ -2,6 +2,7 @@ import React from 'react'
 import { FixedLimitProfit } from './action'
 import GetContractArgs from "../../constants";
 import BigNumber from 'bignumber.js'
+import {connect} from "react-redux";
 
 class Profit extends React.Component {
 
@@ -19,11 +20,12 @@ class Profit extends React.Component {
   }
 
   componentDidMount() {
+    const bytom = this.props.bytom
     if (
-      window.bytom
-      && window.bytom.defaultAccount
+      bytom
+      && bytom.default_account
     ) {
-      this.setState({ account: window.bytom.defaultAccount })
+      this.setState({ account: bytom.default_account })
     }
   }
 
@@ -109,4 +111,8 @@ class Profit extends React.Component {
   }
 }
 
-export default Profit
+const mapStateToProps = state => ({
+  bytom: state.bytom,
+})
+
+export default connect(mapStateToProps)(Profit)
index 07cb11c..15c91ed 100644 (file)
@@ -77,13 +77,13 @@ function createContractTransaction(resp, amount, address){
 
 function updateDatatbaseBalance(resp, amount, address){
  return updateBalances({
-    "tx_id": resp.message.result.data.transaction_hash,
+    "tx_id": resp.transaction_hash,
     address,
     "asset": GetContractArgs().assetDeposited,
     "amount": -amount
   }).then(()=>{
     return updateBalances({
-      "tx_id": resp.message.result.data.transaction_hash,
+      "tx_id": resp.transaction_hash,
       address,
       "asset": GetContractArgs().assetBill,
       "amount": amount
index 928a652..8b51129 100644 (file)
@@ -1,6 +1,7 @@
 import React from 'react'
 import { FixedLimitDeposit} from './action'
 import GetContractArgs from '../../constants'
+import {connect} from "react-redux";
 
 class Save extends React.Component {
 
@@ -18,11 +19,12 @@ class Save extends React.Component {
   }
 
   componentDidMount() {
+    const bytom = this.props.bytom
     if (
-      window.bytom
-      && window.bytom.defaultAccount
+      bytom
+      && bytom.default_account
     ) {
-      this.setState({ account: window.bytom.defaultAccount })
+      this.setState({ account: bytom.default_account })
     }
   }
 
@@ -100,5 +102,8 @@ class Save extends React.Component {
     )
   }
 }
+const mapStateToProps = state => ({
+  bytom: state.bytom,
+})
 
-export default Save
+export default connect(mapStateToProps)(Save)
index 15f06ed..5224383 100644 (file)
@@ -11,7 +11,7 @@ export function listAddress(guid)
 export function listDappUTXO(params)
 {
   let url
-  switch (window.bytom.defaultAccount.net){
+  switch (window.bytom.net){
     case "testnet":
       url = "/dapptestnet/list-utxos"
       break
@@ -24,7 +24,7 @@ export function listDappUTXO(params)
 export function updateUtxo(params)
 {
   let url
-  switch (window.bytom.defaultAccount.net) {
+  switch (window.bytom.net) {
     case "testnet":
       url = "/dapptestnet/update-utxo"
       break
@@ -37,7 +37,7 @@ export function updateUtxo(params)
 export function updateBalances(params)
 {
   let url
-  switch (window.bytom.defaultAccount.net) {
+  switch (window.bytom.net) {
     case "testnet":
       url = "/dapptestnet/update-balance"
       break
@@ -50,7 +50,7 @@ export function updateBalances(params)
 export function listBalances(params)
 {
   let url
-  switch (window.bytom.defaultAccount.net) {
+  switch (window.bytom.net) {
     case "testnet":
       url = "/dapptestnet/list-balances"
       break
index b2c9f6e..740979f 100644 (file)
@@ -23,22 +23,17 @@ export function submitContract(listDepositUTXO, createContractTransaction, updat
           .then(()=>{
 
             //Transactions
-            window.bytom.advancedTransfer(input, output, GetContractArgs().gas*100000000, args, 1)
+            return window.bytom.send_advanced_transaction({input, output, gas: GetContractArgs().gas*100000000, args})
               .then((resp) => {
-                if(resp.action === 'reject'){
-                  reject('user reject the request')
-                }else if(resp.action === 'success'){
-
                   //Update Balance
                   return updateDatatbaseBalance(resp, ...updateParameters).then(()=>{
                     resolve()
                   }).catch(err => {
                     throw err
                   })
-                }
               })
               .catch(err => {
-                throw err
+                throw err.message
               })
           })
           .catch(err => {
index c60513e..0cf643b 100644 (file)
@@ -10,51 +10,16 @@ import { BrowserRouter } from 'react-router-dom';
 import { Provider } from "react-redux";
 import configureStore from "./store";
 
-import Bytom from 'bytom-js-sdk'
-
 require("babel-core/register");
 require("babel-polyfill");
 
-window.addEventListener('load', async function() {
-  if (typeof window.bytom !== 'undefined') {
-    let bytomPollInterval =  3 * 1000;
-
-    let networks = {
-      solonet: 'http://app.bycoin.io:3000/',
-      testnet: 'http://app.bycoin.io:3020/',
-      mainnet: 'https://api.bycoin.im:8000/'
-    };
-
-    try {
-      window.bytom.defaultAccount = await window.bytom.request('currentAccount')
-
-      const bytom = new Bytom(networks, '')
-      bytom.setNetType(window.bytom.defaultAccount.net)
-
-      global.bytomAPI = bytom
-
-      // Check to see if the user has signed in/out of their
-      // bytom wallet or switched accounts
-      let accountInterval = setInterval(async function() {
-        const account = await window.bytom.request('currentAccount')
-        if ( account.guid !== window.bytom.defaultAccount.guid) {
-          location.reload(true);
-        }
-      }, bytomPollInterval);
-    } catch (err) {
-      console.log(err);
-    }
-
-  }
-
-  ReactDOM.render((
-    <Provider store={configureStore()}>
-      <BrowserRouter>
-        <App />
-      </BrowserRouter>
-    </Provider>
-  ), document.getElementById('root'));
-});
+ReactDOM.render((
+  <Provider store={configureStore()}>
+    <BrowserRouter>
+      <App />
+    </BrowserRouter>
+  </Provider>
+), document.getElementById('root'));
 
 
 
index 0ca09ab..e5a2667 100644 (file)
@@ -10,6 +10,11 @@ export default (state, action) => {
         ...state,
         depositAssetBalance: action.depositAssetBalance
       };
+    case "UPDATE_BYTOM":
+      return {
+        ...state,
+        bytom: action.bytom
+      };
     default:
       return state
   }
index 8e9b85b..2218f32 100644 (file)
@@ -2,7 +2,7 @@ import rotateReducer from "./reducers/rotateReducer"
 import { createStore, applyMiddleware, compose } from 'redux'
 import thunkMiddleware from 'redux-thunk'
 
-function configureStore(state = { account: '' , depositAssetBalance:'',billAssetBalance:''}) {
+function configureStore(state = { account: '' , depositAssetBalance:'',billAssetBalance:'', bytom:''}) {
   return createStore(
     rotateReducer,
     state,