Skip to main content
Version: Next

Interfaces

An interface is an abstract type that specifies the behavior of types that implement the interface. Interfaces declare the required functions and fields, the access control for those declarations, and preconditions and postconditions that implementing types need to provide.

There are three kinds of interfaces:

  • Structure interfaces: implemented by structures
  • Resource interfaces: implemented by resources
  • Contract interfaces: implemented by contracts

Structure, resource, and contract types may implement multiple interfaces.

There is no support for event and enum interfaces.

Nominal typing applies to composite types that implement interfaces. This means that a type only implements an interface if it has explicitly declared the conformance, the composite type does not implicitly conform to an interface, even if it satisfies all requirements of the interface.

Interfaces consist of the function and field requirements that a type implementing the interface must provide implementations for. Interface requirements, and therefore also their implementations, must always be at least public.

Variable field requirements may be annotated to require them to be publicly settable.

Function requirements consist of the name of the function, parameter types, an optional return type, and optional preconditions and postconditions.

Field requirements consist of the name and the type of the field. Field requirements may optionally declare a getter requirement and a setter requirement, each with preconditions and postconditions.

Calling functions with preconditions and postconditions on interfaces instead of concrete implementations can improve the security of a program, as it ensures that even if implementations change, some aspects of them will always hold.

Interface Declaration

Interfaces are declared using the struct, resource, or contract keyword, followed by the interface keyword, the name of the interface, and the requirements, which must be enclosed in opening and closing braces.

Field requirements can be annotated to require the implementation to be a variable field, by using the var keyword; require the implementation to be a constant field, by using the let keyword; or the field requirement may specify nothing, in which case the implementation may either be a variable or a constant field.

Field requirements and function requirements must specify the required level of access. The access must be at least be public, so the access(all) keyword must be provided.

Interfaces can be used in types. This is explained in detail in the section Interfaces in Types. For now, the syntax {I} can be read as the type of any value that implements the interface I.

// Declare a resource interface for a fungible token.
// Only resources can implement this resource interface.
//
access(all) resource interface FungibleToken {

// Require the implementing type to provide a field for the balance
// that is readable in all scopes (`access(all)`).
//
// Neither the `var` keyword, nor the `let` keyword is used,
// so the field may be implemented as either a variable
// or as a constant field.
//
access(all) balance: Int

// Require the implementing type to provide an initializer that
// given the initial balance, must initialize the balance field.
//
init(balance: Int) {
pre {
balance >= 0:
"Balances are always non-negative"
}
post {
self.balance == balance:
"the balance must be initialized to the initial balance"
}

// NOTE: The declaration contains no implementation code.
}

// Require the implementing type to provide a function that is
// callable in all scopes, which withdraws an amount from
// this fungible token and returns the withdrawn amount as
// a new fungible token.
//
// The given amount must be positive and the function implementation
// must add the amount to the balance.
//
// The function must return a new fungible token.
// The type `{FungibleToken}` is the type of any resource
// that implements the resource interface `FungibleToken`.
//
access(all) fun withdraw(amount: Int): @{FungibleToken} {
pre {
amount > 0:
"the amount must be positive"
amount <= self.balance:
"insufficient funds: the amount must be smaller or equal to the balance"
}
post {
self.balance == before(self.balance) - amount:
"the amount must be deducted from the balance"
}

// NOTE: The declaration contains no implementation code.
}

// Require the implementing type to provide a function that is
// callable in all scopes, which deposits a fungible token
// into this fungible token.
//
// No precondition is required to check the given token's balance
// is positive, as this condition is already ensured by
// the field requirement.
//
// The parameter type `{FungibleToken}` is the type of any resource
// that implements the resource interface `FungibleToken`.
//
access(all) fun deposit(_ token: @{FungibleToken}) {
post {
self.balance == before(self.balance) + token.balance:
"the amount must be added to the balance"
}

// NOTE: The declaration contains no implementation code.
}
}

Note that the required initializer and functions do not have any executable code.

Struct and resource Interfaces can only be declared directly inside contracts, i.e. not inside of functions. Contract interfaces can only be declared globally and not inside contracts.

Interface Implementation

Declaring that a type implements (conforms) to an interface is done in the type declaration of the composite type (e.g., structure, resource): The kind and the name of the composite type is followed by a colon (:) and the name of one or more interfaces that the composite type implements.

This will tell the checker to enforce any requirements from the specified interfaces onto the declared type.

A type implements (conforms to) an interface if it declares the implementation in its signature, provides field declarations for all fields required by the interface, and provides implementations for all functions required by the interface.

The field declarations in the implementing type must match the field requirements in the interface in terms of name, type, and declaration kind (e.g. constant, variable) if given. For example, an interface may require a field with a certain name and type, but leaves it to the implementation what kind the field is.

The function implementations must match the function requirements in the interface in terms of name, parameter argument labels, parameter types, and the return type.

// Declare a resource named `ExampleToken` that has to implement
// the `FungibleToken` interface.
//
// It has a variable field named `balance`, that can be written
// by functions of the type, but outer scopes can only read it.
//
access(all) resource ExampleToken: FungibleToken {

// Implement the required field `balance` for the `FungibleToken` interface.
// The interface does not specify if the field must be variable, constant,
// so in order for this type (`ExampleToken`) to be able to write to the field,
// but limit outer scopes to only read from the field, it is declared variable,
// and only has public access (non-settable).
//
access(all) var balance: Int

// Implement the required initializer for the `FungibleToken` interface:
// accept an initial balance and initialize the `balance` field.
//
// This implementation satisfies the required postcondition.
//
// NOTE: the postcondition declared in the interface
// does not have to be repeated here in the implementation.
//
init(balance: Int) {
self.balance = balance
}

// Implement the required function named `withdraw` of the interface
// `FungibleToken`, that withdraws an amount from the token's balance.
//
// The function must be public.
//
// This implementation satisfies the required postcondition.
//
// NOTE: neither the precondition nor the postcondition declared
// in the interface have to be repeated here in the implementation.
//
access(all) fun withdraw(amount: Int): @ExampleToken {
self.balance = self.balance - amount
return create ExampleToken(balance: amount)
}

// Implement the required function named `deposit` of the interface
// `FungibleToken`, that deposits the amount from the given token
// to this token.
//
// The function must be public.
//
// NOTE: the type of the parameter is `{FungibleToken}`,
// i.e., any resource that implements the resource interface `FungibleToken`,
// so any other token – however, we want to ensure that only tokens
// of the same type can be deposited.
//
// This implementation satisfies the required postconditions.
//
// NOTE: neither the precondition nor the postcondition declared
// in the interface have to be repeated here in the implementation.
//
access(all) fun deposit(_ token: @{FungibleToken}) {
if let exampleToken <- token as? ExampleToken {
self.balance = self.balance + exampleToken.balance
destroy exampleToken
} else {
panic("cannot deposit token which is not an example token")
}
}
}

// Declare a constant which has type `ExampleToken`,
// and is initialized with such an example token.
//
let token <- create ExampleToken(balance: 100)

// Withdraw 10 units from the token.
//
// The amount satisfies the precondition of the `withdraw` function
// in the `FungibleToken` interface.
//
// Invoking a function of a resource does not destroy the resource,
// so the resource `token` is still valid after the call of `withdraw`.
//
let withdrawn <- token.withdraw(amount: 10)

// The postcondition of the `withdraw` function in the `FungibleToken`
// interface ensured the balance field of the token was updated properly.
//
// `token.balance` is `90`
// `withdrawn.balance` is `10`

// Deposit the withdrawn token into another one.
let receiver: @ExampleToken <- // ...
receiver.deposit(<-withdrawn)

// Run-time error: The precondition of function `withdraw` in interface
// `FungibleToken` fails, the program aborts: the parameter `amount`
// is larger than the field `balance` (100 > 90).
//
token.withdraw(amount: 100)

// Withdrawing tokens so that the balance is zero does not destroy the resource.
// The resource has to be destroyed explicitly.
//
token.withdraw(amount: 90)

The access level for variable fields in an implementation may be less restrictive than the interface requires. For example, an interface may require a field to be at least contract-accessible (i.e. the access(contract) modifier is used), and an implementation may provide a variable field which is public, (the access(all) modifier is used).

access(all) struct interface AnInterface {
// Require the implementing type to provide a contract-readable
// field named `a` that has type `Int`. It may be a variable
// or a constant field.
//
access(contract) a: Int
}

access(all) struct AnImplementation: AnInterface {
// Declare a public variable field named `a` that has type `Int`.
// This implementation satisfies the requirement for interface `AnInterface`:
//
access(all) var a: Int

init(a: Int) {
self.a = a
}
}

Interfaces in Types

Interfaces can be used in types: The type {I} is the type of all objects that implement the interface I.

This is called a intersection type: Only the functionality (members and functions) of the interface can be used when accessing a value of such a type.

// Declare an interface named `Shape`.
//
// Require implementing types to provide a field which returns the area,
// and a function which scales the shape by a given factor.
//
access(all) struct interface Shape {
access(all) fun getArea(): Int
access(all) fun scale(factor: Int)
}

// Declare a structure named `Square` the implements the `Shape` interface.
//
access(all) struct Square: Shape {
// In addition to the required fields from the interface,
// the type can also declare additional fields.
//
access(all) var length: Int

// Provided the field `area` which is required to conform
// to the interface `Shape`.
//
// Since `area` was not declared as a constant, variable,
// field in the interface, it can be declared.
//
access(all) fun getArea(): Int {
return self.length * self.length
}

access(all) init(length: Int) {
self.length = length
}

// Provided the implementation of the function `scale`
// which is required to conform to the interface `Shape`.
//
access(all) fun scale(factor: Int) {
self.length = self.length * factor
}
}

// Declare a structure named `Rectangle` that also implements the `Shape` interface.
//
access(all) struct Rectangle: Shape {
access(all) var width: Int
access(all) var height: Int

// Provided the field `area which is required to conform
// to the interface `Shape`.
//
access(all) fun getArea(): Int {
return self.width * self.height
}

access(all) init(width: Int, height: Int) {
self.width = width
self.height = height
}

// Provided the implementation of the function `scale`
// which is required to conform to the interface `Shape`.
//
access(all) fun scale(factor: Int) {
self.width = self.width * factor
self.height = self.height * factor
}
}

// Declare a constant that has type `Shape`, which has a value that has type `Rectangle`.
//
var shape: {Shape} = Rectangle(width: 10, height: 20)

Values implementing an interface are assignable to variables that have the interface as their type.

// Assign a value of type `Square` to the variable `shape` that has type `Shape`.
//
shape = Square(length: 30)

// Invalid: cannot initialize a constant that has type `Rectangle`.
// with a value that has type `Square`.
//
let rectangle: Rectangle = Square(length: 10)

Fields declared in an interface can be accessed and functions declared in an interface can be called on values of a type that implements the interface.

// Declare a constant which has the type `Shape`.
// and is initialized with a value that has type `Rectangle`.
//
let shape: {Shape} = Rectangle(width: 2, height: 3)

// Access the field `area` declared in the interface `Shape`.
//
shape.area // is `6`

// Call the function `scale` declared in the interface `Shape`.
//
shape.scale(factor: 3)

shape.area // is `54`

Interface Nesting

info

🚧 Status: Currently only contracts and contract interfaces support nested interfaces.

Interfaces can be arbitrarily nested. Declaring an interface inside another does not require implementing types of the outer interface to provide an implementation of the inner interfaces.

// Declare a resource interface `OuterInterface`, which declares
// a nested structure interface named `InnerInterface`.
//
// Resources implementing `OuterInterface` do not need to provide
// an implementation of `InnerInterface`.
//
// Structures may just implement `InnerInterface`.
//
resource interface OuterInterface {

struct interface InnerInterface {}
}

// Declare a resource named `SomeOuter` that implements the interface `OuterInterface`.
//
// The resource is not required to implement `OuterInterface.InnerInterface`.
//
resource SomeOuter: OuterInterface {}

// Declare a structure named `SomeInner` that implements `InnerInterface`,
// which is nested in interface `OuterInterface`.
//
struct SomeInner: OuterInterface.InnerInterface {}

Contract interfaces may also declare events, which also do not require implementing types of the outer interface to "implement" the event. The event can be emitted in the declaring interface, in a condition or in a default implementation of a function. E.g.

// Declare a contract interface
//
contract interface ContractInterface {
// some event declaration
//
event SomeEvent()

// some function that emits `SomeEvent` when called
//
fun eventEmittingFunction() {
pre {
emit SomeEvent()
}
}
}

// A contract implementing `ContractInterface`
// Note that no declaration of `SomeEvent` is required
//
contract ImplementingContract: ContractInterface {
// implementation of `eventEmittingFunction`;
// this will emit `SomeEvent` when called
//
fun eventEmittingFunction() {
// ...
}
}

Interface Default Functions

Interfaces can provide default functions: If the concrete type implementing the interface does not provide an implementation for the function required by the interface, then the interface's default function is used in the implementation.

// Declare a struct interface `Container`,
// which declares a default function `getCount`.
//
struct interface Container {

let items: [AnyStruct]

fun getCount(): Int {
return self.items.length
}
}

// Declare a concrete struct named `Numbers` that implements the interface `Container`.
//
// The struct does not implement the function `getCount` of the interface `Container`,
// so the default function for `getCount` is used.
//
struct Numbers: Container {
let items: [AnyStruct]

init() {
self.items = []
}
}

let numbers = Numbers()
numbers.getCount() // is 0

Interfaces cannot provide default initializers or default destructors.

Only one conformance may provide a default function.

Interface inheritance

An interface can inherit from (conform to) other interfaces of the same kind. For example, a resource interface can inherit from another resource interface, but cannot inherit from a struct interface. When an interface inherits from another, all the fields, functions, and types of the parent interface are implicitly available to the inheriting interface.

access(all) resource interface Receiver {
access(all) fun deposit(_ something: @AnyResource)
}

// `Vault` interface inherits from `Receiver` interface.
access(all) resource interface Vault: Receiver {
access(all) fun withdraw(_ amount: Int): @Vault
}

In the example above, Vault inherits Receiver. Anyone implementing the Vault interface would also have to implement the Receiver interface.

access(all) resource MyVault: Vault {
// Must implement all the methods coming from both `Vault` and `Receiver` interfaces.
access(all) fun deposit(_ something: @AnyResource) {}

access(all) fun withdraw(_ amount: Int): @Vault {}
}

Duplicate interface members

When an interface implements another interface, it is possible for the two interfaces to have members with the same name. The following sections explain how these ambiguities are resolved for different scenarios.

Fields

If two fields with identical names have identical types, then it will be valid.

access(all) resource interface Receiver {
access(all) var id: UInt64
}

access(all) resource interface Vault: Receiver {
// `id` field has the same type as the `Receiver.id`. Hence this is valid.
access(all) var id: UInt64
}

Otherwise, interface conformance is not valid.

access(all) resource interface Receiver {
access(all) var id: Int
}

access(all) resource interface Vault: Receiver {
// `id` field has a different type than the `Receiver.id`. Hence this is invalid.
access(all) var id: UInt64
}

Functions

If two functions with identical names also have identical signatures, that is valid.

