All files / tests/helpers utils.ts

62.19% Statements 51/82
42.62% Branches 26/61
71.42% Functions 5/7
62.82% Lines 49/78

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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 1891x 1x   1x 1x       1x           6x 3x     1x 1x 1x 1x             1x   1x             1x           22x         22x 22x   22x 70x 70x 35x 35x   35x   70x 92x   70x 2x   22x         22x 68x 2x               22x   22x 22x 22x 22x 22x 22x                                   22x 22x               22x 17x 17x 17x 17x                     17x                                                           17x 5x           1x                                            
import { Mina, PublicKey, Field, checkZkappTransaction } from "o1js";
import { blockchain, sleep, fetchMinaAccount } from "zkcloudworker";
 
let chain: blockchain = "local" as blockchain;
export function setChain(chainName: blockchain) {
  chain = chainName;
}
 
export function processArguments(): {
  chain: blockchain;
  proofsEnabled: boolean;
  useWhitelistedAdmin: boolean;
} {
  function getArgument(arg: string): string | undefined {
    const argument = process.argv.find((a) => a.startsWith("--" + arg));
    return argument?.split("=")[1];
  }
 
  const chainName = getArgument("chain") ?? "local";
  const proofs = getArgument("proofs") ?? "true";
  const useWhitelistedAdmin = getArgument("whitelist") ?? "false";
  Iif (
    chainName !== "local" &&
    chainName !== "devnet" &&
    chainName !== "lightnet" &&
    chainName !== "zeko"
  )
    throw new Error("Invalid chain name");
  chain = chainName as blockchain;
 
  return {
    chain,
    proofsEnabled: proofs === "true",
    useWhitelistedAdmin: useWhitelistedAdmin === "true",
  };
}
 
export async function sendTx(
  tx: Mina.Transaction<false, true> | Mina.Transaction<true, true>,
  description?: string,
  wait?: boolean
) {
  // flatten accountUpdates
  const accountUpdates = JSON.parse(tx.toJSON()).accountUpdates;
  const auCount: {
    publicKey: string;
    tokenId: string | undefined;
    count: number;
  }[] = [];
  let proofAuthorizationCount = 0;
  // Calculate the number of account updates for each { publicKey, tokenId }
  for (const au of accountUpdates) {
    const { publicKey, tokenId, authorizationKind } = au.body;
    if (au.authorization.proof) {
      proofAuthorizationCount++;
      Iif (authorizationKind.isProved === false)
        console.error("Proof authorization exists but isProved is false");
    } else Iif (authorizationKind.isProved === true)
      console.error("isProved is true but no proof authorization");
    const index = auCount.findIndex(
      (item) => item.publicKey === publicKey && item.tokenId === tokenId
    );
    if (index === -1) auCount.push({ publicKey, tokenId, count: 1 });
    else auCount[index].count++;
  }
  console.log(
    `Account updates for ${description ?? "tx"}: ${
      auCount.length
    }, proof authorizations: ${proofAuthorizationCount}`
  );
  for (const au of auCount) {
    if (au.count > 1)
      console.log(
        `DUPLICATE AU ${description ?? ""}: ${au.publicKey}  ${
          au.tokenId !== "wSHV2S4qX9jFsLjQo8r1BsMLH2ZRKsZx6EJd1sbozGPieEC4Jf"
            ? "tokenId: " + au.tokenId
            : ""
        } count: ${au.count}`
      );
  }
  try {
    let txSent;
    let sent = false;
    while (!sent) {
      txSent = await tx.safeSend();
      if (txSent.status == "pending") {
        sent = true;
        console.log(
          `${description ?? ""} tx sent: hash: ${txSent.hash} status: ${
            txSent.status
          }`
        );
      } else Eif (chain === "zeko") {
        console.log("Retrying Zeko tx");
        await sleep(10000);
      } else {
        console.log(
          `${description ?? ""} tx NOT sent: hash: ${txSent?.hash} status: ${
            txSent?.status
          }`,
          txSent.errors
        );
        return undefined;
      }
    }
    Iif (txSent === undefined) throw new Error("txSent is undefined");
    Iif (txSent.errors.length > 0) {
      console.error(
        `${description ?? ""} tx error: hash: ${txSent.hash} status: ${
          txSent.status
        }  errors: ${txSent.errors}`
      );
    }
 
    if (txSent.status === "pending" && wait !== false && chain !== "zeko") {
      console.log(`Waiting for tx inclusion...`);
      const txIncluded = await txSent.safeWait();
      if (txIncluded.status === "included")
        console.log(
          `${description ?? ""} tx included into block: hash: ${
            txIncluded.hash
          } status: ${txIncluded.status}`
        );
      else
        Econsole.error(
          `${description ?? ""} tx NOT included into block: hash: ${
            txIncluded.hash
          } status: ${txIncluded.status}`
        );
      Iif (chain !== "local") {
        // we still wait for the tx to be included in the block by checking the nonce
        // even in the case of tx NOT included
        // because the tx might still be included in the block in the case of devnet instability
        const { publicKey, nonce } = tx.transaction.feePayer.body;
        const started = Date.now();
        while (Date.now() - started < 1000 * 60 * 10) {
          const newNonce = (
            await fetchMinaAccount({
              publicKey,
              force: true,
            })
          ).account?.nonce;
          Iif (
            newNonce &&
            Number(newNonce.toBigint()) > Number(nonce.toBigint())
          )
            return txIncluded;
          console.log(
            `Waiting for ${chain} to update state for ${Math.floor(
              (Date.now() - started) / 1000
            )} sec...`
          );
          await sleep(10000);
        }
        // finally, if the tx is still not included, show an error
        console.error(
          `${chain} do not reflect nonce update for tx ${txIncluded.hash} with status ${txIncluded.status}`
        );
      }
      return txIncluded;
    } else return txSent;
  } catch (error) {
    Iif (chain !== "zeko") console.error("Error sending tx", error);
  }
}
 
export async function getTxStatusFast(params: {
  hash: string;
}): Promise<{ success: boolean; result?: boolean; error?: string }> {
  Iif (chain === "local" || chain === "zeko")
    return { success: true, result: true };
  const { hash } = params;
 
  try {
    const txStatus = await checkZkappTransaction(hash);
    return {
      success: true,
      result: txStatus?.success ?? false,
    };
  } catch (error: any) {
    console.error(
      "getTxStatusFast error while getting tx status - catch",
      hash,
      error
    );
    return { success: false, error: error?.message ?? "Cannot get tx status" };
  }
}