Flow CLI

repository·master·Indexed 42 days ago

https://github.com/onflow/flow-cli

The official command-line interface for the Flow blockchain. It provides developers with tools for project scaffolding via `flow init`, running a local emulator, deploying smart contracts, executing Cadence scripts, and managing accounts, keys, and network interactions.

Tokens
13K
Snippets
41
Records
57
Agent score
51%

What's inside Flow CLI

  1. Overview of Flow CLI

    master

    The Flow CLI is the official command-line interface for the Flow network. It is designed for developers building dapps, smart contracts, or tooling on Flow.

    Key capabilities include:

    • Project Scaffolding: Starting new projects with template files.
    • Local Development: Running a local Flow emulator to test code before deploying to testnet or mainnet.
    • Network Interaction: Deploying contracts, executing Cadence scripts, and sending transactions.
    • Account & Key Management: Creating accounts, managing keys, and handling signatures.
    • Cadence Tooling: Running Cadence tests and executing Cadence code directly.
  2. Handle Cadence script imports for ad-hoc queries

    master

    When using scripts cloned from external repositories, you may encounter import errors if the script uses alias-based imports (e.g., import "FlowToken") instead of explicit addresses.

    To resolve this for ad-hoc queries without setting up a full flow.json configuration with address mappings, you must manually update the script to use explicit addresses:

    1. Repo style (Requires flow.json aliases): import "FlowToken"
    2. Direct style (Works for ad-hoc queries): import FlowToken from 0x1654653399040a61
    // Repo style (requires flow.json aliases):
    import "FlowToken"
    
    // Direct style (works without flow.json):
    import FlowToken from 0x1654653399040a61
  3. Query generic Fungible Token (FT) balances and metadata

    master

    Retrieve the balance of any Fungible Token by providing its account address and the public path to its balance capability. You can also retrieve display metadata for a specific FT vault.

    ### Generic FT Balance (Any Token by Path)
    ```cadence
    import FungibleToken from 0xf233dcee88fe0abe
    
    access(all) fun main(address: Address, path: PublicPath): UFix64 {
        return getAccount(address).capabilities
            .borrow<&{FungibleToken.Balance}>(path)? .balance
            ?? panic("Could not borrow FungibleToken Balance capability for account \(address) at path \(path). Make sure the account has a Fungible Token Vault set up at this path.")
    }

    FT Metadata (Display Info)

    import FungibleToken from 0xf233dcee88fe0abe
    import FungibleTokenMetadataViews from 0xf233dcee88fe0abe
    
    access(all) fun main(address: Address, vaultPath: PublicPath): FungibleTokenMetadataViews.FTDisplay? {
        let account = getAccount(address)
        let vaultRef = account.capabilities
            .borrow<&{FungibleToken.Vault}>(vaultPath)
            ?? panic("Could not borrow FungibleToken Vault capability for account \(address) at path \(vaultPath). Make sure the account has a Fungible Token Vault set up at this path.")
        return FungibleTokenMetadataViews.getFTDisplay(vaultRef)
    }
  4. Query Epoch information

    master

    Retrieve details about the current Flow epoch, including the counter, the current phase (Staking Auction, Epoch Setup, or Epoch Commit), metadata for a specific epoch, and timing configurations.

    ### Current Epoch Counter
    ```cadence
    import FlowEpoch from 0x8624b52f9ddcd04a
    
    access(all) fun main(): UInt64 {
        return FlowEpoch.currentEpochCounter
    }

    Current Epoch Phase

    import FlowEpoch from 0x8624b52f9ddcd04a
    
    // Returns: 0=StakingAuction, 1=EpochSetup, 2=EpochCommit
    access(all) fun main(): UInt8 {
        return FlowEpoch.currentEpochPhase.rawValue
    }

    Epoch Metadata

    import FlowEpoch from 0x8624b52f9ddcd04a
    
    access(all) fun main(counter: UInt64): FlowEpoch.EpochMetadata {
        return FlowEpoch.getEpochMetadata(counter)!
    }

    Epoch Timing Config

    import FlowEpoch from 0x8624b52f9ddcd04a
    
    access(all) fun main(): FlowEpoch.EpochTimingConfig {
        return FlowEpoch.getEpochTimingConfig()
    }
  5. Query FLOW token balances and supply

    master

    Use these Cadence scripts to retrieve the balance of a specific account for FLOW or to check the total supply of the FLOW token on mainnet.

    Note: These scripts use mainnet addresses. For testnet, substitute addresses from the contract address tables in SKILL.md.

    ### FLOW Token Balance
    ```cadence
    import FungibleToken from 0xf233dcee88fe0abe
    import FlowToken from 0x1654653399040a61
    
    access(all) fun main(address: Address): UFix64 {
        let account = getAccount(address)
        let vaultRef = account.capabilities
            .borrow<&{FungibleToken.Balance}>(/public/flowTokenBalance)
            ?? panic("Could not borrow FungibleToken Balance capability for account \(address) at path /public/flowTokenBalance. Make sure the account has a FlowToken Vault set up properly.")
        return vaultRef.balance
    }

    FLOW Total Supply

    import FlowToken from 0x1654653399040a61
    
    access(all) fun main(): UFix64 {
        return FlowToken.totalSupply
    }
  6. Execute Cadence scripts for advanced queries

    master

    When standard CLI commands do not expose the required data (e.g., calling a contract view function or combining data from multiple contracts), use flow scripts execute.

    Command Signature: flow scripts execute <script.cdc> [args...] [--args-json '<json_string>'] [--block-height N] [--block-id <id>] [--network <network>]

    Argument Handling:

    • Simple types (Address, UInt64, String, Bool): Pass as positional arguments.
    • Complex types (UFix64, optionals, structs, arrays): Pass using the --args-json flag with JSON-Cadence encoding.
    • Historical state: Use --block-height N or --block-id <id> to query state at a specific point in time.

    Workflow Example:

    1. Write your Cadence script to a temporary .cdc file.
    2. Execute the script using flow scripts execute.
    3. Clean up the temporary file.
    flow scripts execute /tmp/query.cdc 0xe467b9dd11fa00df --network mainnet
    
    # Using complex types
    flow scripts execute /tmp/query.cdc --args-json '[{"type":"UFix64","value":"100.0"},{"type":"Address","value":"0xe467b9dd11fa00df"}]' --network mainnet
  7. Start a new Flow project with `flow init`

    master

    If you are starting a new Flow project, use the init super command to scaffold a new project structure. This command sets up the necessary files to begin developing Cadence code and managing your project.

    flow init
  8. Query Protocol and NFT information

    master

    Retrieve protocol-level data such as the current node version and the latest random beacon source. You can also query NFT collections to get all token IDs and specific NFT metadata (display info).

    ### Current Node Version
    ```cadence
    import NodeVersionBeacon from 0xe467b9dd11fa00df
    
    access(all) fun main(): NodeVersionBeacon.Semver {
        return NodeVersionBeacon.getCurrentVersionBoundary().version
    }

    Latest Random Beacon Source

    import RandomBeaconHistory from 0xe467b9dd11fa00df
    
    access(all) fun main(): RandomBeaconHistory.RandomSourceHistoryEntry {
        return RandomBeaconHistory.getLatestSourceOfRandomness()
    }

    NFT Collection IDs

    import NonFungibleToken from 0x1d7e57aa55817448
    
    access(all) fun main(address: Address, collectionPublicPath: PublicPath): [UInt64] {
        let account = getAccount(address)
        let collectionRef = account.capabilities
            .borrow<&{NonFungibleToken.Collection}>(collectionPublicPath)
            ?? panic("Could not borrow NonFungibleToken Collection capability for account \(address) at path \(collectionPublicPath). Make sure the account has an NFT Collection set up at this path.")
        return collectionRef.getIDs()
    }

    NFT Metadata (Display)

    import NonFungibleToken from 0x1d7e57aa55817448
    import MetadataViews from 0x1d7e57aa55817448
    
    access(all) fun main(address: Address, collectionPublicPath: PublicPath, id: UInt64): MetadataViews.Display? {
        let account = getAccount(address)
        let collectionRef = account.capabilities
            .borrow<&{NonFungibleToken.Collection}>(collectionPublicPath)
            ?? panic("Could not borrow NonFungibleToken Collection capability for account \(address) at path \(collectionPublicPath). Make sure the account has an NFT Collection set up at this path.")
        let nft = collectionRef.borrowNFT(id)!
        return MetadataViews.getDisplay(nft)
    }
  9. Configure the network for flow-cli commands

    master

    By default, flow-cli uses the mainnet. You can specify different networks using the --network flag. Use the following mapping to choose the correct network for your context:

    • Mainnet (Production): --network mainnet
    • Testnet: --network testnet
    • Local development / emulator: --network emulator

    To point at a custom access node, use the --host <endpoint> flag.

    flow accounts get 0xe467b9dd11fa00df --network mainnet
  10. Query account storage and fee parameters

    master

    Access information regarding account storage capacity, available balances after storage reservation, account creation fees, and current transaction fee parameters.

    ### Account Storage Capacity
    ```cadence
    import FlowStorageFees from 0xe467b9dd11fa00df
    
    access(all) fun main(address: Address): UFix64 {
        return FlowStorageFees.calculateAccountCapacity(address)
    }

    Account Available Balance (After Storage Reservation)

    import FlowStorageFees from 0xe467b9dd11fa00df
    
    access(all) fun main(address: Address): UFix64 {
        return FlowStorageFees.defaultTokenAvailableBalance(address)
    }

    Account Creation Fee

    import FlowServiceAccount from 0xe467b9dd11fa00df
    
    access(all) fun main(): UFix64 {
        return FlowServiceAccount.accountCreationFee
    }

    Transaction Fee Parameters

    import FlowFees from 0xf919ee77447b7497
    
    access(all) fun main(): FlowFees.FeeParameters {
        return FlowFees.getFeeParameters()
    }
  11. Use external script libraries for complex blockchain queries

    master

    For complex queries that are not covered by standard flow-cli commands, you can use Cadence scripts from official Flow repositories. To do this, clone the desired repository to a local directory (e.g., /tmp) and use the flow scripts execute command, pointing to the specific .cdc script file.

    RepositoryScripts PathUse Case
    flow-core-contractstransactions/*/scripts/Staking, epoch, fees, locked tokens, version beacon, random beacon
    flow-fttransactions/scripts/, transactions/metadata/scripts/FT balances, supply, metadata, switchboard
    flow-nfttransactions/scripts/NFT collections, metadata views, cross-VM views
    flow-evm-bridgecadence/scripts/Bridge state, onboarding checks, escrow, EVM balances, cross-VM associations
    nft-storefrontscripts/Marketplace listings, ghost listings, commission receivers, storefront IDs
    hybrid-custodyscripts/hybrid-custody/, scripts/delegator/, scripts/factory/Child/parent account relationships, cross-account NFT/FT access, capability delegation
    # Example: use an existing script from flow-core-contracts
    git clone --depth 1 https://github.com/onflow/flow-core-contracts.git /tmp/flow-core-contracts
    flow scripts execute /tmp/flow-core-contracts/transactions/idTableStaking/scripts/get_node_info.cdc "abc123...def456" --network mainnet