All files / src/storage arweave.ts

75% Statements 63/84
50% Branches 12/24
100% Functions 6/6
81.81% Lines 63/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 17527x 27x 27x               4x 4x 4x       4x                         1x 1x 1x   1x 1x 1x   1x           1x 1x   1x   1x 1x 1x         1x 1x 1x   1x                             2x 2x 2x   2x 2x 2x   2x       2x 2x 2x 2x 2x   2x 6x 6x         2x 2x 2x 2x                 11x 11x 11x                                   1x 1x 1x 1x 1x 1x 1x 11x 11x                     11x 1x         10x   10x                   2x 2x 2x 2x      
export { ARWEAVE };
import Arweave from "arweave";
import { sleep } from "../mina";
 
class ARWEAVE {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private key: any;
  arweave: Arweave;
 
  constructor(key: string | object) {
    if (typeof key === "string") {
      Iif (key === "") key = { test: true };
      else this.key = JSON.parse(key);
    } else E{
      this.key = key;
    }
    this.arweave = Arweave.init({
      host: "arweave.net",
      port: 443,
      protocol: "https",
    });
  }
 
  // TODO: change to pinJSON with the same parameters as pinJSON in IPFS
  public async pinString(
    data: string,
    // eslint-disable-next-line @typescript-eslint/no-inferrable-types
    waitForConfirmation: boolean = false
  ): Promise<string | undefined> {
    try {
      Iif (this.key === undefined) return undefined;
      Iif (this.key?.test === true)
        return "CtQFMSLwvvWDkl5b2epJAroxXVbr1ISlAl1quCaxrOc";
      const address = await this.arweave.wallets.jwkToAddress(this.key);
      const balance = await this.arweave.wallets.getBalance(address);
      Iif (parseInt(balance) === 0) return undefined;
 
      const transaction = await this.arweave.createTransaction(
        {
          data: Buffer.from(data, "utf8"),
        },
        this.key
      );
      transaction.addTag("Content-Type", "application/json");
      await this.arweave.transactions.sign(transaction, this.key);
 
      const uploader = await this.arweave.transactions.getUploader(transaction);
 
      while (!uploader.isComplete) {
        await uploader.uploadChunk();
        console.log(
          `${uploader.pctComplete}% complete, ${uploader.uploadedChunks}/${uploader.totalChunks}`
        );
      }
      //console.log("transaction", transaction);
      const hash = transaction.id;
      console.log("arweave hash", hash);
      Iif (waitForConfirmation) await this.wait({ hash }); // wait for confirmation, can take a while
 
      return hash;
    } catch (err) {
      console.error(err);
      return undefined;
    }
  }
 
  public async pinFile(
    data: Buffer,
    filename: string,
    size: number,
    mimeType: string,
    // eslint-disable-next-line @typescript-eslint/no-inferrable-types
    waitForConfirmation: boolean = false
  ): Promise<string | undefined> {
    try {
      Iif (this.key === undefined) return undefined;
      Iif (this.key?.test === true)
        return "CtQFMSLwvvWDkl5b2epJAroxXVbr1ISlAl1quCaxrOc";
      const address = await this.arweave.wallets.jwkToAddress(this.key);
      const balance = await this.arweave.wallets.getBalance(address);
      Iif (parseInt(balance) === 0) return undefined;
 
      const transaction = await this.arweave.createTransaction(
        { data: data },
        this.key
      );
      transaction.addTag("Content-Type", mimeType);
      transaction.addTag("knownLength", size.toString());
      transaction.addTag("filename", filename);
      await this.arweave.transactions.sign(transaction, this.key);
      const uploader = await this.arweave.transactions.getUploader(transaction);
 
      while (!uploader.isComplete) {
        await uploader.uploadChunk();
        console.log(
          `${uploader.pctComplete}% complete, ${uploader.uploadedChunks}/${uploader.totalChunks}`
        );
      }
      //console.log("transaction", transaction);
      const hash = transaction.id;
      console.log("arweave hash", hash);
      Iif (waitForConfirmation) await this.wait({ hash }); // wait for confirmation, can take a while
      return hash;
    } catch (err) {
      console.error(err);
      return undefined;
    }
  }
 
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  public async status(hash: string) {
    try {
      const status = await this.arweave.transactions.getStatus(hash);
      return { success: true, data: status };
    } catch (err) {
      console.error(err);
      return { success: false, error: err };
    }
  }
 
  public async wait(data: {
    hash: string;
    maxAttempts?: number;
    interval?: number;
    maxErrors?: number;
  }): Promise<{
    success: boolean;
    error?: string;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    result?: any;
  }> {
    const maxAttempts = data?.maxAttempts ?? 360;
    const interval = data?.interval ?? 5000;
    const maxErrors = data?.maxErrors ?? 10;
    const errorDelay = 30000; // 30 seconds
    let attempts = 0;
    let errors = 0;
    while (attempts < maxAttempts) {
      const result = await this.status(data.hash);
      Iif (result.success === false) {
        errors++;
        Iif (errors > maxErrors) {
          return {
            success: false,
            error: "Too many network errors",
            result: undefined,
          };
        }
        await sleep(errorDelay * errors);
      } else {
        if (result.data?.confirmed?.block_height !== undefined) {
          return {
            success: result.success,
            result: result.data,
          };
        }
        await sleep(interval);
      }
      attempts++;
    }
    return {
      success: false,
      error: "Timeout",
      result: undefined,
    };
  }
 
  public async balance(): Promise<string | undefined> {
    const address = await this.arweave.wallets.jwkToAddress(this.key);
    const balance = await this.arweave.wallets.getBalance(address);
    const ar = this.arweave.ar.winstonToAr(balance);
    return ar;
  }
}