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

Fix Cardano UTXO and balance bugs #849

Merged
merged 2 commits into from
Oct 30, 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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## Unreleased

- fixed: (ADA) Improved balance calculation by deriving from UTXO state.
- fixed: (ADA) Race condition between network queries and local transaction processing causing incorrect UTXO state.

## 4.26.2 (2024-10-29)

- fixed: (ADA) Fixed a bug in Blockfrost response handling that caused an error when processing successful non-JSON responses.
Expand Down
63 changes: 46 additions & 17 deletions src/cardano/CardanoEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import {
CardanoTxOtherParams,
CardanoWalletOtherData,
KoiosNetworkTx,
KoiosUtxo,
SafeCardanoWalletInfo
} from './cardanoTypes'

Expand All @@ -58,7 +59,10 @@ export class CardanoEngine extends CurrencyEngine<
initOptions: CardanoInitOptions
epochNumber: number
slot: number
utxos: ReturnType<typeof asKoiosBalance>[number]['utxo_set']
// All tx output seen:
seenVouts: Set<string> = new Set()
// Only unspent:
utxos: KoiosUtxo[] = []

constructor(
env: PluginEnvironment<CardanoNetworkInfo>,
Expand All @@ -73,7 +77,6 @@ export class CardanoEngine extends CurrencyEngine<
this.networkInfo = env.networkInfo
this.epochNumber = -1
this.slot = -1
this.utxos = []
}

setOtherData(_raw: any): void {
Expand Down Expand Up @@ -234,17 +237,15 @@ export class CardanoEngine extends CurrencyEngine<
_addresses: [this.walletInfo.keys.bech32Address]
})
const clean = asKoiosBalance(raw)
const mainnetBal = clean[0]?.balance ?? '0'

this.updateBalance(this.currencyInfo.currencyCode, mainnetBal)
// Merge unseen utxos into wallet state:
const networkUtxos = clean[0]?.utxo_set ?? []
for (const utxo of networkUtxos) {
this.addUnseenUtxo(utxo)
}

this.utxos =
clean[0]?.utxo_set.map(utxo => ({
asset_list: utxo.asset_list,
tx_hash: utxo.tx_hash,
tx_index: utxo.tx_index,
value: utxo.value
})) ?? []
// Network balance may be out of date, so we'll calculate it from utxos:
this.updateBalanceFromUtxos(this.currencyInfo.currencyCode)
} catch (e) {
this.log.warn('queryBalance error: ', e)
}
Expand Down Expand Up @@ -513,13 +514,10 @@ export class CardanoEngine extends CurrencyEngine<
const txHash = Cardano.hash_transaction(tx.body()).to_hex()
const txJson = tx.to_js_value()

// Filter out spent utxos:
const vouts = new Set(
// Remove any spent utxos:
this.removeUtxosByVouts(
txJson.body.inputs.map(input => `${input.transaction_id}_${input.index}`)
)
this.utxos = this.utxos.filter(utxo => {
return !vouts.has(`${utxo.tx_hash}_${utxo.tx_index}`)
})

// Add new utxos that our own:
const ownAddress = this.walletInfo.keys.bech32Address
Expand All @@ -528,14 +526,17 @@ export class CardanoEngine extends CurrencyEngine<
// Skip over multiasset outputs (we don't support spending from them):
if (output.amount.multiasset != null) return

this.utxos.push({
this.addUnseenUtxo({
asset_list: [],
tx_hash: txHash,
tx_index: index,
value: output.amount.coin
})
}
})

// Update balance incase the UTXO set changed:
this.updateBalanceFromUtxos(this.currencyInfo.currencyCode)
}

async signTx(
Expand Down Expand Up @@ -614,6 +615,34 @@ export class CardanoEngine extends CurrencyEngine<
}
}

