Balance of cryptowallet

48 Views Asked by At

I am new to learning Dune analytics and wish to query the Ethereum balance of a given wallet (provided by wallet ID).Preferably this could be queried directly but it seems that you need to look through transaction history to calculate the balance. I have attempted to do this using the ethereum.transactions and ethereum.trace datasets on Dune. However, this outputs balances that often negative and clearly not accurate ie -6623. In the code I have posted below, Land is my own dataset with wallet id as a column. Any help with this would be greatly appreciated!


WITH current_holders AS (
    SELECT 
        t."to" AS wallet_id
    FROM 
        land.Transfer t
    INNER JOIN (
        SELECT 
            tokenId, 
            MAX(evt_block_time) AS max_block_time
        FROM 
            Land.Transfer
        GROUP BY 
            tokenId
    ) t_max ON t.tokenId = t_max.tokenId AND t.evt_block_time = t_max.max_block_time
    GROUP BY 
        t."to"
),

eth_credits AS (
    SELECT 
        et."to" AS wallet_id, 
        SUM(et.value) AS credit -- Convert from wei to ETH
    FROM 
        ethereum.transactions et
    WHERE 
        et."to" IN (SELECT wallet_id FROM current_holders)
    GROUP BY 
        et."to"
),

eth_debits AS (
    SELECT 
        et."from" AS wallet_id, 
        SUM(et.value) AS debit -- Convert from wei to ETH
    FROM 
        ethereum.transactions et
    WHERE 
        et."from" IN (SELECT wallet_id FROM current_holders)
    GROUP BY 
        et."from"
),

internal_credits AS (
    SELECT 
        et."to" AS wallet_id, 
        SUM(et.value) AS internal_credit
    FROM 
        ethereum.traces et
    WHERE 
        et."to" IN (SELECT wallet_id FROM current_holders) AND
        et.success = true AND
        et.value > 0
    GROUP BY 
        et."to"
),
internal_debits AS (
    SELECT 
        et."from" AS wallet_id, 
        SUM(et.value) AS internal_debit
    FROM 
        ethereum.traces et
    WHERE 
        et."from" IN (SELECT wallet_id FROM current_holders) AND
        et.success = true AND
        et.value > 0
    GROUP BY 
        et."from"
)

SELECT 
    ch.wallet_id, 
    (COALESCE(ed.debit, 0) + COALESCE(id.internal_debit, 0)) * 0.000000000000000001 AS total_eth_debit,
    (COALESCE(ec.credit, 0) + COALESCE(ic.internal_credit, 0)) * 0.000000000000000001 AS total_eth_credit,
    ((COALESCE(ec.credit, 0) + COALESCE(ic.internal_credit, 0))* 0.000000000000000001 -(COALESCE(ed.debit, 0) + COALESCE(id.internal_debit, 0))* 0.000000000000000001)  AS balance



FROM 
    current_holders ch
LEFT JOIN 
    eth_credits ec ON ch.wallet_id = ec.wallet_id
LEFT JOIN 
    eth_debits ed ON ch.wallet_id = ed.wallet_id
LEFT JOIN 
    internal_credits ic ON ch.wallet_id = ic.wallet_id
LEFT JOIN 
    internal_debits id ON ch.wallet_id = id.wallet_id
    
LIMIT 100
0

There are 0 best solutions below