Improve codec handling

This commit is contained in:
Simon Warta 2020-02-10 10:53:38 +01:00
parent 59d336e54a
commit a3b6ab5bd8
9 changed files with 42 additions and 33 deletions

View File

@ -1,9 +1,10 @@
import { UserProfile } from "@iov/keycontrol";
import cors = require("@koa/cors");
import { createCosmWasmConnector } from "@cosmwasm/bcp";
import Koa from "koa";
import bodyParser from "koa-bodyparser";
import { codecImplementation, establishConnection } from "../../codec";
import { isValidAddress } from "../../addresses";
import * as constants from "../../constants";
import { logAccountsState, logSendJob } from "../../debugging";
import { Faucet } from "../../faucet";
@ -41,8 +42,14 @@ export async function start(args: ReadonlyArray<string>): Promise<void> {
if (!constants.mnemonic) {
throw new Error("The FAUCET_MNEMONIC environment variable is not set");
}
const connector = createCosmWasmConnector(
blockchainBaseUrl,
constants.addressPrefix,
constants.tokenConfig,
);
console.info(`Connecting to blockchain ${blockchainBaseUrl} ...`);
const connection = await establishConnection(blockchainBaseUrl);
const connection = await connector.establishConnection();
const connectedChainId = connection.chainId();
console.info(`Connected to network: ${connectedChainId}`);
@ -67,8 +74,8 @@ export async function start(args: ReadonlyArray<string>): Promise<void> {
const faucet = new Faucet(constants.tokenConfig);
await faucet.refill(profile, connection);
setInterval(async () => faucet.refill(profile, connection), 60_000); // ever 60 seconds
await faucet.refill(profile, connection, connector.codec);
setInterval(async () => faucet.refill(profile, connection, connector.codec), 60_000); // ever 60 seconds
console.info("Creating webserver ...");
const api = new Koa();
@ -112,7 +119,7 @@ export async function start(args: ReadonlyArray<string>): Promise<void> {
const requestBody = context.request.body;
const { address, ticker } = RequestParser.parseCreditBody(requestBody);
if (!codecImplementation().isValidAddress(address)) {
if (!isValidAddress(address)) {
throw new HttpError(400, "Address is not in the expected format for this chain.");
}
@ -131,7 +138,7 @@ export async function start(args: ReadonlyArray<string>): Promise<void> {
tokenTicker: ticker,
};
logSendJob(job);
await send(profile, connection, job);
await send(profile, connection, connector.codec, job);
} catch (e) {
console.error(e);
throw new HttpError(500, "Sending tokens failed");

View File

@ -0,0 +1,17 @@
import { CosmWasmCodec } from "@cosmwasm/bcp";
import { Address, Identity, TxCodec } from "@iov/bcp";
import * as constants from "./constants";
const noTokensCodec: Pick<TxCodec, "identityToAddress" | "isValidAddress"> = new CosmWasmCodec(
constants.addressPrefix,
[],
);
export function identityToAddress(identity: Identity): Address {
return noTokensCodec.identityToAddress(identity);
}
export function isValidAddress(input: string): boolean {
return noTokensCodec.isValidAddress(input);
}

View File

@ -1 +0,0 @@
describe("codec", () => {});

View File

@ -1,14 +0,0 @@
import { CosmWasmCodec, CosmWasmConnection } from "@cosmwasm/bcp";
import { TxCodec } from "@iov/bcp";
import { tokenConfig } from "./constants";
const prefix = "cosmos";
export async function establishConnection(url: string): Promise<CosmWasmConnection> {
return CosmWasmConnection.establish(url, prefix, tokenConfig);
}
export function codecImplementation(): TxCodec {
return new CosmWasmCodec(prefix, tokenConfig.bankTokens);
}

View File

@ -5,6 +5,7 @@ export const concurrency: number = Number.parseInt(process.env.FAUCET_CONCURRENC
export const port: number = Number.parseInt(process.env.FAUCET_PORT || "", 10) || 8000;
export const mnemonic: string | undefined = process.env.FAUCET_MNEMONIC;
export const addressPrefix = "cosmos";
export const tokenConfig: TokenConfiguration = {
bankTokens: [
{

View File

@ -1,7 +1,7 @@
import { Account, Amount } from "@iov/bcp";
import { Decimal } from "@iov/encoding";
import { codecImplementation } from "./codec";
import { identityToAddress } from "./addresses";
import { SendJob } from "./types";
/** A string representation of a coin in a human-readable format that can change at any time */
@ -31,7 +31,7 @@ export function logAccountsState(accounts: ReadonlyArray<Account>): void {
}
export function logSendJob(job: SendJob): void {
const from = codecImplementation().identityToAddress(job.sender);
const from = identityToAddress(job.sender);
const to = job.recipient;
const amount = debugAmount(job.amount);
console.info(`Sending ${amount} from ${from} to ${to} ...`);

View File

@ -1,5 +1,5 @@
import { TokenConfiguration } from "@cosmwasm/bcp";
import { Account, Amount, BlockchainConnection, TokenTicker } from "@iov/bcp";
import { Account, Amount, BlockchainConnection, TokenTicker, TxCodec } from "@iov/bcp";
import { Decimal, Uint53 } from "@iov/encoding";
import { UserProfile } from "@iov/keycontrol";
import { sleep } from "@iov/utils";
@ -53,7 +53,7 @@ export class Faucet {
return this.creditAmount(token, factor);
}
public async refill(profile: UserProfile, connection: BlockchainConnection): Promise<void> {
public async refill(profile: UserProfile, connection: BlockchainConnection, codec: TxCodec): Promise<void> {
console.info(`Connected to network: ${connection.chainId()}`);
console.info(`Tokens on network: ${(await loadTokenTickers(connection)).join(", ")}`);
@ -87,7 +87,7 @@ export class Faucet {
if (jobs.length > 0) {
for (const job of jobs) {
logSendJob(job);
await send(profile, connection, job);
await send(profile, connection, codec, job);
await sleep(50);
}

View File

@ -6,10 +6,11 @@ import {
isBlockInfoPending,
SendTransaction,
TokenTicker,
TxCodec,
} from "@iov/bcp";
import { UserProfile } from "@iov/keycontrol";
import { codecImplementation } from "./codec";
import { identityToAddress } from "./addresses";
import { SendJob } from "./types";
export function identitiesOfFirstWallet(profile: UserProfile): ReadonlyArray<Identity> {
@ -21,8 +22,7 @@ export async function loadAccounts(
profile: UserProfile,
connection: BlockchainConnection,
): Promise<ReadonlyArray<Account>> {
const codec = codecImplementation();
const addresses = identitiesOfFirstWallet(profile).map(identity => codec.identityToAddress(identity));
const addresses = identitiesOfFirstWallet(profile).map(identity => identityToAddress(identity));
const out: Account[] = [];
for (const address of addresses) {
@ -55,10 +55,9 @@ export async function loadTokenTickers(
export async function send(
profile: UserProfile,
connection: BlockchainConnection,
codec: TxCodec,
job: SendJob,
): Promise<void> {
const codec = codecImplementation();
const sendWithFee = await connection.withDefaultFee<SendTransaction>({
kind: "bcp/send",
chainId: connection.chainId(),

View File

@ -1,7 +1,7 @@
import { ChainId } from "@iov/bcp";
import { HdPaths, Secp256k1HdWallet, UserProfile } from "@iov/keycontrol";
import { codecImplementation } from "./codec";
import { identityToAddress } from "./addresses";
import * as constants from "./constants";
import { debugPath } from "./hdpaths";
@ -24,7 +24,7 @@ export async function setSecretAndCreateIdentities(
// log
const role = i === 0 ? "token holder " : `distributor ${i}`;
const address = codecImplementation().identityToAddress(identity);
const address = identityToAddress(identity);
console.info(`Created ${role} (${debugPath(path)}): ${address}`);
}
}