Skip to content

Commit

Permalink
Revert "(Bug) #955 withdraw transaction failed (#1003)" (#1012)
Browse files Browse the repository at this point in the history
This reverts commit df178fc.
  • Loading branch information
sirpy committed Dec 1, 2019
1 parent 3cbca7e commit 6d1532f
Show file tree
Hide file tree
Showing 8 changed files with 54 additions and 109 deletions.
9 changes: 1 addition & 8 deletions src/components/dashboard/Claim.js
Expand Up @@ -205,13 +205,8 @@ const Claim = props => {
if (curEntitlement == 0) { if (curEntitlement == 0) {
return return
} }

let txHash

const receipt = await goodWallet.claim({ const receipt = await goodWallet.claim({
onTransactionHash: hash => { onTransactionHash: hash => {
txHash = hash

const date = new Date() const date = new Date()
const transactionEvent: TransactionEvent = { const transactionEvent: TransactionEvent = {
id: hash, id: hash,
Expand All @@ -225,9 +220,7 @@ const Claim = props => {
userStorage.enqueueTX(transactionEvent) userStorage.enqueueTX(transactionEvent)
AsyncStorage.setItem('GD_AddWebAppLastClaim', date.toISOString()) AsyncStorage.setItem('GD_AddWebAppLastClaim', date.toISOString())
}, },
onError: () => { onError: userStorage.markWithErrorEvent,
userStorage.markWithErrorEvent(txHash)
},
}) })


if (receipt.status) { if (receipt.status) {
Expand Down
15 changes: 0 additions & 15 deletions src/components/dashboard/FeedItems/EventSettingsByType.js
Expand Up @@ -61,21 +61,6 @@ const getEventSettingsByType = (theme, type) => {
color: theme.colors.green, color: theme.colors.green,
name: 'receive-filled', name: 'receive-filled',
}, },
withdrawerror: {
color: theme.colors.primary,
name: 'info',
withoutAmount: true,
},
withdrawcompleted: {
actionSymbol: '+',
color: theme.colors.green,
name: 'receive-filled',
},
withdrawpending: {
actionSymbol: '+',
color: theme.colors.orange,
name: 'receive-filled',
},
message: { message: {
color: theme.colors.purple, color: theme.colors.purple,
name: 'social-good-filled', name: 'social-good-filled',
Expand Down
2 changes: 1 addition & 1 deletion src/components/dashboard/FeedItems/FeedModalItem.js
Expand Up @@ -42,7 +42,7 @@ const FeedModalItem = (props: FeedEventProps) => {
> >
{item.type === 'feedback' ? ( {item.type === 'feedback' ? (
<FeedbackModalItem {...props} /> <FeedbackModalItem {...props} />
) : ['senderror', 'withdrawerror'].includes(itemType) ? ( ) : itemType === 'senderror' ? (
<SendModalItemWithError {...props} /> <SendModalItemWithError {...props} />
) : ( ) : (
<React.Fragment> <React.Fragment>
Expand Down
6 changes: 2 additions & 4 deletions src/components/dashboard/FeedItems/ListEventItem.js
Expand Up @@ -26,7 +26,6 @@ const ListEvent = ({ item: feed, theme, styles }: FeedEventProps) => {
const mainColor = eventSettings.color const mainColor = eventSettings.color
const isSmallDevice = isMobile && getScreenWidth() < 353 const isSmallDevice = isMobile && getScreenWidth() < 353
const isFeedTypeClaiming = feed.type === 'claiming' const isFeedTypeClaiming = feed.type === 'claiming'
const isErrorCard = ['senderror', 'withdrawerror'].includes(itemType)


if (itemType === 'empty') { if (itemType === 'empty') {
return <EmptyEventFeed /> return <EmptyEventFeed />
Expand Down Expand Up @@ -65,7 +64,7 @@ const ListEvent = ({ item: feed, theme, styles }: FeedEventProps) => {
source={feed.data && feed.data.endpoint && feed.data.endpoint.avatar} source={feed.data && feed.data.endpoint && feed.data.endpoint.avatar}
/> />
<View style={[styles.mainInfo, isFeedTypeClaiming && styles.claimingCardFeedText]}> <View style={[styles.mainInfo, isFeedTypeClaiming && styles.claimingCardFeedText]}>
{isErrorCard ? ( {itemType === 'senderror' ? (
<> <>
<Text fontWeight="medium" lineHeight={19} style={styles.mainText} color="primary"> <Text fontWeight="medium" lineHeight={19} style={styles.mainText} color="primary">
{`We're sorry.`} {`We're sorry.`}
Expand Down Expand Up @@ -108,7 +107,7 @@ const getWelcomeStyles = ({ theme }) => ({
display: 'inline', display: 'inline',
}, },
welcomeText: { welcomeText: {
textAlign: 'left', flexShrink: 0,
}, },
}) })


Expand Down Expand Up @@ -249,7 +248,6 @@ const getStylesFromProps = ({ theme }) => ({
}, },
mainText: { mainText: {
textAlignVertical: 'middle', textAlignVertical: 'middle',
paddingTop: 5,
}, },
}) })


Expand Down
11 changes: 1 addition & 10 deletions src/components/dashboard/SendLinkSummary.js
Expand Up @@ -109,8 +109,6 @@ const SendLinkSummary = ({ screenProps }: AmountProps) => {
*/ */
const generateLink = () => { const generateLink = () => {
try { try {
let txHash

// Generate link deposit // Generate link deposit
const generateLinkResponse = goodWallet.generateLink( const generateLinkResponse = goodWallet.generateLink(
amount, amount,
Expand Down Expand Up @@ -143,14 +141,7 @@ const SendLinkSummary = ({ screenProps }: AmountProps) => {
}) })
} }
}, },
{ { onError: userStorage.markWithErrorEvent }
onTransactionHash: _h => {
txHash = _h
},
onError: () => {
userStorage.markWithErrorEvent(txHash)
},
}
) )
log.debug('generateLinkAndSend:', { generateLinkResponse }) log.debug('generateLinkAndSend:', { generateLinkResponse })
if (generateLinkResponse) { if (generateLinkResponse) {
Expand Down
9 changes: 6 additions & 3 deletions src/components/dashboard/SendQRSummary.js
Expand Up @@ -57,11 +57,9 @@ const SendQRSummary = ({ screenProps }: AmountProps) => {
const sendGD = () => { const sendGD = () => {
try { try {
setLoading(true) setLoading(true)
let txhash
goodWallet.sendAmount(to, amount, { goodWallet.sendAmount(to, amount, {
onTransactionHash: hash => { onTransactionHash: hash => {
log.debug({ hash }) log.debug({ hash })
txhash = hash


// Save transaction // Save transaction
const transactionEvent: TransactionEvent = { const transactionEvent: TransactionEvent = {
Expand Down Expand Up @@ -94,7 +92,12 @@ const SendQRSummary = ({ screenProps }: AmountProps) => {
}, },
onError: e => { onError: e => {
log.error('Send TX failed:', e.message, e) log.error('Send TX failed:', e.message, e)
userStorage.markWithErrorEvent(txhash) showDialog({
visible: true,
title: 'Transaction Failed!',
message: `There was a problem sending G$. Try again`,
dismissText: 'OK',
})
}, },
}) })
} catch (e) { } catch (e) {
Expand Down
98 changes: 41 additions & 57 deletions src/lib/gundb/UserStorageClass.js
Expand Up @@ -26,7 +26,6 @@ import { getUserModel, type UserModel } from './UserModel'


const logger = pino.child({ from: 'UserStorage' }) const logger = pino.child({ from: 'UserStorage' })


const EVENT_TYPE_WITHDRAW = 'withdraw'
const EVENT_TYPE_BONUS = 'bonus' const EVENT_TYPE_BONUS = 'bonus'
const EVENT_TYPE_CLAIM = 'claim' const EVENT_TYPE_CLAIM = 'claim'
const EVENT_TYPE_SEND = 'send' const EVENT_TYPE_SEND = 'send'
Expand Down Expand Up @@ -716,15 +715,15 @@ export class UserStorage {
.catch(_ => new Date()) .catch(_ => new Date())


//if we withdrawn the payment link then its canceled //if we withdrawn the payment link then its canceled
const status = const otplStatus =
data.name === CONTRACT_EVENT_TYPE_PAYMENT_CANCEL || data.to === data.from ? 'cancelled' : 'completed' data.name === CONTRACT_EVENT_TYPE_PAYMENT_CANCEL || data.to === data.from ? 'cancelled' : 'completed'
const prevDate = feedEvent.date const prevDate = feedEvent.date
feedEvent.data.from = data.from feedEvent.data.from = data.from
feedEvent.data.to = data.to feedEvent.data.to = data.to
feedEvent.data.otplData = data feedEvent.data.otplData = data
feedEvent.status = status feedEvent.status = feedEvent.data.otplStatus = otplStatus
feedEvent.date = receiptDate.toString() feedEvent.date = receiptDate.toString()
logger.debug('handleOTPLUpdated receiptReceived', { feedEvent, status, receipt, data }) logger.debug('handleOTPLUpdated receiptReceived', { feedEvent, otplStatus, receipt, data })
await this.updateFeedEvent(feedEvent, prevDate) await this.updateFeedEvent(feedEvent, prevDate)
return feedEvent return feedEvent
} catch (e) { } catch (e) {
Expand Down Expand Up @@ -1218,25 +1217,12 @@ export class UserStorage {
return Promise.all( return Promise.all(
eventsIndex eventsIndex
.filter(_ => _.id) .filter(_ => _.id)
.map(async eventIndex => { .map(eventIndex =>
let item = this.feed this.feed
.get('byid') .get('byid')
.get(eventIndex.id) .get(eventIndex.id)
.decrypt() .decrypt()

)
if (item === undefined) {
const receipt = await this.wallet.getReceiptWithLogs(eventIndex.id).catch(e => {
logger.warn('no receipt found for id:', eventIndex.id, e.message, e)
return undefined
})

if (receipt) {
item = await this.handleReceiptUpdated(receipt)
}
}

return item
})
) )
} }


Expand All @@ -1250,17 +1236,16 @@ export class UserStorage {


return Promise.all( return Promise.all(
feed feed
.filter(feedItem => feedItem.data && ['deleted', 'cancelled'].includes(feedItem.status) === false) .filter(
.map(feedItem => { feedItem =>
if (!(feedItem.data && feedItem.data.receiptData)) { feedItem.data && ['deleted', 'cancelled'].includes(feedItem.status || feedItem.otplStatus) === false
return this.getFormatedEventById(feedItem.id) )
} .map(feedItem =>

this.formatEvent(feedItem).catch(e => {
return this.formatEvent(feedItem).catch(e => {
logger.error('getFormattedEvents Failed formatting event:', e.message, e, feedItem) logger.error('getFormattedEvents Failed formatting event:', e.message, e, feedItem)
return {} return {}
}) })
}) )
) )
} }


Expand Down Expand Up @@ -1405,10 +1390,10 @@ export class UserStorage {


try { try {
const { data, type, date, id, status, createdDate } = event const { data, type, date, id, status, createdDate } = event
const { sender, reason, code: withdrawCode, customName, subtitle } = data const { sender, reason, code: withdrawCode, otplStatus, customName, subtitle } = data


const { address, initiator, initiatorType, value, displayName, message } = this._extractData(event) const { address, initiator, initiatorType, value, displayName, message } = this._extractData(event)
const withdrawStatus = this._extractWithdrawStatus(withdrawCode, status) const withdrawStatus = this._extractWithdrawStatus(withdrawCode, otplStatus, status)
const displayType = this._extractDisplayType(type, withdrawStatus, status) const displayType = this._extractDisplayType(type, withdrawStatus, status)
logger.debug('formatEvent:', event.id, { initiatorType, initiator, address }) logger.debug('formatEvent:', event.id, { initiatorType, initiator, address })
const profileNode = this._extractProfileToShow(initiatorType, initiator, address) const profileNode = this._extractProfileToShow(initiatorType, initiator, address)
Expand Down Expand Up @@ -1488,17 +1473,13 @@ export class UserStorage {
return data return data
} }


_extractWithdrawStatus(withdrawCode, status) { _extractWithdrawStatus(withdrawCode, otplStatus = 'pending', status) {
return status === 'error' ? status : withdrawCode ? status : '' return status === 'error' ? status : withdrawCode ? otplStatus : ''
} }


_extractDisplayType(type, withdrawStatus, status) { _extractDisplayType(type, withdrawStatus, status) {
let sufix = '' let sufix = ''


if (type === EVENT_TYPE_WITHDRAW) {
sufix = withdrawStatus
}

if (type === EVENT_TYPE_SEND) { if (type === EVENT_TYPE_SEND) {
sufix = withdrawStatus sufix = withdrawStatus
} }
Expand Down Expand Up @@ -1537,9 +1518,7 @@ export class UserStorage {


return ( return (
(type === EVENT_TYPE_BONUS && favicon) || (type === EVENT_TYPE_BONUS && favicon) ||
(((type === EVENT_TYPE_SEND && withdrawStatus === 'error') || (type === EVENT_TYPE_SEND && withdrawStatus === 'error' && favicon) || //errored send
(type === EVENT_TYPE_WITHDRAW && withdrawStatus === 'error')) &&
favicon) || // errored send/withdraw
(await profileFromGun()) || // extract avatar from profile (await profileFromGun()) || // extract avatar from profile
(type === EVENT_TYPE_CLAIM || address === '0x0000000000000000000000000000000000000000' ? favicon : undefined) (type === EVENT_TYPE_CLAIM || address === '0x0000000000000000000000000000000000000000' ? favicon : undefined)
) )
Expand Down Expand Up @@ -1589,7 +1568,7 @@ export class UserStorage {
.get('queue') .get('queue')
.get(event.id) .get(event.id)
.putAck(event) .putAck(event)
await this.updateFeedEvent(event) this.updateFeedEvent(event)
logger.debug('enqueueTX ok:', { event, putRes }) logger.debug('enqueueTX ok:', { event, putRes })
return true return true
} catch (e) { } catch (e) {
Expand Down Expand Up @@ -1638,9 +1617,7 @@ export class UserStorage {
*/ */
async updateEventStatus(eventId: string, status: string): Promise<FeedEvent> { async updateEventStatus(eventId: string, status: string): Promise<FeedEvent> {
const feedEvent = await this.getFeedItemByTransactionHash(eventId) const feedEvent = await this.getFeedItemByTransactionHash(eventId)

feedEvent.status = status feedEvent.status = status

return this.feed return this.feed
.get('byid') .get('byid')
.get(eventId) .get(eventId)
Expand All @@ -1654,23 +1631,30 @@ export class UserStorage {
} }


/** /**
* Sets the event's status as error * Sets the event's otpl status
* @param {string} txHash * @param {string} eventId
* @returns {Promise<void>} * @param {string} status
* @returns {Promise<FeedEvent>}
*/ */
async markWithErrorEvent(txHash: string): Promise<void> { async updateEventOtplStatus(eventId: string, status: string): Promise<FeedEvent> {
if (txHash === undefined) { const feedEvent = await this.getFeedItemByTransactionHash(eventId)
return feedEvent.status = status
}
const release = await this.feedMutex.lock()


try { if (feedEvent.data) {
await this.updateEventStatus(txHash, 'error') feedEvent.data.otplStatus = status
} catch (e) {
logger.error('Failed to set error status for feed event', e.message, e)
} finally {
release()
} }

return this.updateFeedEvent(feedEvent)
}

/**
* Sets the event's status as error
* @param {*} err
* @returns {Promise<FeedEvent>}
*/
async markWithErrorEvent(err: any): Promise<FeedEvent> {
const error = JSON.parse(`{${err.message.split('{')[1]}`)
await this.updateEventOtplStatus(error.transactionHash, 'error')
} }


/** /**
Expand All @@ -1697,7 +1681,7 @@ export class UserStorage {
* @returns {Promise<FeedEvent>} * @returns {Promise<FeedEvent>}
*/ */
async cancelOTPLEvent(eventId: string): Promise<FeedEvent> { async cancelOTPLEvent(eventId: string): Promise<FeedEvent> {
await this.updateEventStatus(eventId, 'cancelled') await this.updateEventOtplStatus(eventId, 'cancelled')
} }


/** /**
Expand Down
13 changes: 2 additions & 11 deletions src/lib/undux/utils/withdraw.js
Expand Up @@ -23,25 +23,16 @@ type ReceiptType = {
* *
* @param {Store} store - Undux store * @param {Store} store - Undux store
* @param {string} code - code that unlocks the escrowed payment * @param {string} code - code that unlocks the escrowed payment
* @param {string} reason - the reason of payment
* @returns {Promise} Returns the receipt of the transaction * @returns {Promise} Returns the receipt of the transaction
*/ */
export const executeWithdraw = async ( export const executeWithdraw = async (store: Store, code: string, reason: string): Promise<ReceiptType> => {
store: Store,
code: string,
reason: string
): Promise<ReceiptType | { status: boolean }> => {
log.info('executeWithdraw', code, reason) log.info('executeWithdraw', code, reason)
try { try {
const { amount, sender, status } = await goodWallet.getWithdrawDetails(code) const { amount, sender, status } = await goodWallet.getWithdrawDetails(code)
if (status === WITHDRAW_STATUS_PENDING) { if (status === WITHDRAW_STATUS_PENDING) {
let txHash

return new Promise((res, rej) => { return new Promise((res, rej) => {
goodWallet.withdraw(code, { goodWallet.withdraw(code, {
onTransactionHash: transactionHash => { onTransactionHash: transactionHash => {
txHash = transactionHash

const transactionEvent: TransactionEvent = { const transactionEvent: TransactionEvent = {
id: transactionHash, id: transactionHash,
date: new Date().toString(), date: new Date().toString(),
Expand All @@ -57,7 +48,7 @@ export const executeWithdraw = async (
res({ status, transactionHash }) res({ status, transactionHash })
}, },
onError: e => { onError: e => {
userStorage.markWithErrorEvent(txHash) userStorage.markWithErrorEvent(e)
rej(e) rej(e)
}, },
}) })
Expand Down

0 comments on commit 6d1532f

Please sign in to comment.