Skip to content

Commit

Permalink
Merge branch 'develop-iota2.0' into feat/add-syncBalance-poll
Browse files Browse the repository at this point in the history
  • Loading branch information
begonaalvarezd authored Mar 25, 2024
2 parents ab9167c + 1391a49 commit 89c981d
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 51 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,31 @@
ITransactionInfoToCalculateManaCost,
getManaBalance,
getPassiveManaForOutput,
DEFAULT_SECONDS_PER_SLOT,
} from '@core/network'
import { activeProfile } from '@core/profile'
import { implicitAccountCreationRouter } from '@core/router'
import { MILLISECONDS_PER_SECOND, SECONDS_PER_MINUTE, getBestTimeDuration } from '@core/utils'
import { IWalletState, formatTokenAmountBestMatch, selectedWallet, selectedWalletAssets } from '@core/wallet'
import { OutputData } from '@iota/sdk/out/types'
import { Button, FontWeight, KeyValueBox, Text, TextType, TextHint, TextHintVariant, CopyableBox } from '@ui'
import { onDestroy, onMount } from 'svelte'
export let outputId: string | undefined
// TODO: update when mana generation is available
const isLowManaGeneration = false
const LOW_MANA_GENERATION_SECONDS = 10 * SECONDS_PER_MINUTE
let walletAddress: string = ''
const transactionInfo: ITransactionInfoToCalculateManaCost = {}
let hasEnoughMana = false
let isLowManaGeneration = false
$: baseCoin = $selectedWalletAssets?.[$activeProfile?.network?.id]?.baseCoin
$: selectedOutput = getSelectedOutput($selectedWallet, outputId)
let totalAvailableMana: number
$: $selectedWallet, seconds, (totalAvailableMana = getTotalAvailableMana())
$: $selectedWallet, (totalAvailableMana = getTotalAvailableMana()), prepareTransaction(selectedOutput?.outputId)
let formattedSelectedOutputBlance: string
$: selectedOutput,
Expand All @@ -53,14 +56,14 @@
function getTotalAvailableMana(): number {
return (
getManaBalance($selectedWallet?.balances?.mana?.available) +
$selectedWallet?.balances.totalWalletBic -
getImplicitAccountsMana($selectedWallet?.implicitAccountOutputs, [outputId])
($selectedWallet?.balances.totalWalletBic ?? 0) -
getImplicitAccountsMana($selectedWallet?.implicitAccountOutputs, outputId ? [outputId] : [])
)
}
function getImplicitAccountsMana(implicitAccountOutputs: OutputData[], excludeIds: string[] | undefined): number {
function getImplicitAccountsMana(implicitAccountOutputs: OutputData[], excludeIds: string[]): number {
return implicitAccountOutputs?.reduce((acc: number, outputData: OutputData) => {
if (excludeIds && excludeIds.includes(outputData.outputId)) {
if (excludeIds.length > 1 && !excludeIds.includes(outputData.outputId)) {
const totalMana = getPassiveManaForOutput(outputData)
return totalMana ? acc + totalMana : acc
} else {
Expand All @@ -69,28 +72,40 @@
}, 0)
}
// TODO: Replace this with proper time remaining
async function prepareTransaction(outputId: string): Promise<void> {
if (!outputId) return
try {
transactionInfo.preparedTransaction = await $selectedWallet?.prepareImplicitAccountTransition(outputId)
seconds = 0 // If we don't get an error, it's because we can follow on to the next step
} catch (error) {
console.error(error.message)
if (error.message?.includes('slots remaining until enough mana')) {
transactionInfo.preparedTransactionError = error.message
const slotsRemaining = Number(error.message?.split(' ').reverse()[0].replace('`', ''))
seconds = slotsRemaining * DEFAULT_SECONDS_PER_SLOT
isLowManaGeneration = seconds >= LOW_MANA_GENERATION_SECONDS
}
}
}
// ----------------------------------------------------------------
let seconds: number = 10
let countdownInterval: NodeJS.Timeout
let timeRemaining: string
$: timeRemaining = `${seconds}s remaining`
$: timeRemaining = `${getBestTimeDuration(seconds * MILLISECONDS_PER_SECOND)} remaining`
onMount(async () => {
walletAddress = await $selectedWallet?.address()
$selectedWallet
.prepareImplicitAccountTransition(selectedOutput.outputId)
.then((prepareTx) => (transactionInfo.preparedTransaction = prepareTx))
.catch((error) => (transactionInfo.preparedTransactionError = error))
$selectedWallet?.address().then((address) => (walletAddress = address))
await prepareTransaction(selectedOutput.outputId)
if (seconds === 0) onTimeout()
countdownInterval = setInterval(() => {
seconds -= 1
if (seconds <= 0) {
clearInterval(countdownInterval)
onTimeout()
}
}, 1000)
}, MILLISECONDS_PER_SECOND)
})
onDestroy(() => {
Expand All @@ -103,10 +118,10 @@
// ----------------------------------------------------------------
</script>

<step-content class="flex flex-col items-center justify-between h-full pt-20">
<div class="flex flex-col h-full justify-between space-y-8 items-center">
<step-content class={`flex flex-col items-center justify-between h-full ${isLowManaGeneration ? 'pt-8' : 'pt-20'}`}>
<div class="flex flex-col h-full justify-between space-y-4 items-center">
<div class="flex flex-col text-center space-y-4 max-w-md">
<div class="flex items-center justify-center mb-7">
<div class={`flex items-center justify-center ${isLowManaGeneration ? 'mb-2' : 'mb-7'}`}>
<img
src="assets/illustrations/implicit-account-creation/step2.svg"
alt={localize('views.implicit-account-creation.steps.step2.title')}
Expand Down Expand Up @@ -140,7 +155,7 @@
</div>
</div>
{#if isLowManaGeneration}
<div class="flex flex-col space-y-4 w-2/3">
<div class="flex flex-col space-y-2 w-2/3">
<TextHint
variant={TextHintVariant.Warning}
text={localize('views.implicit-account-creation.steps.step2.view.walletAddress.description')}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
activity.direction === ActivityDirection.SelfTransaction
? localize('general.internalTransaction')
: localize(isIncoming ? 'general.fromAddress' : 'general.toAddress', {
values: { account: getSubjectLocaleFromActivity(activity) },
values: { address: getSubjectLocaleFromActivity(activity) },
})
$: amount = getFormattedAmountFromActivity(activity)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { IWalletState } from '@core/wallet/interfaces'

import { setOutgoingAsyncActivitiesToClaimed } from '../setOutgoingAsyncActivitiesToClaimed'
import { preprocessTransactionsForWallet } from './preprocessTransactionsForWallet'
import { preprocessOutputsForWallet } from './preprocessOutputsForWallet'
import { linkTransactionsWithClaimingTransactions } from './linkTransactionsWithClaimingTransactions'
import { hideActivitiesForFoundries } from './hideActivitiesForFoundries'
import { generateActivitiesFromProcessedTransactions } from './generateActivitiesFromProcessedTransactions'
Expand All @@ -13,7 +12,7 @@ export async function generateAndStoreActivitiesForWallet(wallet: IWalletState):
// Step 1: process wallet transactions and outputs into processed transactions
const processedTransactions = [
...(await preprocessTransactionsForWallet(wallet)),
...(await preprocessOutputsForWallet(wallet)),
// ...(await preprocessOutputsForWallet(wallet)),
]

// Step 2: link transactions with corresponding claiming transactions
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,21 @@
import { CommonOutput, OutputData, OutputResponse, UTXOInput } from '@iota/sdk/out/types'
import { CommonOutput, OutputData, OutputWithMetadata, UTXOInput } from '@iota/sdk/out/types'
import { IWalletState } from '@core/wallet/interfaces'
import { InclusionState, ActivityDirection } from '../../enums'
import { IProcessedTransaction, IWrappedOutput } from '../../interfaces'
import { getRecipientAddressFromOutput } from './getRecipientAddressFromOutput'
import { getSenderAddressFromInputs } from '../transactions'
import { getOutputIdFromTransactionIdAndIndex } from './getOutputIdFromTransactionIdAndIndex'
import { getUnixTimestampFromNodeInfoAndSlotIndex, nodeInfoProtocolParameters } from '@core/network'
import { get } from 'svelte/store'
import { MILLISECONDS_PER_SECOND } from '@core/utils'

// TODO(2.0) Fix all usages
export function preprocessGroupedOutputs(
outputDatas: OutputData[],
transactionInputs: OutputResponse[],
transactionInputs: OutputWithMetadata[],
wallet: IWalletState
): IProcessedTransaction {
const transactionMetadata = outputDatas[0]?.metadata
const wrappedInputs = convertTransactionOutputResponsesToWrappedOutputs(
transactionMetadata?.included.transactionId,
transactionInputs
)
const wrappedInputs = convertTransactionOutputResponsesToWrappedOutputs(transactionInputs)
const utxoInputs = getUtxoInputsFromWrappedInputs(wrappedInputs)
const direction = getDirectionForOutputs(outputDatas, wrappedInputs, wallet.depositAddress)
const wrappedOutputs = outputDatas.map((outputData) => ({
Expand Down Expand Up @@ -75,25 +71,18 @@ function getDirectionForOutputs(
}
}

function convertTransactionOutputResponsesToWrappedOutputs(
transactionId: string,
outputResponses: OutputResponse[]
): IWrappedOutput[] {
return outputResponses.map((outputResponse) =>
convertTransactionOutputResponseToWrappedOutput(transactionId, outputResponse)
)
function convertTransactionOutputResponsesToWrappedOutputs(outputResponses: OutputWithMetadata[]): IWrappedOutput[] {
return outputResponses.map((outputResponse) => convertTransactionOutputResponseToWrappedOutput(outputResponse))
}

function convertTransactionOutputResponseToWrappedOutput(
transactionId: string,
outputResponse: OutputResponse
): IWrappedOutput {
const outputId = getOutputIdFromTransactionIdAndIndex(transactionId, outputResponse.metadata.outputIndex)
return { outputId, output: outputResponse.output, metadata: outputResponse.metadata }
function convertTransactionOutputResponseToWrappedOutput(outputResponse: OutputWithMetadata): IWrappedOutput {
return {
outputId: outputResponse.metadata.outputId,
output: outputResponse.output,
metadata: outputResponse.metadata,
}
}

function getUtxoInputsFromWrappedInputs(wrappedInputs: IWrappedOutput[]): UTXOInput[] {
return (
wrappedInputs?.map((input) => new UTXOInput(input.metadata?.transactionId, input.metadata?.outputIndex)) ?? []
)
return wrappedInputs?.map((input) => UTXOInput.fromOutputId(input.outputId)) ?? []
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ export async function preprocessOutgoingTransaction(
const outputs = convertTransactionsOutputTypesToWrappedOutputs(transactionId, regularTransactionEssence.outputs)

const direction = getDirectionFromOutgoingTransaction(outputs, wallet.depositAddress)
const utxoInputs = regularTransactionEssence.inputs.map((i) => i as UTXOInput)
const inputIds = await Promise.all(
utxoInputs.map((input) => {
const transactionId = input.transactionId
const transactionOutputIndex = input.transactionOutputIndex
regularTransactionEssence.inputs.map((input) => {
const _input = input as UTXOInput
const transactionId = _input.transactionId
const transactionOutputIndex = _input.transactionOutputIndex
return computeOutputId(transactionId, transactionOutputIndex)
})
)
Expand All @@ -33,7 +33,6 @@ export async function preprocessOutgoingTransaction(
time: new Date(Number(transaction.timestamp)),
inclusionState: transaction.inclusionState,
wrappedInputs: <IWrappedOutput[]>inputs,
utxoInputs,
}
}

Expand Down

0 comments on commit 89c981d

Please sign in to comment.