Deploy overview
After you have built a canister, you can deploy it to:
- The local canister execution environment on your machine where no tokens or cycles are required
- The playground on the mainnet, a testnet-like sandbox environment. No tokens or cycles are required to deploy and run your canister smart contract, but it will be removed after 20 minutes.
- Mainnet for production use. This deployment method will require cycles.
This page will guide you through all 3 deployment methods.
This page details using the dfx deploy
command, which does several processes in the background, including:
Creating each canister listed in the
dfx.json
file.Compiling the code for each canister into a Wasm module.
Installing the Wasm module into each canister.
Deploying the canisters to the deployment endpoint of choice (local, playground, mainnet).
Testnets
Most blockchain networks have separate testnets that allow smart contract developers to test their projects in a production-like environment at significantly lower cost than on the mainnet. Because the execution of canisters is fairly cheap on ICP, and ICP smart contracts can be upgraded once deployed, there is no testnet for ICP. Developers are encouraged to test their canister smart contracts locally or directly on the mainnet.
However, the playground sandbox environment can be used as a testnet-like deployment option. It does not require cycles or tokens to deploy and operate a canister, but it has limitations, and canisters will be automatically removed after 20 minutes.
For the majority of developers, the playground option can be used for most workflows, as will be demonstrated below. For more advanced developers and use cases, there are two possible options for a testnet-like environment:
Private testnets: Developers can deploy their own custom instance of the playground on the mainnet, allowing for full customization of the playground's parameters.
Synthetic testnets: The
dfx
named network feature can be used to create custom local networks that can be used for local testing segmented from other projects deployed locally.
Deployment
Before you deploy your canister, open a new terminal and navigate to your project
directory. Verify the canisters you'd like to deploy are configured in the
project's dfx.json
file.
Need to create a project? Check out the Hello, world! sample project.
An example dfx.json
file can be found in the
default project template document.
Local deployment
Start the local canister execution environment:
dfx start
To deploy locally, use the command:
dfx deploy
Deploying to playground
To deploy to the playground, use the command:
dfx deploy --playground
Deploying to mainnet
To deploy to the mainnet, use the command:
dfx deploy --network ic
Deploying canisters to the mainnet will cost cycles. Learn more about cycles and how to acquire them.
Deploying specific canisters
The deploy
command deploys all canisters configured in your dfx.json
file.
To deploy just one canister, specify the canister's name:
dfx deploy hello_backend ## Deploy locally
dfx deploy hello_backend --playground ## Deploy to the playground
dfx deploy hello_backend --network ic ## Deploy to the mainnet
Use a custom Motoko version with dfx deploy
To use a custom Motoko version with dfx deploy
, export the following
environment variable that indicates which Motoko base version you'd like dfx
to use:
DFX_MOC_PATH="$(vessel bin)/moc" dfx deploy
Setting a canister's init arguments
You can set a canister's init arguments when the canister is deployed by passing
the --argument
flag in either the dfx install
or dfx deploy
commands:
dfx canister install <CANISTER_NAME> --argument "(arg in candid)"
dfx deploy <CANISTER_NAME> --argument "(arg in candid)"
If several arguments should be used, an argument file can be defined with the
--argument-file
flag instead:
dfx deploy <CANISTER_NAME> --argument-file file.txt
Alternatively, init arguments can be set in dfx.json
in dfx
versions
v0.17.0
and newer:
"canisters": {
"hello_backend": {
"candid": "src/hello_backend/hello_backend.did",
"package": "hello_backend",
"type": "rust",
"init_arg": "(arg in candid)"
},
}
If an init argument is set in dfx.json
and set with the CLI command, the
argument set in the CLI command is used.
Setting tasks to execute once a canister has been deployed
For certain workflows, it may be important to have a canister execute a task or call as soon as the canister is deployed or started. For this workflow, using timers can be useful.
Here is an example:
- Motoko
- Rust
- TypeScript
- Python
This example uses a global timer that gets called immediately after the canister starts:
import Time "mo:base/Time";
import Timer "mo:base/Timer";
import Nat64 "mo:base/Nat64";
actor {
system func timer(setGlobalTimer : Nat64 -> ()) : async () {
let next = Nat64.fromIntWrap(Time.now()) + 20_000_000_000;
setGlobalTimer(next); // absolute time in nanoseconds
print("Tick!");
}
}
You can learn more in the Motoko Timer library documentation.
This example creates a periodic timer that gets called immediately after the canister starts:
#[ic_cdk::init]
fn init(timer_interval_secs: u64) {
let interval = std::time::Duration::from_secs(timer_interval_secs);
ic_cdk::println!("Starting a periodic task with interval {interval:?}");
ic_cdk_timers::set_timer_interval(interval, || {
COUNTER.fetch_add(1, Ordering::Relaxed);
});
}
This example creates a timer function that must be manually called once a canister starts:
import {
call,
clearTimer,
IDL,
query,
setTimer,
setTimerInterval,
update
} from 'azle';
const StatusReport = IDL.Record({
single: IDL.Bool,
inline: IDL.Int8,
capture: IDL.Text,
repeat: IDL.Int8,
singleCrossCanister: IDL.Vec(IDL.Nat8),
repeatCrossCanister: IDL.Vec(IDL.Nat8)
});
type StatusReport = {
single: boolean;
inline: number;
capture: string;
repeat: number;
singleCrossCanister: Uint8Array;
repeatCrossCanister: Uint8Array;
};
const TimerIds = IDL.Record({
single: IDL.Nat64,
inline: IDL.Nat64,
capture: IDL.Nat64,
repeat: IDL.Nat64,
singleCrossCanister: IDL.Nat64,
repeatCrossCanister: IDL.Nat64
});
type TimerIds = {
single: bigint;
inline: bigint;
capture: bigint;
repeat: bigint;
singleCrossCanister: bigint;
repeatCrossCanister: bigint;
};
let statusReport: StatusReport = {
single: false,
inline: 0,
capture: '',
repeat: 0,
singleCrossCanister: Uint8Array.from([]),
repeatCrossCanister: Uint8Array.from([])
};
export default class {
@update([IDL.Nat64])
clearTimer(timerId: bigint): void {
clearTimer(timerId);
console.info(`timer ${timerId} cancelled`);
}
@update([IDL.Nat64, IDL.Nat64], TimerIds)
setTimers(delay: bigint, interval: bigint): TimerIds {
const capturedValue = '🚩';
const singleId = setTimer(delay, oneTimeTimerCallback);
const inlineId = setTimer(delay, () => {
statusReport.inline = 1;
console.info('Inline timer called');
});
const captureId = setTimer(delay, () => {
statusReport.capture = capturedValue;
console.info(`Timer captured value ${capturedValue}`);
});
const repeatId = setTimerInterval(interval, () => {
statusReport.repeat++;
console.info(`Repeating timer. Call ${statusReport.repeat}`);
});
const singleCrossCanisterId = setTimer(
delay,
singleCrossCanisterTimerCallback
);
const repeatCrossCanisterId = setTimerInterval(
interval,
repeatCrossCanisterTimerCallback
);
return {
single: singleId,
inline: inlineId,
capture: captureId,
repeat: repeatId,
singleCrossCanister: singleCrossCanisterId,
repeatCrossCanister: repeatCrossCanisterId
};
}
@query([], StatusReport)
statusReport(): StatusReport {
return statusReport;
}
}
function oneTimeTimerCallback(): void {
statusReport.single = true;
console.info('oneTimeTimerCallback called');
}
async function singleCrossCanisterTimerCallback(): Promise<void> {
console.info('singleCrossCanisterTimerCallback');
statusReport.singleCrossCanister = await getRandomness();
}
async function repeatCrossCanisterTimerCallback(): Promise<void> {
console.info('repeatCrossCanisterTimerCallback');
statusReport.repeatCrossCanister = Uint8Array.from([
...statusReport.repeatCrossCanister,
...(await getRandomness())
]);
}
async function getRandomness(): Promise<Uint8Array> {
return await call('aaaaa-aa', 'raw_rand', {
returnIdlType: IDL.Vec(IDL.Nat8)
});
}
This example creates a timer function that must be manually called once a canister starts:
from kybra import (
Duration,
ic,
TimerId,
update,
)
@update
def set_timer(delay: Duration) -> TimerId:
return ic.set_timer(delay, timer_callback)
def timer_callback():
ic.print("timer_callback")