Flow dynamic transaction fee

Original link: https://caos.me/f230e2dd-6228-4aff-8b6e-d6da94c751a5

https%3A%2F%2Fdocs.onflow.org%2F64eca026

# Flow dynamic transaction fee

> Translated from Flow official document dynamic [dynamic transaction fee](/f230e2dd62284aff8b6ed6da94c751a5)

This guide will explain why transaction fees are important, how to calculate transaction fees, and how to handle fees in your implementation. Specifically, it shows how to estimate transaction costs, how to set cost limits, and how to optimize Cadence code to keep transaction costs as low as possible.

This guide concludes with how to educate users about fees and how to learn more about transaction fee implementation.

> Note: The implementation of transaction costs is based on the FLIP process with community participation. This work is currently in progress. Learn more at the end of the article to get involved in the process.

## [The need to understand transaction fees](https://ift.tt/eR0snlK)

Dynamic transaction fees are critical to ensuring fair pricing based on impact on the network. For example, heavier operations will require more resources to process and propagate transactions. However, ordinary operations will remain reasonably priced.

Fees reduce the viability of malicious behavior (such as spam) on the network, thereby increasing the overall security of the network.
The unique Flow structure targets high throughput. This makes the system easier to slack, so short-term high usage demands can be handled more gracefully.

## [Understanding Fee Structure](https://ift.tt/vgP24Od)

Fees are calculated based on three components: execution fee, packaging fee, and network surge factor.
Packaging and execution charges can be expressed as packaging or execution work and an associated multiplier to reflect the cost of packaging and execution work. The final transaction fee calculation is as follows:

“`go
inclusionFee = inclusionEffort * inclusionEffortCost;

executionFee = executionEffort * executionEffortCost;

totalFee = (inclusionFee + executionFee) * surgeFactor;

“`

> Note: If you want to learn more about the cost function, [see FLIP 753](https://ift.tt/AoCmhK2)

### [Execution Consumption](https://ift.tt/QlecnjO)

The execution of a transaction is determined by the code path taken by the exchange and the actions it performs. Operations that have an associated cost of performing work can be grouped into four broad categories:

– Generic Cadence lines of code, execution of loops or function calls

– Read data from memory, billed by bytes read

– Write data to memory, billed by bytes written

– Account Creation

**Fee Overview**
To give you a better idea of ​​the fee range, given the current `executionEffortCost` and `inclusionEffortCost` parameters, here are some common transaction types and their associated execution costs:

### [Package Fee](https://ift.tt/k0wVjto)

The packaging work of a transaction represents the work required for the following:

– Pack transactions in blocks

– Transfer transaction information between nodes

– Verify transaction signature

Now, the packing job is always 1.0, and the packing job cost is fixed at `0.000001`.

> Note: Packing fees can always be calculated without executing the transaction code.

In the future, the packaging cost will be affected by the size of the transaction in bytes and the number of required signatures.

> Note: Changes to variable packaging costs will be updated in [one of the upcoming SPORKs] (https://ift.tt/c04gyHf).

### [Network Surge Value](https://ift.tt/A3eHzLf)

In the future, the network surge value will be applied when the network is busy due to an increase in the volume of transactions that need to be processed or a decrease in the ability to process transactions. Currently, network traffic is fixed at `1.0`.

### [Storage Fee](https://ift.tt/Rz2JVQm)

Storage fees are implemented differently than transaction fees. See the [Guidelines for storing data in FLOW]([https://docs.onflow.org/concepts/storage/#storage-capacity](https://docs.onflow.org/concepts/storage/#storage-capacity ) for more details. In summary, storage fees are the costs associated with storing data on-chain.

## [Estimated transaction fee](https://ift.tt/gI0kWZm)

Cost estimation is done in two steps. First, you need to collect execution work through the emulator or testnet. Second, you can use a JavaScript or Go-FCL SDK to calculate the final fee using the transaction’s execution effort.

### [Understanding Execution Work](https://ift.tt/kdcj54n)

Execution work is best determined by running a transaction and viewing the emitted event details.

**Using Flow Simulator**

You can [start the emulator with the Flow CLI]([https://ift.tt/QwBbRk6). Run the transaction and see the events emitted:](https://ift.tt/lPHAeat %BF%90%E8%A1%8C%E4%BA%A4%E6%98%93%E5%B9%B6%E6%9F%A5%E7%9C%8B%E5%8F%91%E5%87 %BA%E7%9A%84%E4%BA%8B%E4%BB%B6%EF%BC%9A)

“`plain text
0|emulator | time=”2022-04-06T17:13:22-07:00″ level=info msg=” ⭐ Transaction executed” computationUsed=3 txID=a782c2210c0c1f2a6637b20604d37353346bd5389005e4bff6ec7bcf507fac06

“`

You should see the `ComputeUsed` field. Make a note of this value, you will use it in the next step.

**on testnet**
After the transaction is completed, the transaction details and emitted events can be viewed using a block explorer similar to [Flowscan](https://flowscan.org/). For Flowscan, you can open the transaction in question and look for the `FeesDeducted` event from [`FlowFees`](https://ift.tt/0J7AOxB), contract:

![](https://docs.onflow.org/64eca026ca805fa52f8b44e846670a90/flowscan-fees.png)

In the event data on the right, you will see a set of fields representing [FeeParameters] ([https://ift.tt/gmGMyUK] (https://ift.tt/toPv1GO

– surgeFactor surge factor

– InclusionEffort package consumption

– executionEffort execution consumption

Note the last value in the list, the `executionEffort` value. Will use it in the next step.

### [Calculate final cost](https://ift.tt/rBtlocm)

The cost of transactions can be calculated using the following FCL scripts on mainnet/testnet respectively.

**on mainnet**

“`go
import FlowFees from 0xf919ee77447b7497
pub fun main(
inclusionEffort: UFix64,
executionEffort: UFix64
): UFix64 {
return FlowFees.computeFees(inclusionEffort: inclusionEffort, executionEffort: executionEffort)
}

“`

**on testnet**

“`go
import FlowFees from 0x912d5440f7e3769e
pub fun main(
inclusionEffort: UFix64,
executionEffort: UFix64
): UFix64 {
return FlowFees.computeFees(inclusionEffort: inclusionEffort, executionEffort: executionEffort)
}

“`

## [Configuration Execution Limit](https://ift.tt/vL3EgWK)

The FCL SDK allows you to set an execution workload limit for each transaction. Based on the execution workload limit determined in the previous step, you should set a reasonable maximum value to avoid unexpected behavior and protect your users. The final transaction fee is calculated based on the actual work performed until the maximum value is reached.

> Note: Remember that the limit is not for the final fee that the user must pay. Restrictions are specific to performing work.
> It is important to set a limit that is not too high or too low. If set too high, the payer needs to have more funds in their account before sending the transaction. If it is too low, execution may fail and all state changes will be removed.

**Using FCL JS SDK**
You need to set the `limit` parameter for the `mutate` function, for example:

“`javascript
import * as fcl from “@onflow/fcl”

const transactionId = await fcl.mutate({
cadence: `
transaction {
execute {
log(“Hello from execute”)
}
}
`,
proposer: fcl.currentUser,
payer: fcl.currentUser,
limit: 100
})

const transaction = await fcl.tx(transactionId).onceSealed();
console.log(transaction;)

“`

**Using FCL Go SDK**
You need to call the `SetGasLimit` method to set the fee limit, for example:

“`go
import (
“github.com/onflow/flow-go-sdk”
“github.com/onflow/flow-go-sdk/crypto”
)

var (
myAddress flow.Address
myAccountKey flow.AccountKey
myPrivateKey crypto.PrivateKey
)

tx := flow.NewTransaction().
SetScript([]byte(“transaction { execute { log(\\”Hello, World!\\”) } }”)).
SetGasLimit(100).
SetProposalKey(myAddress, myAccountKey.Index, myAccountKey.SequenceNumber).
SetPayer(myAddress)

“`

## [Optimize Cadence code to reduce workload](https://ift.tt/HiU7A0t)

Some optimizations can reduce the execution time of transactions. Some practices are listed below. This list is not exhaustive but exemplary.

**Limit function calls**
Whenever you make function calls, make sure these are absolutely required. In some cases you can check for preconditions and avoid extra calls:

“`javascript
for obj in sampleList {
/// Check if the execution is necessary
if obj.id != nil {
functionCall(obj)
}
}

“`

**Limited loops and iterations**
Whenever you want to iterate over a list, make sure it is necessary to iterate over all elements, not a subset. Avoid loops that get too big over time. Limit loops as much as possible.

“`javascript
// Iterating over long lists can be expensive
pub fun sum(list: [Int]): Int {
var total = 0
var i = 0
// if the list becomes too large, this may not execute smoothly
while i (from: /storage/exampleToken)

let burnVault Note: If the requested resource does not exist, there is no read charge.

**Limit accounts created per transaction**

There is a cost associated with creating an account and adding keys. Try to create accounts and keys only when necessary.

**Check user balance before executing transaction**

You should ensure that the user’s balance is sufficient to cover the highest possible fee. For transfers of Fungible Tokens, in addition to the highest possible fee, you also need to pay the transfer amount.

## [User Education](https://ift.tt/pMGR7sc)

The wallet will handle the representation of the final transaction cost, but you can still facilitate the user experience by educating it in the app.
If your users are using non-custodial wallets, they may be charged transaction fees and want to know about fees. Here are some suggestions.

**Explain transaction fees may vary based on network usage**

Suggested message: “Charging increases the security of the network. Flexible pricing ensures fair pricing based on impact on the network.”

**Indicates waiting for network spikes to subside is an option**

Inevitably, network surges will lead to higher fees. If users wish to submit transactions when network usage spikes, they should consider sending transactions later to reduce costs.

**Explain that the wallet may not allow transactions due to insufficient funds**

If the dynamic fee increases to the highest possible level, the user’s funds may not be sufficient to execute the transaction. Let users know that they should either increase their funds or try when the network is less busy.

## [How to learn more](https://ift.tt/VnNALZR)

There are several places to learn more about transaction fees:

– [FLIP-660](https://ift.tt/KIxNJZm)

– [FLIP-753](https://ift.tt/XvsZ40U)

– [Flow Fees Contract](https://ift.tt/0J7AOxB)

> Note: If you have thoughts on the implementation of transaction fees on Flow, you can leave feedback on this forum post.

> Note: If you have ideas about the implementation of Flow transaction fees, you can post them in [this forum post](https://ift.tt/n6kCv4H ) to leave feedback.

## [FAQs](https://ift.tt/ZB9gwlh)

**When will the fee update take effect**
The update was published on [Spork] on April 6, 2022 (https://ift.tt/iQEV23H), but was released on [June 1](https://ift.tt/HhbPoX8 permissionless-contract-deployment-progress/2981) enabled in [weekly epoch transition](https://ift.tt/g1Mrity -1) period.

**Why are you charged even if the transaction fails**

Broadcasting and validating transactions need to be executed, so costs can be deducted appropriately.

**Which execution costs are considered above average**

There is no average for execution cost. Each function will be very different depending on the logic implemented. You should review optimization best practices to determine if you can reduce costs.

This article is reprinted from: https://caos.me/f230e2dd-6228-4aff-8b6e-d6da94c751a5
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment