Errors Catching
If you want to abort your smart contract execution because of an error or some condition, inside a module or script you can use the following two constructs: abort and assert.
In case of an error, the VM will generate the error and add error code to the transaction output events.
For example, let's start with assert:
1
script {
2
fun error(a: u128, b: u128) {
3
assert(a > b, 101); // Throw error with code 101 if a is less than b.
4
}
5
}
Copied!
And same could be done with abort:
1
script {
2
fun error_1(a: u128, b: u128) {
3
if (a < b) {
4
abort 101 // Throw error with code 101 if a is less than b.
5
}
6
}
7
}
Copied!
You can also use abort and assert in your modules.
Let's compile one of the examples using Dove and execute using CLI (easiest way to see returned events):
1
polkadot-js-api tx.mvm.execute @<script> <file> --seed <seed> --ws <ws-endpoint>
Copied!
Replace values with your own, run execute transaction and see the output, a generated event:
1
"event": {
2
"method": "Event",
3
"section": "mvm",
4
"index": "0x0800",
5
"data": [
6
"5C4hrfjw9DjXZTzV3MwzrrAr9P1MJhSrvWGWqi1eSuyUpnhM",
7
"0x07000000000000000000000000000000000000000000000000000000000000000120564d53746174757320564d53746174757300",
8
"0x02016500000000000000",
9
null
10
]
11
}
Copied!
Where value 0x02016500000000000000 is indeed our error included in BCS, see Events tutorial for details.
Important: The way described above is not the best, but it is the only way to get custom errors from the Move VM in the Move pallet right now. We are working to make it better and more useful.
Last modified 1mo ago
Copy link