All files / src mina.ts

48.8% Statements 41/84
25% Branches 7/28
64.28% Functions 9/14
49.35% Lines 38/77

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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247  29x 29x 29x 29x 29x 29x 29x   29x 29x 29x     29x                 29x                     29x                                                                                                       1x       1x 1x     1x 1x 10x             1x                                                                                                   28x 28x 28x                 1x       167x         1x   1x   1x 10x     1x                                             29x             107x 107x 107x 107x 107x   107x                                                   107x      
export {
  initBlockchain,
  Memory,
  makeString,
  sleep,
  accountBalance,
  accountBalanceMina,
  formatTime,
  MinaNetworkInstance,
  currentNetwork,
  getNetworkIdHash,
  getDeployer,
};
 
import {
  Mina,
  PublicKey,
  PrivateKey,
  UInt64,
  fetchAccount,
  Field,
  CircuitString,
} from "o1js";
import { networks, blockchain, MinaNetwork, Local } from "./networks";
 
interface MinaNetworkInstance {
  keys: {
    publicKey: PublicKey;
    privateKey: PrivateKey;
  }[];
  network: MinaNetwork;
  networkIdHash: Field;
}
 
let currentNetwork: MinaNetworkInstance | undefined = undefined;
 
function getNetworkIdHash(): Field {
  Iif (currentNetwork === undefined) {
    throw new Error("Network is not initialized");
  }
  return currentNetwork.networkIdHash;
}
 
function getDeployer(): PrivateKey {
  Iif (currentNetwork === undefined) {
    throw new Error("Network is not initialized");
  }
  return currentNetwork.keys[0].privateKey;
}
 
/*function getNetworkIdHash(params: {
  chainId?: blockchain;
  verbose?: boolean;
}): Field {
  const { chainId, verbose } = params;
  if (chainId !== undefined) {
    if (verbose) console.log(`Chain ID: ${chainId}`);
    return CircuitString.fromString(chainId).hash();
  }
  const networkId = Mina.getNetworkId();
  if (verbose) console.log(`Network ID: ${networkId}`);
  if (networkId === "testnet")
    throw new Error(
      "Network ID is not set, please call initBlockchain() first"
    );
 
  if (networkId === "mainnet")
    return CircuitString.fromString("mainnet").hash();
  else {
    if (
      networkId.custom === undefined ||
      typeof networkId.custom !== "string"
    ) {
      throw new Error(
        "Network ID is not set, please call initBlockchain() first"
      );
    }
    return CircuitString.fromString(networkId.custom).hash();
  }
}
*/
 
async function initBlockchain(
  instance: blockchain,
  deployersNumber: number = 0
): Promise<MinaNetworkInstance> {
  Iif (instance === "mainnet") {
    throw new Error("Mainnet is not supported yet by zkApps");
  }
 
  if (instance === "local") {
    const local = await Mina.LocalBlockchain({
      proofsEnabled: true,
    });
    Mina.setActiveInstance(local);
    currentNetwork = {
      keys: local.testAccounts.map((key) => ({
        privateKey: key.key,
        publicKey: key,
      })),
      network: Local,
      networkIdHash: CircuitString.fromString("local").hash(),
    };
    return currentNetwork;
  }
 
  const network = networks.find((n) => n.chainId === instance);
  Iif (network === undefined) {
    throw new Error("Unknown network");
  }
 
  const networkInstance = Mina.Network({
    mina: network.mina,
    archive: network.archive,
    lightnetAccountManager: network.accountManager,
  });
  Mina.setActiveInstance(networkInstance);
 
  const keys: {
    publicKey: PublicKey;
    privateKey: PrivateKey;
  }[] = [];
 
  Iif (deployersNumber > 0) {
    if (instance === "lighnet") {
      throw new Error(
        "Use await Lightnet.acquireKeyPair() to get keys for Lightnet"
      );
    } else {
      const deployers = process.env.DEPLOYERS;
      Iif (
        deployers === undefined ||
        Array.isArray(deployers) === false ||
        deployers.length < deployersNumber
      )
        throw new Error("Deployers are not set");
      for (let i = 0; i < deployersNumber; i++) {
        const privateKey = PrivateKey.fromBase58(deployers[i]);
        const publicKey = privateKey.toPublicKey();
        keys.push({ publicKey, privateKey });
      }
    }
  }
 
  currentNetwork = {
    keys,
    network,
    networkIdHash: CircuitString.fromString(instance).hash(),
  };
  return currentNetwork;
}
 
async function accountBalance(address: PublicKey): Promise<UInt64> {
  try {
    await fetchAccount({ publicKey: address });
    if (Mina.hasAccount(address)) return Mina.getBalance(address);
    else Ereturn UInt64.from(0);
  } catch (error: any) {
    //console.error(error);
    return UInt64.from(0);
  }
}
 
async function accountBalanceMina(address: PublicKey): Promise<number> {
  return Number((await accountBalance(address)).toBigInt()) / 1e9;
}
 
function sleep(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
 
function makeString(length: number): string {
  // eslint-disable-next-line @typescript-eslint/no-inferrable-types
  let outString: string = ``;
  // eslint-disable-next-line @typescript-eslint/no-inferrable-types
  const inOptions: string = `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`;
 
  for (let i = 0; i < length; i++) {
    outString += inOptions.charAt(Math.floor(Math.random() * inOptions.length));
  }
 
  return outString;
}
 
function formatTime(ms: number): string {
  Iif (ms === undefined) return "";
  Iif (ms < 1000) return ms.toString() + " ms";
  Iif (ms < 60 * 1000)
    return parseInt((ms / 1000).toString()).toString() + " sec";
  if (ms < 60 * 60 * 1000) {
    const minutes = parseInt((ms / 1000 / 60).toString());
    const seconds = parseInt(((ms - minutes * 60 * 1000) / 1000).toString());
    return minutes.toString() + " min " + seconds.toString() + " sec";
  } else {
    const hours = parseInt((ms / 1000 / 60 / 60).toString());
    const minutes = parseInt(
      ((ms - hours * 60 * 60 * 1000) / 1000 / 60).toString()
    );
    return hours.toString() + " h " + minutes.toString() + " min";
  }
}
 
class Memory {
  // eslint-disable-next-line @typescript-eslint/no-inferrable-types
  static rss: number = 0;
  constructor() {
    Memory.rss = 0;
  }
 
  // eslint-disable-next-line @typescript-eslint/no-inferrable-types
  public static info(description: string = ``, fullInfo: boolean = false) {
    const memoryData = process.memoryUsage();
    const formatMemoryUsage = (data: number) =>
      `${Math.round(data / 1024 / 1024)} MB`;
    const oldRSS = Memory.rss;
    Memory.rss = Math.round(memoryData.rss / 1024 / 1024);
 
    const memoryUsage = fullInfo
      ? {
          step: `${description}:`,
          rssDelta: `${(oldRSS === 0
            ? 0
            : Memory.rss - oldRSS
          ).toString()} MB -> Resident Set Size memory change`,
          rss: `${formatMemoryUsage(
            memoryData.rss
          )} -> Resident Set Size - total memory allocated`,
          heapTotal: `${formatMemoryUsage(
            memoryData.heapTotal
          )} -> total size of the allocated heap`,
          heapUsed: `${formatMemoryUsage(
            memoryData.heapUsed
          )} -> actual memory used during the execution`,
          external: `${formatMemoryUsage(
            memoryData.external
          )} -> V8 external memory`,
        }
      : `RSS memory ${description}: ${formatMemoryUsage(memoryData.rss)}${
          oldRSS === 0
            ? ``
            : `, changed by ` + (Memory.rss - oldRSS).toString() + ` MB`
        }`;
 
    console.log(memoryUsage);
  }
}