All files / src/chain abi.ts

96.74% Statements 208/215
88.7% Branches 55/62
100% Functions 25/25
96.44% Lines 190/197

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 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416                    1x 1x                                 461x 461x 461x 461x 461x 461x 461x       486x 26x   460x 2x         458x     458x       3x 3x 3x 3x 1x   3x 3x 3x 17x 17x 17x 17x 17x 41x   17x   3x 3x 3x 12x 12x 12x 12x   3x 3x 3x 5x 5x 5x 5x 5x 1x   5x 5x 5x 1x   5x 5x   3x 3x 3x 1x 1x 1x     3x 3x         3x 3x         3x 3x 3x 3x 1x 1x 1x 1x 2x   1x     3x                       6x 6x 6x 3x 3x   6x 6x 27x 27x 27x 27x 63x 63x     6x 6x 18x 18x 18x   6x 6x 9x 9x 9x 9x 3x   9x 9x 3x   9x   6x 6x 3x 3x   6x 6x 6x 6x 3x 3x 3x 6x           466x 466x       1x 1x 1x 5x 1x 3x               10126x 10126x 4592x   5534x 5534x 5534x 5534x 97x 97x   5437x 5437x 2172x 199x   2172x 8212x         2172x   3265x 3265x 1143x 240x     3025x       42838x       3371x         5x 10x 5x 5x         2x 2x                     2x       1x                           1x                                                                                     1x                         5598x 5598x 82x 82x   5516x   5598x 310x 310x   5288x   5598x 1126x 1126x   4472x   5598x 5598x             6206x 6206x 1132x   6206x 317x   6206x 84x   6206x           1096x 1096x 1096x 1096x 1266x 6x   1260x     1260x 4356x   1260x 1260x   1090x        
import {isInstanceOf} from '../utils'
import type {ABISerializableObject} from '../serializer/serializable'
import {abiDecode, ABIDecoder} from '../serializer/decoder'
import {abiEncode, ABIEncoder} from '../serializer/encoder'
 
import {Blob, Name, NameType} from '../'
 
export type ABIDef = string | Partial<ABI.Def> | ABI | Blob
 
export class ABI implements ABISerializableObject {
    static abiName = 'abi'
    static version = 'eosio::abi/1.1'
 
    version: string
    /// List of type aliases.
    types: ABI.TypeDef[]
    /// List of variant types.
    variants: ABI.Variant[]
    /// List of struct types.
    structs: ABI.Struct[]
    /// List of contract actions.
    actions: ABI.Action[]
    /// List of contract tables.
    tables: ABI.Table[]
    /// Ricardian contracts.
    ricardian_clauses: ABI.Clause[]
 
    constructor(args: Partial<ABI.Def>) {
        this.version = args.version || ABI.version
        this.types = args.types || []
        this.variants = args.variants || []
        this.structs = args.structs || []
        this.actions = args.actions || []
        this.tables = args.tables || []
        this.ricardian_clauses = args.ricardian_clauses || []
    }
 
    static from(value: ABIDef) {
        if (isInstanceOf(value, ABI)) {
            return value
        }
        if (isInstanceOf(value, Blob)) {
            return abiDecode({
                data: value.array,
                type: this,
            })
        }
        Iif (typeof value === 'string') {
            return new ABI(JSON.parse(value))
        }
        return new ABI(value)
    }
 
