Cadence Language Repository

repository·master·Indexed 19 days ago

https://github.com/onflow/cadence

The resource-oriented smart contract programming language for the Flow blockchain. This repository contains documentation and tools for contributors and developers of the Cadence language itself, including the parser, semantic error generation, the Source Compatibility Suite, and utilities like the AST Explorer and Accounts Script.

Tokens
36.3K
Snippets
156
Records
220
Agent score
69%

What's inside Cadence

  1. What is maprange?

    master
    maprange is a Go analyzer designed to detect the use of for-range statements when iterating over maps. Because iteration order in Go maps is undefined and nondeterministic, using for-range on a map can lead to unpredictable behavior in programs where order matters. This tool helps developers identify these instances to prevent nondeterministic logic.
  2. Overview of Accounts Script

    master
    Accounts Script is a specialized tool designed to run a specific Cadence script against every account on a network by utilizing an execution checkpoint. This is useful for large-scale operations like iterating through storage or auditing account states across the entire blockchain state.
  3. Encode and decode Cadence values using the encoding package

    master
    The encoding package provides utilities to convert Cadence values between the Cadence language and other data formats. Currently, the package exclusively supports the JSON-Cadence specification. This is useful for serializing Cadence data for transmission or storage in external systems that consume JSON.
  4. What is Cadence and its core design principles

    master

    Cadence is a resource-oriented, capability-based smart contract programming language used on the Flow network. It is designed to prevent common smart contract vulnerabilities (like reentrancy or unauthorized asset duplication) at the compiler level.

    Core Design Principles

    • Resource-oriented programming: Assets are first-class resources with move semantics. The compiler ensures resources cannot be duplicated, implicitly destroyed, or accessed after being moved.
    • Capability-based security: Uses entitlements for fine-grained access control. Functions are restricted based on the caller's specific authorizations.
    • Type safety: Features a strong static type system with type inference to prevent runtime type errors.
    • Upgradeable by default: Contracts support upgrades with enforced backward compatibility without requiring proxy patterns.
    • Reentrancy mitigation: When a resource transfers, the caller's reference is invalidated at runtime, mitigating reentrancy attack vectors.
  5. Handle special dependency cases (flowkit and modules)

    master

    Certain dependencies require specific handling in the update command:

    • flowkit: Because Go handles v2 specially, you must specify the version for both the base package and the v2 path.
      • Pattern: onflow/flowkit@<version>,onflow/flowkit/v2@<version>
    • Modules: When updating or releasing modules within a single repository, use the --mod flag during the release process.
    • Unreleased repos: For repos without tags, use the 12-character commit hash format via the --versions flag.
    ts-node main.ts update --version v2.0.0-stable-cadence-alpha.5 --versions onflow/flowkit@v2.0.0-stable-cadence-alpha.5,onflow/flowkit/v2@v2.0.0-stable-cadence-alpha.5
  6. Understand Resource Move Semantics

    master

    Resources in Cadence follow linear typing rules to ensure they are never lost or duplicated:

    • Mandatory Move (<-): You must use the move operator <- for resource expressions; this invalidates the source.
    • Creation: create can only be used inside the declaring contract/location and only for direct resource types.
    • Destruction: destroy can only be called on resources and emits the ResourceDestroyed event.
    • Restrictions: Resources are forbidden in ternary expressions. Moving a resource into an array or dictionary follows specific nested-resource move rules.
    • Double-transfer: A pattern like let x <- a <- b temporarily invalidates the first target before re-validating it.
  7. Cadence Versioning Strategy

    master

    Cadence follows Semantic Versioning (SemVer) to communicate the impact of changes:

    • Major version change: Used for language-breaking changes (e.g., 1.0.0 -> 2.0.0). Breaking changes are rare and require community consensus.
    • Minor version change: Used for feature additions, Go API changes, or other non-breaking updates (e.g., 1.0.0 -> 1.1.0).
    • Patch version change: Used for bug fixes (e.g., 1.0.0 -> 1.0.1).
  8. Understand Cadence built-in types and interfaces

    master

    Cadence provides several built-in types and interfaces for common operations.

    Core Interfaces

    • Storable: Indicates a type can be saved to account storage. Most value types and capabilities are Storable, but references and functions are NOT storable.
    • Hashable: Indicates a type can be used as a dictionary key. Valid types include numbers, Address, Bool, Character, String, Type, paths, enums, and HashableStruct.
    • Equatable: Supports == and !=. Includes numeric types, String, Character, Bool, Address, path types, Type, and enums. Note that general structs/resources are not equatable.
    • Comparable: Supports < <= > >=. Includes all numeric types, String, Character, and Bool.
    • StructStringer: A built-in interface providing a toString() method.

    Special Types

    • Bool, Void, Never.
    • AnyStruct, AnyResource.
    • AnyStructAttachment, AnyResourceAttachment.
    • HashableStruct.
  9. Cadence Lexical and Syntactic Foundations

    master

    Cadence supports several lexical features for code documentation and data representation:

    • Comments: Supports line comments and nested block comments /* */.
    • Doc-strings: Used for documenting code elements.
    • Literals:
      • Nil: nil
      • Boolean: true, false
      • Integers: Supports decimal, hex (0x), binary (0b), octal (0o), and digit grouping using _.
      • Fixed-point: Fixed-point literals.
      • Strings: Supports escape sequences (\0 \n \r \t \" \' \\) and Unicode (\u{...}).
      • String Interpolation: Use the syntax "... \(expr) ...".
      • Collections: Array literals [...] and dictionary literals {k: v}.
      • Paths: Path literals use the format /domain/identifier.
      • Void: Represented by ().

    Note: The parser has a depth limit of 16 levels for both expressions and types.

  10. Understand References and Authorization

    master

    References allow access to values but come with strict safety and authorization rules:

    • Explicit Targets: References require an explicit target type. References-to-references are not allowed.
    • Optionality: &T? is parsed as (&T)?. The reference's optionality must match the referenced value's.
    • Dereferencing (*r): Reads through a reference. On an optional reference, it yields an optional. The inner type must be a primitive or a container of primitives.
    • Authorization: Member/index access through a reference returns a reference with authorization that is either intersected/narrowed (entitlement-set) or mapped (entitlement-map).
    • Binding Restriction: Resource methods cannot be bound to a variable; they must be invoked directly.
  11. How resource-oriented programming works in Cadence

    master

    Resource-oriented programming in Cadence pairs linear types with object capabilities. This model ensures that a resource (representing a digital asset) can only exist in one location at a time.

    Key constraints enforced by the compiler:

    • Resources cannot be copied.
    • Resources cannot be accidentally lost or deleted.
    • Resources cannot be accessed after they have been moved to a new location.