All files / src/serializer encoder.ts

96.87% Statements 155/160
91.35% Branches 74/81
100% Functions 19/19
96.79% Lines 151/156

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 340 341 342 343 344 345                                  1x 1x       6x   10x     10x       6x 6x 6x 6x                                                                                                           10622x 7142x 3480x 1x 1x   1x 3479x 7x 7x   3472x 3472x 3468x 3468x 1x         10622x 10622x 3476x 7146x 7142x 7142x     10622x 7024x 3598x 3479x 3479x 3479x 119x 115x   4x         10618x 10618x 10618x 2x   10618x         10618x 10618x   6x   10612x       109613x 109613x 20x 20x 14x     109599x 3072x 1x   3071x 3071x 3070x   3071x 2687x 2687x 2687x     106527x     109214x 109214x   15x 11x   109199x 9x 7x   2x   5x       109190x   9444x 99746x   87409x     12337x 9866x     9866x 9866x     9866x 98937x 98937x 98933x   2471x   44x 3x 3x 41x 37x 37x   4x   131x 44x 4x 1x   43x 43x 43x 43x 43x   2427x 1x       2426x 2425x     2425x                       1x 1x   10619x     10619x     10619x   10619x 10619x 10619x 10619x       110936x 110911x   25x 25x 25x 25x 25x 25x 25x 25x         4723x 4723x         57505x 57505x 57505x 57505x       37364x 37364x   16304x 16304x   21060x 21060x       37364x       11344x 11344x 11380x 36x 36x   11344x 11344x           1x       5243x 5243x 5243x       10613x       1x      
/**
 * 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)) {
        if (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
        if (!type.size) {
            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) {
            if (type.isExtension) {
                return
            }
            throw new Error(
                `Found ${value} for non-optional type: ${type.typeName} (${ctx.codingPath
                    .map((path) => path.field)
                    .join('.')})`
            )
        }
        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())
    }
}