Basic Service (C++)

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)

# Libraries for building services and tests
find_package(psibase REQUIRED)

# Build example.wasm service
add_executable(example example.cpp)
target_link_libraries(example Psibase::service)

psibase_package(
    NAME Example
    VERSION 1.0.0
    DESCRIPTION "An example service"
    SERVICE example
    TARGET example
)

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 example account, 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. -i is a shortcut for --create-insecure-account.
  • Deploy the example.wasm service 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

Code completion and symbol lookup in VSCode won't work until you add .vscode/c_cpp_properties.json and .vscode/settings.json to the root of your project. You can check the corresponding *.sample files at the root of the psibase repository for an example.