All files / src/api/v1 chain.ts

84.8% Statements 106/125
71.26% Branches 62/87
93.54% Functions 29/31
85.95% Lines 104/121

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 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441                                                                                                                    2x 2x 2x 5x       1x 11x     6x             1x               2x               8x               2x               1x               9x               3x                               2x       2x 1x   2x                     1x       1x       1x 1x 1x   1x       19x               1x             1x 1x   1x                 96x 96x   96x                 7x 7x   7x             1x 1x   1x                   4x 4x   4x                   4x 1x                     2x                 1x   3x                                           19x 19x 19x 19x   2x   2x   2x   2x   2x 1x 1x       19x 4x   19x 19x   7x   19x 19x         1x   19x 38x 17x 15x   19x 19x 19x 19x 2x 17x 1x     19x                               18x 1x 1x 1x 1x     18x 2x                   2x 3x 3x     18x     12x   8x 8x         2x 2x   1x 1x   1x 1x                   12x   2x   10x     6x   18x       2x               1x                  
import {APIClient, APIError} from '../client'
import {APIResponse} from '../provider'
 
import {
    BlockIdType,
    Bytes,
    Checksum160,
    Checksum256,
    Checksum256Type,
    Float128,
    Float64,
    Name,
    NameType,
    PackedTransaction,
    SignedTransaction,
    SignedTransactionType,
    UInt128,
    UInt32,
    UInt32Type,
    UInt64,
} from '../../chain'
 
import {
    AccountObject,
    AccountsByAuthorizers,
    GetAbiResponse,
    GetAccountsByAuthorizersParams,
    GetBlockHeaderStateResponse,
    GetBlockInfoResponse,
    GetBlockResponse,
    GetCodeResponse,
    GetCurrencyStatsItemResponse,
    GetCurrencyStatsResponse,
    GetInfoResponse,
    GetProducerScheduleResponse,
    GetProtocolFeaturesParams,
    GetProtocolFeaturesResponse,
    GetRawAbiResponse,
    GetTableByScopeParams,
    GetTableByScopeResponse,
    GetTableRowsParams,
    GetTableRowsParamsKeyed,
    GetTableRowsParamsTyped,
    GetTableRowsResponse,
    GetTransactionStatusResponse,
    PushTransactionResponse,
    SendTransaction2Options,
    SendTransaction2Response,
    SendTransactionResponse,
    SendTransactionResponseExceptionStack,
    TableIndexType,
    TableIndexTypes,
} from './types'
 
import {ABISerializableConstructor, ABISerializableType, Serializer} from '../../serializer'
import {isInstanceOf} from '../../utils'
 
function resolveStackFormat(entry: SendTransactionResponseExceptionStack): string {
    Iif (!entry.format) return ''
    Iif (!entry.data) return entry.format
    return entry.format.replace(/\$\{(\w+)\}/g, (_, key) =>
        entry.data[key] !== undefined ? String(entry.data[key]) : `\${${key}}`
    )
}
 
export class ChainAPI {
    constructor(private client: APIClient) {}
 
    async get_abi(accountName: NameType) {
        return this.client.call<GetAbiResponse>({
            path: '/v1/chain/get_abi',
            params: {account_name: Name.from(accountName)},
        })
    }
 
    async get_code(accountName: NameType) {
        return this.client.call({
            path: '/v1/chain/get_code',
            params: {account_name: Name.from(accountName)},
            responseType: GetCodeResponse,
        })
    }
 
    async get_raw_abi(accountName: NameType) {
        return this.client.call({
            path: '/v1/chain/get_raw_abi',
            params: {account_name: Name.from(accountName)},
            responseType: GetRawAbiResponse,
        })
    }
 
    async get_account(accountName: NameType, responseType = AccountObject) {
        return this.client.call({
            path: '/v1/chain/get_account',
            params: {account_name: Name.from(accountName)},
            responseType: responseType,
        })
    }
 
    async get_accounts_by_authorizers(params: GetAccountsByAuthorizersParams) {
        return this.client.call({
            path: '/v1/chain/get_accounts_by_authorizers',
            params,
            responseType: AccountsByAuthorizers,
        })
    }
 
    async get_activated_protocol_features(params?: GetProtocolFeaturesParams) {
        return this.client.call({
            path: '/v1/chain/get_activated_protocol_features',
            params,
            responseType: GetProtocolFeaturesResponse,
        })
    }
 
    async get_block(block_num_or_id: BlockIdType | UInt32Type) {
        return this.client.call({
            path: '/v1/chain/get_block',
            params: {block_num_or_id},
            responseType: GetBlockResponse,
        })
    }
 
    async get_block_header_state(block_num_or_id: BlockIdType | UInt32Type) {
        return this.client.call({
            path: '/v1/chain/get_block_header_state',
            params: {block_num_or_id},
            responseType: GetBlockHeaderStateResponse,
        })
    }
 
