### Install All Development Tools Source: https://github.com/onflow/flow-go/blob/master/AGENTS.md Install all the necessary development tools required for working with the Flow-Go project. ```bash make install-tools ``` -------------------------------- ### Go Method Description Example Source: https://github.com/onflow/flow-go/blob/master/docs/agents/GoDocs.md Illustrates the required format for the first line of a Go method's godoc comment, which must be a complete sentence starting with the method name. ```go // ByBlockID returns the header with the given ID. It is available for finalized and ambiguous blocks. // // Expected error returns during normal operation: // - [ErrNotFound] if no block header with the given ID exists ByBlockID(blockID flow.Identifier) (*flow.Header, error) ``` -------------------------------- ### Example of Detailed Method Documentation in Go Source: https://github.com/onflow/flow-go/blob/master/docs/agents/GoDocs.md An example demonstrating the required structure for Go method documentation, including descriptions, context, concurrency notes, and expected errors. ```go // MethodName performs a specific action or returns specific information. // // Additional important details about the method. // // NOT CONCURRENCY SAFE! // // Expected error returns during normal operation: // - [ErrType1]: when and why this error occurs // - [ErrType2]: when and why this error occurs ``` -------------------------------- ### Install Prometheus using Homebrew Source: https://github.com/onflow/flow-go/blob/master/module/metrics/example/README.md Installs the Prometheus monitoring system using the Homebrew package manager. ```bash brew install prometheus ``` -------------------------------- ### Install Mock Generation Tools Source: https://github.com/onflow/flow-go/blob/master/AGENTS.md Install the specific tools required for generating mock objects used in testing. ```bash make install-mock-generators ``` -------------------------------- ### Start Flow Emulator with Persistence Source: https://github.com/onflow/flow-go/blob/master/cmd/util/ledger/migrations/test-data/cadence_values_migration/README.md Use the `--persist` flag when starting the emulator to enable snapshotting capabilities. This is a prerequisite for creating snapshots. ```shell flow emulator --persist ``` -------------------------------- ### Configuration Key Prefixing Example Source: https://github.com/onflow/flow-go/blob/master/config/README.md Configuration values are stored with keys prefixed by their parent properties. This example shows how a nested property like `networking-connection-pruning` within `network-config` gets a prefixed key. ```text network-config.networking-connection-pruning ``` -------------------------------- ### Return Value Documentation Examples in Go Source: https://github.com/onflow/flow-go/blob/master/docs/agents/GoDocs.md Provides examples for documenting Go return values, focusing on cases where additional context beyond the method signature is necessary. ```go // GetBlockStatus returns the block's current status. // Returns `PENDING` if still processing, `FINALIZED` if complete, or `INVALID` if failed validation. ``` -------------------------------- ### Finalize Network Setup Source: https://github.com/onflow/flow-go/blob/master/cmd/bootstrap/README.md Finalizes the network setup by generating necessary files for node startup. This includes private keys, public information, and genesis data. ```bash go run . finalize \ --config ./bootstrap-example/node-config.json \ --partner-dir ./example_files/partner-node-infos \ --partner-weights ./example_files/partner-weights.json \ --internal-priv-dir ./bootstrap-example/keys/private-root-information \ --dkg-data ./bootstrap-example/private-root-information/root-dkg-data.priv.json \ --root-block ./bootstrap-example/public-root-information/root-block.json \ --intermediary-bootstrapping-data ./bootstrap-example/public-root-information/intermediary-bootstrapping-data.json \ --root-block-votes-dir ./bootstrap-example/public-root-information/root-block-votes/ \ --root-commit 0000000000000000000000000000000000000000000000000000000000000000 \ --genesis-token-supply="1000000000.0" \ --service-account-public-key-json "{\"PublicKey\":\"R7MTEDdLclRLrj2MI1hcp4ucgRTpR15PCHAWLM5nks6Y3H7+PGkfZTP2di2jbITooWO4DD1yqaBSAVK8iQ6i0A==\",\"SignAlgo\":2,\"HashAlgo\":1,\"SeqNumber\":0,\"Weight\":1000}" \ -o ./bootstrap-example ``` -------------------------------- ### Parameter Documentation Example in Go Source: https://github.com/onflow/flow-go/blob/master/docs/agents/GoDocs.md Shows how to document parameters in Go when they have non-obvious aspects like complex constraints or validation rules. ```go // ValidateTransaction validates the transaction against the current state. // `script` must be valid BPL-encoded script with max size of 64KB // `accounts` must contain at least one account with signing capability ``` -------------------------------- ### Start and Stop Local Network Source: https://github.com/onflow/flow-go/blob/master/integration/localnet/AGENTS.md Commands to manage the local Flow network services. 'make start' builds images and starts all nodes, while 'make start-cached' starts without rebuilding for faster iteration. 'make stop' halts all services. ```bash make start ``` ```bash make start-cached ``` ```bash make stop ``` -------------------------------- ### Access Localnet gRPC API Source: https://github.com/onflow/flow-go/blob/master/integration/localnet/AGENTS.md Example using grpcurl to list services available on the localnet gRPC access node. This requires grpcurl to be installed and the gRPC service to be running on localhost:4001. ```bash grpcurl -plaintext localhost:4001 list ``` -------------------------------- ### Start the Flow Local Network Source: https://github.com/onflow/flow-go/blob/master/integration/localnet/README.md Build new Docker images from the latest code changes and start the local Flow test network. Use 'start-cached' to start using the most recently built image without rebuilding. ```sh make start ``` ```sh make start-cached ``` -------------------------------- ### Start Local Metrics Server for Loki Source: https://github.com/onflow/flow-go/blob/master/integration/README.md Starts the local observability stack, including Loki, Grafana, and Prometheus, by running a make command in the integration/localnet directory. Access Grafana at http://localhost:3000. ```bash cd integration/localnet make start-metrics ``` -------------------------------- ### Log Test Start and End in Go Test Suite Source: https://github.com/onflow/flow-go/blob/master/integration/tests/README.md For tests within a suite, implement start and end logging in SetupTest and TearDownTest methods respectively. This ensures that logs are captured even for tests defined within a suite structure. ```go func (s *Suite) TestYYY() { ... } func (s *Suite) SetupTest() { t := s.T() t.Logf("%v ================> START TESTING %v", time.Now().UTC(), t.Name()) ... } func (s *Suite) TearDownTest() { ... t := s.T() t.Logf("%v ================> FINISH TESTING %v", time.Now().UTC(), t.Name()) } ``` -------------------------------- ### Mocking Interface Example Source: https://github.com/onflow/flow-go/blob/master/README.md Example of how to create a mock for an interface, specifically demonstrating the `StateMachineEventsTelemetryFactory`. This pattern is used when mockery drops support for direct function mocks. ```go package mockinterfaces import "github.com/onflow/flow-go/state/protocol/protocol_state" // ExecForkActor allows to create a mock for the ExecForkActor callback type StateMachineEventsTelemetryFactory interface { Execute(candidateView uint64) protocol_state.StateMachineTelemetryConsumer } ``` -------------------------------- ### Running the Ledger Service Source: https://github.com/onflow/flow-go/blob/master/cmd/ledger/README.md Instructions and examples for running the flow-go ledger service with different configurations. ```APIDOC ## Running the Ledger Service ### Basic Usage ```bash ./flow-ledger-service \ -triedir /path/to/trie \ -ledger-service-tcp 0.0.0.0:9000 ``` ### Listening on Unix Socket ```bash ./flow-ledger-service \ -triedir /path/to/trie \ -ledger-service-socket /sockets/ledger.sock ``` ### Listening on Both TCP and Unix Socket ```bash ./flow-ledger-service \ -triedir /path/to/trie \ -ledger-service-tcp 0.0.0.0:9000 \ -ledger-service-socket /sockets/ledger.sock \ -mtrie-cache-size 500 \ -checkpoint-distance 100 \ -checkpoints-to-keep 3 ``` ### With Admin Server Enabled ```bash ./flow-ledger-service \ -triedir /path/to/trie \ -ledger-service-tcp 0.0.0.0:9000 \ -admin-addr 0.0.0.0:9003 ``` ### Flags - **`-triedir`** (string) - Directory for trie files (required). - **`-ledger-service-tcp`** (string) - TCP listen address (e.g., 0.0.0.0:9000). If provided, server accepts TCP connections. - **`-ledger-service-socket`** (string) - Unix socket path (e.g., /sockets/ledger.sock). If provided, server accepts Unix socket connections. Can specify multiple sockets separated by comma. - **Note**: At least one of `-ledger-service-tcp` or `-ledger-service-socket` must be provided. - **`-admin-addr`** (string) - Address to bind on for admin HTTP server (e.g., 0.0.0.0:9003). If provided, enables admin commands. Use a different port than the execution node's admin server (default 9002). Optional. - **`-mtrie-cache-size`** (integer) - MTrie cache size - number of tries (default: 500). - **`-checkpoint-distance`** (integer) - Checkpoint distance (default: 100). - **`-checkpoints-to-keep`** (integer) - Number of checkpoints to keep (default: 3). - **`-max-request-size`** (string) - Maximum request message size in bytes (default: 1 GiB). - **`-max-response-size`** (string) - Maximum response message size in bytes (default: 1 GiB). - **`-loglevel`** (string) - Log level (panic, fatal, error, warn, info, debug) (default: info). ``` -------------------------------- ### Launch Prometheus Server Source: https://github.com/onflow/flow-go/blob/master/module/metrics/example/README.md Starts the Prometheus server, configuring it to scrape metrics from a local metrics server using a specified configuration file. ```bash prometheus --config.file=module/metrics/example/prometheus.yml ``` -------------------------------- ### Bootstrap a New Flow Network Source: https://github.com/onflow/flow-go/blob/master/integration/localnet/README.md Run the bootstrapping process to generate keys and a genesis block for a new local Flow network. This is a prerequisite before starting the network. ```sh make bootstrap ``` -------------------------------- ### Access Node REST API Examples Source: https://context7.com/onflow/flow-go/llms.txt Provides examples of using `curl` to interact with the Flow Access Node's REST API. These commands demonstrate how to retrieve block information by height or ID, and query account details such as balance and keys. ```bash # Get block by height curl -X GET "https://rest-mainnet.onflow.org/v1/blocks?height=1000000" \ -H "Accept: application/json" # Get block by ID curl -X GET "https://rest-mainnet.onflow.org/v1/blocks/abc123..." \ -H "Accept: application/json" # Get account information curl -X GET "https://rest-mainnet.onflow.org/v1/accounts/0x1654653399040a61" \ -H "Accept: application/json" # Get account balance curl -X GET "https://rest-mainnet.onflow.org/v1/accounts/0x1654653399040a61/balance" \ -H "Accept: application/json" # Get account keys curl -X GET "https://rest-mainnet.onflow.org/v1/accounts/0x1654653399040a61/keys" \ -H "Accept: application/json" ``` -------------------------------- ### Run Ledger Service with TCP Source: https://github.com/onflow/flow-go/blob/master/cmd/ledger/README.md Starts the ledger service listening on TCP. Requires a trie directory and a TCP listen address. ```bash ./flow-ledger-service \ -triedir /path/to/trie \ -ledger-service-tcp 0.0.0.0:9000 ``` -------------------------------- ### Example Calculation for Limit Override Source: https://github.com/onflow/flow-go/blob/master/config/docs/resourceManager.MD Demonstrates how to calculate the new value for a limit override flag. For example, if the current system streams inbound limit is 10,000, the new value would be 15,000. ```bash --libp2p-resource-manager-limits-override-system-streams-inbound=15000 ``` -------------------------------- ### Example: Method with Only Exceptional Errors Source: https://github.com/onflow/flow-go/blob/master/docs/agents/GoDocs.md Demonstrates documenting a method where no specific benign errors are expected during normal operation. This implies all returned errors are exceptions. ```go // ProcessFinalizedBlock processes a block that is known to be finalized. // // No error returns are expected during normal operation. ``` -------------------------------- ### Generate Basic Transaction Source: https://github.com/onflow/flow-go/blob/master/utils/unittest/fixtures/README.md Use `suite.Transactions().Fixture()` to create a basic transaction body. This is the simplest way to get a transaction for testing. ```go txGen := suite.Transactions() // Basic transaction body tx := txGen.Fixture() ``` -------------------------------- ### Run Ledger Service with Unix Socket Source: https://github.com/onflow/flow-go/blob/master/cmd/ledger/README.md Starts the ledger service listening on a Unix socket. Requires a trie directory and a socket path. ```bash ./flow-ledger-service \ -triedir /path/to/trie \ -ledger-service-socket /sockets/ledger.sock ``` -------------------------------- ### Run Ledger Service with Admin Server Source: https://github.com/onflow/flow-go/blob/master/cmd/ledger/README.md Starts the ledger service with TCP enabled and an admin server on a separate port to avoid conflicts. Requires a trie directory. ```bash ./flow-ledger-service \ -triedir /path/to/trie \ -ledger-service-tcp 0.0.0.0:9000 \ -admin-addr 0.0.0.0:9003 ``` -------------------------------- ### Generate Basic Event Type Source: https://github.com/onflow/flow-go/blob/master/utils/unittest/fixtures/README.md Use `suite.EventTypes().Fixture()` to create a basic event type. This is a starting point for testing event emission and handling. ```go eventTypeGen := suite.EventTypes() // Basic event type eventType := eventTypeGen.Fixture() ``` -------------------------------- ### Create and Use Complete Ledger in Go Source: https://context7.com/onflow/flow-go/llms.txt Demonstrates how to initialize a complete ledger with write-ahead logging and checkpointing, update its state, query values, and generate proofs. Ensure the specified path for the write-ahead log is accessible. ```go import ( "fmt" "github.com/onflow/flow-go/ledger" "github.com/onflow/flow-go/ledger/complete" "github.com/onflow/flow-go/ledger/common/pathfinder" "github.com/onflow/flow-go/metrics" ) // Placeholder for logger and metrics.NoopCollector var logger = &struct{}{} func main() { // Create a complete ledger with WAL and checkpointing led, err := complete.NewLedger( "/tmp/flow-go-ledger", // Write-ahead log directory 100, // Capacity (number of recent states to keep) &metrics.NoopCollector{}, logger, complete.DefaultPathFinderVersion, ) if err != nil { panic(err) } defer led.Done() // Update ledger state (creates new state commitment) keys := []ledger.Key{ ledger.NewKey([]ledger.KeyPart{ ledger.NewKeyPart(0, []byte("owner")), ledger.NewKeyPart(1, []byte("key")), }), } values := []ledger.Value{[]byte("value")} // Get current state commitment currentState := led.InitialState() // Apply update and get new state update := &ledger.Update{ State: currentState, Keys: keys, Values: values, } newState, trieUpdate, err := led.Set(update) if err != nil { panic(err) } fmt.Printf("New state commitment: %x\n", newState) // Query value at specific state query := &ledger.Query{ State: newState, Keys: keys, } retrievedValues, err := led.Get(query) if err != nil { panic(err) } fmt.Printf("Retrieved value: %s\n", retrievedValues[0]) // Generate inclusion proof proof, err := led.Prove(query) if err != nil { panic(err) } // Verify proof (for partial ledger / light clients) valid, err := ledger.VerifyTrieProof(proof, newState) if err != nil { panic(err) } fmt.Printf("Proof valid: %t\n", valid) } ``` -------------------------------- ### Get Events by Type and Height Range via REST Source: https://context7.com/onflow/flow-go/llms.txt Retrieve events filtered by type and a specific block height range using a GET request. Specify the event type, start height, and end height. ```bash curl -X GET "https://rest-mainnet.onflow.org/v1/events?type=A.1654653399040a61.FlowToken.TokensWithdrawn&start_height=1000&end_height=1010" \ -H "Accept: application/json" ``` -------------------------------- ### Initialize and Run a Transaction Procedure Source: https://github.com/onflow/flow-go/blob/master/fvm/README.md Initializes a new virtual machine, creates a transaction, sets up the execution context and ledger, and runs the transaction procedure. Ensure the 'fmt' package is imported for printing logs. ```go import ( "fmt" "github.com/onflow/cadence/runtime" "github.com/onflow/flow-go/fvm" "github.com/onflow/flow-go/fvm/storage/state" "github.com/onflow/flow-go/model/flow" ) vm := fvm.NewVirtualMachine() tx := flow.NewTransactionBody(). SetScript([]byte(`transaction { execute { log("Hello, World!") } }`)) ctx := fvm.NewContext() ledger := state.NewMapLedger() txIndex := uint32(0) txProc := fvm.Transaction(tx, txIndex) executionSnapshot, output, err := vm.Run(ctx, txProc, ledger) if err != nil { panic("fatal error during transaction procedure!") } fmt.Println(txProc.Logs[0]) // prints "Hello, World!" ``` -------------------------------- ### Interact with Localnet using Flow CLI Source: https://github.com/onflow/flow-go/blob/master/integration/localnet/AGENTS.md Connect to the local Flow network using the Flow CLI with the network name 'localnet'. The configuration file is located at 'integration/localnet/client/flow-localnet.json'. This example shows how to get account information. ```bash flow -n localnet accounts get f8d6e0586b0a20c7 ``` -------------------------------- ### Execute Transactions and Scripts with FVM Source: https://context7.com/onflow/flow-go/llms.txt Demonstrates creating a new FVM instance, setting up an execution context, and running transactions or read-only scripts against an in-memory ledger. Includes examples for basic transactions, scripts, and scripts with arguments. ```go import ( "fmt" "github.com/onflow/flow-go/fvm" "github.com/onflow/flow-go/fvm/storage/state" "github.com/onflow/flow-go/model/flow" ) // Create a new FVM instance vm := fvm.NewVirtualMachine() // Create execution context with chain configuration ctx := fvm.NewContext(flow.Mainnet) // Create in-memory ledger for testing ledger := state.NewMapLedger() // Execute a transaction tx := flow.NewTransactionBody(). SetScript([]byte(`transaction { execute { log("Hello, World!") } }`)) txIndex := uint32(0) txProc := fvm.Transaction(tx, txIndex) executionSnapshot, output, err := vm.Run(ctx, txProc, ledger) if err != nil { panic("fatal error during transaction procedure!") } fmt.Println(output.Logs[0]) // prints "Hello, World!" // Execute a read-only script script := fvm.Script([]byte(`access(all) fun main(): Int { return 42 }`)) _, scriptOutput, err := vm.Run(ctx, script, ledger) if err != nil { panic("script execution failed!") } fmt.Printf("Script result: %v\n", scriptOutput.Value) // Script with arguments scriptWithArgs := fvm.Script([]byte(`access(all) fun main(x: Int): Int { return x * 2 }`)). WithArguments([]byte(`{"type":"Int","value":"21"}`)) _, result, _ := vm.Run(ctx, scriptWithArgs, ledger) fmt.Printf("Result: %v\n", result.Value) // 42 ``` -------------------------------- ### Root Sealing Segment Example: Root Block with Seal-less Blocks Source: https://github.com/onflow/flow-go/blob/master/model/flow/sealing_segment.md Illustrates a sealing segment starting with a self-sealing root block followed by any number of seal-less blocks. All non-root segments contain more than one block, ordered by ascending height. ```plaintext ROOT <- A <- B ``` -------------------------------- ### Initialize Pebble Database Source: https://context7.com/onflow/flow-go/llms.txt Demonstrates how to initialize a Pebble database instance for persistent storage. Ensure the provided path is valid for data storage. ```go import ( "github.com/onflow/flow-go/storage" "github.com/onflow/flow-go/storage/operation" "github.com/onflow/flow-go/storage/pebble" "github.com/onflow/flow-go/model/flow" ) // Initialize Pebble database db, err := pebble.OpenDefaultPebbleDB("/path/to/data") if err != nil { panic(err) } defer db.Close() ``` -------------------------------- ### Run Flow Go Verification Node Metrics Example Source: https://github.com/onflow/flow-go/blob/master/module/metrics/example/README.md Launches a local metrics server for a Flow Go Verification Node. Use the -happypath flag to examine metrics collection on a real happy path. ```go go run module/metrics/example/verification/main.go ``` -------------------------------- ### Start Grafana Docker Container Source: https://github.com/onflow/flow-go/blob/master/integration/scripts/README-loki.md Starts the Grafana service using Docker Compose. Ensure you are in the integration/localnet directory. ```bash cd integration/localnet docker-compose -f docker-compose.metrics.yml up -d grafana ``` -------------------------------- ### Start Loki Docker Container Source: https://github.com/onflow/flow-go/blob/master/integration/scripts/README-loki.md Starts the Loki service using Docker Compose. Ensure you are in the integration/localnet directory. ```bash cd integration docker-compose -f docker-compose.metrics.yml up -d loki ``` -------------------------------- ### Run Flow Go Execution Node Metrics Example Source: https://github.com/onflow/flow-go/blob/master/module/metrics/example/README.md Launches a local metrics server for a Flow Go Execution Node. This server exposes metrics data via the /metrics endpoint. ```go go run module/metrics/example/execution/main.go ``` -------------------------------- ### Run Flow Go Collection Node Metrics Example Source: https://github.com/onflow/flow-go/blob/master/module/metrics/example/README.md Launches a local metrics server for a Flow Go Collection Node. This server exposes metrics data via the /metrics endpoint. ```go go run module/metrics/example/collection/main.go ``` -------------------------------- ### Run Flow Go Consensus Node Metrics Example Source: https://github.com/onflow/flow-go/blob/master/module/metrics/example/README.md Launches a local metrics server for a Flow Go Consensus Node. This server exposes metrics data via the /metrics endpoint. ```go go run module/metrics/example/consensus/main.go ``` -------------------------------- ### Get Network Parameters via REST Source: https://context7.com/onflow/flow-go/llms.txt Retrieve the current network parameters of the Flow blockchain using a GET request. ```bash curl -X GET "https://rest-mainnet.onflow.org/v1/network/parameters" \ -H "Accept: application/json" ``` -------------------------------- ### Get Node Version Info via REST Source: https://context7.com/onflow/flow-go/llms.txt Fetch information about the Flow node's version using a GET request. ```bash curl -X GET "https://rest-mainnet.onflow.org/v1/node_version_info" \ -H "Accept: application/json" ``` -------------------------------- ### Generate Basic Proposal Key Source: https://github.com/onflow/flow-go/blob/master/utils/unittest/fixtures/README.md Use `suite.ProposalKeys().Fixture()` to create a basic proposal key. This is used for testing transaction proposals and authorization. ```go pkGen := suite.ProposalKeys() // Basic proposal key pk := pkGen.Fixture() ``` -------------------------------- ### Get Collection by ID via REST Source: https://context7.com/onflow/flow-go/llms.txt Fetch a collection of transactions by its ID using a GET request to the Flow Access API. ```bash curl -X GET "https://rest-mainnet.onflow.org/v1/collections/abc123..." \ -H "Accept: application/json" ``` -------------------------------- ### Get Transaction by ID via REST Source: https://context7.com/onflow/flow-go/llms.txt Retrieve transaction details by its ID using a GET request to the Flow Access API. ```bash curl -X GET "https://rest-mainnet.onflow.org/v1/transactions/abc123..." \ -H "Accept: application/json" ``` -------------------------------- ### Acquire Storage Locks with Context Source: https://github.com/onflow/flow-go/blob/master/storage/README.md Shows how to use `lockctx.Context` to acquire storage locks before performing insert operations. Ensure locks are released using `defer`. ```go func (blocks *Blocks) Insert(block *Block) { lctx := blocks.LockManager.NewContext() defer lctx.Release() lctx.AcquireLock(storage.LockInsertHeader) lctx.AcquireLock(storage.LockInsertPayload) blocks.db.WithReaderBatchWriter(func(batch) { operation.InsertHeader(lctx, block.Header) operation.InsertPayload(lctx, block.Payload) } } ``` -------------------------------- ### Get Transaction Result via REST Source: https://context7.com/onflow/flow-go/llms.txt Fetch the result of a transaction using its ID via a GET request to the Flow Access API. ```bash curl -X GET "https://rest-mainnet.onflow.org/v1/transaction_results/abc123..." \ -H "Accept: application/json" ``` -------------------------------- ### Access API Go Interface Example Source: https://context7.com/onflow/flow-go/llms.txt Demonstrates basic usage of the Flow Access API in Go, including fetching blocks, accounts, executing scripts, sending transactions, and subscribing to block events. Ensure necessary imports are included. ```go import ( "context" "github.com/onflow/flow-go/access" "github.com/onflow/flow-go/model/flow" "github.com/onflow/flow/protobuf/go/flow/entities" ) // Example: Using the Access API interface func useAccessAPI(api access.API) { ctx := context.Background() // Get latest sealed block block, status, err := api.GetLatestBlock(ctx, true) if err != nil { panic(err) } fmt.Printf("Latest sealed block: %d, status: %v\n", block.Header.Height, status) // Get block by height block, status, err = api.GetBlockByHeight(ctx, 1000000) // Get account at latest block account, err := api.GetAccountAtLatestBlock(ctx, flow.HexToAddress("0x1654653399040a61")) fmt.Printf("Account balance: %d\n", account.Balance) // Execute script at latest block script := []byte(`access(all) fun main(): Int { return 42 }`) result, err := api.ExecuteScriptAtLatestBlock(ctx, script, nil) // Send transaction tx := &flow.TransactionBody{ Script: []byte(`transaction { execute { log("Hello") } }`), ReferenceBlockID: block.ID(), Payer: flow.HexToAddress("0x1654653399040a61"), } err = api.SendTransaction(ctx, tx) // Get transaction result txResult, err := api.GetTransactionResult(ctx, tx.ID(), flow.ZeroID, flow.ZeroID, entities.EventEncodingVersion_CCF_V0) fmt.Printf("TX Status: %v, Error: %v\n", txResult.Status, txResult.ErrorMessage) // Subscribe to blocks (streaming) subscription := api.SubscribeBlocksFromLatest(ctx, flow.BlockStatusSealed) for { block, err := subscription.Next() if err != nil { break } fmt.Printf("New sealed block: %d\n", block.(*flow.Block).Header.Height) } // Get events for height range events, err := api.GetEventsForHeightRange(ctx, "A.1654653399040a61.FlowToken.TokensWithdrawn", 1000, 1010, entities.EventEncodingVersion_CCF_V0) } ``` -------------------------------- ### Run Unit Tests Source: https://github.com/onflow/flow-go/blob/master/AGENTS.md Execute the unit test suite using the 'make test' command. ```bash make test ``` -------------------------------- ### Get Execution Result by Block ID via REST Source: https://context7.com/onflow/flow-go/llms.txt Retrieve execution results for a given block ID using a GET request to the Flow Access API. ```bash curl -X GET "https://rest-mainnet.onflow.org/v1/execution_results?block_id=abc123..." \ -H "Accept: application/json" ``` -------------------------------- ### Build Docker Container for Benchmarking Source: https://github.com/onflow/flow-go/blob/master/integration/README.md Builds a Docker container with the benchmarking binary from the root of the repository. ```bash make docker-native-build-loader ``` -------------------------------- ### Block Time Controller TimedBlock Initialization Source: https://github.com/onflow/flow-go/blob/master/consensus/hotstuff/cruisectl/README.md This code initializes a TimedBlock with the current UTC time, serving as the starting point for view timing in the BlockTimeController. This is the reference time for the start of a new view. ```golang TimedBlock{Block: block, TimeObserved: time.Now().UTC()} ``` -------------------------------- ### Build Native Access Node Binary Source: https://github.com/onflow/flow-go/blob/master/AGENTS.md Build the native binary for the access node. ```bash make docker-native-build-access-binary ``` -------------------------------- ### Configure FVM Execution Contexts Source: https://context7.com/onflow/flow-go/llms.txt Shows how to create and configure FVM execution contexts, including setting chain parameters, block headers, computation and memory limits, and enabling/disabling specific features like service accounts. Contexts can be nested to inherit and override settings. ```go import ( "github.com/onflow/flow-go/fvm" "github.com/onflow/flow-go/model/flow" ) // Create base context for the chain globalCtx := fvm.NewContext(flow.Mainnet) // Create block-specific context with custom options block1Ctx := fvm.NewContextFromParent(globalCtx, fvm.WithBlockHeader(block1Header), fvm.WithComputationLimit(1000000), // 1M computation units fvm.WithMemoryLimit(256 * 1024 * 1024), // 256MB memory limit ) // Create another context for a different block block2Ctx := fvm.NewContextFromParent(globalCtx, fvm.WithBlockHeader(block2Header), fvm.WithServiceAccountEnabled(true), ) // Contexts can be safely used in parallel for different blocks go executeBlock(vm, block1Ctx) go executeBlock(vm, block2Ctx) // Disable limits for service account transactions serviceCtx := fvm.NewContextFromParent(block1Ctx, fvm.WithDisableMemoryAndInteractionLimits(true), ) ``` -------------------------------- ### Create and Use Execution Contexts Source: https://github.com/onflow/flow-go/blob/master/fvm/README.md Initializes a new virtual machine and creates execution contexts. Contexts are immutable and can be spawned from a parent context, allowing for hierarchical configuration, such as setting block headers for different blocks. Contexts can be safely used in parallel. ```go vm := fvm.New(runtime.NewRuntime()) globalCtx := fvm.NewContext() // create separate contexts for different blocks block1Ctx := fvm.NewContextFromParent(globalCtx, fvm.WithBlockHeader(block1)) block2Ctx := fvm.NewContextFromParent(globalCtx, fvm.WithBlockHeader(block2)) // contexts can be safely used in parallel go executeBlock(vm, block1Ctx) go executeBlock(vm, block2Ctx) ``` -------------------------------- ### Get Configuration Value Source: https://github.com/onflow/flow-go/blob/master/admin/README.md Retrieves the current value of a specific configuration parameter. ```bash curl localhost:9002/admin/run_command -H 'Content-Type: application/json' -d '{"commandName": "get-config", "data": "consensus-required-approvals-for-sealing"}' ``` -------------------------------- ### Get Identity by Peer ID Source: https://github.com/onflow/flow-go/blob/master/admin/README.md Retrieves identity information for a given peer ID. ```bash curl localhost:9002/admin/run_command -H 'Content-Type: application/json' -d '{"commandName": "get-latest-identity", "data": { "peer_id": "QmNqszdfyEZmMCXcnoUdBDWboFvVLF5reyKPuiqFQT77Vw" }}' ``` -------------------------------- ### Load Localnet for Benchmarking Source: https://github.com/onflow/flow-go/blob/master/integration/localnet/README.md Initiate a load test on the local network using the 'make load' command. The default configuration applies increasing transaction per second (tps) rates over time. ```sh make load ``` -------------------------------- ### Import and Create GeneratorSuite Source: https://github.com/onflow/flow-go/blob/master/utils/unittest/fixtures/README.md Import the fixtures package and create a GeneratorSuite. Use a specific seed for deterministic results. ```go import ( "github.com/onflow/flow-go/utils/unittest/fixtures" ) // Create suite with random seed suite := fixtures.NewGeneratorSuite(t) // Create suite with specific seed for deterministic reproducible results suite := fixtures.NewGeneratorSuite(fixtures.WithSeed(12345)) ``` -------------------------------- ### List All Admin Commands Source: https://github.com/onflow/flow-go/blob/master/admin/README.md Use this command to get a list of all available commands for the admin tool. ```bash curl localhost:9002/admin/run_command -H 'Content-Type: application/json' -d '{"commandName": "list-commands"}' ``` -------------------------------- ### Upsert Collection (No Lock) Source: https://github.com/onflow/flow-go/blob/master/storage/README.md Example of an operation that does not require a lock. It directly performs the storage operation. ```go func UpsertCollection(w storage.Writer, col *flow.LightCollection) error { return UpsertByKey(w, MakePrefix(codeCollection, col.ID()), col) } ``` -------------------------------- ### Run Integration Tests Source: https://github.com/onflow/flow-go/blob/master/AGENTS.md Execute the integration test suite. This command requires Docker to be installed and running. ```bash make integration-test ```