All files / src/storage/methods listActions.ts

97.61% Statements 82/84
77.77% Branches 63/81
100% Functions 11/11
97.53% Lines 79/81

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 17450x   50x     50x             11x 11x   11x   11x         11x 11x 10x               10x 12x     11x 11x     11x       11x 11x   11x   11x 10x 80x               70x     10x 10x 10x 1x   9x 10x 10x 10x 10x     11x 1x 1x 1x     11x       11x   11x   11x 2x   9x 9x     11x 91x                 91x     11x   90x       90x 90x 78x   90x 20x 20x 20x 30x 30x     100x         30x 15x 30x     90x 30x 30x 30x 6x 6x 6x 6x   6x 6x 6x 6x     6x           6x 6x 2x   6x 2x                 11x    
import { Transaction as BsvTransaction, ActionStatus, ListActionsResult, WalletAction, WalletActionOutput, WalletActionInput } from "@bsv/sdk"
import { table } from "../index.client"
import { asString, sdk, verifyOne } from "../../index.client"
import { StorageKnex } from "../StorageKnex"
 
export async function listActions(
    storage: StorageKnex,
    auth: sdk.AuthId,
    vargs: sdk.ValidListActionsArgs
)
: Promise<ListActionsResult>
{
    const limit = vargs.limit
    const offset = vargs.offset
 
    const k = storage.toDb(undefined)
 
    const r: ListActionsResult = {
        totalActions: 0,
        actions: []
    }
 
    let labelIds: number[] = []
    if (vargs.labels.length > 0) {
        const q = k<table.TxLabel>('tx_labels')
            .where({
                'userId': auth.userId,
                'isDeleted': false
            })
            .whereNotNull('txLabelId')
            .whereIn('label', vargs.labels)
            .select('txLabelId')
        const r = await q
        labelIds = r.map(r => r.txLabelId!)
    }
 
    const isQueryModeAll = vargs.labelQueryMode === 'all'
    Iif (isQueryModeAll && labelIds.length < vargs.labels.length)
        return r
 
    Iif (isQueryModeAll && labelIds.length < vargs.labels.length)
        // No actions will match if a required label doesn't exist yet...
        return r
 
    const columns: string[] = ['transactionId', 'txid', 'satoshis', 'status', 'isOutgoing', 'description', 'version', 'lockTime']
    const stati: string[] = ['completed', 'unprocessed', 'sending', 'unproven', 'unsigned', 'nosend', 'nonfinal']
 
    const noLabels = labelIds.length === 0
 
    const makeWithLabelsQueries = () => {
        const cteq = k.raw(`
            SELECT ${columns.map(c => 't.' + c).join(',')}, 
                    (SELECT COUNT(*) 
                    FROM tx_labels_map AS m 
                    WHERE m.transactionId = t.transactionId 
                    AND m.txLabelId IN (${labelIds.join(',')}) 
                    ) AS lc
            FROM transactions AS t
            WHERE t.userId = ${auth.userId}
            AND t.status in (${stati.map(s => `'${s}'`).join(',')})
            `);
 
        const q = k.with('tlc', cteq)
        q.from('tlc')
        if (isQueryModeAll)
            q.where('lc', labelIds.length)
        else
            q.where('lc', '>', 0)
        const qcount = q.clone()
        q.select(columns)
        qcount.count('transactionId as total')
        return { q, qcount }
    }
 
    const makeWithoutLabelsQueries = () => {
        const q = k('transactions').where('userId', auth.userId).whereIn('status', stati)
        const qcount = q.clone().count('transactionId as total')
        return { q, qcount }
    }
 
    const { q, qcount } = noLabels
        ? makeWithoutLabelsQueries()
        : makeWithLabelsQueries()
 
    q.limit(limit).offset(offset).orderBy('transactionId', 'asc')
 
    const txs: Partial<table.Transaction>[] = await q
 
    if (!limit || txs.length < limit)
        r.totalActions = txs.length
    else {
        const total = verifyOne(await qcount)['total']
        r.totalActions = Number(total)
    }
 
    for (const tx of txs) {
        const wtx: WalletAction = {
            txid: tx.txid || '',
            satoshis: tx.satoshis || 0,
            status: <ActionStatus>tx.status!,
            isOutgoing: !!tx.isOutgoing,
            description: tx.description || '',
            version: tx.version || 0,
            lockTime: tx.lockTime || 0
        }
        r.actions.push(wtx)
    }
 
    if (vargs.includeLabels || vargs.includeInputs || vargs.includeOutputs) {
 
        await Promise.all(txs.map(async (tx, i) => {
        //let i = -1
        //for (const tx of txs) {
        //    i++
            const action = r.actions[i]
            if (vargs.includeLabels) {
                action.labels = (await storage.getLabelsForTransactionId(tx.transactionId)).map(l => l.label)
            }
            if (vargs.includeOutputs) {
                const outputs: table.OutputX[] = await storage.findOutputs({ partial: { transactionId: tx.transactionId }, noScript: !vargs.includeOutputLockingScripts })
                action.outputs = []
                for (const o of outputs) {
                    await storage.extendOutput(o, true, true)
                    const wo: WalletActionOutput = {
                        satoshis: o.satoshis || 0,
                        spendable: !!o.spendable,
                        tags: o.tags?.map(t => t.tag) || [],
                        outputIndex: Number(o.vout),
                        outputDescription: o.outputDescription || '',
                        basket: o.basket?.name || '',
                    }
                    if (vargs.includeOutputLockingScripts)
                        wo.lockingScript = asString(o.lockingScript || [])
                    action.outputs.push(wo)
                }
            }
            if (vargs.includeInputs) {
                const inputs: table.OutputX[] = await storage.findOutputs({ partial: { spentBy: tx.transactionId }, noScript: !vargs.includeInputSourceLockingScripts })
                action.inputs = []
                if (inputs.length > 0) {
                    const rawTx = await storage.getRawTxOfKnownValidTransaction(tx.txid)
                    let bsvTx: BsvTransaction | undefined = undefined
                    if (rawTx) {
                        bsvTx = BsvTransaction.fromBinary(rawTx)
                    }
                    for (const o of inputs) {
                        await storage.extendOutput(o, true, true)
                        const input = bsvTx?.inputs.find(v =>
                            v.sourceTXID === o.txid
                            && v.sourceOutputIndex === o.vout
                        )
                        const wo: WalletActionInput = {
                            sourceOutpoint: `${o.txid}.${o.vout}`,
                            sourceSatoshis: o.satoshis || 0,
                            inputDescription: o.outputDescription || '',
                            sequenceNumber: input?.sequence || 0
                        }
                        action.inputs.push(wo)
                        if (vargs.includeInputSourceLockingScripts) {
                            wo.sourceLockingScript = asString(o.lockingScript || [])
                        }
                        if (vargs.includeInputUnlockingScripts) {
                            wo.unlockingScript = input?.unlockingScript?.toHex()
                        }
                    }
                }
            }
        //}
        }))
    }
 
    return r
}