    async get_block_info(block_num: UInt32Type) {
        return this.client.call({
            path: '/v1/chain/get_block_info',
            params: {block_num},
            responseType: GetBlockInfoResponse,
        })
    }
 
    async get_currency_balance(contract: NameType, accountName: NameType, symbol?: string) {
        const params: any = {
            account: Name.from(accountName),
            code: Name.from(contract),
        }
        if (symbol) {
            params.symbol = symbol
        }
        return this.client.call({
            path: '/v1/chain/get_currency_balance',
            params,
            responseType: 'asset[]',
        })
    }
 
    async get_currency_stats(
        contract: NameType,
        symbol: string
    ): Promise<GetCurrencyStatsResponse> {
        const params: any = {
            code: Name.from(contract),
            symbol,
        }
        const response: GetCurrencyStatsResponse = await this.client.call({
            path: '/v1/chain/get_currency_stats',
            params,
        })
        const result: GetCurrencyStatsResponse = {}
        Object.keys(response).forEach(
            (r) => (result[r] = GetCurrencyStatsItemResponse.from(response[r]))
        )
        return result
    }
 
    async get_info() {
        return this.client.call({
            path: '/v1/chain/get_info',
            responseType: GetInfoResponse,
            method: 'GET',
        })
    }
 
    async get_producer_schedule() {
        return this.client.call({
            path: '/v1/chain/get_producer_schedule',
            responseType: GetProducerScheduleResponse,
        })
    }
 
    async compute_transaction(tx: SignedTransactionType | PackedTransaction) {
        if (!isInstanceOf(tx, PackedTransaction)) {
            tx = PackedTransaction.fromSigned(SignedTransaction.from(tx))
        }
        return this.client.call<SendTransactionResponse>({
            path: '/v1/chain/compute_transaction',
            params: {
                transaction: tx,
            },
        })
    }
 
    async send_read_only_transaction(tx: SignedTransactionType | PackedTransaction) {
        if (!isInstanceOf(tx, PackedTransaction)) {
            tx = PackedTransaction.fromSigned(SignedTransaction.from(tx))
        }
        return this.client.call<SendTransactionResponse>({
            path: '/v1/chain/send_read_only_transaction',
            params: {
                transaction: tx,
            },
        })
    }
 
    async push_transaction(tx: SignedTransactionType | PackedTransaction) {
        if (!isInstanceOf(tx, PackedTransaction)) {
            tx = PackedTransaction.fromSigned(SignedTransaction.from(tx))
        }
        return this.client.call<PushTransactionResponse>({
            path: '/v1/chain/push_transaction',
            params: tx,
        })
    }
 
    async send_transaction(tx: SignedTransactionType | PackedTransaction) {
        if (!isInstanceOf(tx, PackedTransaction)) {
            tx = PackedTransaction.fromSigned(SignedTransaction.from(tx))
        }
        return this.client.call<SendTransactionResponse>({
            path: '/v1/chain/send_transaction',
            params: tx,
        })
    }
 
    async send_transaction2(
        tx: SignedTransactionType | PackedTransaction,
        options?: SendTransaction2Options
    ) {
        if (!isInstanceOf(tx, PackedTransaction)) {
            tx = PackedTransaction.fromSigned(SignedTransaction.from(tx))
        }
        const response = await this.client.call<SendTransaction2Response>({
            path: '/v1/chain/send_transaction2',
            params: {
                return_failure_trace: true,
                retry_trx: false,
                retry_trx_num_blocks: 0,
                transaction: tx,
                ...options,
            },
        })
        if (response && response.processed && response.processed.except) {
            const except = response.processed.except
            const synthesized: APIResponse = {
                status: 202,
                headers: {},
                text: JSON.stringify(response),
                json: {
                    ...response,
                    error: {
                        code: except.code || 0,
                        name: except.name || 'transaction_exception',
                        what: except.message || 'Transaction failed',
                        details: (except.stack || []).map((s) => ({
                            message: resolveStackFormat(s) || '',
                            file: (s.context && s.context.file) || '',
                            line_number: (s.context && s.context.line) || 0,
                            method: (s.context && s.context.method) || '',
                        })),
                    },
                },
            }
            throw new APIError('/v1/chain/send_transaction2', synthesized)
        }
        return response
    }
 