    static fromABI(decoder: ABIDecoder) {
        const version = decoder.readString()
        const types: ABI.TypeDef[] = []
        const numTypes = decoder.readVaruint32()
        for (let i = 0; i < numTypes; i++) {
            types.push({new_type_name: decoder.readString(), type: decoder.readString()})
        }
        const structs: ABI.Struct[] = []
        const numStructs = decoder.readVaruint32()
        for (let i = 0; i < numStructs; i++) {
            const name = decoder.readString()
            const base = decoder.readString()
            const numFields = decoder.readVaruint32()
            const fields: ABI.Field[] = []
            for (let j = 0; j < numFields; j++) {
                fields.push({name: decoder.readString(), type: decoder.readString()})
            }
            structs.push({base, name, fields})
        }
        const actions: ABI.Action[] = []
        const numActions = decoder.readVaruint32()
        for (let i = 0; i < numActions; i++) {
            const name = Name.fromABI(decoder)
            const type = decoder.readString()
            const ricardian_contract = decoder.readString()
            actions.push({name, type, ricardian_contract})
        }
        const tables: ABI.Table[] = []
        const numTables = decoder.readVaruint32()
        for (let i = 0; i < numTables; i++) {
            const name = Name.fromABI(decoder)
            const index_type = decoder.readString()
            const key_names: string[] = []
            const numKeyNames = decoder.readVaruint32()
            for (let j = 0; j < numKeyNames; j++) {
                key_names.push(decoder.readString())
            }
            const key_types: string[] = []
            const numKeyTypes = decoder.readVaruint32()
            for (let j = 0; j < numKeyTypes; j++) {
                key_types.push(decoder.readString())
            }
            const type = decoder.readString()
            tables.push({name, index_type, key_names, key_types, type})
        }
        const ricardian_clauses: ABI.Clause[] = []
        const numClauses = decoder.readVaruint32()
        for (let i = 0; i < numClauses; i++) {
            const id = decoder.readString()
            const body = decoder.readString()
            ricardian_clauses.push({id, body})
        }
        // error_messages, never used?
        const numErrors = decoder.readVaruint32()
        for (let i = 0; i < numErrors; i++) {
            decoder.advance(8) // uint64 error_code
            decoder.advance(decoder.readVaruint32()) // string error_msgr
        }
        // extensions, not used
        const numExtensions = decoder.readVaruint32()
        for (let i = 0; i < numExtensions; i++) {
            decoder.advance(2) // uint16 type
            decoder.advance(decoder.readVaruint32()) // bytes data
        }
        // variants is a binary extension for some reason even though extensions are defined on the type
        const variants: ABI.Variant[] = []
        Eif (decoder.canRead()) {
            const numVariants = decoder.readVaruint32()
            for (let i = 0; i < numVariants; i++) {
                const name = decoder.readString()
                const types: string[] = []
                const numTypes = decoder.readVaruint32()
                for (let j = 0; j < numTypes; j++) {
                    types.push(decoder.readString())
                }
                variants.push({name, types})
            }
        }
        return new ABI({
            version,
            types,
            structs,
            actions,
            tables,
            ricardian_clauses,
            variants,
        })
    }
 
    toABI(encoder: ABIEncoder) {
        encoder.writeString(this.version)
        encoder.writeVaruint32(this.types.length)
        for (const type of this.types) {
            encoder.writeString(type.new_type_name)
            encoder.writeString(type.type)
        }
        encoder.writeVaruint32(this.structs.length)
        for (const struct of this.structs) {
            encoder.writeString(struct.name)
            encoder.writeString(struct.base)
            encoder.writeVaruint32(struct.fields.length)
            for (const field of struct.fields) {
                encoder.writeString(field.name)
                encoder.writeString(field.type)
            }
        }
        encoder.writeVaruint32(this.actions.length)
        for (const action of this.actions) {
            Name.from(action.name).toABI(encoder)
            encoder.writeString(action.type)
            encoder.writeString(action.ricardian_contract)
        }
        encoder.writeVaruint32(this.tables.length)
        for (const table of this.tables) {
            Name.from(table.name).toABI(encoder)
            encoder.writeString(table.index_type)
            encoder.writeVaruint32(table.key_names.length)
            for (const key of table.key_names) {
                encoder.writeString(key)
            }
            encoder.writeVaruint32(table.key_types.length)
            for (const key of table.key_types) {
                encoder.writeString(key)
            }
            encoder.writeString(table.type)
        }
        encoder.writeVaruint32(this.ricardian_clauses.length)
        for (const clause of this.ricardian_clauses) {
            encoder.writeString(clause.id)
            encoder.writeString(clause.body)
        }
        encoder.writeVaruint32(0) // error_messages
        encoder.writeVaruint32(0) // extensions
        encoder.writeVaruint32(this.variants.length)
        for (const variant of this.variants) {
            encoder.writeString(variant.name)
            encoder.writeVaruint32(variant.types.length)
            for (const type of variant.types) {
                encoder.writeString(type)
            }
        }
    }
 
    resolveType(name: string): ABI.ResolvedType {
        const types: {[name: string]: ABI.ResolvedType} = {}
        return this.resolve({name, types}, {id: 0})
    }
 
    resolveAll() {
        const types: {[name: string]: ABI.ResolvedType} = {}
        const ctx: {id: number} = {id: 0}
        return {
            types: this.types.map((t) => this.resolve({name: t.new_type_name, types}, ctx)),
            variants: this.variants.map((t) => this.resolve({name: t.name, types}, ctx)),
            structs: this.structs.map((t) => this.resolve({name: t.name, types}, ctx)),
        }
    }
 
