Remove codec parameter

This commit is contained in:
Simon Warta 2020-01-30 08:17:35 +01:00
parent 102488cb06
commit ddf2bf1c2f
10 changed files with 46 additions and 122 deletions

View File

@ -27,6 +27,7 @@
"import/no-cycle": "warn",
"simple-import-sort/sort": "warn",
"@typescript-eslint/explicit-function-return-type": ["warn", { "allowExpressions": true }],
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-empty-interface": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_", "varsIgnorePattern": "^_" }],

View File

@ -21,7 +21,7 @@ FAUCET_CREDIT_AMOUNT_COSM=10 \
FAUCET_CREDIT_AMOUNT_STAKE=5 \
FAUCET_CONCURRENCY=3 \
FAUCET_MNEMONIC="economy stock theory fatal elder harbor betray wasp final emotion task crumble siren bottom lizard educate guess current outdoor pair theory focus wife stone" \
./bin/cosmwasm-faucet start cosmwasm "http://localhost:1317"
./bin/cosmwasm-faucet start "http://localhost:1317"
```
## Usage
@ -36,12 +36,10 @@ help Shows a help text and exits
version Prints the version and exits
generate Generates a random mnemonic, shows derived faucet addresses and exits
1 Codec
2 Chain ID
1 Chain ID
start Starts the faucet
1 Codec
2 Node base URL, e.g. wss://bov.friendnet-fast.iov.one
1 Node base URL, e.g. http://localhost:1317
Environment variables
@ -99,7 +97,7 @@ DOCKER_HOST_IP=$(docker run --read-only --rm alpine ip route | awk 'NR==1 {print
-e FAUCET_CONCURRENCY \
-p 8000:8000 \
cosmwasm/faucet:manual \
start cosmwasm "http://$DOCKER_HOST_IP:1317"
start "http://$DOCKER_HOST_IP:1317"
```
### Using the faucet

View File

@ -21,7 +21,7 @@
"access": "public"
},
"scripts": {
"dev-start": "FAUCET_CREDIT_AMOUNT_COSM=10 FAUCET_CREDIT_AMOUNT_STAKE=5 FAUCET_CONCURRENCY=3 FAUCET_MNEMONIC=\"economy stock theory fatal elder harbor betray wasp final emotion task crumble siren bottom lizard educate guess current outdoor pair theory focus wife stone\" ./bin/cosmwasm-faucet start cosmwasm \"http://localhost:1317\"",
"dev-start": "FAUCET_CREDIT_AMOUNT_COSM=10 FAUCET_CREDIT_AMOUNT_STAKE=5 FAUCET_CONCURRENCY=3 FAUCET_MNEMONIC=\"economy stock theory fatal elder harbor betray wasp final emotion task crumble siren bottom lizard educate guess current outdoor pair theory focus wife stone\" ./bin/cosmwasm-faucet start \"http://localhost:1317\"",
"docs": "shx rm -rf docs && typedoc --options typedoc.js",
"format": "prettier --write --loglevel warn \"./src/**/*.ts\"",
"lint": "eslint --max-warnings 0 \"**/*.{js,ts}\" && tslint -t verbose --project .",

View File

@ -2,22 +2,21 @@ import { ChainId } from "@iov/bcp";
import { Bip39, Random } from "@iov/crypto";
import { UserProfile } from "@iov/keycontrol";
import { codecFromString } from "../codec";
import * as constants from "../constants";
import { setSecretAndCreateIdentities } from "../profile";
export async function generate(args: ReadonlyArray<string>): Promise<void> {
if (args.length < 2) {
if (args.length < 1) {
throw Error(
`Not enough arguments for action 'generate'. See '${constants.binaryName} help' or README for arguments.`,
);
}
const codecName = codecFromString(args[0]);
const chainId = args[1] as ChainId;
const chainId = args[0] as ChainId;
const mnemonic = Bip39.encode(Random.getBytes(16)).toString();
console.info(`FAUCET_MNEMONIC="${mnemonic}"`);
const profile = new UserProfile();
await setSecretAndCreateIdentities(profile, mnemonic, chainId, codecName);
await setSecretAndCreateIdentities(profile, mnemonic, chainId);
}

View File

@ -11,12 +11,10 @@ help Shows a help text and exits
version Prints the version and exits
generate Generates a random mnemonic, shows derived faucet addresses and exits
1 Codec
2 Chain ID
1 Chain ID
start Starts the faucet
1 Codec
2 Node base URL, e.g. wss://bov.friendnet-fast.iov.one
1 Node base URL, e.g. http://localhost:1317
Environment variables

View File

@ -6,12 +6,7 @@ import Koa from "koa";
import bodyParser from "koa-bodyparser";
import { creditAmount, setFractionalDigits } from "../../cashflow";
import {
codecDefaultFractionalDigits,
codecFromString,
codecImplementation,
createChainConnector,
} from "../../codec";
import { codecDefaultFractionalDigits, codecImplementation, createChainConnector } from "../../codec";
import * as constants from "../../constants";
import { logAccountsState, logSendJob } from "../../debugging";
import {
@ -35,13 +30,13 @@ function getCount(): number {
}
export async function start(args: ReadonlyArray<string>): Promise<void> {
if (args.length < 2) {
if (args.length < 1) {
throw Error(
`Not enough arguments for action 'start'. See '${constants.binaryName} help' or README for arguments.`,
);
}
const codec = codecFromString(args[0]);
const blockchainBaseUrl: string = args[1];
const blockchainBaseUrl = args[0];
const port = constants.port;
@ -51,13 +46,13 @@ export async function start(args: ReadonlyArray<string>): Promise<void> {
}
const signer = new MultiChainSigner(profile);
console.info(`Connecting to blockchain ${blockchainBaseUrl} ...`);
const connection = (await signer.addChain(createChainConnector(codec, blockchainBaseUrl))).connection;
const connection = (await signer.addChain(createChainConnector(blockchainBaseUrl))).connection;
const connectedChainId = connection.chainId();
console.info(`Connected to network: ${connectedChainId}`);
setFractionalDigits(codecDefaultFractionalDigits(codec));
await setSecretAndCreateIdentities(profile, constants.mnemonic, connectedChainId, codec);
setFractionalDigits(codecDefaultFractionalDigits());
await setSecretAndCreateIdentities(profile, constants.mnemonic, connectedChainId);
const chainTokens = await tokenTickersOfFirstChain(signer);
console.info("Chain tokens:", chainTokens);
@ -120,7 +115,7 @@ export async function start(args: ReadonlyArray<string>): Promise<void> {
const requestBody = (context.request as any).body;
const { address, ticker } = RequestParser.parseCreditBody(requestBody);
if (!codecImplementation(codec).isValidAddress(address)) {
if (!codecImplementation().isValidAddress(address)) {
throw new HttpError(400, "Address is not in the expected format for this chain.");
}

View File

@ -1,14 +1 @@
import { Codec, codecFromString } from "./codec";
describe("Codec", () => {
it("can convert string to codec", () => {
expect(codecFromString("cosmwasm")).toEqual(Codec.CosmWasm);
expect(() => codecFromString("")).toThrowError(/not supported/i);
expect(() => codecFromString("lisk")).toThrowError(/not supported/i);
expect(() => codecFromString("bns")).toThrowError(/not supported/i);
expect(() => codecFromString("abc")).toThrowError(/not supported/i);
expect(() => codecFromString("LISK")).toThrowError(/not supported/i);
expect(() => codecFromString("CosmWasm")).toThrowError(/not supported/i);
});
});
describe("codec", () => {});

View File

@ -1,66 +1,28 @@
import { createCosmWasmConnector, TokenInfo } from "@cosmwasm/bcp";
import { ChainConnector, TokenTicker, TxCodec } from "@iov/bcp";
import { Slip10RawIndex } from "@iov/crypto";
import { HdPaths } from "@iov/keycontrol";
export const enum Codec {
CosmWasm,
export function createChainConnector(url: string): ChainConnector {
const tokens: readonly TokenInfo[] = [
{
fractionalDigits: 6,
tokenName: "Fee Token",
tokenTicker: "COSM" as TokenTicker,
denom: "cosm",
},
{
fractionalDigits: 6,
tokenName: "Staking Token",
tokenTicker: "STAKE" as TokenTicker,
denom: "stake",
},
];
return createCosmWasmConnector(url, "cosmos", tokens);
}
export function codecFromString(input: string): Codec {
switch (input) {
case "cosmwasm":
return Codec.CosmWasm;
default:
throw new Error(`Codec '${input}' not supported`);
}
export function codecImplementation(): TxCodec {
return createChainConnector("unused dummy url").codec;
}
export function createPathBuilderForCodec(codec: Codec): (derivation: number) => readonly Slip10RawIndex[] {
const pathBuilder = (accountIndex: number): readonly Slip10RawIndex[] => {
switch (codec) {
case Codec.CosmWasm:
return HdPaths.cosmos(accountIndex);
default:
throw new Error("No path builder for this codec found");
}
};
return pathBuilder;
}
export function createChainConnector(codec: Codec, url: string): ChainConnector {
switch (codec) {
case Codec.CosmWasm: {
const tokens: readonly TokenInfo[] = [
{
fractionalDigits: 6,
tokenName: "Fee Token",
tokenTicker: "COSM" as TokenTicker,
denom: "cosm",
},
{
fractionalDigits: 6,
tokenName: "Staking Token",
tokenTicker: "STAKE" as TokenTicker,
denom: "stake",
},
];
return createCosmWasmConnector(url, "cosmos", tokens);
}
default:
throw new Error("No connector for this codec found");
}
}
export function codecImplementation(codec: Codec): TxCodec {
return createChainConnector(codec, "unused dummy url").codec;
}
export function codecDefaultFractionalDigits(codec: Codec): number {
switch (codec) {
case Codec.CosmWasm:
return 6;
default:
throw new Error("Unknown codec");
}
export function codecDefaultFractionalDigits(): number {
return 6;
}

View File

@ -1,12 +0,0 @@
import { Secp256k1HdWallet, Wallet } from "@iov/keycontrol";
import { Codec } from "./codec";
export function createWalletForCodec(input: Codec, mnemonic: string): Wallet {
switch (input) {
case Codec.CosmWasm:
return Secp256k1HdWallet.fromMnemonic(mnemonic);
default:
throw new Error(`Codec '${input}' not supported`);
}
}

View File

@ -1,34 +1,30 @@
import { ChainId } from "@iov/bcp";
import { UserProfile } from "@iov/keycontrol";
import { HdPaths, Secp256k1HdWallet, UserProfile } from "@iov/keycontrol";
import { Codec, codecImplementation, createPathBuilderForCodec } from "./codec";
import { codecImplementation } from "./codec";
import * as constants from "./constants";
import { createWalletForCodec } from "./crypto";
import { debugPath } from "./hdpaths";
export async function setSecretAndCreateIdentities(
profile: UserProfile,
mnemonic: string,
chainId: ChainId,
codecName: Codec,
): Promise<void> {
if (profile.wallets.value.length !== 0) {
throw new Error("Profile already contains wallets");
}
const wallet = profile.addWallet(createWalletForCodec(codecName, mnemonic));
const pathBuilder = createPathBuilderForCodec(codecName);
const wallet = profile.addWallet(Secp256k1HdWallet.fromMnemonic(mnemonic));
// first account is the token holder
const numberOfIdentities = 1 + constants.concurrency;
for (let i = 0; i < numberOfIdentities; i++) {
// create
const path = pathBuilder(i);
const path = HdPaths.cosmos(i);
const identity = await profile.createIdentity(wallet.id, chainId, path);
// log
const role = i === 0 ? "token holder " : `distributor ${i}`;
const address = codecImplementation(codecName).identityToAddress(identity);
const address = codecImplementation().identityToAddress(identity);
console.info(`Created ${role} (${debugPath(path)}): ${address}`);
}
}