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

Release/fees upgrade #5342

Merged
merged 9 commits into from
May 2, 2024
Merged
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
Binary file added public/assets/avatars/stx20-avatar-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,74 @@ const demoUtxos = [
{ value: 909 },
];

function generate10kSpendWithDummyUtxoSet(recipient: string) {
return determineUtxosForSpend({
utxos: demoUtxos as any,
amount: 10_000,
feeRate: 20,
recipient,
});
}

describe(determineUtxosForSpend.name, () => {
function generate10kSpendWithTestData(recipient: string) {
return determineUtxosForSpend({
utxos: demoUtxos as any,
amount: 10_000,
feeRate: 20,
recipient,
describe('Estimated size', () => {
test('that Native Segwit, 1 input 2 outputs weighs 140 vBytes', () => {
const estimation = determineUtxosForSpend({
utxos: [{ value: 50_000 }] as any[],
amount: 40_000,
recipient: 'tb1qt28eagxcl9gvhq2rpj5slg7dwgxae2dn2hk93m',
feeRate: 20,
});
console.log(estimation);
expect(estimation.txVBytes).toBeGreaterThan(140);
expect(estimation.txVBytes).toBeLessThan(142);
});

test('that Native Segwit, 2 input 2 outputs weighs 200vBytes', () => {
const estimation = determineUtxosForSpend({
utxos: [{ value: 50_000 }, { value: 50_000 }] as any[],
amount: 60_000,
recipient: 'tb1qt28eagxcl9gvhq2rpj5slg7dwgxae2dn2hk93m',
feeRate: 20,
});
console.log(estimation);
expect(estimation.txVBytes).toBeGreaterThan(208);
expect(estimation.txVBytes).toBeLessThan(209);
});
}

describe('sorting algorithm (biggest first and no dust)', () => {
test('that Native Segwit, 10 input 2 outputs weighs 200vBytes', () => {
const estimation = determineUtxosForSpend({
utxos: [
{ value: 20_000 },
{ value: 20_000 },
{ value: 10_000 },
{ value: 10_000 },
{ value: 10_000 },
{ value: 10_000 },
{ value: 10_000 },
{ value: 10_000 },
{ value: 10_000 },
{ value: 10_000 },
] as any[],
amount: 100_000,
recipient: 'tb1qt28eagxcl9gvhq2rpj5slg7dwgxae2dn2hk93m',
feeRate: 20,
});
expect(estimation.txVBytes).toBeGreaterThan(750);
expect(estimation.txVBytes).toBeLessThan(751);
});
});

describe('sorting algorithm', () => {
test('that it filters out dust utxos', () => {
const result = generate10kSpendWithTestData('tb1qt28eagxcl9gvhq2rpj5slg7dwgxae2dn2hk93m');
const result = generate10kSpendWithDummyUtxoSet('tb1qt28eagxcl9gvhq2rpj5slg7dwgxae2dn2hk93m');
console.log(result);
const hasDust = result.filteredUtxos.some(utxo => utxo.value <= BTC_P2WPKH_DUST_AMOUNT);
expect(hasDust).toBeFalsy();
});

test('that it sorts utxos in decending order', () => {
const result = generate10kSpendWithTestData('tb1qt28eagxcl9gvhq2rpj5slg7dwgxae2dn2hk93m');
const result = generate10kSpendWithDummyUtxoSet('tb1qt28eagxcl9gvhq2rpj5slg7dwgxae2dn2hk93m');
result.inputs.forEach((u, i) => {
const nextUtxo = result.inputs[i + 1];
if (!nextUtxo) return;
Expand All @@ -50,38 +99,38 @@ describe(determineUtxosForSpend.name, () => {

test('that it accepts a wrapped segwit address', () =>
expect(() =>
generate10kSpendWithTestData('33SVjoCHJovrXxjDKLFSXo1h3t5KgkPzfH')
generate10kSpendWithDummyUtxoSet('33SVjoCHJovrXxjDKLFSXo1h3t5KgkPzfH')
).not.toThrowError());

test('that it accepts a legacy addresses', () =>
expect(() =>
generate10kSpendWithTestData('15PyZveQd28E2SHZu2ugkWZBp6iER41vXj')
generate10kSpendWithDummyUtxoSet('15PyZveQd28E2SHZu2ugkWZBp6iER41vXj')
).not.toThrowError());

test('that it throws an error with non-legit address', () => {
expect(() =>
generate10kSpendWithTestData('whoop-de-da-boop-da-de-not-a-bitcoin-address')
generate10kSpendWithDummyUtxoSet('whoop-de-da-boop-da-de-not-a-bitcoin-address')
).toThrowError();
});

test('that given a set of utxos, legacy is more expensive', () => {
const legacy = generate10kSpendWithTestData('15PyZveQd28E2SHZu2ugkWZBp6iER41vXj');
const segwit = generate10kSpendWithTestData('33SVjoCHJovrXxjDKLFSXo1h3t5KgkPzfH');
const legacy = generate10kSpendWithDummyUtxoSet('15PyZveQd28E2SHZu2ugkWZBp6iER41vXj');
const segwit = generate10kSpendWithDummyUtxoSet('33SVjoCHJovrXxjDKLFSXo1h3t5KgkPzfH');
expect(legacy.fee).toBeGreaterThan(segwit.fee);
});

test('that given a set of utxos, wrapped segwit is more expensive than native', () => {
const segwit = generate10kSpendWithTestData('33SVjoCHJovrXxjDKLFSXo1h3t5KgkPzfH');
const native = generate10kSpendWithTestData('tb1qt28eagxcl9gvhq2rpj5slg7dwgxae2dn2hk93m');
const segwit = generate10kSpendWithDummyUtxoSet('33SVjoCHJovrXxjDKLFSXo1h3t5KgkPzfH');
const native = generate10kSpendWithDummyUtxoSet('tb1qt28eagxcl9gvhq2rpj5slg7dwgxae2dn2hk93m');
expect(segwit.fee).toBeGreaterThan(native.fee);
});

test('that given a set of utxos, taproot is more expensive than native segwit', () => {
// Non-obvious behaviour.
// P2TR outputs = 34 vBytes
// P2WPKH outputs = 22 vBytes
const native = generate10kSpendWithTestData('tb1qt28eagxcl9gvhq2rpj5slg7dwgxae2dn2hk93m');
const taproot = generate10kSpendWithTestData(
const native = generate10kSpendWithDummyUtxoSet('tb1qt28eagxcl9gvhq2rpj5slg7dwgxae2dn2hk93m');
const taproot = generate10kSpendWithDummyUtxoSet(
'tb1parwmj7533de3k2fw2kntyqacspvhm67qnjcmpqnnpfvzu05l69nsczdywd'
);
expect(taproot.fee).toBeGreaterThan(native.fee);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import BigNumber from 'bignumber.js';
import { validate } from 'bitcoin-address-validation';

import type { RpcSendTransferRecipient } from '@shared/rpc/methods/send-transfer';

import { sumNumbers } from '@app/common/math/helpers';
import { UtxoResponseItem } from '@app/query/bitcoin/bitcoin-client';

import {
filterUneconomicalUtxos,
filterUneconomicalUtxosMultipleRecipients,
getSizeInfo,
getBitcoinTxSizeEstimation,
getSizeInfoMultipleRecipients,
} from '../utils';

Expand All @@ -33,9 +35,9 @@ export function determineUtxosForSpendAll({
if (!validate(recipient)) throw new Error('Cannot calculate spend of invalid address type');
const filteredUtxos = filterUneconomicalUtxos({ utxos, feeRate, address: recipient });

const sizeInfo = getSizeInfo({
inputLength: filteredUtxos.length,
outputLength: 1,
const sizeInfo = getBitcoinTxSizeEstimation({
inputCount: filteredUtxos.length,
outputCount: 1,
recipient,
});

Expand All @@ -52,6 +54,10 @@ export function determineUtxosForSpendAll({
};
}

function getUtxoTotal(utxos: UtxoResponseItem[]) {
return sumNumbers(utxos.map(utxo => utxo.value));
}

export function determineUtxosForSpend({
amount,
feeRate,
Expand All @@ -60,47 +66,59 @@ export function determineUtxosForSpend({
}: DetermineUtxosForSpendArgs) {
if (!validate(recipient)) throw new Error('Cannot calculate spend of invalid address type');

const orderedUtxos = utxos.sort((a, b) => b.value - a.value);

const filteredUtxos = filterUneconomicalUtxos({
utxos: orderedUtxos,
const filteredUtxos: UtxoResponseItem[] = filterUneconomicalUtxos({
utxos: utxos.sort((a, b) => b.value - a.value),
feeRate,
address: recipient,
});

const neededUtxos = [];
let sum = 0n;
let sizeInfo = null;
if (!filteredUtxos.length) throw new InsufficientFundsError();

for (const utxo of filteredUtxos) {
sizeInfo = getSizeInfo({
inputLength: neededUtxos.length,
outputLength: 2,
// Prepopulate with first UTXO, at least one is needed
const neededUtxos: UtxoResponseItem[] = [filteredUtxos[0]];

function estimateTransactionSize() {
return getBitcoinTxSizeEstimation({
inputCount: neededUtxos.length,
outputCount: 2,
recipient,
});
if (sum >= BigInt(amount) + BigInt(Math.ceil(sizeInfo.txVBytes * feeRate))) break;
}

sum += BigInt(utxo.value);
neededUtxos.push(utxo);
function hasSufficientUtxosForTx() {
const txEstimation = estimateTransactionSize();
const neededAmount = new BigNumber(txEstimation.txVBytes * feeRate).plus(amount);
return getUtxoTotal(neededUtxos).isGreaterThanOrEqualTo(neededAmount);
}

if (!sizeInfo) throw new InsufficientFundsError();
function getRemainingUnspentUtxos() {
return filteredUtxos.filter(utxo => !neededUtxos.includes(utxo));
}

const fee = Math.ceil(sizeInfo.txVBytes * feeRate);
while (!hasSufficientUtxosForTx()) {
const [nextUtxo] = getRemainingUnspentUtxos();
if (!nextUtxo) throw new InsufficientFundsError();
neededUtxos.push(nextUtxo);
}

const fee = Math.ceil(
new BigNumber(estimateTransactionSize().txVBytes).multipliedBy(feeRate).toNumber()
);

const outputs = [
// outputs[0] = the desired amount going to recipient
{ value: BigInt(amount), address: recipient },
// outputs[1] = the remainder to be returned to a change address
{ value: sum - BigInt(amount) - BigInt(fee) },
{ value: BigInt(getUtxoTotal(neededUtxos).toString()) - BigInt(amount) - BigInt(fee) },
];

return {
filteredUtxos,
inputs: neededUtxos,
outputs,
size: sizeInfo.txVBytes,
size: estimateTransactionSize().txVBytes,
fee,
...estimateTransactionSize(),
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ export function useGenerateUnsignedNativeSegwitMultipleRecipientsTx() {
tx.addOutputAddress(output.address, BigInt(output.value), networkMode);
});

return { hex: tx.hex, fee, psbt: tx.toPSBT(), inputs };
return { hex: tx.hex, fee: fee, psbt: tx.toPSBT(), inputs };
} catch (e) {
// eslint-disable-next-line no-console
console.log('Error signing bitcoin transaction', e);
Expand Down
18 changes: 9 additions & 9 deletions src/app/common/transactions/bitcoin/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ export function getSpendableAmount({
}) {
const balance = utxos.map(utxo => utxo.value).reduce((prevVal, curVal) => prevVal + curVal, 0);

const size = getSizeInfo({
inputLength: utxos.length,
outputLength: 1,
const size = getBitcoinTxSizeEstimation({
inputCount: utxos.length,
outputCount: 1,
recipient: address,
});
const fee = Math.ceil(size.txVBytes * feeRate);
Expand Down Expand Up @@ -80,22 +80,22 @@ export function filterUneconomicalUtxos({
return filteredUtxos;
}

export function getSizeInfo(payload: {
inputLength: number;
outputLength: number;
export function getBitcoinTxSizeEstimation(payload: {
inputCount: number;
outputCount: number;
recipient: string;
}) {
const { inputLength, recipient, outputLength } = payload;
const { inputCount, recipient, outputCount } = payload;
const addressInfo = validate(recipient) ? getAddressInfo(recipient) : null;
const outputAddressTypeWithFallback = addressInfo ? addressInfo.type : 'p2wpkh';

const txSizer = new BtcSizeFeeEstimator();
const sizeInfo = txSizer.calcTxSize({
// Only p2wpkh is supported by the wallet
input_script: 'p2wpkh',
input_count: inputLength,
input_count: inputCount,
// From the address of the recipient, we infer the output type
[outputAddressTypeWithFallback + '_output_count']: outputLength,
[outputAddressTypeWithFallback + '_output_count']: outputCount,
});

return sizeInfo;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import type { Src20Token } from '@app/query/bitcoin/stamps/stamps-by-address.que
import { Src20TokenAssetItemLayout } from './src20-token-asset-item.layout';

interface Src20TokenAssetListProps {
src20Tokens: Src20Token[];
tokens: Src20Token[];
}
export function Src20TokenAssetList({ src20Tokens }: Src20TokenAssetListProps) {
return src20Tokens.map((token, i) => (
export function Src20TokenAssetList({ tokens }: Src20TokenAssetListProps) {
return tokens.map((token, i) => (
<Src20TokenAssetItemLayout key={`${token.id}${i}`} token={token} />
));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { styled } from 'leather-styles/jsx';

import { formatBalance } from '@app/common/format-balance';
import type { Stx20Token } from '@app/query/stacks/stacks-client';
import { Stx20AvatarIcon } from '@app/ui/components/avatar/stx20-avatar-icon';
import { ItemLayout } from '@app/ui/components/item-layout/item-layout';
import { BasicTooltip } from '@app/ui/components/tooltip/basic-tooltip';
import { Pressable } from '@app/ui/pressable/pressable';

interface Stx20TokenAssetItemLayoutProps {
token: Stx20Token;
}
export function Stx20TokenAssetItemLayout({ token }: Stx20TokenAssetItemLayoutProps) {
const balanceAsString = token.balance.amount.toString();
const formattedBalance = formatBalance(balanceAsString);

return (
<Pressable my="space.02">
<ItemLayout
flagImg={<Stx20AvatarIcon />}
titleLeft={token.tokenData.ticker}
captionLeft="STX-20"
titleRight={
<BasicTooltip
asChild
label={formattedBalance.isAbbreviated ? balanceAsString : undefined}
side="left"
>
<styled.span data-testid={token.tokenData.ticker} fontWeight={500} textStyle="label.02">
{formattedBalance.value}
</styled.span>
</BasicTooltip>
}
/>
</Pressable>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { Stx20Token } from '@app/query/stacks/stacks-client';

import { Stx20TokenAssetItemLayout } from './stx20-token-asset-item.layout';

interface Stx20TokenAssetListProps {
tokens: Stx20Token[];
}
export function Stx20TokenAssetList({ tokens }: Stx20TokenAssetListProps) {
return tokens.map((token, i) => (
<Stx20TokenAssetItemLayout key={`${token.tokenData.ticker}${i}`} token={token} />
));
}
6 changes: 3 additions & 3 deletions src/app/components/loaders/brc20-tokens-loader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { Brc20Token } from '@app/query/bitcoin/bitcoin-client';
import { useBrc20Tokens } from '@app/query/bitcoin/ordinals/brc20/brc20-tokens.hooks';

interface Brc20TokensLoaderProps {
children(brc20Tokens: Brc20Token[]): React.ReactNode;
children(tokens: Brc20Token[]): React.ReactNode;
}
export function Brc20TokensLoader({ children }: Brc20TokensLoaderProps) {
const brc20Tokens = useBrc20Tokens();
return children(brc20Tokens);
const tokens = useBrc20Tokens();
return children(tokens);
}
6 changes: 3 additions & 3 deletions src/app/components/loaders/src20-tokens-loader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import type { Src20Token } from '@app/query/bitcoin/stamps/stamps-by-address.que

interface Src20TokensLoaderProps {
address: string;
children(src20Tokens: Src20Token[]): React.ReactNode;
children(tokens: Src20Token[]): React.ReactNode;
}
export function Src20TokensLoader({ address, children }: Src20TokensLoaderProps) {
const { data: src20Tokens = [] } = useSrc20TokensByAddress(address);
return children(src20Tokens);
const { data: tokens = [] } = useSrc20TokensByAddress(address);
return children(tokens);
}
Loading
Loading