Skip to content

Executing Methods

mero.rpc executes methods on the WASM application inside a context. It speaks JSON-RPC 2.0 to the node’s /jsonrpc endpoint and decodes the method’s return value straight into your @Serializable type with kotlinx.serialization.

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
@Serializable data class Post(val id: String, val title: String)
val post: Post = mero.rpc.execute(
contextId = "…",
method = "get_post",
argsJson = buildJsonObject { put("id", "42") },
)
  • contextId — the context to run in.
  • method — the contract method name.
  • argsJson — a JsonObject of named arguments (defaults to an empty object).
  • The return type is inferred from the call site; the reified overload of execute decodes result.output into it.

argsJson is a kotlinx.serialization JsonObject. Build it with buildJsonObject, nesting objects and arrays as needed:

import kotlinx.serialization.json.*
val args = buildJsonObject {
put("id", "42")
put("limit", 10)
put("verbose", true)
putJsonArray("tags") { add("a"); add("b") }
putJsonObject("filter") { put("author", "alice") }
}
val result: MyResult = mero.rpc.execute(
contextId = contextId, method = "search", argsJson = args
)

If you don’t need a typed result, use executeRaw and work with the JsonElement:

val raw = mero.rpc.executeRaw(contextId = contextId, method = "get_state")
val name = raw.jsonObject["name"]?.jsonPrimitive?.content

A JSON-RPC error from the contract throws RpcException:

import com.calimero.mero.rpc.RpcException
try {
val r: Receipt = mero.rpc.execute(
contextId = contextId, method = "transfer",
argsJson = buildJsonObject { put("to", to); put("amount", 10) },
)
} catch (e: RpcException) {
println("contract error ${e.code}: ${e.message}") // e.type, e.data also available
throw e
}

RpcException carries code, message, an optional type, and optional data (JsonElement?). Transport failures (HTTP 4xx/5xx, network) are HttpException / NetworkException, not RpcException — see the error model.

Two convenience wrappers over execute support the entry-migration flow used when an application upgrades its state schema:

val summary = mero.rpc.migrateMyEntries(contextId) // .converted, .remaining
val pending = mero.rpc.countMyPending(contextId) // Int