Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[C-4285] Add claim all rewards button functionality #8292

Merged
merged 6 commits into from
May 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions packages/common/src/store/pages/audio-rewards/slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,12 @@ const slice = createSlice({
resetAndCancelClaimReward: (state) => {
state.claimState = { status: ClaimStatus.NONE }
},
claimAllChallengeRewards: (
state,
_action: PayloadAction<{ claims: AudioRewardsClaim[] }>
) => {
state.claimState = { status: ClaimStatus.CUMULATIVE_CLAIMING }
},
claimChallengeReward: (
state,
_action: PayloadAction<{
Expand Down Expand Up @@ -235,6 +241,9 @@ const slice = createSlice({
claimChallengeRewardSucceeded: (state) => {
state.claimState = { status: ClaimStatus.SUCCESS }
},
claimAllChallengeRewardsSucceeded: (state) => {
state.claimState = { status: ClaimStatus.CUMULATIVE_SUCCESS }
},
showRewardClaimedToast: (state) => {
state.showRewardClaimedToast = true
},
Expand All @@ -257,10 +266,12 @@ export const {
resetHCaptchaStatus,
updateHCaptchaScore,
claimChallengeReward,
claimAllChallengeRewards,
claimChallengeRewardWaitForRetry,
claimChallengeRewardAlreadyClaimed,
claimChallengeRewardFailed,
claimChallengeRewardSucceeded,
claimAllChallengeRewardsSucceeded,
showRewardClaimedToast,
resetRewardClaimedToast,
updateOptimisticListenStreak,
Expand Down
4 changes: 4 additions & 0 deletions packages/common/src/store/pages/audio-rewards/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ export type ChallengeRewardsModalType = ChallengeRewardID
export type ClaimState =
| { status: ClaimStatus.NONE }
| { status: ClaimStatus.CLAIMING }
| { status: ClaimStatus.CUMULATIVE_CLAIMING }
| { status: ClaimStatus.WAITING_FOR_RETRY }
| { status: ClaimStatus.ALREADY_CLAIMED }
| { status: ClaimStatus.SUCCESS }
| { status: ClaimStatus.CUMULATIVE_SUCCESS }
| { status: ClaimStatus.ERROR; aaoErrorCode: number | undefined }

export type AudioRewardsClaim = {
Expand Down Expand Up @@ -42,8 +44,10 @@ export enum HCaptchaStatus {
export enum ClaimStatus {
NONE = 'none',
CLAIMING = 'claiming',
CUMULATIVE_CLAIMING = 'cumulative claiming',
WAITING_FOR_RETRY = 'waiting for retry',
ALREADY_CLAIMED = 'already claimed',
SUCCESS = 'success',
CUMULATIVE_SUCCESS = 'cumulative success',
ERROR = 'error'
}
Original file line number Diff line number Diff line change
Expand Up @@ -118,15 +118,10 @@ export const ChallengeRewardsDrawerProvider = () => {
claimChallengeReward({
claim: {
challengeId: modalType,
specifiers:
challenge.challenge_type === 'aggregate'
? getClaimableChallengeSpecifiers(
challenge.undisbursedSpecifiers,
undisbursedUserChallenges
)
: [
{ specifier: challenge.specifier, amount: challenge.amount }
],
specifiers: getClaimableChallengeSpecifiers(
challenge.undisbursedSpecifiers,
undisbursedUserChallenges
),
amount: challenge?.claimableAmount ?? 0
},
retryOnFailure: true
Expand Down
Original file line number Diff line number Diff line change
@@ -1,35 +1,32 @@
import { useCallback } from 'react'
import { useCallback, useEffect } from 'react'

import {
formatCooldownChallenges,
useChallengeCooldownSchedule
} from '@audius/common/hooks'
import type { CommonState } from '@audius/common/store'
import {
challengesSelectors,
audioRewardsPageSelectors,
audioRewardsPageActions
ClaimStatus,
audioRewardsPageActions,
audioRewardsPageSelectors
} from '@audius/common/store'
import { getClaimableChallengeSpecifiers } from '@audius/common/utils'
import { ScrollView, View } from 'react-native'
import { useDispatch, useSelector } from 'react-redux'

import { Flex, Text, Button, IconArrowRight } from '@audius/harmony-native'
import { useToast } from 'app/hooks/useToast'
import { makeStyles } from 'app/styles'
import { formatLabel } from 'app/utils/challenges'

import { AppDrawer, useDrawerState } from '../drawer/AppDrawer'
import { SummaryTable } from '../summary-table'

const { getChallengeRewardsModalType, getUndisbursedUserChallenges } =
audioRewardsPageSelectors
const { claimChallengeReward, resetAndCancelClaimReward } =
const { claimAllChallengeRewards, resetAndCancelClaimReward } =
audioRewardsPageActions
const { getOptimisticUserChallenges } = challengesSelectors
const { getClaimStatus } = audioRewardsPageSelectors

const messages = {
// Claim success toast
claimSuccessMessage: 'Reward successfully claimed!',
claimSuccessMessage: 'All rewards successfully claimed!',
pending: (amount) => `${amount} Pending`,
claimAudio: (amount) => `Claim ${amount} $AUDIO`,
done: 'Done'
Expand Down Expand Up @@ -60,43 +57,36 @@ export const ClaimAllRewardsDrawer = () => {
const styles = useStyles()

const dispatch = useDispatch()
const { toast } = useToast()
const claimStatus = useSelector(getClaimStatus)
const { onClose } = useDrawerState(MODAL_NAME)
const modalType = useSelector(getChallengeRewardsModalType)
const userChallenges = useSelector((state: CommonState) =>
getOptimisticUserChallenges(state, true)
)
const undisbursedUserChallenges = useSelector(getUndisbursedUserChallenges)
const { cooldownChallenges, summary } = useChallengeCooldownSchedule({
multiple: true
})
const { claimableChallenges, cooldownChallenges, summary } =
useChallengeCooldownSchedule({
multiple: true
})
const claimInProgress = claimStatus === ClaimStatus.CUMULATIVE_CLAIMING

useEffect(() => {
if (claimStatus === ClaimStatus.CUMULATIVE_SUCCESS) {
toast({ content: messages.claimSuccessMessage, type: 'info' })
}
}, [claimStatus, toast])

const handleClose = useCallback(() => {
dispatch(resetAndCancelClaimReward())
onClose()
}, [dispatch, onClose])

const challenge = userChallenges ? userChallenges[modalType] : null

const onClaim = useCallback(() => {
if (!challenge) {
return
}
dispatch(
claimChallengeReward({
claim: {
challengeId: modalType,
specifiers:
challenge.challenge_type === 'aggregate'
? getClaimableChallengeSpecifiers(
challenge.undisbursedSpecifiers,
undisbursedUserChallenges
)
: [{ specifier: challenge.specifier, amount: challenge.amount }],
amount: challenge?.claimableAmount ?? 0
},
retryOnFailure: true
})
)
}, [dispatch, modalType, challenge, undisbursedUserChallenges])
const claims = claimableChallenges.map((challenge) => ({
challengeId: challenge.challenge_id,
specifiers: [
{ specifier: challenge.specifier, amount: challenge.amount }
],
amount: challenge.amount
}))
dispatch(claimAllChallengeRewards({ claims }))
}, [dispatch, claimableChallenges])

return (
<AppDrawer
Expand Down Expand Up @@ -126,6 +116,7 @@ export const ClaimAllRewardsDrawer = () => {
<View style={styles.stickyClaimRewardsContainer}>
{summary && summary?.value > 0 ? (
<Button
isLoading={claimInProgress}
variant='primary'
onPress={onClaim}
iconRight={IconArrowRight}
Expand Down
121 changes: 88 additions & 33 deletions packages/web/src/common/store/pages/audio-rewards/sagas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import {
UserChallenge,
StringAudio,
ChallengeRewardID,
StringWei
StringWei,
SpecifierWithAmount
} from '@audius/common/models'
import {
IntKeys,
Expand Down Expand Up @@ -32,7 +33,7 @@ import {
waitForValue
} from '@audius/common/utils'
import { AUDIO } from '@audius/fixed-decimal'
import { ChallengeId } from '@audius/sdk'
import { AudiusSdk, ChallengeId } from '@audius/sdk'
import {
call,
fork,
Expand Down Expand Up @@ -68,8 +69,10 @@ const {
const {
resetAndCancelClaimReward,
claimChallengeReward,
claimAllChallengeRewards,
claimChallengeRewardFailed,
claimChallengeRewardSucceeded,
claimAllChallengeRewardsSucceeded,
claimChallengeRewardWaitForRetry,
fetchUserChallenges,
fetchUserChallengesFailed,
Expand Down Expand Up @@ -220,13 +223,46 @@ function* waitForOptimisticChallengeToComplete({
}
}

type ErrorResult = {
type ErrorResult = SpecifierWithAmount & {
error: unknown
specifier: string
amount: number
}

function* claimChallengeRewardAsync(
async function claimRewardsForChallenge({
sdk,
userId,
challengeId,
specifiers
}: {
sdk: AudiusSdk
userId: string
challengeId: ChallengeId
specifiers: SpecifierWithAmount[]
}): Promise<(SpecifierWithAmount | ErrorResult)[]> {
return await Promise.all(
specifiers.map(async (specifierWithAmount) =>
sdk.challenges
.claimReward({
challengeId,
specifier: specifierWithAmount.specifier,
amount: specifierWithAmount.amount,
userId
})
.then(() => {
return specifierWithAmount
})
// Handle the individual specifier failures here to let the other
// ones continue to claim and not reject the all() call.
.catch((error: unknown) => {
return {
...specifierWithAmount,
error
}
})
)
)
}

function* claimSingleChallengeRewardAsync(
action: ReturnType<typeof claimChallengeReward>
) {
const remoteConfigInstance = yield* getContext('remoteConfigInstance')
Expand Down Expand Up @@ -255,30 +291,12 @@ function* claimChallengeRewardAsync(
const userId = encodeHashId(decodedUserId)

try {
const results = yield* all(
specifiers.map((specifierWithAmount) =>
call(async () => {
return await sdk.challenges
.claimReward({
challengeId: challengeId as ChallengeId,
specifier: specifierWithAmount.specifier,
amount: specifierWithAmount.amount,
userId
})
.then(() => {
return specifierWithAmount
})
// Handle the individual specifier failures here to let the other
// ones continue to claim and not reject the all() call.
.catch((error: unknown) => {
return {
...specifierWithAmount,
error
}
})
})
)
)
const results = yield* call(claimRewardsForChallenge, {
sdk,
userId,
challengeId: challengeId as ChallengeId,
specifiers
})
const claimed = results.filter((r) => !('error' in r))
const claimedAmount = results.reduce((sum, { amount }) => {
return sum + amount
Expand Down Expand Up @@ -311,11 +329,9 @@ function* claimChallengeRewardAsync(
}
throw new Error('Some specifiers failed to claim')
}

yield* put(claimChallengeRewardSucceeded())
} catch (e) {
console.error(e)
yield* put(claimChallengeRewardFailed())
throw new Error('Failed to claim for challenge')
}
}

Expand Down Expand Up @@ -516,6 +532,37 @@ function* claimChallengeRewardAsyncOld(
}
}

function* claimChallengeRewardAsync(
action: ReturnType<typeof claimChallengeReward>
) {
try {
yield* call(claimSingleChallengeRewardAsync, action)
yield* put(claimChallengeRewardSucceeded())
} catch (e) {
yield* put(claimChallengeRewardFailed())
}
}

function* claimAllChallengeRewardsAsync(
action: ReturnType<typeof claimAllChallengeRewards>
) {
const { claims } = action.payload
try {
yield* all(
claims.map((claim) =>
call(claimSingleChallengeRewardAsync, {
type: claimChallengeReward.type,
payload: { claim, retryOnFailure: false }
})
)
)
yield* put(claimAllChallengeRewardsSucceeded())
} catch (e) {
console.error(e)
yield* put(claimChallengeRewardFailed())
}
}

function* watchSetHCaptchaStatus() {
yield* takeLatest(
setHCaptchaStatus.type,
Expand Down Expand Up @@ -555,6 +602,13 @@ function* watchClaimChallengeReward() {
)
}

function* watchClaimAllChallengeRewards() {
yield* takeLatest(
claimAllChallengeRewards.type,
claimAllChallengeRewardsAsync
)
}

function* fetchUserChallengesAsync() {
yield* call(waitForRead)
const apiClient = yield* getContext('apiClient')
Expand Down Expand Up @@ -759,6 +813,7 @@ const sagas = () => {
watchFetchUserChallenges,
watchFetchUserChallengesSucceeded,
watchClaimChallengeReward,
watchClaimAllChallengeRewards,
watchSetHCaptchaStatus,
watchUpdateHCaptchaScore,
userChallengePollingDaemon,
Expand Down
Loading