Tx fee что значит
Перейти к содержимому

Tx fee что значит

  • автор:

How does tx fee calculation work when txin and txout are similar amounts?

This website has an example called «When Too Much is Not Enough» on its main page. I’ll quote it an case this is changed in the future:

Suppose you have only two outputs in your wallet, worth 1 XBT and 2 XBT. You want to buy something for 2.999 XBT. The coin selection code has no choice; it has to select both coins to get a big enough total to make the transaction. That means the change will be 0.001 XBT, which triggers the 0.0001 XBT fee for having an output that’s less than 0.01 XBT. As a result your transaction will fail, because the amount you’re sending plus the fee is more than you have.

What this means is that there’s no way of spending 2.999 XBT when you have 3 XBT. You could send the full 3 XBT to the vendor without a fee (assuming the outputs are sufficiently old to satisfy step 3), but some vendors ask you to send the exact amount they specify.

Since the 1 BTC input and the 2 BTC input are interchangeable in this respect, let’s (for the sake of simplicity) settle that the bitcoin client decides to send the 2 BTC input in full for this example.

Then it has to split the 1 BTC input into a 0.999 BTC output and a 0.001 BTC output. I assume that doing so requires a fee because one of the outputs is smaller than 0.01 BTC. So 0.0001 BTC have to be paid for this. This means that there now is a 0.999 BTC junk and a 0.0009 BTC. The 2 BTC junk and the 0.999 BTC junk are send away and the 0.0009 BTC junk remains at its owner.

Can you tell me what I did wrong to get an outcome different from the one of the authors of that website?

Сколько платить за транзакцию Bitcoin? Размер комиссии в Сатоши.

Вы уже установили кошелек Bitcoin и даже отправили тестовый перевод, но все же много осталось непонятным: Кто такие Сатошики? Что за байты у транзакции? Как не платить лишнего? Разберем на пальцах все эти вопросы.

Транзакция Биткоин

1 BTC = 1000 mBTC = 100 000 000 Satoshi
mBTC — это миллиБиткоин (BTC и mBTC это как миллиметр и метр)
Сатоши — это 10 -8 Биткоина, минимальная единица этой криптовалюты, названа в честь основателя Bitcoin — Сатоши Накамото

Современные криптовалютные кошельки устроены так, чтобы пользователь мог не задумываться о том, что на самом деле происходит (ходя до настоящего удобства им еще как до луны). Пользователь вводит адрес кошелька получателя перевода, сумму перевода и размер комиссии, подтверждает перевод паролем и вуаля: монеты ушли!

Рассмотрим на примере кошелька Electrum.

Если вы двигаете бегунок «Fee», меняется размер комиссии от 0.0166 mBTC до 1.0586 mBTC. При этом скорость проведения транзакции, которую обещает кошелек, меняется в диапазоне от 25 до 1 блока соответственно.

Возможно, вы встречали понятие размера транзакции в байтах. Что это такое?
Если нажать на кнопку Preview вы получите детальную информацию о переводе:

В красной рамочке красуется как раз размер транзакции. Как он определяется?

Биткоины, которые пришли к вам на кошелек невозможно взять и просто так разделить. Например, если вам пришел 1 BTC, а затем вы хотите отправить товарищу 0.5 BTC, то транзакция будет создана таким образом, что вы отправите 0.5 BTC товарищу и сдачу 0.5 BTC получите обратно на свой кошелек. Этот процесс можно сравнить с операцией с бумажными деньгами: если вам дали купюру 100 рублей, вы не можете разрезать ее пополам и отдать 50 рублей за батон, вам надо отдать 100 и получить 50 в виде сдачи.

Каждая транзакция — программный код, который генерируется, учитывая то откуда пришли Биткоины и то, куда они отправляются. Все очень просто: чем больше адресов участвуют в транзакции — тем длиннее получается код.
Например, вы получили 1 BTC от Васи, 2 BTC от Гриши, 5 BTC от Игоря, а затем отправили все эти BTC (8 штук) Маше -> в этой транзакции участвует 4 адреса!

  1. Каждый адрес, с которого получены средства — это ±148 байтов
  2. Каждый адрес на который уходят средства — это ±34 байта
  3. Каждая транзакция занимает еще ±10 байтов, независимо от количества адресов, которые в ней участвуют

В нашем примере с кошельком Electrum 2 входящих адреса (Inputs) и 2 исходящих адреса (Outputs):

148×2 + 34×2 + 10 = 374 байта
Мы рассчитали довольно точно (Electrum показывает 372 байта)

Стоимость транзакции в сети Биткоин не зависит от суммы транзакции, она зависит от количества адресов, участвующих в ней.

Пример кода транзакции приведен ниже. Если вы хотите детально разобраться как генерируется код транзакции, рекомендуем эту статью.

01000000 01 be66e10da854e7aea9338c1f91cd489768d1d6d7189f586d7a3613f2a24d5396 00000000 8c 49 3046022100cf4d7571dd47a4d47f5cb767d54d6702530a3555726b27b6ac56117f5e7808fe0221008cbb42233bb04d7f28a715cf7c938e238afde90207e9d103dd9018e12cb7180e 01 41 042daa93315eebbe2cb9b5c3505df4c6fb6caca8b756786098567550d4820c09db988fe9997d049d687292f815ccd6e7fb5c1b1a91137999818d17c73d0f80aef9 ffffffff 01 23ce010000000000 19 76 a9 14 a2fd2e039a86dbcf0e1a664729e09e8007f89510 88 ac 00000000

Как работают майнеры

Майнеры не дураки, они хотят денег! В любом вопросе, связанном с майнерами, никогда не стоит это забывать: будь то обработка транзакций или войны о форках Биткоина.

После того, как вы подписали и отправили транзакцию в сеть Биткоин, она очень быстро распространяется по всей сети и попадает в мемпул (mempool) — очередь транзакций. Мемпул принято сравнивать с бутылкой, через горлышко которой транзакции попадают в блоки.

Размер блока в сети Биткоин на данный момент — 1 МБ, время нахождения блока — 10 минут. В один блок может попасть только 2000-3000 транзакций.

Еще раз повторимся, прикол криптовалют в их «открытости»! Вы можете сами взять и посмотреть любой блок сети: все транзакции, которые вошли в блок, сколько их было, сколько получили майнеры, какой был размер блока и т.д. и т.п. Воспользуйтесь, например сервисом https://blockchain.info/

На момент написания статьи размер мемпула — 15 МБ. Это значит, что лишь 6.7% транзакций могут попасть в следующий блок, остальные будут стоять и ждать своей очереди.

Как определяется очередь? Очень просто! Первым проходит тот, кто даст больше денег! Важное замечание: пользователи обычно смотрят какую комиссию они платят за транзакцию, а майнеры смотрят сколько стоит каждый байт транзакции. Именно поэтому мы забивали вам голову всякой ерундой в начале статьи. Важно понимать, что если Вася платит комиссию 0.1 mBTC, но у него в транзакции участвует 2 адреса — его транзакция пройдет быстрее, чем Мишина, который платит 0.5 mBTC, но у него задействовано 20 адресов.

Сколько мне платить майнерам? Разумная экономия

Перед переводом Биткоинов всегда смотрите размер мемпула. Это даст понимание того, что происходит с сетью. Если мемпул практически пуст, ваши транзакции, даже с минимально возможной комиссией, пройдут довольно быстро.

Мы недавно тестировали сеть Bitcoin: при размере мемпула 4 МБ транзакция размером 225 байтов с комиссией 1 Сатоши/байт прошла за 3 блока. Мы заплатили 225 Сатоши = 0.00000225 BTC = 0.01$

Кошельки безбожно врут с оценкой необходимого количества блоков (= времени) для обработки транзакции при установке комиссии. Почему это важно? Например, в очереди стоит 10000 транзакций, пройти в следующем блоке может только 2500. 9000 транзакций стоят с комиссией 1 Сатоши/байт. Нет смысла ставить комиссию 10 Сатоши/байт, ведь даже при 2 Сатоши/байт ваша транзакция попадет в первый же блок.

Сервис показывает какие комиссии платили пользователи Биткоин за свои транзакции за последние сутки и за последние 2 недели. Под графиком приведено оптимальное значение комиссии, которое надо выставить, чтобы ваш перевод был обработан в ближайших блоках.

На момент написания статьи размер мемпула 15 МБ. Рекомендация сайта:

Which fee should I use?

The fastest and cheapest transaction fee is currently 200 satoshis/byte, shown in green at the top.
For the median transaction size of 226 bytes, this results in a fee of 45,200 satoshis.

При учете того, что, в среднем, транзакция занимает 226 байтов, сайт рекомендует отдать 200 Сатоши за байт. Общая комиссия за перевод составит 452 mBTC (2.5$). Это очень дорого, но транзакция будет обработана почти сразу.

Биржи

Обычно биржи не дают возможность установить комиссию, которую вы готовы заплатить за обработку транзакции. У каждой биржи есть определенная фиксированная комиссия, например, у Bitfinex Tx Fee = 0.0005 BTC (2.75$). Проблема заключается в том, что неизвестно сколько по факту биржи платят майнерам, а сколько оставляют себе.

Недавно нам пришлось ждать 10 часов пока Биткоины с биржи дойдут до нашего кошелька, при том что комиссию мы заплатили довольно большую.

  • Комиссия сети Биткоин не зависит от суммы перевода (будь то 0.001 BTC или 100000 BTC).
  • При выборе цены обработки транзакции следует учитывать комиссию в расчете на 1 байт.
  • Перед отправкой транзакции стоит заглянуть в мемпул и bitcoinfees.
  • Биржи не дают выбрать размер комиссии, при этом часть они могут вообще забрать себе, приходится только смириться и ждать пока транзакция пройдет.

Немного занимательной арифметики. Биткоин часто сравнивают с платежными системами Visa, MasterCard и т.п. или с системами мгновенных переводов WesterUnion. Давайте сделаем свой просто расчет:

Смотрим последние блоки в сети: https://blockchain.info/ru/blocks
Берем, например, блок 490375: https://blockchain.info/ru/block-height/490375
Количество транзакций: 2668
Вознаграждение майнеров: 12.5 BTC + 0.96 BTC = 13.46 BTC (75 376$)
1 транзакция обошлась почти в 30$.

ЭЭЭ… ЭЭЭЭЭЭЭЭ… Все нормально? А как же замена WesternUnion’а? Или может Биткоин = пузырь? Добро пожаловать в наш чат, обсуждаем все там. Кстати, подобные рассуждения мы часто выкладываем в Telegram канал и до сайта они не успевают дойти, подписывайтесь.

Думаете в Эфире лучше? Ну-ну. Скоро и ему от нас достанется. Подождите немного.

The UX of TX

Network fees for blockchain transactions are notoriously difficult to explain to mainstream users. The Gas Station Network allows DApps to foot the gas bill. Problem solved, right? Not quite.

portis

Portis

Ain’t Nobody Paying Your AWS Fees

Whenever we discuss the hard parts of blockchain UX, the two issues that always stand out are private key management and network fees. This post is about the latter.

Users don’t like network fees

Network fees are confusing and feel out of place. Even if users do understand why they’re needed, they might get upset about the whole idea. After all, in the familiar world of web2, they aren’t paying anyone to use web apps, so this requirement can create antagonism towards your DApp.

The friction is real

Paying gas fees requires users to get their hands on some ETH, which means going through KYC and buying a lot more than they need just for gas. All of this, even if they only want to interact with your DApp, not necessarily buy something.

“Free Rides!”

In the early days of Portis, we were determined to let users experience the true potential of DApps. We wanted to get around the issue of network fees, so we simply gave each new user $1 of ETH for free.

Scalable? Hell no. Abusable? You bet.

But it did the trick. DApp owners loved it since it gave their users an opportunity to actually use their DApp with minimal friction.

At some point, despite our phone verification process, the abuse became too costly to manage (in some countries, it’s well worth your time to go to great lengths of trouble for $1 of free ETH), so we had to shut it down.

Nevertheless, our little experiment was a success

We saw that once you remove the friction of network fees, churn is reduced significantly.

After all, the difference between 1 cent and free is more than just 1 cent.

Introducing MetaTx

In September 2018, while we were still giving out $1 of free ETH to new Portis users, a group of people in ETHBerlin were discussing the same issue of network fees and how it might be solved using something called Meta Transactions (or MetaTx for short). This group would go on to become the MetaCartel.

From conference to hackathon to meetup, discussions continued, and this group grew in size, as more and more developers were eager to solve this challenge in an elegant fashion.

“Do You Accept the Charges?”

Since the DApps themselves sponsor the users’ gas fees, we like to compare MetaTxs to collect calls. The user is trying to make a call to the DApp’s smart contract, and the DApp is the one picking up the tab for the call by agreeing to accept the charges (in theory, it can be anyone accepting the charges, but we believe it will be mostly DApps, and perhaps also wallet providers).

Instead of asking users to deposit gas money in their wallets so they can submit transactions to the network, they only need to sign messages that convey what a regular transaction would have done. A “gasless transaction” if you will.

Those signed messages are sent to a relayer using a regular HTTP API endpoint. The relayer then wraps the message inside a MetaTx, paying the gas fees for both the user’s original message/transaction and the newly wrapped transaction.

The DApp smart contract knows how to handle this MetaTx, unwrapping it and executing the content of the message as if it was a regular transaction.

At first, this seems like a terrific solution, but further investigation reveals plenty of difficult challenges, mainly revolving around centralization and synchronization.

The Gas Station Network (developed by the amazing team at TabooKey), which we talked about in a previous post, solves these challenges and provides a robust and decentralized way of sponsoring users’ network fees.

Less Is More

We got the GSN hooked up to Portis (Ropsten only, mainnet coming very soon. Update: mainnet is live!), and the experience in our demo DApp CryptoPuppers was amazing: a brand new user could write to the blockchain for free in seconds! Couple that with the smooth Portis onboarding experience and we have removed literally all friction. A few clicks are all it takes to interact with a smart contract. Outstanding!

Once we finished geeking out, our first dilemma was “so… what do we write under network fees?”

One approach was to simply show nothing. After all, when you upload an image to Instagram or book an apartment on Airbnb, the app doesn’t tell you that they’ve just paid $0.000001 for AWS on your behalf.

On the other hand, gas fees wouldn’t necessarily always be free. Some DApps won’t sponsor them. Others might only sponsor gas fees for specific actions and/or certain users. We like our UI to be consistent.

A decision was made — under “network fees” we will write down “Free”. We believed DApps might also wish to convey to the user that they have sponsored their gas fees, as this is still not the norm everywhere.

A Match Made In Heaven

In our quest to offer users the best blockchain UX possible, we released a feature last year called “Trust this App”, which we explained here.

As a user, trusting a specific app means you won’t need to manually confirm each action through Portis, as long as you’re only paying small amounts for network fees. Portis will keep track of users’ network fee expenses, and if they exceed $1 per hour, they will revert to using manual confirmations.

The Gas Station Network makes sure that last part will never occur (as DApps are footing the gas bill for each transaction), meaning that by combining these two features (gas sponsoring + trust this app) we can finally offer end-users a web3 experience that feels like web2.

Simple. Secure. Seamless.

There are many scenarios that need to be considered, such as what happens when the DApp turns off the relay (or it runs out of funds), which users are worthy of being sponsored, and many more.

Luckily we have a wonderful community of DApp developers to brainstorm with and figure out solutions to these challenges, so we can provide users with solutions that are both secure and simple to understand.

We’re looking forward to exploring these uncharted territories with our partners, paving together the path of least resistance to the blockchain.

Make sure you also check the GSN website built by the terrific team at Zeppelin.

The Portis Team

Have any questions? Join the conversation on our Telegram and Twitter. Ready to #BUIDL? Head on to our docs.
Got any suggestions? We �� feedback!

TX Fee Understanding: What is a transaction fee? (2022)

thumbnail

As crypto natives, it is such a usual thing that we pay fees for every operation with blockchain, such as token transfer, minting, smart contract establishment, etc. The fee for each transaction might be small, but it can accumulate into a significant sum of money over time.

Let’s explore what a transaction fee is and why it is important for the existence of blockchains.

What is a transaction fee (TX fee)?

Transaction fee is the fee that users have to pay when conducting transactions on the blockchain space. The fees are often paid in the native token of the blockchain, which can vary over time. Due to different blockchain designs, transactions come with flexible fee structures.

Besides fees for blockchain transactions, in the crypto world, there are many other transaction fees for service providers, increasing their total revenue.

For example, the total revenue of the Ethereum network is around $8.4B, updated on Jul 7, 2022. A considerable proportion of that might come from transaction fees.

Where do transaction fees go?

Blockchain networks or crypto projects generate billions of revenue from daily transaction fees. It is a major factor that can turn an ecosystem into a sustainable one. The effectiveness of how transaction fees are distributed will yield massive results if it is carefully planned.

Let’s track where transaction fees possibly go.

Validators/nodes: Without a doubt, node operators will receive a proportion of transaction fees since they make an effort to complete the transactions. They are incentivized to operate systems of nodes because it is profitable.

Treasury: Blockchains or service providers might extract a small portion of transaction fees to build their treasury for ecosystem growth or hedging risk management.

Burning mechanism: To go against inflation, some blockchains have the token burning mechanism. This means a small proportion of transaction fees will be used to buy the native token, then it will be burnt to maintain a sustainable supply. For example, BNB Smart Chain has extracted over $22M of BNB from tx fees to burn.

Service providers/project teams: In most cases, we have to go to trading platforms or use blockchain wallet applications to conduct transactions instead of directly interacting with the blockchain.

Those service providers will charge us a fraction of the transaction amount as fee. The fee rate depends on the policy of the service providers. Uniswap is one of the top leading trading platforms on Ethereum that charges 0.3% of the transaction amount for most token pairs and around 1% for exotic pairs.

Why are transaction fees important?

Let’s see notable reasons why transaction fees are important for long-term success.

Motivation for blockchain nodes/validators: The more nodes a blockchain has, the more decentralization and computing power it has. Running validators or nodes will reward operators with a proportion of transaction fees.

Overload prevention: Let’s imagine how congested a blockchain network will be if every transaction is completely free and users have nothing to pay. Both users and trading bots constantly conduct no-fees transactions while blockchain validators are not incentivized to operate. This leads to an unstable system for the blockchain network.

A sustainable ecosystem: Blockchains and protocols generate revenue from charging fees for activities such as transactions, lending/borrowing, etc. The generated revenue will be reinvested in the ecosystem to create more value. This is why transaction fees are the key driver of growth.

How to calculate the transaction fee

Bitcoin

Bitcoin miners are responsible for validating blockchain transactions in every new block generated. Pending transactions are consolidated in a group called mempool (memory pool). Miners will verify those transactions and receive the transaction fees associated with new block rewards in Bitcoin.

The block rewards and the Bitcoin hash rate decrease by half after each Bitcoin halving (4-year period). Therefore, in the far future, Bitcoin rewards for miners will primarily depend on the sum of transaction fees.

In general, Bitcoin's transaction fees vary, depending on the data volume and the status of the network, not the transaction amount. The maximum data of one Bitcoin block is 4 MB which only includes a limited number of transactions in one block. Each transaction requires a number of bytes in the Bitcoin block.

Users have to pay the tx fees in Satoshis (sats), the smallest unit of Bitcoin, 100,000,000 Satoshis for one Bitcoin. The sats/vByte rate is used to calculate the transaction fees of Bitcoin where sats are satoshis, and a block has one million of vBytes. The data volume of the transaction is multiplied by the sats/vByte rate, which is the fee for each transaction.

Some blockchain wallet interfaces allow users to adjust the rate in case they are in the rush or do not have time to wait. During the network congestion, investors have to pay more fees to be prioritized in a block fixed to have 4 MB in size.

Ethereum

Every operation on the Ethereum network requires a certain amount of gas, representing miners' computational efforts. In simple terms, gas is needed to successfully conduct a transaction on the Ethereum network. It can vary depending on the status of the network, and it is paid in the native token of Ethereum, ETH.

The gas price is denoted in gwei (giga-wei). Wei is the smallest unit of ETH and one ETH equals 1,000,000,000,000,000,000 wei or 1 billion gwei.

The transaction fee is calculated:

Gas units (limit) * (Gas price + Tip)

For example, Alice sends 1 ETH to Bob with a gas limit of 40,000 units. At the same time, the gas price is 50 gwei and Alice wants to give a tip to miners of 10 gwei. As a result, she has to pay 40,000*(50+10) = 2,400,000 gwei = 0.0024 ETH as the gas fee. Alice will be deducted 1.0024 ETH in order for Bob to receive 1 ETH.

A priority fee is an amount users have to spend as a tip to miners. The bigger the tip, the more likely the transaction is preferentially executed. A gas limit is an adjustable number for users to limit the transaction fee at their discretion.

Besides revenue generation, Bitcoin, Ethereum, and other blockchain platforms charge fees to prevent network spamming from congestion. This sometimes happens to blockchains with cheap transaction fees, exposing them to be attacked.

Other platforms or protocols

Other than blockchains like Bitcoin and Ethereum, investors might tolerate more fees from centralized platforms or protocols for using their services. The fee rate is often fixed or flexible, based on the terms and conditions.

For example, centralized exchanges like Gate.io and Binance charge the users a certain level of fees. Furthermore, the fee structure might include the utilization of their tokens. BNB holders can get discounted transaction fees based on which tier it is.

FAQs about TX fee

Who will pay the transaction fee?

Whoever conducts the transaction on the blockchain will have to pay transaction fees. Blockchain validators cannot verify the transactions without paying tx fees, making them fail to complete. On the other hand, some blockchain platforms, such as Ethereum, prioritize transactions with high tips, creating an active environment for users who have tightened hours.

How to avoid paying transaction fees

It is impossible to avoid paying fees on blockchains since validators are bonded with a strong consensus that is possibly immune to attacks. In contrast, exchanges or dApps might release incentive programs that reduce or eliminate the transaction fees for project contributors or their token holders.

Transaction fees vs. withdrawal fees

Users who conduct transactions in the blockchain environment will have to pay transaction fees. Users might have to pay fees to withdraw crypto assets from protocols or exchanges. Transaction fees and withdrawal fees describe the fees that users have to pay.

The former is for each transaction, while the latter is for each withdrawal order. However, each platform has different terms and conditions, it might charge no fees for withdrawing or depositing.

Conclusion

Transaction fees are an indispensable part of the blockchain world. Every operation with blockchains requires paying native tokens as fees that might go back to the ecosystem, creating a compounding growth loop.

In addition, tx fees can prevent network spamming because it might cost hackers a tremendous pile of transaction fees. During market selloffs or high-level congestion, the transaction fees might peak, discouraging investors to conduct any additional transactions. To reiterate, the advantages of transaction fees might outweigh the limitations.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *