Skip to content

Commit

Permalink
feat: start and stop voting activity (#5602)
Browse files Browse the repository at this point in the history
* feat: add governance activity types

Co-authored-by: MarkNerdi <MarkNerdi@users.noreply.github.com>

* chore: remove inputs on activity

* feat: generate + display governance activities

* feat-mobile: prepare network configuration settings router & init view (#5525)

* feat-mobile: kickoff node config settings

* feat-mobile: prepare network configuration settings router & move settings files around

* fix: function typo

* refactor: clean settings meta constant

* emtpy commit to trigger the checks

Co-authored-by: Paul Bögelsack <pboegelsack@googlemail.com>

* fix: swap logic order (#5545)

Co-authored-by: Jean Ribeiro <iamjeanribeiro@gmail.com>

* Update crowdin.yml (#5550)

* chore: update files after branch rename (#5551)

* chore: make changes for some files

* chore: update PR template

* chore: add main branches to Snyk CI

* chore: update documentation (#5552)

* chore: update documentation

* empty

Co-authored-by: Matthew Maxwell <44885822+maxwellmattryan@users.noreply.github.com>
Co-authored-by: Matthew Maxwell <maxwellmattryan@gmail.com>

* chore: update `wallet.rs` version (#5555)

* chore: update `wallet.rs` version

* chore: remove comment

* chore: cleanup imports

* chore: fix tests

* chore: polish governance UI/UX (#5532)

* fix: proposals grid spacing

* enhancement: adds sorting to proposals

* chore: wrap register proposal in a form element

* chore: wrap vote for proposal in a form element

* enhancement: adds only value UI to SelectorInput

* feat: adds NodeInput component

* enhancement: adds NodeInput in RegisterProposalPopup

* feat: adds disabled state to SliderInput

* fix: adds dark mode styling

* chore: debounce buttons and add spinners in register proposal and node auth popups

* fix: only show text hint in remove proposal popup if event status is commencing or holding

* fix: disabled voting options when event is in upcoming or ended phase

* fix: adds reactivity to counted votes

* enhancement: adds reactivity to ProposalDetailsMenu

* Merge branch 'stardust-develop' of github.com:iotaledger/firefly into chore/polish-governance-ui-ux

* refactor: SliderInput code style

* fix: apply suggestions

* fix: adds missing semicolon in css

* fix: missing display block

Co-authored-by: Tuditi <45079109+Tuditi@users.noreply.github.com>

* refactor: minimize `getParticipationOverview` calls (#5533)

* fix: use store instead of calling function always

* chore: fix linting error

* fix: reactive changes to votes counted

* fix: update participation overview onMount

* refactor: improves code

* fix: make changes per PR comments

* fix: show 0 value proposals details

Co-authored-by: Jean Ribeiro <iamjeanribeiro@gmail.com>
Co-authored-by: Jean Ribeiro <contact@jeanribeiro.dev>
Co-authored-by: Tuditi <45079109+Tuditi@users.noreply.github.com>
Co-authored-by: Tuditi <daviddetroch@pm.me>

* feat-mobile: view node information (#5527)

* feat-mobile: kickoff node config settings

* feat-mobile: prepare network configuration settings router & move settings files around

* fix: function typo

* wip: kickoff node info details

* feat-mobile: add node info view

* fix: add missing prop

* style: polish UI

Co-authored-by: Paul Bögelsack <pboegelsack@googlemail.com>

* enhancement: governance activity tile

* enhancmenet: governance activity details popup

* feat: show current vote (#5557)

* feat: select current vote

* fix: correct background color for selected vote

* fix: blue border if selected

* refactor: consistent event handling

* fix: rerender answer if necessary

* change "clicked" to "click"

* fix: pr review

* fix: improve error handling

* fix: correct event name

* feat: disable event handler if question is answer is hidden

* fix: add optional chaining to toString

Co-authored-by: Jean Ribeiro <contact@jeanribeiro.dev>

* fix: add check for reserved tag keywords (#5567)

Co-authored-by: Jean Ribeiro <iamjeanribeiro@gmail.com>

* feat: pinging badge active vote (#5568)

* chore: adds prop classes to PingingBadge and remove positioning classes from it

* feat: adds PingingBadge component to ProposalAnswer

* chore: remove .ring css selector

Co-authored-by: Tuditi <daviddetroch@pm.me>

* chore: upgrade `postcss-url` dep (#5553)

Co-authored-by: Tuditi <45079109+Tuditi@users.noreply.github.com>

* chore: remove acceptance criteria (#5565)

Co-authored-by: Tuditi <45079109+Tuditi@users.noreply.github.com>

* chore: update translations

* enhancement: PR reviews

* fix: fix initial voting power increase

* fix: submit only once (#5563)

* fix: submit only once

* refactor: use correct type

* fix: two-way binding of values for repeated errors

Co-authored-by: paul-boegelsack <paul.boegelsack@iota.org>

* feat: feature flag platform method (#5560)

* feat: adds "isFeatureFlagEnabled" method in platforms

* feat: adds example

* chore: add method to mock

* fix: format electronApi

* fix: format capacitorApi

* fix: adds brackets wrapping the method code

* chore: adds missing types

* fix: removes arrow from function

* fix

* fix: add fetch to default module property

Co-authored-by: Matthew Maxwell <44885822+maxwellmattryan@users.noreply.github.com>
Co-authored-by: Matthew Maxwell <maxwellmattryan@gmail.com>

* fix: removes username and password from NodeAuthRequiredPopup (#5570)

* enhancement: burn nft activity (#5526)

* enhancement: calculate if output is burning output

* enhancement: fix burn activity

* enhancement: remove already classified nft

* chore: improve code quality

* chore: improve code

* fix: burned nfts dont show up in gallery

* chore: rename parameter

* chore: rename generator functions

* enhancement: fix not loaded nfts on account restore + improve performance

Co-authored-by: Nicole O'Brien <nicole.obrien@iota.org>

* enhancement: update ui

* revert: revert capacitor api

* fix: fix import

* fix: fix random typescript bug

* ui: fix alignment

* enhancement: parse governance metadata

* enhancement: add start/stop voting activity tile

* fix: fix eventId encoding

* enhancement: governent activity details popup

* enhancement: add proposal name to details popup

* fix: fix start/stop voting

Co-authored-by: Tuditi <Tuditi@users.noreply.github.com>

* refactro: extract helper functions to own file

Co-authored-by: Tuditi <Tuditi@users.noreply.github.com>

* feat: voting power activities (#5547)

* feat: add governance activity types

Co-authored-by: MarkNerdi <MarkNerdi@users.noreply.github.com>

* chore: remove inputs on activity

* feat: generate + display governance activities

* feat-mobile: prepare network configuration settings router & init view (#5525)

* feat-mobile: kickoff node config settings

* feat-mobile: prepare network configuration settings router & move settings files around

* fix: function typo

* refactor: clean settings meta constant

* emtpy commit to trigger the checks

Co-authored-by: Paul Bögelsack <pboegelsack@googlemail.com>

* fix: swap logic order (#5545)

Co-authored-by: Jean Ribeiro <iamjeanribeiro@gmail.com>

* Update crowdin.yml (#5550)

* chore: update files after branch rename (#5551)

* chore: make changes for some files

* chore: update PR template

* chore: add main branches to Snyk CI

* chore: update documentation (#5552)

* chore: update documentation

* empty

Co-authored-by: Matthew Maxwell <44885822+maxwellmattryan@users.noreply.github.com>
Co-authored-by: Matthew Maxwell <maxwellmattryan@gmail.com>

* chore: update `wallet.rs` version (#5555)

* chore: update `wallet.rs` version

* chore: remove comment

* chore: cleanup imports

* chore: fix tests

* chore: polish governance UI/UX (#5532)

* fix: proposals grid spacing

* enhancement: adds sorting to proposals

* chore: wrap register proposal in a form element

* chore: wrap vote for proposal in a form element

* enhancement: adds only value UI to SelectorInput

* feat: adds NodeInput component

* enhancement: adds NodeInput in RegisterProposalPopup

* feat: adds disabled state to SliderInput

* fix: adds dark mode styling

* chore: debounce buttons and add spinners in register proposal and node auth popups

* fix: only show text hint in remove proposal popup if event status is commencing or holding

* fix: disabled voting options when event is in upcoming or ended phase

* fix: adds reactivity to counted votes

* enhancement: adds reactivity to ProposalDetailsMenu

* Merge branch 'stardust-develop' of github.com:iotaledger/firefly into chore/polish-governance-ui-ux

* refactor: SliderInput code style

* fix: apply suggestions

* fix: adds missing semicolon in css

* fix: missing display block

Co-authored-by: Tuditi <45079109+Tuditi@users.noreply.github.com>

* refactor: minimize `getParticipationOverview` calls (#5533)

* fix: use store instead of calling function always

* chore: fix linting error

* fix: reactive changes to votes counted

* fix: update participation overview onMount

* refactor: improves code

* fix: make changes per PR comments

* fix: show 0 value proposals details

Co-authored-by: Jean Ribeiro <iamjeanribeiro@gmail.com>
Co-authored-by: Jean Ribeiro <contact@jeanribeiro.dev>
Co-authored-by: Tuditi <45079109+Tuditi@users.noreply.github.com>
Co-authored-by: Tuditi <daviddetroch@pm.me>

* feat-mobile: view node information (#5527)

* feat-mobile: kickoff node config settings

* feat-mobile: prepare network configuration settings router & move settings files around

* fix: function typo

* wip: kickoff node info details

* feat-mobile: add node info view

* fix: add missing prop

* style: polish UI

Co-authored-by: Paul Bögelsack <pboegelsack@googlemail.com>

* enhancement: governance activity tile

* enhancmenet: governance activity details popup

* feat: show current vote (#5557)

* feat: select current vote

* fix: correct background color for selected vote

* fix: blue border if selected

* refactor: consistent event handling

* fix: rerender answer if necessary

* change "clicked" to "click"

* fix: pr review

* fix: improve error handling

* fix: correct event name

* feat: disable event handler if question is answer is hidden

* fix: add optional chaining to toString

Co-authored-by: Jean Ribeiro <contact@jeanribeiro.dev>

* fix: add check for reserved tag keywords (#5567)

Co-authored-by: Jean Ribeiro <iamjeanribeiro@gmail.com>

* feat: pinging badge active vote (#5568)

* chore: adds prop classes to PingingBadge and remove positioning classes from it

* feat: adds PingingBadge component to ProposalAnswer

* chore: remove .ring css selector

Co-authored-by: Tuditi <daviddetroch@pm.me>

* chore: upgrade `postcss-url` dep (#5553)

Co-authored-by: Tuditi <45079109+Tuditi@users.noreply.github.com>

* chore: remove acceptance criteria (#5565)

Co-authored-by: Tuditi <45079109+Tuditi@users.noreply.github.com>

* chore: update translations

* enhancement: PR reviews

* fix: fix initial voting power increase

* fix: submit only once (#5563)

* fix: submit only once

* refactor: use correct type

* fix: two-way binding of values for repeated errors

Co-authored-by: paul-boegelsack <paul.boegelsack@iota.org>

* feat: feature flag platform method (#5560)

* feat: adds "isFeatureFlagEnabled" method in platforms

* feat: adds example

* chore: add method to mock

* fix: format electronApi

* fix: format capacitorApi

* fix: adds brackets wrapping the method code

* chore: adds missing types

* fix: removes arrow from function

* fix

* fix: add fetch to default module property

Co-authored-by: Matthew Maxwell <44885822+maxwellmattryan@users.noreply.github.com>
Co-authored-by: Matthew Maxwell <maxwellmattryan@gmail.com>

* fix: removes username and password from NodeAuthRequiredPopup (#5570)

* enhancement: burn nft activity (#5526)

* enhancement: calculate if output is burning output

* enhancement: fix burn activity

* enhancement: remove already classified nft

* chore: improve code quality

* chore: improve code

* fix: burned nfts dont show up in gallery

* chore: rename parameter

* chore: rename generator functions

* enhancement: fix not loaded nfts on account restore + improve performance

Co-authored-by: Nicole O'Brien <nicole.obrien@iota.org>

* enhancement: update ui

* revert: revert capacitor api

* fix: fix import

* fix: fix random typescript bug

* ui: fix alignment

Co-authored-by: MarkNerdi <MarkNerdi@users.noreply.github.com>
Co-authored-by: Mark Nardi <mark.nardi@iota.org>
Co-authored-by: Begoña Álvarez de la Cruz <balvarez@boxfish.studio>
Co-authored-by: Paul Bögelsack <pboegelsack@googlemail.com>
Co-authored-by: Matthew Maxwell <44885822+maxwellmattryan@users.noreply.github.com>
Co-authored-by: Jean Ribeiro <iamjeanribeiro@gmail.com>
Co-authored-by: Nicole O'Brien <nicole.obrien@iota.org>
Co-authored-by: Matthew Maxwell <maxwellmattryan@gmail.com>
Co-authored-by: Jean Ribeiro <contact@jeanribeiro.dev>
Co-authored-by: paul-boegelsack <paul.boegelsack@iota.org>
Co-authored-by: MarkNerdi <105642810+MarkNerdi@users.noreply.github.com>

* chore: remove duplicated import

* enhancement: add activity after start/stop voting

* enhancement: truncat proposalname

* fix: fix loading state

Co-authored-by: Tuditi <daviddetroch@pm.me>
Co-authored-by: MarkNerdi <MarkNerdi@users.noreply.github.com>
Co-authored-by: Begoña Álvarez de la Cruz <balvarez@boxfish.studio>
Co-authored-by: Paul Bögelsack <pboegelsack@googlemail.com>
Co-authored-by: Matthew Maxwell <44885822+maxwellmattryan@users.noreply.github.com>
Co-authored-by: Jean Ribeiro <iamjeanribeiro@gmail.com>
Co-authored-by: Nicole O'Brien <nicole.obrien@iota.org>
Co-authored-by: Tuditi <45079109+Tuditi@users.noreply.github.com>
Co-authored-by: Matthew Maxwell <maxwellmattryan@gmail.com>
Co-authored-by: Jean Ribeiro <contact@jeanribeiro.dev>
Co-authored-by: paul-boegelsack <paul.boegelsack@iota.org>
Co-authored-by: Tuditi <Tuditi@users.noreply.github.com>
  • Loading branch information
13 people committed Jan 18, 2023
1 parent 929afe2 commit be59a66
Show file tree
Hide file tree
Showing 17 changed files with 223 additions and 51 deletions.
Expand Up @@ -8,6 +8,7 @@
} from '@core/wallet'
import { Text, Icon, FontWeight } from 'shared/components'
import { Icon as IconEnum } from '@lib/auxiliary/icon'
import { truncateString } from '@core/utils'
export let activity: GovernanceActivity
Expand All @@ -34,7 +35,7 @@
>
{localize(title)}
</Text>
{#if amount}
{#if activity.governanceAction === GovernanceAction.DecreaseVotingPower || activity.governanceAction === GovernanceAction.IncreaseVotingPower}
<Text
fontWeight={FontWeight.semibold}
lineHeight="140"
Expand All @@ -45,4 +46,13 @@
</Text>
{/if}
</div>
{#if activity.participation}
<div class="flex flex-row justify-between">
<Text fontWeight={FontWeight.medium} lineHeight="140" color="gray-600">
{localize('general.forEvent', {
values: { eventId: truncateString(activity.participation.eventId, 6, 6) },
})}
</Text>
</div>
{/if}
</div>
@@ -1,21 +1,36 @@
<script lang="typescript">
import { AmountBox, ActivityInclusionStatusPill } from 'shared/components'
import { AmountBox, ActivityInclusionStatusPill, Text, FontWeight } from 'shared/components'
import { formatTokenAmountDefault, getAssetFromPersistedAssets } from '@core/wallet'
import { GovernanceActivity } from '@core/wallet'
import { BASE_TOKEN, COIN_TYPE } from '@core/network'
import { activeProfile } from '@core/profile'
import { getVotingEvent } from '@core/profile-manager'
import { truncateString } from '@core/utils'
export let activity: GovernanceActivity
let proposalName: string
$: asset = getAssetFromPersistedAssets(String(COIN_TYPE[$activeProfile.networkProtocol]))
$: amount = activity.votingPowerDifference
? formatTokenAmountDefault(
Number(activity.votingPowerDifference),
BASE_TOKEN[$activeProfile.networkProtocol],
asset?.metadata?.unit
)
: 0
: ''
$: localizationKey = 'governance.' + activity.governanceAction
$: activity.participation?.eventId, setProposalName()
async function setProposalName(): Promise<void> {
try {
if (activity?.participation?.eventId) {
proposalName = (await getVotingEvent(activity.participation.eventId)).data.name
}
} catch (err) {
proposalName = truncateString(activity.participation.eventId, 6, 6)
}
}
</script>

<main-content class="flex flex-auto w-full flex-col items-center justify-center space-y-3">
Expand All @@ -25,4 +40,9 @@
<governance-status class="flex flex-row w-full space-x-2 justify-center">
<ActivityInclusionStatusPill {localizationKey} inclusionState={activity.inclusionState} />
</governance-status>
{#if proposalName}
<Text color="gray-800" darkColor="gray-500" fontWeight={FontWeight.semibold} fontSize="text-15">
{proposalName}
</Text>
{/if}
</main-content>
@@ -1,23 +1,32 @@
<script lang="typescript">
import { KeyValueBox } from 'shared/components'
import { getFormattedTimeStamp, localize } from '@core/i18n'
import { getFormattedVotingPowerFromGovernanceActivity, GovernanceActivity } from '@core/wallet'
import { formatTokenAmountBestMatch, GovernanceAction, GovernanceActivity } from '@core/wallet'
import { BASE_TOKEN } from '@core/network'
import { activeProfile } from '@core/profile'
export let activity: GovernanceActivity
$: formattedTransactionTime = getFormattedTimeStamp(activity.time)
let transactionDetailsList: { [key in string]: { data: string } }
let transactionDetailsList: { [key in string]: { data: string; alternateKey?: string } }
$: transactionDetailsList = {
...(activity.time && {
transactionTime: { data: formattedTransactionTime },
}),
...(activity.votingPower && {
votingPower: { data: getFormattedVotingPowerFromGovernanceActivity(activity) },
votingPower: {
data: formatTokenAmountBestMatch(activity.votingPower, BASE_TOKEN[$activeProfile?.networkProtocol], 2),
alternateKey:
activity.governanceAction === GovernanceAction.DecreaseVotingPower ||
activity.governanceAction === GovernanceAction.IncreaseVotingPower
? 'newVotingPower'
: 'votingPower',
},
}),
}
</script>

{#each Object.entries(transactionDetailsList) as [key, value]}
<KeyValueBox keyText={localize(`general.${key}`)} valueText={value.data} />
<KeyValueBox keyText={localize(`general.${value.alternateKey ?? key}`)} valueText={value.data} />
{/each}
23 changes: 20 additions & 3 deletions packages/shared/components/popups/StopVotingPopup.svelte
Expand Up @@ -9,6 +9,13 @@
import { localize } from '@core/i18n'
import { checkActiveProfileAuth } from '@core/profile/actions'
import { selectedAccount, updateSelectedAccount } from '@core/account/stores'
import {
addActivitiesToAccountActivitiesInAllAccountActivities,
generateActivities,
preprocessTransaction,
} from '@core/wallet'
import { activeProfile, ProfileType } from '@core/profile'
import { handleLedgerError } from '@core/ledger'
$: isTransferring = $selectedAccount?.isTransferring
Expand All @@ -20,17 +27,27 @@
try {
await checkActiveProfileAuth(async () => {
updateSelectedAccount({ isTransferring: true })
await stopVotingForProposal($selectedProposal?.id)
const transaction = await stopVotingForProposal($selectedProposal?.id)
const processedTransaction = await preprocessTransaction(transaction, $selectedAccount)
const activities = generateActivities(processedTransaction, $selectedAccount)
addActivitiesToAccountActivitiesInAllAccountActivities($selectedAccount.index, activities)
showAppNotification({
type: 'success',
message: localize('notifications.stopVoting.success'),
alert: true,
})
closePopup()
updateSelectedAccount({ isTransferring: false })
closePopup()
})
} catch (err) {
handleError(err)
if ($activeProfile.type === ProfileType.Ledger) {
handleLedgerError(err)
} else {
handleError(err)
}
updateSelectedAccount({ isTransferring: false })
}
}
Expand Down
22 changes: 17 additions & 5 deletions packages/shared/components/popups/VoteForProposalPopup.svelte
Expand Up @@ -4,11 +4,14 @@
import { selectedAccount, updateSelectedAccount, vote } from '@core/account'
import { localize } from '@core/i18n'
import { BASE_TOKEN } from '@core/network'
import { activeProfile, checkActiveProfileAuth } from '@core/profile'
import { formatTokenAmountBestMatch } from '@core/wallet/utils'
import { activeProfile, checkActiveProfileAuth, ProfileType } from '@core/profile'
import { formatTokenAmountBestMatch, generateActivities, preprocessTransaction } from '@core/wallet/utils'
import { selectedProposal } from '@contexts/governance/stores'
import { showAppNotification } from '@auxiliary/notification'
import { closePopup } from '@auxiliary/popup'
import { addActivitiesToAccountActivitiesInAllAccountActivities } from '@core/wallet'
import { handleError } from '@core/error/handlers'
import { handleLedgerError } from '@core/ledger'
export let selectedAnswerValues: number[]
Expand All @@ -24,17 +27,26 @@
try {
await checkActiveProfileAuth(async () => {
updateSelectedAccount({ isTransferring: true })
await vote($selectedAccount.index, $selectedProposal?.id, selectedAnswerValues)
const transaction = await vote($selectedAccount.index, $selectedProposal?.id, selectedAnswerValues)
const processedTransaction = await preprocessTransaction(transaction, $selectedAccount)
const activities = generateActivities(processedTransaction, $selectedAccount)
addActivitiesToAccountActivitiesInAllAccountActivities($selectedAccount.index, activities)
showAppNotification({
type: 'success',
message: localize('notifications.vote.success'),
alert: true,
})
closePopup()
updateSelectedAccount({ isTransferring: false })
closePopup()
})
} catch (err) {
console.error(err)
if ($activeProfile.type === ProfileType.Ledger) {
handleLedgerError(err)
} else {
handleError(err)
}
updateSelectedAccount({ isTransferring: false })
}
}
Expand Down
@@ -1,4 +1,6 @@
export enum GovernanceAction {
StartVoting = 'startVoting',
StopVoting = 'stopVoting',
IncreaseVotingPower = 'increaseVotingPower',
DecreaseVotingPower = 'decreaseVotingPower',
}
1 change: 1 addition & 0 deletions packages/shared/lib/core/wallet/interfaces/index.ts
Expand Up @@ -9,6 +9,7 @@ export * from './processed-transaction.interface'
export * from './claimed-activities.interface'
export * from './filter/filter.interface'
export * from './filter'
export * from './participation.interface'
export * from './hidden-activities.interface'
export * from './irc30-metadata.interface'
export * from './mint-nft-details.interface'
Expand Down
@@ -0,0 +1,4 @@
export interface IParticipation {
eventId: string
answers: number[]
}
@@ -1,9 +1,11 @@
import { ActivityType, GovernanceAction } from '@core/wallet/enums'
import { IParticipation } from '@core/wallet/interfaces'
import { BaseActivity } from './base-activity.type'

export type GovernanceActivity = BaseActivity & {
type: ActivityType.Governance
governanceAction: GovernanceAction
votingPower: number
participation?: IParticipation
votingPowerDifference?: number
}
Expand Up @@ -8,6 +8,8 @@ import {
OUTPUT_TYPE_NFT,
} from '@core/wallet'
import { Activity } from '@core/wallet/types'
import { isParticipationOutput } from '@contexts/governance/utils'

import { generateSingleAliasActivity } from './generateSingleAliasActivity'
import { generateSingleFoundryActivity } from './generateSingleFoundryActivity'
import { generateSingleGovernanceActivity } from './generateSingleGovernanceActivity'
Expand All @@ -17,8 +19,7 @@ import { getActivityTypeFromOutput } from './helper'
import { generateActivitiesFromNftOutputs } from './generateActivitiesFromNftOutputs'
import { generateActivitiesFromAliasOutputs } from './generateActivitiesFromAliasOutputs'
import { generateActivitiesFromFoundryOutputs } from './generateActivitiesFromFoundryOutputs'
import { isParticipationOutput } from '@contexts/governance/utils'
import { generateActivitiesFromBasicOutputs } from '@core/wallet/utils/generateActivity/generateActivitiesFromBasicOutputs'
import { generateActivitiesFromBasicOutputs } from './generateActivitiesFromBasicOutputs'

export function generateActivities(processedTransaction: IProcessedTransaction, account: IAccountState): Activity[] {
if (processedTransaction.wrappedInputs?.length > 0) {
Expand Down
@@ -1,17 +1,17 @@
import { IAccountState } from '@core/account'
import { IActivityGenerationParameters, IWrappedOutput } from '@core/wallet/interfaces'
import { GovernanceActivity, Output } from '@core/wallet/types'
import { IActivityGenerationParameters } from '@core/wallet/interfaces'
import { GovernanceActivity } from '@core/wallet/types'
import type { IBasicOutput } from '@iota/types'
import { ActivityType, GovernanceAction } from '../../enums'
import { ActivityType } from '../../enums'
import { activityOutputContainsValue } from '..'
import {
getAmountFromOutput,
getGovernanceInfo,
getMetadataFromOutput,
getSendingInformation,
getStorageDepositFromOutput,
getTagFromOutput,
} from './helper'
import { isParticipationOutput } from '@contexts/governance'

export function generateSingleGovernanceActivity(
account: IAccountState,
Expand All @@ -35,7 +35,7 @@ export function generateSingleGovernanceActivity(

const { storageDeposit } = getStorageDepositFromOutput(output)
const votingPower = getAmountFromOutput(output)
const governanceInfo = getGovernanceInfo(output, wrappedInputs)
const governanceInfo = getGovernanceInfo(output, wrappedInputs, metadata)

return {
type: ActivityType.Governance,
Expand All @@ -59,31 +59,3 @@ export function generateSingleGovernanceActivity(
...sendingInfo,
}
}

function getGovernanceInfo(
output: Output,
inputs: IWrappedOutput[]
): {
governanceAction: GovernanceAction
votingPower: number
votingPowerDifference?: number
} {
const currentVotingPower = getAmountFromOutput(output)
const governanceInput = inputs?.find((input) => isParticipationOutput(input.output))
if (governanceInput) {
const oldVotingPower = getAmountFromOutput(governanceInput.output)
return {
governanceAction:
currentVotingPower - oldVotingPower > 0
? GovernanceAction.IncreaseVotingPower
: GovernanceAction.DecreaseVotingPower,
votingPower: currentVotingPower,
votingPowerDifference: Math.abs(currentVotingPower - oldVotingPower),
}
}
return {
governanceAction: GovernanceAction.IncreaseVotingPower,
votingPower: currentVotingPower,
votingPowerDifference: currentVotingPower,
}
}
@@ -0,0 +1,70 @@
import { isParticipationOutput } from '@contexts/governance'
import { GovernanceAction } from '@core/wallet/enums'
import { IParticipation, IWrappedOutput } from '@core/wallet/interfaces'
import { Output } from '@core/wallet/types'
import { parseGovernanceMetadata } from '../../parseGovernanceMetadata'
import { getAmountFromOutput } from './getAmountFromOutput'
import { getMetadataFromOutput } from './getMetadataFromOutput'

interface IGovernanceInfo {
governanceAction: GovernanceAction
votingPower: number
votingPowerDifference?: number
participation?: IParticipation
}

export function getGovernanceInfo(output: Output, inputs: IWrappedOutput[], metadata: string): IGovernanceInfo {
const currentVotingPower = getAmountFromOutput(output)
const participations = parseGovernanceMetadata(metadata)

const governanceInput = inputs?.find((input) => isParticipationOutput(input.output))
if (governanceInput) {
const oldMetadata = getMetadataFromOutput(governanceInput.output)
const oldParticipations = parseGovernanceMetadata(oldMetadata)

const addedParticipation = getParticipationDifference(oldParticipations, participations)
const removedParticipation = getParticipationDifference(participations, oldParticipations)

if (addedParticipation) {
return {
governanceAction: GovernanceAction.StartVoting,
votingPower: currentVotingPower,
participation: addedParticipation,
}
} else if (removedParticipation) {
return {
governanceAction: GovernanceAction.StopVoting,
votingPower: currentVotingPower,
participation: removedParticipation,
}
} else {
const oldVotingPower = getAmountFromOutput(governanceInput.output)
return {
governanceAction:
currentVotingPower - oldVotingPower > 0
? GovernanceAction.IncreaseVotingPower
: GovernanceAction.DecreaseVotingPower,
votingPower: currentVotingPower,
votingPowerDifference: Math.abs(currentVotingPower - oldVotingPower),
}
}
} else {
// There is no governance input when the user first adds voting power
return {
governanceAction: GovernanceAction.IncreaseVotingPower,
votingPower: currentVotingPower,
votingPowerDifference: currentVotingPower,
}
}
}

function getParticipationDifference(
oldParticipations: IParticipation[],
newParticipations: IParticipation[]
): IParticipation {
const participationDifference = newParticipations.find(
(newParticipation) =>
!oldParticipations.some((oldParticipation) => newParticipation.eventId === oldParticipation.eventId)
)
return participationDifference
}

0 comments on commit be59a66

Please sign in to comment.