Best practices
#
Enable overflow checksIt's usually helpful to panic on integer overflow. To enable it, add the following into your Cargo.toml
file:
assert!
early#
Use Try to validate the input, context, state and access first before taking any actions. The earlier you panic, the more gas you will save for the caller.
Note: as of the SDK version 4.0.0-pre.2
, there is a more lightweight version of the Rust assert!
macro called require!
.
log!
#
Use Use logging for debugging and notifying user.
When you need a formatted message, you can use the following macro:
It's equivalent to the following message:
Promise
#
Return If your method makes a cross-contract call, you probably want to return the newly created Promise
.
This allows the caller (such as a near-cli or near-api-js call) to wait for the result of the promise instead of returning immediately.
Additionally, if the promise fails for some reason, returning it will let the caller know about the failure, as well as enabling NEAR Explorer and other tools to mark the whole transaction chain as failing.
This can prevent false-positives when the first or first few transactions in a chain succeed but a subsequent transaction fails.
E.g.
near-sdk
#
Reuse crates from near-sdk
re-exports the following crates:
borsh
base64
bs58
serde
serde_json
Most common crates include borsh
which is needed for internal STATE serialization and
serde
for external JSON serialization.
When marking structs with serde::Serialize
you need to use #[serde(crate = "near_sdk::serde")]
to point serde to the correct base crate.
std::panic!
vs env::panic
#
std::panic!
panics the current thread. It usesformat!
internally, so it can take arguments. SDK sets up a panic hook, which converts the generatedPanicInfo
frompanic!
into a string and usesenv::panic
internally to report it to Runtime. This may provide extra debugging information such as the line number of the source code where the panic happened.env::panic
directly calls the host method to panic the contract. It doesn't provide any other extra debugging information except for the passed message.
#
Use simulation testingNote: simulation testing is deprecated in favor of Sandbox testing.
Simulation testing allows you to run tests for multiple contracts and cross-contract calls in a simulated runtime environment. Read more, near-sdk-sim