Skip to content
This repository has been archived by the owner on Jun 11, 2024. It is now read-only.

Commit

Permalink
♻️ Update plugin to follow new application architecture (#6835)
Browse files Browse the repository at this point in the history
  • Loading branch information
shuse2 committed Oct 18, 2021
1 parent edb7409 commit 795aafe
Show file tree
Hide file tree
Showing 30 changed files with 630 additions and 541 deletions.
1 change: 0 additions & 1 deletion elements/lisk-elements/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,3 @@ export * as validator from '@liskhq/lisk-validator';
export * as codec from '@liskhq/lisk-codec';
export * as db from '@liskhq/lisk-db';
export * as chain from '@liskhq/lisk-chain';
export * as genesis from '@liskhq/lisk-genesis';
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ const NodeInfoDialog: React.FC<NodeInfoDialogProps> = props => {
<Text>{fee.moduleID}</Text>
</Grid>
<Grid xs={4}>
<Text>{fee.assetID}</Text>
<Text>{fee.commandID}</Text>
</Grid>
<Grid xs={4}>
<Text>{fee.baseFee}</Text>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const SendTransactionWidget: React.FC<WidgetProps> = props => {
const [validAsset, setValidAsset] = React.useState(true);
const assets = props.modules
.map(m =>
m.transactionAssets.map(t => ({
m.commands.map(t => ({
label: `${m.name}:${t.name}`,
value: `${m.name}:${t.name}`,
})),
Expand All @@ -42,17 +42,17 @@ const SendTransactionWidget: React.FC<WidgetProps> = props => {
const handleSubmit = () => {
const assetSelectedValue = selectedAsset ? selectedAsset.value : '';
const moduleName = assetSelectedValue.split(':').shift();
const assetName = assetSelectedValue.split(':').slice(1).join(':');
const commandName = assetSelectedValue.split(':').slice(1).join(':');
let moduleID: number | undefined;
let assetID: number | undefined;
let commandID: number | undefined;

for (const m of props.modules) {
if (m.name === moduleName) {
moduleID = m.id;

for (const t of m.transactionAssets) {
if (t.name === assetName) {
assetID = t.id;
for (const t of m.commands) {
if (t.name === commandName) {
commandID = t.id;

break;
}
Expand All @@ -62,12 +62,12 @@ const SendTransactionWidget: React.FC<WidgetProps> = props => {
}
}

if (moduleID !== undefined && assetID !== undefined) {
if (moduleID !== undefined && commandID !== undefined) {
props.onSubmit({
moduleID,
assetID,
commandID,
passphrase,
asset: JSON.parse(asset) as Record<string, unknown>,
params: JSON.parse(asset) as Record<string, unknown>,
});
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ interface WidgetProps {
const getModuleAsset = (
nodeInfo: NodeInfo | undefined,
moduleID: number,
assetID: number,
commandID: number,
): string => {
if (!nodeInfo) {
return 'unknown';
Expand All @@ -37,7 +37,7 @@ const getModuleAsset = (
if (!registeredModule) {
return 'unknown';
}
const registeredAsset = registeredModule.transactionAssets?.find(ta => ta.id === assetID);
const registeredAsset = registeredModule.commands?.find(ta => ta.id === commandID);
if (!registeredAsset) {
return `${registeredModule.name}:unknown`;
}
Expand Down Expand Up @@ -83,7 +83,7 @@ const TransactionWidget: React.FC<WidgetProps> = props => {
</td>
<td>
<Text>
{getModuleAsset(props.nodeInfo, transaction.moduleID, transaction.assetID)}
{getModuleAsset(props.nodeInfo, transaction.moduleID, transaction.commandID)}
</Text>
</td>
<td>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,16 +85,6 @@ const callAndProcessActions = async (
let result = (await client.invoke(action, params)) as unknown;

switch (action) {
case 'app:getAccount':
result = client.account.toJSON(client.account.decode(result as string));
break;

case 'app:getAccounts':
result = (result as string[]).map(account =>
client.account.toJSON(client.account.decode(account)),
);
break;

case 'app:getLastBlock':
case 'app:getBlockByID':
case 'app:getBlockByHeight':
Expand Down Expand Up @@ -289,29 +279,29 @@ const MainPage: React.FC = () => {
const { publicKey, address } = cryptography.getAddressAndPublicKeyFromPassphrase(
data.passphrase,
);
const assetSchema = getClient().schemas.transactionsAssets.find(
a => a.moduleID === data.moduleID && a.assetID === data.assetID,
const assetSchema = getClient().schemas.commands.find(
a => a.moduleID === data.moduleID && a.commandID === data.commandID,
);
if (!assetSchema) {
throw new Error(`ModuleID: ${data.moduleID} AssetID: ${data.assetID} is not registered`);
throw new Error(`ModuleID: ${data.moduleID} AssetID: ${data.commandID} is not registered`);
}
const assetObject = codec.codec.fromJSON<Record<string, unknown>>(
assetSchema.schema,
data.asset,
data.params,
);
const sender = await getClient().account.get(address);
const sender = await getClient().invoke<{ nonce: string }>('auth_getAuthData', { address: address.toString('hex') });
const fee = getClient().transaction.computeMinFee({
moduleID: data.moduleID,
assetID: data.assetID,
commandID: data.commandID,
asset: assetObject,
senderPublicKey: publicKey,
nonce: BigInt((sender.sequence as { nonce: bigint }).nonce),
nonce: BigInt(sender.nonce),
});
const transaction = await getClient().transaction.create(
{
moduleID: data.moduleID,
assetID: data.assetID,
asset: assetObject,
commandID: data.commandID,
params: assetObject,
senderPublicKey: publicKey,
fee,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export interface GenesisConfig {
readonly minFeePerByte: number;
readonly baseFees: {
readonly moduleID: number;
readonly assetID: number;
readonly commandID: number;
readonly baseFee: string;
}[];
}
Expand All @@ -53,17 +53,16 @@ export interface NodeInfo {

export interface Fee {
moduleId: number;
assetId: number;
commandId: number;
baseFee: number;
}

export interface RegisteredModule {
id: number;
name: string;
actions: string[];
events: string[];
reducers: string[];
transactionAssets: {
actions: string[];
commands: {
id: number;
name: string;
}[];
Expand All @@ -84,7 +83,7 @@ export interface Transaction {
id: string;
senderPublicKey: string;
moduleID: number;
assetID: number;
commandID: number;
fee: number;
}

Expand All @@ -95,8 +94,8 @@ export interface EventData {

export interface SendTransactionOptions {
moduleID: number;
assetID: number;
asset: Record<string, unknown>;
commandID: number;
params: Record<string, unknown>;
passphrase: string;
}

Expand Down
123 changes: 123 additions & 0 deletions framework-plugins/lisk-framework-faucet-plugin/src/plugin/endpoint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
* Copyright © 2021 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/

import axios from 'axios';
import {
decryptPassphraseWithPassword,
getAddressAndPublicKeyFromPassphrase,
parseEncryptedPassphrase,
} from '@liskhq/lisk-cryptography';
import { LiskValidationError, validator } from '@liskhq/lisk-validator';
import { BasePluginEndpoint, PluginEndpointContext } from 'lisk-framework';
import { convertLSKToBeddows } from '@liskhq/lisk-transactions';
import { APIClient } from '@liskhq/lisk-api-client';
import { authorizeParamsSchema, fundParamsSchema } from './schemas';
import { FaucetPluginConfig, State } from './types';

export class Endpoint extends BasePluginEndpoint {
private _state: State = { publicKey: undefined, passphrase: undefined };
private _client!: APIClient;
private _config!: FaucetPluginConfig;

public init(state: State, apiClient: APIClient, config: FaucetPluginConfig) {
this._state = state;
this._client = apiClient;
this._config = config;
}
// eslint-disable-next-line @typescript-eslint/require-await
public async authorize(context: PluginEndpointContext): Promise<{ result: string }> {
const errors = validator.validate(authorizeParamsSchema, context.params);

if (errors.length) {
throw new LiskValidationError(errors);
}

const { enable, password } = context.params;

try {
const parsedEncryptedPassphrase = parseEncryptedPassphrase(this._config.encryptedPassphrase);

const passphrase = decryptPassphraseWithPassword(
parsedEncryptedPassphrase,
password as string,
);

const { publicKey } = getAddressAndPublicKeyFromPassphrase(passphrase);

this._state.publicKey = enable ? publicKey : undefined;
this._state.passphrase = enable ? passphrase : undefined;
const changedState = enable ? 'enabled' : 'disabled';

return {
result: `Successfully ${changedState} the faucet.`,
};
} catch (error) {
throw new Error('Password given is not valid.');
}
}

public async fundTokens(context: PluginEndpointContext): Promise<{ result: string }> {
const errors = validator.validate(fundParamsSchema, context.params);
const { address, token } = context.params;

if (errors.length) {
throw new LiskValidationError(errors);
}

if (!this._state.publicKey || !this._state.passphrase) {
throw new Error('Faucet is not enabled.');
}

const captchaResult = await axios({
method: 'post',
url: 'https://www.google.com/recaptcha/api/siteverify',
params: {
secret: this._config.captchaSecretkey,
response: token,
},
});

// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (!captchaResult?.data?.success) {
throw new Error('Captcha response was invalid.');
}

await this._transferFunds(address as string);

return {
result: `Successfully funded account at address: ${address as string}.`,
};
}

private async _transferFunds(address: string): Promise<void> {
const transferTransactionParams = {
amount: BigInt(convertLSKToBeddows(this._config.amount)),
recipientAddress: Buffer.from(address, 'hex'),
data: '',
};

const transaction = await this._client.transaction.create(
{
moduleID: 2,
commandID: 0,
senderPublicKey: this._state.publicKey as Buffer,
fee: BigInt(convertLSKToBeddows(this._config.fee)), // TODO: The static fee should be replaced by fee estimation calculation
params: transferTransactionParams,
},
this._state.passphrase as string,
);

await this._client.transaction.send(transaction);
}
}
Loading

0 comments on commit 795aafe

Please sign in to comment.