All files / src/serializer encoder.ts

95.51% Statements 149/156
90.72% Branches 88/97
94.44% Functions 17/18
95.39% Lines 145/152

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 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339                                    1x       6x   10x     10x       6x 6x 6x 6x                                                                                                           144x 27x 117x 1x 1x   1x 116x 7x 7x   109x 109x 105x 105x 1x         144x 144x 113x 31x 27x 27x     144x 12x 132x 116x 116x 116x 16x 12x   4x         140x 140x 140x 2x   140x         140x 140x   6x   134x       1479x 1479x 18x 18x 12x     1467x 264x 1x   263x 263x 263x 301x 301x 301x     1203x     1504x 1504x   15x 11x   1489x 2x     2x   1487x   103x 1384x   951x     433x 342x     342x 342x     342x 1282x 1282x 1278x   91x   43x 3x 3x 40x 37x 37x   3x   130x 43x 4x 1x   42x 42x 42x 42x 42x   48x 1x       47x 46x     46x                         1x   140x     140x     140x   140x 140x 140x 140x       2324x 2319x   5x 5x 5x 5x 5x 5x 5x 5x         46x 46x         1322x 1322x 1322x 1322x       2x 2x   1x 1x   1x 1x       2x       954x 954x 962x 8x 8x   954x 954x           1x       356x 356x 356x       134x              
/**
 * Antelope/EOSIO ABI Encoder
 */
import {ABI, ABIDef, Bytes, Variant} from '../chain'
import {isInstanceOf} from '../utils'
 
import {
    ABISerializable,
    ABISerializableConstructor,
    ABISerializableObject,
    ABISerializableType,
    abiTypeString,
    isTypeDescriptor,
    synthesizeABI,
} from './serializable'
import {buildTypeLookup, getType, getTypeName} from './builtins'
 
class EncodingError extends Error {
    static __className = 'EncodingError'
    ctx: EncodingContext
    underlyingError: Error
    constructor(ctx: EncodingContext, underlyingError: Error) {
        const path = ctx.codingPath
            .map(({field, type}) => {
                Iif (typeof field === 'number') {
                    return field
                } else {
                    return `${field}<${type.typeName}>`
                }
            })
            .join('.')
        super(`Encoding error at ${path}: ${underlyingError.message}`)
        this.stack = underlyingError.stack
        this.ctx = ctx
        this.underlyingError = underlyingError
    }
}
 
interface EncodeArgsBase {
    /**
     * ABI definition to use when encoding.
     */
    abi?: ABIDef
    /**
     * Additional types to use when encoding, can be used to pass type constructors
     * that should be used when encountering a custom type.
     */
    customTypes?: ABISerializableConstructor[]
    /**
     * Can be passed to use a custom ABIEncoder instance.
     */
    encoder?: ABIEncoder
    /**
     * Optional metadata to pass to the encoder.
     */
    metadata?: Record<string, any>
}
 
interface EncodeArgsUntyped extends EncodeArgsBase {
    /**
     * Object to encode, either a object conforming to `ABISerializable`
     * or a JavaScript object, when the latter is used an the `type`
     * argument must also be set.
     */
    object: any
    /**
     * Type to use when encoding the given object, either a type constructor
     * or a string name of a builtin type or a custom type in the given `abi`.
     */
    type: ABISerializableType
}
 
interface EncodeArgsSerializable extends EncodeArgsBase {
    /**
     * Object conforming to `ABISerializable` to be encoded.
     */
    object: ABISerializable
    /**
     * Optional type-override for given serializable object.
     */
    type?: ABISerializableType
}
 
export type EncodeArgs = EncodeArgsSerializable | EncodeArgsUntyped
 
export function abiEncode(args: EncodeArgs): Bytes {
    let type: ABISerializableConstructor | undefined
    let typeName: string | undefined
    if (typeof args.type === 'string') {
        typeName = args.type
    } else if (args.type && isTypeDescriptor(args.type)) {
        Eif (typeof args.type.type !== 'string') {
            type = args.type.type
        }
        typeName = abiTypeString(args.type)
    } else if (args.type && args.type.abiName !== undefined) {
        type = args.type
        typeName = args.type.abiName
    } else {
        type = getType(args.object)
        if (type) {
            typeName = type.abiName
            if (Array.isArray(args.object)) {
                typeName += '[]'
            }
        }
    }
 
    const customTypes = args.customTypes ? args.customTypes.slice() : []
    if (type) {
        customTypes.unshift(type)
    } else if (typeName) {
        const rootName = new ABI.ResolvedType(typeName).name
        type = customTypes.find((t) => t.abiName === rootName)
    }
    let rootType: ABI.ResolvedType
    if (args.abi && typeName) {
        rootType = ABI.from(args.abi).resolveType(typeName)
    } else if (type) {
        const synthesized = synthesizeABI(type)
        rootType = synthesized.abi.resolveType(typeName || type.abiName)
        customTypes.push(...synthesized.types)
    } else if (typeName) {
        rootType = new ABI.ResolvedType(typeName)
    } else {
        throw new Error(
            'Unable to determine the type of the object to be encoded. ' +
                'To encode custom ABI types you must pass the type argument.'
        )
    }
    const types = buildTypeLookup(customTypes)
    const encoder = args.encoder || new ABIEncoder()
    if (args.metadata) {
        encoder.metadata = args.metadata
    }
    const ctx: EncodingContext = {
        types,
        encoder,
        codingPath: [{field: 'root', type: rootType}],
    }
    try {
        encodeAny(args.object, rootType, ctx)
    } catch (error) {
        throw new EncodingError(ctx, error)
    }
    return Bytes.from(encoder.getData())
}
 
