When developing on-chain scripts for CKB, numeric calculations are often required. Some developers prefer using fixed-point arithmetic due to its simplicity. To ensure consistent calculations between on-chain scripts and off-chain applications, we provide a solution based on WASM and Rust.
This solution consists of two parts:
- A Rust library (ckb-fixed) for on-chain scripts. It is based on fixed.
- WASM bindings of the same Rust library for off-chain applications, generated using
wasm-pack
This approach ensures identical numerical behavior across both environments.
Install required tools:
# Install wasm-pack for WASM bindings generation
cargo install wasm-pack --version 0.13.1
# Add WebAssembly target to Rust
rustup target add wasm32-unknown-unknown
Generate WASM bindings:
cd crates/ckb-fixed
make wasm-pack
The generated WASM bindings will be available in the pkg
directory. For usage instructions, refer to the wasm-pack documentation.
Add the dependency to your Cargo.toml
:
[dependencies]
ckb-fixed = "1.0.0"
For implementation examples, see our on-chain script example.
We've implemented fuzzing for the ckb-fixed crates. The fuzzer executes WASM bytecode using wasmer and compares the results with native Rust code execution.
Findings from fuzzing:
Basically, these are not bugs in the WASM implementation but rather in the native implementation.