extending functionality for kilogin

This commit is contained in:
sergeych committed 2024-09-15 12:28:40 +03:00
1 parent 6ce1b576ee
commit 93ab8ddf91
3 files changed
+39 -4

No files matched your search

@@ -5,6 +5,8 @@ import kotlinx.serialization.Serializable
import net.sergeych.bintools.toDataSource
import net.sergeych.bipack.BipackDecoder
import net.sergeych.bipack.BipackEncoder
import net.sergeych.kiloparsec.Command.Call
import net.sergeych.kiloparsec.Command.Companion.unpackCall
import net.sergeych.utools.unpack
/**
@@ -12,6 +14,18 @@ import net.sergeych.utools.unpack
* in node-2-node protocols and client API, and most importantly in calling smart contract
* methods. This is essentially a Kotlin binding to typesafe serialize command calls and
* deserialize results.
*
* To create command instances, it is recommended to use [command] that returns [CommandDelegate].
*
* Use [packCall] to serialize the command call with some arguments.
*
* Note that `Command` instances themselves are not serialized, instead, the call is serialized,
* in the form of [Call], containing name and properly serialized arguments.
*
* [unpackCall] deserialized result of the [packCall] so the proper handler for the command could
* be used. Then the result of the execution could be packed with [exec] and then unpacked with
* [unpackResult].
*
*/
class Command<A, R>(
val name: String,
@@ -21,13 +35,29 @@ class Command<A, R>(
@Serializable
data class Call(val name: String,val serializedArgs: UByteArray)
fun packCall(args: A): UByteArray = BipackEncoder.encode(
Call(name, BipackEncoder.encode(argsSerializer, args).toUByteArray())
).toUByteArray()
/**
* Pack command invocation with specified arguments.
*/
fun packCall(args: A): UByteArray = BipackEncoder.encode(createCall(args)).toUByteArray()
/**
* Create [Call] instance for specified args vy serializing it properly
*/
fun createCall(args: A): Call = Call(name, BipackEncoder.encode(argsSerializer, args).toUByteArray())
/**
* Unpack result, obtained by [exec].
*/
fun unpackResult(packedResult: UByteArray): R =
unpack(resultSerializer, packedResult)
/**
* Execute a command unpacking args.
*
* @param packedArgs arguments, as provided by [packCall] in the [Call] instance
* @param handler actual code to execute the command
* @return properly serialized result to be unpacked with [unpackResult].
*/
suspend fun exec(packedArgs: UByteArray, handler: suspend (A) -> R): UByteArray =
BipackEncoder.encode(
resultSerializer,
@@ -36,6 +66,10 @@ class Command<A, R>(
).toUByteArray()
companion object {
/**
* Unpack command invocation instance from [packCall]. Use [exec] to deserialize arguments and
* perform command.
*/
fun unpackCall(packedCall: UByteArray): Call = BipackDecoder.decode(packedCall.toDataSource())
}
}