All files / src/chain blob.ts

30.3% Statements 10/33
36.36% Branches 4/11
55.55% Functions 5/9
31.25% Lines 10/32

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              1x           6x     6x 6x             6x 6x                                                 7x                           1x 1x                             1x              
import {ABISerializableObject} from '../serializer/serializable'
import {ABIEncoder} from '../serializer/encoder'
import {arrayEquals, isInstanceOf} from '../utils'
 
export type BlobType = Blob | string
 
export class Blob implements ABISerializableObject {
    static abiName = 'blob'
 
    /**
     * Create a new Blob instance.
     */
    static from(value: BlobType): Blob {
        Iif (isInstanceOf(value, this)) {
            return value
        }
        Eif (typeof value === 'string') {
            return this.fromString(value)
        }
        throw new Error('Invalid blob')
    }
 
    static fromString(value: string) {
        // If buffer is available, use it (maintains support for nodejs 14)
        Eif (typeof Buffer === 'function') {
            return new this(new Uint8Array(Buffer.from(value, 'base64')))
        }
        // fix up base64 padding from nodeos
        switch (value.length % 4) {
            case 2:
                value += '=='
                break
            case 3:
                value += '='
                break
            case 1:
                value = value.substring(0, value.length - 1)
                break
        }
        const string = atob(value)
        const array = new Uint8Array(string.length)
        for (let i = 0; i < string.length; i++) {
            array[i] = string.charCodeAt(i)
        }
        return new this(array)
    }
 
    readonly array: Uint8Array
 
    constructor(array: Uint8Array) {
        this.array = array
    }
 
    equals(other: BlobType): boolean {
        const self = this.constructor as typeof Blob
        try {
            return arrayEquals(this.array, self.from(other).array)
        } catch {
            return false
        }
    }
 
    get base64String(): string {
        // If buffer is available, use it (maintains support for nodejs 14)
        Eif (typeof Buffer === 'function') {
            return Buffer.from(this.array).toString('base64')
        }
        return btoa(this.utf8String)
    }
 
    /** UTF-8 string representation of this instance. */
    get utf8String(): string {
        return new TextDecoder().decode(this.array)
    }
 
    toABI(encoder: ABIEncoder) {
        encoder.writeArray(this.array)
    }
 
    toString() {
        return this.base64String
    }
 
    toJSON() {
        return this.toString()
    }
}