Skip to content

Commit

Permalink
fix network change update error
Browse files Browse the repository at this point in the history
  • Loading branch information
lvshaoping007 committed Nov 19, 2022
1 parent ad77477 commit a44a3e7
Show file tree
Hide file tree
Showing 7 changed files with 82 additions and 100 deletions.
28 changes: 28 additions & 0 deletions src/background/api/axios.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const axios = require('axios');
const { ERROR_TYPE } = require('../../constant/errType');
const { default: store } = require('../../store/store');
const timeout = 1 * 60 * 1000;
axios.defaults.retry = 3;
axios.defaults.retryDelay = 1000;
Expand Down Expand Up @@ -109,9 +110,36 @@ axios.interceptors.request.use(function (config) {
let timeToken = setTimeout(() => tokenItem.cancel({ message: 'Timeout', config: config }), timeout);
config.clearCancelToken = () => clearTimeout(timeToken);
});
let netType = store.getState().network?.currentConfig?.netType||""
if(netType){
config.netType = netType
}
return config;
});

const stableOperationNameList = ["sendTx","stakeTx","sendZkapp","txStatus"]

axios.interceptors.response.use(function (response) {
removeQueue(response.config);
let netType = store.getState().network?.currentConfig?.netType||""
if(netType !== response.config.netType){
try {
if(response.config.data){
let gqlData = JSON.parse(response.config.data)
let operationName = gqlData.operationName
if(operationName && stableOperationNameList.indexOf(operationName)=== -1){
if(Array.isArray(response.data.data)){
response.data = []
return response
}else{
response.data ={}
return response
}
}
}
} catch (error) {
return response;
}
}
return response;
}, axiosRetryInterceptor);
39 changes: 14 additions & 25 deletions src/background/api/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { BASE_INFO_URL, TX_LIST_LENGTH } from "../../../config";
import { LOCAL_BASE_INFO, LOCAL_CACHE_KEYS, NETWORK_ID_AND_TYPE } from "../../constant/storageKey";
import { NET_CONFIG_TYPE } from "../../constant/walletType";
import { getCurrentNetConfig, parseStakingList } from "../../utils/utils";
import { saveLocal } from "../localStorage";
import { commonFetch, startFetchMyMutation, startFetchMyQuery } from "../request";
Expand All @@ -17,7 +18,9 @@ export async function getBalance(address) {
publicKey: address
}
).catch((error) => error)
let account = result.account || {}
let account = result.account || {
publicKey:address
}
saveLocal(LOCAL_CACHE_KEYS.ACCOUNT_BALANCE, JSON.stringify({ [address]: account }))
if(result.error){
account.error = result.error
Expand Down Expand Up @@ -171,26 +174,6 @@ export async function getBaseInfo() {
return data
}



/**
* get transaction history
* @param {*} address
* @param {*} limit
* @returns
*/
export async function getTransactionList(address, limit = TX_LIST_LENGTH) {
let netConfig = getCurrentNetConfig()
let baseUrl = netConfig.txUrl
let txUrl = baseUrl + "/transactions?account=" + address
if (limit) {
txUrl += "&limit=" + limit
}
let txList = await commonFetch(txUrl).catch(() => [])
saveLocal(LOCAL_CACHE_KEYS.TRANSACTION_HISTORY, JSON.stringify({ [address]: txList }))
return { txList, address }
}

/**
* get pending transation in gql
* @param {*} address
Expand Down Expand Up @@ -257,6 +240,9 @@ export async function getNodeChainId(gqlUrl) {
*/
export async function getCurrencyPrice(currency) {
let netConfig = getCurrentNetConfig()
if(!netConfig.txUrl){
return 0
}
let priceUrl = netConfig.txUrl + "/prices?currency=" + currency
let data = await commonFetch(priceUrl).catch(() => { })
let price = data?.data || 0
Expand Down Expand Up @@ -287,7 +273,7 @@ export async function getGqlTxHistory(address,limit){
{
requestType: "extensionAccountInfo",
publicKey: address,
limit:limit||20
limit:limit||10
},
gqlTxUrl,
).catch((error) => error)
Expand Down Expand Up @@ -329,7 +315,9 @@ export async function getGqlTxHistory(address,limit){
export async function getZkAppTxHistory(address,limit){
let netConfig = getCurrentNetConfig()
let gqlTxUrl = netConfig.gqlTxUrl
if (!gqlTxUrl) {

if (!gqlTxUrl || netConfig.netType !== NET_CONFIG_TYPE.Berkeley) {
saveLocal(LOCAL_CACHE_KEYS.ZKAPP_TX_LIST, JSON.stringify({ [address]: [] }))
return []
}
let txBody = getZkAppTransactionListBody()
Expand All @@ -338,7 +326,7 @@ export async function getZkAppTxHistory(address,limit){
{
requestType: "extensionAccountInfo",
publicKey: address,
limit:limit||20
limit:limit||10
},
gqlTxUrl,
).catch((error) => error)
Expand All @@ -351,7 +339,8 @@ export async function getZkAppTxHistory(address,limit){
export async function getZkAppPendingTx(address,limit){
let netConfig = getCurrentNetConfig()
let gqlTxUrl = netConfig.url
if (!gqlTxUrl) {
if (!gqlTxUrl || netConfig.netType !== NET_CONFIG_TYPE.Berkeley) {
saveLocal(LOCAL_CACHE_KEYS.ZKAPP_PENDING_TX_LIST, JSON.stringify({ [address]: [] }))
return []
}
if(gqlTxUrl.indexOf("graphql")!==-1){
Expand Down
14 changes: 4 additions & 10 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { updateDAppOpenWindow } from "./reducers/cache";
import { updateCurrencyConfig } from "./reducers/currency";
import { ENTRY_WITCH_ROUTE, updateEntryWitchRoute } from "./reducers/entryRouteReducer";
import { NET_CONFIG_DEFAULT, updateNetConfig } from "./reducers/network";
import store from "./store/store";
import { sendMsg } from "./utils/commonMsg";
import { sendNetworkChangeMsg } from "./utils/utils";

Expand Down Expand Up @@ -217,8 +218,7 @@ async function getLocalStatus(store) {

export const applicationEntry = {
async run() {
this.createReduxStore();
await this.appInit(this.reduxStore)
await this.appInit(store)
this.render();
},

Expand All @@ -239,17 +239,11 @@ export const applicationEntry = {
store.dispatch(updateEntryWitchRoute(nextRoute))
}
},
createReduxStore() {
this.reduxStore = configureStore({
reducer: rootReducer,
middleware: [...getDefaultMiddleware(),
],
});
},

render() {
ReactDOM.render(
<React.StrictMode>
<Provider store={this.reduxStore}>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
Expand Down
51 changes: 0 additions & 51 deletions src/popup/pages/AccountInfo/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import cls from "classnames";
import i18n from "i18next";
import { useCallback, useMemo, useState } from "react";
import { cointypes } from "../../../../config";
import { getTransactionList } from "../../../background/api";
import { SEC_DELETE_ACCOUNT } from "../../../constant/secTypes";
import {
DAPP_DELETE_ACCOUNT_CONNECT_HIS,
Expand Down Expand Up @@ -97,56 +96,6 @@ const AccountInfo = ({}) => {
});
}, []);

const exportCsvTransactions = useCallback(async () => {
Loading.show();
const { txList } = await getTransactionList(account.address, null);
Loading.hide();
const csvList = txList.map((tx) => {
return {
date: tx.time.replace(/T/, " ").replace(/Z/, " UTC"),
amount: amountDecimals(tx.amount, cointypes.decimals),
sender: tx.sender,
receiver: tx.receiver,
memo: tx.memo ? tx.memo : "",
fee: amountDecimals(tx.fee, cointypes.decimals),
nonce: tx.nonce,
type: tx.type,
hash: tx.hash,
status: tx.status,
};
});
JSonToCSV.setDataConver({
data: csvList,
fileName: account.address,
columns: {
title: [
"Date",
"Amount",
"Sender",
"Receiver",
"Memo",
"Fee",
"Nonce",
"Type",
"TxHash",
"Status",
],
key: [
"date",
"amount",
"sender",
"receiver",
"memo",
"fee",
"nonce",
"type",
"hash",
"status",
],
},
});
}, [account]);

const deleteAccount = useCallback(() => {
if (account.type === ACCOUNT_TYPE.WALLET_WATCH) {
Loading.show();
Expand Down
17 changes: 8 additions & 9 deletions src/popup/pages/Wallet/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Trans } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { cointypes } from '../../../../config';
import { getBalance, getCurrencyPrice, getGqlTxHistory, getPendingTxList, getTransactionList, getZkAppPendingTx, getZkAppTxHistory } from "../../../background/api";
import { getBalance, getCurrencyPrice, getGqlTxHistory, getPendingTxList, getZkAppPendingTx, getZkAppTxHistory } from "../../../background/api";
import { saveLocal } from '../../../background/localStorage';
import { NET_WORK_CONFIG } from '../../../constant/storageKey';
import { DAPP_DISCONNECT_SITE, DAPP_GET_CONNECT_STATUS, WALLET_GET_ALL_ACCOUNT } from '../../../constant/types';
Expand Down Expand Up @@ -317,15 +317,15 @@ const WalletInfo = () => {
}
})
fetchPrice()
}, [i18n, currentAccount, fetchPrice])
}, [i18n, currentAccount])

useEffect(() => {
fetchAccountData()
}, [netConfig.currentConfig.netType, fetchAccountData])

useEffect(()=>{
fetchPrice()
},[currencyConfig.currentCurrency])
},[currencyConfig.currentCurrency,netConfig.currentConfig.netType])
return (
<>
<div className={styles.walletInfoContainer}>
Expand Down Expand Up @@ -450,8 +450,7 @@ const WalletDetail = () => {
if (showHistoryStatus) {
requestHistory(true)
}
}, [showHistoryStatus, requestHistory])

}, [showHistoryStatus])

useEffect(() => {
setHistoryList(accountInfo.txList)
Expand All @@ -474,7 +473,7 @@ const WalletDetail = () => {
} else {
setShowHistoryStatus(true)
}
}, [netConfig.currentConfig.netType, requestHistory])
}, [netConfig.currentConfig.netType])


