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 pub keyword must be provided. Variable field requirements can be specified to also be publicly settable by using the pub(set) keyword.

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.

1
// Declare a resource interface for a fungible token.
2
// Only resources can implement this resource interface.
3
//
4
pub resource interface FungibleToken {
5
6
// Require the implementing type to provide a field for the balance
7
// that is readable in all scopes (`pub`).
8
//
9
// Neither the `var` keyword, nor the `let` keyword is used,
10
// so the field may be implemented as either a variable
11
// or as a constant field.
12
//
13
pub balance: Int
14
15
// Require the implementing type to provide an initializer that
16
// given the initial balance, must initialize the balance field.
17
//
18
init(balance: Int) {
19
pre {
20
balance >= 0:
21
"Balances are always non-negative"
22
}
23
post {
24
self.balance == balance:
25
"the balance must be initialized to the initial balance"
26
}
27
28
// NOTE: The declaration contains no implementation code.
29
}
30
31
// Require the implementing type to provide a function that is
32
// callable in all scopes, which withdraws an amount from
33
// this fungible token and returns the withdrawn amount as
34
// a new fungible token.
35
//
36
// The given amount must be positive and the function implementation
37
// must add the amount to the balance.
38
//
39
// The function must return a new fungible token.
40
// The type `{FungibleToken}` is the type of any resource
41
// that implements the resource interface `FungibleToken`.
42
//
43
pub fun withdraw(amount: Int): @{FungibleToken} {
44
pre {
45
amount > 0:
46
"the amount must be positive"
47
amount <= self.balance:
48
"insufficient funds: the amount must be smaller or equal to the balance"
49
}
50
post {
51
self.balance == before(self.balance) - amount:
52
"the amount must be deducted from the balance"
53
}
54
55
// NOTE: The declaration contains no implementation code.
56
}
57
58
// Require the implementing type to provide a function that is
59
// callable in all scopes, which deposits a fungible token
60
// into this fungible token.
61
//
62
// No precondition is required to check the given token's balance
63
// is positive, as this condition is already ensured by
64
// the field requirement.
65
//
66
// The parameter type `{FungibleToken}` is the type of any resource
67
// that implements the resource interface `FungibleToken`.
68
//
69
pub fun deposit(_ token: @{FungibleToken}) {
70
post {
71
self.balance == before(self.balance) + token.balance:
72
"the amount must be added to the balance"
73
}
74
75
// NOTE: The declaration contains no implementation code.
76
}
77
}

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.

1
// Declare a resource named `ExampleToken` that has to implement
2
// the `FungibleToken` interface.
3
//
4
// It has a variable field named `balance`, that can be written
5
// by functions of the type, but outer scopes can only read it.
6
//
7
pub resource ExampleToken: FungibleToken {
8
9
// Implement the required field `balance` for the `FungibleToken` interface.
10
// The interface does not specify if the field must be variable, constant,
11
// so in order for this type (`ExampleToken`) to be able to write to the field,
12
// but limit outer scopes to only read from the field, it is declared variable,
13
// and only has public access (non-settable).
14
//
15
pub var balance: Int
16
17
// Implement the required initializer for the `FungibleToken` interface:
18
// accept an initial balance and initialize the `balance` field.
19
//
20
// This implementation satisfies the required postcondition.
21
//
22
// NOTE: the postcondition declared in the interface
23
// does not have to be repeated here in the implementation.
24
//
25
init(balance: Int) {
26
self.balance = balance
27
}
28
29
// Implement the required function named `withdraw` of the interface
30
// `FungibleToken`, that withdraws an amount from the token's balance.
31
//
32
// The function must be public.
33
//
34
// This implementation satisfies the required postcondition.
35
//
36
// NOTE: neither the precondition nor the postcondition declared
37
// in the interface have to be repeated here in the implementation.
38
//
39
pub fun withdraw(amount: Int): @ExampleToken {
40
self.balance = self.balance - amount
41
return create ExampleToken(balance: amount)
42
}
43
44
// Implement the required function named `deposit` of the interface
45
// `FungibleToken`, that deposits the amount from the given token
46
// to this token.
47
//
48
// The function must be public.
49
//
50
// NOTE: the type of the parameter is `{FungibleToken}`,
51
// i.e., any resource that implements the resource interface `FungibleToken`,
52
// so any other token – however, we want to ensure that only tokens
53
// of the same type can be deposited.
54
//
55
// This implementation satisfies the required postconditions.
56
//
57
// NOTE: neither the precondition nor the postcondition declared
58
// in the interface have to be repeated here in the implementation.
59
//
60
pub fun deposit(_ token: @{FungibleToken}) {
61
if let exampleToken <- token as? ExampleToken {
62
self.balance = self.balance + exampleToken.balance
63
destroy exampleToken
64
} else {
65
panic("cannot deposit token which is not an example token")
66
}
67
}
68
}
69
70
// Declare a constant which has type `ExampleToken`,
71
// and is initialized with such an example token.
72
//
73
let token <- create ExampleToken(balance: 100)
74
75
// Withdraw 10 units from the token.
76
//
77
// The amount satisfies the precondition of the `withdraw` function
78
// in the `FungibleToken` interface.
79
//
80
// Invoking a function of a resource does not destroy the resource,
81
// so the resource `token` is still valid after the call of `withdraw`.
82
//
83
let withdrawn <- token.withdraw(amount: 10)
84
85
// The postcondition of the `withdraw` function in the `FungibleToken`
86
// interface ensured the balance field of the token was updated properly.
87
//
88
// `token.balance` is `90`
89
// `withdrawn.balance` is `10`
90
91
// Deposit the withdrawn token into another one.
92
let receiver: @ExampleToken <- // ...
93
receiver.deposit(<-withdrawn)
94
95
// Run-time error: The precondition of function `withdraw` in interface
96
// `FungibleToken` fails, the program aborts: the parameter `amount`
97
// is larger than the field `balance` (100 > 90).
98
//
99
token.withdraw(amount: 100)
100
101
// Withdrawing tokens so that the balance is zero does not destroy the resource.
102
// The resource has to be destroyed explicitly.
103
//
104
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 public (i.e. the pub keyword is specified), and an implementation may provide a variable field which is public, but also publicly settable (the pub(set) keyword is specified).

1
pub struct interface AnInterface {
2
// Require the implementing type to provide a publicly readable
3
// field named `a` that has type `Int`. It may be a variable
4
// or a constant field.
5
//
6
pub a: Int
7
}
8
9
pub struct AnImplementation: AnInterface {
10
// Declare a publicly settable variable field named `a` that has type `Int`.
11
// This implementation satisfies the requirement for interface `AnInterface`:
12
// The field is at least publicly readable, but this implementation also
13
// allows the field to be written to in all scopes.
14
//
15
pub(set) var a: Int
16
17
init(a: Int) {
18
self.a = a
19
}
20
}

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 restricted type: Only the functionality (members and functions) of the interface can be used when accessing a value of such a type.

1
// Declare an interface named `Shape`.
2
//
3
// Require implementing types to provide a field which returns the area,
4
// and a function which scales the shape by a given factor.
5
//
6
pub struct interface Shape {
7
pub fun getArea(): Int
8
pub fun scale(factor: Int)
9
}
10
11
// Declare a structure named `Square` the implements the `Shape` interface.
12
//
13
pub struct Square: Shape {
14
// In addition to the required fields from the interface,
15
// the type can also declare additional fields.
16
//
17
pub var length: Int
18
19
// Provided the field `area` which is required to conform
20
// to the interface `Shape`.
21
//
22
// Since `area` was not declared as a constant, variable,
23
// field in the interface, it can be declared.
24
//
25
pub fun getArea(): Int {
26
return self.length * self.length
27
}
28
29
pub init(length: Int) {
30
self.length = length
31
}
32
33
// Provided the implementation of the function `scale`
34
// which is required to conform to the interface `Shape`.
35
//
36
pub fun scale(factor: Int) {
37
self.length = self.length * factor
38
}
39
}
40
41
// Declare a structure named `Rectangle` that also implements the `Shape` interface.
42
//
43
pub struct Rectangle: Shape {
44
pub var width: Int
45
pub var height: Int
46
47
// Provided the field `area which is required to conform
48
// to the interface `Shape`.
49
//
50
pub fun getArea(): Int {
51
return self.width * self.height
52
}
53
54
pub init(width: Int, height: Int) {
55
self.width = width
56
self.height = height
57
}
58
59
// Provided the implementation of the function `scale`
60
// which is required to conform to the interface `Shape`.
61
//
62
pub fun scale(factor: Int) {
63
self.width = self.width * factor
64
self.height = self.height * factor
65
}
66
}
67
68
// Declare a constant that has type `Shape`, which has a value that has type `Rectangle`.
69
//
70
var shape: {Shape} = Rectangle(width: 10, height: 20)

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

1
// Assign a value of type `Square` to the variable `shape` that has type `Shape`.
2
//
3
shape = Square(length: 30)
4
5
// Invalid: cannot initialize a constant that has type `Rectangle`.
6
// with a value that has type `Square`.
7
//
8
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.

1
// Declare a constant which has the type `Shape`.
2
// and is initialized with a value that has type `Rectangle`.
3
//
4
let shape: {Shape} = Rectangle(width: 2, height: 3)
5
6
// Access the field `area` declared in the interface `Shape`.
7
//
8
shape.area // is `6`
9
10
// Call the function `scale` declared in the interface `Shape`.
11
//
12
shape.scale(factor: 3)
13
14
shape.area // is `54`

Interface Nesting

🚧 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.

1
// Declare a resource interface `OuterInterface`, which declares
2
// a nested structure interface named `InnerInterface`.
3
//
4
// Resources implementing `OuterInterface` do not need to provide
5
// an implementation of `InnerInterface`.
6
//
7
// Structures may just implement `InnerInterface`.
8
//
9
resource interface OuterInterface {
10
11
struct interface InnerInterface {}
12
}
13
14
// Declare a resource named `SomeOuter` that implements the interface `OuterInterface`.
15
//
16
// The resource is not required to implement `OuterInterface.InnerInterface`.
17
//
18
resource SomeOuter: OuterInterface {}
19
20
// Declare a structure named `SomeInner` that implements `InnerInterface`,
21
// which is nested in interface `OuterInterface`.
22
//
23
struct SomeInner: OuterInterface.InnerInterface {}

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.

1
// Declare a struct interface `Container`,
2
// which declares a default function `getCount`.
3
//
4
struct interface Container {
5
6
let items: [AnyStruct]
7
8
fun getCount(): Int {
9
return self.items.length
10
}
11
}
12
13
// Declare a concrete struct named `Numbers` that implements the interface `Container`.
14
//
15
// The struct does not implement the function `getCount` of the interface `Container`,
16
// so the default function for `getCount` is used.
17
//
18
struct Numbers: Container {
19
let items: [AnyStruct]
20
21
init() {
22
self.items = []
23
}
24
}
25
26
let numbers = Numbers()
27
numbers.getCount() // is 0

Interfaces cannot provide default initializers or default destructors.

Only one conformance may provide a default function.