/**
* This is a helper function to add utxos to the wallet state that we haven't
* seen before. This avoids duplication and merges utxos into the wallet
* state. Also, we don't want to add utxos that we've already seen because the
* wallet may know that they're spent when the network doesn't.
*
* @param utxo the utxo to add
*/
private addUnseenUtxo(utxo: KoiosUtxo): void {
const vout = `${utxo.tx_hash}_${utxo.tx_index}`
if (!this.seenVouts.has(vout)) {
this.seenVouts.add(vout)
this.utxos.push(utxo)
}
}

private removeUtxosByVouts(vouts: string[] | Set<string>): void {
const voutsSet = new Set(vouts)
this.utxos = this.utxos.filter(
utxo => !voutsSet.has(`${utxo.tx_hash}_${utxo.tx_index}`)
)
}

private updateBalanceFromUtxos(currencyCode: string): void {
const balance = this.utxos.reduce((acc, utxo) => add(acc, utxo.value), '0')
this.updateBalance(currencyCode, balance)
}

getStakeAddress = async (): Promise<string> => {
const { bech32Address } = asSafeCardanoWalletInfo(this.walletInfo).keys

Expand Down
64 changes: 33 additions & 31 deletions src/cardano/cardanoTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,43 +76,45 @@ export const asKoiosBlockheight = asTuple(
})
)

export const asKoiosUtxo = asObject({
// asset_name: '444f4e545350414d',
asset_list: asArray(asUnknown),
// block_height: 42325043,
// block_time: 1506635091,
// fingerprint: 'asset1ua6pz3yd5mdka946z8jw2fld3f8d0mmxt75gv9',
// datum_hash:
// '5a595ce795815e81d22a1a522cf3987d546dc5bb016de61b002edd63a5413ec4',
// decimals: 0,
// inline_datum: {
// bytes: '19029a',
// value: {
// int: 666
// }
// },
// policy_id:
// 'd3501d9531fcc25e3ca4b6429318c2cc374dbdbcf5e99c1c1e5da1ff',
// quantity: 1
// reference_script: {
// hash: '67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656',
// size: 14,
// type: 'plutusV1',
// bytes: '4e4d01000033222220051200120011',
// value: 'null'
// },
tx_hash: asString, // 'f144a8264acf4bdfe2e1241170969c930d64ab6b0996a4a45237b623f1dd670e',
tx_index: asNumber, // 0,
value: asString // 157832856,
})

export type KoiosUtxo = ReturnType<typeof asKoiosUtxo>

export const asKoiosBalance = asArray(
asObject({
// address: 'addr1qxkfe8s6m8qt5436lec3f0320hrmpppwqgs2gah4360krvyssntpwjcz303mx3h4avg7p29l3zd8u3jyglmewds9ezrqdc3cxp',
balance: asString, // 10723473983,
// stake_address: null,
// script_address: true,
utxo_set: asArray(
asObject({
tx_hash: asString, // 'f144a8264acf4bdfe2e1241170969c930d64ab6b0996a4a45237b623f1dd670e',
tx_index: asNumber, // 0,
// block_height: 42325043,
// block_time: 1506635091,
value: asString, // 157832856,
// datum_hash:
// '5a595ce795815e81d22a1a522cf3987d546dc5bb016de61b002edd63a5413ec4',
// inline_datum: {
// bytes: '19029a',
// value: {
// int: 666
// }
// },
// reference_script: {
// hash: '67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656',
// size: 14,
// type: 'plutusV1',
// bytes: '4e4d01000033222220051200120011',
// value: 'null'
// },
asset_list: asArray(asUnknown)
// policy_id:
// 'd3501d9531fcc25e3ca4b6429318c2cc374dbdbcf5e99c1c1e5da1ff',
// asset_name: '444f4e545350414d',
// fingerprint: 'asset1ua6pz3yd5mdka946z8jw2fld3f8d0mmxt75gv9',
// decimals: 0,
// quantity: 1
})
)
utxo_set: asArray(asKoiosUtxo)
})
)

Expand Down
Loading