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.
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//4pub resource interface FungibleToken {56// Require the implementing type to provide a field for the balance7// 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 variable11// or as a constant field.12//13pub balance: Int1415// Require the implementing type to provide an initializer that16// given the initial balance, must initialize the balance field.17//18init(balance: Int) {19pre {20balance >= 0:21"Balances are always non-negative"22}23post {24self.balance == balance:25"the balance must be initialized to the initial balance"26}2728// NOTE: The declaration contains no implementation code.29}3031// Require the implementing type to provide a function that is32// callable in all scopes, which withdraws an amount from33// this fungible token and returns the withdrawn amount as34// a new fungible token.35//36// The given amount must be positive and the function implementation37// 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 resource41// that implements the resource interface `FungibleToken`.42//43pub fun withdraw(amount: Int): @{FungibleToken} {44pre {45amount > 0:46"the amount must be positive"47amount <= self.balance:48"insufficient funds: the amount must be smaller or equal to the balance"49}50post {51self.balance == before(self.balance) - amount:52"the amount must be deducted from the balance"53}5455// NOTE: The declaration contains no implementation code.56}5758// Require the implementing type to provide a function that is59// callable in all scopes, which deposits a fungible token60// into this fungible token.61//62// No precondition is required to check the given token's balance63// is positive, as this condition is already ensured by64// the field requirement.65//66// The parameter type `{FungibleToken}` is the type of any resource67// that implements the resource interface `FungibleToken`.68//69pub fun deposit(_ token: @{FungibleToken}) {70post {71self.balance == before(self.balance) + token.balance:72"the amount must be added to the balance"73}7475// 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.
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 implement2// the `FungibleToken` interface.3//4// It has a variable field named `balance`, that can be written5// by functions of the type, but outer scopes can only read it.6//7pub resource ExampleToken: FungibleToken {89// 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//15pub var balance: Int1617// 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 interface23// does not have to be repeated here in the implementation.24//25init(balance: Int) {26self.balance = balance27}2829// Implement the required function named `withdraw` of the interface30// `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 declared37// in the interface have to be repeated here in the implementation.38//39pub fun withdraw(amount: Int): @ExampleToken {40self.balance = self.balance - amount41return create ExampleToken(balance: amount)42}4344// Implement the required function named `deposit` of the interface45// `FungibleToken`, that deposits the amount from the given token46// 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 tokens53// of the same type can be deposited.54//55// This implementation satisfies the required postconditions.56//57// NOTE: neither the precondition nor the postcondition declared58// in the interface have to be repeated here in the implementation.59//60pub fun deposit(_ token: @{FungibleToken}) {61if let exampleToken <- token as? ExampleToken {62self.balance = self.balance + exampleToken.balance63destroy exampleToken64} else {65panic("cannot deposit token which is not an example token")66}67}68}6970// Declare a constant which has type `ExampleToken`,71// and is initialized with such an example token.72//73let token <- create ExampleToken(balance: 100)7475// Withdraw 10 units from the token.76//77// The amount satisfies the precondition of the `withdraw` function78// 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//83let withdrawn <- token.withdraw(amount: 10)8485// 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`9091// Deposit the withdrawn token into another one.92let receiver: @ExampleToken <- // ...93receiver.deposit(<-withdrawn)9495// Run-time error: The precondition of function `withdraw` in interface96// `FungibleToken` fails, the program aborts: the parameter `amount`97// is larger than the field `balance` (100 > 90).98//99token.withdraw(amount: 100)100101// Withdrawing tokens so that the balance is zero does not destroy the resource.102// The resource has to be destroyed explicitly.103//104token.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).
1pub struct interface AnInterface {2// Require the implementing type to provide a publicly readable3// field named `a` that has type `Int`. It may be a variable4// or a constant field.5//6pub a: Int7}89pub 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 also13// allows the field to be written to in all scopes.14//15pub(set) var a: Int1617init(a: Int) {18self.a = a19}20}
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//6pub struct interface Shape {7pub fun getArea(): Int8pub fun scale(factor: Int)9}1011// Declare a structure named `Square` the implements the `Shape` interface.12//13pub struct Square: Shape {14// In addition to the required fields from the interface,15// the type can also declare additional fields.16//17pub var length: Int1819// Provided the field `area` which is required to conform20// 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//25pub fun getArea(): Int {26return self.length * self.length27}2829pub init(length: Int) {30self.length = length31}3233// Provided the implementation of the function `scale`34// which is required to conform to the interface `Shape`.35//36pub fun scale(factor: Int) {37self.length = self.length * factor38}39}4041// Declare a structure named `Rectangle` that also implements the `Shape` interface.42//43pub struct Rectangle: Shape {44pub var width: Int45pub var height: Int4647// Provided the field `area which is required to conform48// to the interface `Shape`.49//50pub fun getArea(): Int {51return self.width * self.height52}5354pub init(width: Int, height: Int) {55self.width = width56self.height = height57}5859// Provided the implementation of the function `scale`60// which is required to conform to the interface `Shape`.61//62pub fun scale(factor: Int) {63self.width = self.width * factor64self.height = self.height * factor65}66}6768// Declare a constant that has type `Shape`, which has a value that has type `Rectangle`.69//70var 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//3shape = Square(length: 30)45// Invalid: cannot initialize a constant that has type `Rectangle`.6// with a value that has type `Square`.7//8let 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//4let shape: {Shape} = Rectangle(width: 2, height: 3)56// Access the field `area` declared in the interface `Shape`.7//8shape.area // is `6`910// Call the function `scale` declared in the interface `Shape`.11//12shape.scale(factor: 3)1314shape.area // is `54`
🚧 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 declares2// a nested structure interface named `InnerInterface`.3//4// Resources implementing `OuterInterface` do not need to provide5// an implementation of `InnerInterface`.6//7// Structures may just implement `InnerInterface`.8//9resource interface OuterInterface {1011struct interface InnerInterface {}12}1314// Declare a resource named `SomeOuter` that implements the interface `OuterInterface`.15//16// The resource is not required to implement `OuterInterface.InnerInterface`.17//18resource SomeOuter: OuterInterface {}1920// Declare a structure named `SomeInner` that implements `InnerInterface`,21// which is nested in interface `OuterInterface`.22//23struct SomeInner: OuterInterface.InnerInterface {}
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//4struct interface Container {56let items: [AnyStruct]78fun getCount(): Int {9return self.items.length10}11}1213// 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//18struct Numbers: Container {19let items: [AnyStruct]2021init() {22self.items = []23}24}2526let numbers = Numbers()27numbers.getCount() // is 0
Interfaces cannot provide default initializers or default destructors.
Only one conformance may provide a default function.
🚧 Status: Currently only contracts and contract interfaces support nested type requirements.
Interfaces can require implementing types to provide concrete nested types. For example, a resource interface may require an implementing type to provide a resource type.
1// Declare a resource interface named `FungibleToken`.2//3// Require implementing types to provide a resource type named `Vault`4// which must have a field named `balance`.5//6resource interface FungibleToken {7pub resource Vault {8pub balance: Int9}10}11// Declare a resource named `ExampleToken` that implements the `FungibleToken` interface.12//13// The nested type `Vault` must be provided to conform to the interface.14//15resource ExampleToken: FungibleToken {16pub resource Vault {17pub var balance: Int18init(balance: Int) {19self.balance = balance20}21}22}