Add findAttribute to logs module

This commit is contained in:
Simon Warta 2020-02-07 16:19:34 +01:00
parent cce7ee52e4
commit 8b382d76d5
3 changed files with 35 additions and 15 deletions

View File

@ -59,3 +59,26 @@ export function parseLogs(input: unknown): readonly Log[] {
if (!Array.isArray(input)) throw new Error("Logs must be an array");
return input.map(parseLog);
}
/**
* Searches in logs for the first event of the given event type and in that event
* for the first first attribute with the given attribute key.
*
* Throws if the attribute was not found.
*/
export function findAttribute(
logs: readonly Log[],
eventType: "message" | "transfer",
attrKey: string,
): Attribute {
const firstLogs = logs.find(() => true);
const out = firstLogs?.events
.find(event => event.type === eventType)
?.attributes.find(attr => attr.key === attrKey);
if (!out) {
throw new Error(
`Could not find attribute '${attrKey}' in first event of type '${eventType}' in first log.`,
);
}
return out;
}

View File

@ -4,7 +4,7 @@ import { Bech32, Encoding } from "@iov/encoding";
import { encodeSecp256k1Signature, makeSignBytes, marshalTx } from "./encoding";
import { leb128Encode } from "./leb128.spec";
import { Attribute, Log, parseLogs } from "./logs";
import { findAttribute, parseLogs } from "./logs";
import { Pen, Secp256k1Pen } from "./pen";
import { PostTxsResponse, RestClient } from "./restclient";
import contract from "./testdata/contract.json";
@ -75,20 +75,6 @@ function makeRandomAddress(): string {
return Bech32.encode("cosmos", Random.getBytes(20));
}
/** Throws if the attribute was not found */
function findAttribute(logs: readonly Log[], eventType: "message" | "transfer", attrKey: string): Attribute {
const firstLogs = logs.find(() => true);
const out = firstLogs?.events
.find(event => event.type === eventType)
?.attributes.find(attr => attr.key === attrKey);
if (!out) {
throw new Error(
`Could not find attribute '${attrKey}' in first event of type '${eventType}' in first log.`,
);
}
return out;
}
async function uploadContract(client: RestClient, pen: Pen): Promise<PostTxsResponse> {
const memo = "My first contract on chain";
const theMsg: MsgStoreCode = {

View File

@ -15,3 +15,14 @@ export declare function parseAttribute(input: unknown): Attribute;
export declare function parseEvent(input: unknown): Event;
export declare function parseLog(input: unknown): Log;
export declare function parseLogs(input: unknown): readonly Log[];
/**
* Searches in logs for the first event of the given event type and in that event
* for the first first attribute with the given attribute key.
*
* Throws if the attribute was not found.
*/
export declare function findAttribute(
logs: readonly Log[],
eventType: "message" | "transfer",
attrKey: string,
): Attribute;