    async get_table_rows<Index extends TableIndexType = Name>(
        params: GetTableRowsParams<Index>
    ): Promise<GetTableRowsResponse<Index>>
    async get_table_rows<Key extends keyof TableIndexTypes>(
        params: GetTableRowsParamsKeyed<TableIndexTypes[Key], Key>
    ): Promise<GetTableRowsResponse<TableIndexTypes[Key]>>
    async get_table_rows<
        Row extends ABISerializableConstructor,
        Index extends TableIndexType = Name,
    >(
        params: GetTableRowsParamsTyped<Index, Row>
    ): Promise<GetTableRowsResponse<Index, InstanceType<Row>>>
    async get_table_rows<Row extends ABISerializableConstructor, Key extends keyof TableIndexTypes>(
        params: GetTableRowsParamsTyped<TableIndexTypes[Key], Row> &
            GetTableRowsParamsKeyed<TableIndexTypes[Key], Key>
    ): Promise<GetTableRowsResponse<TableIndexTypes[Key], InstanceType<Row>>>
    async get_table_rows(
        params: GetTableRowsParams | GetTableRowsParamsTyped | GetTableRowsParamsKeyed
    ) {
        const type = (params as GetTableRowsParamsTyped).type
        let key_type = (params as GetTableRowsParamsKeyed).key_type
        const someBound = params.lower_bound || params.upper_bound
        if (!key_type && someBound) {
            // determine key type from bounds type
            Iif (isInstanceOf(someBound, UInt64)) {
                key_type = 'i64'
            } else Iif (isInstanceOf(someBound, UInt128)) {
                key_type = 'i128'
            } else Iif (isInstanceOf(someBound, Checksum256)) {
                key_type = 'sha256'
            } else Iif (isInstanceOf(someBound, Checksum160)) {
                key_type = 'ripemd160'
            } else if (isInstanceOf(someBound, Float128)) {
                key_type = 'float128'
            } else Iif (isInstanceOf(someBound, Float64)) {
                key_type = 'float64'
            }
        }
        if (!key_type) {
            key_type = 'name'
        }
        let json = params.json
        if (json === undefined) {
            // if we know the row type don't ask the node to perform abi decoding
            json = type === undefined
        }
        let encode_type = params.encode_type
        if (
            !encode_type &&
            (isInstanceOf(params.lower_bound, Float128) ||
                isInstanceOf(params.upper_bound, Float128))
        ) {
            encode_type = 'hex'
        }
        const boundString = (bound: any) => {
            if (!bound) return bound
            if (isInstanceOf(bound, Float128) && encode_type === 'hex') return bound.toBoundHex()
            return String(bound)
        }
        const upper_bound = boundString(params.upper_bound)
        const lower_bound = boundString(params.lower_bound)
        let scope = params.scope
        if (typeof scope === 'undefined') {
            scope = String(Name.from(params.code))
        } else if (typeof scope !== 'string') {
            scope = String(scope)
        }
        // eslint-disable-next-line prefer-const
        let {rows, more, next_key} = await this.client.call<any>({
            path: '/v1/chain/get_table_rows',
            params: {
                ...params,
                code: Name.from(params.code),
                table: Name.from(params.table),
                limit: params.limit !== undefined ? UInt32.from(params.limit) : undefined,
                scope,
                key_type,
                encode_type,
                json,
                upper_bound,
                lower_bound,
            },
        })
        let ram_payers: Name[] | undefined
        if (params.show_payer) {
            ram_payers = []
            rows = rows.map(({data, payer}) => {
                ram_payers!.push(Name.from(payer))
                return data
            })
        }
        if (type) {
            Iif (json) {
                rows = rows.map((value) => {
                    if (typeof value === 'string' && Bytes.isBytes(value)) {
                        // this handles the case where nodeos bails on abi decoding and just returns a hex string
                        return Serializer.decode({data: Bytes.from(value), type})
                    } else {
                        return Serializer.decode({object: value, type})
                    }
                })
            } else {
                rows = rows
                    .map((hex) => Bytes.from(hex))
                    .map((data) => Serializer.decode({data, type}))
            }
        }
        if (next_key && next_key.length > 0) {
            let indexType: ABISerializableType
            // set index type so we can decode next_key in the response if present
            switch (key_type) {
                case 'i64':
                    indexType = UInt64
                    break
                case 'i128':
                    indexType = UInt128
                    break
                case 'name':
                    indexType = Name
                    break
                case 'float64':
                    indexType = Float64
                    break
                case 'float128':
                    indexType = Float128
                    break
                case 'sha256':
                    indexType = Checksum256
                    break
                case 'ripemd160':
                    indexType = Checksum160
                    break
                default:
                    throw new Error(`Unsupported key type: ${key_type}`)
            }
            if (indexType === Name) {
                // names are sent back as an uint64 string instead of a name string..
                next_key = Name.from(Serializer.decode({object: next_key, type: UInt64}))
            } else {
                next_key = Serializer.decode({object: next_key, type: indexType})
            }
        } else {
            next_key = undefined
        }
        return {rows, more, next_key, ram_payers}
    }
 
    async get_table_by_scope(params: GetTableByScopeParams) {
        return this.client.call({
            path: '/v1/chain/get_table_by_scope',
            params,
            responseType: GetTableByScopeResponse,
        })
    }
 
    async get_transaction_status(id: Checksum256Type) {
        return this.client.call({
            path: '/v1/chain/get_transaction_status',
            params: {
                id: Checksum256.from(id),
            },
            responseType: GetTransactionStatusResponse,
        })
    }
}