access(all) resource interface Receiver {
access(all) fun deposit(_ something: @AnyResource)
}

access(all) resource interface Vault: Receiver {
// `deposit` function has the same signature as the `Receiver.deposit`.
// Also none of them have any default implementations.
// Hence this is valid.
access(all) fun deposit(_ something: @AnyResource)
}

If the signatures of the two functions are different, then the interface conformance is not valid.

access(all) resource interface Receiver {
access(all) fun deposit(_ something: @AnyResource)
}

access(all) resource interface Vault: Receiver {
// Error: `deposit` function has a different signature compared to the `Receiver.deposit`.
// So these two cannot co-exist.
access(all) fun deposit()
}

Functions with conditions

If the two functions with identical names and signatures have pre/post conditions, then it will still be valid. However, the pre/post conditions are linearized (refer to the linearizing conditions section) to determine the order of the execution of the conditions. Given the pre/post conditions are view only, the order of execution would not have an impact on the conditions.

access(all) resource interface Receiver {
access(all) fun deposit(_ something: @AnyResource) {
pre{ self.balance > 100 }
}
}

access(all) resource interface Vault: Receiver {
// `deposit` function has the same signature as the `Receiver.deposit`.
// Having pre/post condition is valid.
// Both conditions would be executed, in a pre-determined order.
access(all) fun deposit(_ something: @AnyResource) {
pre{ self.balance > 50 }
}
}

Default functions

An interface can provide a default implementation to an inherited function.

access(all) resource interface Receiver {
access(all) fun log(_ message: String)
}

access(all) resource interface Vault: Receiver {
// Valid: Provides the implementation for `Receiver.log` method.
access(all) fun log(_ message: String) {
log(message.append("from Vault"))
}
}

However, an interface cannot override an inherited default implementation of a function.

access(all) resource interface Receiver {
access(all) fun log(_ message: String) {
log(message.append("from Receiver"))
}
}

access(all) resource interface Vault: Receiver {
// Invalid: Cannot override the `Receiver.log` method.
access(all) fun log(_ message: String) {
log(message.append("from Vault"))
}
}

It is also invalid to have two or more inherited default implementations for an interface.

access(all) resource interface Receiver {
access(all) fun log(_ message: String) {
log(message.append("from Receiver"))
}
}

access(all) resource interface Provider {
access(all) fun log(_ message: String) {
log(message.append("from Provider"))
}
}

// Invalid: Two default functions from two interfaces.
access(all) resource interface Vault: Receiver, Provider {}

Having said that, there can be situations where the same default function can be available via different inheritance paths.

access(all) resource interface Logger {
access(all) fun log(_ message: String) {
log(message.append("from Logger"))
}
}

access(all) resource interface Receiver: Logger {}

access(all) resource interface Provider: Logger {}

// Valid: `Logger.log()` default function is visible to the `Vault` interface
// via both `Receiver` and `Provider`.
access(all) resource interface Vault: Receiver, Provider {}

In the above example, Logger.log() default function is visible to the Vault interface via both Receiver and Provider. Even though it is available from two different interfaces, they are both referring to the same default implementation. Therefore, the above code is valid.

Conditions with Default functions

A more complex situation is where a default function is available via one inheritance path and a pre/post condition is available via another inheritance path.

access(all) resource interface Receiver {
access(all) fun log(_ message: String) {
log(message.append("from Receiver"))
}
}

access(all) resource interface Provider {
access(all) fun log(_ message: String) {
pre{ message != "" }
}
}

// Valid: Both the default function and the condition would be available.
access(all) resource interface Vault: Receiver, Provider {}

In such situations, all rules applicable for default functions inheritance as well as condition inheritance would be applied. Thus, the default function from coming from the Receiver interface, and the condition comes from the Provider interface would be made available for the inherited interface.

Types and event definitions

Type and event definitions would also behave similarly to the default functions. Inherited interfaces can override type definitions and event definitions.

access(all) contract interface Token {
access(all) struct Foo {}
}

access(all) contract interface NonFungibleToken: Token {
access(all) struct Foo {}
}

access(all) contract MyToken: NonFungibleToken {
access(all) fun test() {
let foo: Foo // This will refer to the `NonFungibleToken.Foo`
}
}

If a user needed to access the Foo struct coming from the super interface Token, then they can access it using the fully qualified name. e.g: let foo: Token.Foo.

However, it is not allowed to have two or more inherited type/events definitions with identical names for an interface.

access(all) contract interface Token {
access(all) struct Foo {}
}

access(all) contract interface Collectible {
access(all) struct Foo {}
}

// Invalid: Two type definitions with the same name from two interfaces.
access(all) contract NonFungibleToken: Token, Collectible {
}

Similar to default functions, there can be situations where the same type/event definition can be available via different inheritance paths.

access(all) contract interface Logger {
access(all) struct Foo {}
}

access(all) contract interface Token: Logger {}

access(all) contract interface Collectible: Logger {}

// Valid: `Logger.Foo` struct is visible to the `NonFungibleToken` interface via both `Token` and `Collectible`.
access(all) contract interface NonFungibleToken: Token, Collectible {}

In the above example, Logger.Foo type definition is visible to the NonFungibleToken interface via both Token and Collectible. Even though it is available from two different interfaces, they are both referring to the same type definition. Therefore, the above code is valid.

However, if at least one of the interfaces in the middle of the chain also overrides the type definition Foo, then the code becomes invalid, as there are multiple implementations present now, which leads to ambiguity.

access(all) contract interface Logger {
access(all) struct Foo {}
}

access(all) contract interface Token: Logger {
access(all) struct Foo {}
}

access(all) contract interface Collectible: Logger {}

// Invalid: The default implementation of the `Foo` struct by the `Logger`
// interface is visible to the `NonFungibleToken` via the `Collectible` interface.
// Another implementation of `Foo` struct is visible to the `NonFungibleToken` via the `Token` interface.
// This creates ambiguity.
access(all) resource interface NonFungibleToken: Token, Provider {}

Linearizing Conditions

As mentioned in the functions with conditions section, it would be required to linearize the function conditions, to determine the order in which pre- and post-conditions are executed. This is done by linearizing the interfaces, and hence conditions, in a depth-first pre-ordered manner, without duplicates.

For example, consider an interface inheritance hierarchy as below:

A
/ \
B C
/ \ /
D E
where an edge from A (top) to B (bottom) means A inherits B.

This would convert to a Cadence implementation similar to:

struct interface A: B, C {
access(all) fun test() {
pre { print("A") }
}
}

struct interface B: D, E {
access(all) fun test() {
pre { print("B") }
}
}

struct interface C: E {
access(all) fun test() {
pre { print("C") }
}
}

struct interface D {
access(all) fun test() {
pre { print("D") }
}
}

struct interface E {
access(all) fun test() {
pre { print("E") }
}
}

Any concrete type implementing interface A would be equivalent to implementing all interfaces from A to E, linearized.

struct Foo: A {
access(all) fun test() {
pre { print("Foo") }
}
}

The linearized interface order would be: [A, B, D, E, C].

i.e: same as having:

struct Foo: A, B, D, C, E {
access(all) fun test() {
pre { print("Foo") }
}
}

Thus, invoking test method of Foo would first invoke the pre-conditions of [A, B, D, E, C], in that particular order, and eventually runs the pre-condition of the concrete implementation Foo.

let foo = Foo()
foo.test()

Above will print:

A
B
D
E
C
Foo

Similarly, for post-conditions, the same linearization of interfaces would be used, and the post-conditions are executed in the reverse order. For example, replacing the pre conditions in the above example with post conditions with the exact same content would result in an output similar to:

Foo
C
E
D
B
A