Skip to content

Commit

Permalink
feat: claim fees ui (#895)
Browse files Browse the repository at this point in the history
Description
---
Add claim fees button to the dan wallet ui.

Motivation and Context
---

How Has This Been Tested?
---
I've started dan testing with 1 VN. After I had account I started a
second VN with the account public key as a claim fee public key for the
2nd VN. I mined 20 blocks (to get it into the committee). I did couple
of transaction and I checked that the VN has some fees to be claimed.
Mined another 10 blocks to switch epoch. Pressed the button for claiming
fees, filled the VN public key, selected the correct account and claimed
the fees.

What process can a PR reviewer use to test or verify this change?
---


Breaking Changes
---

- [x] None
- [ ] Requires data directory to be deleted
- [ ] Other - Please specify
  • Loading branch information
Cifko authored Jan 24, 2024
1 parent 94c3e77 commit b3a5e2e
Show file tree
Hide file tree
Showing 10 changed files with 340 additions and 7 deletions.
4 changes: 4 additions & 0 deletions applications/tari_dan_wallet_cli/src/command/validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ pub struct ClaimFeesArgs {
pub epoch: u64,
#[clap(long)]
pub max_fee: Option<u32>,
#[clap(long)]
pub dry_run: bool,
}

#[derive(Debug, Args, Clone)]
Expand Down Expand Up @@ -77,6 +79,7 @@ pub async fn handle_claim_validator_fees(
validator_public_key,
epoch,
max_fee,
dry_run,
} = args;

println!("Submitting claim validator fees transaction...");
Expand All @@ -90,6 +93,7 @@ pub async fn handle_claim_validator_fees(
validator_public_key: PublicKey::from_canonical_bytes(validator_public_key.into_inner().as_bytes())
.map_err(anyhow::Error::msg)?,
epoch: Epoch(epoch),
dry_run,
})
.await?;

Expand Down
17 changes: 17 additions & 0 deletions applications/tari_dan_wallet_daemon/src/handlers/validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,23 @@ pub async fn handle_claim_validator_fees(

// send the transaction
let required_inputs = inputs.into_iter().map(Into::into).collect();

if req.dry_run {
let result = sdk
.transaction_api()
.submit_dry_run_transaction(transaction, required_inputs)
.await?;
let execute_result = result.result.into_execute_result().unwrap();
return Ok(ClaimValidatorFeesResponse {
transaction_id: result.transaction_id,
fee: execute_result
.fee_receipt
.clone()
.map(|fee_receipt| fee_receipt.total_fees_paid)
.unwrap_or_default(),
result: execute_result.finalize,
});
}
let tx_id = sdk
.transaction_api()
.submit_transaction(transaction, required_inputs)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { useAccountsCreateFreeTestCoins } from "../../../api/hooks/useAccounts";
import ClaimBurn from "./ClaimBurn";
import useAccountStore from "../../../store/accountStore";
import SendMoney from "./SendMoney";
import ClaimFees from "./ClaimFees";

function ActionMenu() {
const { mutate } = useAccountsCreateFreeTestCoins();
Expand All @@ -50,6 +51,7 @@ function ActionMenu() {
}}
>
<SendMoney />
<ClaimFees />
<Button variant="outlined" onClick={onClaimFreeCoins}>
Claim Free Testnet Coins
</Button>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
// Copyright 2022. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import { useState } from "react";
import { Form } from "react-router-dom";
import Button from "@mui/material/Button";
import CheckBox from "@mui/material/Checkbox";
import TextField from "@mui/material/TextField";
import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import FormControlLabel from "@mui/material/FormControlLabel";
import Box from "@mui/material/Box";
import { useAccountsList, useAccountsTransfer } from "../../../api/hooks/useAccounts";
import { useTheme } from "@mui/material/styles";
import useAccountStore from "../../../store/accountStore";
import { FormControl, InputLabel, MenuItem, Select, SelectChangeEvent } from "@mui/material";
import { claimFees } from "../../../utils/json_rpc";
import { useKeysList } from "../../../api/hooks/useKeys";

export default function ClaimFees() {
const [open, setOpen] = useState(false);
const [disabled, setDisabled] = useState(false);
const [estimatedFee, setEstimatedFee] = useState(0);
const [claimFeesFormState, setClaimFeesFormState] = useState({
account: "",
fee: "",
validatorNodePublicKey: "",
epoch: "",
key: "",
});

const { data: dataAccountsList } = useAccountsList(0, 10);
const { data: dataKeysList } = useKeysList();
const { setPopup } = useAccountStore();

const theme = useTheme();

const isFormFilled = () => {
if (claimFeesFormState.validatorNodePublicKey.length !== 64) {
return false;
}
return (
claimFeesFormState.account !== "" &&
claimFeesFormState.validatorNodePublicKey !== "" &&
claimFeesFormState.epoch !== ""
);
};

const is_filled = isFormFilled();

const onClaimFeesKeyChange = (e: SelectChangeEvent<string>) => {
let key = e.target.value;
let key_index = dataKeysList.keys.indexOf(key);
let account = claimFeesFormState.account;
let selected_account = dataAccountsList.accounts.find((account: any) => account.account.key_index === key_index);
let new_account_name;
account = selected_account.account.name;
new_account_name = false;
setClaimFeesFormState({
...claimFeesFormState,
key: key,
account: account,
});
};

const onEpochChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (/^[0-9]*$/.test(e.target.value)) {
setEstimatedFee(0);
setClaimFeesFormState({
...claimFeesFormState,
[e.target.name]: e.target.value,
});
}
};

const onClaimBurnAccountNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setEstimatedFee(0);
setClaimFeesFormState({
...claimFeesFormState,
[e.target.name]: e.target.value,
});
};

const onPublicKeyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (/^[0-9a-fA-F]*$/.test(e.target.value)) {
setClaimFeesFormState({
...claimFeesFormState,
[e.target.name]: e.target.value,
});
}
setEstimatedFee(0);
};

const onClaim = async () => {
if (claimFeesFormState.account) {
setDisabled(true);
claimFees(
claimFeesFormState.account,
3000,
claimFeesFormState.validatorNodePublicKey,
parseInt(claimFeesFormState.epoch),
estimatedFee == 0,
)
.then((resp) => {
if (estimatedFee == 0) {
setEstimatedFee(resp.fee);
} else {
setEstimatedFee(0);
setOpen(false);
setPopup({ title: "Claim successful", error: false });
setClaimFeesFormState({
account: "",
fee: "",
validatorNodePublicKey: "",
epoch: "",
key: "",
});
}
})
.catch((e) => {
setPopup({ title: "Claim failed", error: true, message: e.message });
})
.finally(() => {
setDisabled(false);
});
}
};

const handleClickOpen = () => {
setOpen(true);
};

const handleClose = () => {
setOpen(false);
};

const formattedKey = (key: any[]) => {
let account = dataAccountsList.accounts.find((account: any) => account.account.key_index === +key[0]);
if (account === undefined) {
return null;
return (
<div>
<b>{key[0]}</b> {key[1]}
</div>
);
}
return (
<div>
<b>{key[0]}</b> {key[1]}
<br></br>Account <i>{account.account.name}</i>
</div>
);
};

return (
<div>
<Button variant="outlined" onClick={handleClickOpen}>
Claim Fees
</Button>
<Dialog open={open} onClose={handleClose}>
<DialogTitle>Claim Fees</DialogTitle>
<DialogContent className="dialog-content">
<Form onSubmit={onClaim} className="flex-container-vertical" style={{ paddingTop: theme.spacing(1) }}>
<FormControl>
<InputLabel id="key">Key</InputLabel>
<Select
labelId="key"
name="key"
label="Key"
value={claimFeesFormState.key}
onChange={onClaimFeesKeyChange}
style={{ flexGrow: 1, minWidth: "200px" }}
disabled={disabled}
>
{dataKeysList?.keys?.map((key: any) => (
<MenuItem key={key} value={key}>
{formattedKey(key)}
</MenuItem>
))}
</Select>
</FormControl>
<TextField
name="account"
label="Account Name"
value={claimFeesFormState.account}
onChange={onClaimBurnAccountNameChange}
style={{ flexGrow: 1 }}
disabled={true}
></TextField>
<TextField
name="fee"
label="Fee"
value={estimatedFee || "Press fee estimate to calculate"}
style={{ flexGrow: 1 }}
InputProps={{ readOnly: true }}
disabled={disabled}
/>
<TextField
name="validatorNodePublicKey"
label="Validator Node Public Key"
value={claimFeesFormState.validatorNodePublicKey}
onChange={onPublicKeyChange}
style={{ flexGrow: 1 }}
disabled={disabled}
/>
<TextField
name="epoch"
label="Epoch"
value={claimFeesFormState.epoch}
style={{ flexGrow: 1 }}
onChange={onEpochChange}
disabled={disabled}
/>
<Box
className="flex-container"
style={{
justifyContent: "flex-end",
}}
>
<Button variant="outlined" onClick={handleClose} disabled={disabled}>
Cancel
</Button>
<Button variant="contained" type="submit" disabled={disabled || !is_filled}>
{estimatedFee ? "Claim" : "Estimate fee"}
</Button>
</Box>
</Form>
</DialogContent>
</Dialog>
</div>
);
}
11 changes: 11 additions & 0 deletions applications/tari_dan_wallet_web_ui/src/utils/json_rpc.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,14 @@ export const accountNFTsList = (offset: number, limit: number) => jsonRpc("nfts.
// settings
export const getSettings = () => jsonRpc("settings.get", []);
export const setSettings = (settings: any) => jsonRpc("settings.set", settings);

// validators
export const getFeeSummary = (validatorPublicKey: string, minEpoch: number, maxEpoch: number) =>
jsonRpc("validators.get_fee_summary", [validatorPublicKey, minEpoch, maxEpoch]);
export const claimFees = (
account: string,
maxFee: number,
validatorPublicKey: string,
epoch: number,
isDryRun: boolean,
) => jsonRpc("validators.claim_fees", [account, maxFee, validatorPublicKey, epoch, isDryRun]);
4 changes: 3 additions & 1 deletion applications/tari_indexer/src/dry_run/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use tari_dan_app_utilities::transaction_executor::TransactionProcessorError;
use tari_dan_common_types::{Epoch, SubstateAddress};
use tari_engine_types::substate::SubstateId;
use tari_epoch_manager::EpochManagerError;
use tari_indexer_lib::transaction_autofiller::TransactionAutofillerError;
use tari_indexer_lib::{error::IndexerError, transaction_autofiller::TransactionAutofillerError};
use tari_rpc_framework::RpcStatus;
use thiserror::Error;

Expand All @@ -51,4 +51,6 @@ pub enum DryRunTransactionProcessorError {
err_count: usize,
committee_size: usize,
},
#[error("Indexer error : {0}")]
IndexerError(#[from] IndexerError),
}
Loading

0 comments on commit b3a5e2e

Please sign in to comment.