Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Advising on UTXO Dusting based on feeRate (Frontend) #118

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/coordinator/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"@caravan/clients": "*",
"@caravan/descriptors": "^0.1.1",
"@caravan/eslint-config": "*",
"@caravan/health": "*",
"@caravan/psbt": "*",
"@caravan/typescript-config": "*",
"@caravan/wallets": "*",
Expand Down
49 changes: 49 additions & 0 deletions apps/coordinator/src/components/ScriptExplorer/DustChip.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { useSelector } from "react-redux";
import { WasteMetrics } from "@caravan/health";
import { getWalletConfig } from "../../selectors/wallet";
import { Chip } from "@mui/material";
import React from "react";

interface DustChipProps {
amountSats: number; // Type for amountSats
feeRate: number; // Type for feeRate
}

const DustChip: React.FC<DustChipProps> = ({ amountSats, feeRate }) => {
const walletConfig = useSelector(getWalletConfig);
const wasteMetrics = new WasteMetrics();
const scriptType = walletConfig.addressType;
const config = {
requiredSignerCount: walletConfig.quorum.requiredSigners,
totalSignerCount: walletConfig.quorum.totalSigners,
};
const { lowerLimit, upperLimit } = wasteMetrics.calculateDustLimits(
feeRate,
scriptType,
config,
);

let chipArgs: {
color: "error" | "success" | "warning";
label: React.ReactNode;
} = {
color: "success", // Use valid color values
label: "economical",
};

if (amountSats <= lowerLimit) {
chipArgs = {
color: "error",
label: "dust",
};
} else if (amountSats > lowerLimit && amountSats <= upperLimit) {
chipArgs = {
color: "warning",
label: "warning",
};
}

return <Chip {...chipArgs} />;
};

export default DustChip;
87 changes: 84 additions & 3 deletions apps/coordinator/src/components/ScriptExplorer/OutputsForm.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
InputAdornment,
Typography,
FormHelperText,
Slider,
} from "@mui/material";
import { Speed } from "@mui/icons-material";
import AddIcon from "@mui/icons-material/Add";
Expand All @@ -29,6 +30,9 @@ import { updateBlockchainClient } from "../../actions/clientActions";
import { MIN_SATS_PER_BYTE_FEE } from "../Wallet/constants";
import OutputEntry from "./OutputEntry";
import styles from "./styles.module.scss";
import InfoIcon from "@mui/icons-material/Info";
import { WasteMetrics } from "@caravan/health";
import { getWalletConfig } from "../../selectors/wallet";