export function encodeAny(value: any, type: ABI.ResolvedType, ctx: EncodingContext) {
    const valueExists = value !== undefined && value !== null
    if (type.isOptional) {
        ctx.encoder.writeByte(valueExists ? 1 : 0)
        if (!valueExists) {
            return
        }
    }
    if (type.isArray) {
        if (!Array.isArray(value)) {
            throw new Error(`Expected array for: ${type.typeName}`)
        }
        const len = value.length
        ctx.encoder.writeVaruint32(len)
        for (let i = 0; i < len; i++) {
            ctx.codingPath.push({field: i, type})
            encodeInner(value[i])
            ctx.codingPath.pop()
        }
    } else {
        encodeInner(value)
    }
    function encodeInner(value: any) {
        const abiType = ctx.types[type.name]
        if (type.ref && !abiType) {
            // type is alias, follow it
            encodeAny(value, type.ref, ctx)
            return
        }
        if (!valueExists) {
            Iif (type.isExtension) {
                return
            }
            throw new Error(`Found ${value} for non-optional type: ${type.typeName}`)
        }
        if (abiType && abiType.toABI) {
            // type explicitly handles encoding
            abiType.toABI(value, ctx.encoder)
        } else if (typeof value.toABI === 'function' && value.constructor.abiName === type.name) {
            // instance handles encoding
            value.toABI(ctx.encoder)
        } else {
            // encode according to abi def if possible
            if (type.fields) {
                Iif (typeof value !== 'object') {
                    throw new Error(`Expected object for: ${type.name}`)
                }
                const fields = type.allFields
                Iif (!fields) {
                    throw new Error('Invalid struct fields')
                }
                for (const field of fields) {
                    ctx.codingPath.push({field: field.name, type: field.type})
                    encodeAny(value[field.name], field.type, ctx)
                    ctx.codingPath.pop()
                }
            } else if (type.variant) {
                let vName: string | undefined
                if (Array.isArray(value) && value.length === 2 && typeof value[0] === 'string') {
                    vName = value[0]
                    value = value[1]
                } else if (isInstanceOf(value, Variant)) {
                    vName = value.variantName
                    value = value.value
                } else {
                    vName = getTypeName(value)
                }
                const vIdx = type.variant.findIndex((t) => t.typeName === vName)
                if (vIdx === -1) {
                    const types = type.variant.map((t) => `'${t.typeName}'`).join(', ')
                    throw new Error(`Unknown variant type '${vName}', expected one of ${types}`)
                }
                const vType = type.variant[vIdx]
                ctx.encoder.writeVaruint32(vIdx)
                ctx.codingPath.push({field: `v${vIdx}`, type: vType})
                encodeAny(value, vType, ctx)
                ctx.codingPath.pop()
            } else {
                if (!abiType) {
                    throw new Error(
                        type.name === 'any' ? 'Unable to encode any type to binary' : 'Unknown type'
                    )
                }
                const instance = abiType.from(value) as ABISerializableObject
                Iif (!instance.toABI) {
                    throw new Error(`Invalid type ${type.name}, no encoding methods implemented`)
                }
                instance.toABI(ctx.encoder)
            }
        }
    }
}
 
interface EncodingContext {
    encoder: ABIEncoder
    types: ReturnType<typeof buildTypeLookup>
    codingPath: {field: string | number; type: ABI.ResolvedType}[]
}
 
export class ABIEncoder {
    static __className = 'ABIEncoder'
 
    private pos = 0
    private data: DataView
    private array: Uint8Array
    private textEncoder = new TextEncoder()
 
    /** User declared metadata, can be used to pass info to instances when encoding.  */
    metadata: Record<string, any> = {}
 
    constructor(private pageSize = 1024) {
        const buffer = new ArrayBuffer(pageSize)
        this.data = new DataView(buffer)
        this.array = new Uint8Array(buffer)
    }
 
    private ensure(bytes: number) {
        if (this.data.byteLength >= this.pos + bytes) {
            return
        }
        const pages = Math.ceil(bytes / this.pageSize)
        const newSize = this.data.byteLength + this.pageSize * pages
        const buffer = new ArrayBuffer(newSize)
        const data = new DataView(buffer)
        const array = new Uint8Array(buffer)
        array.set(this.array)
        this.data = data
        this.array = array
    }
 
    /** Write a single byte. */
    writeByte(byte: number) {
        this.ensure(1)
        this.array[this.pos++] = byte
    }
 
    /** Write an array of bytes. */
    writeArray(bytes: ArrayLike<number>) {
        const size = bytes.length
        this.ensure(size)
        this.array.set(bytes, this.pos)
        this.pos += size
    }
 
    writeFloat(value: number, byteWidth: number) {
        this.ensure(byteWidth)
        switch (byteWidth) {
            case 4:
                this.data.setFloat32(this.pos, value, true)
                break
            case 8:
                this.data.setFloat64(this.pos, value, true)
                break
            default:
                throw new Error('Invalid float size')
        }
        this.pos += byteWidth
    }
 
    writeVaruint32(v: number) {
        this.ensure(4)
        for (;;) {
            if (v >>> 7) {
                this.array[this.pos++] = 0x80 | (v & 0x7f)
                v = v >>> 7
            } else {
                this.array[this.pos++] = v
                break
            }
        }
    }
 
    writeVarint32(v: number) {
        this.writeVaruint32((v << 1) ^ (v >> 31))
    }
 
    writeString(v: string) {
        const data = this.textEncoder.encode(v)
        this.writeVaruint32(data.byteLength)
        this.writeArray(data)
    }
 
    getData(): Uint8Array {
        return new Uint8Array(this.array.buffer, this.array.byteOffset, this.pos)
    }
 
    getBytes(): Bytes {
        return new Bytes(this.getData())
    }
}