Cadence OOPs Mastery: Access Control

Access control

Access control allows making certain parts of the program accessible/visible and making other parts inaccessible/invisible.

In Flow and Cadence, there are two types of access control:

Access control on objects in account storage using capability security.

Within Flow, a caller is not able to access an object unless it owns the object or has a specific reference to that object. This means that nothing is truly public by default. Other accounts can not read or write the objects in an account unless the owner of the account has granted them access by providing references to the objects.

Access control within contracts and objects using pub and access keywords.

For the explanations of the following keywords, we assume that the defining type is either a contract, where capability security doesn't apply, or that the caller would have valid access to the object governed by capability security.

There are four levels of access control defined in the code that specify where a declaration can be accessed or called.

1. Public or access(all)

The declaration is accessible/visible in all scopes. This includes the current scope, inner scopes, and the outer scopes.

An element is made publicly accessible / by any code by using the pub or access(all) keywords.

2. access(account)

The declaration is only accessible/visible in the scope of the entire account where it is defined. This means that other contracts in the account are able to access it,

An element is made accessible by code in the same account (e.g. other contracts) by using the access(account) keyword.

3. access(contract)

The declaration is only accessible/visible in the scope of the contract that defined it. This means that other types and functions that are defined in the same contract can access it, but not other contracts in the same account.

An element is made accessible by code in the same contract by using the access(contract) keyword.

4. Private or access(self)

The declaration is only accessible/visible in the current and inner scopes.

An element is made accessible by code in the same containing type by using the access(self) keyword.

Summary is provided here

// Access modifier | Access scope

priv / access(self) Current and inner

access(account) Current, inner, and other contracts in same account

pub / access(all) All

access(contract) Current, inner, and containing contract

// Declare a private constant.

access(self) let a = 1