Skip to content

Commit

Permalink
Add Stable variable conversion info (#4541)
Browse files Browse the repository at this point in the history
  • Loading branch information
jessiemongeon1 authored May 17, 2024
1 parent e31f85b commit 0b43753
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions doc/md/canister-maintenance/upgrades.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,49 @@ In general, object types are not stable because they can contain local functions

:::

## Converting non-stable types into stable types

For variables that do not have a stable type, there are two options for making them stable:

1. Use a `stable` module for the type, such as:

- [StableBuffer](https://github.com/canscale/StableBuffer)
- [StableHashMap](https://github.com/canscale/StableHashMap)
- [StableRBTree](https://github.com/canscale/StableRBTree)

2. You can convert the variable to another type that is stable, such as the following example that converts a `Buffer` to an `Array`:

```motoko
let theProjectsBuffer : Buffer.Buffer = Buffer.Buffer(theProjectsNew.size());
for (x in theProjectsNew.vals()) {
theProjectsBuffer.add(x);
};
theProjectsBuffer.add(newProject);
return theProjectsBuffer.toArray();
```

Here is another example that takes a `HashMap` type and creates a stable `Array`:

```motoko
private var canisters: HashMap.HashMap<Principal, CanisterId> = HashMap.HashMap<Principal, CanisterId>(10, isPrincipalEqual, Principal.hash);
private stable var upgradeCanisters : [(Principal, CanisterId)] = [];
system func preupgrade() {
upgradeCanisters := Iter.toArray(canisters.entries());
};
system func postupgrade() {
canisters := HashMap.fromIter<Principal, CanisterId>(upgradeCanisters.vals(), 10, isPrincipalEqual, Principal.hash);
upgradeCanisters := [];
};
```

## Stable type signatures

The collection of stable variable declarations in an actor can be summarized in a stable signature.
Expand Down Expand Up @@ -139,6 +182,7 @@ You can check valid Candid subtyping between two services described in `.did` fi

:::


## Metadata sections

The Motoko compiler embeds the Candid interface and stable signature of a canister as canister metadata, recorded in additional Wasm custom sections of a compiled binary.
Expand Down

0 comments on commit 0b43753

Please sign in to comment.