useEffect(() => {
Expand Down Expand Up @@ -637,10 +636,10 @@ const TxItem = ({ txData, currentAccount }) => {
let statusIcon, showAddress, timeInfo, amount, statusText, statusStyle = ''


if (txData.kind.toLowerCase() === "payment") {
if (txData.kind?.toLowerCase() === "payment") {
isReceive = txData.to.toLowerCase() === currentAccount.address.toLowerCase()
statusIcon = isReceive ? "/img/tx_receive.svg" : "/img/tx_send.svg"
} else if(txData.kind.toLowerCase() === "zkapp"){
} else if(txData.kind?.toLowerCase() === "zkapp"){
isReceive = false
statusIcon = "/img/tx_history_zkapp.svg"
}else {
Expand All @@ -657,7 +656,7 @@ const TxItem = ({ txData, currentAccount }) => {
amount = getDisplayAmount(amount, 2)
amount = isReceive ? "+" + amount : "-" + amount

if(txData.kind.toLowerCase() === "zkapp"){
if(txData.kind?.toLowerCase() === "zkapp"){
amount = "0"
}

Expand Down
26 changes: 22 additions & 4 deletions src/reducers/accountReducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ function pendingTx(txList) {
"nonce": detail.nonce,
"memo": detail.memo,
"status": "PENDING",
timestamp : new Date(detail.time).getTime()
})
}
return newList
Expand Down Expand Up @@ -137,11 +138,17 @@ function zkAppFormat(zkAppList,isPending=false){
"status": status,
type:"zkApp",
body:zkApp,
timestamp : isPending ? "": new Date(zkApp.dateTime).getTime()
})
}
return newList
}

function commonHistoryFormat(list){
return list.map((item)=>{
item.timestamp = new Date(item.dateTime).getTime()
return item
})
}
const accountInfo = (state = initState, action) => {
switch (action.type) {
case CHANGE_ACCOUNT_TX_HISTORY:
Expand All @@ -154,9 +161,20 @@ const accountInfo = (state = initState, action) => {
txPendingList = pendingTx(txPendingList)
zkAppList = zkAppFormat(zkAppList)
zkPendingList = zkAppFormat(zkPendingList,true)

txList = commonHistoryFormat(txList)

let newList = [...txPendingList, ...txList,...zkAppList,...zkPendingList]
newList.sort((a,b)=>b.nonce-a.nonce)
const commonList = [...txList,...zkAppList]
commonList.sort((a,b)=>b.timestamp-a.timestamp)

const commonPendingList = [...txPendingList,...zkPendingList]
commonPendingList.sort((a,b)=>b.nonce-a.nonce)
let newList = [...commonPendingList,...commonList]
if (newList.length > 0) {
newList.push({
showExplorer: true
})
}
return {
...state,
txList: newList
Expand All @@ -179,7 +197,7 @@ const accountInfo = (state = initState, action) => {
}
case UPDATE_NET_ACCOUNT:
let netAccount = action.account
let balance = amountDecimals(netAccount.balance.total, cointypes.decimals)
let balance = amountDecimals(netAccount.balance?.total, cointypes.decimals)
let nonce = netAccount.nonce
let inferredNonce = netAccount.inferredNonce

Expand Down
7 changes: 6 additions & 1 deletion src/store/store.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { configureStore, getDefaultMiddleware } from "@reduxjs/toolkit";
import { applyMiddleware, createStore } from "redux";
import thunk from 'redux-thunk';
import rootReducer from '../reducers';


const store = createStore(rootReducer, applyMiddleware(thunk));
const store = configureStore({
reducer: rootReducer,
middleware: [...getDefaultMiddleware(),
],
});
export default store;

0 comments on commit a44a3e7

Please sign in to comment.