Basic C++ Service
Here is a basic service definition. Place example.cpp and CMakeLists.txt in an empty folder.
example.cpp
#include <psibase/psibase.hpp>
// The service
struct ExampleService
{
// Add two numbers
int32_t add(int32_t a, int32_t b) { return a + b; }
// Multiply two numbers
int32_t multiply(int32_t a, int32_t b) { return a * b; }
};
// Reflect the service's methods. This enables
// PSIBASE_DISPATCH and other mechanisms to operate.
PSIO_REFLECT(ExampleService, //
method(add, a, b),
method(multiply, a, b))
// Allow users to invoke reflected methods inside transactions.
// Also allows other services to invoke these methods.
PSIBASE_DISPATCH(ExampleService)
CMakeLists.txt
# All cmake projects need these
cmake_minimum_required(VERSION 3.16)
project(example)
# Generate compile_commands.json to aid vscode and other editors
set(CMAKE_EXPORT_COMPILE_COMMANDS on)
# psidk requires C++20
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Libraries for building services and tests
find_package(psidk REQUIRED)
# Build example.wasm service
add_executable(example example.cpp)
target_link_libraries(example psibase-service-simple-malloc)
# These symlinks help vscode
execute_process(COMMAND ln -sfT ${psidk_DIR} ${CMAKE_CURRENT_BINARY_DIR}/psidk)
execute_process(COMMAND ln -sfT ${WASI_SDK_PREFIX} ${CMAKE_CURRENT_BINARY_DIR}/wasi-sdk)
Building
This will create example.wasm:
mkdir build
cd build
cmake `psidk-cmake-args` ..
make -j $(nproc)
Deploying the service
This, when run on a local test chain, will:
- Create the
exampleaccount, if it doesn't already exist. The account won't be secured; anyone can authorize as this account without signing. Caution: this option should not be used on production or public chains.-iis a shortcut for--create-insecure-account. - Deploy the
example.wasmservice on that service.
psibase deploy -i example example.wasm
Trying the service
Even though other services may call into our service's add and multiply methods,
we haven't provided end users with a way to construct transactions which use them.
That's the topic of the next section, Minimal User Interface.
Homework
There's a potentially-exploitable bug in add and multiply. What is it? Why is it
more dangerous in C++ than it is in psibase's other service languages? How can
you avoid it?
vscode support
The following files configure vscode:
Code completion and symbol lookup does not work until the project is built (above).