    private resolve(
        {name, types}: {name: string; types: {[name: string]: ABI.ResolvedType}},
        ctx: {id: number}
    ): ABI.ResolvedType {
        const existing = types[name]
        if (existing) {
            return existing
        }
        const type = new ABI.ResolvedType(name, ++ctx.id)
        types[type.typeName] = type
        const alias = this.types.find((typeDef) => typeDef.new_type_name == type.name)
        if (alias) {
            type.ref = this.resolve({name: alias.type, types}, ctx)
            return type
        }
        const struct = this.getStruct(type.name)
        if (struct) {
            if (struct.base) {
                type.base = this.resolve({name: struct.base, types}, ctx)
            }
            type.fields = struct.fields.map((field) => {
                return {
                    name: field.name,
                    type: this.resolve({name: field.type, types}, ctx),
                }
            })
            return type
        }
        const variant = this.getVariant(type.name)
        if (variant) {
            type.variant = variant.types.map((name) => this.resolve({name, types}, ctx))
            return type
        }
        // builtin or unknown type
        return type
    }
 
    getStruct(name: string): ABI.Struct | undefined {
        return this.structs.find((struct) => struct.name == name)
    }
 
    getVariant(name: string): ABI.Variant | undefined {
        return this.variants.find((variant) => variant.name == name)
    }
 
    /** Return arguments type of an action in this ABI. */
    getActionType(actionName: NameType): string | undefined {
        const name = Name.from(actionName).toString()
        const action = this.actions.find((a) => a.name.toString() === name)
        Eif (action) {
            return action.type
        }
    }
 
    equals(other: ABIDef): boolean {
        const o = ABI.from(other)
        Iif (
            this.version != o.version ||
            this.types.length != o.types.length ||
            this.structs.length != o.structs.length ||
            this.actions.length != o.actions.length ||
            this.tables.length != o.tables.length ||
            this.ricardian_clauses.length != o.ricardian_clauses.length ||
            this.variants.length != o.variants.length
        ) {
            return false
        }
        return abiEncode({object: this}).equals(abiEncode({object: o}))
    }
 
    toJSON() {
        return {
            version: this.version,
            types: this.types,
            structs: this.structs,
            actions: this.actions,
            tables: this.tables,
            ricardian_clauses: this.ricardian_clauses,
            error_messages: [],
            abi_extensions: [],
            variants: this.variants,
        }
    }
}
 
export namespace ABI {
    export interface TypeDef {
        new_type_name: string
        type: string
    }
    export interface Field {
        name: string
        type: string
    }
    export interface Struct {
        name: string
        base: string
        fields: Field[]
    }
    export interface Action {
        name: NameType
        type: string
        ricardian_contract: string
    }
    export interface Table {
        name: NameType
        index_type: string
        key_names: string[]
        key_types: string[]
        type: string
    }
    export interface Clause {
        id: string
        body: string
    }
    export interface Variant {
        name: string
        types: string[]
    }
    export interface Def {
        version: string
        types: TypeDef[]
        variants: Variant[]
        structs: Struct[]
        actions: Action[]
        tables: Table[]
        ricardian_clauses: Clause[]
    }
    export class ResolvedType {
        name: string
        id: number
        isArray: boolean
        isOptional: boolean
        isExtension: boolean
 
        base?: ResolvedType
        fields?: {name: string; type: ResolvedType}[]
        variant?: ResolvedType[]
        ref?: ResolvedType
 
        constructor(fullName: string, id = 0) {
            let name = fullName
            if (name.endsWith('$')) {
                name = name.slice(0, -1)
                this.isExtension = true
            } else {
                this.isExtension = false
            }
            if (name.endsWith('?')) {
                name = name.slice(0, -1)
                this.isOptional = true
            } else {
                this.isOptional = false
            }
            if (name.endsWith('[]')) {
                name = name.slice(0, -2)
                this.isArray = true
            } else {
                this.isArray = false
            }
            this.id = id
            this.name = name
        }
 
        /**
         * Type name including suffixes: [] array, ? optional, $ binary ext
         */
        get typeName(): string {
            let rv = this.name
            if (this.isArray) {
                rv += '[]'
            }
            if (this.isOptional) {
                rv += '?'
            }
            if (this.isExtension) {
                rv += '$'
            }
            return rv
        }
 
        /** All fields including base struct(s), undefined if not a struct type. */
        get allFields() {
            // eslint-disable-next-line @typescript-eslint/no-this-alias
            let current: ResolvedType | undefined = this
            const rv: {name: string; type: ResolvedType}[] = []
            const seen = new Set<string>()
            do {
                if (!current.fields) {
                    return // invalid struct
                }
                Iif (seen.has(current.name)) {
                    return // circular ref
                }
                for (let i = current.fields.length - 1; i >= 0; i--) {
                    rv.unshift(current.fields[i])
                }
                seen.add(current.name)
                current = current.base
            } while (current !== undefined)
            return rv
        }
    }
}