class OutputsForm extends React.Component {
static unitLabel(label, options) {
Expand Down Expand Up @@ -56,12 +60,15 @@ class OutputsForm extends React.Component {
super(props);
this.state = {
feeRateFetchError: "",
longTermFeeEstimate: 101,
wasteAmount: 0,
};
}

componentDidMount = () => {
this.initialOutputState();
this.scrollToTitle();
this.calculateWaste();
};

scrollToTitle = () => {
Expand Down Expand Up @@ -109,7 +116,6 @@ class OutputsForm extends React.Component {
// only care to add fee if we have inputs
// which we won't have in auto-spend wallet output form
if (fee && inputs.length) total = total.plus(fee);

if (updatesComplete) {
this.outputsTotal = total;
return total.toFixed(8);
Expand Down Expand Up @@ -149,12 +155,13 @@ class OutputsForm extends React.Component {
handleAddOutput = () => {
const { addOutput } = this.props;
addOutput();
this.calculateWaste();
};

handleFeeRateChange = (event) => {
const { setFeeRate } = this.props;
let rate = event.target.value;

this.calculateWaste();
if (
rate === "" ||
Number.isNaN(parseFloat(rate, 10)) ||
Expand All @@ -167,6 +174,7 @@ class OutputsForm extends React.Component {
handleFeeChange = (event) => {
const { setFee } = this.props;
setFee(event.target.value);
this.calculateWaste();
};

handleFinalize = () => {
Expand All @@ -181,7 +189,7 @@ class OutputsForm extends React.Component {
};

getFeeEstimate = async () => {
const { getBlockchainClient, setFeeRate } = this.props;
const { getBlockchainClient, setFeeRate, onFeeEstimate } = this.props;
const client = await getBlockchainClient();
let feeEstimate;
let feeRateFetchError = "";
Expand All @@ -196,6 +204,10 @@ class OutputsForm extends React.Component {
? feeEstimate.toString()
: MIN_SATS_PER_BYTE_FEE.toString(),
);
// Call the parent's callback function with the feeEstimate
if (onFeeEstimate) {
onFeeEstimate(feeEstimate.toString());
}
this.setState({ feeRateFetchError });
}
};
Expand Down Expand Up @@ -231,6 +243,34 @@ class OutputsForm extends React.Component {
setOutputAmount(1, outputAmount);
}

handleLongTermFeeEstimateChange = (event, newValue) => {
this.setState({ longTermFeeEstimate: newValue });
this.calculateWaste();
};

calculateWaste = () => {
console.log("Called calculate waste");
const { feeRate, fee } = this.props;
const { longTermFeeEstimate } = this.state;
const weight = fee / satoshisToBitcoins(feeRate);
const wasteMetrics = new WasteMetrics();
const walletConfig = this.props.walletConfig;
const scriptType = walletConfig.addressType;
const config = {
requiredSignerCount: walletConfig.quorum.requiredSigners,
totalSignerCount: walletConfig.quorum.totalSigners,
};
const wasteAmount = wasteMetrics.spendWasteAmount(
weight,
feeRate,
scriptType,
config,
longTermFeeEstimate,
);
// console.log(fee, feeRate, weight,walletConfig, wasteAmount);
this.setState({ wasteAmount });
};

render() {
const {
feeRate,
Expand All @@ -249,6 +289,7 @@ class OutputsForm extends React.Component {
const totalMt = 7;
const actionMt = 7;
const gridSpacing = isWallet ? 10 : 1;
const { longTermFeeEstimate, wasteAmount } = this.state;
return (
<>
<Box ref={this.titleRef}>
Expand Down Expand Up @@ -414,6 +455,43 @@ class OutputsForm extends React.Component {
</Grid>
<Grid item xs={2} />
</Grid>

{wasteAmount ? (
<Grid item xs={12}>
<h3>
Waste Analysis
<Tooltip title="Waste analysis helps calculate inefficiencies in the transaction due to fees, UTXO consolidation, etc.">
<IconButton size="small" sx={{ marginLeft: 1 }}>
<InfoIcon fontSize="small" />
</IconButton>
</Tooltip>
</h3>
<Typography gutterBottom>
Spend Waste Amount (SWA): {wasteAmount.toFixed(2)} Sats
<Tooltip title="SWA represents the amount of waste in Satoshis spent during the transaction due to inefficiencies. Postive SWA means that it would be efficient to spend this transaction later when the feerate decreases. For Negative SWA, spending now could be the best decision.">
<IconButton size="small" sx={{ marginLeft: 1 }}>
<InfoIcon fontSize="small" />
</IconButton>
</Tooltip>
</Typography>
<Slider
value={longTermFeeEstimate}
min={1}
max={500}
step={1}
onChange={this.handleLongTermFeeEstimateChange}
aria-labelledby="long-term-fee-estimate-slider"
/>
<Typography id="long-term-fee-estimate-slider" gutterBottom>
Long Term Fee Estimate (L): {longTermFeeEstimate} sats/vB
<Tooltip title="L refers to the long-term estimated fee rate in Satoshis per vByte for future transactions.">
<IconButton size="small" sx={{ marginLeft: 1 }}>
<InfoIcon fontSize="small" />
</IconButton>
</Tooltip>
</Typography>
</Grid>
) : null}
</Box>

{!isWallet && (
Expand Down Expand Up @@ -473,6 +551,7 @@ OutputsForm.propTypes = {
}).isRequired,
isWallet: PropTypes.bool.isRequired,
network: PropTypes.string.isRequired,
onFeeEstimate: PropTypes.func,
outputs: PropTypes.arrayOf(
PropTypes.shape({
address: PropTypes.string,
Expand All @@ -488,6 +567,7 @@ OutputsForm.propTypes = {
signatureImporters: PropTypes.shape({}).isRequired,
updatesComplete: PropTypes.bool,
getBlockchainClient: PropTypes.func.isRequired,
walletConfig: PropTypes.object,
};

OutputsForm.defaultProps = {
Expand All @@ -504,6 +584,7 @@ function mapStateToProps(state) {
...state.client,
signatureImporters: state.spend.signatureImporters,
change: state.wallet.change,
walletConfig: getWalletConfig(state),
};
}

Expand Down
8 changes: 7 additions & 1 deletion apps/coordinator/src/components/ScriptExplorer/UTXOSet.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { OpenInNew } from "@mui/icons-material";
import BigNumber from "bignumber.js";
import { externalLink } from "utils/ExternalLink";
import Copyable from "../Copyable";
import DustChip from "./DustChip";

// Actions
import { setInputs as setInputsAction } from "../../actions/transactionActions";
Expand Down Expand Up @@ -171,7 +172,7 @@ class UTXOSet extends React.Component {
};

renderInputs = () => {
const { network, showSelection, finalizedOutputs } = this.props;
const { network, showSelection, finalizedOutputs, feeRate } = this.props;
const { localInputs } = this.state;
return localInputs.map((input, inputIndex) => {
const confirmedStyle = `${styles.utxoTxid}${
Expand Down Expand Up @@ -203,6 +204,9 @@ class UTXOSet extends React.Component {
<TableCell>
<Copyable text={satoshisToBitcoins(input.amountSats)} />
</TableCell>
<TableCell>
<DustChip amountSats={input.amountSats} feeRate={feeRate} />
</TableCell>
<TableCell>
{externalLink(
blockExplorerTransactionURL(input.txid, network),
Expand Down Expand Up @@ -247,6 +251,7 @@ class UTXOSet extends React.Component {
<TableCell>TXID</TableCell>
<TableCell>Index</TableCell>
<TableCell>Amount (BTC)</TableCell>
<TableCell>Dust Status</TableCell>
<TableCell>View</TableCell>
</TableRow>
</TableHead>
Expand Down Expand Up @@ -284,6 +289,7 @@ UTXOSet.propTypes = {
existingTransactionInputs: PropTypes.arrayOf(PropTypes.shape({})),
setSpendCheckbox: PropTypes.func,
autoSpend: PropTypes.bool.isRequired,
feeRate: PropTypes.string,
};

UTXOSet.defaultProps = {
Expand Down
4 changes: 3 additions & 1 deletion apps/coordinator/src/components/Wallet/AddressExpander.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ class AddressExpander extends React.Component {
};

expandContent = () => {
const { client, node, setSpendCheckbox } = this.props;
const { client, node, setSpendCheckbox, feeRate } = this.props;
const { utxos, balanceSats, multisig, bip32Path, spend } = node;
const { expandMode } = this.state;

Expand All @@ -242,6 +242,7 @@ class AddressExpander extends React.Component {
selectAll={spend}
node={node}
setSpendCheckbox={setSpendCheckbox}
feeRate={feeRate}
/>
</Grid>
);
Expand Down Expand Up @@ -431,6 +432,7 @@ AddressExpander.propTypes = {
requiredSigners: PropTypes.number.isRequired,
totalSigners: PropTypes.number.isRequired,
setSpendCheckbox: PropTypes.func,
feeRate: PropTypes.string,
};

AddressExpander.defaultProps = {
Expand Down
3 changes: 2 additions & 1 deletion apps/coordinator/src/components/Wallet/Node.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,12 @@ class Node extends React.Component {
};

renderAddress = () => {
const { braidNode } = this.props;
const { braidNode, feeRate } = this.props;
return (
<AddressExpander
node={braidNode}
setSpendCheckbox={this.setSpendCheckbox}
feeRate={feeRate}
/>
);
};
Expand Down
4 changes: 3 additions & 1 deletion apps/coordinator/src/components/Wallet/NodeSet.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ class NodeSet extends React.Component {

renderNodes = () => {
const { page, nodesPerPage, select } = this.state;
const { addNode, updateNode } = this.props;
const { addNode, updateNode, feeRate } = this.props;
const startingIndex = page * nodesPerPage;
const nodesRows = [];
const nodeSet = this.getNodeSet();
Expand All @@ -168,6 +168,7 @@ class NodeSet extends React.Component {
bip32Path={bip32Path}
addNode={addNode}
updateNode={updateNode}
feeRate={feeRate}
change={change}
select={select}
/>
Expand Down Expand Up @@ -276,6 +277,7 @@ NodeSet.propTypes = {
changeNodes: PropTypes.shape({}).isRequired,
addNode: PropTypes.func.isRequired,
updateNode: PropTypes.func.isRequired,
feeRate: PropTypes.string,
walletMode: PropTypes.number.isRequired,
};

Expand Down
13 changes: 11 additions & 2 deletions apps/coordinator/src/components/Wallet/WalletSpend.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,14 @@ class WalletSpend extends React.Component {
this.state = {
importPSBTDisabled: false,
importPSBTError: "",
feeEstimate: "",
};
}

handleFeeEstimate = (feeEstimate) => {
this.setState({ feeEstimate });
};

componentDidUpdate = (prevProps) => {
const { finalizedOutputs } = this.props;
if (finalizedOutputs && !prevProps.finalizedOutputs) {
Expand Down Expand Up @@ -219,9 +224,13 @@ class WalletSpend extends React.Component {
</Box>
</Grid>
<Box component="div" display={autoSpend ? "none" : "block"}>
<NodeSet addNode={addNode} updateNode={updateNode} />
<NodeSet
addNode={addNode}
updateNode={updateNode}
feeRate={feeRate}
/>
</Box>
<OutputsForm />
<OutputsForm onFeeEstimate={this.handleFeeEstimate} />
<Box mt={2}>
<Button
onClick={this.handleShowPreview}
Expand Down
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading