Skip to content

Commit

Permalink
refactor modules to async await (#321)
Browse files Browse the repository at this point in the history
* refactor modules to async await

* chain the promise resolves

* put send back in one test

* unchain promises

* remove done callback from async await methods
  • Loading branch information
dvdschwrtz authored and evgenyboxer committed Nov 12, 2017
1 parent 52f8e04 commit 2c7c83f
Show file tree
Hide file tree
Showing 10 changed files with 204 additions and 250 deletions.
86 changes: 36 additions & 50 deletions __tests__/components/Claim.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,44 +66,36 @@ describe('Claim', () => {
})

describe('when do gas claim button is clicked', () => {
test('should dispatch transaction failure event', (done) => {
test('should dispatch transaction failure event', async () => {
const { wrapper, store } = setup()
const response = Promise.resolve('pause')
neonjs.doSendAsset = jest.fn(() => {
return new Promise((resolve, reject) => {
resolve({ result: undefined })
})
})
wrapper.dive().find('#claim button').simulate('click')

response.then(() => {
try {
const actions = store.getActions()
expect(actions.length).toEqual(2)
expect(actions[0]).toEqual({
payload: {
message: 'Sending Neo to Yourself...',
type: 'INFO'
},
type: 'SHOW_NOTIFICATION'
})
expect(actions[1]).toEqual({
payload: {
message: 'Transaction failed!',
type: 'ERROR'
},
type: 'SHOW_NOTIFICATION'
})
done()
} catch (e) {
done.fail(e)
}
await Promise.resolve().then().then().then()
const actions = store.getActions()
expect(actions.length).toEqual(2)
expect(actions[0]).toEqual({
payload: {
message: 'Sending Neo to Yourself...',
type: 'INFO'
},
type: 'SHOW_NOTIFICATION'
})
expect(actions[1]).toEqual({
payload: {
message: 'Transaction failed!',
type: 'ERROR'
},
type: 'SHOW_NOTIFICATION'
})
})

test('should dispatch transaction waiting, set claim request and disable claim event', (done) => {
test('should dispatch transaction waiting, set claim request and disable claim event', async () => {
const { wrapper, store } = setup()
const response = Promise.resolve('pause')
neonjs.doSendAsset = jest.fn(() => {
return new Promise((resolve, reject) => {
resolve({ result: true })
Expand All @@ -112,31 +104,25 @@ describe('Claim', () => {

wrapper.dive().find('#claim button').simulate('click')

response.then(() => {
try {
const actions = store.getActions()
expect(actions.length).toEqual(4)
expect(actions[0]).toEqual({
payload: {
message: 'Sending Neo to Yourself...',
type: 'INFO'
},
type: 'SHOW_NOTIFICATION'
})
expect(actions[1]).toEqual({
payload: {
message: 'Waiting for transaction to clear...',
type: 'INFO'
},
type: 'SHOW_NOTIFICATION'
})
expect(actions[2]).toEqual(setClaimRequest(true))
expect(actions[3]).toEqual(disableClaim(true))
done()
} catch (e) {
done.fail(e)
}
await Promise.resolve().then().then().then()
const actions = store.getActions()
expect(actions.length).toEqual(4)
expect(actions[0]).toEqual({
payload: {
message: 'Sending Neo to Yourself...',
type: 'INFO'
},
type: 'SHOW_NOTIFICATION'
})
expect(actions[1]).toEqual({
payload: {
message: 'Waiting for transaction to clear...',
type: 'INFO'
},
type: 'SHOW_NOTIFICATION'
})
expect(actions[2]).toEqual(setClaimRequest(true))
expect(actions[3]).toEqual(disableClaim(true))
})
})
})
17 changes: 8 additions & 9 deletions __tests__/components/NetworkSwitch.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ describe('NetworkSwitch', () => {
done()
})

test('switches to TestNet when clicked', (done) => {
test('switches to TestNet when clicked', async () => {
const { wrapper, store } = setup()
const state = store.getState()
const deepWrapper = wrapper.dive()
Expand All @@ -70,13 +70,12 @@ describe('NetworkSwitch', () => {
SET_BALANCE
]
deepWrapper.find('.netName').simulate('click')
setTimeout(() => {
const actions = store.getActions()
actions.forEach(action => {
expect(actionTypes.indexOf(action.type) > -1).toEqual(true)
})
expect(actions.length).toEqual(5)
done()
}, 0)

await Promise.resolve().then().then().then()
const actions = store.getActions()
actions.forEach(action => {
expect(actionTypes.indexOf(action.type) > -1).toEqual(true)
})
expect(actions.length).toEqual(5)
})
})
3 changes: 1 addition & 2 deletions __tests__/components/Send.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'

jest.useFakeTimers()
jest.mock('neon-js')

const axiosMock = new MockAdapter(axios)
axiosMock.onAny().reply(200)
Expand Down Expand Up @@ -298,7 +297,7 @@ describe('Send', () => {

wrapper.find('#confirmPane').simulate('click')

Promise.resolve('pause').then(() => {
Promise.resolve('pause').then().then().then(() => {
jest.runAllTimers()
const actions = store.getActions()
expect(actions.length).toEqual(3)
Expand Down
27 changes: 12 additions & 15 deletions app/modules/account.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,24 +44,21 @@ export function setKeys (accountKeys: any) {
}

export const loginNep2 = (passphrase: string, wif: string, history: Object) => (dispatch: DispatchType) => {
const dispatchError = (message: string) => dispatch(showErrorNotification({ message }))

if (!validatePassphrase(passphrase)) {
dispatch(showErrorNotification({ message: 'Passphrase too short' }))
return dispatchError('Passphrase too short')
}
dispatch(showInfoNotification({ message: 'Decrypting encoded key...' }))
const wrongPassphraseOrEncryptedKeyError = () => {
dispatch(showErrorNotification({ message: 'Wrong passphrase or invalid encrypted key' }))
}
setTimeout(() => {

setTimeout(async () => {
try {
decryptWIF(wif, passphrase).then((wif) => {
dispatch(hideNotification({ noAnimation: true }))
dispatch(login(wif))
history.push(ROUTES.DASHBOARD)
}).catch(() => {
wrongPassphraseOrEncryptedKeyError()
})
const [_err, responseWif] = await asyncWrap(decryptWIF(wif, passphrase)) // eslint-disable-line
dispatch(hideNotification({ noAnimation: true }))
dispatch(login(responseWif))
return history.push(ROUTES.DASHBOARD)
} catch (e) {
wrongPassphraseOrEncryptedKeyError()
return dispatchError('Wrong passphrase or invalid encrypted key')
}
}, 500)
}
Expand Down Expand Up @@ -90,9 +87,9 @@ export function hardwarePublicKey (publicKey: string) {
export const loginWithPrivateKey = (wif: string, history: Object, route?: RouteType) => (dispatch: DispatchType) => {
if (verifyPrivateKey(wif)) {
dispatch(login(wif))
history.push(route || ROUTES.DASHBOARD)
return history.push(route || ROUTES.DASHBOARD)
} else {
dispatch(showErrorNotification({ message: 'That is not a valid private key' }))
return dispatch(showErrorNotification({ message: 'That is not a valid private key' }))
}
}

Expand Down
50 changes: 24 additions & 26 deletions app/modules/claim.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { FIVE_MINUTES_MS } from '../core/time'
import { getWif, getAddress, getSigningFunction, getPublicKey } from './account'
import { getNetwork } from './metadata'
import { getNeo } from './wallet'
import asyncWrap from '../core/asyncHelper'

// Constants
export const SET_CLAIM = 'SET_CLAIM'
Expand Down Expand Up @@ -38,13 +39,12 @@ export function disableClaim (disableClaimButton: boolean) {
}
}

export const syncAvailableClaim = (net: NetworkType, address: string) => (dispatch: DispatchType) => {
getClaimAmounts(net, address).then((result) => {
return dispatch(setClaim(result.available, result.unavailable))
})
export const syncAvailableClaim = (net: NetworkType, address: string) => async (dispatch: DispatchType) => {
const [_err, result] = await asyncWrap(getClaimAmounts(net, address)) // eslint-disable-line
return dispatch(setClaim(result.available, result.unavailable))
}

export const doClaimNotify = () => (dispatch: DispatchType, getState: GetStateType) => {
export const doClaimNotify = () => async (dispatch: DispatchType, getState: GetStateType) => {
const state = getState()
const wif = getWif(state)
const address = getAddress(state)
Expand All @@ -67,21 +67,20 @@ export const doClaimNotify = () => (dispatch: DispatchType, getState: GetStateTy
claimGasFn = () => doClaimAllGas(net, wif)
}

claimGasFn().then((response) => {
if (response.result) {
dispatch(showSuccessNotification({
message: 'Claim was successful! Your balance will update once the blockchain has processed it.'
}))
setTimeout(() => dispatch(disableClaim(false)), FIVE_MINUTES_MS)
} else {
dispatch(showErrorNotification({ message: 'Claim failed' }))
}
})
const [err, response] = await asyncWrap(claimGasFn())
if (!err && response.result) {
dispatch(showSuccessNotification({
message: 'Claim was successful! Your balance will update once the blockchain has processed it.'
}))
setTimeout(() => dispatch(disableClaim(false)), FIVE_MINUTES_MS)
} else {
return dispatch(showErrorNotification({ message: 'Claim failed' }))
}
}

// To initiate claim, first send all Neo to own address, the set claimRequest state
// When new claims are available, this will trigger the claim
export const doGasClaim = () => (dispatch: DispatchType, getState: GetStateType) => {
export const doGasClaim = () => async (dispatch: DispatchType, getState: GetStateType) => {
const state = getState()
const wif = getWif(state)
const address = getAddress(state)
Expand All @@ -92,7 +91,7 @@ export const doGasClaim = () => (dispatch: DispatchType, getState: GetStateType)

// if no neo in account, no need to send to self first
if (neo === 0) {
dispatch(doClaimNotify())
return dispatch(doClaimNotify())
} else {
dispatch(showInfoNotification({ message: 'Sending Neo to Yourself...', dismissible: false }))
log(net, 'SEND', address, { to: address, amount: neo, asset: ASSETS.NEO })
Expand All @@ -110,15 +109,14 @@ export const doGasClaim = () => (dispatch: DispatchType, getState: GetStateType)
sendAssetFn = () => doSendAsset(net, address, wif, { [ASSETS.NEO]: neo })
}

sendAssetFn().then((response) => {
if (response.result === undefined || response.result === false) {
dispatch(showErrorNotification({ message: 'Transaction failed!' }))
} else {
dispatch(showInfoNotification({ message: 'Waiting for transaction to clear...', dismissible: false }))
dispatch(setClaimRequest(true))
dispatch(disableClaim(true))
}
})
const [err, response] = await asyncWrap(sendAssetFn())
if (err || response.result === undefined || response.result === false) {
return dispatch(showErrorNotification({ message: 'Transaction failed!' }))
} else {
dispatch(showInfoNotification({ message: 'Waiting for transaction to clear...', dismissible: false }))
dispatch(setClaimRequest(true))
return dispatch(disableClaim(true))
}
}
}

Expand Down
Loading

0 comments on commit 2c7c83f

Please sign in to comment.