butaneprotocol / blaze-cardano

🔥 The hottest transaction building library for Cardano
https://blaze.butane.dev
Apache License 2.0
58 stars 22 forks source link

Adjust Maestro::getUnspentOutputByNFT flow to prevent race condition. #178

Closed clifforous closed 1 month ago

clifforous commented 2 months ago

Race condition checking the utxos array length while a fetch may still be happening asynchronously highlighed below.

const utxos: TransactionUnspentOutput[] = [];
for (const maestroUTxO of response.data) {
  //...snip
  fetch(`${this.url}${query2}?with_cbor=true`, {
    headers: this.headers(),
  })
    .then((resp) => resp.json())
    .then((json) => {
        //...snip
        utxos.push(new TransactionUnspentOutput(txIn, txOut));
       //...snip
    });
}
// This check can happen before the async fetch in the for loop above completes
if (utxos.length !== 1)  {
  throw new Error(
    "getUnspentOutputByNFT: Expected 1 UTxO, got " + utxos.length,
  );
}

I moved the array length check to before the fetch using the initial response.data array instead which should have the same behavior. I then removed the for loop since it is guaranteed after that check to be a single utxo in the array.

changeset-bot[bot] commented 2 months ago

🦋 Changeset detected

Latest commit: eb28df8e02e8dee86914b487360ebdfe40829fdb

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages | Name | Type | | ----------------------- | ----- | | @blaze-cardano/query | Patch | | @blaze-cardano/emulator | Patch | | @blaze-cardano/sdk | Patch | | @blaze-cardano/wallet | Patch |

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR