diff --git a/docs/build/cadence/basics/accounts.md b/docs/build/cadence/basics/accounts.md index 6a689fac20..f35fd0e198 100644 --- a/docs/build/cadence/basics/accounts.md +++ b/docs/build/cadence/basics/accounts.md @@ -29,13 +29,12 @@ Are you an EVM developer looking for information about EVM Accounts on Flow? If An account on Flow is a record in the chain state that holds the following information: -- Address: unique identifier for the account -- Public Keys: public keys authorized on the account -- Code: Cadence contracts deployed to the account +- Address: unique identifier for the account. +- Public Keys: public keys authorized on the account. +- Code: Cadence contracts deployed to the account. - Storage: area of the account used to store resource assets. -Accounts and their keys are needed to sign transactions that change the Flow blockchain state. To execute a transaction, a small amount of Flow, called a ["Fee"](./fees.md) must be paid by the account or subsidized by a wallet or service. Flow allocates a fixed amount of storage to each account for saving data structures and Resources. Flow allocates a [fixed amount of storage](./fees.md#storage) to each account for saving data structures and Resources. -An account may also contain contract code which transactions and scripts can interact with to query or mutate the state of the blockchain. +Accounts and their keys are needed to sign transactions that change the Flow blockchain state. To execute a transaction, a small amount of Flow, called a ["Fee"] must be paid by the account or subsidized by a wallet or service. Flow allocates a [fixed amount of storage] to each account to save data structures and Resources. An account may also contain contract code which transactions and scripts can interact with to query or mutate the state of the blockchain. A simple representation of an account: @@ -43,13 +42,13 @@ A simple representation of an account: ## Address -A Flow address is represented as 16 hex-encoded characters (usually prefixed with `0x` to indicate hex encoding). Unlike Bitcoin and Ethereum, Flow addresses are not derived from cryptographic public keys. Instead, each Flow address is assigned by the Flow protocol using an onchain deterministic sequence. The sequence uses an error detection code to guarantee that all addresses differ with at least 2 hex characters. This makes typos resulting in accidental loss of assets not possible. +A Flow address is represented as 16 hex-encoded characters (usually prefixed with `0x` to indicate hex encoding). Unlike Bitcoin and Ethereum, Flow addresses are not derived from cryptographic public keys. Instead, each Flow address is assigned by the Flow protocol via an onchain deterministic sequence. The sequence uses an error detection code to guarantee that all addresses differ with at least two hex characters. This makes typos that result in accidental loss of assets impossible. -This decoupling is a unique advantage of Flow, allowing for multiple public keys to be associated with one account, or for a single public key to be used across several accounts. +This decoupling is a unique advantage of Flow, as it allows for multiple public keys to be associated with one account, or for a single public key to be used across several accounts. ## Balance -Each Flow account created on Mainnet will by default [hold a Flow vault that holds a balance and is part of the FungibleToken standard](./flow-token.md). This balance is used to pay for [transaction fees and storage fees](./fees.md). More on that in the fees document. +Each Flow account created on Mainnet will by default [hold a Flow vault that holds a balance and is part of the FungibleToken standard]. This balance is used to pay for [transaction fees and storage fees]. :::warning @@ -57,11 +56,11 @@ The minimum amount of FLOW an account can have is **0.001**. ::: -This minimum storage fee is provided by the account creator and covers the cost of storing up to 100kB of data in perpetuity. This fee is applied only once and can be "topped up" to add additional storage to an account. The minimum account reservation ensures that most accounts won't run out of storage capacity if anyone deposits anything (like an NFT) to the account. +This minimum storage fee is provided by the account creator and covers the cost of storage up to 100kB of data in perpetuity. This fee is applied only once and can be "topped up" to add additional storage to an account. The minimum account reservation ensures that most accounts won't run out of storage capacity if anyone deposits anything (like an NFT) to the account. ### Maximum available balance -Due to the storage restrictions, there is a maximum available balance that user can withdraw from the wallet. The core contract [`FlowStorageFees`](../core-contracts/05-flow-fees.md#flowstoragefees) provides a function to retrieve that value: +Due to the storage restrictions, there is a maximum available balance that user can withdraw from the wallet. The core contract [`FlowStorageFees`] provides a function to retrieve that value: ```cadence import "FlowStorageFees" @@ -85,17 +84,17 @@ access(all) fun main(address: Address): UFix64 { ## Contracts -An account can optionally store multiple [Cadence contracts](https://cadence-lang.org/docs/language/contracts). The code is stored as a human-readable UTF-8 encoded string which makes it easy for anyone to inspect the contents. +An account can optionally store multiple [Cadence contracts]. The code is stored as a human-readable UTF-8 encoded string which makes it easy for anyone to inspect the contents. ## Storage -Each Flow account has an associated storage and capacity. The account's storage used is the byte size of all the data stored in the account's storage. An account's [storage capacity is directly tied to the balance of Flow tokens](./fees.md#storage) an account has. An account can, without any additional cost, use any amount of storage up to its storage capacity. If a transaction puts an account over storage capacity or drops an account's balance below the minimum 0.001 Flow tokens, that transaction fails and is reverted. +Each Flow account has an associated storage and capacity. The account's storage used is the byte size of all the data stored in the account's storage. An account's [storage capacity is directly tied to the balance of Flow tokens] an account has. An account can, without any additional cost, use any amount of storage up to its storage capacity. If a transaction puts an account over storage capacity or drops an account's balance below the minimum 0.001 Flow tokens, that transaction fails and reverts. -## Account **Keys** +## Account **keys** Flow accounts can be configured with multiple public keys that are used to control access. Owners of the associated private keys can sign transactions to mutate the account's state. -During account creation, public keys can be provided which will be used when interacting with the account. Account keys can be added, removed, or revoked by sending a transaction. This is radically different from blockchains like Ethereum where an account is tied to a single public/private key pair. +During account creation, public keys can be provided which will be used when owners interact with the account. You can send a transaction to add, remove, or revoke account keys. This is radically different from blockchains like Ethereum where an account is tied to a single public/private key pair. Each account key has a weight that determines the signing power it holds. @@ -105,34 +104,34 @@ A transaction is not authorized to access an account unless it has a total signa ::: -For example, an account might contain 3 keys, each with 500 weight: +For example, an account might contain three keys, each with 500 weight: ![Screenshot 2023-08-16 at 16.28.58.png](_accounts_images/Screenshot_2023-08-16_at_16.28.58.png) -This represents a 2-of-3 multi-sig quorum, in which a transaction is authorized to access the account if it receives signatures from _at least_ 2 out of 3 keys. +This represents a 2-of-3 multi-sig quorum, in which a transaction is authorized to access the account if it receives signatures from _at least_ two out of three keys. An account key contains the following attributes: -- **ID** used to identify keys within an account -- **Public Key** raw public key (encoded as bytes) -- **Signature algorithm** (see below) -- **Hash algorithm** (see below) -- **Weight** integer between 0-1000 -- **Revoked** whether the key has been revoked or it's active -- **Sequence Number** is a number that increases with each submitted transaction signed by this key +- **ID** used to identify keys within an account. +- **Public Key** raw public key (encoded as bytes). +- **Signature algorithm** (see below). +- **Hash algorithm** (see below). +- **Weight** integer between 0-1000. +- **Revoked** whether the key has been revoked or it's active. +- **Sequence Number** is a number that increases with each submitted transaction signed by this key. -### Signature and Hash Algorithms +### Signature and hash algorithms The signature and hashing algorithms are used during the transaction signing process and can be set to certain predefined values. -There are two curves commonly used with the ECDSA algorithm, secp256r1 ([OID 1.2.840.10045.3.1.7](http://oid-info.com/get/1.2.840.10045.3.1.7), also called the "NIST P-256." this curve is common for mobile secure enclave support), and secp256k1 ([OID 1.3.132.0.10](http://oid-info.com/get/1.3.132.0.10), the curve used by "Bitcoin"). Please be sure to double-check which parameters you are using before registering a key, as presenting a key using one of the curves under the code and format of the other will generate an error. +There are two curves commonly used with the ECDSA algorithm, secp256r1 ([OID 1.2.840.10045.3.1.7], also called the "NIST P-256." this curve is common for mobile secure enclave support), and secp256k1 ([OID 1.3.132.0.10], the curve used by "Bitcoin"). Be sure to double-check which parameters you use before you register a key, because if you present a key that uses one of the curves under the code and format of the other, an error will occur. | Algorithm | Curve | ID | Code | | --------- | --------- | --------------- | ---- | | ECDSA | P-256 | ECDSA_P256 | 2 | | ECDSA | secp256k1 | ECDSA_secp256k1 | 3 | -_Please note that the codes listed here are for the signature algorithms as used by the node API, and they are different from the ones [defined in Cadence](https://cadence-lang.org/docs/language/crypto#signing-algorithms)_ +_Note that the codes listed here are for the signature algorithms as used by the node API, and they are different from the ones [defined in Cadence]_ | Algorithm | Output Size | ID | Code | | --------- | ----------- | -------- | ---- | @@ -141,23 +140,23 @@ _Please note that the codes listed here are for the signature algorithms as used Both hashing and signature algorithms are compatible with each other, so you can freely choose from the set. -### **Locked / Keyless Accounts** +### **Locked / keyless accounts** -An account on Flow doesn't require keys in order to exist, but this makes the account immutable since no transaction can be signed that can change the account. This can be useful if we want to freeze an account contract code and it elegantly solves the problem of having multiple account types (as that is the case for Ethereum). +An account on Flow doesn't require keys in order to exist, but this makes the account immutable since no transaction can be signed that can change the account. This can be useful if we want to freeze an account contract code and it elegantly solves the problem of when you have multiple account types (as that is the case for Ethereum). ![Screenshot 2023-08-16 at 18.59.10.png](_accounts_images/Screenshot_2023-08-16_at_18.59.10.png) -You can achieve keyless accounts by either removing an existing public key from an account signing with that same key and repeating that action until an account has no keys left, or you can create a new account that has no keys assigned. With account linking you can also have a child account that has no keys but is controlled by the parent. +To achieve keyless accounts, you can remove a public key from an account signing with that same key and repeat that action until an account has no keys left. You can also create a new account that has no keys assigned. With account linking, you can also have a child account that has no keys, but that the parent controls. :::danger -Be careful when removing keys from an existing account, because once an account's total key weights sum to less than 1000, it can no longer be modified. +Be careful when you remove keys from an account, because after an account's total key weights sum to less than 1000, it can no longer be modified. ::: -### **Multi-Sig Accounts** +### **Multi-sig accounts** -Creating a multi-signature account is easily done by managing the account keys and their corresponding weight. To repeat, in order to sign a transaction the keys used to sign it must have weights that sum up to at least 1000. Using this information we can easily see how we can achieve the following cases: +To create a multi-signature account, you can manage the account keys and their corresponding weight. To repeat, in order to sign a transaction the keys used to sign it must have weights that sum up to at least 1000. With this information, we can easily see how we can achieve the following cases: #### 2-of-3 multi-sig quorum @@ -171,74 +170,94 @@ Creating a multi-signature account is easily done by managing the account keys a ![Screenshot 2023-08-16 at 19.34.51.png](_accounts_images/Screenshot_2023-08-16_at_19.34.51.png) -### Key Format +### Key format -We are supporting ECDSA with the curves `P-256` and `secp256k1`. For these curves, the public key is encoded into 64 bytes as `X||Y` where `||` is the concatenation operator. +We support ECDSA with the curves `P-256` and `secp256k1`. For these curves, the public key is encoded into 64 bytes as `X||Y` where `||` is the concatenation operator. - `X` is 32 bytes and is the big endian byte encoding of the `x`-coordinate of the public key padded to 32, i.e. `X=x_31||x_30||...||x_0` or `X = x_31*256^31 + ... + x_i*256^i + ... + x_0`. - `Y` is 32 bytes and is the big endian byte encoding of the `y`-coordinate of the public key padded to 32, i.e. `Y=y_31||y_30||...||y_0` or `Y = y_31*256^31 + ... + y_i*256^i + ... + y_0` -## Account Creation +## Account creation -Accounts are created on the Flow blockchain by calling a special [create account Cadence function](https://cadence-lang.org/docs/language/accounts#account-creation). Once an account is created we can associate a new key with that account. Of course, all that can be done within a single transaction. Keep in mind that there is an account creation fee that needs to be paid. Account creation fees are relatively low, and we expect that wallet providers and exchanges will cover the cost when a user converts fiat to crypto for the first time. +To create accounts on the Flow blockchain, we call a special [create account Cadence function]. After an account is created, we can associate a new key with that account. Of course, all that can be done within a single transaction. Keep in mind that there is an account creation fee that needs to be paid. Account creation fees are relatively low, and we expect that wallet providers and exchanges will cover the cost when a user converts fiat to crypto for the first time. -For development purposes, [you can use Flow CLI to easily create emulator, testnet and mainnet accounts.](../../../build/tools/flow-cli/accounts/create-accounts.md) The account creation fee is paid by a funding wallet so you don't need a pre-existing account to create it. +For development purposes, [you can use Flow CLI to easily create emulator, testnet and mainnet accounts]. The account creation fee is paid by a funding wallet, so you don't need a pre-existing account to create it. -### **Key Generation** +### **Key generation** -Keys should be generated in a secure manner. Depending on the purpose of the keys different levels of caution need to be taken. +You should generate keys in a secure manner, and take different levels of caution for each key's purpose. :::warning -Anyone obtaining access to a private key can modify the account the key is associated with (assuming it has enough weight). Be very careful how you store the keys. +Anyone who obtains access to a private key can modify the account the key is associated with (assuming it has enough weight). Be very careful how you store the keys. ::: -For secure production keys, we suggest using key management services such as [Google key management](https://cloud.google.com/security-key-management) or [Amazon KMS](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.Encryption.Keys.html), which are also supported by our CLI and SDKs. Those services are mostly great when integrated into your application. However, for personal use, you can securely use any [existing wallets](../../../ecosystem/wallets.md) as well as a [hardware Ledger wallet](../../../ecosystem/wallets.md). +For secure production keys, we suggest that you use key management services such as [Google key management] or [Amazon KMS], which are also supported by our CLI and SDKs. Those services are mostly great when integrated into your application. However, for personal use, you can securely use any [existing wallets] as well as a [hardware Ledger wallet]. -## Service Accounts +## Service accounts ### Flow Service Account The Service Account is a special account in Flow that has special permissions to manage system contracts. It is able to mint tokens, set fees, and update network-level contracts. -### Tokens & Fees +### Tokens and fees The Service Account has administrator access to the FLOW token smart contract, so it has authorization to mint and burn tokens. It also has access to the transaction fee smart contract and can adjust the fees charged for transactions execution on Flow. -### Network Management +### Network management The Service Account administers other smart contracts that manage various aspects of the Flow network, such as epochs and (in the future) validator staking auctions. ### Governance -Besides its special permissions, the Service Account is an account like any other in Flow. -The service account is currently controlled by a smart contract governed by the Flow community. -No single entity has the ability to unilaterally execute a transaction -from the service account because it requires four signatures from controlling keys. -The Flow foundation only controls 3 of the keys and the others are controlled -by trusted community members and organizations. +Besides its special permissions, the Service Account is an account like any other in Flow. The service account is currently controlled by a smart contract governed by the Flow community. No single entity has the ability to unilaterally execute a transaction from the service account because it requires four signatures from controlling keys. The Flow foundation only controls three of the keys and the others are controlled by trusted community members and organizations. -## Accounts Retrieval +## Accounts retrieval -You can use the Flow CLI to get account data by running: +You can use the Flow Command Line Interface (CLI) to get account data. To do this, run the following command: ```sh flow accounts get 0xf919ee77447b7497 -n mainnet ``` -Find [more about the command in the CLI docs](../../../build/tools/flow-cli/accounts/get-accounts.md). +Find [more about the command in the CLI docs]. Accounts can be obtained from the access node APIs, currently, there are two gRPC and REST APIs. You can find more information about them here: -**gRPC API** [building-on-flow/nodes/access-api#accounts](../../../protocol/access-onchain-data/index.md#accounts) +**gRPC API** [building-on-flow/nodes/access-api#accounts] -**REST API** [http-api#tag/Accounts](/http-api#tag/Accounts) +**REST API** [http-api#tag/Accounts] There are multiple SDKs implementing the above APIs for different languages: -**Javascript SDK** [tools/clients/fcl-js](../../../build/tools/clients/fcl-js/index.md) - -**Go SDK** [tools/clients/flow-go-sdk](../../../build/tools/clients/flow-go-sdk/index.md) - -Find a list of all SDKs here: [tools/clients](../../../build/tools/clients/index.md) +**Javascript SDK** [tools/clients/fcl-js] + +**Go SDK** [tools/clients/flow-go-sdk] + +Find a list of all SDKs here: [tools/clients] + + + +["Fee"]: ./fees.md +[fixed amount of storage]: ./fees.md#storage +[hold a Flow vault that holds a balance and is part of the FungibleToken standard]: ./flow-token.md +[transaction fees and storage fees]: ./fees.md +[`FlowStorageFees`]: ../core-contracts/05-flow-fees.md#flowstoragefees +[Cadence contracts]: https://cadence-lang.org/docs/language/contracts +[storage capacity is directly tied to the balance of Flow tokens]: ./fees.md#storage +[OID 1.2.840.10045.3.1.7]: http://oid-info.com/get/1.2.840.10045.3.1.7 +[OID 1.3.132.0.10]: http://oid-info.com/get/1.3.132.0.10 +[defined in Cadence]: https://cadence-lang.org/docs/language/crypto#signing-algorithms +[create account Cadence function]: https://cadence-lang.org/docs/language/accounts#account-creation +[you can use Flow CLI to easily create emulator, testnet and mainnet accounts]: ../../../build/tools/flow-cli/accounts/create-accounts.md +[Google key management]: https://cloud.google.com/security-key-management +[Amazon KMS]: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.Encryption.Keys.html +[existing wallets]: ../../../ecosystem/wallets.md +[hardware Ledger wallet]: ../../../ecosystem/wallets.md) +[more about the command in the CLI docs]: ../../../build/tools/flow-cli/accounts/get-accounts.md +[building-on-flow/nodes/access-api#accounts]: ../../../protocol/access-onchain-data/index.md#accounts +[http-api#tag/Accounts]: /http-api#tag/Accounts +[tools/clients/fcl-js]: ../../../build/tools/clients/fcl-js/index.md +[tools/clients/flow-go-sdk]: ../../../build/tools/clients/flow-go-sdk/index.md +[tools/clients]: ../../../build/tools/clients/index.md \ No newline at end of file diff --git a/docs/build/cadence/basics/blocks.md b/docs/build/cadence/basics/blocks.md index 39e3faee66..aa015b1b1a 100644 --- a/docs/build/cadence/basics/blocks.md +++ b/docs/build/cadence/basics/blocks.md @@ -21,48 +21,46 @@ keywords: # Blocks -## Overview +Blocks are entities that make up the Flow blockchain. Each block contains a list of [transactions] that were executed and as a result, changed the global blockchain state. Each block is identified by a unique ID which is a cryptographic hash of the block contents. Block also includes a link to the parent block ID, which creates a linked list of blocks called the Flow blockchain. -Blocks are entities that make up the Flow blockchain. Each block contains a list of [transactions](./transactions.md) that were executed and as a result, changed the global blockchain state. Each block is identified by a unique ID which is a cryptographic hash of the block contents. Block also includes a link to the parent block ID creating a linked list of blocks called the Flow blockchain. - -The unique block ID serves as proof of the block contents which can be independently validated by any observer. Interesting cryptographic properties of the hash that make up the block ID guarantee that if any change is made to the block data it would produce a different hash and because blocks are linked, a different hash would break the link as it would no longer be referenced in the next block. +The unique block ID serves as proof of the block contents which any oberver can independently validate. Interesting cryptographic properties of the hash that make up the block ID guarantee that if any change is made to the block data, it would produce a different hash. Because blocks are linked, a different hash would break the link as it would no longer be referenced in the next block. A very basic representation of blocks is: ![Screenshot 2023-08-16 at 15.16.38.png](_blocks_images/Screenshot_2023-08-16_at_15.16.38.png) -Blocks are ordered starting from the genesis block 0 up to the latest block. Each block contains an ordered list of transactions. This is how the Flow blockchain preserves the complete history of all the changes made to the state from the beginning to the current state. +Blocks are ordered from the genesis block 0 up to the latest block. Each block contains an ordered list of transactions. This is how the Flow blockchain preserves the complete history of all the changes made to the state from the start to the current state. -Each block contains more data which is divided into **block header** and **block payload**. There are many representations of block data within the Flow protocol. APIs, node types, and specific components within the node may view a block from differing perspectives. For the purpose of this documentation, we will talk about block data we expose through APIs to the clients. +Each block contains more data which is divided into **block header** and **block payload**. There are many representations of block data within the Flow protocol. APIs, node types, and specific components within the node may view a block from different perspectives. For the purpose of this document, we will talk about block data we expose through APIs to the clients. ![Screenshot 2023-08-16 at 10.50.53.png](_blocks_images/Screenshot_2023-08-16_at_10.50.53.png) -### Block Header +### Block header The Block header contains the following fields: -- **ID** represents the block's unique identifier, which is derived from the hashing block header including the payload hash. The algorithm used on Flow to hash the content and get an identifier is SHA3 256. This ID is a commitment to all the values in the block staying the same. -- **Parent ID** is a link to the previous block ID in the list making up the blockchain. -- **Height** is the block sequence number, where block 0 was the first block produced, and each next block increments the value by 1. -- **Timestamp** is the timestamp at which this block was proposed by the consensus node. Depending on your use case this time might not be accurate enough, [read more about measuring time on the Flow blockchain](https://cadence-lang.org/docs/measuring-time#time-on-the-flow-blockchain). -- **Payload Hash** represents the payload hash that is included when producing the ID of the block. Payload hash is calculated by taking Merkle root hashes of collection guarantees, seals, execution receipts, and execution results and hashing them together. More on each of the values in the block payload section. +- **ID** represents the block's unique identifier, which is derived from the hashing block header, which includes the payload hash. The algorithm used on Flow to hash the content and get an identifier is SHA3 256. This ID is a commitment to all the values in the block staying the same. +- **Parent ID** is a link to the previous block ID in the list that makes up the blockchain. +- **Height** is the block sequence number, where block 0 was the first block produced, and each next block increments the value by one. +- **Timestamp** is the timestamp at which this block was proposed by the consensus node. Depending on your use case, this time might not be accurate enough, [read more about how to measure time on the Flow blockchain]. +- **Payload Hash** represents the payload hash that is included when producing the ID of the block. To calculate the payload hash take Merkle root hashes of collection guarantees, seals, execution receipts, and execution results and hash them together. For more information, see the block payload section below. -### Block Payload +### Block payload The block payload contains the following fields: -- **Collection Guarantees** is a list of collection IDs with the signatures from the collection nodes that produced the collections. This acts as a guarantee by collection nodes that [transaction data](./transactions.md) in the collection will be available on the collection node if requested by other nodes at a later time. Flow purposely skips including transaction data in a block, making blocks as small as possible, and the production of new blocks by consensus nodes fast, that is because consensus nodes have to sync the proposed block between nodes, and that data should be the smallest possible. The consensus nodes don't really care what will a transaction do as long as it's valid, they only need to define an order of those transactions in a block. +- **Collection Guarantees** is a list of collection IDs with the signatures from the collection nodes that produced the collections. This acts as a guarantee by collection nodes that [transactions]data in the collection will be available on the collection node if requested by other nodes at a later time. Flow purposely skips including transaction data in a block, makes blocks as small as possible, and produces new blocks by consensus nodes fast, because consensus nodes have to sync the proposed block between nodes, and that data should be the smallest possible. The consensus nodes don't really care what will a transaction do as long as it's valid, they only need to define an order of those transactions in a block. - **Block Seals** is the attestation by verification nodes that the transactions in a previously executed block have been verified. This seals a previous block referenced by the block ID. It also references the result ID and execution root hash. It contains signatures of the verification nodes that produced the seal. -## Lifecycle and Status +## Lifecycle and status -Block status is not a value stored inside the block itself but it represents the lifecycle of a block. We derive this value based on the block inclusion in the Flow blockchain and present it to the user as it acts as an important indicator of the finality of the changes the block contains. +Block status is not a value stored inside the block itself, but it represents the lifecycle of a block. We derive this value based on the block inclusion in the Flow blockchain and present it to the user as it acts as an important indicator of the finality of the changes the block contains. -Here we'll give an overview of the different phases a block goes through. [More details can be found in the whitepaper](https://flow.com/technical-paper). Also, a lot of the block states are not necessarily important to the developer but only important to the functioning of the Flow blockchain. +Here, we'll give an overview of the different phases a block goes through. [More details can be found in the whitepaper]. Also, a lot of the block states are not necessarily important to the developer but only important to the Flow blockchain's function. -New blocks are constantly being proposed even if no new transactions are submitted to the network. Consensus nodes are in charge of producing blocks. They use a consensus algorithm (an implementation of HotStuff) to agree on what the new block will be. A block contains the ordered list of collections and each collection contains an ordered list of transactions. This is an important fact to reiterate. A block serves as a list of transitions to the Flow state machine. It documents, as an ordered list, all the changes transactions will make to the state. +New blocks are constantly being proposed even if no new transactions are submitted to the network. Consensus nodes are in charge of blocks production. They use a consensus algorithm (an implementation of HotStuff) to agree on what the new block will be. A block contains the ordered list of collections and each collection contains an ordered list of transactions. This is an important fact to reiterate. A block serves as a list of transitions to the Flow state machine. It documents, as an ordered list, all the changes transactions will make to the state. -A block that is [agreed upon by the consensus nodes using an implementation of HotStuff consensus algorithm](https://arxiv.org/pdf/2002.07403.pdf) to be the next block is **finalized**. This means the block won't change anymore and it will next be executed by the execution node. Please be careful because until a block is **sealed** the changes are not to be trusted. After verification nodes validate and agree on the correctness of execution results, a block is sealed and consensus nodes will include these seals in the new block. +A block that is [agreed upon by the consensus nodes via an implementation of HotStuff consensus algorithm] to be the next block is **finalized**. This means the block won't change anymore and it will next be executed by the execution node. Be careful because until a block is **sealed** the changes are not to be trusted. After verification nodes validate and agree on the correctness of execution results, a block is sealed and consensus nodes will include these seals in the new block. In summary, a block can be either **finalized** which guarantees transactions included in the block will stay the same and will be executed, and **sealed** which means the block execution was verified. @@ -76,18 +74,32 @@ You can use the Flow CLI to get the block data by running: flow blocks get latest -network mainnet ``` -Find [more about the command in the CLI docs](../../../build/tools/flow-cli/get-flow-data/get-blocks.md). +Find [more about the command in the CLI docs] Blocks can be obtained from the access node APIs, currently, there are two gRPC and REST APIs. You can find more information about them here: -[**gRPC Block API**](../../../protocol/access-onchain-data/index.md#blocks) +[**gRPC Block API**] + +[**REST Block API**] + +There are multiple SDKs that implement the above APIs for different languages: -[**REST Block API**](/http-api#tag/Blocks) +[**Javascript SDK**] -There are multiple SDKs implementing the above APIs for different languages: +[**Go SDK**] -[**Javascript SDK**](../../../build/tools/clients/fcl-js/index.md) +Find a list of all SDKs [here]. -[**Go SDK**](../../../build/tools/clients/flow-go-sdk/index.md) + -Find a list of all SDKs [here](../../../build/tools/clients/index.md) +[read more about how to measure time on the Flow blockchain]: https://cadence-lang.org/docs/measuring-time#time-on-the-flow-blockchain +[read more about measuring time on the Flow blockchain]: https://cadence-lang.org/docs/measuring-time#time-on-the-flow-blockchain +[transactions]: ./transactions.md +[More details can be found in the whitepaper]: https://flow.com/technical-paper +[agreed upon by the consensus nodes via an implementation of HotStuff consensus algorithm]: https://arxiv.org/pdf/2002.07403.pdf +[more about the command in the CLI docs]: ../../../build/tools/flow-cli/get-flow-data/get-blocks.md +[**gRPC Block API**]: ../../../protocol/access-onchain-data/index.md#blocks +[**REST Block API**]: /http-api#tag/Blocks +[**Javascript SDK**]: ../../../build/tools/clients/fcl-js/index.md +[**Go SDK**]: ../../../build/tools/clients/flow-go-sdk/index.md +[here]: ../../../build/tools/clients/index.md \ No newline at end of file diff --git a/docs/build/cadence/basics/collections.md b/docs/build/cadence/basics/collections.md index f8bbac850c..b87ab6dd79 100644 --- a/docs/build/cadence/basics/collections.md +++ b/docs/build/cadence/basics/collections.md @@ -21,30 +21,40 @@ keywords: # Collections -Collections link blocks and transactions together. Collection node clusters make these collections (using the HotStuff consensus algorithm), made up of an ordered list of one or more hashes of [signed transactions](./transactions.md). In order to optimize data, blocks don't contain transactions (as they do on Ethereum). The benefits are transaction data does not get transferred to consensus nodes on the network which optimizes transfer speed and this architecture allows scaling of ingestion speed by adding collection clusters. Consensus nodes need to only agree on the order of transactions to be executed, they don't need to know the transaction payload, thus making blocks and collections lightweight. Collection nodes hold transaction payloads for anyone who requests them (e.g. execution nodes). +Collections link blocks and transactions together. Collection node clusters make these collections (via the HotStuff consensus algorithm), made up of an ordered list of one or more hashes of [signed transactions]. In order to optimize data, blocks don't contain transactions (as they do on Ethereum). The benefits are transaction data does not get transferred to consensus nodes on the network which optimizes transfer speed, and this architecture allows you to add collection clusters, which scales ingestion speed. Consensus nodes need to only agree on the order of transactions to be executed, they don't need to know the transaction payload, which makes blocks and collections lightweight. Collection nodes hold transaction payloads for anyone who requests them (for example, execution nodes). ![Screenshot 2023-08-17 at 19.50.39.png](_collection_images/Screenshot_2023-08-17_at_19.50.39.png) -## Collection Retrieval +## Collection retrieval -You can use the Flow CLI to get the collection data by running: +To use the Flow CLI to get the collection data, run the following command: ```sh flow collections get caff1a7f4a85534e69badcda59b73428a6824ef8103f09cb9eaeaa216c7d7d3f -n mainnet ``` -Find [more about the command in the CLI docs](../../../build/tools/flow-cli/get-flow-data/get-collections.md). +Find [more about the command in the CLI docs]. Collections can be obtained from the access node APIs, currently, there are two gRPC and REST APIs. You can find more information about them here: -[**gRPC Collection API**](../../../protocol/access-onchain-data/index.md#collections) +[**gRPC Collection API**] -[**REST Collection API**](/http-api#tag/Collections) +[**REST Collection API**] -There are multiple SDKs implementing the above APIs for different languages: +There are multiple SDKs that implement the above APIs for different languages: -[**Javascript SDK**](../../../build/tools/clients/fcl-js/index.md) +[**Javascript SDK**] -[**Go SDK**](../../../build/tools/clients/flow-go-sdk/index.md) +[**Go SDK**] -Find a list of all SDKs [here](../../../build/tools/clients/index.md) +Find a list of all SDKs [here]. + + + +[signed transactions]: ./transactions.md +[more about the command in the CLI docs]: ../../../build/tools/flow-cli/get-flow-data/get-blocks.md +[**gRPC Collection API**]: ../../../protocol/access-onchain-data/index.md#collections +[**REST Collection API**]: /http-api#tag/Collections +[**Javascript SDK**]: ../../../build/tools/clients/fcl-js/index.md +[**Go SDK**]: ../../../build/tools/clients/flow-go-sdk/index.md +[here]: ../../../build/tools/clients/index.md \ No newline at end of file diff --git a/docs/build/cadence/basics/events.md b/docs/build/cadence/basics/events.md index 13a4ba0728..65e0b87841 100644 --- a/docs/build/cadence/basics/events.md +++ b/docs/build/cadence/basics/events.md @@ -24,9 +24,9 @@ keywords: Flow events are special values that are emitted on the network during the execution of a Cadence program and can be observed by off-chain observers. -Events are defined as Cadence code and you should [read Cadence documentation](https://cadence-lang.org/docs/language/events) to understand how to define them. +Events are defined as Cadence code and you should [read the Cadence documentation] to understand how to define them. -Since transactions don't have return values you can leverage events to broadcast certain changes the transaction caused. Clients listening on Flow networks (apps) can listen to these events being emitted and react. +Since transactions don't have return values you can leverage events to broadcast certain changes the transaction caused. Clients taht listen on Flow networks (apps) can listen to these events that are emitted and react. ![Screenshot 2023-08-18 at 14.09.33.png](_events_images/Screenshot_2023-08-18_at_14.09.33.png) @@ -39,7 +39,7 @@ Events consist of the **event name** and an optional **payload**. ![Screenshot 2023-08-18 at 13.59.01.png](_events_images/Screenshot_2023-08-18_at_13.59.01.png) -## Core Events +## Core events Core events are events emitted directly from the FVM (Flow Virtual Machine). The events have the same name on all networks and do not follow the same naming as user-defined events (they have no address). @@ -57,11 +57,11 @@ A list of events that are emitted by the Flow network is: | flow.InboxValueUnpublished | Event that is emitted when a Capability is unpublished from an account. | | flow.InboxValueClaimed1 | Event that is emitted when a Capability is claimed by an account. | -For more details [on the core events, you can read Cadence reference documentation](https://cadence-lang.org/docs/language/core-events). +For more details [on the core events, you can read Cadence reference documentation]. ## User-defined events -Events that are defined inside contracts and when emitted follow a common naming schema. The schema consists of 4 parts: +Events that are defined inside contracts and when emitted follow a common naming schema. The schema consists of four parts: ```cadence A.{contract address}.{contract name}.{event type} @@ -71,21 +71,17 @@ An example event would look like: ![Screenshot 2023-08-18 at 14.30.36.png](_events_images/Screenshot_2023-08-18_at_14.30.36.png) -The first `A` means the event is originating from a contract, which will always be the case for user-defined events. The contract address as the name implies is the location of a contract deployed on the Flow network. Next, is the name of the contracted event originates from, and last is the event type defined in the contract. +The first `A` means the event originates from a contract, which will always be the case for user-defined events. The contract address as the name implies is the location of a contract deployed on the Flow network. Next, is the name of the contracted event originates from, and last is the event type defined in the contract. There is an unlimited amount of events that can be defined on Flow, but you should know about the most common ones. -### Fungible Token Events +### Fungible token events -All fungible token contracts, including [The FLOW Token contract](../core-contracts/03-flow-token.md), -use the [fungible token standard on Flow](../core-contracts/02-fungible-token.md). -As with any contract, the standard emits events when interacted with. -When any fungible token is transferred, standard events are emitted. -You can find a lot of details on the events emitted in the [Fungible Token documentation](../core-contracts/02-fungible-token.md). +All fungible token contracts, which includes [The FLOW Token contract], use the [fungible token standard on Flow]. As with any contract, the standard emits events when interacted with. When any fungible token is transferred, standard events are emitted. You can find a lot of details on the events emitted in the [Fungible Token documentation]. -The most common events are when tokens are transferred which is accomplished with two actions: withdrawing tokens from the payer and depositing tokens in the receiver. Each of those actions has a corresponding event: +The most common events are when tokens are transferred which is accomplished with two actions: withdraw tokens from the payer and deposit tokens in the receiver. Each of those actions has a corresponding event: -**Withdraw Tokens** +**Withdraw tokens** Event name: `FungibleToken.Withdrawn` @@ -102,7 +98,7 @@ Mainnet event: `A.f233dcee88fe0abe.FungibleToken.Withdrawn` Testnet event: `A.9a0766d93b6608b7.FungibleToken.Withdrawn` -**Deposit Tokens** +**Deposit tokens** ```cadence event Deposited(type: String, @@ -159,3 +155,11 @@ Events: - inclusionEffort (UFix64): 1.00000000 - executionEffort (UFix64): 0.00000000 ``` + + + +[read the Cadence documentation]: https://cadence-lang.org/docs/language/events +[The FLOW Token contract]: ../core-contracts/03-flow-token.md +[fungible token standard on Flow]: ../core-contracts/02-fungible-token.md +[Fungible Token documentation]: ../core-contracts/02-fungible-token.md +[on the core events, you can read Cadence reference documentation]: https://cadence-lang.org/docs/language/core-events \ No newline at end of file diff --git a/docs/build/cadence/basics/fees.md b/docs/build/cadence/basics/fees.md index 35780c3380..58680e4d23 100644 --- a/docs/build/cadence/basics/fees.md +++ b/docs/build/cadence/basics/fees.md @@ -23,44 +23,44 @@ keywords: :::info -Are you an EVM developer looking for information about EVM Accounts on Flow? If so, check out the EVM specific documentation [here](../../../build/evm/fees.md) +Are you an EVM developer who wants information about EVM Accounts on Flow? If so, check out the EVM specific documentation [here] ::: # Fees -## Transaction Fees +## Transaction fees -A transaction fee is a cost paid in Flow by the payer account and is required for a transaction to be included in the Flow blockchain. Fees are necessary for protecting the network against spam/infinite running transactions and to provide monetary incentives for participants that make up the Flow network. +A transaction fee is a cost paid in Flow by the payer account and is required for a transaction to be included in the Flow blockchain. Fees are necessary to protect the network against spam or infinite running transactions and to provide monetary incentives for participants that make up the Flow network. -On Flow, transaction fees are determined using `compute units (CU)`, a metric that captures the effort needed to include and execute a transaction. Compute units function similarly to gas in EVM systems but are derived differently. The final fee paid by the user is calculated by multiplying the transaction’s total compute units by the current compute-unit price, with all fees payable in FLOW. +On Flow, transaction fees are determined with `compute units (CU)`, a metric that captures the effort needed to include and execute a transaction. Compute units function similarly to gas in EVM systems but are derived differently. To calculate the final fee paid by the user, multiply the transaction’s total compute units by the current compute-unit price, with all fees payable in FLOW. -A transaction fee is paid regardless of whether a transaction succeeds or fails. If the payer account doesn't have sufficient Flow balance to pay for the transaction fee, the transaction will fail. We can limit the transaction fee to some extent by providing the compute unit limit value when submitting the transaction. +A transaction fee is paid regardless of whether a transaction succeeds or fails. If the payer account doesn't have sufficient Flow balance to pay for the transaction fee, the transaction will fail. We can provide the compute unit limit value when you submit the transaction, which helps limit the transaction fee. -### Understanding the need for transaction fees +### Understand the need for transaction fees One of the ways that a single computer that no one owns and anyone can use from being monopolized by any part is to charge a fee measured by the amount of computation needed to execute code. All blockchains implement a form of this system. -Segmented transaction fees are essential to ensure fair pricing based on the impact on the network. For instance, more heavy operations will require more resources to process and propagate transactions. Common operations, however, will stay reasonably priced. +Segmented transaction fees are essential to ensure fair pricing based on the impact on the network. For instance, heavier operations will require more resources to process and propagate transactions. Common operations, however, will stay reasonably priced. -Fees improve the overall security of the network by making malicious actions (eg spam) on the network less viable. They also prevent the computer from crashing in the event that an infinite loop is started maliciously or accidentally. +To improve the overall security of the network, fees makie malicious actions (such as spam) on the network less viable. They also prevent a computer crash if an infinite loop is started maliciously or accidentally. The unique Flow architecture is targeted at high throughput. It makes it easier to have slack in the system, so short spikes can be handled more gracefully. -### **Fee Structure** +### **Fee structure** Each transaction fee consists of three components: execution fee, inclusion fee, and network surge factor. ![Screenshot 2023-08-17 at 17.16.32.png](_fees_images/Screenshot_2023-08-17_at_17.16.32.png) -**Execution Fee** +**Execution fee** The execution effort for a transaction is determined by the code path the transaction takes and the actions it does. The actions that have an associated execution effort cost can be separated into four broad buckets: -- Normal lines of cadence, loops, or function calls -- Reading data from storage, charged per byte read -- Writing data to storage, charged per byte written -- Account creation +- Normal lines of cadence, loops, or function calls. +- Reading data from storage, charged per byte read. +- Writing data to storage, charged per byte written. +- Account creation. | Transaction Type | Estimated cost (FLOW) | | -------------------------------------------------- | --------------------- | @@ -72,29 +72,29 @@ The execution effort for a transaction is determined by the code path the transa | Create 10 accounts | 0.00002261 | | Deploying a contract that is ~50kb | 0.00002965 | -**Inclusion Fee** +**Inclusion fee** -The inclusion effort of a transaction represents the work needed for: +The inclusion effort of a transaction represents the work needed to: -- Including the transaction in a block -- Transporting the transaction information from node to node -- Verifying transaction signatures +- Include the transaction in a block +- Transport the transaction information from node to node +- Verify transaction signatures Right now, the inclusion effort is always 1.0 and the inclusion effort cost is fixed to `0.000001`. -**Surge Factor** +**Surge factor** A network surge factor is applied when the network is busy due to an increased influx of transactions required to be processed or a decrease in the ability to process transactions. -See [FLIP 336](https://github.com/onflow/flips/blob/main/governance/20250727-dynamic-transaction-fees.md) for details on this calculation. +See [FLIP 336] for details on this calculation. -**Estimating transaction costs** +**Estimat transaction costs** -Cost estimation is a two-step process. First, you need to gather the execution effort with either the emulator, on testnet, or on mainnet. Second, you use the execution effort for a transaction to calculate the final fees using one of the JavaScript or Go FCL SDKs. +Cost estimation is a two-step process. First, you need to gather the execution effort with either the emulator, on testnet, or on mainnet. Second, you use the execution effort for a transaction to calculate the final fees with one of the JavaScript or Go FCL SDKs. ## Storage -Flow's approach to storage capacity is a bit similar to some banks' pricing models, where maintaining a minimum balance prevents monthly account fees. Here, the amount of data in your account determines your minimum balance. If you fall below the minimum balance, you cannot transact with your account, except for deposits or deleting data. The essence of storage fee model is that it ensures data availability without continuously charging fees for storage, while also preventing abuses that could burden the network's storage resources. This distinction between current state and blockchain history is crucial for understanding storage requirements and limitations. +Flow's approach to storage capacity is a bit similar to some banks' pricing models, where you maintain a minimum balance to prevent monthly account fees. Here, the amount of data in your account determines your minimum balance. If you fall below the minimum balance, you can't transact with your account, except for deposits or data deletion. The essence of storage fee model is that it ensures data availability but doesn't continuously charge fees for storage, and also prevents abuses that could burden the network's storage resources. This distinction between current state and blockchain history is crucial for you to understand storage requirements and limitations. Each Flow account has associated storage used. The account's storage used is the byte size of all the data stored in the account's storage. Accounts also have a storage capacity, which is directly tied to the amount of Flow tokens an account has. The account can, without any additional cost, use any amount of storage up to its storage capacity. @@ -104,7 +104,7 @@ If a transaction puts an account over storage capacity, that transaction fails a ::: -**Storage Capacity** +**Storage capacity** The storage capacity of an account is dictated by the amount of FLOW it has. @@ -116,21 +116,21 @@ The **minimum amount of FLOW an account can have is 0.001**. This minimum is pro The minimum account reservation ensures that most accounts won't run out of storage capacity if anyone deposits anything (like an NFT) to the account. -Currently, the amount required to store 100 MB in account storage is 1 Flow. +Currently, the amount required to store 100 MB in account storage is one Flow. ![Screenshot 2023-08-17 at 17.27.50.png](_fees_images/Screenshot_2023-08-17_at_17.27.50.png) -Please note that storing data in an account on Flow doesn't charge tokens from the account, it just makes sure you will keep the tokens as a reserve. Once the storage is freed up you can transfer the Flow tokens. +When you store data in an account on Flow, it doesn't charge tokens from the account. Rather, it just makes sure you will keep the tokens as a reserve. After the storage is freed up, you can transfer the Flow tokens. -### Storage Capacity of the Payer +### Storage capacity of the payer -The storage capacity of the Payer of a transaction is generally computed the same way as the capacity of any other account, however, the system needs to account for the transaction fees the payer will incur at the end of the transaction. The final transaction fee amount is not fully known at this step, only when accounts are checked for storage compliance. If their storage used is more than their storage capacity, the transaction will fail. +The storage capacity of the Payer of a transaction is generally computed the same way as the capacity of any other account. However, the system needs to account for the transaction fees the payer will incur at the end of the transaction. The final transaction fee amount is not fully known at this step, only when accounts are checked for storage compliance. If their storage used is more than their storage capacity, the transaction will fail. Because of this, the payer's balance is conservatively considered to be lower by the maximum possible transaction fees, when checking for storage compliance. The maximum transaction fee of a specific transaction is the transaction fee as if the transaction would have used up all of its execution effort limit. -### Storage Used +### Storage used -All data that is in an account's storage counts towards storage used. Even when an account is newly created it is not empty. There are already some items in its storage: +All data that is in an account's storage counts towards storage used. Even when an account is newly created, it is not empty. There are already some items in its storage: - Metadata that marks that the account exists. - An empty FLOW vault, and stored receiver capability. @@ -138,13 +138,13 @@ All data that is in an account's storage counts towards storage used. Even when - Smart contracts deployed on the account if the account was created with contracts. - The value of the account's storage used as an unsigned integer. -Adding additional keys, smart contracts, capabilities, resources, etc. to the account counts towards storage used. +When you add additional keys, smart contracts, capabilities, resources, and so on to the account, it counts towards storage used. Data stored on the Flow blockchain is stored in a key-value ledger. Each item's key contains the address that owns the item and the path to the item. An account can have many keys, therefore flow considers the account key items are stored with. This means that the storage used by each item is the byte length of the item plus the byte length of the item's key. ### Maximum available balance -Due to the storage restrictions, there is a maximum available balance that user can withdraw from the wallet. The core contract [`FlowStorageFees`](../core-contracts/05-flow-fees.md#flowstoragefees) provides a function to retrieve that value: +Due to the storage restrictions, there is a maximum available balance that user can withdraw from the wallet. The core contract [`FlowStorageFees`] provides a function to retrieve that value: ```cadence import "FlowStorageFees" @@ -166,11 +166,11 @@ access(all) fun main(address: Address): UFix64 { ``` -## Practical Understanding of Fees +## Practically understand fees -**Using Flow Emulator** +**Use the Flow emulator** -You can start the [emulator using the Flow CLI](../../../build/tools/emulator/index.md#running-the-emulator-with-the-flow-cli). Run your transaction and take a look at the events emitted: +You can start the [emulator with the Flow CLI]. Run your transaction and take a look at the events emitted: ```shell 0|emulator | time="2022-04-06T17:13:22-07:00" level=info msg="⭐ Transaction executed" computationUsed=3 txID=a782c2210c0c1f2a6637b20604d37353346bd5389005e4bff6ec7bcf507fac06 @@ -180,11 +180,11 @@ You should see the `computationUsed` field. Take a note of the value, you will u **On testnet or mainnet** -Once a transaction is completed, you can use an explorer like [Flowscan](https://flowscan.io/) to review the transaction details and events emitted. For Flowscan, you can open the transaction in question and look for the event `FeesDeducted` from the [`FlowFees`](https://github.com/onflow/flow-core-contracts/blob/master/contracts/FlowFees.cdc) contract: +When a transaction is completed, you can use an explorer like [Flowscan] to review the transaction details and events emitted. For Flowscan, you can open the transaction in question and look for the event `FeesDeducted` from the [`FlowFees`] contract: ![flowscan-fees](./_fees_images/flowscan-fees.png) -In the event data on the right side, you will see a set of fields representing [the fees for a specific transaction.](https://github.com/onflow/flow-core-contracts/blob/master/contracts/FlowFees.cdc#L14): +In the event data on the right side, you will see a set of fields that represent [the fees for a specific transaction.]: - Total Fees Paid - Inclusion Effort @@ -192,9 +192,9 @@ In the event data on the right side, you will see a set of fields representing [ Take a note of the last value in the list - the `executionEffort` value. You will use it in the next step. -### Calculating final costs +### Calculate final costs -The cost for transactions can be calculated using the following FCL scripts on mainnet/testnet respectively. +The cost for transactions can be calculated with the following FCL scripts on mainnet/testnet respectively. **On mainnet** @@ -220,15 +220,19 @@ access(all) fun main( } ``` -## Configuring execution limits +## Configure execution limits FCL SDKs allow you to set the execution effort limit for each transaction. Based on the execution effort limit determined in the previous step, you should set a reasonable maximum to avoid unexpected behavior and protect your users. The final transaction fee is computed from the actual execution effort used up to this maximum. -> **Note**: Keep in mind that the limits are not for the final fees that the user will have to pay. The limits are for the execution efforts specifically. +:::info + +Keep in mind that the limits are not for the final fees that the user will have to pay. The limits are for the execution efforts specifically. -It is important to set a limit that isn't too high or too low. If it is set too high, the payer needs to have more funds in their account before sending the transaction. If it is too low, the execution could fail and all state changes are dropped. +::: -**Using FCL JS SDK** +It is important to set a limit that isn't too high or too low. If it is set too high, the payer needs to have more funds in their account before they send the transaction. If it is too low, the execution could fail and all state changes are dropped. + +**Use FCL JS SDK** You need to set the `limit` parameter for the `mutate` function, for example: @@ -252,7 +256,7 @@ const transaction = await fcl.tx(transactionId).onceExecuted(); console.log(transaction;) ``` -**Using FCL Go SDK** +**Use FCL Go SDK** You need to call the `SetComputeLimit` method to set the fee limit, for example: @@ -277,11 +281,11 @@ tx := flow.NewTransaction(). ### Maximum transaction fees of a transaction -The maximum possible fee imposed on the payer for a transaction can be calculated as the **inclusion cost plus the execution cost**. The execution cost is the fee calculated for running the transaction based on the [execution effort limit maximum specified](#configuring-execution-limits). +The maximum possible fee imposed on the payer for a transaction can be calculated as the **inclusion cost plus the execution cost**. The execution cost is the fee calculated to run the transaction based on the [execution effort limit maximum specified]. The payer will never pay more than this amount for the transaction. -## Optimizing Cadence code to reduce effort +## Optimize Cadence code to reduce effort Several optimizations can lead to reduced execution time of transactions. Below is a list of some practices. This list is not exhaustive but rather exemplary. @@ -349,7 +353,7 @@ access(all) fun add(_ a: Int, _ b: Int): Int { **Avoid excessive load and save operations** -Avoid costly loading and storage operations and [borrow references](https://cadence-lang.org/docs/design-patterns#avoid-excessive-load-and-save-storage-operations-prefer-in-place-mutations) where possible, for example: +Avoid costly loading and storage operations and [borrow references] where possible, for example: ```cadence transaction { @@ -372,25 +376,25 @@ transaction { **Limit accounts created per transaction** -Creating accounts and adding keys are associated with costs. Try to only create accounts and keys when necessary. +Try to only create accounts and add keys when necessary, because there are costs associated with these actions. -**Check user's balance before executing transactions** +**Check user's balance before you execute transactions** You should ensure that the user's balance has enough balance to cover the highest possible fees. For FT transfers, you need to cover the amount to transfer in addition to the highest possible fees. -## Educating users +## Educate users -Wallets will handle the presentation of the final transaction costs but you can still facilitate the user experience by educating them within your application. +Wallets will handle the presentation of the final transaction costs, but you can still facilitate the user experience when you educate them within your application. -If your user is using self-custody wallets, they may have to pay the transaction and want to understand the fees. Here are some suggestions. +If your user has self-custody wallets, they may have to pay the transaction and want to understand the fees. Here are some suggestions. **Explain that costs can vary depending on the network usage** Suggested message: "Fees improve the security of the network. They are flexible to ensure fair pricing based on the impact on the network." -**Explain that waiting for the network surge to pass is an option** +**Explain that they can wait for the network surge to pass** -Inevitably, network surges will cause higher fees. Users who might want to submit a transaction while the network usage is surging should consider sending the transaction at a later time to reduce costs. +Inevitably, network surges will cause higher fees. Users who might want to submit a transaction while the network usage surges may want to send the transaction at a later time to reduce costs. **Explain that the wallet might not allow the transaction due to a lack of funds** @@ -400,21 +404,25 @@ If dynamic fees increase to the highest possible level, the user's fund might no There are several places to learn more about transaction fees: -- [FLIP-660](https://github.com/onflow/flow/pull/660) -- [FLIP-753](https://github.com/onflow/flow/pull/753) -- [Flow Fees Contract](https://github.com/onflow/flow-core-contracts/blob/master/contracts/FlowFees.cdc) +- [FLIP-660] +- [FLIP-753] +- [Flow Fees Contract] -> **Note**: If you have thoughts on the implementation of transaction fees on Flow, you can [leave feedback on this forum post](https://forum.flow.com/t/variable-transaction-fees-are-coming-to-flow/2941). +:::info + +If you have thoughts on the implementation of transaction fees on Flow, you can [leave feedback on this forum post]. + +::: ## FAQs **When will the fee update go into effect?** -The updates were rolled out with the [Spork on April 6, 2022](../../../protocol/node-ops/node-operation/past-upgrades#mainnet-17), and were enabled on [June 1st](https://forum.flow.com/t/permissionless-contract-deployment-progress/2981) during the [weekly epoch transition](https://github.com/onflow/service-account/tree/main/transactions/set-execution-effort-weights/2022/jun-1). +The updates were rolled out with the [Spork on April 6, 2022], and were turned on [June 1st] during the [weekly epoch transition]. **Why are fees collected even when transactions fail?** -Broadcasting and verifying a transaction requires execution, so costs are deducted appropriately. +Costs are deducted appropriately when you or your users broadcast and verify a transaction. **What execution costs are considered above average?** @@ -426,11 +434,14 @@ Yes. **What is the lowest execution cost?** -The lowest execution cost is 1. This means your transaction included one function call or loop that didn't read or write any date. +The lowest execution cost is one. This means your transaction included one function call or loop that didn't read or write any date. **Can I determine how much a transaction will cost on mainnet without actually paying?** -You can estimate the costs in a two-way process: 1) determine execution costs for transactions (emulator or testnet) and 2) use an FCL SDK method to calculate the final transaction fees. +You can estimate the costs in a two-way process: + +1. Determine execution costs for transactions (emulator or testnet). +2. Use an FCL SDK method to calculate the final transaction fees. **How accurate will testnet fees be to mainnet fees?** @@ -438,7 +449,7 @@ Final fees are determined by the surge factor on the network. The surge factor f **I use Blocto and I haven't paid any fees yet. Why is that?** -That is because Blocto is acting as the payer for transactions. Self-custody wallets may have the user pay the transaction. Additionally, apps can sponsor the transaction if they choose. +That is because Blocto acts as the payer for transactions. Self-custody wallets may have the user pay the transaction. Additionally, apps can sponsor the transaction if they choose. **Why would the same transaction have different fees when executed for different accounts?** @@ -446,8 +457,28 @@ Execution costs, among other things, include the cost to read data from account Additional Details: -- The most expensive operations in Cadence are reading and writing to storage. This isn't punitive! Every read needs to be sent to all Verification nodes for verification (with Merkel proofs), and every write requires a path of Merkel hashes to be updated. Reading and writing to storage is inherently expensive on any blockchain. +- The most expensive operations in Cadence are reading and writing to storage. This isn't punitive! Every read needs to be sent to all Verification nodes for verification (with Merkel proofs), and every write requires a path of Merkel hashes to be updated. It's inherently expensive to read and write on any blockchain. - The way data is stored in accounts is as a tree (the hint is in the name "atree" :wink:). So, the more elements in the account, the more levels of the tree, and therefore the more nodes of that tree that need to be read and updated. So, looking at the byte size of an account is a decent proxy for figuring out how much it's going to cost. - Because it's a tree, the cost of reads and writes grows with log(n), but does scale. -- atree has an update queued up for [Crescendo](https://flow.com/upgrade/crescendo) that will improve this. The previous version erred on the side of adding new levels to the tree (to keep the code simple), while the new version tries to pack more data at each level. This should result in fewer levels for the same byte size. Additionally, it includes a more compact encoding leading to a reduction in the byte size of most accounts. -- Even with these improvements, this relationship is likely to remain indefinitely. The bigger the account, the more bookkeeping the nodes have to do, which will result in somewhat larger tx fees. +- atree has an update queued up for [Crescendo] that will improve this. The previous version erred on the side of adding new levels to the tree (to keep the code simple), while the new version tries to pack more data at each level. This will result in fewer levels for the same byte size. Additionally, it includes a more compact encoding leading to a reduction in the byte size of most accounts. +- Even with these improvements, this relationship is likely to remain indefinitely. The bigger the account, the more maintenance the nodes have to do, which will result in somewhat larger tx fees. + + + +[here]: ../../../build/evm/fees.md +[FLIP 336]: https://github.com/onflow/flips/blob/main/governance/20250727-dynamic-transaction-fees.md +[`FlowStorageFees`]: ../core-contracts/05-flow-fees.md#flowstoragefees +[emulator with the Flow CLI]: ../../../build/tools/emulator/index.md#running-the-emulator-with-the-flow-cli +[Flowscan]: https://flowscan.io/ +[`FlowFees`]: https://github.com/onflow/flow-core-contracts/blob/master/contracts/FlowFees.cdc: +[the fees for a specific transaction.]: https://github.com/onflow/flow-core-contracts/blob/master/contracts/FlowFees.cdc#L14 +[execution effort limit maximum specified]: #configuring-execution-limits +[borrow references]: https://cadence-lang.org/docs/design-patterns#avoid-excessive-load-and-save-storage-operations-prefer-in-place-mutations +[FLIP-660]: https://github.com/onflow/flow/pull/660 +[FLIP-753]: https://github.com/onflow/flow/pull/753 +[Flow Fees Contract]: https://github.com/onflow/flow-core-contracts/blob/master/contracts/FlowFees.cdc +[leave feedback on this forum post]: https://forum.flow.com/t/variable-transaction-fees-are-coming-to-flow/2941 +[Spork on April 6, 2022]: ../../../protocol/node-ops/node-operation/past-upgrades#mainnet-17 +[June 1st]: https://forum.flow.com/t/permissionless-contract-deployment-progress/2981 +[weekly epoch transition]: https://github.com/onflow/service-account/tree/main/transactions/set-execution-effort-weights/2022/jun-1 +[Crescendo]: https://flow.com/upgrade/crescendo \ No newline at end of file diff --git a/docs/build/cadence/basics/flow-token.md b/docs/build/cadence/basics/flow-token.md index 0c6835f150..e425b73ce8 100644 --- a/docs/build/cadence/basics/flow-token.md +++ b/docs/build/cadence/basics/flow-token.md @@ -20,26 +20,22 @@ keywords: - Flow ecosystem --- -## Introduction +# FLOW Coin This section contains information about the FLOW Coin for individual backers, wallet providers, custodians and node operators. ### FLOW as a Native Coin -FLOW is the default coin for the Flow protocol, meaning it is used for all protocol-level fee payments, -rewards and staking transactions. FLOW implements the standard [Flow Fungible Token interface](https://github.com/onflow/flow-ft), -which all other onchain fungible tokens also conform to. This interface is defined in Cadence, -Flow's native smart-contract programming language, which makes it easy to write applications that -interact with FLOW. +FLOW is the default coin for the Flow protocol, meaning it is used for all protocol-level fee payments, rewards and staking transactions. FLOW implements the standard [Flow Fungible Token interface], which all other onchain fungible tokens also conform to. This interface is defined in Cadence, Flow's native smart-contract programming language, which makes it easy to write applications that interact with FLOW. ## How to Get FLOW There are two ways to acquire FLOW Coins as yield: -1. [Earn FLOW as a Validator or Delegator](../../../protocol/staking/06-technical-overview.md): Receive newly-minted FLOW as a reward for running a node. -1. [Earn FLOW as a Community Contributor](https://github.com/onflow/developer-grants): Flow offers grants for selected proposals as well as RFPs for teams to submit proposals for funded development +1. [Earn FLOW as a Validator or Delegator]: Receive newly-minted FLOW as a reward when you run a node. +1. [Earn FLOW as a Community Contributor]: Flow offers grants for selected proposals as well as RFPs for teams to submit proposals for funded development -## How to Use FLOW +## How to use FLOW With FLOW, you can: @@ -51,77 +47,71 @@ With FLOW, you can: - Send and share - Create, develop, and grow your dapp -### Spending FLOW +### Spend FLOW -All you need to spend FLOW is an account and a tool for signing transactions -(a wallet, custodian, or other signing service). -The FCL (Flow Client Library) makes it super duper easy to go to any dapp, -login with your account, have a great time, -and then sign with the wallet of your choice only once you decide to make a purchase. +All you need to spend FLOW is an account and a tool to sign transactions (a wallet, custodian, or other signing service). The FCL (Flow Client Library) makes it super duper easy to go to any dapp, login with your account, have a great time, and then sign with the wallet of your choice only once you decide to make a purchase. -### Staking FLOW +### Stake FLOW -[You can use FLOW to operate a staked node.](../../../protocol/staking/06-technical-overview.md) Node operators receive newly-minted FLOW -as a reward for helping to secure the network. +[You can use FLOW to operate a staked node.] Node operators receive newly-minted FLOW as a reward for helping to secure the network. -### Delegating FLOW +### Delegate FLOW -[You can use FLOW for stake delegation.](../../../protocol/staking/06-technical-overview.md) Delegators receive newly-minted FLOW -as a reward for helping to secure the network. +[You can use FLOW for stake delegation.] Delegators receive newly-minted FLOW as a reward for helping to secure the network. -### Holding FLOW +### Hold FLOW If you have already purchased FLOW and wish to hold it, you have a couple of options: - For relatively small, short term holdings - most people use a wallet. - Wallets are used to help you sign transactions (verify your actions) when using your FLOW tokens. + Wallets are used to help you sign transactions (verify your actions) when you use your FLOW tokens. - For larger, long term holdings - you may want to use a custody provider to keep your funds safe. -You can find wallets and custodians supporting Flow in the [Flow Port](https://port.flow.com/) +You can find wallets and custodians that support Flow in the [Flow Port] -### Voting with FLOW +### Vote with FLOW -Participating in the Flow community is more than just running a node or building a dapp. -It's also about engaging in discussion, debate, and decision making about the protocol, -the content on it, and the people impacted by it. -You can use your Flow account to submit votes to community polls and other governance related activities. +Participation in the Flow community means more than just run a node or build a dapp. It's also about engaging in discussion, debate, and decision making about the protocol, the content on it, and the people that it impacts. You can use your Flow account to submit votes to community polls and other governance related activities. -### Sending and Sharing FLOW +### Send and share FLOW If you simply want to share the love and bring your friends to Flow, it's easier than an edible arrangement. -It is possible to use the Flow blockchain without holding any FLOW coins yourself. -Free to play games, trials, community polls, -and other community activities can all take place with only an account -(which may be created on a person's behalf) -and a small fixed fee which may be paid by a user agent. +It is possible to use the Flow blockchain and not hold any FLOW coins yourself. Free to play games, trials, community polls, and other community activities can all take place with only an account (which may be created on a person's behalf) and a small fixed fee which may be paid by a user agent. -The protocol requires some FLOW coins to process these transactions, -but (and this is the cool part!) a product can support users who do not themselves hold FLOW -while still providing that user with all the underlying security guarantees the Flow protocol provides. +The protocol requires some FLOW coins to process these transactions, but (and this is the cool part!) a product can support users who do not themselves hold FLOW and still provide that user with all the underlying security guarantees the Flow protocol provides. -Transferring FLOW, creating accounts, and updating keys are all actions made easy on [Flow Port](https://port.flow.com/) +It's easy to transfer FLOW, create accounts, and update keys on [Flow Port] -### Submitting Transactions and Updating Users +### Submit transactions and update users -Transactions are submitted using a Flow SDK via the Access API. +Transactions are submitted with a Flow SDK via the Access API. -On Flow, a transaction is identified by its hash - the hash that exists as soon as that transaction is signed and submitted to an Access or Collection node. -Results of transactions can be queried by transaction hash through the Access API. -A user can check the status of a transaction at any time via the [Flow Block Explorer](https://flowscan.io/). +On Flow, a transaction is identified by its hash - the hash that exists as soon as that transaction is signed and submitted to an Access or Collection node. Results of transactions can be queried by transaction hash through the Access API. A user can check the status of a transaction at any time via the [Flow Block Explorer]. -To expose these results natively in your app, you can use a Flow SDK to fetch transaction results, -[for example using the Flow Go SDK](https://github.com/onflow/flow-go-sdk#querying-transaction-results). +To expose these results natively in your app, you can use a Flow SDK to [fetch transaction results]. -Using a Flow SDK you can also fetch account state by address from a Flow Access API, -[for example using the Flow Go SDK](https://github.com/onflow/flow-go-sdk#querying-accounts). +With a Flow SDK, you can also [fetch account state by address] from a Flow Access API. -Once the transaction is sealed, an event is emitted and you will be able to read transaction events and update the user. +After the transaction is sealed, an event is emitted and you will be able to read transaction events and update the user. -The Flow SDKs also allow polling for events using the Flow Access API, -[for example using the Flow Go SDK](https://github.com/onflow/flow-go-sdk#querying-events). +The Flow SDKs also allow [polling for events] with the Flow Access API. -## How to Build with FLOW +## How to build with FLOW -To get started building on Flow, please see the [Flow App Quickstart](../../../blockchain-development-tutorials/cadence/getting-started/building-a-frontend-app.md) +To get started with Flow, see the [Flow App Quickstart] + + + +[Flow Fungible Token interface]: https://github.com/onflow/flow-ft +[Earn FLOW as a Validator or Delegator]: ../../../protocol/staking/06-technical-overview.md +[Earn FLOW as a Community Contributor]: https://github.com/onflow/developer-grants +[You can use FLOW to operate a staked node.]: ../../../protocol/staking/06-technical-overview.md +[You can use FLOW for stake delegation.]: ../../../protocol/staking/06-technical-overview.md +[Flow Port]: https://port.flow.com/ +[Flow Block Explorer]: https://flowscan.io/ +[fetch transaction results]: https://github.com/onflow/flow-go-sdk#querying-transaction-results +[fetch account state by address]: https://github.com/onflow/flow-go-sdk#querying-accounts +[polling for events]: https://github.com/onflow/flow-go-sdk#querying-events) +[Flow App Quickstart]: ../../../blockchain-development-tutorials/cadence/getting-started/building-a-frontend-app.md \ No newline at end of file diff --git a/docs/build/cadence/basics/mev-resistance.md b/docs/build/cadence/basics/mev-resistance.md index 5003d90a49..970ed64b3a 100644 --- a/docs/build/cadence/basics/mev-resistance.md +++ b/docs/build/cadence/basics/mev-resistance.md @@ -25,69 +25,68 @@ keywords: > -## The Hidden Cost of MEV in Decentralized Systems +## The hidden cost of MEV in decentralized systems One of the most under-discussed benefits of decentralization is **equitable access**. Ideally, the value and quality-of-service you receive from a decentralized platform should not depend on your identity, computing power, or personal connections. However, **Maximal Extractable Value (MEV)** poses a significant threat to this principle. -MEV allows block producers to manipulate transaction ordering for profit—often at the direct expense of users. The ability to front-run, back-run, or sandwich transactions can extract value from ordinary users, reinforcing inequalities rather than eliminating them. In most blockchain networks, MEV is not just an unfortunate side effect; it is structurally embedded in how transactions are processed. +MEV allows block producers to manipulate transaction ordering for profit—often at the direct expense of users. The ability to front-run, back-run, or sandwich transactions can extract value from ordinary users, which reinforces inequalities instead of eliminating them. In most blockchain networks, MEV is not just an unfortunate side effect; it is structurally embedded in how transactions are processed. -## Why MEV Persists on Most Blockchains +## Why MEV persists on most blockchains MEV is difficult to prevent on most blockchains because **each block has a single builder**. This builder must have: -- A full copy of the blockchain state -- The ability to simulate transactions before they are finalized -- Absolute control over transaction selection and ordering +- A full copy of the blockchain state. +- The ability to simulate transactions before they are finalized. +- Absolute control over transaction selection and ordering. -In practice, this means that **the entity responsible for adding your transaction to the blockchain can first simulate it to identify profit opportunities**. They can test hundreds or thousands of ways to rearrange transactions, inserting their own to extract MEV—often at **your** expense. +In practice, this means that **the entity who adds your transaction to the blockchain can first simulate it to identify profit opportunities**. They can test hundreds or thousands of ways to rearrange transactions, and insert their own to extract MEV—often at **your** expense. -For example, if a block builder can earn $10 by sandwiching your transaction, it means **you** likely lose $10 in value. This is functionally theft, and the worst part? If your transaction is airtight and offers no MEV opportunities, the block builder has no obligation to include it at all. Pay the toll, or get locked out. +For example, if a block builder can sandwich your transaction and earn $10, it means **you** likely lose $10 in value. This is functionally theft, and the worst part? If your transaction is airtight and offers no MEV opportunities, the block builder has no obligation to include it at all. Pay the toll, or get locked out. -## How Flow Accomplishes MEV Resilience +## How Flow accomplishes MEV resilience Unlike many blockchains, **Flow was designed from the ground up to minimize MEV** through a unique multi-role architecture. Flow introduces key design choices that break the typical MEV-enabling structure: -### 1. **Separating Transaction Selection from Execution** +### 1. **Separate transaction selection from execution** On Flow, **Collection Nodes** select transactions, but they do not have access to the execution state or computing power to simulate them. Meanwhile, **Execution Nodes** run transactions but cannot choose or reorder them. This separation significantly reduces the ability of block builders to test transactions before execution. Even if an attacker controls both a Collection Node and an Execution Node, they cannot easily extract MEV. -### 2. **Separating Transaction Ordering from Execution** +### 2. **Separate transaction ordering from execution** Flow further decentralizes control by introducing **Consensus Nodes** that determine transaction order. These nodes are separate from both Collection Nodes and Execution Nodes. For an attacker to perform MEV, they would need to: -- Control a **Collection Node** to insert a transaction -- Control a **Consensus Node** to place it in the desired order -- Have execution state access to predict its effects +- Control a **Collection Node** to insert a transaction. +- Control a **Consensus Node** to place it in the desired order. +- Have execution state access to predict its effects. This makes it vastly more difficult to extract MEV compared to traditional blockchains, where a single entity often controls all three functions. -### 3. **Strict Transaction Execution Rules** +### 3. **Strict transaction execution rules** -Execution Nodes on Flow have a **simple, enforceable rule**: -They **must** execute transactions exactly as ordered by Consensus Nodes—or they get slashed. +Execution Nodes on Flow have a **simple, enforceable rule**: They **must** execute transactions exactly as ordered by Consensus Nodes, or they get slashed. Unlike traditional blockchains, where the same party both orders and executes transactions, Flow ensures that Execution Nodes cannot manipulate transaction order for profit. -### 4. **Parallel Processing for Extra MEV Resistance** +### 4. **Parallel processing for extra MEV resistance** Flow’s unique **pipelined execution model** adds another layer of complexity for potential attackers. -While one block is being executed, the next block is undergoing consensus, and a third block is still collecting transactions. This means that **to front-run or sandwich attack on Flow, an attacker must successfully predict the outcome of at least two unexecuted blocks—one of which hasn’t even been built yet**. +While one block is executed, the next block undergoes consensus, and a third block continues to collect transactions. This means that **to front-run or sandwich attack on Flow, an attacker must successfully predict the outcome of at least two unexecuted blocks—one of which hasn’t even been built yet**. Even with significant resources, this makes profitable MEV attacks incredibly difficult. -## The End Result: A Fairer Blockchain +## The end result: a fairer blockchain Flow’s architecture ensures that: -- The nodes selecting transactions **don’t know** their order -- The nodes ordering transactions **don’t know** the blockchain state -- The nodes executing transactions **can’t** modify the order +- The nodes that select transactions **don’t know** their order. +- The nodes that order transactions **don’t know** the blockchain state. +- The nodes that execute transactions **can’t** modify the order. -By **intentionally separating powers**, Flow eliminates MEV at its root rather than merely mitigating its effects. +By **intentionally separating powers**, Flow eliminates MEV at its root rather than merely mitigate its effects. This level of protection against MEV is not an afterthought—it has been a fundamental design goal of Flow since day one. If equitable access matters, **why settle for anything less?** diff --git a/docs/build/cadence/basics/scripts.md b/docs/build/cadence/basics/scripts.md index 10e2989f9b..7954c637fc 100644 --- a/docs/build/cadence/basics/scripts.md +++ b/docs/build/cadence/basics/scripts.md @@ -26,8 +26,7 @@ A script provides a light-weight method to query chain data. It is executable Cadence code that can query for Flow execution state data but cannot modify it in any way. -Unlike a Flow transaction, a script is not signed and requires no transaction fees. Also unlike a transaction, a script can return a value back to the caller. -You can think of executing a script as a read-only operation, very similar to the `eth_call` RPC method on Ethereum. +Unlike a Flow transaction, a script is not signed and requires no transaction fees. Also unlike a transaction, a script can return a value back to the caller. You can think of script execution as a read-only operation, very similar to the `eth_call` RPC method on Ethereum. Scripts are currently executed on either the Access Nodes or the Execution Nodes based on the Access node configuration. @@ -66,63 +65,81 @@ access(all) fun main(): String { } ``` -Scripts can also be run against previous blocks, allowing you to query historic data from the Flow network. This is particularly useful for retrieving historical states of contracts or tracking changes over time. +Scripts can also be run against previous blocks, which allows you to query historic data from the Flow network. This is particularly useful to retrieve historical states of contracts or track changes over time. ## When to use a script? Scripts can be used for the following: -1. Validating a transaction before submitting it e.g. checking if the payer has sufficient balance, the receiver account is setup correctly to receive a token or NFT etc. -2. Collecting chain data over time. -3. Continuously verifying accounts through a background job e.g. a Discord bot that verifies users by their Flow account. -4. Querying core contracts e.g. see [staking scripts and events](../../../protocol/staking/07-staking-scripts-events.md) for querying staking and epoch related information, see the scripts directory under each of the [core contract transactions](https://github.com/onflow/flow-core-contracts/tree/master/transactions) for other core contracts related scripts. +1. Validate a transaction before you submit it (for example, confirm that if the payer has sufficient balance, the receiver account is setup correctly to receive a token or NFT). +2. Collect chain data over time. +3. Continuously verify accounts through a background job, such as a Discord bot that verifies users by their Flow account. +4. Query core contracts. For an example, see how to [query staking and epoch related information]. Also, see the scripts directory under each of the [core contract transactions] for other core contracts related scripts. -## Executing Scripts +## Execute Scripts ### Access API -A script can be executed by submitting it to the Access API provided by access nodes. Currently, there are three API endpoints that allow a user to execute scripts at the latest sealed block, a previous block height, or a previous block ID. +To execute a script, submit it to the Access API provided by access nodes. Currently, there are three API endpoints that allow a user to execute scripts at the latest sealed block, a previous block height, or a previous block ID. -[**gRPC Script API**](../../../protocol/access-onchain-data/index.md#scripts) +[**gRPC Script API**] -[**REST Script API**](/http-api#tag/Scripts) +[**REST Script API**] There are multiple SDKs implementing the above APIs for different languages: -[**Javascript SDK**](../../../build/tools/clients/fcl-js/index.md) +[**Javascript SDK**] -[**Go SDK**](../../../build/tools/clients/flow-go-sdk/index.md) +[**Go SDK**] -Find a list of all SDKs [here](../../../build/tools/clients/index.md) +Find a list of all SDKs [here] ### Flow CLI -You can also execute a script by using the [Flow CLI](../../../build/tools/flow-cli/scripts/execute-scripts): +You can also execute a script with the [Flow CLI]: ```sh flow scripts execute ./helloWorld.cdc ``` -A user can define their own scripts or can use already defined scripts by the contract authors that can be found by using the [FLIX](../../../build/tools/flow-cli/flix) service. +A user can define their own scripts or can use already defined scripts by the contract authors that can be found with the [FLIX] service. ## Best Practices -Following are some recommendations on how to write efficient scripts: +The following are some recommendations for how to write efficient scripts: -1. **Simpler and shorter scripts**: Scripts, like transactions, are subject to computation limits (see [limitations](#limitations)). It is recommended to run shorter and simpler scripts which have low time complexity for a faster response. If you have a script with several nested loops, long iteration, or that queries many onchain fields, consider simplifying the script logic. +1. **Simpler and shorter scripts**: Scripts, like transactions, are subject to computation limits (see [limitations]).We recommend that you run shorter and simpler scripts which have low time complexity for a faster response. If you have a script with several nested loops, long iteration, or that queries many onchain fields, we recommend that you simplify the script logic. 2. **Fewer state reads**: A script reads execution state and to get a faster response, it is best to limit the amount of state that is read by the script. -3. **Smaller length of array or dictionary type arguments**: If your script requires an array or a dictionary as an argument where each element causes a state lookup, instead of making a single script call passing in a long list, make multiple calls with a smaller subset of the array or dictionary. +3. **Smaller length of array or dictionary type arguments**: If your script requires an array or a dictionary as an argument where each element causes a state lookup, instead of a single script call that passes in a long list, make multiple calls with a smaller subset of the array or dictionary. -4. **NFTCatalog**: If your script uses the [NFTCatalog](https://github.com/onflow/nft-catalog) functions, ensure that you use the [latest functions](https://github.com/onflow/nft-catalog?tab=readme-ov-file#using-the-catalog-for-marketplaces-and-other-nft-applications) and do not use any of the deprecated functions such as `getCatalog()`. +4. **NFTCatalog**: If your script uses the [NFTCatalog] functions, ensure that you use the [latest functions] and do not use any of the deprecated functions such as `getCatalog()`. ## Limitations -1. **Rate limit** - Script execution is subjected to API rate-limits imposed by the Access nodes and the Execution nodes. The rate limits for the Public Access nodes hosted by QuickNode are outlined [here](https://www.quicknode.com/docs/flow#endpoint-rate-limits). +1. **Rate limit** - Script execution is subjected to API rate-limits imposed by the Access nodes and the Execution nodes. The rate limits for the Public Access nodes hosted by QuickNode are outlined [outlined here]. 2. **Computation limit** - Similar to a transaction, each script is also subjected to a computation limit. The specific value can be configured by individual Access and Execution node operators. Currently, the default compute unit (gas) limit for a script is 100,000. 3. **Historic block data limit** 1. Script execution on execution nodes is restricted to approximately the last 100 blocks. Any request for script execution on an execution node on a past block (specified by block ID or block height) will fail if that block is more than 100 blocks in the past. - 2. Script execution on an access node can go much beyond the last 100 blocks but is restricted to the height when the [last](https://developers.flow.com/protocol/node-ops/node-operation/past-upgrades) network upgrade ([HCU](https://developers.flow.com/protocol/node-ops/node-operation/hcu) or spork) occurred. + 2. Script execution on an access node can go much beyond the last 100 blocks but is restricted to the height when the [last] network upgrade ([HCU] or spork) occurred. + + + +[query staking and epoch related information]: ../../../protocol/staking/07-staking-scripts-events.md +[core contract transactions]: https://github.com/onflow/flow-core-contracts/tree/master/transactions +[**gRPC Script API**]: ../../../protocol/access-onchain-data/index.md#scripts +[**REST Script API**]: /http-api#tag/Scripts +[**Javascript SDK**]: ../../../build/tools/clients/fcl-js/index.md +[**Go SDK**]: ../../../build/tools/clients/flow-go-sdk/index.md +[here]: ../../../build/tools/clients/index.md +[Flow CLI]: ../../../build/tools/flow-cli/scripts/execute-scripts +[FLIX]: ../../../build/tools/flow-cli/flix +[limitations]: #limitations +[NFTCatalog]: https://github.com/onflow/nft-catalog +[latest functions]: https://github.com/onflow/nft-catalog?tab=readme-ov-file#using-the-catalog-for-marketplaces-and-other-nft-applications +[outlined here]: https://www.quicknode.com/docs/flow#endpoint-rate-limits +[last]: https://developers.flow.com/protocol/node-ops/node-operation/past-upgrades +[HCU]: https://developers.flow.com/protocol/node-ops/node-operation/hcu \ No newline at end of file diff --git a/docs/build/cadence/basics/transactions.md b/docs/build/cadence/basics/transactions.md index b4202a3687..09495a3473 100644 --- a/docs/build/cadence/basics/transactions.md +++ b/docs/build/cadence/basics/transactions.md @@ -29,11 +29,13 @@ Transactions are cryptographically signed data messages that contain a set of in :::tip -Transactions on Flow are fundamentally different from those on Ethereum. The main purpose of a transaction is not to send funds but to contain code that gets executed. This makes transactions very flexible and powerful. In addition to being able to access the authorizing accounts private assets, transactions can also read and call functions in public contracts, and access public domains in other users' accounts Transactions on Flow also feature different roles, such as defining third-party payer accounts, proposer accounts, and authorizers, which we will talk about in detail soon. +Transactions on Flow are fundamentally different from those on Ethereum. The main purpose of a transaction is not to send funds, but to contain code that gets executed. This makes transactions very flexible and powerful. In addition to being able to access the authorizing accounts private assets, transactions can also read and call functions in public contracts, and access public domains in other users' accounts. + + Transactions on Flow also feature different roles, such as define third-party payer accounts, proposer accounts, and authorizers, which we will talk about in detail soon. ::: -In order for a transaction to be valid and executed it must contain signatures from accounts involved as well as some other information, let's take a look at all the required fields. +In order for a transaction to be valid and executed, it must contain signatures from accounts involved as well as some other information, let's take a look at all the required fields. ![Screenshot 2023-08-17 at 14.52.56.png](_transactions_images/Screenshot_2023-08-17_at_14.52.56.png) @@ -41,12 +43,12 @@ In order for a transaction to be valid and executed it must contain signatures f The script section contains instructions for transaction execution. This is a Cadence program in source code form (human-readable), and encoded as UTF-8. The transaction program must contain a `transaction` declaration. -A transaction includes multiple optional phases `prepare`, `pre`, `execute`, and `post` phase. You can read more about it in the [Cadence reference document on transactions](https://cadence-lang.org/docs/language/transactions). Each phase has a purpose, the two most important phases are `prepare` and `execute`. +A transaction includes multiple optional phases `prepare`, `pre`, `execute`, and `post` phase. You can read more about it in the Cadence [documentation on transactions]. Each phase has a purpose, the two most important phases are `prepare` and `execute`. In the `prepare` phase, we have access to `&Account` objects, which gives us the power to interact with those accounts. The accounts are called authorizers of transactions, so each account we want to interact with in the `prepare` phase must sign the transaction as an authorizer. The `execute` phase does exactly what it says, it executes the main logic of the transaction. This phase is optional, but it is a best practice to add your main transaction logic in the section, so it is explicit. -Again make sure to read Cadence [documentation on transactions](https://cadence-lang.org/docs/language/transactions) +Again, make sure to read Cadence [documentation on transactions] This is an example of a transaction script: @@ -60,25 +62,27 @@ transaction(greeting: String) { ### Arguments -Transactions may declare parameters it needs during execution, these must be provided as input arguments when sending a transaction. You can think of them as function arguments. Currently, we provide [arguments in the JSON-Cadence Data Interchange Format](https://cadencelang.dev/docs/1.0/json-cadence-spec). Which is a human-readable JSON format. The sample script from above accepts a single `String` argument. +Transactions may declare parameters it needs during execution, these must be provided as input arguments when you send a transaction. You can think of them as function arguments. Currently, we provide [arguments in the JSON-Cadence Data Interchange Format]. Which is a human-readable JSON format. The sample script from above accepts a single `String` argument. -### Reference Block +### Reference block -A reference to a recent block used for expiry. A transaction is considered expired if it is submitted to Flow after reference block height + N, where N is a constant defined by the network. On mainnet current setting for N is 600 which amounts to approximately 10 minutes for expiry (please note this is subject to change). +A reference to a recent block used for expiry. A transaction is considered expired if it is submitted to Flow after reference block height + N, where N is a constant defined by the network. On mainnet current setting for N is 600 which amounts to approximately 10 minutes for expiry (this is subject to change). :::caution -It is recommended to use the latest finalized block as the reference block, as it is the most recent block guaranteed to be included by the network. Using the latest sealed block is not recommended, as sealing occurs after finalization and could cause the transaction to fall outside of the expiration window. + +We recommend that you use the latest finalized block as the reference block, as it is the most recent block guaranteed to be included by the network. We don't recommend that you use the latest sealed block, as sealing occurs after finalization and could cause the transaction to fall outside of the expiration window. + ::: -### Gas Limit +### Gas limit -When a transaction is executed each operation consumes a predefined amount of computational units (we define more about that in the Fees documentation). This defines the maximum amount of computation that is allowed to be done during this transaction. If a transaction completes execution using fewer computational units than the limit, it remains unaffected. However, if it hits this limit during execution, the transaction will fail, its changes will be reverted, but fees will still be applied. The maximum computational limit for Flow mainnet is currently at 9999, but this might change. The maximum network limit is defined to protect the network from transactions that would run forever. +When a transaction is executed each operation consumes a predefined amount of computational units (we define more about that in the Fees documentation). This defines the maximum amount of computation that is allowed to be done during this transaction. If a transaction completes execution with fewer computational units than the limit, it remains unaffected. However, if it hits this limit during execution, the transaction will fail, its changes will be reverted, but fees will still be applied. The maximum computational limit for Flow mainnet is currently at 9999, but this might change. The maximum network limit is defined to protect the network from transactions that would run forever. -### Proposal Key +### Proposal key Each transaction must declare a proposal key, which can be an account key from any Flow account (App, User or Wallet). The account that owns the proposal key is referred to as the _proposer_. -Proposer is a role in a transaction that defines who is proposing the transaction, the effect of the transaction being submitted on the proposer is that it will increment the sequence number for the provided proposer key. This is done to ensure transactions are not resubmitted (replay attack) and thus sequencing actions. +Proposer is a role in a transaction that defines who proposes the transaction, the effect of the transaction being submitted on the proposer is that it will increment the sequence number for the provided proposer key. This is done to ensure transactions are not resubmitted (replay attack) and thus sequence actions. A proposal key definition declares the address, key ID, and up-to-date sequence number for the account key. A single proposer can have many transactions executed in parallel only limited by the key they use to propose the transaction. @@ -86,11 +90,11 @@ A proposal key definition declares the address, key ID, and up-to-date sequence - Address identifies the account that will act as a proposer of this transaction. - Key ID is an index number (starting at 0) that identifies the key on the account provided in the address. -- Sequence Number is a number on each key that increments by 1 with each transaction. This ensures that each transaction executes at most once and prevents many unwanted situations, such as [transaction replay attacks](https://en.wikipedia.org/wiki/Replay_attack). Each key in an account has a dedicated sequence number associated with it. Unlike Ethereum, there is no sequence number for the entire account. +- Sequence Number is a number on each key that increments by one with each transaction. This ensures that each transaction executes at most once and prevents many unwanted situations, such as [transaction replay attacks]. Each key in an account has a dedicated sequence number associated with it. Unlike Ethereum, there is no sequence number for the entire account. ### Authorizers -Authorizers are accounts that authorize a transaction to read and mutate their state. A transaction can specify zero or more authorizers, depending on how many accounts the transaction needs to access. +Authorizers are accounts that authorize a transaction to read and mutate their state. A transaction can specify zero or more authorizers, and this depends on how many accounts the transaction needs to access. The number of authorizers on the transaction must match the number of &Account parameters declared in the prepare statement of the Cadence script. @@ -102,31 +106,23 @@ transaction { } ``` -Each account defined as an authorizer must sign the transaction with its own key, -and by doing so it acknowledges the transaction it signed -will have access to that account and may modify it. -How it will modify it is understood from the list of account entitlements -that are granted in the `prepare` argument list and by reading the transaction script. -In an transaction, developers should only give the minimum set of account entitlements -that are required for the transaction to execute properly. -This ensures that users who are signing transactions can understand -what parts of their account a transaction can access. +Each account defined as an authorizer must sign the transaction with its own key, and when it does so, it acknowledges the transaction it signed will have access to that account and may modify it. How it will modify it is understood from the list of account entitlements that are granted in the `prepare` argument list and when it reads the transaction script. In an transaction, developers should only give the minimum set of account entitlements that are required for the transaction to execute properly. This ensures that users who sign transactions can understand what parts of their account a transaction can access. ### Payer -A payer is the account that pays the fees for the transaction. A transaction must specify exactly one payer. The payer is only responsible for paying the network and compute unit fees; the transaction is not authorized to access resources or code stored in the payer account. +A payer is the account that pays the fees for the transaction. A transaction must specify exactly one payer. The payer only has to pay the network and compute unit fees; the transaction is not authorized to access resources or code stored in the payer account. -By explicitly specifying a payer a transaction can be paid by third-party services such as wallet providers. +When you explicitly specify a payer, third-party services such as wallet providers can pay a transaction. -## Transaction Lifecycle +## Transaction lifecycle -Once a transaction has been submitted to the Flow network using the Access node APIs, it will begin its lifecycle and eventually reach a finality. Each submitted transaction can be identified with an ID. +After a transaction has been submitted to the Flow network with the Access node APIs, it will begin its lifecycle and eventually reach a finality. Each submitted transaction can be identified with an ID. **Transaction ID** A transaction ID is a hash of the encoded transaction payload and can be calculated at any time. We don't submit transaction ID as part of the transaction payload as it can be derived from the data and thus would mean duplication of data. -### Transaction Status +### Transaction status The transaction status represents the state of a transaction on the Flow blockchain. Some statuses are mutable and some are immutable, they usually follow a timeline like so: @@ -145,9 +141,9 @@ It is **important to differentiate the transaction status and transaction result ::: -### Transaction Result +### Transaction result -Once a transaction is executed, its result will be available, providing details on its success or any errors encountered during execution. It also includes events the transaction may have emitted. +After a transaction is executed, its result will be available, which provides details on its success or any errors encountered during execution. It also includes events the transaction may have emitted. ![Screenshot 2023-08-17 at 16.29.30.png](_transactions_images/Screenshot_2023-08-17_at_16.29.30.png) @@ -160,20 +156,20 @@ From a developer perspective, a transaction is only successful if: ::: -## Transaction Time +## Transaction time -Understanding how transaction times work across different blockchains is crucial for developers and users to optimize their operations and expectations. Flow's multi-node architecture allows for some of the fastest transaction times and finality times across chains. Read on for more detail on how it works and what it means for developers and users. +It's crucial that developers and users understand how transaction times work across different blockchains to optimize their operations and expectations. Flow's multi-node architecture allows for some of the fastest transaction times and finality times across chains. Read on for more detail on how it works and what it means for developers and users. -### Two Key Transaction Questions +### Two key transaction questions Whenever a transaction is processed, two primary questions come to mind: 1. **Inclusion**: Will this transaction be included in the final chain? 2. **Result**: What is the outcome of the transaction? -Different blockchains tackle these questions in varied sequences. For instance, Bitcoin and Ethereum provide answers simultaneously. Layer 2 solutions (L2s) can sometimes address the outcome before confirming inclusion. But there's a catch: you can have an answer to those questions that might be wrong. Flow, on the other hand, prioritizes the inclusion question. +Different blockchains tackle these questions in varied sequences. For instance, Bitcoin and Ethereum provide answers simultaneously. Layer 2 solutions (L2s) can sometimes address the outcome before it confirms inclusion. But, there's a catch: you can have an answer to those questions that might be wrong. Flow, on the other hand, prioritizes the inclusion question. -### Transaction Finality +### Transaction finality Drawing a parallel to traditional finance, a vendor might instantly know if Visa approves a transaction, but the possibility of chargebacks lingers for weeks. This uncertainty introduces the concept of "finality" in blockchain transactions. @@ -181,11 +177,11 @@ In the dominant Proof-of-Stake (PoS) environment, which includes most chains exc - **Preliminary result**: It's an initial answer to the aforementioned questions. The preliminary result doesn't ensure correctness, and there are no economic penalties (like "slashing") if the informant provides false information. - **Soft economic finality**: This stage provides an answer backed by cryptographic proof. If the informant is deceptive, they face economic repercussions or "slashing." -- **Hard economic finality**: The provided answer either holds true, or the entire blockchain requires a restart. The latter case sees at least one-third of the nodes facing economic penalties. +- **Hard economic finality**: The provided answer either holds true, or the entire blockchain requires a restart. The latter case sees at least one-third of the nodes face economic penalties. ![finality.png](./_transactions_images/finality.png) -### Chain Comparisons +### Chain comparisons | Chain | Preliminary | Soft finality | Hard finality | | -------- | ----------- | ------------- | ------------- | @@ -195,11 +191,11 @@ In the dominant Proof-of-Stake (PoS) environment, which includes most chains exc #### Flow -Flow bypasses preliminary results entirely. It reaches soft finality ("Executed") in about 4 seconds and hard finality ("Sealed") in around 10 seconds. If an Access Node on Flow states a transaction has occurred, it's either correct or cryptographic proof exists that can lead to the node's slashing. +Flow bypasses preliminary results entirely. It reaches soft finality ("Executed") in about four seconds and hard finality ("Sealed") in around 10 seconds. If an Access Node on Flow states a transaction has occurred, it's either correct or cryptographic proof exists that can lead to the node's slashing. ![transaction-time.png](_transactions_images/chain-comparison.png) -## Signing a Transaction +## Sign a transaction Due to the existence of **weighted keys** and **split signing roles**, Flow transactions sometimes need to be signed multiple times by one or more parties. That is, multiple unique signatures may be needed to authorize a single transaction. @@ -210,8 +206,8 @@ A transaction can contain two types of signatures: **payload signatures** and ** ### Signer Roles - **Proposer**: the account that specifies a proposal key. -- **Payer**: the account paying for the transaction fees. -- **Authorizers**: zero or more accounts authorizing the transaction to mutate their state. +- **Payer**: the account that pays for the transaction fees. +- **Authorizers**: zero or more accounts that authorize the transaction to mutate their state. ### Payload @@ -223,7 +219,7 @@ The transaction payload is the innermost portion of a transaction and contains t ::: -### Authorization Envelope +### Authorization envelope The transaction authorization envelope contains both the transaction payload and the payload signatures. @@ -235,7 +231,7 @@ Special case: if an account is both the payer and either a proposer or authorize ::: -### Payment Envelope +### Payment envelope The outermost portion of the transaction, which contains the payload and envelope signatures, is referred to as the payment envelope. @@ -245,7 +241,7 @@ Special case: if an account is both the payer and either a proposer or authorize ::: -### Payer Signs Last +### Payer signs last The payer must sign the portion of the transaction that contains the payload signatures, which means that the payer must always sign last. This ensures the payer that they are signing a valid transaction with all of the required payload signatures. @@ -255,9 +251,9 @@ Special case: if an account is both the payer and either a proposer or authorize ::: -### Signature Structure +### Signature structure -A transaction signature is a composite structure containing three fields: +A transaction signature is a composite structure that contains three fields: - Address - Key ID @@ -265,9 +261,9 @@ A transaction signature is a composite structure containing three fields: The _address_ and _key ID_ fields declare the account key that generated the signature, which is required in order to verify the signature against the correct public key. -### Sequence Numbers +### Sequence numbers -Flow uses sequence numbers to ensure that each transaction executes at most once. This prevents many unwanted situations such as [transaction replay attacks](https://en.wikipedia.org/wiki/Replay_attack). +Flow uses sequence numbers to ensure that each transaction executes at most once. This prevents many unwanted situations such as [transaction replay attacks]. Sequence numbers work similarly to transaction nonces in Ethereum, but with several key differences: @@ -280,11 +276,11 @@ The transaction proposer is only required to specify a sequence number for a sin ::: -Each time an account key is used as a proposal key, its sequence number is incremented by 1. The sequence number is updated after execution, even if the transaction fails (reverts) during execution. +Each time an account key is used as a proposal key, its sequence number is incremented by one. The sequence number is updated after execution, even if the transaction fails (reverts) during execution. A transaction is failed if its proposal key does not specify a sequence number equal to the sequence number stored on the account _at execution time._ -## Common Signing Scenarios +## Common signing scenarios Below are several scenarios in which different signature combinations are required to authorize a transaction. @@ -442,28 +438,40 @@ A transaction that declares different accounts for each signing role may require } ``` -## Transaction Submission and Retrieval +## Transaction submission and retrieval -You can use the Flow CLI to get an existing transaction by ID: +You can use the Flow CLI to get a current transaction by ID: ```sh flow transactions get 1ec90051e3bc74fc36cbd16fc83df08e463dda8f92e8e2193e061f9d41b2ad92 -n mainnet ``` -Find [more about the command in the CLI docs](../../../build/tools/flow-cli/get-flow-data/get-blocks.md). +Find [more about the command in the CLI docs]. -A user can define their own transactions or it can use already defined transactions by the contract authors that can be found by using the FLIX service. +A user can define their own transactions or it can use already defined transactions by the contract authors that can be found by with the FLIX service. Transactions can be submitted and obtained from the access node APIs, currently, there are two gRPC and REST APIs. You can find more information about them here: -[**gRPC Transaction API**](../../../protocol/access-onchain-data/index.md#transactions) +[**gRPC Transaction API**] + +[**REST Transaction API**] + +There are multiple SDKs that the above APIs for different languages: -[**REST Transaction API**](/http-api#tag/Transactions) +[**Javascript SDK**] -There are multiple SDKs implementing the above APIs for different languages: +[**Go SDK**] -[**Javascript SDK**](../../../build/tools/clients/fcl-js/index.md) +Find a list of all SDKs [here] -[**Go SDK**](../../../build/tools/clients/flow-go-sdk/index.md) + -Find a list of all SDKs [here](../../../build/tools/clients/index.md) +[documentation on transactions]: https://cadence-lang.org/docs/language/transactions +[arguments in the JSON-Cadence Data Interchange Format]: https://cadencelang.dev/docs/1.0/json-cadence-spec +[transaction replay attacks]: https://en.wikipedia.org/wiki/Replay_attack +[more about the command in the CLI docs]: ../../../build/tools/flow-cli/get-flow-data/get-blocks.md +[**gRPC Transaction API**]: ../../../protocol/access-onchain-data/index.md#transactions +[**REST Transaction API**]: /http-api#tag/Transactions +[**Javascript SDK**]: ../../../build/tools/clients/fcl-js/index.md +[**Go SDK**]: ../../../build/tools/clients/flow-go-sdk/index.md +[here]: ../../../build/tools/clients/index.md \ No newline at end of file