diff --git a/.gitignore b/.gitignore index 3892468..41fc5df 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ build/ cmake-build-debug/ -.idea \ No newline at end of file +.idea +/CMakeLists.txt.user +/CMakeSettings.json +.vs/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..a6e4ebf --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "include/rapidjson"] + path = include/rapidjson + url = https://github.com/Tencent/rapidjson.git + branch = version1.1.0 \ No newline at end of file diff --git a/CMakeGlobalFunctions.cmake b/CMakeGlobalFunctions.cmake index 1421a70..a83c792 100644 --- a/CMakeGlobalFunctions.cmake +++ b/CMakeGlobalFunctions.cmake @@ -1,22 +1,33 @@ +# Method to get GTest and link it from https://google.github.io/googletest/quickstart-cmake.html + +if (XPX_CHAIN_SDK_BUILD_TESTS) + include(FetchContent) + FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip + ) + # For Windows: Prevent overriding the parent project's compiler/linker settings + set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) + FetchContent_MakeAvailable(googletest) +endif() + function(add_single_test TARGET_NAME SOURCE_CPP) - find_package(GTest REQUIRED) - include_directories(SYSTEM ${GTEST_INCLUDE_DIR}) + enable_testing() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}" PARENT_SCOPE) # test libraries are in the form test.xyz, so add xyz as a dependency (the library under test) add_executable(${TARGET_NAME} ${SOURCE_CPP}) - add_test( - NAME ${TARGET_NAME} - WORKING_DIRECTORY ${CMAKE_BINARY_DIR} - COMMAND ${TARGET_NAME} - ) target_link_libraries(${TARGET_NAME} gtest gtest_main) target_link_libraries(${TARGET_NAME} xpxchaincpp - CONAN_PKG::rapidjson - CONAN_PKG::boost - CONAN_PKG::openssl) + ${Boost_LIBRARIES} + OpenSSL::SSL + OpenSSL::Crypto + pthread) + + include(GoogleTest) + gtest_discover_tests(${TARGET_NAME}) endfunction() \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index ccc6493..00824cb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,9 +1,21 @@ -cmake_minimum_required(VERSION 3.9) +cmake_minimum_required(VERSION 3.10) project(cpp-xpx-chain-sdk VERSION 1.0.0) -include(CMakeGlobalFunctions.cmake) -# CMP0068: fallback to older policies for macOS -cmake_policy(SET CMP0068 OLD) +if(POLICY CMP0074) + cmake_policy(SET CMP0074 NEW) +endif() + +if(POLICY CMP0144) + cmake_policy(SET CMP0144 NEW) +endif() + +if(POLICY CMP0167) + cmake_policy(SET CMP0167 NEW) +endif() + +if(POLICY CMP0048) + cmake_policy(SET CMP0048 NEW) +endif() #----------------------------------------------------------------------------- # options and features @@ -12,7 +24,34 @@ cmake_policy(SET CMP0068 OLD) option(XPX_CHAIN_SDK_BUILD_STATIC "Build static version of XPX-CHAIN SDK library." OFF) option(XPX_CHAIN_SDK_BUILD_TESTS "Build XPX-CHAIN SDK tests." OFF) option(XPX_CHAIN_SDK_BUILD_EXAMPLES "Build XPX-CHAIN SDK examples." OFF) -option(XPX_CHAIN_SDK_ENABLE_WEBSOCKETS "Enable WebSockets API." OFF) + +if (EMSCRIPTEN) + option(XPX_CHAIN_SDK_ENABLE_WEBSOCKETS "Enable WebSockets API." ON) +else() + option(XPX_CHAIN_SDK_ENABLE_WEBSOCKETS "Enable WebSockets API." OFF) +endif() + +include(CMakeGlobalFunctions.cmake) + +if (APPLE OR EMSCRIPTEN) + set(CMAKE_VERBOSE_MAKEFILE ON) + set(BOOST_INCLUDE_DIR "/usr/local/include") + set(BOOST_LIB_DIR "/usr/local/lib") + + if (EMSCRIPTEN) # set(OPENSSL_ROOT_DIR "/opt/local/opt/openssl") + set(OPENSSL_ROOT_DIR "/opt/homebrew/opt/openssl") + set(OPENSSL_INCLUDE_DIR "/opt/homebrew/opt/openssl/include") + set(OPENSSL_LIBRARIES "/opt/homebrew/opt/openssl/lib") + set(OPENSSL_SSL_LIBRARY "/opt/homebrew/opt/openssl/lib/libssl.dylib") + set(OPENSSL_CRYPTO_LIBRARY "/opt/homebrew/opt/openssl/lib/libcrypto.dylib") + else() + set(OPENSSL_ROOT_DIR "/usr/local/opt/openssl") + endif() +endif() + +find_package(Threads REQUIRED) +find_package(Boost 1.71.0 REQUIRED) +find_package(OpenSSL 1.1.1 REQUIRED) if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Release" CACHE STRING "XPX-CHAIN SDK build type." FORCE) @@ -20,10 +59,11 @@ if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) "Debug" "Release" "RelWithDebInfo" "MinSizeRel") endif() -if (MSVC) - add_compile_options(/W3) +if (WIN32) + add_definitions(-D_WIN32_WINNT=0x0601) else() - add_compile_options(-Wall) + add_compile_options(-w) + add_compile_options(-Wno-error=class-memaccess) endif() set(CMAKE_CXX_STANDARD 17) @@ -33,24 +73,19 @@ set(CMAKE_CXX_EXTENSIONS OFF) include(cmake/CheckFeatures.cmake) check_string_literal_operator_template(HAVE_STRING_LITERAL_OPERATOR_TEMPLATE) -#----------------------------------------------------------------------------- -# dependencies -#----------------------------------------------------------------------------- -if(NOT EXISTS "${CMAKE_BINARY_DIR}/conan.cmake") - message(STATUS "Downloading conan.cmake from https://github.com/conan-io/cmake-conan") - file(DOWNLOAD "https://github.com/conan-io/cmake-conan/raw/v0.14/conan.cmake" - "${CMAKE_BINARY_DIR}/conan.cmake") -endif() +# Fix rapidjson for gcc 14 +file(READ ${CMAKE_CURRENT_SOURCE_DIR}/include/rapidjson/include/rapidjson/document.h CONTENTS) +string(REPLACE "const SizeType length;" "SizeType length;" CONTENTS "${CONTENTS}") +file(WRITE ${CMAKE_CURRENT_SOURCE_DIR}/include/rapidjson/include/rapidjson/document.h "${CONTENTS}") -include(${CMAKE_BINARY_DIR}/conan.cmake) +# suppress errors & warnings from rapidjson +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated-declarations") -conan_cmake_run(REQUIRES - rapidjson/1.1.0@bincrafters/stable - boost/1.71.0 - openssl/1.1.1k - BASIC_SETUP - CMAKE_TARGETS - BUILD missing) +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread") +elseif (CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") +endif() #----------------------------------------------------------------------------- # sources @@ -106,21 +141,21 @@ source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" FILES ${sources}) #----------------------------------------------------------------------------- if (XPX_CHAIN_SDK_BUILD_STATIC) - add_library(xpxchaincpp STATIC "") - set_target_properties(xpxchaincpp PROPERTIES - OUTPUT_NAME "xpxchaincpp-static") + add_library(xpxchaincpp STATIC "") + set_target_properties(xpxchaincpp PROPERTIES + OUTPUT_NAME "xpxchaincpp-static") else() - add_library(xpxchaincpp SHARED "") + add_library(xpxchaincpp SHARED "") - set_target_properties(xpxchaincpp PROPERTIES - VERSION ${PROJECT_VERSION} - SOVERSION ${PROJECT_VERSION_MAJOR}) + set_target_properties(xpxchaincpp PROPERTIES + VERSION ${PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR}) - if (MSVC) - set_target_properties(xpxchaincpp PROPERTIES - WINDOWS_EXPORT_ALL_SYMBOLS ON) - endif() + if (MSVC) + set_target_properties(xpxchaincpp PROPERTIES + WINDOWS_EXPORT_ALL_SYMBOLS ON) + endif() endif() include(GNUInstallDirs) @@ -135,16 +170,35 @@ target_include_directories(xpxchaincpp $ $ PRIVATE + include/rapidjson/include/ ${CMAKE_CURRENT_SOURCE_DIR}/src) if(XPX_CHAIN_SDK_ENABLE_WEBSOCKETS) target_compile_definitions(xpxchaincpp PRIVATE XPX_CHAIN_SDK_ENABLE_WEBSOCKETS) endif() -target_link_libraries(xpxchaincpp - CONAN_PKG::rapidjson - CONAN_PKG::boost - CONAN_PKG::openssl) +if(APPLE) + include_directories(${BOOST_INCLUDE_DIR}) + include_directories(${OPENSSL_INCLUDE_DIR}) + target_include_directories(xpxchaincpp PUBLIC ${Boost_INCLUDE_DIRS}) +else() + include_directories(${Boost_INCLUDE_DIR}) +endif() + +if (WIN32) + target_link_libraries(xpxchaincpp + ${Boost_LIBRARIES} + OpenSSL::SSL + OpenSSL::Crypto + wsock32 + ws2_32) +else() + target_link_libraries(xpxchaincpp + ${Boost_LIBRARIES} + OpenSSL::SSL + OpenSSL::Crypto + pthread) +endif() #----------------------------------------------------------------------------- # install @@ -192,16 +246,67 @@ install(FILES # tests #----------------------------------------------------------------------------- -if (XPX_CHAIN_SDK_BUILD_TESTS) - enable_testing() - add_subdirectory(tests) -endif() +if (APPLE OR EMSCRIPTEN) +else() -if (XPX_CHAIN_SDK_BUILD_EXAMPLES) - add_executable(get_block ${CMAKE_CURRENT_SOURCE_DIR}/examples/get_block.cpp) - target_link_libraries(get_block - xpxchaincpp - CONAN_PKG::rapidjson - CONAN_PKG::boost - CONAN_PKG::openssl) + if (XPX_CHAIN_SDK_BUILD_TESTS) + enable_testing() + add_subdirectory(tests) + endif() + + if (XPX_CHAIN_SDK_BUILD_EXAMPLES) + add_executable(get_block ${CMAKE_CURRENT_SOURCE_DIR}/examples/get_block.cpp) + if (WIN32) + target_link_libraries(get_block + xpxchaincpp + ${Boost_LIBRARIES} + OpenSSL::SSL + OpenSSL::Crypto + wsock32 + ws2_32) + else() + target_link_libraries(get_block + xpxchaincpp + ${Boost_LIBRARIES} + OpenSSL::SSL + OpenSSL::Crypto + pthread) + endif() + + add_executable(bonded_aggregate_transaction ${CMAKE_CURRENT_SOURCE_DIR}/examples/bonded_aggregate_transaction.cpp) + if (WIN32) + target_link_libraries(bonded_aggregate_transaction + xpxchaincpp + ${Boost_LIBRARIES} + OpenSSL::SSL + OpenSSL::Crypto + wsock32 + ws2_32) + else() + target_link_libraries(bonded_aggregate_transaction + xpxchaincpp + ${Boost_LIBRARIES} + OpenSSL::SSL + OpenSSL::Crypto + pthread) + endif() + + add_executable(liquidity_provider_transactions ${CMAKE_CURRENT_SOURCE_DIR}/examples/liquidity_provider_transactions.cpp) + if (WIN32) + target_link_libraries(liquidity_provider_transactions + xpxchaincpp + ${Boost_LIBRARIES} + OpenSSL::SSL + OpenSSL::Crypto + wsock32 + ws2_32) + else() + target_link_libraries(liquidity_provider_transactions + xpxchaincpp + ${Boost_LIBRARIES} + OpenSSL::SSL + OpenSSL::Crypto + pthread) + endif() + endif() endif() diff --git a/README.md b/README.md index 51cdca1..a681452 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,8 @@ Official ProximaX Sirius Blockchain SDK Library in C++. ## Prerequisites ## * C++ compliler with C++17 support -* CMake 3.8 or higher -* [Conan](https://conan.io) +* CMake 3.9 or higher +* Boost 1.71.0 or higher ## Common notes ## @@ -19,7 +19,13 @@ Following variables can be used to control build process: * XPX_CHAIN_SDK_BUILD_EXAMPLES - set to ON if you want to build the example programs (default - OFF) * other well-known CMake variables (CMAKE_INSTALL_PREFIX, CMAKE_BUILD_TYPE, etc.) -## Building ## +## Update submodules + +```shell +git submodule update --init --recursive +``` + +## Building on Linux ## Prepare build with following instructions: @@ -36,12 +42,28 @@ make -j 4 make install ``` -### Building with Visual Studio ### +## Building on Windows ## + +### Install CMake ### +Download and install the latest CMake from https://cmake.org/download/ using the Windows x64 Installer. +Make sure to select the option to add CMake bin directory to PATH in system variables. + +### Install Conan ### +Download and install Conan from https://conan.io/downloads.html +Add C:\Program Files\Conan\conan to PATH in system variables. + +### Install MinGW-W64 ### +If you do not have MinGW-W64 installed, download the 12.1.0 MSVCRT runtime version from here https://winlibs.com/ +Extract the zip file to your C: drive, then add C:\mingw64\bin to PATH in system variables. + +### Build ### +Run cmd as an administrator and go to the root directory of cpp-xpx-chain-sdk, then do the following: -You can open _cpp-xpx-chain-sdk.sln_ file with VS and build from its GUI or use Microsoft Build Engine: ``` -msbuild.exe /p:Configuration=Release ALL_BUILD.vcxproj -msbuild.exe INSTALL.vcxproj +mkdir build +cd build +cmake -G "MinGW Makefiles" .. +mingw32-make -j 6 ``` ## Usage ## diff --git a/examples/bonded_aggregate_transaction.cpp b/examples/bonded_aggregate_transaction.cpp new file mode 100644 index 0000000..77922e1 --- /dev/null +++ b/examples/bonded_aggregate_transaction.cpp @@ -0,0 +1,139 @@ +/** +*** Copyright 2019 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#include + +#include +#include +#include + +using namespace xpx_chain_sdk; + +std::shared_ptr CreateAccount(const std::string& privateKeyHex) { + return std::make_shared([privateKeyHex](xpx_chain_sdk::PrivateKeySupplierReason reason, xpx_chain_sdk::PrivateKeySupplierParam param) { + xpx_chain_sdk::Key key; + ParseHexStringIntoContainer(privateKeyHex.c_str(), privateKeyHex.size(), key); + + if (PrivateKeySupplierReason::Aggregate_Transaction_Cosigning == reason) { + PrivateKey privateKey = xpx_chain_sdk::PrivateKey(key.data(), key.size()); + const KeyPair keyPair(std::move(privateKey)); + auto transaction = const_cast(std::get(param)); + if (transaction) { + std::cout << "Aggregate_Transaction_Cosigning hash: " << ToHex(transaction->hash()) << std::endl; + SignTransaction(transaction, keyPair); + } + } + + + return xpx_chain_sdk::PrivateKey(key.data(), key.size()); + }); +} + +int main () { + xpx_chain_sdk::Config config = xpx_chain_sdk::GetConfig(); + config.nodeAddress = "127.0.0.1"; + config.port = "3000"; + + std::string accountAddress = "SDHDCKRVH4NXSKIRX3M7PLPMP6F4O3Z3JUWKJHLB"; + std::string publicKey = "E92978122F00698856910664C480E8F3C2FDF0A733F42970FBD58A5145BD6F21"; + std::string privateKey = "7AA907C3D80B3815BE4B4E1470DEEE8BB83BFEB330B9A82197603D09BA947230"; + + auto client = xpx_chain_sdk::getClient(config); + auto sponsorAccount = CreateAccount(privateKey); + + Key senderKey; + ParseHexStringIntoContainer(publicKey.c_str(), publicKey.size(), senderKey); + Address sender(senderKey); + + Key recipientKey; + std::string recipientKeyHex = "A384FBAAADBFF0405DDA0212D8A6C85F9164A08C24AFD15425927BCB274A45D4"; + ParseHexStringIntoContainer(recipientKeyHex.c_str(), recipientKeyHex.size(), recipientKey); + Address recipient(recipientKey); + + // xpx id + MosaicId xpx = 992621222383397347; + Mosaic mosaic(xpx, 100); + MosaicContainer mosaics{ mosaic }; + RawBuffer firstMessage("first transaction"); + + Key signer; + ParseHexStringIntoContainer(publicKey.c_str(), publicKey.size(), signer); + + std::unique_ptr firstTransferTransaction = CreateEmbeddedTransferTransaction(recipient, mosaics, firstMessage, signer); + + RawBuffer secondMessage("second transaction"); + std::unique_ptr secondTransferTransaction = CreateEmbeddedTransferTransaction(recipient, mosaics, secondMessage, signer); + + EmbeddedTransactions embeddedTransactions; + embeddedTransactions.push_back(std::move(firstTransferTransaction)); + embeddedTransactions.push_back(std::move(secondTransferTransaction)); + + auto aggregateBondedTransaction = CreateBondedAggregateTransaction(embeddedTransactions, {}); + sponsorAccount->signTransaction(aggregateBondedTransaction.get()); + + auto lockFundsTransaction = CreateLockFundsTransaction(Mosaic(xpx, 10000000), 240, aggregateBondedTransaction->hash()); + sponsorAccount->signTransaction(lockFundsTransaction.get()); + + std::cout << "lockHash: " << ToHex(lockFundsTransaction->lockHash()) << std::endl; + std::cout << "main lock has: " << ToHex(lockFundsTransaction->hash()) << std::endl; + + Notifier statusNotifier([sponsorAccount](const notifierId& id, const xpx_chain_sdk::TransactionStatusNotification& notification) { + std::cout << "transaction status notification is received : " << notification.status.c_str() << " : " << notification.hash.c_str() << std::endl; + }); + + Notifier confirmedAddedNotifier([sponsorAccount, + client, + lockFundHash = ToHex(lockFundsTransaction->hash()), + binaryDataAggregate = aggregateBondedTransaction->binary(), + aggregateHash = ToHex(aggregateBondedTransaction->hash())](const notifierId& id, const xpx_chain_sdk::TransactionNotification& notification) { + if (notification.meta.hash == lockFundHash) { + std::cout << "confirmed lock fund transaction: " << lockFundHash << std::endl; + + client->transactions()->announceAggregateBoundedTransaction(binaryDataAggregate); + std::cout << "announced new aggregateBoundedTransaction: " << aggregateHash << std::endl; + } else if (notification.meta.hash == aggregateHash) { + std::cout << "confirmed aggregate bonded transaction: " << aggregateHash << std::endl; + client->notifications()->removeConfirmedAddedNotifiers(sponsorAccount->address(), [](){}, [](auto){}, {id}); + } else { + std::cout << "other confirmed transaction hash: " << notification.meta.hash << std::endl; + } + }); + + Notifier> parialAddedNotifier([sponsorAccount, client, hash = ToHex(aggregateBondedTransaction->hash())](const notifierId& id, std::shared_ptr notification) { + std::cout << "confirmed parialAddedNotifier: " << GetTransactionName(notification->type) << std::endl; + }); + + auto announceTransaction = [client, + binaryDataLockFund = lockFundsTransaction->binary(), + lockFundHash = ToHex(lockFundsTransaction->hash()), + binaryDataAggregate = aggregateBondedTransaction->binary(), + aggregateHash = ToHex(aggregateBondedTransaction->hash())](){ + try { + //client->transactions()->announceNewTransaction(binaryDataLockFund); + client->transactions()->announceAggregateBoundedTransaction(binaryDataAggregate); + std::cout << "announced new aggregateBoundedTransaction: " << aggregateHash << std::endl; + //std::cout << "announced new lockFundsTransaction: " << lockFundHash << std::endl; + } catch (const xpx_chain_sdk::InvalidRequest& e) { + std::cout << e.getErrorMessage().message << std::endl; + std::cout << e.getErrorMessage().code << std::endl; + } + }; + + auto onError = [](auto errorCode) { + std::cout << "error code: " << errorCode << std::endl; + }; + + client->notifications()->addStatusNotifiers(sender, { statusNotifier }, [client, sender, confirmedAddedNotifier, parialAddedNotifier, announceTransaction, onError](){ + client->notifications()->addConfirmedAddedNotifiers(sender, { confirmedAddedNotifier }, [client, sender, parialAddedNotifier, announceTransaction, onError](){ + client->notifications()->addPartialAddedNotifiers(sender, { parialAddedNotifier }, announceTransaction, onError); + }, onError); + }, onError); + + char a; + int ret = std::scanf("%c\n", &a); + (void) ret; // ignore + + return 0; +} \ No newline at end of file diff --git a/examples/get_block.cpp b/examples/get_block.cpp index bdd296f..7d6cf0b 100644 --- a/examples/get_block.cpp +++ b/examples/get_block.cpp @@ -8,57 +8,52 @@ #include #include #include +#include +#include using namespace xpx_chain_sdk; int main() { xpx_chain_sdk::Config config = xpx_chain_sdk::GetConfig(); - config.nodeAddress = "bcstage1.xpxsirius.io"; - config.nodeAddress = "0.0.0.0"; + config.nodeAddress = "127.0.0.1"; config.port = "3000"; - std::string accountAddress = "VA7PKVZYTGLHZUCZTIM6TCJZIW2KB2PYCMKVTF27"; - std::string publicKey = "E0C0BDFD0CFBC83D5DDC5F16CAD9CF18FE4339649946A79AC334AB5AA39D4BB7"; - std::string privateKey = "28FCECEA252231D2C86E1BCF7DD541552BDBBEFBB09324758B3AC199B4AA7B78"; + std::string accountAddress = "SDHDCKRVH4NXSKIRX3M7PLPMP6F4O3Z3JUWKJHLB"; + std::string publicKey = "E92978122F00698856910664C480E8F3C2FDF0A733F42970FBD58A5145BD6F21"; + std::string privateKey = "7AA907C3D80B3815BE4B4E1470DEEE8BB83BFEB330B9A82197603D09BA947230"; - accountAddress = "SBGS2IGUED476REYI5ZZGISVSEHAF6YIQZV6YJFQ"; - publicKey = "0EB448D07C7CCB312989AC27AA052738FF589E2F83973F909B506B450DC5C4E2"; + auto client = xpx_chain_sdk::getClient(config); - - - - auto client = xpx_chain_sdk::getClient(std::make_shared(config)); - - auto score = client->blockchain()->getCurrentScore(); - std::cout << "Chain score: " << score.scoreHigh << ' ' << score.scoreLow << std::endl; - - auto storage = client->blockchain()->getStorageInfo(); - std::cout << "Storage Info | Num Transactions: " << storage.numTransactions << std::endl; - std::cout << "Storage Info | Num Blocks : " << storage.numBlocks << std::endl; - - auto height = client->blockchain()->getBlockchainHeight(); - std::cout << "Block number: " << height << std::endl; - - auto block = client->blockchain()->getBlockByHeight(height); - std::cout << "Block signature: " << block.data.signature << std::endl; - - auto blocks = client->blockchain()->getBlocksByHeightWithLimit(height - 1, 25).blocks; - for (auto& block: blocks) { - std::cout << "Block signature: " << block.data.signature << std::endl; - } - - std::cout << "Generation Hash: " << ' ' << client -> blockchain() -> getBlockByHeight(1).meta.generationHash << std::endl; - - auto networkInfo = client -> network() -> getNetworkInfo(); - std::cout << "Network Info " << networkInfo.description << '|' << networkInfo.name << std::endl; - - auto accountInfo = client -> account() -> getAccountInfo(accountAddress); - std::cout << accountInfo.publicKey << ' ' << accountInfo.mosaics[0].id << std::endl; - - auto mosaicId = accountInfo.mosaics[0].id; - std::cout << mosaicId << std::endl; - auto mosaicInfo = client -> mosaics() -> getMosaicInfo(mosaicId); +// auto score = client->blockchain()->getCurrentScore(); +// std::cout << "Chain score: " << score.scoreHigh << ' ' << score.scoreLow << std::endl; +// +// auto storage = client->blockchain()->getStorageInfo(); +// std::cout << "Storage Info | Num Transactions: " << storage.numTransactions << std::endl; +// std::cout << "Storage Info | Num Blocks : " << storage.numBlocks << std::endl; +// +// auto height = client->blockchain()->getBlockchainHeight(); +// std::cout << "Block number: " << height << std::endl; // - std::cout << "Mosaic Info: " << mosaicInfo.data.amount << std::endl; +// auto block = client->blockchain()->getBlockByHeight(height); +// std::cout << "Block signature: " << block.data.signature << std::endl; +// +// auto blocks = client->blockchain()->getBlocksByHeightWithLimit(height - 1, 25).blocks; +// for (auto& block: blocks) { +// std::cout << "Block signature: " << block.data.signature << std::endl; +// } +// +// std::cout << "Generation Hash: " << ' ' << client -> blockchain() -> getBlockByHeight(1).meta.generationHash << std::endl; +// +// auto networkInfo = client -> network() -> getNetworkInfo(); +// std::cout << "Network Info " << networkInfo.description << '|' << networkInfo.name << std::endl; +// +// auto accountInfo = client -> account() -> getAccountInfo(accountAddress); +// std::cout << accountInfo.publicKey << ' ' << accountInfo.mosaics[0].id << std::endl; +// +// auto mosaicId = accountInfo.mosaics[0].id; +// std::cout << mosaicId << std::endl; +// auto mosaicInfo = client -> mosaics() -> getMosaicInfo(mosaicId); +//// +// std::cout << "Mosaic Info: " << mosaicInfo.data.amount << std::endl; // std::vector ids = {accountInfo.mosaics[0].id}; // @@ -84,34 +79,48 @@ int main() { // } // std::cout << std::endl; - xpx_chain_sdk::MosaicPropertyContainer propertyContainer; + auto replicatorOnboardingTransaction = xpx_chain_sdk::CreateReplicatorOnboardingTransaction(2048); + + xpx_chain_sdk::Account account([privateKeyString = privateKey](PrivateKeySupplierReason reason, PrivateKeySupplierParam param) { + Key key; + if(reason == PrivateKeySupplierReason::Transaction_Signing) { + ParseHexStringIntoContainer(privateKeyString.c_str(), privateKeyString.size(), key); + } + + return PrivateKey(key.data(), key.size()); + }, replicatorOnboardingTransaction -> networkId()); - propertyContainer.insert(xpx_chain_sdk::MosaicProperty{xpx_chain_sdk::MosaicPropertyId::Divisibility, 6}); - propertyContainer.insert(xpx_chain_sdk::MosaicProperty{xpx_chain_sdk::MosaicPropertyId::Flags, 4}); + account.signTransaction(replicatorOnboardingTransaction.get()); - xpx_chain_sdk::MosaicProperties mosaicProperties(propertyContainer); + auto hash = ToHex(replicatorOnboardingTransaction->hash()); - auto mosaicDefinitionTransaction = xpx_chain_sdk::CreateMosaicDefinitionTransaction( - 5, - Mosaic::GenerateId(ParseByteArray(publicKey), 5), - MosaicFlags::Supply_Mutable, mosaicProperties); + Notifier notifier([hash](const notifierId& id, const xpx_chain_sdk::TransactionNotification& notification) { + if (notification.meta.hash == hash) { + std::cout << "confirmed replicatorOnboardingTransaction: " << hash << std::endl; - xpx_chain_sdk::Account account([privateKeyString = privateKey](PrivateKeySupplierReason reason, PrivateKeySupplierParam param) { - if(reason == PrivateKeySupplierReason::Transaction_Signing) { - Key key; - ParseHexStringIntoContainer(privateKeyString.c_str(), privateKeyString.size(), key); + exit(0); + } else { + std::cout << "other confirmed transaction hash: " << notification.meta.hash << std::endl; + } + }); - return PrivateKey(key.data(), key.size()); - } - }, mosaicDefinitionTransaction -> networkId()); + client->notifications()->addConfirmedAddedNotifiers(account.address(), {notifier}, [](){}, [](boost::beast::error_code errorCode){}); - account.signTransaction(mosaicDefinitionTransaction.get()); + Notifier statusNotifier([](const notifierId& id, const xpx_chain_sdk::TransactionStatusNotification& notification) { + std::cout << "transaction status notification is received : " << notification.status.c_str() << " : " << notification.hash.c_str() << std::endl; + }); + client->notifications()->addStatusNotifiers(account.address(), {statusNotifier}, [](){}, [](boost::beast::error_code errorCode){}); try { - client -> transactions() -> announceNewTransaction(mosaicDefinitionTransaction->binary()); + client -> transactions() -> announceNewTransaction(replicatorOnboardingTransaction->binary()); } catch(std::exception& e) { std::cout << e.what() << std::endl; } + + char a; + int ret = std::scanf("%c\n", &a); + (void) ret; // ignore + return 0; } \ No newline at end of file diff --git a/examples/liquidity_provider_transactions.cpp b/examples/liquidity_provider_transactions.cpp new file mode 100644 index 0000000..e3a745c --- /dev/null +++ b/examples/liquidity_provider_transactions.cpp @@ -0,0 +1,210 @@ +/** +*** Copyright 2019 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#include + +#include +#include +#include +#include + +using namespace xpx_chain_sdk; + + +std::shared_ptr CreateAccount(const std::string& privateKey) { + return std::make_shared([privateKey](xpx_chain_sdk::PrivateKeySupplierReason reason, xpx_chain_sdk::PrivateKeySupplierParam param) { + xpx_chain_sdk::Key key; + ParseHexStringIntoContainer(privateKey.c_str(), privateKey.size(), key); + return xpx_chain_sdk::PrivateKey(key.data(), key.size()); + }); +} + +void sendTransferTransactionAsync(std::shared_ptr client, + std::shared_ptr sponsorAccount, + const MosaicContainer& mosaics, + const std::string& receiverPublicKey, + std::function onSuccess, + std::function onError) { + std::string message = "message"; + xpx_chain_sdk::Key key; + ParseHexStringIntoContainer(receiverPublicKey.c_str(), receiverPublicKey.size(), key); + auto transferTransaction = xpx_chain_sdk::CreateTransferTransaction(xpx_chain_sdk::Address(key), mosaics, {message.data(), message.size()}); + + sponsorAccount->signTransaction(transferTransaction.get()); + + auto transferHash = ToHex(transferTransaction->hash()); + std::cout << "transferHash: " << transferHash << std::endl; + + Notifier transferConfirmedAddedNotifier([sponsorAccount, client, transferHash, onSuccess]( + const notifierId& id, const xpx_chain_sdk::TransactionNotification& notification) { + if (notification.meta.hash == transferHash) { + std::cout << "confirmed transfer transaction hash: " << transferHash << std::endl; + + client->notifications()->removeConfirmedAddedNotifiers(sponsorAccount->address(), [](){}, [](auto){}, {id}); + onSuccess(); + } else { + std::cout << "other confirmed transaction hash: " << notification.meta.hash << std::endl; + } + }); + + Notifier transferStatusNotifier([sponsorAccount, transferHash, onError](const notifierId& id, const xpx_chain_sdk::TransactionStatusNotification& notification) { + if (transferHash == notification.hash) { + std::cout << "transfer transaction status notification is received : " << notification.status.c_str() << " : " << notification.hash.c_str() << std::endl; + onError("ERROR. other confirmed transaction hash"); + } else { + std::cout << "WARNING. transfer transaction status notification is received : " << notification.status.c_str() << " : " << notification.hash.c_str() << std::endl; + } + }); + + client->notifications()->addStatusNotifiers(sponsorAccount->address(), { transferStatusNotifier }, [](){}, [](auto ){}); + + auto announceTransferTransaction = [client, transferHash, binaryData = transferTransaction->binary(), onError](){ + try { + client->transactions()->announceNewTransaction(binaryData); + + std::cout << "announced new transfer transaction: " << transferHash << std::endl; + } catch (std::exception &e) { + std::cout << e.what() << std::endl; + onError(e.what()); + } + }; + + client->notifications()->addConfirmedAddedNotifiers(sponsorAccount->address(), { transferConfirmedAddedNotifier }, announceTransferTransaction, [](auto ){}); +} + +int main() { + xpx_chain_sdk::Config config = xpx_chain_sdk::GetConfig(); + config.nodeAddress = "127.0.0.1"; + config.port = "3000"; + + std::string accountAddress = "SDBSUK35HH4DHLLNOLZ66LCAIJ43I5BYSUAVBNSX"; + std::string publicKey = "E8D4B7BEB2A531ECA8CC7FD93F79A4C828C24BE33F99CF7C5609FF5CE14605F4"; + std::string privateKey = "2F985E4EC55D60C957C973BD1BEE2C0B3BA313A841D3EE4C74810805E6936053"; + + auto client = xpx_chain_sdk::getClient(config); + + std::string slashingAccountPublicKey = "E92978122F00698856910664C480E8F3C2FDF0A733F42970FBD58A5145BD6F21"; + std::string slashingAccountPrivateKey = "7AA907C3D80B3815BE4B4E1470DEEE8BB83BFEB330B9A82197603D09BA947230"; + + xpx_chain_sdk::MosaicId mosaicId = 2761073989369673764; // storage units + Amount currencyDeposit = 100000; + Amount initialMosaicsMinting = 100000; + uint32_t slashingPeriod = 1; + uint16_t windowSize = 10; + Key slashingAccount; + + ParseHexStringIntoContainer(slashingAccountPublicKey.c_str(), slashingAccountPublicKey.size(), slashingAccount); + + uint32_t alpha = 500; + uint32_t beta = 500; + + auto createLiquidityProviderTransaction = xpx_chain_sdk::CreateCreateLiquidityProviderTransaction( + mosaicId, currencyDeposit, initialMosaicsMinting, slashingPeriod, windowSize, slashingAccount, alpha, beta); + + auto account = CreateAccount(privateKey); + account->signTransaction(createLiquidityProviderTransaction.get()); + + auto hash = ToHex(createLiquidityProviderTransaction->hash()); + std::cout << "transaction hash: " << hash << std::endl; + + const bool currencyBalanceIncrease = true; + const Amount currencyBalanceChange = 100005; + const bool mosaicBalanceIncrease = true; + const Amount mosaicBalanceChange = 1370; + + auto manualRateChangeTransaction = xpx_chain_sdk::CreateManualRateChangeTransaction( + mosaicId, currencyBalanceIncrease, currencyBalanceChange, mosaicBalanceIncrease, mosaicBalanceChange); + + account->signTransaction(manualRateChangeTransaction.get()); + + auto manualRateChangeTransactionHash = ToHex(manualRateChangeTransaction->hash()); + std::cout << "manualRateChangeTransactionHash : " << manualRateChangeTransactionHash << std::endl; + + auto createManualRateChangeTransaction = [client, account, manualRateChangeTransactionHash, binaryData = manualRateChangeTransaction->binary()](){ + Notifier confirmedAddedNotifier([account, client, manualRateChangeTransactionHash]( + const notifierId& id, const xpx_chain_sdk::TransactionNotification& notification) { + if (notification.meta.hash == manualRateChangeTransactionHash) { + std::cout << "confirmed manualRateChangeTransaction hash: " << manualRateChangeTransactionHash << std::endl; + + client->notifications()->removeConfirmedAddedNotifiers(account->address(), [](){}, [](auto){}, {id}); + } else { + std::cout << "other confirmed transaction hash: " << notification.meta.hash << std::endl; + } + }); + + Notifier statusNotifier([account](const notifierId& id, const xpx_chain_sdk::TransactionStatusNotification& notification) { + std::cout << "manualRateChangeTransaction status notification is received : " << notification.status.c_str() << " : " << notification.hash.c_str() << std::endl; + }); + + client->notifications()->addStatusNotifiers(account->address(), { statusNotifier }, [](){}, [](auto ){}); + + auto announceTransaction = [client, manualRateChangeTransactionHash, binaryData](){ + try { + client->transactions()->announceNewTransaction(binaryData); + + std::cout << "announced new manualRateChangeTransaction: " << manualRateChangeTransactionHash << std::endl; + } catch (std::exception &e) { + std::cout << e.what() << std::endl; + } + }; + + client->notifications()->addConfirmedAddedNotifiers(account->address(), { confirmedAddedNotifier }, announceTransaction, [](auto ){}); + }; + + std::atomic isFinished = false; + + auto createLpTransaction = [client, account, &hash, &isFinished, binaryData = createLiquidityProviderTransaction->binary()] () { + Notifier confirmedAddedNotifier([account, client, hash, &isFinished](const notifierId& id, const xpx_chain_sdk::TransactionNotification& notification) { + if (notification.meta.hash == hash) { + std::cout << "confirmed transaction hash: " << hash << std::endl; + + client->notifications()->removeConfirmedAddedNotifiers(account->address(), [](){}, [](auto){}, {id}); + isFinished = true; + } else { + std::cout << "other confirmed transaction hash: " << notification.meta.hash << std::endl; + } + }); + + Notifier statusNotifier([account, &isFinished](const notifierId& id, const xpx_chain_sdk::TransactionStatusNotification& notification) { + std::cout << "transaction status notification is received : " << notification.status.c_str() << " : " << notification.hash.c_str() << std::endl; + isFinished = true; + }); + + client->notifications()->addStatusNotifiers(account->address(), { statusNotifier }, [](){}, [](auto ){}); + + auto announceTransaction = [client, hash, binaryData](){ + try { + client->transactions()->announceNewTransaction(binaryData); + + std::cout << "announced new transaction: " << hash << std::endl; + } catch (std::exception &e) { + std::cout << e.what() << std::endl; + } + }; + + client->notifications()->addConfirmedAddedNotifiers(account->address(), { confirmedAddedNotifier }, announceTransaction, [](auto ){}); + }; + + auto sponsorAccount = CreateAccount("7AA907C3D80B3815BE4B4E1470DEEE8BB83BFEB330B9A82197603D09BA947230"); + // xpx id + MosaicId xpx = 992621222383397347; + Mosaic mosaic(xpx, 1000000); + MosaicContainer mosaics{ mosaic }; + + //createLpTransaction(); + //createManualRateChangeTransaction(); + + sendTransferTransactionAsync(client, sponsorAccount, mosaics, publicKey, createLpTransaction, [](const std::string& errorText){ + std::cout << "error: " << errorText << std::endl; + }); + + + + while (!isFinished) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + + return 0; +} \ No newline at end of file diff --git a/include/rapidjson b/include/rapidjson new file mode 160000 index 0000000..2fb78f9 --- /dev/null +++ b/include/rapidjson @@ -0,0 +1 @@ +Subproject commit 2fb78f9cee01996f020d5af7592b37c5a0693b31 diff --git a/include/xpxchaincpp/client.h b/include/xpxchaincpp/client.h index 9c4014e..1921336 100644 --- a/include/xpxchaincpp/client.h +++ b/include/xpxchaincpp/client.h @@ -11,8 +11,10 @@ #include #include #include +#include #include #include +#include #include @@ -20,12 +22,26 @@ #include namespace xpx_chain_sdk { + class ErrorMessage { + public: + std::string code; + std::string message; + }; + class InvalidRequest : public std::runtime_error { public: - explicit InvalidRequest(uint16_t code); + explicit InvalidRequest(const std::string& errorMessage, uint16_t code); + + public: + int getHttpErrorCode() const; + ErrorMessage getErrorMessage() const; private: static std::string getErrorMessage(uint16_t code); + + private: + const int httpErrorCode; + const std::string errorMessage; }; class InvalidJson : public std::runtime_error { @@ -35,15 +51,18 @@ namespace xpx_chain_sdk { class IClient { public: + virtual const Config& getConfig() const = 0; virtual std::shared_ptr account() const = 0; virtual std::shared_ptr blockchain() const = 0; virtual std::shared_ptr mosaics() const = 0; virtual std::shared_ptr namespaces() const = 0; virtual std::shared_ptr notifications() const = 0; virtual std::shared_ptr network() const = 0; + virtual std::shared_ptr liquidityProvider() const = 0; virtual std::shared_ptr transactions() const = 0; + virtual std::shared_ptr storage() const = 0; virtual ~IClient() = default; }; - std::shared_ptr getClient(std::shared_ptr config); + std::shared_ptr getClient(const Config& config); } diff --git a/include/xpxchaincpp/client/account_service.h b/include/xpxchaincpp/client/account_service.h index 96fc9ed..405d75f 100644 --- a/include/xpxchaincpp/client/account_service.h +++ b/include/xpxchaincpp/client/account_service.h @@ -27,7 +27,7 @@ namespace xpx_chain_sdk { class AccountService { public: AccountService( - std::shared_ptr config, + const Config& config, std::shared_ptr context); ~AccountService() = default; @@ -40,7 +40,7 @@ namespace xpx_chain_sdk { AccountNames getAccountNames(const std::vector& addresses); private: - std::shared_ptr _config; + const Config& _config; std::shared_ptr _context; }; } diff --git a/include/xpxchaincpp/client/blockchain_service.h b/include/xpxchaincpp/client/blockchain_service.h index 56ebdfa..4fecd88 100644 --- a/include/xpxchaincpp/client/blockchain_service.h +++ b/include/xpxchaincpp/client/blockchain_service.h @@ -7,7 +7,6 @@ #pragma once #include -#include #include #include #include @@ -29,7 +28,7 @@ namespace xpx_chain_sdk { class BlockchainService { public: BlockchainService( - std::shared_ptr config, + const Config& config, std::shared_ptr context); ~BlockchainService() = default; @@ -41,7 +40,7 @@ namespace xpx_chain_sdk { private: - std::shared_ptr _config; + const Config& _config; std::shared_ptr _context; }; diff --git a/include/xpxchaincpp/client/liquidity_provider_service.h b/include/xpxchaincpp/client/liquidity_provider_service.h new file mode 100644 index 0000000..bc6e635 --- /dev/null +++ b/include/xpxchaincpp/client/liquidity_provider_service.h @@ -0,0 +1,38 @@ +/* +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +*/ + +#pragma once + +#include +#include +#include + + +namespace xpx_chain_sdk::internal::network { + class Context; + class RequestParamsBuilder; +} + +namespace xpx_chain_sdk { + + using internal::network::Context; + using internal::network::RequestParamsBuilder; + + class LiquidityProviderService { + public: + LiquidityProviderService( + const Config& config, + std::shared_ptr context); + ~LiquidityProviderService() = default; + + LiquidityProvider getLiquidityProviderByKey(const std::string& key); + liquidity_providers_page::LiquidityProvidersPage getLiquidityProviders(); + + private: + const Config& _config; + std::shared_ptr _context; + }; +} diff --git a/include/xpxchaincpp/client/mosaic_service.h b/include/xpxchaincpp/client/mosaic_service.h index 32de489..056db9f 100644 --- a/include/xpxchaincpp/client/mosaic_service.h +++ b/include/xpxchaincpp/client/mosaic_service.h @@ -27,7 +27,7 @@ namespace xpx_chain_sdk { class MosaicService { public: MosaicService( - std::shared_ptr config, + const Config& config, std::shared_ptr context); ~MosaicService() = default; @@ -36,7 +36,7 @@ namespace xpx_chain_sdk { MosaicNames getMosaicsNames(const std::vector& ids); private: - std::shared_ptr _config; + const Config& _config; std::shared_ptr _context; }; }; diff --git a/include/xpxchaincpp/client/namespace_service.h b/include/xpxchaincpp/client/namespace_service.h index bc0c90a..5426dd2 100644 --- a/include/xpxchaincpp/client/namespace_service.h +++ b/include/xpxchaincpp/client/namespace_service.h @@ -29,7 +29,7 @@ namespace xpx_chain_sdk { class NamespaceService { public: NamespaceService( - std::shared_ptr config, + const Config& config, std::shared_ptr context); ~NamespaceService() = default; @@ -40,7 +40,7 @@ namespace xpx_chain_sdk { NamespaceNames getNamespaceNames(const std::vector & namespaceIds); private: - std::shared_ptr _config; + const Config& _config; std::shared_ptr _context; }; } diff --git a/include/xpxchaincpp/client/network_service.h b/include/xpxchaincpp/client/network_service.h index 92b38da..d607972 100644 --- a/include/xpxchaincpp/client/network_service.h +++ b/include/xpxchaincpp/client/network_service.h @@ -25,7 +25,7 @@ namespace xpx_chain_sdk { class NetworkService { public: NetworkService( - std::shared_ptr config, + const Config& config, std::shared_ptr context); ~NetworkService() = default; @@ -36,7 +36,7 @@ namespace xpx_chain_sdk { NetworkVersion getNetworkVersionAtHeight(uint64_t height); private: - std::shared_ptr _config; + const Config& _config; std::shared_ptr _context; }; } diff --git a/include/xpxchaincpp/client/notification_service.h b/include/xpxchaincpp/client/notification_service.h index b9a8b0f..7e6990e 100644 --- a/include/xpxchaincpp/client/notification_service.h +++ b/include/xpxchaincpp/client/notification_service.h @@ -6,20 +6,16 @@ #pragma once #include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include #include #include #include #include -#include -#include +#include +#include +#include +#include namespace xpx_chain_sdk::internal::network { class Context; @@ -33,75 +29,101 @@ namespace xpx_chain_sdk::internal { namespace xpx_chain_sdk { using internal::network::Context; - using BlockNotifier = std::function; - using ConfirmedAddedNotifier = std::function; - using UnconfirmedAddedNotifier = std::function; - using UnconfirmedRemovedNotifier = std::function; - using PartialAddedNotifier = std::function transaction)>; - using PartialRemovedNotifier = std::function; - using StatusNotifier = std::function; - using CosignatureNotifier = std::function; - using DriveStateNotifier = std::function; + using notifierId = std::string; class NotificationService : public std::enable_shared_from_this { public: - NotificationService( - std::shared_ptr config, - std::shared_ptr context); + NotificationService(const Config& config); ~NotificationService(); - void addBlockNotifiers(const std::initializer_list& notifiers); - void removeBlockNotifiers(); + void addBlockNotifiers(const std::vector>& notifiers, + std::function onSuccess, std::function onError); - void addConfirmedAddedNotifiers(const Address& address, const std::initializer_list& notifiers); - void removeConfirmedAddedNotifiers(const Address& address); + void removeBlockNotifiers(std::function onSuccess, std::function onError, + const std::vector& notifierIds = {}); - void addUnconfirmedAddedNotifiers(const Address& address, const std::initializer_list& notifiers); - void removeUnconfirmedAddedNotifiers(const Address& address); + void addConfirmedAddedNotifiers(const Address& address, const std::vector>& notifiers, + std::function onSuccess, std::function onError); - void addUnconfirmedRemovedNotifiers(const Address& address, const std::initializer_list& notifiers); - void removeUnconfirmedRemovedNotifiers(const Address& address); + void removeConfirmedAddedNotifiers(const Address& address, std::function onSuccess, std::function onError, + const std::vector& notifierIds = {}); - void addPartialAddedNotifiers(const Address& address, const std::initializer_list& notifiers); - void removePartialAddedNotifiers(const Address& address); + void addUnconfirmedAddedNotifiers(const Address& address, const std::vector>& notifiers, + std::function onSuccess, std::function onError); - void addPartialRemovedNotifiers(const Address& address, const std::initializer_list& notifiers); - void removePartialRemovedNotifiers(const Address& address); + void removeUnconfirmedAddedNotifiers(const Address& address, std::function onSuccess, std::function onError, + const std::vector& notifierIds = {}); - void addStatusNotifiers(const Address& address, const std::initializer_list& notifiers); - void removeStatusNotifiers(const Address& address); + void addUnconfirmedRemovedNotifiers(const Address& address, const std::vector>& notifiers, + std::function onSuccess, std::function onError); - void addCosignatureNotifiers(const Address& address, const std::initializer_list& notifiers); - void removeCosignatureNotifiers(const Address& address); + void removeUnconfirmedRemovedNotifiers(const Address& address, std::function onSuccess, std::function onError, + const std::vector& notifierIds = {}); - void addDriveStateNotifiers(const Address& address, const std::initializer_list& notifiers); - void removeDriveStateNotifiers(const Address& address); + void addPartialAddedNotifiers(const Address& address, const std::vector>>& notifiers, + std::function onSuccess, std::function onError); + + void removePartialAddedNotifiers(const Address& address, std::function onSuccess, std::function onError, + const std::vector& notifierIds = {}); + + void addPartialRemovedNotifiers(const Address& address, const std::vector>& notifiers, + std::function onSuccess, std::function onError); + + void removePartialRemovedNotifiers(const Address& address, std::function onSuccess, std::function onError, + const std::vector& notifierIds = {}); + + void addStatusNotifiers(const Address& address, const std::vector>& notifiers, + std::function onSuccess, std::function onError); + + void removeStatusNotifiers(const Address& address, std::function onSuccess, std::function onError, + const std::vector& notifierIds = {}); + + void addCosignatureNotifiers(const Address& address, const std::vector>& notifiers, + std::function onSuccess, std::function onError); + + void removeCosignatureNotifiers(const Address& address, std::function onSuccess, std::function onError, + const std::vector& notifierIds = {}); + + void addDriveStateNotifiers(const Address& address, const std::vector>& notifiers, + std::function onSuccess, std::function onError); + + void removeDriveStateNotifiers(const Address& address, std::function onSuccess, std::function onError, + const std::vector& notifierIds = {}); + + void connect(std::function callback); private: - void addMutexIfNotExist(const std::string& mutexKey); - void initialize(std::function initializeCallback); + void run(); + void runTask(std::function); void notificationsHandler(const std::string& json); - void finalize(); + void stop(); + + template + void addNotifiers(const Address&, const std::string&, InternalContainer&, const ExternalContainer&, + std::function onSuccess, std::function onError); + + template + void removeNotifiers(const Address&, const std::string&, InternalContainer&, const ExternalContainer&, + std::function onSuccess, std::function onError); private: - std::shared_ptr _config; - std::shared_ptr _context; + const Config& _config; std::shared_ptr _wsClient; std::shared_ptr _subscriptionManager; - std::map> _notifiersMutexes; - std::vector _blockNotifiers; - std::map> _confirmedAddedNotifiers; - std::map> _unconfirmedAddedNotifiers; - std::map> _unconfirmedRemovedNotifiers; - std::map> _partialAddedNotifiers; - std::map> _partialRemovedNotifiers; - std::map> _statusNotifiers; - std::map> _cosignatureNotifiers; - std::map> _driveStateNotifiers; - std::mutex _commonMutex; - std::mutex _initializeMutex; - std::condition_variable _initializeCheck; + std::shared_ptr _io_context; + std::deque> _tasks; + std::thread _mainWorker; + std::map> _blockNotifiers; + std::map>> _confirmedAddedNotifiers; + std::map>> _unconfirmedAddedNotifiers; + std::map>> _unconfirmedRemovedNotifiers; + std::map>>> _partialAddedNotifiers; + std::map>> _partialRemovedNotifiers; + std::map>> _statusNotifiers; + std::map>> _cosignatureNotifiers; + std::map>> _driveStateNotifiers; + std::function _connectionCallback; std::string _uid; - bool _isInitialized; + bool _isConnectionInProgress; }; } \ No newline at end of file diff --git a/include/xpxchaincpp/client/storage_service.h b/include/xpxchaincpp/client/storage_service.h new file mode 100644 index 0000000..c754246 --- /dev/null +++ b/include/xpxchaincpp/client/storage_service.h @@ -0,0 +1,47 @@ +/* +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +*/ + +#pragma once + +#include +#include +#include +#include +#include "xpxchaincpp/model/storage/download_channels_page_options.h" +#include "xpxchaincpp/model/storage/replicators_page_options.h" +#include "xpxchaincpp/model/storage/drives_page_options.h" +#include + + +namespace xpx_chain_sdk::internal::network { + class Context; + class RequestParamsBuilder; +} + +namespace xpx_chain_sdk { + + using internal::network::Context; + using internal::network::RequestParamsBuilder; + + class StorageService { + public: + StorageService( + const Config& config, + std::shared_ptr context); + ~StorageService() = default; + + Drive getDriveById(const std::string& id); + drives_page::DrivesPage getDrives(const DrivesPageOptions& options); + Replicator getReplicatorById(const std::string& id); + replicators_page::ReplicatorsPage getReplicators(const ReplicatorsPageOptions& options); + DownloadChannel getDownloadChannelById(const std::string& id); + download_channels_page::DownloadChannelsPage getDownloadChannels(const DownloadChannelsPageOptions& options); + + private: + const Config& _config; + std::shared_ptr _context; + }; +} diff --git a/include/xpxchaincpp/client/supercontract_v2_service.h b/include/xpxchaincpp/client/supercontract_v2_service.h new file mode 100644 index 0000000..bb6f5c8 --- /dev/null +++ b/include/xpxchaincpp/client/supercontract_v2_service.h @@ -0,0 +1,38 @@ +/* +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +*/ + +#pragma once + +#include +#include +#include +#include + +namespace xpx_chain_sdk::internal::network { + class Context; + class RequestParamsBuilder; +} + +namespace xpx_chain_sdk { + + using internal::network::Context; + using internal::network::RequestParamsBuilder; + + class SuperContractV2Service { + public: + SuperContractV2Service( + const Config& config, + std::shared_ptr context); + + ~SuperContractV2Service() = default; + + SuperContractV2 getSuperContractByKey(const std::string& contractKey); + + private: + const Config& _config; + std::shared_ptr _context; + }; +}; diff --git a/include/xpxchaincpp/client/transaction_service.h b/include/xpxchaincpp/client/transaction_service.h index 503f33c..4994d83 100644 --- a/include/xpxchaincpp/client/transaction_service.h +++ b/include/xpxchaincpp/client/transaction_service.h @@ -25,7 +25,7 @@ namespace xpx_chain_sdk { class TransactionService { public: TransactionService( - std::shared_ptr config, + const Config& config, std::shared_ptr context); ~TransactionService() = default; @@ -43,7 +43,7 @@ namespace xpx_chain_sdk { static TransactionGroup transactionGroupFromString(const std::string& group) ; private: - std::shared_ptr _config; + const Config& _config; std::shared_ptr _context; }; } diff --git a/include/xpxchaincpp/config.h b/include/xpxchaincpp/config.h index 0cded06..2a50aa1 100644 --- a/include/xpxchaincpp/config.h +++ b/include/xpxchaincpp/config.h @@ -14,7 +14,7 @@ namespace xpx_chain_sdk { constexpr NetworkIdentifier Network_Id = NetworkIdentifier::Mijin_Test; - constexpr std::chrono::system_clock::time_point Network_Epoch(std::chrono::milliseconds(1459468800ll * 1000)); + constexpr std::chrono::system_clock::time_point Network_Epoch(std::chrono::milliseconds(1459468800000)); constexpr uint32_t Block_Avg_Fee_Multiplier = 20; @@ -59,6 +59,16 @@ namespace xpx_chain_sdk { bool useSSL = false; std::string basePath = "/"; std::string baseWsPath = "/ws"; + + struct WebsocketOptions + { + uint64_t resolveHostTimeoutSecSec = 60; + std::chrono::seconds handshakeTimeoutSec = std::chrono::seconds(60); + std::chrono::seconds idleTimeoutSec = std::chrono::seconds(600); + bool keepAlivePings = true; + }; + + WebsocketOptions wsOptions; }; /// Returns SDK config. diff --git a/include/xpxchaincpp/model/liquidity_provider/liquidity_provider.h b/include/xpxchaincpp/model/liquidity_provider/liquidity_provider.h new file mode 100644 index 0000000..9ad1472 --- /dev/null +++ b/include/xpxchaincpp/model/liquidity_provider/liquidity_provider.h @@ -0,0 +1,49 @@ +/** +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include + +namespace xpx_chain_sdk { + + class RateData { + public: + uint64_t currencyAmount; + uint64_t mosaicAmount; + }; + + class TurnoverData { + public: + RateData rate; + uint64_t turnover; + }; + + class LiquidityProviderData { + public: + uint64_t mosaicId; + std::string providerKey; + std::string owner; + uint64_t additionallyMinted; + std::string slashingAccount; + uint32_t slashingPeriod; + uint16_t windowSize; + uint64_t creationHeight; + uint32_t alpha; + uint32_t beta; + TurnoverData recentTurnover; + std::vector turnoverHistory; + }; + + class LiquidityProvider { + public: + LiquidityProviderData data; + }; + + class MultipleLiquidityProviders { + public: + std::vector liquidityProviders; + }; +} \ No newline at end of file diff --git a/include/xpxchaincpp/model/liquidity_provider/liquidity_providers_page.h b/include/xpxchaincpp/model/liquidity_provider/liquidity_providers_page.h new file mode 100644 index 0000000..bd7ccd8 --- /dev/null +++ b/include/xpxchaincpp/model/liquidity_provider/liquidity_providers_page.h @@ -0,0 +1,27 @@ +/** +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include "liquidity_provider.h" + +namespace xpx_chain_sdk::liquidity_providers_page { + + class Pagination { + public: + uint64_t totalEntries; + uint64_t pageNumber; + uint64_t pageSize; + uint64_t totalPages; + }; + + class LiquidityProvidersPage { + public: + MultipleLiquidityProviders data; + Pagination pagination; + }; +} \ No newline at end of file diff --git a/include/xpxchaincpp/model/mosaic/mosaic_property.h b/include/xpxchaincpp/model/mosaic/mosaic_property.h index cc24692..fa5060c 100644 --- a/include/xpxchaincpp/model/mosaic/mosaic_property.h +++ b/include/xpxchaincpp/model/mosaic/mosaic_property.h @@ -30,8 +30,7 @@ namespace xpx_chain_sdk { None = 0x00, Supply_Mutable = 0x01, Transferable = 0x02, - Levy_Mutable = 0x04, - All = 0x07 + All = 0x03 }; XPX_CHAIN_SDK_BITWISE_ENUM(MosaicFlags); diff --git a/include/xpxchaincpp/model/notification/notifier.h b/include/xpxchaincpp/model/notification/notifier.h new file mode 100644 index 0000000..402b7c2 --- /dev/null +++ b/include/xpxchaincpp/model/notification/notifier.h @@ -0,0 +1,63 @@ +/** +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace xpx_chain_sdk { + + template + class Notifier { + public: + Notifier() : + uuid(generateUuid()), + notifier() {} + + Notifier(std::function n) : + uuid(generateUuid()), + notifier(n) {} + + ~Notifier() = default; + + public: + std::string getId() const { + return uuid; + } + + void run(const NotificationType& notification) const { + if (!notifier) { + XPX_CHAIN_SDK_THROW_1(notification_error, "Notifier is not set:", getId()); + } + + notifier(uuid, notification); + } + + void set(std::function n) { + notifier = n; + } + + private: + static std::string generateUuid() { + boost::uuids::uuid id = boost::uuids::random_generator()(); + return boost::uuids::to_string(id); + } + + private: + std::string uuid; + std::function notifier; + }; +} diff --git a/include/xpxchaincpp/model/notification/transaction_notification.h b/include/xpxchaincpp/model/notification/transaction_notification.h index 1b81de1..b6cf77b 100644 --- a/include/xpxchaincpp/model/notification/transaction_notification.h +++ b/include/xpxchaincpp/model/notification/transaction_notification.h @@ -18,7 +18,6 @@ namespace xpx_chain_sdk { TransactionType type; int64_t maxFee; int64_t deadline; - std::string hash; }; class TransactionMeta { diff --git a/include/xpxchaincpp/model/storage/download_channel.h b/include/xpxchaincpp/model/storage/download_channel.h new file mode 100644 index 0000000..d0f1e00 --- /dev/null +++ b/include/xpxchaincpp/model/storage/download_channel.h @@ -0,0 +1,40 @@ +/** +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include + +namespace xpx_chain_sdk { + + class CumulativePayment { + public: + std::string replicator; + uint64_t payment; + }; + + class DownloadChannelData { + public: + std::string id; + std::string consumer; + std::string drive; + uint64_t downloadSizeMegabytes; + uint16_t downloadApprovalCount; + bool finished; + std::vector listOfPublicKeys; + std::vector shardReplicators; + std::vector cumulativePayments; + }; + + class DownloadChannel { + public: + DownloadChannelData data; + }; + + class MultipleDownloadChannels { + public: + std::vector channels; + }; +} \ No newline at end of file diff --git a/include/xpxchaincpp/model/storage/download_channels_page.h b/include/xpxchaincpp/model/storage/download_channels_page.h new file mode 100644 index 0000000..edec72d --- /dev/null +++ b/include/xpxchaincpp/model/storage/download_channels_page.h @@ -0,0 +1,27 @@ +/** +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include "download_channel.h" + +namespace xpx_chain_sdk::download_channels_page { + + class Pagination { + public: + uint64_t totalEntries; + uint64_t pageNumber; + uint64_t pageSize; + uint64_t totalPages; + }; + + class DownloadChannelsPage { + public: + MultipleDownloadChannels data; + Pagination pagination; + }; +} \ No newline at end of file diff --git a/include/xpxchaincpp/model/storage/download_channels_page_options.h b/include/xpxchaincpp/model/storage/download_channels_page_options.h new file mode 100644 index 0000000..6158eb9 --- /dev/null +++ b/include/xpxchaincpp/model/storage/download_channels_page_options.h @@ -0,0 +1,66 @@ +/** +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include +#include +#include "xpxchaincpp/utils/paginationOrderingOptions.h" + +namespace xpx_chain_sdk { + + class DownloadChannelsPageOptions { + public: + std::map toMap() const { + std::map options; + if (downloadSize.has_value()) { + options.insert(std::pair("downloadSize",std::to_string(downloadSize.value()))); + } + + if (fromDownloadSize.has_value()) { + options.insert(std::pair("fromDownloadSize",std::to_string(fromDownloadSize.value()))); + } + + if (toDownloadSize.has_value()) { + options.insert(std::pair("toDownloadSize",std::to_string(toDownloadSize.value()))); + } + + if (downloadApprovalCount.has_value()) { + options.insert(std::pair("downloadApprovalCount",std::to_string(downloadApprovalCount.value()))); + } + + if (fromDownloadApprovalCount.has_value()) { + options.insert(std::pair("fromDownloadApprovalCount",std::to_string(fromDownloadApprovalCount.value()))); + } + + if (toDownloadApprovalCount.has_value()) { + options.insert(std::pair("toDownloadApprovalCount",std::to_string(toDownloadApprovalCount.value()))); + } + + if (consumerKey.has_value()) { + options.insert(std::pair("consumerKey",consumerKey.value())); + } + + if (paginationOrderingOptions.has_value()) { + auto poOptions = paginationOrderingOptions.value().toMap(); + options.insert(poOptions.begin(), poOptions.end()); + } + + return options; + } + + public: + std::optional downloadSize; + std::optional fromDownloadSize; + std::optional toDownloadSize; + std::optional downloadApprovalCount; + std::optional fromDownloadApprovalCount; + std::optional toDownloadApprovalCount; + std::optional consumerKey; + std::optional paginationOrderingOptions; + }; +} \ No newline at end of file diff --git a/include/xpxchaincpp/model/storage/drive.h b/include/xpxchaincpp/model/storage/drive.h new file mode 100644 index 0000000..5fafebd --- /dev/null +++ b/include/xpxchaincpp/model/storage/drive.h @@ -0,0 +1,104 @@ +/** +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include + +namespace xpx_chain_sdk { + + class DataModification { + public: + std::string id; + std::string owner; + std::string downloadDataCdi; + uint64_t expectedUploadSize; + uint64_t actualUploadSize; + std::string folderName; + bool readyForApproval; + bool isStream; + }; + + class ActiveDataModification { + public: + DataModification dataModification; + }; + + class CompletedDataModification { + public: + DataModification dataModification; + uint8_t state; + uint8_t success; + }; + + class ConfirmedUsedSize { + public: + std::string replicator; + uint64_t size; + }; + + class Shard { + public: + uint32_t id; + std::vector replicators; + }; + + class Verification { + public: + std::string verificationTrigger; + uint64_t expiration; + uint32_t duration; + std::vector shards; + }; + + class DownloadShard { + public: + std::string downloadChannelId; + }; + + class UploadInfo { + public: + std::string key; + uint64_t uploadSize; + }; + + class DataModificationShard { + public: + std::string replicator; + std::vector actualShardReplicators; + std::vector formerShardReplicators; + uint64_t ownerUpload; + }; + + class DriveData { + public: + std::string multisig; + std::string multisigAddress; + std::string owner; + std::string rootHash; + uint64_t size; + uint64_t usedSizeBytes; + uint64_t metaFilesSizeBytes; + uint16_t replicatorCount; + std::vector activeDataModifications; + std::vector completedDataModifications; + std::vector confirmedUsedSizes; + std::vector replicators; + std::vector offboardingReplicators; + Verification verification; + std::vector downloadShards; + std::vector dataModificationShards; + }; + + class Drive { + public: + DriveData data; + }; + + class MultipleDrives { + public: + std::vector drives; + }; +} \ No newline at end of file diff --git a/include/xpxchaincpp/model/storage/drives_page.h b/include/xpxchaincpp/model/storage/drives_page.h new file mode 100644 index 0000000..23d79b5 --- /dev/null +++ b/include/xpxchaincpp/model/storage/drives_page.h @@ -0,0 +1,27 @@ +/** +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include "drive.h" + +namespace xpx_chain_sdk::drives_page { + + class Pagination { + public: + uint64_t totalEntries; + uint64_t pageNumber; + uint64_t pageSize; + uint64_t totalPages; + }; + + class DrivesPage { + public: + MultipleDrives data; + Pagination pagination; + }; +} \ No newline at end of file diff --git a/include/xpxchaincpp/model/storage/drives_page_options.h b/include/xpxchaincpp/model/storage/drives_page_options.h new file mode 100644 index 0000000..1c3f727 --- /dev/null +++ b/include/xpxchaincpp/model/storage/drives_page_options.h @@ -0,0 +1,96 @@ +/** +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include +#include +#include "xpxchaincpp/utils/paginationOrderingOptions.h" + +namespace xpx_chain_sdk { + + class DrivesPageOptions { + public: + std::map toMap() const { + std::map options; + if (size.has_value()) { + options.insert(std::pair("size",std::to_string(size.value()))); + } + + if (fromSize.has_value()) { + options.insert(std::pair("fromSize",std::to_string(fromSize.value()))); + } + + if (toSize.has_value()) { + options.insert(std::pair("toSize",std::to_string(toSize.value()))); + } + + if (usedSize.has_value()) { + options.insert(std::pair("usedSize",std::to_string(usedSize.value()))); + } + + if (fromUsedSize.has_value()) { + options.insert(std::pair("fromUsedSize",std::to_string(fromUsedSize.value()))); + } + + if (toUsedSize.has_value()) { + options.insert(std::pair("toUsedSize",std::to_string(toUsedSize.value()))); + } + + if (metaFilesSize.has_value()) { + options.insert(std::pair("metaFilesSize",std::to_string(metaFilesSize.value()))); + } + + if (fromMetaFilesSize.has_value()) { + options.insert(std::pair("fromMetaFilesSize",std::to_string(fromMetaFilesSize.value()))); + } + + if (toMetaFilesSize.has_value()) { + options.insert(std::pair("toMetaFilesSize",std::to_string(toMetaFilesSize.value()))); + } + + if (replicatorCount.has_value()) { + options.insert(std::pair("replicatorCount",std::to_string(replicatorCount.value()))); + } + + if (fromReplicatorCount.has_value()) { + options.insert(std::pair("fromReplicatorCount",std::to_string(fromReplicatorCount.value()))); + } + + if (toReplicatorCount.has_value()) { + options.insert(std::pair("toReplicatorCount",std::to_string(toReplicatorCount.value()))); + } + + if (owner.has_value()) { + options.insert(std::pair("owner",owner.value())); + } + + if (paginationOrderingOptions.has_value()) { + auto poOptions = paginationOrderingOptions.value().toMap(); + options.insert(poOptions.begin(), poOptions.end()); + } + + return options; + } + + public: + std::optional size; + std::optional fromSize; + std::optional toSize; + std::optional usedSize; + std::optional fromUsedSize; + std::optional toUsedSize; + std::optional metaFilesSize; + std::optional fromMetaFilesSize; + std::optional toMetaFilesSize; + std::optional replicatorCount; + std::optional fromReplicatorCount; + std::optional toReplicatorCount; + std::optional owner; + std::optional paginationOrderingOptions; + }; +} \ No newline at end of file diff --git a/include/xpxchaincpp/model/storage/replicator.h b/include/xpxchaincpp/model/storage/replicator.h new file mode 100644 index 0000000..681b72b --- /dev/null +++ b/include/xpxchaincpp/model/storage/replicator.h @@ -0,0 +1,37 @@ +/** +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include + +namespace xpx_chain_sdk { + + class DriveInfo { + public: + std::string drive; + std::string lastApprovedDataModificationId; + uint64_t initialDownloadWork; + uint64_t lastCompletedCumulativeDownloadWork; + }; + + class ReplicatorData { + public: + std::string key; + uint32_t version; + std::vector drivesInfo; + std::vector downloadChannels; + }; + + class Replicator { + public: + ReplicatorData data; + }; + + class MultipleReplicators { + public: + std::vector replicators; + }; +} \ No newline at end of file diff --git a/include/xpxchaincpp/model/storage/replicators_page.h b/include/xpxchaincpp/model/storage/replicators_page.h new file mode 100644 index 0000000..ca47bb0 --- /dev/null +++ b/include/xpxchaincpp/model/storage/replicators_page.h @@ -0,0 +1,27 @@ +/** +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include "replicator.h" + +namespace xpx_chain_sdk::replicators_page { + + class Pagination { + public: + uint64_t totalEntries; + uint64_t pageNumber; + uint64_t pageSize; + uint64_t totalPages; + }; + + class ReplicatorsPage { + public: + MultipleReplicators data; + Pagination pagination; + }; +} \ No newline at end of file diff --git a/include/xpxchaincpp/model/storage/replicators_page_options.h b/include/xpxchaincpp/model/storage/replicators_page_options.h new file mode 100644 index 0000000..d1cb7c9 --- /dev/null +++ b/include/xpxchaincpp/model/storage/replicators_page_options.h @@ -0,0 +1,61 @@ +/** +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include +#include +#include "xpxchaincpp/utils/paginationOrderingOptions.h" + +namespace xpx_chain_sdk { + + class ReplicatorsPageOptions { + public: + std::map toMap() const { + std::map options; + if (version.has_value()) { + options.insert(std::pair("version",std::to_string(version.value()))); + } + + if (fromVersion.has_value()) { + options.insert(std::pair("fromVersion",std::to_string(fromVersion.value()))); + } + + if (toVersion.has_value()) { + options.insert(std::pair("toVersion",std::to_string(toVersion.value()))); + } + + if (capacity.has_value()) { + options.insert(std::pair("capacity",std::to_string(capacity.value()))); + } + + if (fromCapacity.has_value()) { + options.insert(std::pair("fromCapacity",std::to_string(fromCapacity.value()))); + } + + if (toCapacity.has_value()) { + options.insert(std::pair("toCapacity",std::to_string(toCapacity.value()))); + } + + if (paginationOrderingOptions.has_value()) { + auto poOptions = paginationOrderingOptions.value().toMap(); + options.insert(poOptions.begin(), poOptions.end()); + } + + return options; + } + + public: + std::optional version; + std::optional fromVersion; + std::optional toVersion; + std::optional capacity; + std::optional fromCapacity; + std::optional toCapacity; + std::optional paginationOrderingOptions; + }; +} \ No newline at end of file diff --git a/include/xpxchaincpp/model/supercontract_v2/supercontract.h b/include/xpxchaincpp/model/supercontract_v2/supercontract.h new file mode 100644 index 0000000..f0a72cd --- /dev/null +++ b/include/xpxchaincpp/model/supercontract_v2/supercontract.h @@ -0,0 +1,93 @@ +/** +*** Copyright 2019 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace xpx_chain_sdk { + + struct AutomaticExecutionsInfo { + std::string automaticExecutionFileName; + std::string automaticExecutionsFunctionName; + uint64_t automaticExecutionsNextBlockToCheck; + uint64_t automaticExecutionCallPayment; + uint64_t automaticDownloadCallPayment; + uint32_t automatedExecutionsNumber = 0U; + std::optional automaticExecutionsPrepaidSince; + }; + + struct CompletedCall { + std::string callId; + std::string caller; + int16_t status; + uint64_t executionWork; + uint64_t downloadWork; + }; + + struct Batch { + bool success; + std::array poExVerificationInformation; + std::vector completedCalls; + }; + + struct ServicePayment { + uint64_t mosaicId; + uint64_t amount; + }; + + struct ContractCall { + std::string callId; + std::string caller; + std::string fileName; + std::string functionName; + std::string actualArguments; + uint64_t executionCallPayment; + uint64_t downloadCallPayment; + std::vector servicePayments; + uint64_t blockHeight; + }; + + struct ProofOfExecution { + uint64_t startBatchId = 0; + std::array T; + std::array R; + }; + + struct ExecutorInfo { + uint64_t nextBatchToApprove = 0; + ProofOfExecution poEx; + }; + + class SuperContractV2Data { + public: + std::string contractKey; + std::string executionPaymentKey; + std::string assignee; + std::string creator; + std::string deploymentBaseModificationId; + AutomaticExecutionsInfo automaticExecutionsInfo; + std::deque requestedCalls; + std::map executorsInfo; + std::map batches; + std::multiset releasedTransactions; + }; + + class SuperContractV2 { + public: + SuperContractV2Data data; + }; + + class MultipleSuperContracts { + public: + std::vector supercontracts; + }; +} diff --git a/include/xpxchaincpp/model/transaction/automatic_execution_transaction.h b/include/xpxchaincpp/model/transaction/automatic_execution_transaction.h new file mode 100644 index 0000000..3561005 --- /dev/null +++ b/include/xpxchaincpp/model/transaction/automatic_execution_transaction.h @@ -0,0 +1,66 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +namespace xpx_chain_sdk { + + /// Automatic executions payment transaction base class. + template + class TAutomaticExecutionsPaymentTransaction: public TBase { + public: + /// Creates Automatic executions payment transaction. + template + explicit TAutomaticExecutionsPaymentTransaction( + const Key& contractKey, + uint32_t automaticExecutionsNumber, + TArgs&&... args): + TBase(TransactionType::Automatic_Executions_Payment, std::forward(args)...), + contractKey_(contractKey), + automaticExecutionsNumber_(automaticExecutionsNumber) + { } + + const Key& contractKey() const; + + uint32_t automaticExecutionsNumber() const; + + private: + Key contractKey_; + uint32_t automaticExecutionsNumber_; + }; + + extern template class TAutomaticExecutionsPaymentTransaction; + extern template class TAutomaticExecutionsPaymentTransaction; + + using AutomaticExecutionsPaymentTransaction = TAutomaticExecutionsPaymentTransaction; + using EmbeddedAutomaticExecutionsPaymentTransaction = TAutomaticExecutionsPaymentTransaction; + + /// Creates Automatic executions payment transaction. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateAutomaticExecutionsPaymentTransaction(const Key& contractKey, + uint32_t automaticExecutionsNumber, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); + + + /// Creates Automatic executions payment transaction. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateEmbeddedAutomaticExecutionsPaymentTransaction(const Key& contractKey, + uint32_t automaticExecutionsNumber, + const Key& signer, + std::optional networkId = std::nullopt); +} diff --git a/include/xpxchaincpp/model/transaction/create_liquidity_provider_transaction.h b/include/xpxchaincpp/model/transaction/create_liquidity_provider_transaction.h new file mode 100644 index 0000000..2858883 --- /dev/null +++ b/include/xpxchaincpp/model/transaction/create_liquidity_provider_transaction.h @@ -0,0 +1,116 @@ +/** +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace xpx_chain_sdk { + + /// Create liquidity provider transaction base class. + template + class TCreateLiquidityProviderTransaction: public TBase { + public: + /// Creates create liquidity provider transaction. + template + explicit TCreateLiquidityProviderTransaction(const MosaicId providerMosaicId, + const Amount currencyDeposit, + const Amount initialMosaicsMinting, + const uint32_t slashingPeriod, + const uint16_t windowSize, + const Key& slashingAccount, + const uint32_t alpha, + const uint32_t beta, + TArgs&&... args): + TBase(TransactionType::Create_Liquidity_Provider, std::forward(args)...), + providerMosaicId_(providerMosaicId), + currencyDeposit_(currencyDeposit), + initialMosaicsMinting_(initialMosaicsMinting), + slashingPeriod_(slashingPeriod), + windowSize_(windowSize), + slashingAccount_(slashingAccount), + alpha_(alpha), + beta_(beta) + { } + + /// Returns mosaic id. + MosaicId providerMosaicId() const; + + /// Returns current deposit. + Amount currencyDeposit() const; + + /// Returns initial mosaics minting. + Amount initialMosaicsMinting() const; + + /// Returns slashing period. + uint32_t slashingPeriod() const; + + /// Returns windows size. + uint16_t windowSize() const; + + /// Returns slashing account. + const Key& slashingAccount() const; + + /// Returns alpha. + uint32_t alpha() const; + + /// Returns beta. + uint32_t beta() const; + + private: + MosaicId providerMosaicId_; + Amount currencyDeposit_; + Amount initialMosaicsMinting_; + uint32_t slashingPeriod_; + uint16_t windowSize_; + Key slashingAccount_; + uint32_t alpha_; + uint32_t beta_; + }; + + extern template class TCreateLiquidityProviderTransaction; + extern template class TCreateLiquidityProviderTransaction; + + using CreateLiquidityProviderTransaction = TCreateLiquidityProviderTransaction; + using EmbeddedCreateLiquidityProviderTransaction = TCreateLiquidityProviderTransaction; + + /// Creates liquidity provider transaction. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateCreateLiquidityProviderTransaction(const MosaicId providerMosaicId, + const Amount currencyDeposit, + const Amount initialMosaicsMinting, + const uint32_t slashingPeriod, + const uint16_t windowSize, + const Key& slashingAccount, + const uint32_t alpha, + const uint32_t beta, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); + + + /// Creates embedded liquidity provider transaction. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateEmbeddedCreateLiquidityProviderTransaction(const MosaicId providerMosaicId, + const Amount currencyDeposit, + const Amount initialMosaicsMinting, + const uint32_t slashingPeriod, + const uint16_t windowSize, + const Key& slashingAccount, + const uint32_t alpha, + const uint32_t beta, + const Key& signer, + std::optional networkId = std::nullopt); +} diff --git a/include/xpxchaincpp/model/transaction/data_modification_approval_transaction.h b/include/xpxchaincpp/model/transaction/data_modification_approval_transaction.h index 9cd3cbe..0160175 100644 --- a/include/xpxchaincpp/model/transaction/data_modification_approval_transaction.h +++ b/include/xpxchaincpp/model/transaction/data_modification_approval_transaction.h @@ -26,15 +26,35 @@ namespace xpx_chain_sdk { const Key& driveKey, const Hash256& dataModificationId, const Hash256& fileStructureCdi, - uint64_t fileStructureSize, - uint64_t usedDriveSize, + uint8_t modificationStatus, + uint64_t fileStructureSizeBytes, + uint64_t metaFilesSizeBytes, + uint64_t usedDriveSizeBytes, + uint8_t judgingKeysCount, + uint8_t overlappingKeysCount, + uint8_t judgedKeysCount, + uint16_t opinionElementCount, + const std::vector& publicKeys, + const std::vector& signatures, + const std::vector& presentOpinions, + const std::vector& opinions, TArgs&&... args): TBase(TransactionType::Data_Modification_Approval, std::forward(args)...), driveKey_(driveKey), dataModificationId_(dataModificationId), fileStructureCdi_(fileStructureCdi), - fileStructureSize_(fileStructureSize), - usedDriveSize_(usedDriveSize) + modificationStatus_(modificationStatus), + fileStructureSize_(fileStructureSizeBytes), + metaFilesSize_(metaFilesSizeBytes), + usedDriveSize_(usedDriveSizeBytes), + judgingKeysCount_(judgingKeysCount), + overlappingKeysCount_(overlappingKeysCount), + judgedKeysCount_(judgedKeysCount), + opinionElementCount_(opinionElementCount), + publicKeys_(publicKeys), + signatures_(signatures), + presentOpinions_(presentOpinions), + opinions_(opinions) { } /// Returns drive key. @@ -46,18 +66,60 @@ namespace xpx_chain_sdk { /// Returns Content Download Information for the File Structure. const Hash256& fileStructureCdi() const; + /// Returns Status of the modification + uint8_t modificationStatus() const; + /// Returns size of the File Structure. - uint64_t fileStructureSize() const; + uint64_t fileStructureSizeBytes() const; + + /// Returns the size of metafiles including File Structure. + uint64_t metaFilesSizeBytes() const; /// Returns total used disk space of the drive. - uint64_t usedDriveSize() const; + uint64_t usedDriveSizeBytes() const; + + /// Returns number of replicators that provided their opinions, but on which no opinions were provided. + uint8_t judgingKeysCount() const; + + /// Returns number of replicators that provided their opinions, but on which no opinions were provided. + uint8_t overlappingKeysCount() const; + + /// Returns number of replicators that didn't provide their opinions, but on which at least one opinion was provided. + uint8_t judgedKeysCount() const; + + /// Returns total number of opinion elements. + uint8_t opinionElementCount() const; + + /// Returns replicators' public keys. + std::vector publicKeys() const; + + /// Returns signatures of replicators' opinions. + std::vector signatures() const; + + /// Returns present opinions. + /// Two-dimensional array of opinion element presence. + /// Must be interpreted bitwise (1 if corresponding element exists, 0 otherwise). + std::vector presentOpinions() const; + + /// Returns total number of opinion elements. + std::vector opinions() const; private: Key driveKey_; Hash256 dataModificationId_; Hash256 fileStructureCdi_; + uint8_t modificationStatus_; uint64_t fileStructureSize_; + uint64_t metaFilesSize_; uint64_t usedDriveSize_; + uint8_t judgingKeysCount_; + uint8_t overlappingKeysCount_; + uint8_t judgedKeysCount_; + uint16_t opinionElementCount_; + std::vector publicKeys_; + std::vector signatures_; + std::vector presentOpinions_; + std::vector opinions_; }; extern template class TDataModificationApprovalTransaction; @@ -71,24 +133,44 @@ namespace xpx_chain_sdk { /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. std::unique_ptr CreateDataModificationApprovalTransaction(const Key& driveKey, - const Hash256& dataModificationId, - const Hash256& fileStructureCdi, - uint64_t fileStructureSize, - uint64_t usedDriveSize, - std::optional maxFee = std::nullopt, - std::optional deadline = std::nullopt, - std::optional networkId = std::nullopt); + const Hash256& dataModificationId, + const Hash256& fileStructureCdi, + uint8_t modificationStatus, + uint64_t fileStructureSizeBytes, + uint64_t metaFilesSizeBytes, + uint64_t usedDriveSizeBytes, + uint8_t judgingKeysCount, + uint8_t overlappingKeysCount, + uint8_t judgedKeysCount, + uint16_t opinionElementCount, + const std::vector& publicKeys, + const std::vector& signatures, + const std::vector& presentOpinions, + const std::vector& opinions, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); /// Creates data modification approval transaction. /// \note Throws \c transaction_error if mosaics or message have invalid size. /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. std::unique_ptr - CreateEmbeddedDataModificationApprovalTransaction(const Key& driveKey, - const Hash256& dataModificationId, - const Hash256& fileStructureCdi, - uint64_t fileStructureSize, - uint64_t usedDriveSize, - const Key& signer, - std::optional networkId = std::nullopt); + CreateEmbeddedDataModificationApprovalTransaction(const Key& driveKey, + const Hash256& dataModificationId, + const Hash256& fileStructureCdi, + uint8_t modificationStatus, + uint64_t fileStructureSizeBytes, + uint64_t metaFilesSizeBytes, + uint64_t usedDriveSizeBytes, + uint8_t judgingKeysCount, + uint8_t overlappingKeysCount, + uint8_t judgedKeysCount, + uint16_t opinionElementCount, + const std::vector& publicKeys, + const std::vector& signatures, + const std::vector& presentOpinions, + const std::vector& opinions, + const Key& signer, + std::optional networkId = std::nullopt); } diff --git a/include/xpxchaincpp/model/transaction/data_modification_cancel_transaction.h b/include/xpxchaincpp/model/transaction/data_modification_cancel_transaction.h index ffda0ca..43dbc67 100644 --- a/include/xpxchaincpp/model/transaction/data_modification_cancel_transaction.h +++ b/include/xpxchaincpp/model/transaction/data_modification_cancel_transaction.h @@ -26,7 +26,7 @@ namespace xpx_chain_sdk { const Key& driveKey, const Hash256& dataModificationId, TArgs&&... args): - TBase(TransactionType::Data_Modification_Approval, std::forward(args)...), + TBase(TransactionType::Data_Modification_Cancel, std::forward(args)...), driveKey_(driveKey), dataModificationId_(dataModificationId) { } diff --git a/include/xpxchaincpp/model/transaction/data_modification_transaction.h b/include/xpxchaincpp/model/transaction/data_modification_transaction.h index 9d57e97..e746aac 100644 --- a/include/xpxchaincpp/model/transaction/data_modification_transaction.h +++ b/include/xpxchaincpp/model/transaction/data_modification_transaction.h @@ -26,11 +26,13 @@ namespace xpx_chain_sdk { const Key& driveKey, const Hash256& downloadDataCdi, uint64_t uploadSize, + const Amount& feedbackFeeAmount, TArgs&&... args): TBase(TransactionType::Data_Modification, std::forward(args)...), driveKey_(driveKey), downloadDataCdi_(downloadDataCdi), - uploadSize_(uploadSize) + uploadSize_(uploadSize), + feedbackFeeAmount_(feedbackFeeAmount) { } /// Returns drive key. @@ -42,10 +44,14 @@ namespace xpx_chain_sdk { /// Returns upload size. uint64_t uploadSize() const; + /// Returns amount of XPXs to transfer to the drive. + const Amount& feedbackFeeAmount() const; + private: Key driveKey_; Hash256 downloadDataCdi_; uint64_t uploadSize_; + Amount feedbackFeeAmount_; }; extern template class TDataModificationTransaction; @@ -58,21 +64,23 @@ namespace xpx_chain_sdk { /// \note Throws \c transaction_error if mosaics or message have invalid size. /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. std::unique_ptr - CreateDataModificationTransaction(const Key& driveKey, - const Hash256& downloadDataCdi, - uint64_t uploadSize, - std::optional maxFee = std::nullopt, - std::optional deadline = std::nullopt, - std::optional networkId = std::nullopt); + CreateDataModificationTransaction(const Key& driveKey, + const Hash256& downloadDataCdi, + uint64_t uploadSize, + const Amount& feedbackFeeAmount, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); /// Creates data modification transaction. /// \note Throws \c transaction_error if mosaics or message have invalid size. /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. std::unique_ptr - CreateEmbeddedDataModificationTransaction(const Key& driveKey, - const Hash256& downloadDataCdi, - uint64_t uploadSize, - const Key& signer, - std::optional networkId = std::nullopt); + CreateEmbeddedDataModificationTransaction(const Key& driveKey, + const Hash256& downloadDataCdi, + uint64_t uploadSize, + const Amount& feedbackFeeAmount, + const Key& signer, + std::optional networkId = std::nullopt); } diff --git a/include/xpxchaincpp/model/transaction/deploy_contract_transaction.h b/include/xpxchaincpp/model/transaction/deploy_contract_transaction.h new file mode 100644 index 0000000..17b58cd --- /dev/null +++ b/include/xpxchaincpp/model/transaction/deploy_contract_transaction.h @@ -0,0 +1,145 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace xpx_chain_sdk { + + /// Deploy contract transaction base class. + template + class TDeployContractTransaction: public TBase { + public: + /// Creates Deploy contract transaction. + template + explicit TDeployContractTransaction( + const Key& driveKey, + const std::string fileName, + const std::string functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + MosaicContainer servicePayments, + const std::string automaticExecutionsFileName, + const std::string automaticExecutionsFunctionName, + const Amount& automaticExecutionsCallPayment, + const Amount& automaticDownloadCallPayment, + uint32_t automaticExecutionsNumber, + const Key& assignee, + TArgs&&... args): + TBase(TransactionType::Deploy_Contract, std::forward(args)...), + driveKey_(driveKey), + fileName_(fileName), + functionName_(functionName), + actualArguments_(actualArguments), + executionCallPayment_(executionCallPayment), + downloadCallPayment_(downloadCallPayment), + servicePayments_(servicePayments), + automaticExecutionsFileName_(automaticExecutionsFileName), + automaticExecutionsFunctionName_(automaticExecutionsFunctionName), + automaticExecutionsCallPayment_(automaticExecutionsCallPayment), + automaticDownloadCallPayment_(automaticDownloadCallPayment), + automaticExecutionsNumber_(automaticExecutionsNumber), + assignee_(assignee) + { } + + const Key& driveKey() const; + + const std::string& fileName() const; + + const std::string& functionName() const; + + const std::vector& actualArguments() const; + + const Amount& executionCallPayment() const; + + const Amount& downloadCallPayment() const; + + const MosaicContainer& servicePayments() const; + + const std::string& automaticExecutionsFileName() const; + + const std::string& automaticExecutionsFunctionName() const; + + const Amount& automaticExecutionsCallPayment() const; + + const Amount& automaticDownloadCallPayment() const; + + uint32_t automaticExecutionsNumber() const; + + const Key& assignee() const; + + private: + Key driveKey_; + std::string fileName_; + std::string functionName_; + std::vector actualArguments_; + Amount executionCallPayment_; + Amount downloadCallPayment_; + MosaicContainer servicePayments_; + std::string automaticExecutionsFileName_; + std::string automaticExecutionsFunctionName_; + Amount automaticExecutionsCallPayment_; + Amount automaticDownloadCallPayment_; + uint32_t automaticExecutionsNumber_; + Key assignee_; + }; + + extern template class TDeployContractTransaction; + extern template class TDeployContractTransaction; + + using DeployContractTransaction = TDeployContractTransaction; + using EmbeddedDeployContractTransaction = TDeployContractTransaction; + + /// Creates Deploy contract transaction. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateDeployContractTransaction(const Key& driveKey, + const std::string& fileName, + const std::string& functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + MosaicContainer servicePayments, + const std::string& automaticExecutionsFileName, + const std::string& automaticExecutionsFunctionName, + const Amount& automaticExecutionsCallPayment, + const Amount& automaticDownloadCallPayment, + uint32_t automaticExecutionsNumber, + const Key& assignee, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); + + + /// Creates deploy contract transaction. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateEmbeddedDeployContractTransaction(const Key& driveKey, + const std::string& fileName, + const std::string& functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + MosaicContainer servicePayments, + const std::string& automaticExecutionsFileName, + const std::string& automaticExecutionsFunctionName, + const Amount& automaticExecutionsCallPayment, + const Amount& automaticDownloadCallPayment, + uint32_t automaticExecutionsNumber, + const Key& assignee, + const Key& signer, + std::optional networkId = std::nullopt); +} diff --git a/include/xpxchaincpp/model/transaction/download_payment_transaction.h b/include/xpxchaincpp/model/transaction/download_payment_transaction.h new file mode 100644 index 0000000..7451bc8 --- /dev/null +++ b/include/xpxchaincpp/model/transaction/download_payment_transaction.h @@ -0,0 +1,78 @@ +/** +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +namespace xpx_chain_sdk { + + /// Download payment transaction base class. + template + class TDownloadPaymentTransaction: public TBase { + public: + /// Creates download payment transaction. + template + explicit TDownloadPaymentTransaction( + const Hash256& downloadChannelId, + uint64_t downloadSize, + const Amount& feedbackFeeAmount, + TArgs&&... args): + TBase(TransactionType::Download_Payment, std::forward(args)...), + downloadChannelId_(downloadChannelId), + downloadSize_(downloadSize), + feedbackFeeAmount_(feedbackFeeAmount) + { } + + /// Returns identifier of the download channel. + const Hash256& downloadChannelId() const; + + /// Returns download size to add to the prepaid size of the download channel. + uint64_t downloadSize() const; + + /// Returns amount of XPXs to transfer to the download channel. + const Amount& feedbackFeeAmount() const; + + private: + Hash256 downloadChannelId_; + uint64_t downloadSize_; + Amount feedbackFeeAmount_; + }; + + extern template class TDownloadPaymentTransaction; + extern template class TDownloadPaymentTransaction; + + using DownloadPaymentTransaction = TDownloadPaymentTransaction; + using EmbeddedDownloadPaymentTransaction = TDownloadPaymentTransaction; + + /// Creates download payment transaction. + /// \note Throws \c transaction_error if mosaics or message have invalid size. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateDownloadPaymentTransaction(const Hash256& downloadChannelId, + uint64_t downloadSize, + const Amount& feedbackFeeAmount, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); + + + /// Creates download payment transaction. + /// \note Throws \c transaction_error if mosaics or message have invalid size. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateEmbeddedDownloadPaymentTransaction(const Hash256& downloadChannelId, + uint64_t downloadSize, + const Amount& feedbackFeeAmount, + const Key& signer, + std::optional networkId = std::nullopt); +} diff --git a/include/xpxchaincpp/model/transaction/download_transaction.h b/include/xpxchaincpp/model/transaction/download_transaction.h index f109d16..21959a2 100644 --- a/include/xpxchaincpp/model/transaction/download_transaction.h +++ b/include/xpxchaincpp/model/transaction/download_transaction.h @@ -25,12 +25,16 @@ namespace xpx_chain_sdk { explicit TDownloadTransaction( const Key& driveKey, uint64_t downloadSize, - const Amount& transactionFee, + const Amount& feedbackFeeAmount, + const uint16_t& listOfPublicKeysSize, + const std::vector& listOfPublicKeys, TArgs&&... args): - TBase(TransactionType::Data_Modification, std::forward(args)...), + TBase(TransactionType::Download, std::forward(args)...), driveKey_(driveKey), downloadSize_(downloadSize), - transactionFee_(transactionFee) + feedbackFeeAmount_(feedbackFeeAmount), + listOfPublicKeysSize_(listOfPublicKeysSize), + listOfPublicKeys_(listOfPublicKeys) { } /// Returns drive key. @@ -39,13 +43,21 @@ namespace xpx_chain_sdk { /// Returns download size. uint64_t downloadSize() const; - /// Returns transaction fee. - const Amount& transactionFee() const; + /// Returns XPXs to lock for future payment for. + const Amount& feedbackFeeAmount() const; + + /// Returns size of the list of public keys. + uint16_t listOfPublicKeysSize() const; + + /// Returns list of public keys. + std::vector listOfPublicKeys() const; private: Key driveKey_; uint64_t downloadSize_; - Amount transactionFee_; + Amount feedbackFeeAmount_; + uint16_t listOfPublicKeysSize_; + std::vector listOfPublicKeys_; }; extern template class TDownloadTransaction; @@ -59,8 +71,10 @@ namespace xpx_chain_sdk { /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. std::unique_ptr CreateDownloadTransaction(const Key& driveKey, - uint64_t downloadSize, - const Amount& transactionFee, + uint64_t downloadSize, + const Amount& feedbackFeeAmount, + uint16_t listOfPublicKeysSize, + const std::vector& listOfPublicKeys, std::optional maxFee = std::nullopt, std::optional deadline = std::nullopt, std::optional networkId = std::nullopt); @@ -72,7 +86,9 @@ namespace xpx_chain_sdk { std::unique_ptr CreateEmbeddedDownloadTransaction(const Key& driveKey, uint64_t downloadSize, - const Amount& transactionFee, + const Amount& feedbackFeeAmount, + const uint16_t& listOfPublicKeysSize, + const std::vector& listOfPublicKeys, const Key& signer, std::optional networkId = std::nullopt); } diff --git a/include/xpxchaincpp/model/transaction/drive_closure_transaction.h b/include/xpxchaincpp/model/transaction/drive_closure_transaction.h new file mode 100644 index 0000000..1a15935 --- /dev/null +++ b/include/xpxchaincpp/model/transaction/drive_closure_transaction.h @@ -0,0 +1,62 @@ +/** +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +namespace xpx_chain_sdk { + + /// Drive closure transaction base class. + template + class TDriveClosureTransaction: public TBase { + public: + /// Creates drive closure transaction. + template + explicit TDriveClosureTransaction( + const Key& driveKey, + TArgs&&... args): + TBase(TransactionType::Drive_Closure, std::forward(args)...), + driveKey_(driveKey) + { } + + /// Returns identifier of the drive. + const Hash256& driveKey() const; + + private: + Key driveKey_; + }; + + extern template class TDriveClosureTransaction; + extern template class TDriveClosureTransaction; + + using DriveClosureTransaction = TDriveClosureTransaction; + using EmbeddedDriveClosureTransaction = TDriveClosureTransaction; + + /// Creates drive closure transaction. + /// \note Throws \c transaction_error if mosaics or message have invalid size. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateDriveClosureTransaction(const Key& driveKey, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); + + + /// Creates drive closure transaction. + /// \note Throws \c transaction_error if mosaics or message have invalid size. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateEmbeddedDriveClosureTransaction(const Key& driveKey, + const Key& signer, + std::optional networkId = std::nullopt); +} diff --git a/include/xpxchaincpp/model/transaction/end_batch_execution_transaction_types.h b/include/xpxchaincpp/model/transaction/end_batch_execution_transaction_types.h new file mode 100644 index 0000000..23c683d --- /dev/null +++ b/include/xpxchaincpp/model/transaction/end_batch_execution_transaction_types.h @@ -0,0 +1,46 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include + +#include + +namespace xpx_chain_sdk { + + class ExtendedCallDigest { + public: + Hash256 CallId; + bool Manual; + uint64_t Block; + int16_t Status; + Hash256 ReleasedTransactionHash; + }; + + class RawProofOfExecution { + public: + uint64_t StartBatchId; + std::array T; + std::array R; + std::array F; + std::array K; + }; + + class CallPayment { + public: + Amount ExecutionPayment; + Amount DownloadPayment; + }; + + struct Opinion { + Hash256 publicKey; + Hash256 signature; + std::vector poEx; + std::vector callPayments; + }; +} diff --git a/include/xpxchaincpp/model/transaction/finish_download_transaction.h b/include/xpxchaincpp/model/transaction/finish_download_transaction.h new file mode 100644 index 0000000..35b398f --- /dev/null +++ b/include/xpxchaincpp/model/transaction/finish_download_transaction.h @@ -0,0 +1,70 @@ +/** +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +namespace xpx_chain_sdk { + + /// Finish download transaction base class. + template + class TFinishDownloadTransaction: public TBase { + public: + /// Creates finish download transaction. + template + explicit TFinishDownloadTransaction( + const Hash256& downloadChannelId, + const Amount& feedbackFeeAmount, + TArgs&&... args): + TBase(TransactionType::Finish_Download, std::forward(args)...), + downloadChannelId_(downloadChannelId), + feedbackFeeAmount_(feedbackFeeAmount) + { } + + /// Returns identifier of the download channel. + const Hash256& downloadChannelId() const; + + /// Returns amount of XPXs to transfer to the download channel. + const Amount& feedbackFeeAmount() const; + + private: + Hash256 downloadChannelId_; + Amount feedbackFeeAmount_; + }; + + extern template class TFinishDownloadTransaction; + extern template class TFinishDownloadTransaction; + + using FinishDownloadTransaction = TFinishDownloadTransaction; + using EmbeddedFinishDownloadTransaction = TFinishDownloadTransaction; + + /// Creates finish download transaction. + /// \note Throws \c transaction_error if mosaics or message have invalid size. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateFinishDownloadTransaction(const Hash256& downloadChannelId, + const Amount& feedbackFeeAmount, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); + + + /// Creates finish download transaction. + /// \note Throws \c transaction_error if mosaics or message have invalid size. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateEmbeddedFinishDownloadTransaction(const Hash256& downloadChannelId, + const Amount& feedbackFeeAmount, + const Key& signer, + std::optional networkId = std::nullopt); +} diff --git a/include/xpxchaincpp/model/transaction/manual_call_transaction.h b/include/xpxchaincpp/model/transaction/manual_call_transaction.h new file mode 100644 index 0000000..9c2d96f --- /dev/null +++ b/include/xpxchaincpp/model/transaction/manual_call_transaction.h @@ -0,0 +1,102 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace xpx_chain_sdk { + + /// Manual call transaction base class. + template + class TManualCallTransaction: public TBase { + public: + /// Creates Manual call transaction. + template + explicit TManualCallTransaction( + const Key& contractKey, + const std::string fileName, + const std::string functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + MosaicContainer servicePayments, + TArgs&&... args): + TBase(TransactionType::Manual_Call, std::forward(args)...), + contractKey_(contractKey), + fileName_(fileName), + functionName_(functionName), + actualArguments_(actualArguments), + executionCallPayment_(executionCallPayment), + downloadCallPayment_(downloadCallPayment), + servicePayments_(servicePayments) + { } + + const Key& contractKey() const; + + const std::string& fileName() const; + + const std::string& functionName() const; + + const std::vector& actualArguments() const; + + const Amount& executionCallPayment() const; + + const Amount& downloadCallPayment() const; + + const MosaicContainer& servicePayments() const; + + private: + Key contractKey_; + std::string fileName_; + std::string functionName_; + std::vector actualArguments_; + Amount executionCallPayment_; + Amount downloadCallPayment_; + MosaicContainer servicePayments_; + }; + + extern template class TManualCallTransaction; + extern template class TManualCallTransaction; + + using ManualCallTransaction = TManualCallTransaction; + using EmbeddedManualCallTransaction = TManualCallTransaction; + + /// Creates Manual call transaction. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateManualCallTransaction(const Key& contractKey, + const std::string& fileName, + const std::string& functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + MosaicContainer servicePayments, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); + + + /// Creates Manual call transaction. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateEmbeddedManualCallTransaction(const Key& contractKey, + const std::string& fileName, + const std::string& functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + MosaicContainer servicePayments, + const Key& signer, + std::optional networkId = std::nullopt); +} diff --git a/include/xpxchaincpp/model/transaction/manual_rate_change_transaction.h b/include/xpxchaincpp/model/transaction/manual_rate_change_transaction.h new file mode 100644 index 0000000..e89cf70 --- /dev/null +++ b/include/xpxchaincpp/model/transaction/manual_rate_change_transaction.h @@ -0,0 +1,92 @@ +/** +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace xpx_chain_sdk { + + /// Manual rate change transaction base class. + template + class TManualRateChangeTransaction: public TBase { + public: + /// Creates manual rate change transaction. + template + explicit TManualRateChangeTransaction(const MosaicId providerMosaicId, + const bool currencyBalanceIncrease, + const Amount currencyBalanceChange, + const bool mosaicBalanceIncrease, + const Amount mosaicBalanceChange, + TArgs&&... args): + TBase(TransactionType::Manual_Rate_Change, std::forward(args)...), + providerMosaicId_(providerMosaicId), + currencyBalanceIncrease_(currencyBalanceIncrease), + currencyBalanceChange_(currencyBalanceChange), + mosaicBalanceIncrease_(mosaicBalanceIncrease), + mosaicBalanceChange_(mosaicBalanceChange) + { } + + /// Returns mosaic id. + MosaicId providerMosaicId() const; + + /// Returns currency balance increase. + bool currencyBalanceIncrease() const; + + /// Returns currency balance change amount. + Amount currencyBalanceChange() const; + + /// Returns mosaic balance increase. + bool mosaicBalanceIncrease() const; + + /// Returns mosaic balance change amount. + Amount mosaicBalanceChange() const; + + private: + MosaicId providerMosaicId_; + bool currencyBalanceIncrease_; + Amount currencyBalanceChange_; + bool mosaicBalanceIncrease_; + Amount mosaicBalanceChange_; + }; + + extern template class TManualRateChangeTransaction; + extern template class TManualRateChangeTransaction; + + using ManualRateChangeTransaction = TManualRateChangeTransaction; + using EmbeddedManualRateChangeTransaction = TManualRateChangeTransaction; + + /// Creates manual rate change transaction. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateManualRateChangeTransaction(const MosaicId providerMosaicId, + const bool currencyBalanceIncrease, + const Amount currencyBalanceChange, + const bool mosaicBalanceIncrease, + const Amount mosaicBalanceChange, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); + + + /// Creates manual rate change transaction. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateEmbeddedManualRateChangeTransaction(const MosaicId providerMosaicId, + const bool currencyBalanceIncrease, + const Amount currencyBalanceChange, + const bool mosaicBalanceIncrease, + const Amount mosaicBalanceChange, + const Key& signer, + std::optional networkId = std::nullopt); +} diff --git a/include/xpxchaincpp/model/transaction/mosaic_definition_transaction.h b/include/xpxchaincpp/model/transaction/mosaic_definition_transaction.h index 53d8d49..9d98118 100644 --- a/include/xpxchaincpp/model/transaction/mosaic_definition_transaction.h +++ b/include/xpxchaincpp/model/transaction/mosaic_definition_transaction.h @@ -24,13 +24,11 @@ namespace xpx_chain_sdk { template explicit TMosaicDefinitionTransaction(uint32_t mosaicNonce, MosaicId mosaicId, - MosaicFlags flags, MosaicProperties mosaicProperties, TArgs&&... args): TBase(TransactionType::Mosaic_Definition, std::forward(args)...), mosaicNonce_(mosaicNonce), mosaicId_(mosaicId), - flags_(flags), mosaicProperties_(std::move(mosaicProperties)) { } @@ -39,9 +37,6 @@ namespace xpx_chain_sdk { /// Returns generated mosaic id. MosaicId mosaicId() const; - - /// Returns mosaic flags; - MosaicFlags flags() const; /// Returns mosaic properties. const MosaicProperties& mosaicProperties() const; @@ -49,7 +44,6 @@ namespace xpx_chain_sdk { private: uint32_t mosaicNonce_; MosaicId mosaicId_; - MosaicFlags flags_; MosaicProperties mosaicProperties_; }; @@ -65,7 +59,6 @@ namespace xpx_chain_sdk { std::unique_ptr CreateMosaicDefinitionTransaction(uint32_t mosaicNonce, MosaicId mosaicId, - MosaicFlags flags, MosaicProperties mosaicProperties, std::optional maxFee = std::nullopt, std::optional deadline = std::nullopt, @@ -77,7 +70,6 @@ namespace xpx_chain_sdk { std::unique_ptr CreateEmbeddedMosaicDefinitionTransaction(uint32_t mosaicNonce, MosaicId mosaicId, - MosaicFlags flags, MosaicProperties mosaicProperties, const Key& signer, std::optional networkId = std::nullopt); diff --git a/include/xpxchaincpp/model/transaction/prepare_bc_drive_transaction.h b/include/xpxchaincpp/model/transaction/prepare_bc_drive_transaction.h index 2361179..fa9c2a2 100644 --- a/include/xpxchaincpp/model/transaction/prepare_bc_drive_transaction.h +++ b/include/xpxchaincpp/model/transaction/prepare_bc_drive_transaction.h @@ -24,21 +24,27 @@ namespace xpx_chain_sdk { template explicit TPrepareBcDriveTransaction( uint64_t driveSize, + const Amount& verificationFeeAmount, uint16_t replicatorCount, TArgs&&... args): TBase(TransactionType::Prepare_Bc_Drive, std::forward(args)...), driveSize_(driveSize), + verificationFeeAmount_(verificationFeeAmount), replicatorCount_(replicatorCount) { } /// Returns drive size. uint64_t driveSize() const; + /// Returns amount of XPXs to transfer to the drive. + Amount verificationFeeAmount() const; + /// Returns replicator count. uint16_t replicatorCount() const; private: uint64_t driveSize_; + Amount verificationFeeAmount_; uint16_t replicatorCount_; }; @@ -52,19 +58,21 @@ namespace xpx_chain_sdk { /// \note Throws \c transaction_error if mosaics or message have invalid size. /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. std::unique_ptr - CreatePrepareBcDriveTransaction(uint64_t driveSize, - uint16_t replicatorCount, - std::optional maxFee = std::nullopt, - std::optional deadline = std::nullopt, - std::optional networkId = std::nullopt); + CreatePrepareBcDriveTransaction(uint64_t driveSize, + const Amount& verificationFeeAmount, + uint16_t replicatorCount, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); /// Creates prepare drive transaction. /// \note Throws \c transaction_error if mosaics or message have invalid size. /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. std::unique_ptr - CreateEmbeddedPrepareBcDriveTransaction(uint64_t driveSize, - uint16_t replicatorCount, - const Key& signer, - std::optional networkId = std::nullopt); + CreateEmbeddedPrepareBcDriveTransaction(uint64_t driveSize, + const Amount& verificationFeeAmount, + uint16_t replicatorCount, + const Key& signer, + std::optional networkId = std::nullopt); } diff --git a/include/xpxchaincpp/model/transaction/replicator_offboarding_transaction.h b/include/xpxchaincpp/model/transaction/replicator_offboarding_transaction.h new file mode 100644 index 0000000..33ccc9c --- /dev/null +++ b/include/xpxchaincpp/model/transaction/replicator_offboarding_transaction.h @@ -0,0 +1,62 @@ +/** +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +namespace xpx_chain_sdk { + + /// Replicator offboarding transaction base class. + template + class TReplicatorOffboardingTransaction: public TBase { + public: + /// Creates offboarding transaction. + template + explicit TReplicatorOffboardingTransaction( + const Key& driveKey, + TArgs&&... args): + TBase(TransactionType::Replicator_Offboarding, std::forward(args)...), + driveKey_(driveKey) + { } + + /// Returns identifier of the drive. + const Key& driveKey() const; + + private: + Key driveKey_; + }; + + extern template class TReplicatorOffboardingTransaction; + extern template class TReplicatorOffboardingTransaction; + + using ReplicatorOffboardingTransaction = TReplicatorOffboardingTransaction; + using EmbeddedReplicatorOffboardingTransaction = TReplicatorOffboardingTransaction; + + /// Creates replicator offboarding transaction. + /// \note Throws \c transaction_error if mosaics or message have invalid size. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateReplicatorOffboardingTransaction(const Key& driveKey, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); + + + /// Creates replicator offboarding transaction. + /// \note Throws \c transaction_error if mosaics or message have invalid size. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateEmbeddedReplicatorOffboardingTransaction(const Key& driveKey, + const Key& signer, + std::optional networkId = std::nullopt); +} diff --git a/include/xpxchaincpp/model/transaction/replicator_onboarding_transaction.h b/include/xpxchaincpp/model/transaction/replicator_onboarding_transaction.h index b47c86d..a1e9678 100644 --- a/include/xpxchaincpp/model/transaction/replicator_onboarding_transaction.h +++ b/include/xpxchaincpp/model/transaction/replicator_onboarding_transaction.h @@ -28,14 +28,14 @@ namespace xpx_chain_sdk { const Hash256& message, const Signature& messageSignature, TArgs&&... args): - TBase(TransactionType::Data_Modification, std::forward(args)...), + TBase(TransactionType::Replicator_Onboarding, std::forward(args)...), capacity_(capacity), nodeBootKey_(nodeBootKey), message_(message), messageSignature_(messageSignature) { } - /// Returns capacity that the replicator is willing to contribute. + /// Returns capacity that the replicator is willing to contribute (Megabytes). const Amount& capacity() const; /// The boot public key of the node where the replicator will be running. @@ -63,9 +63,7 @@ namespace xpx_chain_sdk { /// Creates replicator onboarding transaction. /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. std::unique_ptr - CreateReplicatorOnboardingTransaction( - const Amount& capacity, - const Key& nodeBootKey, + CreateReplicatorOnboardingTransaction(const Amount& capacity,const Key& nodeBootKey, const Hash256& message, const Signature& messageSignature, std::optional maxFee = std::nullopt, @@ -76,9 +74,7 @@ namespace xpx_chain_sdk { /// Creates replicator onboarding transaction. /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. std::unique_ptr - CreateEmbeddedReplicatorOnboardingTransaction( - const Amount& capacity, - const Key& nodeBootKey, + CreateEmbeddedReplicatorOnboardingTransaction(const Amount& capacity,const Key& nodeBootKey, const Hash256& message, const Signature& messageSignature, const Key& signer, diff --git a/include/xpxchaincpp/model/transaction/storage_payment_transaction.h b/include/xpxchaincpp/model/transaction/storage_payment_transaction.h new file mode 100644 index 0000000..0d1f41d --- /dev/null +++ b/include/xpxchaincpp/model/transaction/storage_payment_transaction.h @@ -0,0 +1,70 @@ +/** +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +namespace xpx_chain_sdk { + + /// Storage payment transaction base class. + template + class TStoragePaymentTransaction: public TBase { + public: + /// Creates storage payment transaction. + template + explicit TStoragePaymentTransaction( + const Key& driveKey, + const Amount& storageUnits, + TArgs&&... args): + TBase(TransactionType::Storage_Payment, std::forward(args)...), + driveKey_(driveKey), + storageUnits_(storageUnits) + { } + + /// Returns identifier of the drive. + const Key& driveKey() const; + + /// Returns amount of storage units to transfer to the drive. + const Amount& storageUnitsAmount() const; + + private: + Key driveKey_; + Amount storageUnits_; + }; + + extern template class TStoragePaymentTransaction; + extern template class TStoragePaymentTransaction; + + using StoragePaymentTransaction = TStoragePaymentTransaction; + using EmbeddedStoragePaymentTransaction = TStoragePaymentTransaction; + + /// Creates storage payment transaction. + /// \note Throws \c transaction_error if mosaics or message have invalid size. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateStoragePaymentTransaction(const Key& driveKey, + const Amount& storageUnits, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); + + + /// Creates storage payment transaction. + /// \note Throws \c transaction_error if mosaics or message have invalid size. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateEmbeddedStoragePaymentTransaction(const Key& driveKey, + const Amount& storageUnits, + const Key& signer, + std::optional networkId = std::nullopt); +} diff --git a/include/xpxchaincpp/model/transaction/stream_finish_transaction.h b/include/xpxchaincpp/model/transaction/stream_finish_transaction.h new file mode 100644 index 0000000..adb7f6a --- /dev/null +++ b/include/xpxchaincpp/model/transaction/stream_finish_transaction.h @@ -0,0 +1,80 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include + +#include +#include +#include + +namespace xpx_chain_sdk { + + /// Stream finish transaction base class. + template + class TStreamFinishTransaction: public TBase { + public: + /// Creates stream finish transaction. + template + explicit TStreamFinishTransaction(const Key& driveKey, + const Hash256& streamId, + const uint64_t actualUploadSizeMegabytes, + const Hash256& streamStructureCdi, + TArgs&&... args): + TBase(TransactionType::Stream_Finish, std::forward(args)...), + driveKey_(driveKey), + streamId_(streamId), + actualUploadSizeMegabytes_(actualUploadSizeMegabytes), + streamStructureCdi_(streamStructureCdi) + {} + + /// Returns key of drive. + const Key& driveKey() const; + + /// Returns Id of stream to be finished. + const Hash256& streamId() const; + + /// Returns expected size of stream. + uint64_t actualUploadSizeMegabytes() const; + + /// Returns message of folderName string in bytes. + const Hash256& streamStructureCdi() const; + + private: + Key driveKey_; + Hash256 streamId_; + uint64_t actualUploadSizeMegabytes_; + Hash256 streamStructureCdi_; + }; + + extern template class TStreamFinishTransaction; + extern template class TStreamFinishTransaction; + + using StreamFinishTransaction = TStreamFinishTransaction; + using EmbeddedStreamFinishTransaction = TStreamFinishTransaction; + + /// Creates stream finish transaction. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateStreamFinishTransaction(const Key& driveKey, + const Hash256& streamId, + const uint64_t actualUploadSizeMegabytes, + const Hash256& streamStructureCdi, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); + + /// Creates embedded stream finish transaction. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateEmbeddedStreamFinishTransaction(const Key& driveKey, + const Hash256& streamId, + const uint64_t actualUploadSizeMegabytes, + const Hash256& streamStructureCdi, + const Key &signer, + std::optional networkId = std::nullopt); +} diff --git a/include/xpxchaincpp/model/transaction/stream_payment_transaction.h b/include/xpxchaincpp/model/transaction/stream_payment_transaction.h new file mode 100644 index 0000000..af1163a --- /dev/null +++ b/include/xpxchaincpp/model/transaction/stream_payment_transaction.h @@ -0,0 +1,77 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +namespace xpx_chain_sdk { + + /// Stream payment transaction base class. + template + class TStreamPaymentTransaction: public TBase { + public: + /// Creates stream payment transaction. + template + explicit TStreamPaymentTransaction(const Key &driveKey, + const Hash256 &streamId, + const uint64_t additionalUploadSizeMegabytes, + TArgs &&... args): + TBase(TransactionType::Stream_Payment, std::forward(args)...), + driveKey_(driveKey), + streamId_(streamId), + additionalUploadSizeMegabytes_(additionalUploadSizeMegabytes) + { } + + /// Returns identifier of the drive. + const Key& driveKey() const; + + /// Returns Id of stream to be finished. + const Hash256& streamId() const; + + /// Returns actual size of stream. + uint64_t additionalUploadSizeMegabytes() const; + + private: + Key driveKey_; + Hash256 streamId_; + uint64_t additionalUploadSizeMegabytes_; + }; + + extern template class TStreamPaymentTransaction; + extern template class TStreamPaymentTransaction; + + using StreamPaymentTransaction = TStreamPaymentTransaction; + using EmbeddedStreamPaymentTransaction = TStreamPaymentTransaction; + + /// Creates stream payment transaction. + /// \note Throws \c transaction_error if mosaics or message have invalid size. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateStreamPaymentTransaction(const Key &driveKey, + const Hash256 &streamId, + const uint64_t additionalUploadSizeMegabytes, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); + + + /// Creates stream payment transaction. + /// \note Throws \c transaction_error if mosaics or message have invalid size. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateEmbeddedStreamPaymentTransaction(const Key &driveKey, + const Hash256 &streamId, + const uint64_t additionalUploadSizeMegabytes, + const Key &signer, + std::optional networkId = std::nullopt); +} diff --git a/include/xpxchaincpp/model/transaction/stream_start_transaction.h b/include/xpxchaincpp/model/transaction/stream_start_transaction.h new file mode 100644 index 0000000..6724668 --- /dev/null +++ b/include/xpxchaincpp/model/transaction/stream_start_transaction.h @@ -0,0 +1,88 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include + +#include +#include +#include + +namespace xpx_chain_sdk { + + /// Stream Start transaction base class. + template + class TStreamStartTransaction: public TBase { + public: + /// Creates stream Start transaction. + template + explicit TStreamStartTransaction(const Key &driveKey, + const uint64_t expectedUploadSizeMegabytes, + const uint16_t folderNameSize, + const Amount &feedbackFeeAmount, + const std::vector& folderName, + TArgs &&... args): + TBase(TransactionType::Stream_Start, std::forward(args)...), + driveKey_(driveKey), + expectedUploadSizeMegabytes_(expectedUploadSizeMegabytes), + folderName_(folderName), + folderNameSize_(folderNameSize), + feedbackFeeAmount_(feedbackFeeAmount) + {} + + /// Returns key of drive. + const Key& driveKey() const; + + /// Returns expected size of stream. + uint64_t expectedUploadSizeMegabytes() const; + + /// Returns message of folderName string in bytes. + uint16_t folderNameSize() const; + + /// Returns amount of XPXs to transfer to the drive. + const Amount& feedbackFeeAmount() const; + + /// Returns folder name. + std::vector folderName() const; + + private: + Key driveKey_; + uint64_t expectedUploadSizeMegabytes_; + uint16_t folderNameSize_; + Amount feedbackFeeAmount_; + std::vector folderName_; + }; + + extern template class TStreamStartTransaction; + extern template class TStreamStartTransaction; + + using StreamStartTransaction = TStreamStartTransaction; + using EmbeddedStreamStartTransaction = TStreamStartTransaction; + + /// Creates stream Start transaction. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateStreamStartTransaction(const Key &driveKey, + const uint64_t expectedUploadSizeMegabytes, + const uint16_t folderNameSize, + const Amount &feedbackFeeAmount, + const std::vector& folderName, + std::optional maxFee = std::nullopt, + std::optional deadline = std::nullopt, + std::optional networkId = std::nullopt); + + /// Creates embedded stream Start transaction. + /// \note Optional transaction parameters are initialized using \c Config if not set explicitly. + std::unique_ptr + CreateEmbeddedStreamStartTransaction(const Key &driveKey, + const uint64_t expectedUploadSizeMegabytes, + const uint16_t folderNameSize, + const Amount &feedbackFeeAmount, + const std::vector& folderName, + const Key &signer, + std::optional networkId = std::nullopt); +} diff --git a/include/xpxchaincpp/model/transaction/successful_end_batch_execution_transaction.h b/include/xpxchaincpp/model/transaction/successful_end_batch_execution_transaction.h new file mode 100644 index 0000000..1cad39e --- /dev/null +++ b/include/xpxchaincpp/model/transaction/successful_end_batch_execution_transaction.h @@ -0,0 +1,81 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include + +#include + +namespace xpx_chain_sdk { + + /// Successful rnd batch execution transaction base class. + template + class TSuccessfulEndBatchExecutionTransaction: public TBase { + public: + /// Creates Successful rnd batch execution transaction. + template + explicit TSuccessfulEndBatchExecutionTransaction( + const Key& contractKey, + uint64_t batchId, + const Hash256& storageHash, + uint64_t usedSizeBytes, + uint64_t metaFilesSizeBytes, + const uint64_t automaticExecutionsNextBlockToCheck, + const std::array& proofOfExecutionVerificationInformation, + const std::vector& callDigests, + const std::vector& opinions, + TArgs&&... args): + TBase(TransactionType::Automatic_Executions_Payment, std::forward(args)...), + contractKey_(contractKey), + batchId_(batchId), + storageHash_(storageHash), + usedSizeBytes_(usedSizeBytes), + metaFilesSizeBytes_(metaFilesSizeBytes), + automaticExecutionsNextBlockToCheck_(automaticExecutionsNextBlockToCheck), + proofOfExecutionVerificationInformation_(proofOfExecutionVerificationInformation), + callDigests_(callDigests), + opinions_(opinions) + { } + + const Key& contractKey() const; + + uint64_t batchId() const; + + const Hash256& storageHash() const; + + uint64_t usedSizeBytes() const; + + uint64_t metaFilesSizeBytes() const; + + const uint64_t automaticExecutionsNextBlockToCheck() const; + + const std::array& proofOfExecutionVerificationInformation() const; + + const std::vector& callDigests() const; + + const std::vector& opinions() const; + + + private: + Key contractKey_; + uint64_t batchId_; + Hash256 storageHash_; + uint64_t usedSizeBytes_; + uint64_t metaFilesSizeBytes_; + uint64_t automaticExecutionsNextBlockToCheck_; + std::array proofOfExecutionVerificationInformation_; + std::vector callDigests_; + std::vector opinions_; + }; + + extern template class TSuccessfulEndBatchExecutionTransaction; + extern template class TSuccessfulEndBatchExecutionTransaction; + + using SuccessfulEndBatchExecutionTransaction = TSuccessfulEndBatchExecutionTransaction; + using EmbeddedSuccessfulEndBatchExecutionTransaction = TSuccessfulEndBatchExecutionTransaction; +} diff --git a/include/xpxchaincpp/model/transaction/transaction_type.h b/include/xpxchaincpp/model/transaction/transaction_type.h index b652187..2b492fe 100644 --- a/include/xpxchaincpp/model/transaction/transaction_type.h +++ b/include/xpxchaincpp/model/transaction/transaction_type.h @@ -10,33 +10,51 @@ namespace xpx_chain_sdk { /// Transaction type. - enum class TransactionType: uint16_t { - Unknown = 0x0000, - Transfer = 0x4154, - Mosaic_Definition = 0x414D, - Mosaic_Supply_Change = 0x424D, - Mosaic_Levy_Change = 0x434D, // not defined yet - Register_Namespace = 0x414E, - Address_Alias = 0x424E, - Mosaic_Alias = 0x434E, - Modify_Multisig_Account = 0x4155, - Aggregate_Complete = 0x4141, - Aggregate_Bonded = 0x4241, - Lock_Funds = 0x4148, - Address_Property = 0x4150, - Mosaic_Property = 0x4250, - Transaction_Property = 0x4350, - Secret_Lock = 0x4152, - Secret_Proof = 0x4252, - Account_Link = 0x414C, - Prepare_Bc_Drive = 0x4162, - Data_Modification = 0x4262, - Download = 0x4362, - Data_Modification_Approval = 0x4462, - Data_Modification_Cancel = 0x4562, - Replicator_Onboarding = 0x4662, + enum class TransactionType: uint16_t { + Unknown = 0x0000, + Transfer = 0x4154, + Mosaic_Definition = 0x414D, + Mosaic_Supply_Change = 0x424D, + Mosaic_Levy_Change = 0x434D, // not defined yet + Register_Namespace = 0x414E, + Address_Alias = 0x424E, + Mosaic_Alias = 0x434E, + Modify_Multisig_Account = 0x4155, + Aggregate_Complete = 0x4141, + Aggregate_Bonded = 0x4241, + Lock_Funds = 0x4148, + Address_Property = 0x4150, + Mosaic_Property = 0x4250, + Transaction_Property = 0x4350, + Secret_Lock = 0x4152, + Secret_Proof = 0x4252, + Storage_Payment = 0x4a62, + Account_Link = 0x414C, + Prepare_Bc_Drive = 0x4162, + Data_Modification = 0x4262, + Download = 0x4362, + Download_Payment = 0x4962, + Drive_Closure = 0x4e62, + Data_Modification_Approval = 0x4462, + Data_Modification_Cancel = 0x4562, + Create_Liquidity_Provider = 0x4169, + Manual_Rate_Change = 0x4269, + Finish_Download = 0x4862, + Replicator_Onboarding = 0x4662, + Replicator_Offboarding = 0x4762, + Deploy_Contract = 0x416E, + Manual_Call = 0x426E, + Automatic_Executions_Payment = 0x436E, + Successful_End_Batch_Execution = 0x446E, + Unsuccessful_End_Batch_Execution = 0x456E, + End_Batch_Execution_Single = 0x466E, + Synchronization_Single = 0x476E, + Stream_Start = 0x4166, + Stream_Finish = 0x4266, + Stream_Payment = 0x4366, + Add_Dbrb_Process = 0x416C, Replicators_Cleanup = 0x4062, - }; + }; /// Returns transaction name by \a type. const char* GetTransactionName(TransactionType type); diff --git a/include/xpxchaincpp/model/transaction/unsuccessful_end_batch_execution_transaction.h b/include/xpxchaincpp/model/transaction/unsuccessful_end_batch_execution_transaction.h new file mode 100644 index 0000000..704ea3a --- /dev/null +++ b/include/xpxchaincpp/model/transaction/unsuccessful_end_batch_execution_transaction.h @@ -0,0 +1,60 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include + +#include + +namespace xpx_chain_sdk { + + /// Unsuccessful end batch execution transaction base class. + template + class TUnsuccessfulEndBatchExecutionTransaction: public TBase { + public: + /// Creates Unsuccessful end batch execution transaction. + template + explicit TUnsuccessfulEndBatchExecutionTransaction( + const Key& contractKey, + uint64_t batchId, + const uint64_t automaticExecutionsNextBlockToCheck, + const std::vector& callDigests, + const std::vector& opinions, + TArgs&&... args): + TBase(TransactionType::Automatic_Executions_Payment, std::forward(args)...), + contractKey_(contractKey), + batchId_(batchId), + automaticExecutionsNextBlockToCheck_(automaticExecutionsNextBlockToCheck), + callDigests_(callDigests), + opinions_(opinions) + { } + + const Key& contractKey() const; + + uint64_t batchId() const; + + const uint64_t automaticExecutionsNextBlockToCheck() const; + + const std::vector& callDigests() const; + + const std::vector& opinions() const; + + private: + Key contractKey_; + uint64_t batchId_; + uint64_t automaticExecutionsNextBlockToCheck_; + std::vector callDigests_; + std::vector opinions_; + }; + + extern template class TUnsuccessfulEndBatchExecutionTransaction; + extern template class TUnsuccessfulEndBatchExecutionTransaction; + + using UnsuccessfulEndBatchExecutionTransaction = TUnsuccessfulEndBatchExecutionTransaction; + using EmbeddedUnsuccessfulEndBatchExecutionTransaction = TUnsuccessfulEndBatchExecutionTransaction; +} diff --git a/include/xpxchaincpp/model/transaction_simple/transaction.h b/include/xpxchaincpp/model/transaction_simple/transaction.h index b668d2b..47969c7 100644 --- a/include/xpxchaincpp/model/transaction_simple/transaction.h +++ b/include/xpxchaincpp/model/transaction_simple/transaction.h @@ -7,7 +7,7 @@ #include #include -#include +#include #include #include #include "xpxchaincpp/model/transaction/account_property_transaction_types.h" @@ -103,12 +103,9 @@ namespace xpx_chain_sdk { namespace transactions_info { template class TMosaicDefinitionTransaction : public TBase { public: - uint32_t nonce; - MosaicId mosaicId; - uint8_t optionalPropertiesCount; - MosaicFlags flags; - uint8_t divisibility; - std::vector optionalProperties; + uint32_t mosaicNonce; + MosaicId mosaicId;; + std::vector properties; }; template @@ -149,6 +146,13 @@ namespace xpx_chain_sdk { namespace transactions_info { std::vector proof; }; + template + class TStoragePaymentTransaction: public TBase { + public: + std::string driveKey; + Amount storageUnits; + }; + class TransferTransactionMessage { public: std::uint32_t type; @@ -197,44 +201,103 @@ namespace xpx_chain_sdk { namespace transactions_info { class TPrepareBcDriveTransaction: public TBase { public: uint64_t driveSize; + Amount verificationFeeAmount; uint16_t replicatorCount; - }; template class TDataModificationTransaction: public TBase { public: - Key driveKey; - Hash256 downloadDataCdi; + std::string driveKey; + std::string downloadDataCdi; uint64_t uploadSize; + Amount feedbackFeeAmount; }; template class TDownloadTransaction: public TBase { public: - Key driveKey; + std::string driveKey; uint64_t downloadSize; - Amount transactionFee; + Amount feedbackFeeAmount; + std::vector listOfPublicKeys; }; template - class TDataModificationApprovalTransaction: public TBase { + class TDownloadPaymentTransaction: public TBase { public: - Key driveKey; - Hash256 dataModificationId; - Hash256 fileStructureCdi; - uint64_t fileStructureSize; - uint64_t usedDriveSize; + std::string downloadChannelId; + uint64_t downloadSize; + Amount feedbackFeeAmount; }; + template + class TDriveClosureTransaction: public TBase { + public: + std::string driveKey; + + }; + + template + class TDataModificationApprovalTransaction: public TBase { + public: + std::string driveKey; + std::string dataModificationId; + std::string fileStructureCdi; + uint8_t modificationStatus; + uint64_t fileStructureSizeBytes; + uint64_t metaFilesSizeBytes; + uint64_t usedDriveSizeBytes; + uint8_t judgingKeysCount; + uint8_t overlappingKeysCount; + uint8_t judgedKeysCount; + std::vector publicKeys; + std::vector signatures; + std::vector presentOpinions; + std::vector opinions; + }; + template class TDataModificationCancelTransaction: public TBase { public: - Key driveKey; - Hash256 dataModificationId; + std::string driveKey; + std::string dataModificationId; + + }; + + template + class TCreateLiquidityProviderTransaction: public TBase { + public: + MosaicId providerMosaicId; + Amount currencyDeposit; + Amount initialMosaicsMinting; + uint32_t slashingPeriod; + uint16_t windowSize; + std::string slashingAccount; + uint32_t alpha; + uint32_t beta; + + }; + + template + class TManualRateChangeTransaction: public TBase { + public: + MosaicId providerMosaicId; + bool currencyBalanceIncrease; + Amount currencyBalanceChange; + bool mosaicBalanceIncrease; + Amount mosaicBalanceChange; + + }; + + template + class TFinishDownloadTransaction: public TBase { + public: + std::string downloadChannelId; + Amount feedbackFeeAmount; }; @@ -245,6 +308,120 @@ namespace xpx_chain_sdk { namespace transactions_info { Key nodeBootKey; Hash256 message; Signature messageSignature; + }; + + template + class TDeployContractTransaction: public TBase { + public: + std::string driveKey; + uint16_t fileNameSize; + std::string fileName; + uint16_t functionNameSize; + std::string functionName; + uint16_t actualArgumentsSize; + std::vector actualArguments; + Amount executionCallPayment; + Amount downloadCallPayment; + uint8_t servicePaymentsCount; + std::vector servicePayments; + uint16_t automaticExecutionsFileNameSize; + std::string automaticExecutionsFileName; + uint16_t automaticExecutionsFunctionNameSize; + std::string automaticExecutionsFunctionName; + Amount automaticExecutionsCallPayment; + Amount automaticDownloadCallPayment; + uint32_t automaticExecutionsNumber; + std::string assignee; + }; + + template + class TManualCallTransaction: public TBase { + public: + std::string contractKey; + uint16_t fileNameSize; + std::string fileName; + uint16_t functionNameSize; + std::string functionName; + uint16_t actualArgumentsSize; + std::vector actualArguments; + Amount executionCallPayment; + Amount downloadCallPayment; + uint8_t servicePaymentsCount; + std::vector servicePayments; + }; + + template + class TAutomaticExecutionsPaymentTransaction: public TBase { + public: + std::string contractKey; + uint32_t automaticExecutionsNumber; + }; + + class ExtendedCallDigest { + public: + std::string callId; + bool manual; + uint64_t block; + int16_t status; + std::string releasedTransactionHash; + }; + + class RawProofOfExecution { + public: + uint64_t startBatchId; + std::array T; + std::array R; + std::array F; + std::array K; + }; + + class CallPayment { + public: + Amount executionPayment; + Amount downloadPayment; + }; + + struct Opinion { + std::string publicKey; + std::string signature; + std::vector poEx; + std::vector callPayments; + }; + + template + class TUnsuccessfulEndBatchExecutionTransaction: public TBase { + public: + std::string contractKey; + uint64_t batchId; + std::string automaticExecutionsNextBlockToCheck; + std::vector callDigests; + std::vector opinions; + }; + + template + class TSuccessfulEndBatchExecutionTransaction: public TUnsuccessfulEndBatchExecutionTransaction { + public: + std::string storageHash; + uint64_t usedSizeBytes; + uint64_t metaFilesSizeBytes; + std::array proofOfExecutionVerificationInformation; + }; + + template + class TReplicatorOffboardingTransaction: public TBase { + public: + std::string driveKey; + + }; + + template + class TStreamStartTransaction : public TBase { + public: + std::string driveKey; + uint64_t expectedUploadSize; + uint16_t folderNameSize; + Amount feedbackFeeAmount; + std::string folderName; }; @@ -253,9 +430,28 @@ namespace xpx_chain_sdk { namespace transactions_info { public: uint16_t replicatorCount; std::vector replicatorKeys; + }; + template + class TStreamFinishTransaction : public TBase { + public: + std::string driveKey; + std::string streamId; + uint64_t actualUploadSizeMegabytes; + std::string streamStructureCdi; + }; + + template + class TStreamPaymentTransaction : public TBase { + public: + std::string driveKey; + std::string streamId; + uint64_t additionalUploadSizeMegabytes; }; + template + class TAddDbrbProcessTransaction : public TBase {}; + using AccountLinkTransaction = TAccountLinkTransaction; using EmbeddedAccountLinkTransaction = TAccountLinkTransaction; @@ -280,6 +476,9 @@ namespace xpx_chain_sdk { namespace transactions_info { using SecretProofTransaction = TSecretProofTransaction; using EmbeddedSecretProofTransaction = TSecretProofTransaction; + using StoragePaymentTransaction = TStoragePaymentTransaction; + using EmbeddedStoragePaymentTransaction = TStoragePaymentTransaction; + using TransferTransaction = TTransferTransaction ; using EmbeddedTransferTransaction = TTransferTransaction; @@ -307,21 +506,65 @@ namespace xpx_chain_sdk { namespace transactions_info { using PrepareBcDriveTransaction = TPrepareBcDriveTransaction ; using EmbeddedPrepareBcDriveTransaction = TPrepareBcDriveTransaction; + using CreateLiquidityProviderTransaction = TCreateLiquidityProviderTransaction ; + using EmbeddedCreateLiquidityProviderTransaction = TCreateLiquidityProviderTransaction; + + using ManualRateChangeTransaction = TManualRateChangeTransaction ; + using EmbeddedManualRateChangeTransaction = TManualRateChangeTransaction; + using DataModificationTransaction = TDataModificationTransaction ; using EmbeddedDataModificationTransaction = TDataModificationTransaction; using DownloadTransaction = TDownloadTransaction ; using EmbeddedDownloadTransaction = TDownloadTransaction; + using DownloadPaymentTransaction = TDownloadPaymentTransaction ; + using EmbeddedDownloadPaymentTransaction = TDownloadPaymentTransaction; + + using DriveClosureTransaction = TDriveClosureTransaction ; + using EmbeddedDriveClosureTransaction = TDriveClosureTransaction; + using DataModificationApprovalTransaction = TDataModificationApprovalTransaction ; using EmbeddedDataModificationApprovalTransaction = TDataModificationApprovalTransaction; using DataModificationCancelTransaction = TDataModificationCancelTransaction ; using EmbeddedDataModificationCancelTransaction = TDataModificationCancelTransaction; + using FinishDownloadTransaction = TFinishDownloadTransaction ; + using EmbeddedFinishDownloadTransaction = TFinishDownloadTransaction; + using ReplicatorOnboardingTransaction = TReplicatorOnboardingTransaction ; using EmbeddedReplicatorOnboardingTransaction = TReplicatorOnboardingTransaction; + using ReplicatorOffboardingTransaction = TReplicatorOffboardingTransaction ; + using EmbeddedReplicatorOffboardingTransaction = TReplicatorOffboardingTransaction; + + using DeployContractTransaction = TDeployContractTransaction ; + using EmbeddedDeployContractTransaction = TDeployContractTransaction; + + using ManualCallTransaction = TManualCallTransaction ; + using EmbeddedManualCallTransaction = TManualCallTransaction; + + using AutomaticExecutionsPaymentTransaction = TAutomaticExecutionsPaymentTransaction ; + using EmbeddedAutomaticExecutionsPaymentTransaction = TAutomaticExecutionsPaymentTransaction; + + using UnsuccessfulEndBatchExecutionTransaction = TUnsuccessfulEndBatchExecutionTransaction ; + using EmbeddedUnsuccessfulEndBatchExecutionTransaction = TUnsuccessfulEndBatchExecutionTransaction; + + using SuccessfulEndBatchExecutionTransaction = TSuccessfulEndBatchExecutionTransaction ; + using EmbeddedSuccessfulEndBatchExecutionTransaction = TSuccessfulEndBatchExecutionTransaction; + + using StreamStartTransaction = TStreamStartTransaction ; + using EmbeddedStreamStartTransaction = TStreamStartTransaction; + + using StreamFinishTransaction = TStreamFinishTransaction ; + using EmbeddedStreamFinishTransaction = TStreamFinishTransaction; + + using StreamPaymentTransaction = TStreamPaymentTransaction ; + using EmbeddedStreamPaymentTransaction = TStreamPaymentTransaction; + + using AddDbrbProcessTransaction = TAddDbrbProcessTransaction ; + using ReplicatorsCleanupTransaction = TReplicatorsCleanupTransaction ; using EmbeddedReplicatorsCleanupTransaction = TReplicatorsCleanupTransaction; }} diff --git a/include/xpxchaincpp/model/transaction_simple/transactions_page_options.h b/include/xpxchaincpp/model/transaction_simple/transactions_page_options.h index 08485fc..bd92c8b 100644 --- a/include/xpxchaincpp/model/transaction_simple/transactions_page_options.h +++ b/include/xpxchaincpp/model/transaction_simple/transactions_page_options.h @@ -8,6 +8,7 @@ #include #include #include +#include "xpxchaincpp/utils/paginationOrderingOptions.h" namespace xpx_chain_sdk { @@ -16,40 +17,6 @@ namespace xpx_chain_sdk { Unconfirmed, Partial }; - - class PaginationOrderingOptions { - public: - std::map toMap() const { - std::map options; - if (pageNumber.has_value()) { - options.insert(std::pair("pageNumber",std::to_string(pageNumber.value()))); - } - - if (pageSize.has_value()) { - options.insert(std::pair("pageSize",std::to_string(pageSize.value()))); - } - - if (offset.has_value()) { - options.insert(std::pair("offset",offset.value())); - } - - if (sortDirection.has_value()) { - options.insert(std::pair("order",sortDirection.value())); - } - - if (sortField.has_value()) { - options.insert(std::pair("sortField",sortField.value())); - } - return options; - } - - public: - std::optional pageSize; - std::optional pageNumber; - std::optional offset; - std::optional sortField; - std::optional sortDirection; - }; class TransactionsPageOptions { public: diff --git a/include/xpxchaincpp/sdk.h b/include/xpxchaincpp/sdk.h index a6432e0..d6edfa3 100644 --- a/include/xpxchaincpp/sdk.h +++ b/include/xpxchaincpp/sdk.h @@ -23,14 +23,27 @@ #include #include #include +#include +#include +#include +#include #include #include +#include +#include #include #include +#include +#include #include #include +#include #include +#include #include #include +#include +#include +#include #include #include \ No newline at end of file diff --git a/include/xpxchaincpp/service/read_result.h b/include/xpxchaincpp/service/read_result.h index 2894fc8..668a687 100644 --- a/include/xpxchaincpp/service/read_result.h +++ b/include/xpxchaincpp/service/read_result.h @@ -7,16 +7,17 @@ #include #include +#include namespace xpx_chain_sdk { /// Result code for read operation. - enum class ReadResultCode: uint8_t { + enum class ReadResultCode : uint8_t { Success, Not_Enough_Data, Failure }; - + /// Read result. class ReadResult { public: diff --git a/include/xpxchaincpp/types.h b/include/xpxchaincpp/types.h index da170a2..76dbac1 100644 --- a/include/xpxchaincpp/types.h +++ b/include/xpxchaincpp/types.h @@ -31,7 +31,7 @@ namespace xpx_chain_sdk { using MosaicId = uint64_t; using Amount = uint64_t; - + using BlockDuration = uint64_t; constexpr BlockDuration Eternal_Duration = 0; @@ -40,11 +40,13 @@ namespace xpx_chain_sdk { /// Blockchain network identifier. enum class NetworkIdentifier: uint8_t { - Unknown = 0x00, + Zero = 0, Mijin = 0x60, Mijin_Test = 0x90, - Public = 0x68, - Public_Test = 0x98 + Private = 0xC8, + Private_Test = 0xB0, + Public = 0xB8, + Public_Test = 0xA8 }; template diff --git a/include/xpxchaincpp/utils/paginationOrderingOptions.h b/include/xpxchaincpp/utils/paginationOrderingOptions.h new file mode 100644 index 0000000..b32f72d --- /dev/null +++ b/include/xpxchaincpp/utils/paginationOrderingOptions.h @@ -0,0 +1,47 @@ +/** +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include + +namespace xpx_chain_sdk { + + class PaginationOrderingOptions { + public: + std::map toMap() const { + std::map options; + if (pageNumber.has_value()) { + options.insert(std::pair("pageNumber",std::to_string(pageNumber.value()))); + } + + if (pageSize.has_value()) { + options.insert(std::pair("pageSize",std::to_string(pageSize.value()))); + } + + if (offset.has_value()) { + options.insert(std::pair("offset",offset.value())); + } + + if (sortDirection.has_value()) { + options.insert(std::pair("order",sortDirection.value())); + } + + if (sortField.has_value()) { + options.insert(std::pair("sortField",sortField.value())); + } + return options; + } + + public: + std::optional pageSize; + std::optional pageNumber; + std::optional offset; + std::optional sortField; + std::optional sortDirection; + }; +} \ No newline at end of file diff --git a/src/infrastructure/binary/dto/transaction_dto.h b/src/infrastructure/binary/dto/transaction_dto.h index 70cc5dd..12d6690 100644 --- a/src/infrastructure/binary/dto/transaction_dto.h +++ b/src/infrastructure/binary/dto/transaction_dto.h @@ -112,14 +112,14 @@ namespace xpx_chain_sdk { namespace internal { namespace binary { template using TMosaicDefinitionTransactionDTO = VariadicStruct< TBase, - Field, - Field, - Field, - Field, - Field, - Field, desc::VariableSize>>; - - template + Field, + Field, + Field, + Field, + Field, + Field, desc::VariableSize>>; + + template using TMosaicSupplyChangeTransactionDTO = VariadicStruct< TBase, Field, @@ -152,7 +152,13 @@ namespace xpx_chain_sdk { namespace internal { namespace binary { Field, Field, Field, desc::VariableSize>>; - + + template + using TStoragePaymentTransactionDTO = VariadicStruct< + TBase, + Field, + Field>; + template using TTransferTransactionDTO = VariadicStruct< TBase, @@ -188,22 +194,59 @@ namespace xpx_chain_sdk { namespace internal { namespace binary { template using TPrepareBcDriveTransactionDTO = VariadicStruct< TBase, - Field, + Field, + Field, Field>; - + + template + using TCreateLiquidityProviderTransactionDTO = VariadicStruct< + TBase, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field>; + + template + using TManualRateChangeTransactionDTO = VariadicStruct< + TBase, + Field, + Field, + Field, + Field, + Field>; + template using TDataModificationTransactionDTO = VariadicStruct< TBase, Field, Field, - Field>; + Field, + Field>; template using TDownloadTransactionDTO = VariadicStruct< TBase, Field, Field, - Field>; + Field, + Field, + Field, desc::VariableSize>>; + + template + using TDownloadPaymentTransactionDTO = VariadicStruct< + TBase, + Field, + Field, + Field>; + + template + using TDriveClosureTransactionDTO = VariadicStruct< + TBase, + Field>; template using TDataModificationApprovalTransactionDTO = VariadicStruct< @@ -211,8 +254,18 @@ namespace xpx_chain_sdk { namespace internal { namespace binary { Field, Field, Field, - Field, - Field>; + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, desc::VariableSize>, + Field, desc::VariableSize>, + Field, desc::VariableSize>, + Field, desc::VariableSize>>; template using TDataModificationCancelTransactionDTO = VariadicStruct< @@ -220,10 +273,16 @@ namespace xpx_chain_sdk { namespace internal { namespace binary { Field, Field>; + template + using TFinishDownloadTransactionDTO = VariadicStruct< + TBase, + Field, + Field>; + template using TReplicatorOnboardingTransactionDTO = VariadicStruct< TBase, - Field, + Field, Field, Field, Field>; @@ -234,6 +293,79 @@ namespace xpx_chain_sdk { namespace internal { namespace binary { Field, Field, desc::VariableSize>>; + template + using TReplicatorOffboardingTransactionDTO = VariadicStruct< + TBase, + Field>; + + template + using TDeployContractTransactionDTO = VariadicStruct< + TBase, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field>, + Field>, + Field, desc::VariableSize>, + Field, desc::VariableSize>, + Field>, + Field>>; + + template + using TManualCallTransactionDTO = VariadicStruct< + TBase, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field>, + Field>, + Field, desc::VariableSize>, + Field, desc::VariableSize>>; + + template + using TAutomaticExecutionsPaymentTransactionDTO = VariadicStruct< + TBase, + Field, + Field>; + + template + using TStreamStartTransactionDTO = VariadicStruct< + TBase, + Field, + Field, + Field, + Field, + Field, desc::VariableSize>>; + + template + using TStreamFinishTransactionDTO = VariadicStruct< + TBase, + Field, + Field, + Field, + Field>; + + template + using TStreamPaymentTransactionDTO = VariadicStruct< + TBase, + Field, + Field, + Field>; + using AccountLinkTransactionDTO = TAccountLinkTransactionDTO; using EmbeddedAccountLinkTransactionDTO = TAccountLinkTransactionDTO; @@ -257,7 +389,10 @@ namespace xpx_chain_sdk { namespace internal { namespace binary { using SecretProofTransactionDTO = TSecretProofTransactionDTO; using EmbeddedSecretProofTransactionDTO = TSecretProofTransactionDTO; - + + using StoragePaymentTransactionDTO = TStoragePaymentTransactionDTO; + using EmbeddedStoragePaymentTransactionDTO = TStoragePaymentTransactionDTO; + using TransferTransactionDTO = TTransferTransactionDTO; using EmbeddedTransferTransactionDTO = TTransferTransactionDTO; @@ -279,21 +414,57 @@ namespace xpx_chain_sdk { namespace internal { namespace binary { using PrepareBcDriveTransactionDTO = TPrepareBcDriveTransactionDTO; using EmbeddedPrepareBcDriveTransactionDTO = TPrepareBcDriveTransactionDTO; + using CreateLiquidityProviderTransactionDTO = TCreateLiquidityProviderTransactionDTO; + using EmbeddedCreateLiquidityProviderTransactionDTO = TCreateLiquidityProviderTransactionDTO; + + using ManualRateChangeTransactionDTO = TManualRateChangeTransactionDTO; + using EmbeddedManualRateChangeTransactionDTO = TManualRateChangeTransactionDTO; + using DataModificationTransactionDTO = TDataModificationTransactionDTO; using EmbeddedDataModificationTransactionDTO = TDataModificationTransactionDTO; using DownloadTransactionDTO = TDownloadTransactionDTO; using EmbeddedDownloadTransactionDTO = TDownloadTransactionDTO; + using DownloadPaymentTransactionDTO = TDownloadPaymentTransactionDTO; + using EmbeddedDownloadPaymentTransactionDTO = TDownloadPaymentTransactionDTO; + + using DriveClosureTransactionDTO = TDriveClosureTransactionDTO; + using EmbeddedDriveClosureTransactionDTO = TDriveClosureTransactionDTO; + using DataModificationApprovalTransactionDTO = TDataModificationApprovalTransactionDTO; using EmbeddedDataModificationApprovalTransactionDTO = TDataModificationApprovalTransactionDTO; using DataModificationCancelTransactionDTO = TDataModificationCancelTransactionDTO; using EmbeddedDataModificationCancelTransactionDTO = TDataModificationCancelTransactionDTO; + using FinishDownloadTransactionDTO = TFinishDownloadTransactionDTO; + using EmbeddedFinishDownloadTransactionDTO = TFinishDownloadTransactionDTO; + using ReplicatorOnboardingTransactionDTO = TReplicatorOnboardingTransactionDTO; using EmbeddedReplicatorOnboardingTransactionDTO = TReplicatorOnboardingTransactionDTO; + using ReplicatorOffboardingTransactionDTO = TReplicatorOffboardingTransactionDTO; + using EmbeddedReplicatorOffboardingTransactionDTO = TReplicatorOffboardingTransactionDTO; + + using DeployContractTransactionDTO = TDeployContractTransactionDTO; + using EmbeddedDeployContractTransactionDTO = TDeployContractTransactionDTO; + + using ManualCallTransactionDTO = TManualCallTransactionDTO; + using EmbeddedManualCallTransactionDTO = TManualCallTransactionDTO; + + using AutomaticExecutionsPaymentTransactionDTO = TAutomaticExecutionsPaymentTransactionDTO; + using EmbeddedAutomaticExecutionsPaymentTransactionDTO = TAutomaticExecutionsPaymentTransactionDTO; + + using StreamStartTransactionDTO = TStreamStartTransactionDTO; + using EmbeddedStreamStartTransactionDTO = TStreamStartTransactionDTO; + + using StreamFinishTransactionDTO = TStreamFinishTransactionDTO; + using EmbeddedStreamFinishTransactionDTO = TStreamFinishTransactionDTO; + + using StreamPaymentTransactionDTO = TStreamPaymentTransactionDTO; + using EmbeddedStreamPaymentTransactionDTO = TStreamPaymentTransactionDTO; + using ReplicatorsCleanupTransactionDTO = TReplicatorsCleanupTransactionDTO; using EmbeddedReplicatorsCleanupTransactionDTO = TReplicatorsCleanupTransactionDTO; }}} diff --git a/src/infrastructure/binary/offsets.h b/src/infrastructure/binary/offsets.h index 88089f1..db08d2b 100644 --- a/src/infrastructure/binary/offsets.h +++ b/src/infrastructure/binary/offsets.h @@ -26,5 +26,5 @@ namespace xpx_chain_sdk { namespace internal { namespace binary { constexpr size_t Embedded_Tx_Type_Start = 38; // 2 bytes constexpr size_t Aggregate_Tx_Payload_Size_Start = 120; // 4 bytes - constexpr size_t Aggregate_Tx_Payload_Start = 124; + constexpr size_t Aggregate_Tx_Payload_Start = 126; }}} diff --git a/src/infrastructure/json/dto/download_channels_page_dto.h b/src/infrastructure/json/dto/download_channels_page_dto.h new file mode 100644 index 0000000..6a9b12b --- /dev/null +++ b/src/infrastructure/json/dto/download_channels_page_dto.h @@ -0,0 +1,26 @@ +/* +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +*/ + +#pragma once + +#include +#include "infrastructure/utils/variadic_struct.h" +#include "infrastructure/json/uint32.h" +#include "infrastructure/json/uint64.h" +#include "infrastructure/json/dto/storage_dto.h" + +namespace xpx_chain_sdk::internal::json::dto::download_channels_page { + + using PaginationDto = VariadicStruct< + Field, + Field, + Field, + Field>; + + using DownloadChannelsPageDto = VariadicStruct< + Field>, + Field>; +} diff --git a/src/infrastructure/json/dto/drives_page_dto.h b/src/infrastructure/json/dto/drives_page_dto.h new file mode 100644 index 0000000..8e17981 --- /dev/null +++ b/src/infrastructure/json/dto/drives_page_dto.h @@ -0,0 +1,26 @@ +/* +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +*/ + +#pragma once + +#include +#include "infrastructure/utils/variadic_struct.h" +#include "infrastructure/json/uint32.h" +#include "infrastructure/json/uint64.h" +#include "infrastructure/json/dto/storage_dto.h" + +namespace xpx_chain_sdk::internal::json::dto::drives_page { + + using PaginationDto = VariadicStruct< + Field, + Field, + Field, + Field>; + + using DrivesPageDto = VariadicStruct< + Field>, + Field>; +} diff --git a/src/infrastructure/json/dto/error_message_dto.h b/src/infrastructure/json/dto/error_message_dto.h new file mode 100644 index 0000000..f2aa0bb --- /dev/null +++ b/src/infrastructure/json/dto/error_message_dto.h @@ -0,0 +1,17 @@ +/* +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +*/ + +#pragma once + +#include +#include "infrastructure/utils/variadic_struct.h" + +namespace xpx_chain_sdk::internal::json::dto { + + using ErrorMessageDto = VariadicStruct< + Field, + Field >; +} diff --git a/src/infrastructure/json/dto/liquidity_provider_dto.h b/src/infrastructure/json/dto/liquidity_provider_dto.h new file mode 100644 index 0000000..efa9ea4 --- /dev/null +++ b/src/infrastructure/json/dto/liquidity_provider_dto.h @@ -0,0 +1,45 @@ +/* +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +*/ + +#pragma once + +#include "infrastructure/utils/variadic_struct.h" +#include "infrastructure/json/uint64.h" +#include "infrastructure/json/descriptors.h" +#include + +namespace xpx_chain_sdk::internal::json::dto { + + using Uint64 = xpx_chain_sdk::internal::json::Uint64; + using Uint32 = xpx_chain_sdk::internal::json::Uint32; + + using RateDataDto = VariadicStruct< + Field, + Field >; + + using TurnoverDataDto = VariadicStruct< + Field, + Field>; + + using LiquidityProviderDataDto = VariadicStruct< + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field > >; + + using LiquidityProviderDto = VariadicStruct< + Field >; + + using MultipleLiquidityProvidersDto = std::vector; +} diff --git a/src/infrastructure/json/dto/liquidity_providers_page_dto.h b/src/infrastructure/json/dto/liquidity_providers_page_dto.h new file mode 100644 index 0000000..ac5bf29 --- /dev/null +++ b/src/infrastructure/json/dto/liquidity_providers_page_dto.h @@ -0,0 +1,26 @@ +/* +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +*/ + +#pragma once + +#include +#include "infrastructure/utils/variadic_struct.h" +#include "infrastructure/json/uint32.h" +#include "infrastructure/json/uint64.h" +#include "infrastructure/json/dto/liquidity_provider_dto.h" + +namespace xpx_chain_sdk::internal::json::dto::liquidity_providers_page { + + using PaginationDto = VariadicStruct< + Field, + Field, + Field, + Field>; + + using LiquidityProvidersPageDto = VariadicStruct< + Field>, + Field>; +} diff --git a/src/infrastructure/json/dto/network_config_dto.h b/src/infrastructure/json/dto/network_config_dto.h index 3768fe3..66fb9d9 100644 --- a/src/infrastructure/json/dto/network_config_dto.h +++ b/src/infrastructure/json/dto/network_config_dto.h @@ -7,7 +7,7 @@ #pragma once #include -#include +#include #include #include #include diff --git a/src/infrastructure/json/dto/replicators_page_dto.h b/src/infrastructure/json/dto/replicators_page_dto.h new file mode 100644 index 0000000..93a7ec1 --- /dev/null +++ b/src/infrastructure/json/dto/replicators_page_dto.h @@ -0,0 +1,26 @@ +/* +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +*/ + +#pragma once + +#include +#include "infrastructure/utils/variadic_struct.h" +#include "infrastructure/json/uint32.h" +#include "infrastructure/json/uint64.h" +#include "infrastructure/json/dto/storage_dto.h" + +namespace xpx_chain_sdk::internal::json::dto::replicators_page { + + using PaginationDto = VariadicStruct< + Field, + Field, + Field, + Field>; + + using ReplicatorsPageDto = VariadicStruct< + Field>, + Field>; +} diff --git a/src/infrastructure/json/dto/storage_dto.h b/src/infrastructure/json/dto/storage_dto.h new file mode 100644 index 0000000..f5c384d --- /dev/null +++ b/src/infrastructure/json/dto/storage_dto.h @@ -0,0 +1,122 @@ +/* +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +*/ + +#pragma once + +#include "infrastructure/utils/variadic_struct.h" +#include "infrastructure/json/uint64.h" +#include "infrastructure/json/descriptors.h" +#include + +namespace xpx_chain_sdk::internal::json::dto { + + using Uint64 = xpx_chain_sdk::internal::json::Uint64; + using Uint32 = xpx_chain_sdk::internal::json::Uint32; + + using ActiveDataModificationDto = VariadicStruct< + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field >; + + using CompletedDataModificationDto = VariadicStruct< + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field >; + + using ConfirmedUsedSizeDto = VariadicStruct< + Field, + Field >; + + using ShardDto = VariadicStruct< + Field, + Field > >; + + using VerificationDto = VariadicStruct< + Field, + Field, + Field, + Field, desc::Optional >>; + + using DownloadShardDto = VariadicStruct< + Field >; + + using UploadInfoDto = VariadicStruct< + Field, + Field>; + + using DataModificationShardDto = VariadicStruct< + Field, + Field>, + Field>, + Field>; + + using DriveDataDto = VariadicStruct< + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field >, + Field >, + Field >, + Field >, + Field >, + Field, + Field >, + Field > >; + + using DriveDto = VariadicStruct< + Field >; + + using MultipleDrivesDto = std::vector; + + using DriveInfoDto = VariadicStruct< + Field, + Field, + Field, + Field>; + + using ReplicatorDataDto = VariadicStruct< + Field, + Field, + Field>, + Field >>; + + using ReplicatorDto = VariadicStruct< + Field >; + + using CumulativePaymentDto = VariadicStruct< + Field, + Field>; + + using DownloadChannelDataDto = VariadicStruct< + Field, + Field, + Field, + Field, + Field, + Field, + Field>, + Field>, + Field >>; + + using DownloadChannelDto = VariadicStruct< + Field >; +} diff --git a/src/infrastructure/json/dto/supercontract_v2_dto.h b/src/infrastructure/json/dto/supercontract_v2_dto.h new file mode 100644 index 0000000..fc15dc9 --- /dev/null +++ b/src/infrastructure/json/dto/supercontract_v2_dto.h @@ -0,0 +1,94 @@ + +/* +*** Copyright 2019 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +*/ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include "mosaic_dto.h" + +namespace xpx_chain_sdk::internal::json::dto { + using internal::json::Uint64; + + using AutomaticExecutionsInfoDto = VariadicStruct< + Field, + Field, + Field, + Field, + Field, + Field, + Field + >; + + using ServicePaymentDto = VariadicStruct< + Field, + Field + >; + + using ContractCallDto = VariadicStruct< + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field >, + Field + >; + + using CompletedCallDto = VariadicStruct< + Field, + Field, + Field, + Field, + Field + >; + + using ProofOfExecutionDto = VariadicStruct< + Field, + Field >, + Field > + >; + + using ExecutorInfoDto = VariadicStruct< + Field, + Field, + Field + >; + + using BatchDto = VariadicStruct< + Field, + Field, + Field >, + Field > + >; + + using SuperContractV2Dto = VariadicStruct< + Field, + Field, + Field, + Field, + Field, + Field, + Field >, + Field >, + Field >, + Field > + > + > + >; +} + diff --git a/src/infrastructure/json/dto/transaction_dto.h b/src/infrastructure/json/dto/transaction_dto.h index 0f8e5d3..4f9b4e0 100644 --- a/src/infrastructure/json/dto/transaction_dto.h +++ b/src/infrastructure/json/dto/transaction_dto.h @@ -40,9 +40,13 @@ namespace xpx_chain_sdk::internal::json::dto { // Common Dtos //========================================================================== + + using Uint32 = xpx_chain_sdk::internal::json::Uint32; + using Uint64 = xpx_chain_sdk::internal::json::Uint64; + using MosaicPropertyDto = VariadicStruct< Field, - Field>; + Field>; using CosignatureDto = VariadicStruct< Field, @@ -57,10 +61,34 @@ namespace xpx_chain_sdk::internal::json::dto { Field, Field>; + using ExtendedCallDigestDto = VariadicStruct< + Field, + Field, + Field, + Field, + Field>; + + using RawProofOfExecutionDto = VariadicStruct< + Field, + Field>, + Field>, + Field>, + Field>>; + + using CallPaymentDto = VariadicStruct< + Field, + Field>; + + using OpinionDto = VariadicStruct< + Field, + Field, + Field>, + Field>>; + //Transaction meta Dtos - using Uint32 = xpx_chain_sdk::internal::json::Uint32; + //========================================================================== using TransactionInfoDto = VariadicStruct< Field, @@ -97,12 +125,12 @@ namespace xpx_chain_sdk::internal::json::dto { using EmbeddedTransactionDto = VariadicStruct< Field, - Field, + Field, Field>; using AggregateTransactionDto = VariadicStruct< TransactionDto, - Field, + Field, Field >, Field > >; @@ -129,24 +157,22 @@ namespace xpx_chain_sdk::internal::json::dto { template using TMosaicDefinitionTransactionDto = VariadicStruct< TBase, - Field, - Field, - Field, - Field, - Field > >; + Field, + Field, + Field > >; template using TMosaicSupplyChangeTransactionDto = VariadicStruct< TBase, - Field, + Field, Field, - Field>; + Field>; template using TRegisterNamespaceTransactionDto = VariadicStruct< TBase, Field, - Field, + Field, Field, Field, Field >; @@ -154,8 +180,8 @@ namespace xpx_chain_sdk::internal::json::dto { template using TSecretLockTransactionDto = VariadicStruct< TBase, - Field, - Field, + Field, + Field, Field, Field, Field, @@ -168,8 +194,14 @@ namespace xpx_chain_sdk::internal::json::dto { Field, Field > >; + template + using TStoragePaymentTransactionDto = VariadicStruct< + TBase, + Field, + Field>; + using TransferTransactionMessageDto = VariadicStruct< - Field, + Field, Field >; template @@ -193,7 +225,7 @@ namespace xpx_chain_sdk::internal::json::dto { template using TMosaicAliasTransactionDto = VariadicStruct< TAliasTransactionBaseDto, - Field>; + Field>; template using TAccountPropertyTransactionDto = VariadicStruct< @@ -205,51 +237,185 @@ namespace xpx_chain_sdk::internal::json::dto { template using TPrepareBcDriveTransactionDto = VariadicStruct< TBase, - Field, + Field, + Field, Field >; + template + using TCreateLiquidityProviderTransactionDto = VariadicStruct< + TBase, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field >; + + template + using TManualRateChangeTransactionDto = VariadicStruct< + TBase, + Field, + Field, + Field, + Field, + Field >; + template using TDataModificationTransactionDto = VariadicStruct< TBase, - Field, - Field, - Field >; + Field, + Field, + Field, + Field >; template using TDownloadTransactionDto = VariadicStruct< TBase, - Field, - Field, - Field >; + Field, + Field, + Field, + Field, + Field >>; + + template + using TDownloadPaymentTransactionDto = VariadicStruct< + TBase, + Field, + Field, + Field>; + + template + using TDriveClosureTransactionDto = VariadicStruct< + TBase, + Field>; template using TDataModificationApprovalTransactionDto = VariadicStruct< TBase, - Field, - Field, - Field, - Field, - Field>; + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field>, + Field>, + Field>, + Field>>; template using TDataModificationCancelTransactionDto = VariadicStruct< TBase, - Field, - Field>; + Field, + Field>; + + template + using TFinishDownloadTransactionDto = VariadicStruct< + TBase, + Field, + Field>; template using TReplicatorOnboardingTransactionDto = VariadicStruct< TBase, - Field, + Field, Field, Field, Field>; - template - using TReplicatorsCleanupTransactionDto = VariadicStruct< - TBase, - Field, - Field>>; + template + using TReplicatorOffboardingTransactionDto = VariadicStruct< + TBase, + Field>; + + template + using TDeployContractTransactionDto = VariadicStruct< + TBase, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field, + Field>, + Field>, + Field, + Field>; + + template + using TManualCallTransactionDto = VariadicStruct< + TBase, + Field, + Field, + Field, + Field, + Field, + Field>, + Field>>; + + template + using TAutomaticExecutionsPaymentTransactionDto = VariadicStruct< + TBase, + Field, + Field>; + + template + using TUnsuccessfulEndBatchExecutionTransactionDto = VariadicStruct< + TBase, + Field, + Field, + Field, + Field>, + Field>>; + + template + using TSuccessfulEndBatchExecutionTransactionDto = VariadicStruct< + TUnsuccessfulEndBatchExecutionTransaction, + Field, + Field, + Field, + Field>>; + + template + using TStreamStartTransactionDto = VariadicStruct< + TStreamStartTransaction, + Field, + Field, + Field, + Field>; + + template + using TStreamFinishTransactionDto = VariadicStruct< + TStreamFinishTransaction, + Field, + Field, + Field, + Field>; + + template + using TStreamPaymentTransactionDto = VariadicStruct< + TStreamPaymentTransaction, + Field, + Field, + Field>; + + template + using TReplicatorsCleanupTransactionDto = VariadicStruct< + TBase, + Field, + Field>>; + + template + using TAddDbrbProcessTransactionDto = VariadicStruct; using AccountLinkTransactionDto = TAccountLinkTransactionDto; using EmbeddedAccountLinkTransactionDto = TAccountLinkTransactionDto; @@ -275,6 +441,9 @@ namespace xpx_chain_sdk::internal::json::dto { using SecretProofTransactionDto = TSecretProofTransactionDto; using EmbeddedSecretProofTransactionDto = TSecretProofTransactionDto; + using StoragePaymentTransactionDto = TStoragePaymentTransactionDto; + using EmbeddedStoragePaymentTransactionDto = TStoragePaymentTransactionDto; + using TransferTransactionDto = TTransferTransactionDto; using EmbeddedTransferTransactionDto = TTransferTransactionDto; @@ -305,21 +474,65 @@ namespace xpx_chain_sdk::internal::json::dto { using PrepareBcDriveTransactionDto = TPrepareBcDriveTransactionDto; using EmbeddedPrepareBcDriveTransactionDto = TPrepareBcDriveTransactionDto; + using CreateLiquidityProviderTransactionDto = TCreateLiquidityProviderTransactionDto; + using EmbeddedCreateLiquidityProviderTransactionDto = TCreateLiquidityProviderTransactionDto; + + using ManualRateChangeTransactionDto = TManualRateChangeTransactionDto; + using EmbeddedManualRateChangeTransactionDto = TManualRateChangeTransactionDto; + using DataModificationTransactionDto = TDataModificationTransactionDto; using EmbeddedDataModificationTransactionDto = TDataModificationTransactionDto; using DownloadTransactionDto = TDownloadTransactionDto; using EmbeddedDownloadTransactionDto = TDownloadTransactionDto; + using DownloadPaymentTransactionDto = TDownloadPaymentTransactionDto; + using EmbeddedDownloadPaymentTransactionDto = TDownloadPaymentTransactionDto; + + using DriveClosureTransactionDto = TDriveClosureTransactionDto; + using EmbeddedDriveClosureTransactionDto = TDriveClosureTransactionDto; + using DataModificationApprovalTransactionDto = TDataModificationApprovalTransactionDto; using EmbeddedDataModificationApprovalTransactionDto = TDataModificationApprovalTransactionDto; using DataModificationCancelTransactionDto = TDataModificationCancelTransactionDto; using EmbeddedDataModificationCancelTransactionDto = TDataModificationCancelTransactionDto; + using FinishDownloadTransactionDto = TFinishDownloadTransactionDto; + using EmbeddedFinishDownloadTransactionDto = TFinishDownloadTransactionDto; + using ReplicatorOnboardingTransactionDto = TReplicatorOnboardingTransactionDto; using EmbeddedReplicatorOnboardingTransactionDto = TReplicatorOnboardingTransactionDto; + using ReplicatorOffboardingTransactionDto = TReplicatorOffboardingTransactionDto; + using EmbeddedReplicatorOffboardingTransactionDto = TReplicatorOffboardingTransactionDto; + + using DeployContractTransactionDto = TDeployContractTransactionDto; + using EmbeddedDeployContractTransactionDto = TDeployContractTransactionDto; + + using ManualCallTransactionDto = TManualCallTransactionDto; + using EmbeddedManualCallTransactionDto = TManualCallTransactionDto; + + using AutomaticExecutionsPaymentTransactionDto = TAutomaticExecutionsPaymentTransactionDto; + using EmbeddedAutomaticExecutionsPaymentTransactionDto = TAutomaticExecutionsPaymentTransactionDto; + + using UnsuccessfulEndBatchExecutionTransactionDto = TUnsuccessfulEndBatchExecutionTransactionDto; + using EmbeddedUnsuccessfulEndBatchExecutionTransactionDto = TUnsuccessfulEndBatchExecutionTransactionDto; + + using SuccessfulEndBatchExecutionTransactionDto = TSuccessfulEndBatchExecutionTransactionDto; + using EmbeddedSuccessfulEndBatchExecutionTransactionDto = TSuccessfulEndBatchExecutionTransactionDto; + + using StreamStartTransactionDto = TStreamStartTransactionDto; + using EmbeddedStreamStartTransactionDto = TStreamStartTransactionDto; + + using StreamFinishTransactionDto = TStreamFinishTransactionDto; + using EmbeddedStreamFinishTransactionDto = TStreamFinishTransactionDto; + + using StreamPaymentTransactionDto = TStreamPaymentTransactionDto; + using EmbeddedStreamPaymentTransactionDto = TStreamPaymentTransactionDto; + + using AddDbrbProcessTransactionDto = TAddDbrbProcessTransactionDto; + using ReplicatorsCleanupTransactionDto = TReplicatorsCleanupTransactionDto; using EmbeddedReplicatorsCleanupTransactionDto = TReplicatorsCleanupTransactionDto; } diff --git a/src/infrastructure/network/http.cpp b/src/infrastructure/network/http.cpp index f56b0bb..d0da94b 100644 --- a/src/infrastructure/network/http.cpp +++ b/src/infrastructure/network/http.cpp @@ -54,7 +54,7 @@ std::string _performHTTPRequest_internal( request.set(http::field::content_type, "application/json"); if (method == HTTPRequestMethod::PUT || method == HTTPRequestMethod::POST) { - request.set(http::field::content_length, request_body.size()); + request.set(http::field::content_length, std::to_string(request_body.size())); // request.set(http::field::body, request_body); request.body() = request_body; request.prepare_payload(); @@ -67,10 +67,14 @@ std::string _performHTTPRequest_internal( http::read(stream, buffer, response); if (response.result() == http::status::found) { - auto path = response.at("Location").to_string(); +#if BOOST_VERSION >= 108100 + auto path = response.at("Location"); +#else + auto path = response.at("Location").to_string(); +#endif return _performHTTPRequest_internal(stream, method, host, port, path, request_body); } else if (response.result() != http::status::ok && response.result() != http::status::accepted ) { - throw xpx_chain_sdk::InvalidRequest(static_cast(response.result())); + throw xpx_chain_sdk::InvalidRequest(response.body(), static_cast(response.result())); } return response.body(); @@ -108,12 +112,12 @@ std::string _performHTTPRequest( } } -RequestParamsBuilder::RequestParamsBuilder(std::shared_ptr config) : +RequestParamsBuilder::RequestParamsBuilder(const xpx_chain_sdk::Config& config) : _method(HTTPRequestMethod::GET), - _secure(config->useSSL), - _host(config->nodeAddress), - _port(config->port), - _basePath(config->basePath) + _secure(config.useSSL), + _host(config.nodeAddress), + _port(config.port), + _basePath(config.basePath) {} RequestParamsBuilder& RequestParamsBuilder::setMethod(HTTPRequestMethod method) { diff --git a/src/infrastructure/network/http.h b/src/infrastructure/network/http.h index dc07ccc..f4c9813 100644 --- a/src/infrastructure/network/http.h +++ b/src/infrastructure/network/http.h @@ -8,6 +8,7 @@ #include "context.h" #include +#include #include namespace xpx_chain_sdk::internal::network { @@ -29,7 +30,7 @@ namespace xpx_chain_sdk::internal::network { class RequestParamsBuilder { public: - explicit RequestParamsBuilder(std::shared_ptr config); + explicit RequestParamsBuilder(const xpx_chain_sdk::Config& config); RequestParamsBuilder& setMethod(HTTPRequestMethod method); RequestParamsBuilder& setSecurity(bool secure); diff --git a/src/infrastructure/network/websocket.cpp b/src/infrastructure/network/websocket.cpp index b27d69a..314f688 100644 --- a/src/infrastructure/network/websocket.cpp +++ b/src/infrastructure/network/websocket.cpp @@ -4,83 +4,126 @@ *** license that can be found in the LICENSE file. **/ +#ifndef __EMSCRIPTEN__ + #include "websocket.h" namespace xpx_chain_sdk::internal::network { WsClient::WsClient( - std::shared_ptr config, - std::shared_ptr context, + const Config& config, + std::shared_ptr context, Callback connectionCallback, Callback receiverCallback, ErrorCallback errorCallback) : - _config(config), _context(context), _io_context(boost::asio::io_context()), - _resolver(boost::asio::ip::tcp::resolver(_io_context)), - _ws(boost::asio::make_strand(_io_context)), + _config(config), + _buffer(std::make_shared()), + _outgoingQueue(), + _io_context(context), + _resolver(boost::asio::make_strand(*_io_context)), + _ws(boost::asio::make_strand(*_io_context)), _connectionCallback(connectionCallback), _receiverCallback(receiverCallback), _errorCallback(errorCallback) {} WsClient::~WsClient() { - disconnect(); + } - void WsClient::connect(uint64_t onResolveHostTimeoutSec) { - if (!isConnected()) { - _resolver.async_resolve(_config->nodeAddress, - _config->port, - [pThis = shared_from_this(), onResolveHostTimeoutSec] ( - boost::beast::error_code errorCode, - const boost::asio::ip::tcp::resolver::results_type &resultsType) { - pThis->onResolve(errorCode, resultsType, onResolveHostTimeoutSec); - }); - - boost::thread thread([pThis = shared_from_this()]() { pThis->_io_context.run(); }); - thread.detach(); - } + void WsClient::connect() { + boost::asio::post(*_io_context, [pThis = shared_from_this()] { + pThis->_resolver.async_resolve(pThis->_config.nodeAddress, + pThis->_config.port, + boost::asio::bind_executor(*pThis->_io_context, [pThis] ( + boost::beast::error_code errorCode, + const boost::asio::ip::tcp::resolver::results_type &resultsType) { + pThis->onResolve(errorCode, resultsType); + })); + }); } void WsClient::disconnect() { - if (isConnected()) { - _ws.async_close(boost::beast::websocket::close_code::normal, - [pThis = shared_from_this()](auto errorCode){ - pThis->onClose(errorCode); - }); - } + boost::asio::post(*_io_context, [pThis = shared_from_this()] { + auto disconnectTask = [pThis]() { + if (pThis->isConnected()) { + pThis->_ws.async_close(boost::beast::websocket::close_code::normal, + boost::asio::bind_executor(*pThis->_io_context, [pThis](auto errorCode) { + pThis->onClose(errorCode); + })); + } + }; + + if (pThis->_outgoingQueue.empty()) { + disconnectTask(); + } else { + pThis->_postponedDisconnect = disconnectTask; + } + }); } - void WsClient::send(const std::string& json) { - if (isConnected()) { - _ws.async_write( - boost::asio::buffer(json), - [pThis = shared_from_this()](auto errorCode, auto bytesTransferred) { - pThis->onWrite(errorCode, bytesTransferred); - }); - } + void WsClient::send(const std::string& json, std::function onSuccess, + std::function onError) { + boost::asio::post(*_io_context, [pThis = shared_from_this(), json, onSuccess, onError] { + pThis->_outgoingQueue.push_back({ json, { onSuccess, onError } }); + if (pThis->_outgoingQueue.size() > 1) { + return; + } + + pThis->doWrite(); + }); } - bool WsClient::isConnected() { + bool WsClient::isConnected() const { return _ws.is_open(); } + void WsClient::doWrite() { + _ws.async_write( + boost::asio::buffer(_outgoingQueue[0].first), + boost::asio::bind_executor(*_io_context, [pThis = shared_from_this()](auto errorCode, auto bytesTransferred) { + if (errorCode) { + boost::asio::post(*pThis->_io_context, [errorCode, onError = pThis->_outgoingQueue[0].second.second]() { + if (onError) { + onError(errorCode); + } + }); + + return pThis->_outgoingQueue.pop_front(); + } + + boost::asio::post(*pThis->_io_context, [onSuccess = pThis->_outgoingQueue[0].second.first]() { + if (onSuccess) { + onSuccess(); + } + }); + + pThis->_outgoingQueue.pop_front(); + if (!pThis->_outgoingQueue.empty()) { + pThis->doWrite(); + return; + } + + if (pThis->_postponedDisconnect) { + pThis->_postponedDisconnect(); + } + })); + } + void WsClient::onResolve( boost::beast::error_code errorCode, - const boost::asio::ip::tcp::resolver::results_type& resultsType, - uint64_t onResolveHostTimeoutSec) { + const boost::asio::ip::tcp::resolver::results_type& resultsType) { if (errorCode) { return _errorCallback(errorCode); } - boost::beast::get_lowest_layer(_ws).expires_after(std::chrono::seconds(onResolveHostTimeoutSec)); + boost::beast::get_lowest_layer(_ws).expires_after(std::chrono::seconds(_config.wsOptions.resolveHostTimeoutSecSec)); boost::beast::get_lowest_layer(_ws).async_connect( - resultsType, [pThis = shared_from_this()] (auto ec, const auto& et) { - pThis->onConnect(ec, et); - }); + resultsType, boost::asio::bind_executor(*_io_context, [pThis = shared_from_this()] (auto ec, const auto&) { + pThis->onConnect(ec); + })); } - void WsClient::onConnect( - boost::beast::error_code errorCode, - const boost::asio::ip::tcp::resolver::results_type::endpoint_type&) { + void WsClient::onConnect(boost::beast::error_code errorCode) { if (errorCode) { return _errorCallback(errorCode); } @@ -89,63 +132,59 @@ namespace xpx_chain_sdk::internal::network { // the websocket stream has its own timeout system. boost::beast::get_lowest_layer(_ws).expires_never(); - // Set suggested timeout settings for the websocket - _ws.set_option(boost::beast::websocket::stream_base::timeout::suggested(boost::beast::role_type::client)); - - const std::string host = _config->nodeAddress + ":" + _config->port; - - std::cout << "websocket: connection established: " << host << std::endl; + boost::beast::websocket::stream_base::timeout options{}; + options.handshake_timeout = _config.wsOptions.handshakeTimeoutSec; + options.idle_timeout = _config.wsOptions.idleTimeoutSec; + options.keep_alive_pings = _config.wsOptions.keepAlivePings; + _ws.set_option(options); // Perform the websocket handshake - _ws.async_handshake(host, _config->baseWsPath,[pThis = shared_from_this()](auto ec){ + const std::string host = _config.nodeAddress + ":" + _config.port; + _ws.async_handshake(host, _config.baseWsPath, boost::asio::bind_executor(*_io_context, [pThis = shared_from_this()](auto ec) { pThis->onHandshake(ec); - }); + })); } void WsClient::onHandshake(boost::beast::error_code errorCode) { if (errorCode) { return _errorCallback(errorCode); } else { - std::shared_ptr pBuffer(new boost::beast::flat_buffer); + std::cout << "websocket: connection established: " << _config.nodeAddress << ":" << _config.port << std::endl; _ws.async_read( - *pBuffer, - [pThis = shared_from_this(), pBuffer] ( + *_buffer, + boost::asio::bind_executor(*_io_context, [pThis = shared_from_this()] ( boost::beast::error_code ec, - std::size_t bytesTransferred) { + std::size_t) { if (ec) { return pThis->_errorCallback(ec); } - boost::ignore_unused(bytesTransferred); - const std::string json = boost::beast::buffers_to_string(pBuffer->data()); + const std::string json = boost::beast::buffers_to_string(pThis->_buffer->data()); pThis->_connectionCallback(json); + pThis->readNext(); - }); + })); } } - void WsClient::onRead(boost::beast::error_code errorCode, std::shared_ptr pData, std::size_t bytesTransferred) { + void WsClient::onRead(boost::beast::error_code errorCode) { + // If socket is closed last async_read operation aborted + if (boost::asio::error::operation_aborted == errorCode) { + return; + } + if (errorCode) { return _errorCallback(errorCode); } - boost::ignore_unused(bytesTransferred); - - const std::string json = boost::beast::buffers_to_string(pData->data()); + const std::string json = boost::beast::buffers_to_string(_buffer->data()); _receiverCallback(json); readNext(); } - void WsClient::onWrite(boost::beast::error_code errorCode, std::size_t bytesTransferred) { - if (errorCode) { - return _errorCallback(errorCode); - } - - boost::ignore_unused(bytesTransferred); - } - void WsClient::onClose(boost::beast::error_code errorCode) { + boost::beast::get_lowest_layer(_ws).close(); if (errorCode) { return _errorCallback(errorCode); } else { @@ -154,12 +193,14 @@ namespace xpx_chain_sdk::internal::network { } void WsClient::readNext() { - std::shared_ptr pBuffer(new boost::beast::flat_buffer); + _buffer->consume(_buffer->size()); _ws.async_read( - *pBuffer, - [pThis = shared_from_this(), pBuffer](boost::beast::error_code errorCode, - std::size_t bytesTransferred) { - pThis->onRead(errorCode, pBuffer, bytesTransferred); - }); + *_buffer, + boost::asio::bind_executor(*_io_context, [pThis = shared_from_this()]( + boost::beast::error_code errorCode, std::size_t) { + pThis->onRead(errorCode); + })); } -} \ No newline at end of file +} + +#endif // #ifndef __EMSCRIPTEN__ diff --git a/src/infrastructure/network/websocket.h b/src/infrastructure/network/websocket.h index 944cb2a..ca5af5d 100644 --- a/src/infrastructure/network/websocket.h +++ b/src/infrastructure/network/websocket.h @@ -5,15 +5,20 @@ **/ #pragma once +#ifdef __EMSCRIPTEN__ +#include "websocket_wasm.h" +#else + #include #include #include #include -#include +#include #include #include #include #include +#include #include #include #include @@ -29,45 +34,44 @@ namespace xpx_chain_sdk::internal::network { class WsClient : public std::enable_shared_from_this { public: WsClient( - std::shared_ptr config, - std::shared_ptr context, + const Config& config, + std::shared_ptr context, Callback connectionCallback, Callback receiverCallback, ErrorCallback errorCallback); + ~WsClient(); - void connect(uint64_t onResolveHostTimeoutSec = 30); + void connect(); void disconnect(); - void send(const std::string& json); - bool isConnected(); + void send(const std::string& json, std::function onSuccess, + std::function onError); + bool isConnected() const; private: + void doWrite(); void onResolve( boost::beast::error_code errorCode, - const boost::asio::ip::tcp::resolver::results_type& resultsType, - uint64_t onResolveHostTimeoutSec); - void onConnect( - boost::beast::error_code errorCode, - const boost::asio::ip::tcp::resolver::results_type::endpoint_type& endpointType); + const boost::asio::ip::tcp::resolver::results_type& resultsType); + + void onConnect(boost::beast::error_code errorCode); void onHandshake(boost::beast::error_code errorCode); - void onRead( - boost::beast::error_code errorCode, - std::shared_ptr data, - std::size_t bytes_transferred); + void onRead(boost::beast::error_code errorCode); void readNext(); - void onWrite( - boost::beast::error_code errorCode, - std::size_t bytesTransferred); void onClose(boost::beast::error_code errorCode); private: - std::shared_ptr _config; - std::shared_ptr _context; - boost::asio::io_context _io_context; + const Config& _config; + std::shared_ptr _buffer; + std::deque, std::function>>> _outgoingQueue; + std::shared_ptr _io_context; + std::function _postponedDisconnect; boost::asio::ip::tcp::resolver _resolver; boost::beast::websocket::stream _ws; Callback _connectionCallback; Callback _receiverCallback; ErrorCallback _errorCallback; }; -} \ No newline at end of file +} + +#endif // #else __EMSCRIPTEN__ diff --git a/src/infrastructure/network/websocket_wasm.cpp b/src/infrastructure/network/websocket_wasm.cpp new file mode 100644 index 0000000..87c1153 --- /dev/null +++ b/src/infrastructure/network/websocket_wasm.cpp @@ -0,0 +1,142 @@ +/** +*** Copyright 2024 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ + +#ifdef __EMSCRIPTEN__ + +#include "websocket_wasm.h" + +namespace xpx_chain_sdk::internal::network { + + + //{"uid": "MR4GD5MHKIE6MEFLAYMMG2NPD5COGILF"} + + static EM_BOOL onopen( int eventType, const EmscriptenWebSocketOpenEvent *websocketEvent, void *userData ) + { + emscripten_log( EM_LOG_CONSOLE, "WsClient: opened" ); + return EM_TRUE; + } + + static EM_BOOL onerror( int eventType, const EmscriptenWebSocketErrorEvent *websocketEvent, void *userData ) + { + emscripten_log( EM_LOG_ERROR, "WsClient: error: %d", eventType ); + + WsClient* pThis = (WsClient*) userData; + + boost::beast::error_code errorCode( boost::system::errc::connection_refused, boost::system::generic_category()); + pThis->onError(errorCode); + return EM_TRUE; + } + + static EM_BOOL onclose( int eventType, const EmscriptenWebSocketCloseEvent *websocketEvent, void *userData ) + { + emscripten_log( EM_LOG_CONSOLE, "WsClient: closed: %d", eventType ); + return EM_TRUE; + } + + bool isFirstMessage = true; + + static EM_BOOL onmessage( int eventType, const EmscriptenWebSocketMessageEvent *websocketEvent, void *userData ) + { + emscripten_log( EM_LOG_CONSOLE, "WsClient: message: %d", (char*)websocketEvent->data ); + + WsClient* pThis = (WsClient*) userData; + + if (! websocketEvent->isText) + { + emscripten_log( EM_LOG_ERROR, "WsClient: message must be text" ); + + boost::beast::error_code errorCode( boost::system::errc::protocol_error, boost::system::generic_category()); + pThis->onError(errorCode); + return EM_TRUE; + } + + if ( isFirstMessage ) + { + pThis->onConnectionUid( std::string( (char*)websocketEvent->data, websocketEvent->numBytes) ); + isFirstMessage = false; + return EM_TRUE; + } + + pThis->onMessage( std::string( (char*)websocketEvent->data, websocketEvent->numBytes) ); + + return EM_TRUE; + } + + + WsClient::WsClient( + const Config& config, + std::shared_ptr context, + Callback connectionCallback, + Callback receiverCallback, + ErrorCallback errorCallback) : + _config(config), + _io_context(context), + _connectionCallback(connectionCallback), + _receiverCallback(receiverCallback), + _errorCallback(errorCallback) + { + } + + WsClient::~WsClient() { + + } + + void WsClient::connect() + { + if ( !emscripten_websocket_is_supported() ) + { + emscripten_log( EM_LOG_ERROR, "WsClient: !emscripten_websocket_is_supported()" ); + + boost::beast::error_code errorCode( boost::system::errc::wrong_protocol_type, boost::system::generic_category()); + onError(errorCode); + return; + } + + m_wsUrl = "wss://" + _config.nodeAddress + ":" + _config.port; + EmscriptenWebSocketCreateAttributes ws_attrs = { + m_wsUrl.c_str(), + NULL, + EM_FALSE //EM_TRUE + }; + + m_ws = emscripten_websocket_new( &ws_attrs ); + emscripten_websocket_set_onopen_callback( m_ws, this, onopen ); + emscripten_websocket_set_onerror_callback( m_ws, this, onerror); + emscripten_websocket_set_onclose_callback( m_ws, this, onclose); + emscripten_websocket_set_onmessage_callback( m_ws, this, onmessage); + } + + void WsClient::disconnect() + { + auto result = emscripten_websocket_close( m_ws, 0, 0 ); + emscripten_websocket_delete( m_ws ); + if (result) + { + emscripten_log( EM_LOG_ERROR, "WsClient::disconnect: failed emscripten_websocket_close(): %d", result); + } + } + + void WsClient::send(const std::string& json, std::function onSuccess, + std::function onError) + { + auto result = emscripten_websocket_send_utf8_text( m_ws, json.c_str() ); + + if (result) + { + boost::beast::error_code errorCode( boost::system::errc::protocol_error, boost::system::generic_category()); + onError(errorCode); + return; + } + onSuccess(); + } + + bool WsClient::isConnected() const { + return m_ws > 0 ; + } + +} + +#endif // #ifdef __EMSCRIPTEN__ diff --git a/src/infrastructure/network/websocket_wasm.h b/src/infrastructure/network/websocket_wasm.h new file mode 100644 index 0000000..8920724 --- /dev/null +++ b/src/infrastructure/network/websocket_wasm.h @@ -0,0 +1,72 @@ +/** +*** Copyright 2024 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace xpx_chain_sdk::internal::network { + + class Context; + + using Callback = std::function; + using ErrorCallback = std::function; + + class WsClient : public std::enable_shared_from_this + { + EMSCRIPTEN_WEBSOCKET_T m_ws = 0; + std::string m_wsUrl; + + public: + WsClient( + const Config& config, + std::shared_ptr context, + Callback connectionCallback, + Callback receiverCallback, + ErrorCallback errorCallback); + + ~WsClient(); + + void connect(); + void disconnect(); + void send(const std::string& json, std::function onSuccess, + std::function onError); + bool isConnected() const; + + void onError( boost::beast::error_code errorCode ) + { + _io_context->post( [this,errorCode=errorCode] { _errorCallback(errorCode); } ); + } + + void onMessage( const std::string& json ) + { + _io_context->post( [this,json=json] {_receiverCallback(json); } ); + } + + void onConnectionUid( const std::string& json ) + { + _io_context->post( [this,json=json] { _connectionCallback(json); } ); + } + + private: + const Config& _config; + // std::deque, std::function>>> _outgoingQueue; + std::shared_ptr _io_context; + std::function _postponedDisconnect; + Callback _connectionCallback; + Callback _receiverCallback; + ErrorCallback _errorCallback; + }; +} diff --git a/src/infrastructure/utils/deserialization_json.cpp b/src/infrastructure/utils/deserialization_json.cpp index db706a2..684427b 100644 --- a/src/infrastructure/utils/deserialization_json.cpp +++ b/src/infrastructure/utils/deserialization_json.cpp @@ -273,6 +273,20 @@ namespace xpx_chain_sdk::internal::json::dto { break; } + case TransactionType::Storage_Payment: { + VariadicStruct > t_dto; + + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + auto transaction = fromDto( + t_dto.value<"transaction"_>()); + result = std::make_shared(transaction); + break; + } + case TransactionType::Account_Link: { VariadicStruct > t_dto; @@ -303,6 +317,30 @@ namespace xpx_chain_sdk::internal::json::dto { break; } + case TransactionType::Create_Liquidity_Provider: { + VariadicStruct > t_dto; + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + auto transaction = fromDto(t_dto.value<"transaction"_>()); + result = std::make_shared(transaction); + break; + } + + case TransactionType::Manual_Rate_Change: { + VariadicStruct > t_dto; + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + auto transaction = fromDto(t_dto.value<"transaction"_>()); + result = std::make_shared(transaction); + break; + } + case TransactionType::Data_Modification: { VariadicStruct > t_dto; auto err = Parser::Read(t_dto, jsonStr); @@ -327,6 +365,30 @@ namespace xpx_chain_sdk::internal::json::dto { break; } + case TransactionType::Download_Payment: { + VariadicStruct > t_dto; + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + auto transaction = fromDto(t_dto.value<"transaction"_>()); + result = std::make_shared(transaction); + break; + } + + case TransactionType::Drive_Closure: { + VariadicStruct > t_dto; + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + auto transaction = fromDto(t_dto.value<"transaction"_>()); + result = std::make_shared(transaction); + break; + } + case TransactionType::Data_Modification_Approval: { VariadicStruct > t_dto; auto err = Parser::Read(t_dto, jsonStr); @@ -351,6 +413,18 @@ namespace xpx_chain_sdk::internal::json::dto { break; } + case TransactionType::Finish_Download: { + VariadicStruct > t_dto; + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + auto transaction = fromDto(t_dto.value<"transaction"_>()); + result = std::make_shared(transaction); + break; + } + case TransactionType::Replicator_Onboarding: { VariadicStruct > t_dto; auto err = Parser::Read(t_dto, jsonStr); @@ -363,6 +437,128 @@ namespace xpx_chain_sdk::internal::json::dto { break; } + case TransactionType::Replicator_Offboarding: { + VariadicStruct > t_dto; + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + auto transaction = fromDto(t_dto.value<"transaction"_>()); + result = std::make_shared(transaction); + break; + } + + case TransactionType::Deploy_Contract: { + VariadicStruct > t_dto; + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + auto transaction = fromDto(t_dto.value<"transaction"_>()); + result = std::make_shared(transaction); + break; + } + + case TransactionType::Manual_Call: { + VariadicStruct > t_dto; + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + auto transaction = fromDto(t_dto.value<"transaction"_>()); + result = std::make_shared(transaction); + break; + } + + case TransactionType::Automatic_Executions_Payment: { + VariadicStruct > t_dto; + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + auto transaction = fromDto(t_dto.value<"transaction"_>()); + result = std::make_shared(transaction); + break; + } + + case TransactionType::Unsuccessful_End_Batch_Execution: { + VariadicStruct > t_dto; + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + auto transaction = fromDto(t_dto.value<"transaction"_>()); + result = std::make_shared(transaction); + break; + } + + case TransactionType::Successful_End_Batch_Execution: { + VariadicStruct > t_dto; + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + auto transaction = fromDto(t_dto.value<"transaction"_>()); + result = std::make_shared(transaction); + break; + } + + case TransactionType::Stream_Start: { + VariadicStruct > t_dto; + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + auto transaction = fromDto(t_dto.value<"transaction"_>()); + result = std::make_shared(transaction); + break; + } + + case TransactionType::Stream_Finish: { + VariadicStruct > t_dto; + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + auto transaction = fromDto(t_dto.value<"transaction"_>()); + result = std::make_shared(transaction); + break; + } + + case TransactionType::Stream_Payment: { + VariadicStruct > t_dto; + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + auto transaction = fromDto(t_dto.value<"transaction"_>()); + result = std::make_shared(transaction); + break; + } + + case TransactionType::Add_Dbrb_Process: { + VariadicStruct > t_dto; + auto err = Parser::Read(t_dto, jsonStr); + if (!err) { + XPX_CHAIN_SDK_THROW_1(serialization_error, "Cannot parse JSON. Error with:", err.invalidField()); + } + + AddDbrbProcessTransaction transaction; + EXTRACT_TRANSACTION(transaction, t_dto.value<"transaction"_>()) + result = std::make_shared(transaction); + + break; + } + case TransactionType::Replicators_Cleanup: { VariadicStruct > t_dto; auto err = Parser::Read(t_dto, jsonStr); @@ -602,6 +798,95 @@ namespace xpx_chain_sdk::internal::json::dto { return mbdto; } + template<> + SuperContractV2 fromDto (const SuperContractV2Dto& dto) { + SuperContractV2 scInfo; + auto scDto = dto.value<"supercontract"_>(); + scInfo.data.contractKey = scDto.value<"contractKey"_>(); + scInfo.data.executionPaymentKey = scDto.value<"executionPaymentKey"_>(); + scInfo.data.assignee = scDto.value<"assignee"_>(); + scInfo.data.creator = scDto.value<"creator"_>(); + scInfo.data.deploymentBaseModificationId = scDto.value<"deploymentBaseModificationId"_>(); + + // AutomaticExecutionsInfo + AutomaticExecutionsInfo automaticExecutionsInfo; + auto automaticExecutionsInfoDto = scDto.value<"automaticExecutionsInfo"_>(); + automaticExecutionsInfo.automaticExecutionFileName = automaticExecutionsInfoDto.value<"automaticExecutionFileName"_>(); + automaticExecutionsInfo.automaticExecutionsFunctionName = automaticExecutionsInfoDto.value<"automaticExecutionsFunctionName"_>(); + automaticExecutionsInfo.automaticExecutionsNextBlockToCheck = automaticExecutionsInfoDto.value<"automaticExecutionsNextBlockToCheck"_>(); + automaticExecutionsInfo.automaticExecutionCallPayment = automaticExecutionsInfoDto.value<"automaticExecutionCallPayment"_>(); + automaticExecutionsInfo.automaticDownloadCallPayment = automaticExecutionsInfoDto.value<"automaticDownloadCallPayment"_>(); + automaticExecutionsInfo.automatedExecutionsNumber = automaticExecutionsInfoDto.value<"automatedExecutionsNumber"_>(); + automaticExecutionsInfo.automaticExecutionsPrepaidSince = automaticExecutionsInfoDto.value<"automaticExecutionsPrepaidSince"_>(); + scInfo.data.automaticExecutionsInfo = automaticExecutionsInfo; + + // Requested calls + for(const auto& requestedCallDto : scDto.value<"requestedCalls"_>()) { + ContractCall requestedCall; + requestedCall.callId = requestedCallDto.value<"callId"_>(); + requestedCall.caller = requestedCallDto.value<"caller"_>(); + requestedCall.fileName = requestedCallDto.value<"fileName"_>(); + requestedCall.functionName = requestedCallDto.value<"functionName"_>(); + requestedCall.actualArguments = requestedCallDto.value<"actualArguments"_>(); + requestedCall.executionCallPayment = requestedCallDto.value<"executionCallPayment"_>(); + requestedCall.downloadCallPayment = requestedCallDto.value<"downloadCallPayment"_>(); + requestedCall.blockHeight = requestedCallDto.value<"blockHeight"_>(); + + // Service payments + for(const auto& servicePaymentDto : requestedCallDto.value<"servicePayments"_>()) { + ServicePayment servicePayment; + servicePayment.mosaicId = servicePaymentDto.value<"id"_>(); + servicePayment.amount = servicePaymentDto.value<"amount"_>(); + + requestedCall.servicePayments.emplace_back(servicePayment); + } + + scInfo.data.requestedCalls.emplace_back(requestedCall); + } + + // Executors info + for(const auto& executorInfoDto : scDto.value<"executorsInfo"_>()) { + ExecutorInfo executorInfo; + executorInfo.nextBatchToApprove = executorInfoDto.value<"nextBatchToApprove"_>(); + + // Proof of execution + ProofOfExecution proofOfExecution; + auto poEx = executorInfoDto.value<"poEx"_>(); + proofOfExecution.startBatchId = poEx.value<"startBatchId"_>(); + proofOfExecution.T = poEx.value<"T"_>(); + proofOfExecution.R = poEx.value<"R"_>(); + executorInfo.poEx = proofOfExecution; + + scInfo.data.executorsInfo.emplace(executorInfoDto.value<"replicatorKey"_>(), executorInfo); + } + + // Batches + for(const auto& batchDto : scDto.value<"batches"_>()) { + Batch batch; + batch.success = batchDto.value<"success"_>(); + batch.poExVerificationInformation = batchDto.value<"poExVerificationInformation"_>(); + + // Completed calls + for(const auto& completedCallDto : batchDto.value<"completedCalls"_>()) { + CompletedCall completedCall; + completedCall.callId = completedCallDto.value<"callId"_>(); + completedCall.caller = completedCallDto.value<"caller"_>(); + completedCall.status = completedCallDto.value<"status"_>(); + completedCall.executionWork = completedCallDto.value<"executionWork"_>(); + completedCall.downloadWork = completedCallDto.value<"downloadWork"_>(); + batch.completedCalls.emplace_back(completedCall); + } + scInfo.data.batches.emplace(batchDto.value<"batchId"_>(), batch); + } + + // Released transactions + for(const auto& releasedTransactionDto : scDto.value<"releasedTransactions"_>()) { + scInfo.data.releasedTransactions.emplace(releasedTransactionDto); + } + + return scInfo; + } + // Accounts template<> @@ -742,7 +1027,382 @@ namespace xpx_chain_sdk::internal::json::dto { return {fromDto(dto.value<"blockchainUpgrade"_>())}; } - /// Transaction Meta + template<> + DriveData fromDto(const DriveDataDto &dto) { + DriveData driveData; + driveData.multisig = dto.value<"multisig"_>(); + driveData.multisigAddress = dto.value<"multisigAddress"_>(); + driveData.owner = dto.value<"owner"_>(); + driveData.rootHash = dto.value<"rootHash"_>(); + driveData.size = dto.value<"size"_>(); + driveData.usedSizeBytes = dto.value<"usedSizeBytes"_>(); + driveData.metaFilesSizeBytes = dto.value<"metaFilesSizeBytes"_>(); + driveData.replicatorCount = dto.value<"replicatorCount"_>(); + + for (const auto& activeModificationDto : dto.value<"activeDataModifications"_>()) { + driveData.activeDataModifications.push_back(fromDto(activeModificationDto)); + } + + for (const auto& completedDataModificationDto : dto.value<"completedDataModifications"_>()) { + driveData.completedDataModifications.push_back(fromDto(completedDataModificationDto)); + } + + for (const auto& confirmedUsedSizeDto : dto.value<"confirmedUsedSizes"_>()) { + driveData.confirmedUsedSizes.push_back(fromDto(confirmedUsedSizeDto)); + } + + driveData.replicators = dto.value<"replicators"_>(); + driveData.offboardingReplicators = dto.value<"offboardingReplicators"_>(); + driveData.verification = fromDto(dto.value<"verification"_>()); + + for (const auto& downloadShardDto : dto.value<"downloadShards"_>()) { + driveData.downloadShards.push_back(fromDto(downloadShardDto)); + } + + for (const auto& dataModificationShardDto : dto.value<"dataModificationShards"_>()) { + driveData.dataModificationShards.push_back(fromDto(dataModificationShardDto)); + } + + return driveData; + } + + template<> + Drive fromDto(const DriveDto &dto) { + Drive drive; + drive.data = fromDto(dto.value<"drive"_>()); + return drive; + } + + template<> + MultipleDrives fromDto(const MultipleDrivesDto &dto) { + MultipleDrives mddto; + + for (auto &driveDto: dto) { + Drive drive = fromDto(driveDto); + mddto.drives.push_back(drive); + } + + return mddto; + } + + template<> + xpx_chain_sdk::drives_page::Pagination fromDto(const dto::drives_page::PaginationDto &dto) { + xpx_chain_sdk::drives_page::Pagination pagination { + dto.value<"totalEntries"_>(), + dto.value<"pageNumber"_>(), + dto.value<"pageSize"_>(), + dto.value<"totalPages"_>() + }; + + return pagination; + } + + template<> + xpx_chain_sdk::drives_page::DrivesPage fromDto(const drives_page::DrivesPageDto &dto) { + xpx_chain_sdk::drives_page::DrivesPage drivesPage; + drivesPage.pagination = fromDto(dto.value<"pagination"_>()); + + for(const auto& driveDto : dto.value<"data"_>()) { + drivesPage.data.drives.push_back(fromDto(driveDto)); + } + + return drivesPage; + } + + template<> + ActiveDataModification fromDto(const ActiveDataModificationDto &dto) { + ActiveDataModification activeDataModification; + activeDataModification.dataModification.id = dto.value<"id"_>(); + activeDataModification.dataModification.owner = dto.value<"owner"_>(); + activeDataModification.dataModification.downloadDataCdi = dto.value<"downloadDataCdi"_>(); + activeDataModification.dataModification.expectedUploadSize = dto.value<"expectedUploadSize"_>(); + activeDataModification.dataModification.actualUploadSize = dto.value<"actualUploadSize"_>(); + activeDataModification.dataModification.folderName = dto.value<"folderName"_>(); + activeDataModification.dataModification.readyForApproval = dto.value<"readyForApproval"_>(); + activeDataModification.dataModification.isStream = dto.value<"isStream"_>(); + + return activeDataModification; + } + + template<> + CompletedDataModification fromDto(const CompletedDataModificationDto &dto) { + CompletedDataModification completedDataModification; + completedDataModification.dataModification.id = dto.value<"id"_>(); + completedDataModification.dataModification.owner = dto.value<"owner"_>(); + completedDataModification.dataModification.downloadDataCdi = dto.value<"downloadDataCdi"_>(); + completedDataModification.dataModification.expectedUploadSize = dto.value<"expectedUploadSize"_>(); + completedDataModification.dataModification.actualUploadSize = dto.value<"actualUploadSize"_>(); + completedDataModification.dataModification.folderName = dto.value<"folderName"_>(); + completedDataModification.dataModification.readyForApproval = dto.value<"readyForApproval"_>(); + completedDataModification.state = dto.value<"state"_>(); + completedDataModification.success = dto.value<"success"_>(); + + return completedDataModification; + } + + template<> + ConfirmedUsedSize fromDto(const ConfirmedUsedSizeDto &dto) { + ConfirmedUsedSize confirmedUsedSize; + confirmedUsedSize.replicator = dto.value<"replicator"_>(); + confirmedUsedSize.size = dto.value<"size"_>(); + + return confirmedUsedSize; + } + + template<> + Shard fromDto(const ShardDto &dto) { + Shard shard; + shard.id = dto.value<"id"_>(); + shard.replicators = dto.value<"replicators"_>(); + + return shard; + } + + template<> + Verification fromDto(const VerificationDto &dto) { + Verification verification; + verification.verificationTrigger = dto.value<"verificationTrigger"_>(); + verification.expiration = dto.value<"expiration"_>(); + verification.duration = dto.value<"duration"_>(); + + for (const auto& shard : dto.value<"shards"_>()) { + verification.shards.push_back(fromDto(shard)); + } + + return verification; + } + + template<> + DownloadShard fromDto(const DownloadShardDto &dto) { + DownloadShard downloadShard; + downloadShard.downloadChannelId = dto.value<"downloadChannelId"_>(); + + return downloadShard; + } + + template<> + DataModificationShard fromDto(const DataModificationShardDto &dto) { + DataModificationShard dataModificationShard; + dataModificationShard.replicator = dto.value<"replicator"_>(); + + for (const auto& uploadInfoDto : dto.value<"actualShardReplicators"_>()) { + dataModificationShard.actualShardReplicators.push_back(fromDto(uploadInfoDto)); + } + + for (const auto& uploadInfoDto : dto.value<"formerShardReplicators"_>()) { + dataModificationShard.formerShardReplicators.push_back(fromDto(uploadInfoDto)); + } + + dataModificationShard.ownerUpload = dto.value<"ownerUpload"_>(); + + return dataModificationShard; + } + + template<> + UploadInfo fromDto(const UploadInfoDto &dto) { + UploadInfo uploadInfo; + uploadInfo.key = dto.value<"key"_>(); + uploadInfo.uploadSize = dto.value<"uploadSize"_>(); + + return uploadInfo; + } + + template<> + Replicator fromDto(const ReplicatorDto &dto) { + Replicator replicator; + replicator.data = fromDto(dto.value<"replicator"_>()); + return replicator; + } + + template<> + ReplicatorData fromDto(const ReplicatorDataDto &dto) { + ReplicatorData replicatorData; + replicatorData.key = dto.value<"key"_>(); + replicatorData.version = dto.value<"version"_>(); + replicatorData.downloadChannels = dto.value<"downloadChannels"_>(); + + for (const auto& driveInfoDto : dto.value<"drives"_>()) { + replicatorData.drivesInfo.push_back(fromDto(driveInfoDto)); + } + + return replicatorData; + } + + template<> + DriveInfo fromDto(const DriveInfoDto &dto) { + DriveInfo driveInfo; + driveInfo.drive = dto.value<"drive"_>(); + driveInfo.lastApprovedDataModificationId = dto.value<"lastApprovedDataModificationId"_>(); + driveInfo.initialDownloadWork = dto.value<"initialDownloadWork"_>(); + driveInfo.lastCompletedCumulativeDownloadWork = dto.value<"lastCompletedCumulativeDownloadWork"_>(); + + return driveInfo; + } + + template<> + xpx_chain_sdk::replicators_page::Pagination fromDto(const dto::replicators_page::PaginationDto &dto) { + xpx_chain_sdk::replicators_page::Pagination pagination { + dto.value<"totalEntries"_>(), + dto.value<"pageNumber"_>(), + dto.value<"pageSize"_>(), + dto.value<"totalPages"_>() + }; + + return pagination; + } + + template<> + xpx_chain_sdk::replicators_page::ReplicatorsPage fromDto(const replicators_page::ReplicatorsPageDto &dto) { + xpx_chain_sdk::replicators_page::ReplicatorsPage replicatorsPage; + replicatorsPage.pagination = fromDto(dto.value<"pagination"_>()); + + for(const auto& replicatorDto : dto.value<"data"_>()) { + replicatorsPage.data.replicators.push_back(fromDto(replicatorDto)); + } + + return replicatorsPage; + } + + template<> + DownloadChannel fromDto(const DownloadChannelDto &dto) { + DownloadChannel downloadChannel; + downloadChannel.data = fromDto(dto.value<"downloadChannelInfo"_>()); + return downloadChannel; + } + + template<> + DownloadChannelData fromDto(const DownloadChannelDataDto &dto) { + DownloadChannelData downloadChannelData; + downloadChannelData.id = dto.value<"id"_>(); + downloadChannelData.consumer = dto.value<"consumer"_>(); + downloadChannelData.drive = dto.value<"drive"_>(); + downloadChannelData.downloadSizeMegabytes = dto.value<"downloadSizeMegabytes"_>(); + downloadChannelData.downloadApprovalCount = dto.value<"downloadApprovalCount"_>(); + downloadChannelData.finished = dto.value<"finished"_>(); + downloadChannelData.listOfPublicKeys = dto.value<"listOfPublicKeys"_>(); + downloadChannelData.shardReplicators = dto.value<"shardReplicators"_>(); + + for(const auto& cumulativePaymentDto : dto.value<"cumulativePayments"_>()) { + downloadChannelData.cumulativePayments.push_back(fromDto(cumulativePaymentDto)); + } + + return downloadChannelData; + } + + template<> + CumulativePayment fromDto(const CumulativePaymentDto &dto) { + CumulativePayment cumulativePayment; + cumulativePayment.replicator = dto.value<"replicator"_>(); + cumulativePayment.payment = dto.value<"payment"_>(); + return cumulativePayment; + } + + template<> + xpx_chain_sdk::download_channels_page::Pagination fromDto(const dto::download_channels_page::PaginationDto &dto) { + xpx_chain_sdk::download_channels_page::Pagination pagination { + dto.value<"totalEntries"_>(), + dto.value<"pageNumber"_>(), + dto.value<"pageSize"_>(), + dto.value<"totalPages"_>() + }; + + return pagination; + } + + template<> + xpx_chain_sdk::download_channels_page::DownloadChannelsPage fromDto(const download_channels_page::DownloadChannelsPageDto &dto) { + xpx_chain_sdk::download_channels_page::DownloadChannelsPage downloadChannelsPage; + downloadChannelsPage.pagination = fromDto(dto.value<"pagination"_>()); + + for(const auto& channelDto : dto.value<"data"_>()) { + downloadChannelsPage.data.channels.push_back(fromDto(channelDto)); + } + + return downloadChannelsPage; + } + + template<> + RateData fromDto(const RateDataDto &dto) { + RateData rateData; + rateData.currencyAmount = dto.value<"currencyAmount"_>(); + rateData.mosaicAmount = dto.value<"mosaicAmount"_>(); + return rateData; + } + + template<> + TurnoverData fromDto(const TurnoverDataDto &dto) { + TurnoverData turnoverData; + turnoverData.turnover = dto.value<"turnover"_>(); + turnoverData.rate = fromDto(dto.value<"rate"_>()); + return turnoverData; + } + + template<> + LiquidityProviderData fromDto(const LiquidityProviderDataDto &dto) { + LiquidityProviderData liquidityProviderData; + liquidityProviderData.mosaicId = dto.value<"mosaicId"_>(); + liquidityProviderData.providerKey = dto.value<"providerKey"_>(); + liquidityProviderData.owner = dto.value<"owner"_>(); + liquidityProviderData.additionallyMinted = dto.value<"additionallyMinted"_>(); + liquidityProviderData.slashingAccount = dto.value<"slashingAccount"_>(); + liquidityProviderData.slashingPeriod = dto.value<"slashingPeriod"_>(); + liquidityProviderData.windowSize = dto.value<"windowSize"_>(); + liquidityProviderData.creationHeight = dto.value<"creationHeight"_>(); + liquidityProviderData.alpha = dto.value<"alpha"_>(); + liquidityProviderData.beta = dto.value<"beta"_>(); + liquidityProviderData.recentTurnover = fromDto(dto.value<"recentTurnover"_>()); + + for(const auto& turnoverDto : dto.value<"turnoverHistory"_>()) { + liquidityProviderData.turnoverHistory.push_back(fromDto(turnoverDto)); + } + + return liquidityProviderData; + } + + template<> + LiquidityProvider fromDto(const LiquidityProviderDto &dto) { + LiquidityProvider liquidityProvider; + liquidityProvider.data = fromDto(dto.value<"liquidityProvider"_>()); + return liquidityProvider; + } + + template<> + MultipleLiquidityProviders fromDto(const MultipleLiquidityProvidersDto &dto) { + MultipleLiquidityProviders mldto; + + for (auto &liquidityProviderDto: dto) { + LiquidityProvider liquidityProvider = fromDto(liquidityProviderDto); + mldto.liquidityProviders.push_back(liquidityProvider); + } + + return mldto; + } + + template<> + xpx_chain_sdk::liquidity_providers_page::Pagination fromDto(const dto::liquidity_providers_page::PaginationDto &dto) { + xpx_chain_sdk::liquidity_providers_page::Pagination pagination { + dto.value<"totalEntries"_>(), + dto.value<"pageNumber"_>(), + dto.value<"pageSize"_>(), + dto.value<"totalPages"_>() + }; + + return pagination; + } + + template<> + xpx_chain_sdk::liquidity_providers_page::LiquidityProvidersPage fromDto(const liquidity_providers_page::LiquidityProvidersPageDto &dto) { + xpx_chain_sdk::liquidity_providers_page::LiquidityProvidersPage liquidityProvidersPage; + liquidityProvidersPage.pagination = fromDto(dto.value<"pagination"_>()); + + for(const auto& providerDto : dto.value<"data"_>()) { + liquidityProvidersPage.data.liquidityProviders.push_back(fromDto(providerDto)); + } + + return liquidityProvidersPage; + } + + /// Transaction Meta template<> TransactionInfo fromDto(const TransactionInfoDto& dto) { @@ -811,6 +1471,15 @@ namespace xpx_chain_sdk::internal::json::dto { return transaction; } + template<> + ErrorMessage fromDto(const ErrorMessageDto & dto) { + ErrorMessage errorMessage; + errorMessage.code = dto.value<"code"_>(); + errorMessage.message = dto.value<"message"_>(); + + return errorMessage; + } + template<> xpx_chain_sdk::transactions_page::Pagination fromDto< xpx_chain_sdk::transactions_page::Pagination, @@ -974,12 +1643,10 @@ namespace xpx_chain_sdk::internal::json::dto { EXTRACT_TRANSACTION(transaction, dto) - transaction.nonce = dto.value<"nonce"_>(); + transaction.mosaicNonce = dto.value<"mosaicNonce"_>(); transaction.mosaicId = dto.value<"mosaicId"_>(); - transaction.flags = dto.value<"flags"_>(); - transaction.divisibility = dto.value<"divisibility"_>(); - for(auto & mosaicProperty : dto.value<"optionalProperties"_>()) { - transaction.optionalProperties.push_back(fromDto(mosaicProperty)) ; + for(auto & mosaicProperty : dto.value<"properties"_>()) { + transaction.properties.push_back(fromDto(mosaicProperty)) ; } return transaction; } @@ -1004,7 +1671,6 @@ namespace xpx_chain_sdk::internal::json::dto { EXTRACT_TRANSACTION(transaction, dto) - transaction.namespaceType = dto.value<"namespaceType"_>(); transaction.durationOrParentId = dto.value<"durationOrParentId"_>(); transaction.namespaceId = dto.value<"namespaceId"_>(); @@ -1020,7 +1686,6 @@ namespace xpx_chain_sdk::internal::json::dto { EXTRACT_TRANSACTION(transaction, dto) - transaction.mosaicId = dto.value<"mosaicId"_>(); transaction.amount = dto.value<"amount"_>(); transaction.duration = dto.value<"duration"_>(); @@ -1028,7 +1693,6 @@ namespace xpx_chain_sdk::internal::json::dto { transaction.secret = dto.value<"secret"_>(); transaction.recipient = dto.value<"recipient"_>(); - return transaction; } @@ -1039,15 +1703,25 @@ namespace xpx_chain_sdk::internal::json::dto { EXTRACT_TRANSACTION(transaction, dto) - transaction.hashAlgorithm = dto.value<"hashAlgorithm"_>(); transaction.secret = dto.value<"secret"_>(); transaction.proof = dto.value<"proof"_>(); - return transaction; } + template<> + StoragePaymentTransaction fromDto(const StoragePaymentTransactionDto & dto) { + StoragePaymentTransaction transaction; + + EXTRACT_TRANSACTION(transaction, dto) + + transaction.driveKey = dto.value<"driveKey"_>(); + transaction.storageUnits = dto.value<"storageUnits"_>(); + + return transaction; + } + template<> TransferTransactionMessage fromDto(const TransferTransactionMessageDto & dto) { TransferTransactionMessage message; @@ -1077,7 +1751,6 @@ namespace xpx_chain_sdk::internal::json::dto { EXTRACT_TRANSACTION(transaction, dto) - transaction.aliasAction = dto.value<"aliasAction"_>(); transaction.namespaceId = dto.value<"namespaceId"_>(); @@ -1111,7 +1784,6 @@ namespace xpx_chain_sdk::internal::json::dto { EXTRACT_TRANSACTION(transaction, dto) - transaction.propertyType = dto.value<"propertyType"_>(); transaction.modificationsCount = dto.value<"modificationsCount"_>(); for(auto& accountTransactionPropertyDto : dto.value<"modifications"_>()){ @@ -1127,7 +1799,6 @@ namespace xpx_chain_sdk::internal::json::dto { EXTRACT_TRANSACTION(transaction, dto) - transaction.propertyType = dto.value<"propertyType"_>(); transaction.modificationsCount = dto.value<"modificationsCount"_>(); for(auto& accountTransactionPropertyDto : dto.value<"modifications"_>()){ @@ -1143,7 +1814,6 @@ namespace xpx_chain_sdk::internal::json::dto { EXTRACT_TRANSACTION(transaction, dto) - transaction.propertyType = dto.value<"propertyType"_>(); transaction.modificationsCount = dto.value<"modificationsCount"_>(); for(auto& accountTransactionPropertyDto : dto.value<"modifications"_>()){ @@ -1203,12 +1873,10 @@ namespace xpx_chain_sdk::internal::json::dto { EXTRACT_EMBEDDED_TRANSACTION(transaction, dto) - transaction.nonce = dto.value<"nonce"_>(); + transaction.mosaicNonce = dto.value<"mosaicNonce"_>(); transaction.mosaicId = dto.value<"mosaicId"_>(); - transaction.flags = dto.value<"flags"_>(); - transaction.divisibility = dto.value<"divisibility"_>(); - for(auto & mosaicProperty : dto.value<"optionalProperties"_>()) { - transaction.optionalProperties.push_back(fromDto(mosaicProperty)) ; + for(auto & mosaicProperty : dto.value<"properties"_>()) { + transaction.properties.push_back(fromDto(mosaicProperty)); } return transaction; } @@ -1275,6 +1943,18 @@ namespace xpx_chain_sdk::internal::json::dto { return transaction; } + template<> + EmbeddedStoragePaymentTransaction fromDto(const EmbeddedStoragePaymentTransactionDto & dto) { + EmbeddedStoragePaymentTransaction transaction; + + EXTRACT_EMBEDDED_TRANSACTION(transaction, dto) + + transaction.driveKey = dto.value<"driveKey"_>(); + transaction.storageUnits = dto.value<"storageUnits"_>(); + + return transaction; + } + template<> EmbeddedTransferTransaction fromDto(const EmbeddedTransferTransactionDto & dto) { @@ -1282,7 +1962,6 @@ namespace xpx_chain_sdk::internal::json::dto { EXTRACT_EMBEDDED_TRANSACTION(transaction, dto) - transaction.recipient = dto.value<"recipient"_>(); transaction.message = fromDto(dto.value<"message"_>()); @@ -1300,7 +1979,6 @@ namespace xpx_chain_sdk::internal::json::dto { EXTRACT_EMBEDDED_TRANSACTION(transaction, dto) - transaction.aliasAction = dto.value<"aliasAction"_>(); transaction.namespaceId = dto.value<"namespaceId"_>(); @@ -1374,6 +2052,149 @@ namespace xpx_chain_sdk::internal::json::dto { return transaction; } + template<> + EmbeddedDeployContractTransaction fromDto(const EmbeddedDeployContractTransactionDto& dto) { + EmbeddedDeployContractTransaction transaction; + + EXTRACT_EMBEDDED_TRANSACTION(transaction, dto) + + transaction.driveKey = dto.value<"driveKey"_>(); + transaction.fileName = dto.value<"fileName"_>(); + transaction.functionName = dto.value<"functionName"_>(); + transaction.actualArguments = dto.value<"actualArguments"_>(); + transaction.executionCallPayment = dto.value<"executionCallPayment"_>(); + transaction.downloadCallPayment = dto.value<"downloadCallPayment"_>(); + for(auto& servicePaymentDto : dto.value<"servicePayments"_>()) { + transaction.servicePayments.push_back(fromDto(servicePaymentDto)); + } + transaction.automaticExecutionsFileName = dto.value<"automaticExecutionsFileName"_>(); + transaction.automaticExecutionsFunctionName = dto.value<"automaticExecutionsFunctionName"_>(); + transaction.automaticExecutionsCallPayment = dto.value<"automaticExecutionsCallPayment"_>(); + transaction.automaticDownloadCallPayment = dto.value<"automaticDownloadCallPayment"_>(); + transaction.automaticExecutionsNumber = dto.value<"automaticExecutionsNumber"_>(); + transaction.assignee = dto.value<"assignee"_>(); + + return transaction; + } + + template<> + EmbeddedManualCallTransaction fromDto(const EmbeddedManualCallTransactionDto& dto) { + EmbeddedManualCallTransaction transaction; + + EXTRACT_EMBEDDED_TRANSACTION(transaction, dto) + + transaction.contractKey = dto.value<"contractKey"_>(); + transaction.fileName = dto.value<"fileName"_>(); + transaction.functionName = dto.value<"functionName"_>(); + transaction.actualArguments = dto.value<"actualArguments"_>(); + transaction.executionCallPayment = dto.value<"executionCallPayment"_>(); + transaction.downloadCallPayment = dto.value<"downloadCallPayment"_>(); + for(auto& servicePaymentDto : dto.value<"servicePayments"_>()) { + transaction.servicePayments.push_back(fromDto(servicePaymentDto)); + } + + return transaction; + } + + template<> + EmbeddedAutomaticExecutionsPaymentTransaction fromDto(const EmbeddedAutomaticExecutionsPaymentTransactionDto& dto) { + EmbeddedAutomaticExecutionsPaymentTransaction transaction; + + EXTRACT_EMBEDDED_TRANSACTION(transaction, dto) + + transaction.contractKey = dto.value<"contractKey"_>(); + transaction.automaticExecutionsNumber = dto.value<"automaticExecutionsNumber"_>(); + + return transaction; + } + + template<> + ExtendedCallDigest fromDto(const ExtendedCallDigestDto & dto) { + ExtendedCallDigest result = { + dto.value<"callId"_>(), + dto.value<"manual"_>(), + dto.value<"block"_>(), + dto.value<"status"_>(), + dto.value<"releasedTransactionHash"_>() + }; + return result; + } + + template<> + Opinion fromDto(const OpinionDto & dto) { + Opinion result = { + dto.value<"publicKey"_>(), + dto.value<"signature"_>() + }; + + for(auto& poExDto : dto.value<"poEx"_>()) { + RawProofOfExecution poEx{ + poExDto.value<"startBatchId"_>(), + poExDto.value<"T"_>(), + poExDto.value<"R"_>(), + poExDto.value<"F"_>(), + poExDto.value<"K"_>() + }; + result.poEx.push_back(poEx); + } + + for(auto& callPaymentDto : dto.value<"callPayments"_>()) { + CallPayment callPayment{ + callPaymentDto.value<"executionPayment"_>(), + callPaymentDto.value<"downloadPayment"_>() + }; + result.callPayments.push_back(callPayment); + } + + return result; + } + + template<> + EmbeddedUnsuccessfulEndBatchExecutionTransaction fromDto(const EmbeddedUnsuccessfulEndBatchExecutionTransactionDto& dto) { + EmbeddedUnsuccessfulEndBatchExecutionTransaction transaction; + + EXTRACT_EMBEDDED_TRANSACTION(transaction, dto) + + transaction.contractKey = dto.value<"contractKey"_>(); + transaction.batchId = dto.value<"batchId"_>(); + transaction.automaticExecutionsNextBlockToCheck = dto.value<"automaticExecutionsNextBlockToCheck"_>(); + + for(auto& digestDto : dto.value<"callDigests"_>()) { + transaction.callDigests.push_back(fromDto(digestDto)); + } + + for(auto& opinionDto : dto.value<"opinions"_>()) { + transaction.opinions.push_back(fromDto(opinionDto)); + } + + return transaction; + } + + template<> + EmbeddedSuccessfulEndBatchExecutionTransaction fromDto(const EmbeddedSuccessfulEndBatchExecutionTransactionDto& dto) { + EmbeddedSuccessfulEndBatchExecutionTransaction transaction; + + EXTRACT_EMBEDDED_TRANSACTION(transaction, dto) + + transaction.contractKey = dto.value<"contractKey"_>(); + transaction.batchId = dto.value<"batchId"_>(); + transaction.storageHash = dto.value<"storageHash"_>(); + transaction.usedSizeBytes = dto.value<"usedSizeBytes"_>(); + transaction.metaFilesSizeBytes = dto.value<"metaFilesSizeBytes"_>(); + transaction.automaticExecutionsNextBlockToCheck = dto.value<"automaticExecutionsNextBlockToCheck"_>(); + transaction.proofOfExecutionVerificationInformation = dto.value<"proofOfExecutionVerificationInformation"_>(); + + for(auto& digestDto : dto.value<"callDigests"_>()) { + transaction.callDigests.push_back(fromDto(digestDto)); + } + + for(auto& opinionDto : dto.value<"opinions"_>()) { + transaction.opinions.push_back(fromDto(opinionDto)); + } + + return transaction; + } + template<> PrepareBcDriveTransaction fromDto(const PrepareBcDriveTransactionDto & dto) { PrepareBcDriveTransaction transaction; @@ -1381,11 +2202,45 @@ namespace xpx_chain_sdk::internal::json::dto { EXTRACT_TRANSACTION(transaction, dto) transaction.driveSize = dto.value<"driveSize"_>(); + transaction.verificationFeeAmount = dto.value<"verificationFeeAmount"_>(); transaction.replicatorCount = dto.value<"replicatorCount"_>(); return transaction; } + template<> + CreateLiquidityProviderTransaction fromDto(const CreateLiquidityProviderTransactionDto & dto) { + CreateLiquidityProviderTransaction transaction; + + EXTRACT_TRANSACTION(transaction, dto) + + transaction.providerMosaicId = dto.value<"providerMosaicId"_>(); + transaction.currencyDeposit = dto.value<"currencyDeposit"_>(); + transaction.initialMosaicsMinting = dto.value<"initialMosaicsMinting"_>(); + transaction.slashingPeriod = dto.value<"slashingPeriod"_>(); + transaction.windowSize = dto.value<"windowSize"_>(); + transaction.slashingAccount = dto.value<"slashingAccount"_>(); + transaction.alpha = dto.value<"alpha"_>(); + transaction.beta = dto.value<"beta"_>(); + + return transaction; + } + + template<> + ManualRateChangeTransaction fromDto(const ManualRateChangeTransactionDto & dto) { + ManualRateChangeTransaction transaction; + + EXTRACT_TRANSACTION(transaction, dto) + + transaction.providerMosaicId = dto.value<"providerMosaicId"_>(); + transaction.currencyBalanceIncrease = dto.value<"currencyBalanceIncrease"_>(); + transaction.currencyBalanceChange = dto.value<"currencyBalanceChange"_>(); + transaction.mosaicBalanceIncrease = dto.value<"mosaicBalanceIncrease"_>(); + transaction.mosaicBalanceChange = dto.value<"mosaicBalanceChange"_>(); + + return transaction; + } + template<> DataModificationTransaction fromDto(const DataModificationTransactionDto & dto) { DataModificationTransaction transaction; @@ -1395,6 +2250,7 @@ namespace xpx_chain_sdk::internal::json::dto { transaction.driveKey = dto.value<"driveKey"_>(); transaction.downloadDataCdi = dto.value<"downloadDataCdi"_>(); transaction.uploadSize = dto.value<"uploadSize"_>(); + transaction.feedbackFeeAmount = dto.value<"feedbackFeeAmount"_>(); return transaction; } @@ -1407,11 +2263,36 @@ namespace xpx_chain_sdk::internal::json::dto { transaction.driveKey = dto.value<"driveKey"_>(); transaction.downloadSize = dto.value<"downloadSize"_>(); - transaction.transactionFee = dto.value<"transactionFee"_>(); + transaction.feedbackFeeAmount = dto.value<"feedbackFeeAmount"_>(); + transaction.listOfPublicKeys = dto.value<"listOfPublicKeys"_>(); return transaction; } + template<> + DownloadPaymentTransaction fromDto(const DownloadPaymentTransactionDto & dto) { + DownloadPaymentTransaction transaction; + + EXTRACT_TRANSACTION(transaction, dto) + + transaction.downloadChannelId = dto.value<"downloadChannelId"_>(); + transaction.downloadSize = dto.value<"downloadSize"_>(); + transaction.feedbackFeeAmount = dto.value<"feedbackFeeAmount"_>(); + + return transaction; + } + + template<> + DriveClosureTransaction fromDto(const DriveClosureTransactionDto & dto) { + DriveClosureTransaction transaction; + + EXTRACT_TRANSACTION(transaction, dto) + + transaction.driveKey = dto.value<"driveKey"_>(); + + return transaction; + } + template<> DataModificationApprovalTransaction fromDto(const DataModificationApprovalTransactionDto & dto) { DataModificationApprovalTransaction transaction; @@ -1421,8 +2302,20 @@ namespace xpx_chain_sdk::internal::json::dto { transaction.driveKey = dto.value<"driveKey"_>(); transaction.dataModificationId = dto.value<"dataModificationId"_>(); transaction.fileStructureCdi = dto.value<"fileStructureCdi"_>(); - transaction.fileStructureSize = dto.value<"fileStructureSize"_>(); - transaction.usedDriveSize = dto.value<"usedDriveSize"_>(); + transaction.modificationStatus = dto.value<"modificationStatus"_>(); + transaction.fileStructureSizeBytes = dto.value<"fileStructureSizeBytes"_>(); + transaction.metaFilesSizeBytes = dto.value<"metaFilesSizeBytes"_>(); + transaction.usedDriveSizeBytes = dto.value<"usedDriveSizeBytes"_>(); + transaction.judgingKeysCount = dto.value<"judgingKeysCount"_>(); + transaction.overlappingKeysCount = dto.value<"overlappingKeysCount"_>(); + transaction.judgedKeysCount = dto.value<"judgedKeysCount"_>(); + transaction.publicKeys = dto.value<"publicKeys"_>(); + transaction.signatures = dto.value<"signatures"_>(); + transaction.presentOpinions = dto.value<"presentOpinions"_>(); + + for (const auto opinion : dto.value<"opinions"_>()) { + transaction.opinions.push_back(opinion); + } return transaction; } @@ -1439,6 +2332,18 @@ namespace xpx_chain_sdk::internal::json::dto { return transaction; } + template<> + FinishDownloadTransaction fromDto(const FinishDownloadTransactionDto & dto) { + FinishDownloadTransaction transaction; + + EXTRACT_TRANSACTION(transaction, dto) + + transaction.downloadChannelId = dto.value<"downloadChannelId"_>(), + transaction.feedbackFeeAmount = dto.value<"feedbackFeeAmount"_>(); + + return transaction; + } + template<> ReplicatorOnboardingTransaction fromDto(const ReplicatorOnboardingTransactionDto & dto) { ReplicatorOnboardingTransaction transaction; @@ -1465,11 +2370,165 @@ namespace xpx_chain_sdk::internal::json::dto { return transaction; } + template<> + ReplicatorOffboardingTransaction fromDto(const ReplicatorOffboardingTransactionDto & dto) { + ReplicatorOffboardingTransaction transaction; + + EXTRACT_TRANSACTION(transaction, dto) + + transaction.driveKey = dto.value<"driveKey"_>(); + + return transaction; + } + template<> Uid fromDto(const UidDto &dto) { return { dto.value<"uid"_>() }; } + template<> + DeployContractTransaction fromDto(const DeployContractTransactionDto& dto) { + DeployContractTransaction transaction; + + EXTRACT_TRANSACTION(transaction, dto) + + transaction.driveKey = dto.value<"driveKey"_>(); + transaction.fileName = dto.value<"fileName"_>(); + transaction.functionName = dto.value<"functionName"_>(); + transaction.actualArguments = dto.value<"actualArguments"_>(); + transaction.executionCallPayment = dto.value<"executionCallPayment"_>(); + transaction.downloadCallPayment = dto.value<"downloadCallPayment"_>(); + for(auto& servicePaymentDto : dto.value<"servicePayments"_>()) { + transaction.servicePayments.push_back(fromDto(servicePaymentDto)); + } + transaction.automaticExecutionsFileName = dto.value<"automaticExecutionsFileName"_>(); + transaction.automaticExecutionsFunctionName = dto.value<"automaticExecutionsFunctionName"_>(); + transaction.automaticExecutionsCallPayment = dto.value<"automaticExecutionsCallPayment"_>(); + transaction.automaticDownloadCallPayment = dto.value<"automaticDownloadCallPayment"_>(); + transaction.automaticExecutionsNumber = dto.value<"automaticExecutionsNumber"_>(); + transaction.assignee = dto.value<"assignee"_>(); + + return transaction; + } + + template<> + ManualCallTransaction fromDto(const ManualCallTransactionDto& dto) { + ManualCallTransaction transaction; + + EXTRACT_TRANSACTION(transaction, dto) + + transaction.contractKey = dto.value<"contractKey"_>(); + transaction.fileName = dto.value<"fileName"_>(); + transaction.functionName = dto.value<"functionName"_>(); + transaction.actualArguments = dto.value<"actualArguments"_>(); + transaction.executionCallPayment = dto.value<"executionCallPayment"_>(); + transaction.downloadCallPayment = dto.value<"downloadCallPayment"_>(); + for(auto& servicePaymentDto : dto.value<"servicePayments"_>()) { + transaction.servicePayments.push_back(fromDto(servicePaymentDto)); + } + + return transaction; + } + + template<> + StreamStartTransaction fromDto(const StreamStartTransactionDto& dto) { + StreamStartTransaction transaction; + + EXTRACT_TRANSACTION(transaction, dto) + + transaction.driveKey = dto.value<"driveKey"_>(); + transaction.expectedUploadSize = dto.value<"expectedUploadSize"_>(); + transaction.feedbackFeeAmount = dto.value<"feedbackFeeAmount"_>(); + transaction.folderName = dto.value<"folderName"_>(); + + return transaction; + } + + template<> + StreamFinishTransaction fromDto(const StreamFinishTransactionDto& dto) { + StreamFinishTransaction transaction; + + EXTRACT_TRANSACTION(transaction, dto) + + transaction.driveKey = dto.value<"driveKey"_>(); + transaction.streamId = dto.value<"streamId"_>(); + transaction.actualUploadSizeMegabytes = dto.value<"actualUploadSize"_>(); + transaction.streamStructureCdi = dto.value<"streamStructureCdi"_>(); + + return transaction; + } + + template<> + StreamPaymentTransaction fromDto(const StreamPaymentTransactionDto& dto) { + StreamPaymentTransaction transaction; + + EXTRACT_TRANSACTION(transaction, dto) + + transaction.driveKey = dto.value<"driveKey"_>(); + transaction.streamId = dto.value<"streamId"_>(); + transaction.additionalUploadSizeMegabytes = dto.value<"additionalUploadSize"_>(); + + return transaction; + } + + template<> + AutomaticExecutionsPaymentTransaction fromDto(const AutomaticExecutionsPaymentTransactionDto& dto) { + AutomaticExecutionsPaymentTransaction transaction; + + EXTRACT_TRANSACTION(transaction, dto) + + transaction.contractKey = dto.value<"contractKey"_>(); + transaction.automaticExecutionsNumber = dto.value<"automaticExecutionsNumber"_>(); + + return transaction; + } + + template<> + UnsuccessfulEndBatchExecutionTransaction fromDto(const UnsuccessfulEndBatchExecutionTransactionDto& dto) { + UnsuccessfulEndBatchExecutionTransaction transaction; + + EXTRACT_TRANSACTION(transaction, dto) + + transaction.contractKey = dto.value<"contractKey"_>(); + transaction.batchId = dto.value<"batchId"_>(); + transaction.automaticExecutionsNextBlockToCheck = dto.value<"automaticExecutionsNextBlockToCheck"_>(); + + for(auto& digestDto : dto.value<"callDigests"_>()) { + transaction.callDigests.push_back(fromDto(digestDto)); + } + + for(auto& opinionDto : dto.value<"opinions"_>()) { + transaction.opinions.push_back(fromDto(opinionDto)); + } + + return transaction; + } + + template<> + SuccessfulEndBatchExecutionTransaction fromDto(const SuccessfulEndBatchExecutionTransactionDto& dto) { + SuccessfulEndBatchExecutionTransaction transaction; + + EXTRACT_TRANSACTION(transaction, dto) + + transaction.contractKey = dto.value<"contractKey"_>(); + transaction.batchId = dto.value<"batchId"_>(); + transaction.storageHash = dto.value<"storageHash"_>(); + transaction.usedSizeBytes = dto.value<"usedSizeBytes"_>(); + transaction.metaFilesSizeBytes = dto.value<"metaFilesSizeBytes"_>(); + transaction.automaticExecutionsNextBlockToCheck = dto.value<"automaticExecutionsNextBlockToCheck"_>(); + transaction.proofOfExecutionVerificationInformation = dto.value<"proofOfExecutionVerificationInformation"_>(); + + for(auto& digestDto : dto.value<"callDigests"_>()) { + transaction.callDigests.push_back(fromDto(digestDto)); + } + + for(auto& opinionDto : dto.value<"opinions"_>()) { + transaction.opinions.push_back(fromDto(opinionDto)); + } + + return transaction; + } + template<> WebsocketMeta fromDto(const WebsocketMetaDto &dto) { WebsocketMeta meta; @@ -1492,7 +2551,6 @@ namespace xpx_chain_sdk::internal::json::dto { transactionData.type = dto.value<"type"_>(); transactionData.maxFee = dto.value<"maxFee"_>(); transactionData.deadline = dto.value<"deadline"_>(); - transactionData.hash = dto.value<"hash"_>(); return transactionData; } diff --git a/src/infrastructure/utils/deserialization_json.h b/src/infrastructure/utils/deserialization_json.h index e80b12a..046fda1 100644 --- a/src/infrastructure/utils/deserialization_json.h +++ b/src/infrastructure/utils/deserialization_json.h @@ -7,7 +7,10 @@ #include #include +#include #include +#include +#include #include #include #include @@ -25,7 +28,12 @@ #include #include #include +#include +#include #include +#include +#include +#include #include #include @@ -46,6 +54,7 @@ #include #include #include +#include #include #include #include @@ -54,6 +63,10 @@ #include #include #include +#include +#include +#include +#include #include #include @@ -62,6 +75,7 @@ #include #include #include +#include "xpxchaincpp/client.h" using namespace xpx_chain_sdk::transactions_info; @@ -182,6 +196,93 @@ namespace xpx_chain_sdk { namespace internal { namespace json { template<> NetworkInfo fromDto (const NetworkInfoDto& dto); + template<> + DriveData fromDto(const DriveDataDto &dto); + + template<> + Drive fromDto(const DriveDto &dto); + + template<> + DriveInfo fromDto(const DriveInfoDto &dto); + + template<> + xpx_chain_sdk::drives_page::Pagination fromDto(const dto::drives_page::PaginationDto &dto); + + template<> + xpx_chain_sdk::drives_page::DrivesPage fromDto(const drives_page::DrivesPageDto &dto); + + template<> + ActiveDataModification fromDto(const ActiveDataModificationDto &dto); + + template<> + CompletedDataModification fromDto(const CompletedDataModificationDto &dto); + + template<> + ConfirmedUsedSize fromDto(const ConfirmedUsedSizeDto &dto); + + template<> + Shard fromDto(const ShardDto &dto); + + template<> + Verification fromDto(const VerificationDto &dto); + + template<> + DownloadShard fromDto(const DownloadShardDto &dto); + + template<> + DataModificationShard fromDto(const DataModificationShardDto &dto); + + template<> + Replicator fromDto(const ReplicatorDto &dto); + + template<> + ReplicatorData fromDto(const ReplicatorDataDto &dto); + + template<> + UploadInfo fromDto(const UploadInfoDto &dto); + + template<> + xpx_chain_sdk::replicators_page::Pagination fromDto(const dto::replicators_page::PaginationDto &dto); + + template<> + xpx_chain_sdk::replicators_page::ReplicatorsPage fromDto(const replicators_page::ReplicatorsPageDto &dto); + + template<> + DownloadChannel fromDto(const DownloadChannelDto &dto); + + template<> + DownloadChannelData fromDto(const DownloadChannelDataDto &dto); + + template<> + CumulativePayment fromDto(const CumulativePaymentDto &dto); + + template<> + xpx_chain_sdk::download_channels_page::Pagination fromDto(const dto::download_channels_page::PaginationDto &dto); + + template<> + xpx_chain_sdk::download_channels_page::DownloadChannelsPage fromDto(const download_channels_page::DownloadChannelsPageDto &dto); + + template<> + RateData fromDto(const RateDataDto &dto); + + template<> + TurnoverData fromDto(const TurnoverDataDto &dto); + + template<> + LiquidityProviderData fromDto(const LiquidityProviderDataDto &dto); + + template<> + LiquidityProvider fromDto(const LiquidityProviderDto &dto); + + template<> + MultipleLiquidityProviders fromDto(const MultipleLiquidityProvidersDto &dto); + + template<> + xpx_chain_sdk::liquidity_providers_page::Pagination fromDto(const dto::liquidity_providers_page::PaginationDto &dto); + + template<> + xpx_chain_sdk::liquidity_providers_page::LiquidityProvidersPage fromDto(const liquidity_providers_page::LiquidityProvidersPageDto &dto); + /// Transaction Meta template<> @@ -197,6 +298,12 @@ namespace xpx_chain_sdk { namespace internal { namespace json { MultipleTransactionStatus fromDto(const MultipleTransactionStatusDto& dto); /// Transactions + template<> + xpx_chain_sdk::transactions_page::TransactionsPage fromDto(const dto::transactions_page::TransactionsPageDto& dto); + + template<> + xpx_chain_sdk::transactions_page::Pagination fromDto(const dto::transactions_page::PaginationDto &dto); + template<> Cosignature fromDto(const CosignatureDto& dto); @@ -246,6 +353,9 @@ namespace xpx_chain_sdk { namespace internal { namespace json { template<> SecretProofTransaction fromDto(const SecretProofTransactionDto & dto); + template<> + StoragePaymentTransaction fromDto(const StoragePaymentTransactionDto & dto); + template<> TransferTransaction fromDto(const TransferTransactionDto & dto); @@ -261,25 +371,64 @@ namespace xpx_chain_sdk { namespace internal { namespace json { template<> PrepareBcDriveTransaction fromDto(const PrepareBcDriveTransactionDto & dto); + template<> + CreateLiquidityProviderTransaction fromDto(const CreateLiquidityProviderTransactionDto & dto); + + template<> + ManualRateChangeTransaction fromDto(const ManualRateChangeTransactionDto & dto); + template<> DataModificationTransaction fromDto(const DataModificationTransactionDto & dto); template<> DownloadTransaction fromDto(const DownloadTransactionDto & dto); + template<> + DownloadPaymentTransaction fromDto(const DownloadPaymentTransactionDto & dto); + + template<> + DriveClosureTransaction fromDto(const DriveClosureTransactionDto & dto); + template<> DataModificationApprovalTransaction fromDto(const DataModificationApprovalTransactionDto & dto); template<> DataModificationCancelTransaction fromDto(const DataModificationCancelTransactionDto & dto); - template<> + template<> + FinishDownloadTransaction fromDto(const FinishDownloadTransactionDto & dto); + + template<> ReplicatorOnboardingTransaction fromDto(const ReplicatorOnboardingTransactionDto & dto); + template<> + ReplicatorOffboardingTransaction fromDto(const ReplicatorOffboardingTransactionDto & dto); + template<> ReplicatorsCleanupTransaction fromDto(const ReplicatorsCleanupTransactionDto & dto); - /// Account Property Transactions + /// Utils + template<> + ErrorMessage fromDto(const ErrorMessageDto & dto); + + /// Supercontract V2 + + template<> + DeployContractTransaction fromDto(const DeployContractTransactionDto& dto); + + template<> + ManualCallTransaction fromDto(const ManualCallTransactionDto& dto); + + template<> + AutomaticExecutionsPaymentTransaction fromDto(const AutomaticExecutionsPaymentTransactionDto& dto); + + template<> + SuccessfulEndBatchExecutionTransaction fromDto(const SuccessfulEndBatchExecutionTransactionDto& dto); + + template<> + UnsuccessfulEndBatchExecutionTransaction fromDto(const UnsuccessfulEndBatchExecutionTransactionDto& dto); + + /// Account Property Transactions template<> AccountTransactionPropertyTransaction fromDto(const AccountTransactionPropertyTransactionDto & dto); @@ -289,6 +438,17 @@ namespace xpx_chain_sdk { namespace internal { namespace json { template<> AccountAddressPropertyTransaction fromDto(const AccountAddressPropertyTransactionDto & dto); + /// Streaming + + template<> + StreamStartTransaction fromDto(const StreamStartTransactionDto & dto); + + template<> + StreamFinishTransaction fromDto(const StreamFinishTransactionDto & dto); + + template<> + StreamPaymentTransaction fromDto(const StreamPaymentTransactionDto & dto); + /// Embedded Transactions template<> @@ -315,6 +475,9 @@ namespace xpx_chain_sdk { namespace internal { namespace json { template<> EmbeddedSecretProofTransaction fromDto(const EmbeddedSecretProofTransactionDto & dto); + template<> + EmbeddedStoragePaymentTransaction fromDto(const EmbeddedStoragePaymentTransactionDto & dto); + template<> EmbeddedTransferTransaction fromDto(const EmbeddedTransferTransactionDto & dto); @@ -330,13 +493,25 @@ namespace xpx_chain_sdk { namespace internal { namespace json { template<> EmbeddedPrepareBcDriveTransaction fromDto(const EmbeddedPrepareBcDriveTransactionDto & dto); + template<> + EmbeddedCreateLiquidityProviderTransaction fromDto(const EmbeddedCreateLiquidityProviderTransactionDto & dto); + + template<> + EmbeddedManualRateChangeTransaction fromDto(const EmbeddedManualRateChangeTransactionDto & dto); + template<> EmbeddedDataModificationTransaction fromDto(const EmbeddedDataModificationTransactionDto & dto); template<> EmbeddedDownloadTransaction fromDto(const EmbeddedDownloadTransactionDto & dto); - template<> + template<> + EmbeddedDownloadPaymentTransaction fromDto(const EmbeddedDownloadPaymentTransactionDto & dto); + + template<> + EmbeddedDriveClosureTransaction fromDto(const EmbeddedDriveClosureTransactionDto & dto); + + template<> EmbeddedDataModificationApprovalTransaction fromDto(const EmbeddedDataModificationApprovalTransactionDto & dto); template<> @@ -348,7 +523,13 @@ namespace xpx_chain_sdk { namespace internal { namespace json { template<> EmbeddedReplicatorsCleanupTransaction fromDto(const EmbeddedReplicatorsCleanupTransactionDto & dto); - /// Account Property Transactions + template<> + EmbeddedReplicatorOffboardingTransaction fromDto(const EmbeddedReplicatorOffboardingTransactionDto & dto); + + template<> + EmbeddedFinishDownloadTransaction fromDto(const EmbeddedFinishDownloadTransactionDto & dto); + + /// Account Property Transactions template<> EmbeddedAccountTransactionPropertyTransaction fromDto(const EmbeddedAccountTransactionPropertyTransactionDto & dto); @@ -357,6 +538,43 @@ namespace xpx_chain_sdk { namespace internal { namespace json { template<> EmbeddedAccountAddressPropertyTransaction fromDto(const EmbeddedAccountAddressPropertyTransactionDto & dto); + + /// Streaming + + template<> + EmbeddedStreamStartTransaction fromDto(const EmbeddedStreamStartTransactionDto & dto); + + template<> + EmbeddedStreamFinishTransaction fromDto(const EmbeddedStreamFinishTransactionDto & dto); + + template<> + EmbeddedStreamPaymentTransaction fromDto(const EmbeddedStreamPaymentTransactionDto & dto); + + /// Supercontract V2 + + template<> + EmbeddedDeployContractTransaction fromDto(const EmbeddedDeployContractTransactionDto& dto); + + template<> + EmbeddedManualCallTransaction fromDto(const EmbeddedManualCallTransactionDto& dto); + + template<> + EmbeddedAutomaticExecutionsPaymentTransaction fromDto(const EmbeddedAutomaticExecutionsPaymentTransactionDto& dto); + + template<> + EmbeddedSuccessfulEndBatchExecutionTransaction fromDto(const EmbeddedSuccessfulEndBatchExecutionTransactionDto& dto); + + template<> + EmbeddedUnsuccessfulEndBatchExecutionTransaction fromDto(const EmbeddedUnsuccessfulEndBatchExecutionTransactionDto& dto); + + template<> + ExtendedCallDigest fromDto(const ExtendedCallDigestDto& dto); + + template<> + Opinion fromDto(const OpinionDto& dto); + + template<> + SuperContractV2 fromDto (const SuperContractV2Dto& dto); } } } diff --git a/src/infrastructure/utils/subscription_manager.cpp b/src/infrastructure/utils/subscription_manager.cpp index efc48d8..ee9b568 100644 --- a/src/infrastructure/utils/subscription_manager.cpp +++ b/src/infrastructure/utils/subscription_manager.cpp @@ -14,20 +14,20 @@ namespace xpx_chain_sdk::internal { SubscriptionManager::SubscriptionManager(std::shared_ptr wsClient) : _wsClient(wsClient) {} - void SubscriptionManager::subscribe(const std::string &uid, const std::string &path) { - _wsClient->send(createJson(uid, path, "subscribe")); + void SubscriptionManager::subscribe(const std::string &uid, const std::string &path, std::function onSuccess, std::function onError) { + _wsClient->send(createJson(uid, path, "subscribe"), onSuccess, onError); } - void SubscriptionManager::subscribe(const std::string &uid, const std::string &path, const Address& address) { - _wsClient->send(createJson(uid, path + "/" + address.encoded(), "subscribe")); + void SubscriptionManager::subscribe(const std::string &uid, const std::string &path, const Address& address, std::function onSuccess, std::function onError) { + _wsClient->send(createJson(uid, path + "/" + address.encoded(), "subscribe"), onSuccess, onError); } - void SubscriptionManager::unsubscribe(const std::string &uid, const std::string &path) { - _wsClient->send(createJson(uid, path, "unsubscribe")); + void SubscriptionManager::unsubscribe(const std::string &uid, const std::string &path, std::function onSuccess, std::function onError) { + _wsClient->send(createJson(uid, path, "unsubscribe"), onSuccess, onError); } - void SubscriptionManager::unsubscribe(const std::string &uid, const std::string &path, const Address &address) { - _wsClient->send(createJson(uid, path + "/" + address.encoded(), "unsubscribe")); + void SubscriptionManager::unsubscribe(const std::string &uid, const std::string &path, const Address &address, std::function onSuccess, std::function onError) { + _wsClient->send(createJson(uid, path + "/" + address.encoded(), "unsubscribe"), onSuccess, onError); } std::string SubscriptionManager::createJson(const std::string &uid, const std::string &path, const std::string& type) { diff --git a/src/infrastructure/utils/subscription_manager.h b/src/infrastructure/utils/subscription_manager.h index d33af8f..696479c 100644 --- a/src/infrastructure/utils/subscription_manager.h +++ b/src/infrastructure/utils/subscription_manager.h @@ -29,10 +29,10 @@ namespace xpx_chain_sdk::internal { ~SubscriptionManager() = default; public: - void subscribe(const std::string& uid, const std::string& path); - void subscribe(const std::string& uid, const std::string& path, const Address& address); - void unsubscribe(const std::string& uid, const std::string& path); - void unsubscribe(const std::string& uid, const std::string& path, const Address& address); + void subscribe(const std::string& uid, const std::string& path, std::function onSuccess, std::function onError); + void subscribe(const std::string& uid, const std::string& path, const Address& address, std::function onSuccess, std::function onError); + void unsubscribe(const std::string& uid, const std::string& path, std::function onSuccess, std::function onError); + void unsubscribe(const std::string& uid, const std::string& path, const Address& address, std::function onSuccess, std::function onError); private: static std::string createJson(const std::string &uid, const std::string &path, const std::string& type) ; diff --git a/src/sdk/client.cpp b/src/sdk/client.cpp index f31414e..fadc78d 100644 --- a/src/sdk/client.cpp +++ b/src/sdk/client.cpp @@ -4,6 +4,7 @@ *** license that can be found in the LICENSE file. **/ #include "infrastructure/network/context.h" +#include #include #include #include @@ -15,15 +16,17 @@ using namespace xpx_chain_sdk; class Client : public IClient { public: - explicit Client(std::shared_ptr config) : _config(config) { - _context = std::make_shared(); - _account = std::make_shared(config, _context); - _blockchain = std::make_shared(config, _context); - _mosaic = std::make_shared(config, _context); - _namespace = std::make_shared(config, _context); - _notification = std::make_shared(config, _context); - _network = std::make_shared(config, _context); - _transaction = std::make_shared(config, _context); + explicit Client(const Config& config) : _config(config) { + _context = std::make_shared(); + _account = std::make_shared(config, _context); + _blockchain = std::make_shared(config, _context); + _mosaic = std::make_shared(config, _context); + _namespace = std::make_shared(config, _context); + _notification = std::make_shared(_config); + _network = std::make_shared(config, _context); + _liquidityProvider = std::make_shared(config, _context); + _transaction = std::make_shared(config, _context); + _storage = std::make_shared(config, _context); } std::shared_ptr account() const override { @@ -50,33 +53,57 @@ class Client : public IClient { return _network; } + std::shared_ptr liquidityProvider() const override { + return _liquidityProvider; + } + std::shared_ptr transactions() const override { return _transaction; } + std::shared_ptr storage() const override { + return _storage; + } + + const Config& getConfig() const override { + return _config; + } + private: - std::shared_ptr _config; - std::shared_ptr _context; + const Config& _config; + std::shared_ptr _context; - std::shared_ptr _account; - std::shared_ptr _blockchain; - std::shared_ptr _mosaic; - std::shared_ptr _namespace; + std::shared_ptr _account; + std::shared_ptr _blockchain; + std::shared_ptr _mosaic; + std::shared_ptr _namespace; std::shared_ptr _notification; - std::shared_ptr _network; - std::shared_ptr _transaction; + std::shared_ptr _network; + std::shared_ptr _liquidityProvider; + std::shared_ptr _transaction; + std::shared_ptr _storage; }; namespace xpx_chain_sdk { - std::shared_ptr getClient(std::shared_ptr config) { + std::shared_ptr getClient(const Config& config) { return std::make_shared(config); } } -InvalidRequest::InvalidRequest(uint16_t code) : - runtime_error(InvalidRequest::getErrorMessage(code)) +InvalidRequest::InvalidRequest(const std::string& message, uint16_t code) : + runtime_error(InvalidRequest::getErrorMessage(code)), + httpErrorCode(code), + errorMessage(message) {} +int InvalidRequest::getHttpErrorCode() const { + return httpErrorCode; +} + +ErrorMessage InvalidRequest::getErrorMessage() const { + return internal::json::dto::from_json(errorMessage); +} + std::string InvalidRequest::getErrorMessage(uint16_t code) { std::stringstream s; s << "Server rejected the request. Error code: " << code; diff --git a/src/sdk/client/account_service.cpp b/src/sdk/client/account_service.cpp index 4c4f576..1791bbd 100644 --- a/src/sdk/client/account_service.cpp +++ b/src/sdk/client/account_service.cpp @@ -17,7 +17,7 @@ using xpx_chain_sdk::internal::json::Parser; using xpx_chain_sdk::internal::json::dto::from_json; AccountService::AccountService( - std::shared_ptr config, + const Config& config, std::shared_ptr context) : _config(config), _context(context) {} diff --git a/src/sdk/client/blockchain_service.cpp b/src/sdk/client/blockchain_service.cpp index efe6d09..a435707 100644 --- a/src/sdk/client/blockchain_service.cpp +++ b/src/sdk/client/blockchain_service.cpp @@ -24,7 +24,7 @@ using internal::json::dto::StorageInfoDto; BlockchainService::BlockchainService( - std::shared_ptr config, + const Config& config, std::shared_ptr context ) : _config(config), diff --git a/src/sdk/client/liquidity_provider_service.cpp b/src/sdk/client/liquidity_provider_service.cpp new file mode 100644 index 0000000..f13e7db --- /dev/null +++ b/src/sdk/client/liquidity_provider_service.cpp @@ -0,0 +1,52 @@ + +/* +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +*/ + +#include +#include +#include +#include +#include +#include + +using namespace xpx_chain_sdk; + +using internal::json::dto::from_json; +using internal::json::dto::LiquidityProviderDto; +using internal::json::dto::liquidity_providers_page::LiquidityProvidersPageDto; + + +LiquidityProviderService::LiquidityProviderService( + const Config& config, + std::shared_ptr context +) : + _config(std::move(config)), + _context(std::move(context)) +{}; + +LiquidityProvider LiquidityProviderService::getLiquidityProviderByKey(const std::string &key) { + std::stringstream path; + path << "liquidity_providers/" << key; + + RequestParamsBuilder builder(_config); + builder.setPath(path.str()); + builder.setMethod(internal::network::HTTPRequestMethod::GET); + + std::string response = internal::network::performHTTPRequest(_context, builder.getRequestParams()); + return from_json(response); +} + +liquidity_providers_page::LiquidityProvidersPage LiquidityProviderService::getLiquidityProviders() { + std::stringstream path; + path << "liquidity_providers"; + + RequestParamsBuilder builder(_config); + builder.setPath(path.str()); + builder.setMethod(internal::network::HTTPRequestMethod::GET); + + std::string response = internal::network::performHTTPRequest(_context, builder.getRequestParams()); + return from_json(response); +} \ No newline at end of file diff --git a/src/sdk/client/mosaic_service.cpp b/src/sdk/client/mosaic_service.cpp index 93c8c87..9143c02 100644 --- a/src/sdk/client/mosaic_service.cpp +++ b/src/sdk/client/mosaic_service.cpp @@ -24,7 +24,7 @@ using internal::json::dto::MosaicNamesDto; using internal::json::dto::MultipleMosaicInfoDto; MosaicService::MosaicService( - std::shared_ptr config, + const Config& config, std::shared_ptr context ): _config(config), diff --git a/src/sdk/client/namespace_service.cpp b/src/sdk/client/namespace_service.cpp index 77494cb..ecbb58b 100644 --- a/src/sdk/client/namespace_service.cpp +++ b/src/sdk/client/namespace_service.cpp @@ -21,7 +21,7 @@ using xpx_chain_sdk::internal::json::Parser; using xpx_chain_sdk::internal::json::dto::from_json; NamespaceService::NamespaceService( - std::shared_ptr config, + const Config& config, std::shared_ptr context ) : _config(config), _context(context) {} diff --git a/src/sdk/client/network_service.cpp b/src/sdk/client/network_service.cpp index 2aaa984..ccffded 100644 --- a/src/sdk/client/network_service.cpp +++ b/src/sdk/client/network_service.cpp @@ -17,7 +17,7 @@ using xpx_chain_sdk::internal::json::dto::from_json; static uint64_t getBlockchainHeight( std::shared_ptr context, - std::shared_ptr _config) { + const Config& _config) { RequestParamsBuilder builder(_config); builder.setPath("chain/height"); builder.setMethod(internal::network::HTTPRequestMethod::GET); @@ -28,7 +28,7 @@ static uint64_t getBlockchainHeight( } NetworkService::NetworkService( - std::shared_ptr config, + const Config& config, std::shared_ptr context ):_config(config), _context(context) {} diff --git a/src/sdk/client/notification_service.cpp b/src/sdk/client/notification_service.cpp index f0fe3be..de290ed 100644 --- a/src/sdk/client/notification_service.cpp +++ b/src/sdk/client/notification_service.cpp @@ -12,8 +12,6 @@ #include #include #include -#include -#include using namespace xpx_chain_sdk; @@ -24,109 +22,188 @@ using xpx_chain_sdk::internal::json::dto::from_json; namespace xpx_chain_sdk { - NotificationService::NotificationService( - std::shared_ptr config, - std::shared_ptr context): + NotificationService::NotificationService(const Config& config) + : _config(config), - _context(context), _wsClient(nullptr), _subscriptionManager(nullptr), - _statusNotifiers({}), - _isInitialized(false) {} + _io_context(std::make_shared()), + _tasks(), + _mainWorker(), + _isConnectionInProgress(false) { + } NotificationService::~NotificationService() { - finalize(); + stop(); } - void NotificationService::addMutexIfNotExist(const std::string& mutexKey) { - std::lock_guard lock(_commonMutex); - if (_notifiersMutexes.find(mutexKey) == _notifiersMutexes.end()) { - _notifiersMutexes.insert(std::pair>(mutexKey, new std::mutex)); - } - } + void NotificationService::run() { + boost::asio::post(*_io_context, [this] { + auto connectionCallback = [this](const auto& json) { + Uid uid = from_json(json); + _uid = uid.value; - void NotificationService::initialize(std::function initializeCallback) { - std::unique_lock lock(_initializeMutex); - auto connectionCallback = [pThis = shared_from_this(), initializeCallback](const auto& json) { - Uid uid = from_json(json); - pThis->_uid = uid.value; + _isConnectionInProgress = false; - pThis->_subscriptionManager = std::make_shared(pThis->_wsClient); - pThis->_isInitialized = true; - initializeCallback(); - pThis->_initializeCheck.notify_all(); - }; + for (const auto& task : _tasks) { + task(); + } - auto receiverCallback = [pThis = shared_from_this()](const auto& json) { - pThis->notificationsHandler(json); - }; + _tasks.clear(); + _connectionCallback("", 0); + }; + + auto receiverCallback = [this](const auto& json) { + notificationsHandler(json); + }; + + auto errorCallback = [this](const boost::beast::error_code& errorCode) { + if (errorCode) { + std::string errorMessage = errorCode.message(); + if (boost::asio::error::eof == errorCode) { + errorMessage = "connection closed by server side"; + } - auto errorCallback = [pThis = shared_from_this()](const boost::beast::error_code& errorCode) { - if (errorCode) { - std::string errorMessage = errorCode.message(); - if (boost::asio::error::eof == errorCode) { - errorMessage = "connection closed by server side"; + _isConnectionInProgress = false; + _tasks.clear(); + _connectionCallback(errorMessage, errorCode.value()); } + }; - pThis->_isInitialized = false; - pThis->_initializeCheck.notify_all(); - XPX_CHAIN_SDK_THROW_1(notification_error, errorMessage, errorCode.value()) - } - }; + _isConnectionInProgress = true; + _wsClient = std::make_shared(_config, _io_context, connectionCallback, receiverCallback, errorCallback); + _subscriptionManager = std::make_shared(_wsClient); + _wsClient->connect(); + }); - _wsClient = std::make_shared(_config, _context, connectionCallback, receiverCallback, errorCallback); - _wsClient->connect(); - _initializeCheck.wait_for(lock, std::chrono::seconds(60), [pThis = shared_from_this()]() { - return pThis->_wsClient->isConnected(); + _mainWorker = std::thread([this]() { _io_context->run(); }); + } + + void NotificationService::runTask(std::function task) { + boost::asio::post(*_io_context, [pThis = shared_from_this(), task] { + if (task) { + if (pThis->_isConnectionInProgress) { + pThis->_tasks.emplace_back(task); + } else { + task(); + } + } }); } - void NotificationService::finalize() { - if (_isInitialized) { - _subscriptionManager->unsubscribe(_uid, internal::pathBlock); + void NotificationService::stop() { + if (!_mainWorker.joinable()) { + return; + } - for (auto const& item : _confirmedAddedNotifiers) - { - _subscriptionManager->unsubscribe(_uid, internal::pathConfirmedAdded, Address::FromHex(item.first)); - } + boost::asio::post(*_io_context, [this] { + if (_wsClient->isConnected()) { + _subscriptionManager->unsubscribe(_uid, internal::pathBlock, [](){}, [](auto){}); - for (auto const& item : _unconfirmedAddedNotifiers) - { - _subscriptionManager->unsubscribe(_uid, internal::pathUnconfirmedAdded, Address::FromHex(item.first)); - } + for (auto const &item: _confirmedAddedNotifiers) { + _subscriptionManager->unsubscribe(_uid, internal::pathConfirmedAdded, Address::FromHex(item.first), [](){}, [](auto){}); + } - for (auto const& item : _unconfirmedRemovedNotifiers) - { - _subscriptionManager->unsubscribe(_uid, internal::pathUnconfirmedRemoved, Address::FromHex(item.first)); - } + for (auto const &item: _unconfirmedAddedNotifiers) { + _subscriptionManager->unsubscribe(_uid, internal::pathUnconfirmedAdded, Address::FromHex(item.first), [](){}, [](auto){}); + } - for (auto const& item : _partialAddedNotifiers) - { - _subscriptionManager->unsubscribe(_uid, internal::pathPartialAdded, Address::FromHex(item.first)); - } + for (auto const &item: _unconfirmedRemovedNotifiers) { + _subscriptionManager->unsubscribe(_uid, internal::pathUnconfirmedRemoved, Address::FromHex(item.first), [](){}, [](auto){}); + } - for (auto const& item : _partialRemovedNotifiers) - { - _subscriptionManager->unsubscribe(_uid, internal::pathPartialRemoved, Address::FromHex(item.first)); - } + for (auto const &item: _partialAddedNotifiers) { + _subscriptionManager->unsubscribe(_uid, internal::pathPartialAdded, Address::FromHex(item.first), [](){}, [](auto){}); + } + + for (auto const &item: _partialRemovedNotifiers) { + _subscriptionManager->unsubscribe(_uid, internal::pathPartialRemoved, Address::FromHex(item.first), [](){}, [](auto){}); + } + + for (auto const &item: _statusNotifiers) { + _subscriptionManager->unsubscribe(_uid, internal::pathStatus, Address::FromHex(item.first), [](){}, [](auto){}); + } - for (auto const& item : _statusNotifiers) - { - _subscriptionManager->unsubscribe(_uid, internal::pathStatus, Address::FromHex(item.first)); + for (auto const &item: _cosignatureNotifiers) { + _subscriptionManager->unsubscribe(_uid, internal::pathCosignature, Address::FromHex(item.first), [](){}, [](auto){}); + } + + for (auto const &item: _driveStateNotifiers) { + _subscriptionManager->unsubscribe(_uid, internal::pathDriveState, Address::FromHex(item.first), [](){}, [](auto){}); + } + + _wsClient->disconnect(); } + }); + + boost::asio::post(*_io_context, [this] { _io_context->stop(); }); + + _mainWorker.join(); + } + + template + void NotificationService::addNotifiers( + const Address& address, + const std::string& path, + InternalContainer& linkedNotifiers, + const ExternalContainer& notifiers, + std::function onSuccess, + std::function onError) { + if (empty(notifiers)) { + XPX_CHAIN_SDK_THROW_1(notification_error, "list of notifiers is empty", __FUNCTION__) + } + + auto task = [pThis = shared_from_this(), address, path, &linkedNotifiers, notifiers, onSuccess, onError]() { + const std::string hexAddress = ToHex(address.binary()); + if ( linkedNotifiers.find(hexAddress) != linkedNotifiers.end() ) { + for (const auto& notifier : notifiers) { + linkedNotifiers[hexAddress].insert({notifier.getId(), notifier}); + } + + pThis->runTask(onSuccess); + } else { + linkedNotifiers.insert({hexAddress, {}}); - for (auto const& item : _cosignatureNotifiers) - { - _subscriptionManager->unsubscribe(_uid, internal::pathCosignature, Address::FromHex(item.first)); + for (const auto& notifier : notifiers) { + linkedNotifiers[hexAddress].insert({notifier.getId(), notifier}); + } + + pThis->_subscriptionManager->subscribe(pThis->_uid, path, address, onSuccess, onError); } + }; + + runTask(task); + } + + template + void NotificationService::removeNotifiers( + const Address& address, + const std::string& path, + InternalContainer& linkedNotifiers, + const ExternalContainer& notifierIds, + std::function onSuccess, + std::function onError) { + auto task = [pThis = shared_from_this(), address, path, &linkedNotifiers, notifierIds, onSuccess, onError]() { + const std::string hexAddress = ToHex(address.binary()); + if (linkedNotifiers.find(hexAddress) != linkedNotifiers.end()) { + for (const auto& id : notifierIds) { + linkedNotifiers[hexAddress].erase(id); + } - for (auto const& item : _driveStateNotifiers) - { - _subscriptionManager->unsubscribe(_uid, internal::pathDriveState, Address::FromHex(item.first)); + if (notifierIds.empty()) { + linkedNotifiers[hexAddress].clear(); + } + + if (linkedNotifiers[hexAddress].empty()) { + linkedNotifiers.erase(hexAddress); + pThis->_subscriptionManager->unsubscribe(pThis->_uid, path, address, onSuccess, onError); + } else { + pThis->runTask(onSuccess); + } } + }; - _wsClient->disconnect(); - } + runTask(task); } void NotificationService::notificationsHandler(const std::string &json) { @@ -134,83 +211,83 @@ namespace xpx_chain_sdk { if (internal::pathBlock == websocketInfo.meta.channelName) { if (_blockNotifiers.empty()) { - _subscriptionManager->unsubscribe(_uid, internal::pathBlock); + _subscriptionManager->unsubscribe(_uid, internal::pathBlock, [](){}, [](auto){}); } else { auto block = from_json(json); for (const auto& notifier : _blockNotifiers) { - notifier(block); + notifier.second.run(block); } } } else if (internal::pathConfirmedAdded == websocketInfo.meta.channelName) { if (_confirmedAddedNotifiers.find(websocketInfo.meta.address) == _confirmedAddedNotifiers.end()) { - _subscriptionManager->unsubscribe(_uid, internal::pathConfirmedAdded, Address::FromHex(websocketInfo.meta.address)); + _subscriptionManager->unsubscribe(_uid, internal::pathConfirmedAdded, Address::FromHex(websocketInfo.meta.address), [](){}, [](auto){}); } else { auto transaction = from_json(json); for (const auto& notifier : _confirmedAddedNotifiers[websocketInfo.meta.address]) { - notifier(transaction); + notifier.second.run(transaction); } } } else if (internal::pathUnconfirmedAdded == websocketInfo.meta.channelName) { if (_unconfirmedAddedNotifiers.find(websocketInfo.meta.address) == _unconfirmedAddedNotifiers.end()) { - _subscriptionManager->unsubscribe(_uid, internal::pathUnconfirmedAdded, Address::FromHex(websocketInfo.meta.address)); + _subscriptionManager->unsubscribe(_uid, internal::pathUnconfirmedAdded, Address::FromHex(websocketInfo.meta.address), [](){}, [](auto){}); } else { auto transaction = from_json(json); for (const auto& notifier : _unconfirmedAddedNotifiers[websocketInfo.meta.address]) { - notifier(transaction); + notifier.second.run(transaction); } } } else if (internal::pathUnconfirmedRemoved == websocketInfo.meta.channelName) { if (_unconfirmedRemovedNotifiers.find(websocketInfo.meta.address) == _unconfirmedRemovedNotifiers.end()) { - _subscriptionManager->unsubscribe(_uid, internal::pathUnconfirmedRemoved, Address::FromHex(websocketInfo.meta.address)); + _subscriptionManager->unsubscribe(_uid, internal::pathUnconfirmedRemoved, Address::FromHex(websocketInfo.meta.address), [](){}, [](auto){}); } else { auto transactionInfo = from_json(json); for (const auto& notifier : _unconfirmedRemovedNotifiers[websocketInfo.meta.address]) { - notifier(transactionInfo); + notifier.second.run(transactionInfo); } } } else if (internal::pathStatus == websocketInfo.meta.channelName) { if (_statusNotifiers.find(websocketInfo.meta.address) == _statusNotifiers.end()) { - _subscriptionManager->unsubscribe(_uid, internal::pathStatus, Address::FromHex(websocketInfo.meta.address)); + _subscriptionManager->unsubscribe(_uid, internal::pathStatus, Address::FromHex(websocketInfo.meta.address), [](){}, [](auto){}); } else { auto transactionStatus = from_json(json); for (const auto& notifier : _statusNotifiers[websocketInfo.meta.address]) { - notifier(transactionStatus); + notifier.second.run(transactionStatus); } } } else if (internal::pathPartialAdded == websocketInfo.meta.channelName) { if (_partialAddedNotifiers.find(websocketInfo.meta.address) == _partialAddedNotifiers.end()) { - _subscriptionManager->unsubscribe(_uid, internal::pathPartialAdded, Address::FromHex(websocketInfo.meta.address)); + _subscriptionManager->unsubscribe(_uid, internal::pathPartialAdded, Address::FromHex(websocketInfo.meta.address), [](){}, [](auto){}); } else { auto transaction = transaction_from_json(json); for (const auto& notifier : _partialAddedNotifiers[websocketInfo.meta.address]) { - notifier(transaction); + notifier.second.run(transaction); } } } else if (internal::pathPartialRemoved == websocketInfo.meta.channelName) { if (_partialRemovedNotifiers.find(websocketInfo.meta.address) == _partialRemovedNotifiers.end()) { - _subscriptionManager->unsubscribe(_uid, internal::pathPartialRemoved, Address::FromHex(websocketInfo.meta.address)); + _subscriptionManager->unsubscribe(_uid, internal::pathPartialRemoved, Address::FromHex(websocketInfo.meta.address), [](){}, [](auto){}); } else { auto transactionInfo = from_json(json); for (const auto& notifier : _partialRemovedNotifiers[websocketInfo.meta.address]) { - notifier(transactionInfo); + notifier.second.run(transactionInfo); } } } else if (internal::pathCosignature == websocketInfo.meta.channelName) { if (_cosignatureNotifiers.find(websocketInfo.meta.address) == _cosignatureNotifiers.end()) { - _subscriptionManager->unsubscribe(_uid, internal::pathCosignature, Address::FromHex(websocketInfo.meta.address)); + _subscriptionManager->unsubscribe(_uid, internal::pathCosignature, Address::FromHex(websocketInfo.meta.address), [](){}, [](auto){}); } else { auto signerInfo = from_json(json); for (const auto& notifier : _cosignatureNotifiers[websocketInfo.meta.address]) { - notifier(signerInfo); + notifier.second.run(signerInfo); } } } else if (internal::pathDriveState == websocketInfo.meta.channelName) { if (_driveStateNotifiers.find(websocketInfo.meta.address) == _driveStateNotifiers.end()) { - _subscriptionManager->unsubscribe(_uid, internal::pathDriveState, Address::FromHex(websocketInfo.meta.address)); + _subscriptionManager->unsubscribe(_uid, internal::pathDriveState, Address::FromHex(websocketInfo.meta.address), [](){}, [](auto){}); } else { auto driveState = from_json(json); for (const auto& notifier : _driveStateNotifiers[websocketInfo.meta.address]) { - notifier(driveState); + notifier.second.run(driveState); } } } else { @@ -218,406 +295,161 @@ namespace xpx_chain_sdk { } } - void NotificationService::addBlockNotifiers(const std::initializer_list ¬ifiers) { + void NotificationService::addBlockNotifiers(const std::vector>& notifiers, + std::function onSuccess, + std::function onError) { if (empty(notifiers)) { XPX_CHAIN_SDK_THROW_1(notification_error, "list of notifiers is empty", __FUNCTION__) } - addMutexIfNotExist(internal::pathBlock); + auto task = [pThis = shared_from_this(), notifiers, onSuccess, onError]() { + const bool isEmpty = pThis->_blockNotifiers.empty(); - auto callback = [pThis = shared_from_this(), notifiers]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathBlock]); + for (const auto& notifier : notifiers) { + pThis->_blockNotifiers.insert({notifier.getId(), notifier}); + } - if (pThis->_blockNotifiers.empty()) { - pThis->_blockNotifiers.insert(pThis->_blockNotifiers.end(), notifiers.begin(), notifiers.end()); - pThis->_subscriptionManager->subscribe(pThis->_uid, internal::pathBlock); + if (isEmpty) { + pThis->_subscriptionManager->subscribe(pThis->_uid, internal::pathBlock, onSuccess, onError); } else { - pThis->_blockNotifiers.insert(pThis->_blockNotifiers.end(), notifiers.begin(), notifiers.end()); + pThis->runTask(onSuccess); } }; - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + runTask(task); } - void NotificationService::removeBlockNotifiers() { - addMutexIfNotExist(internal::pathBlock); - auto callback = [pThis = shared_from_this()]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathBlock]); + void NotificationService::removeBlockNotifiers(std::function onSuccess, + std::function onError, + const std::vector& notifierIds) { + auto task = [pThis = shared_from_this(), notifierIds, onSuccess, onError]() { + for (const auto& id : notifierIds) { + pThis->_blockNotifiers.erase(id); + } - if (!pThis->_blockNotifiers.empty()) { - pThis->_subscriptionManager->unsubscribe(pThis->_uid, internal::pathBlock); + if (notifierIds.empty()) { pThis->_blockNotifiers.clear(); } - }; - - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } - } - - void NotificationService::addConfirmedAddedNotifiers(const Address& address, const std::initializer_list ¬ifiers) { - if (empty(notifiers)) { - XPX_CHAIN_SDK_THROW_1(notification_error, "list of notifiers is empty", __FUNCTION__) - } - - addMutexIfNotExist(internal::pathConfirmedAdded); - - auto callback = [pThis = shared_from_this(), address, notifiers]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathConfirmedAdded]); - const std::string hexAddress = ToHex(address.binary()); - if ( pThis->_confirmedAddedNotifiers.find(hexAddress) != pThis->_confirmedAddedNotifiers.end() ) { - pThis->_confirmedAddedNotifiers[hexAddress].insert(pThis->_confirmedAddedNotifiers[hexAddress].end(), notifiers.begin(), notifiers.end()); + if (pThis->_blockNotifiers.empty()) { + pThis->_subscriptionManager->unsubscribe(pThis->_uid, internal::pathBlock, onSuccess, onError); } else { - pThis->_confirmedAddedNotifiers.insert(std::pair>(hexAddress, notifiers)); - pThis->_subscriptionManager->subscribe(pThis->_uid, internal::pathConfirmedAdded, address); + pThis->runTask(onSuccess); } }; - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + runTask(task); } - void NotificationService::removeConfirmedAddedNotifiers(const Address& address) { - addMutexIfNotExist(internal::pathConfirmedAdded); - auto callback = [pThis = shared_from_this(), address]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathConfirmedAdded]); - - const std::string hexAddress = ToHex(address.binary()); - if (pThis->_confirmedAddedNotifiers.find(hexAddress) != pThis->_confirmedAddedNotifiers.end()) { - pThis->_subscriptionManager->unsubscribe(pThis->_uid, internal::pathConfirmedAdded, address); - pThis->_confirmedAddedNotifiers.erase(hexAddress); - } - }; - - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + void NotificationService::addConfirmedAddedNotifiers(const Address& address, const std::vector>& notifiers, + std::function onSuccess, + std::function onError) { + addNotifiers(address, internal::pathConfirmedAdded, _confirmedAddedNotifiers, notifiers, onSuccess, onError); } - void NotificationService::addUnconfirmedAddedNotifiers(const Address& address, const std::initializer_list ¬ifiers) { - if (empty(notifiers)) { - XPX_CHAIN_SDK_THROW_1(notification_error, "list of notifiers is empty", __FUNCTION__) - } - - addMutexIfNotExist(internal::pathUnconfirmedAdded); - - auto callback = [pThis = shared_from_this(), address, notifiers]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathUnconfirmedAdded]); - - const std::string hexAddress = ToHex(address.binary()); - if ( pThis->_unconfirmedAddedNotifiers.find(hexAddress) != pThis->_unconfirmedAddedNotifiers.end() ) { - pThis->_unconfirmedAddedNotifiers[hexAddress].insert(pThis->_unconfirmedAddedNotifiers[hexAddress].end(), notifiers.begin(), notifiers.end()); - } else { - pThis->_unconfirmedAddedNotifiers.insert(std::pair>(hexAddress, notifiers)); - pThis->_subscriptionManager->subscribe(pThis->_uid, internal::pathUnconfirmedAdded, address); - } - }; - - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + void NotificationService::removeConfirmedAddedNotifiers(const Address& address, std::function onSuccess, + std::function onError, + const std::vector& notifierIds) { + removeNotifiers(address, internal::pathConfirmedAdded, _confirmedAddedNotifiers, notifierIds, onSuccess, onError); } - void NotificationService::removeUnconfirmedAddedNotifiers(const Address& address) { - addMutexIfNotExist(internal::pathUnconfirmedAdded); - auto callback = [pThis = shared_from_this(), address]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathUnconfirmedAdded]); - - const std::string hexAddress = ToHex(address.binary()); - if (pThis->_unconfirmedAddedNotifiers.find(hexAddress) != pThis->_unconfirmedAddedNotifiers.end()) { - pThis->_subscriptionManager->unsubscribe(pThis->_uid, internal::pathUnconfirmedAdded, address); - pThis->_unconfirmedAddedNotifiers.erase(hexAddress); - } - }; - - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + void NotificationService::addUnconfirmedAddedNotifiers(const Address& address, const std::vector>& notifiers, + std::function onSuccess, + std::function onError) { + addNotifiers(address, internal::pathUnconfirmedAdded, _unconfirmedAddedNotifiers, notifiers, onSuccess, onError); } - void NotificationService::addUnconfirmedRemovedNotifiers(const Address& address, const std::initializer_list ¬ifiers) { - if (empty(notifiers)) { - XPX_CHAIN_SDK_THROW_1(notification_error, "list of notifiers is empty", __FUNCTION__) - } - - addMutexIfNotExist(internal::pathUnconfirmedRemoved); - - auto callback = [pThis = shared_from_this(), address, notifiers]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathUnconfirmedRemoved]); - - const std::string hexAddress = ToHex(address.binary()); - if ( pThis->_unconfirmedRemovedNotifiers.find(hexAddress) != pThis->_unconfirmedRemovedNotifiers.end() ) { - pThis->_unconfirmedRemovedNotifiers[hexAddress].insert(pThis->_unconfirmedRemovedNotifiers[hexAddress].end(), notifiers.begin(), notifiers.end()); - } else { - pThis->_unconfirmedRemovedNotifiers.insert(std::pair>(hexAddress, notifiers)); - pThis->_subscriptionManager->subscribe(pThis->_uid, internal::pathUnconfirmedRemoved, address); - } - }; - - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + void NotificationService::removeUnconfirmedAddedNotifiers(const Address& address, std::function onSuccess, + std::function onError, + const std::vector& notifierIds) { + removeNotifiers(address, internal::pathUnconfirmedAdded, _unconfirmedAddedNotifiers, notifierIds, onSuccess, onError); } - void NotificationService::removeUnconfirmedRemovedNotifiers(const Address& address) { - addMutexIfNotExist(internal::pathUnconfirmedRemoved); - auto callback = [pThis = shared_from_this(), address]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathUnconfirmedRemoved]); - - const std::string hexAddress = ToHex(address.binary()); - if (pThis->_unconfirmedRemovedNotifiers.find(hexAddress) != pThis->_unconfirmedRemovedNotifiers.end()) { - pThis->_subscriptionManager->unsubscribe(pThis->_uid, internal::pathUnconfirmedRemoved, address); - pThis->_unconfirmedRemovedNotifiers.erase(hexAddress); - } - }; - - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + void NotificationService::addUnconfirmedRemovedNotifiers(const Address& address, const std::vector>& notifiers, + std::function onSuccess, + std::function onError) { + addNotifiers(address, internal::pathUnconfirmedRemoved, _unconfirmedRemovedNotifiers, notifiers, onSuccess, onError); } - void NotificationService::addPartialAddedNotifiers(const Address& address, const std::initializer_list ¬ifiers) { - if (empty(notifiers)) { - XPX_CHAIN_SDK_THROW_1(notification_error, "list of notifiers is empty", __FUNCTION__) - } - - addMutexIfNotExist(internal::pathPartialAdded); - - auto callback = [pThis = shared_from_this(), address, notifiers]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathPartialAdded]); - - const std::string hexAddress = ToHex(address.binary()); - if ( pThis->_partialAddedNotifiers.find(hexAddress) != pThis->_partialAddedNotifiers.end() ) { - pThis->_partialAddedNotifiers[hexAddress].insert(pThis->_partialAddedNotifiers[hexAddress].end(), notifiers.begin(), notifiers.end()); - } else { - pThis->_partialAddedNotifiers.insert(std::pair>(hexAddress, notifiers)); - pThis->_subscriptionManager->subscribe(pThis->_uid, internal::pathPartialAdded, address); - } - }; - - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + void NotificationService::removeUnconfirmedRemovedNotifiers(const Address& address, + std::function onSuccess, + std::function onError, + const std::vector& notifierIds) { + removeNotifiers(address, internal::pathUnconfirmedRemoved, _unconfirmedRemovedNotifiers, notifierIds, onSuccess, onError); } - void NotificationService::removePartialAddedNotifiers(const Address& address) { - addMutexIfNotExist(internal::pathPartialAdded); - auto callback = [pThis = shared_from_this(), address]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathPartialAdded]); - - const std::string hexAddress = ToHex(address.binary()); - if (pThis->_partialAddedNotifiers.find(hexAddress) != pThis->_partialAddedNotifiers.end()) { - pThis->_subscriptionManager->unsubscribe(pThis->_uid, internal::pathPartialAdded, address); - pThis->_partialAddedNotifiers.erase(hexAddress); - } - }; - - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + void NotificationService::addPartialAddedNotifiers(const Address& address, + const std::vector>>& notifiers, + std::function onSuccess, + std::function onError) { + addNotifiers(address, internal::pathPartialAdded, _partialAddedNotifiers, notifiers, onSuccess, onError); } - void NotificationService::addPartialRemovedNotifiers(const Address& address, const std::initializer_list ¬ifiers) { - if (empty(notifiers)) { - XPX_CHAIN_SDK_THROW_1(notification_error, "list of notifiers is empty", __FUNCTION__) - } - - addMutexIfNotExist(internal::pathPartialRemoved); - - auto callback = [pThis = shared_from_this(), address, notifiers]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathPartialRemoved]); - - const std::string hexAddress = ToHex(address.binary()); - if ( pThis->_partialRemovedNotifiers.find(hexAddress) != pThis->_partialRemovedNotifiers.end() ) { - pThis->_partialRemovedNotifiers[hexAddress].insert(pThis->_partialRemovedNotifiers[hexAddress].end(), notifiers.begin(), notifiers.end()); - } else { - pThis->_partialRemovedNotifiers.insert(std::pair>(hexAddress, notifiers)); - pThis->_subscriptionManager->subscribe(pThis->_uid, internal::pathPartialRemoved, address); - } - }; - - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + void NotificationService::removePartialAddedNotifiers(const Address& address, + std::function onSuccess, + std::function onError, + const std::vector& notifierIds) { + removeNotifiers(address, internal::pathPartialAdded, _partialAddedNotifiers, notifierIds, onSuccess, onError); } - void NotificationService::removePartialRemovedNotifiers(const Address& address) { - addMutexIfNotExist(internal::pathPartialRemoved); - auto callback = [pThis = shared_from_this(), address]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathPartialRemoved]); - - const std::string hexAddress = ToHex(address.binary()); - if (pThis->_partialRemovedNotifiers.find(hexAddress) != pThis->_partialRemovedNotifiers.end()) { - pThis->_subscriptionManager->unsubscribe(pThis->_uid, internal::pathPartialRemoved, address); - pThis->_partialRemovedNotifiers.erase(hexAddress); - } - }; - - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + void NotificationService::addPartialRemovedNotifiers(const Address& address, + const std::vector>& notifiers, + std::function onSuccess, + std::function onError) { + addNotifiers(address, internal::pathPartialRemoved, _partialRemovedNotifiers, notifiers, onSuccess, onError); } - void NotificationService::addStatusNotifiers(const Address& address, const std::initializer_list& notifiers) { - if (empty(notifiers)) { - XPX_CHAIN_SDK_THROW_1(notification_error, "list of notifiers is empty", __FUNCTION__) - } - - addMutexIfNotExist(internal::pathStatus); - - auto callback = [pThis = shared_from_this(), address, notifiers]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathStatus]); - - const std::string hexAddress = ToHex(address.binary()); - if ( pThis->_statusNotifiers.find(hexAddress) != pThis->_statusNotifiers.end() ) { - pThis->_statusNotifiers[hexAddress].insert(pThis->_statusNotifiers[hexAddress].end(), notifiers.begin(), notifiers.end()); - } else { - pThis->_statusNotifiers.insert(std::pair>(hexAddress, notifiers)); - pThis->_subscriptionManager->subscribe(pThis->_uid, internal::pathStatus, address); - } - }; - - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + void NotificationService::removePartialRemovedNotifiers(const Address& address, + std::function onSuccess, + std::function onError, + const std::vector& notifierIds) { + removeNotifiers(address, internal::pathPartialRemoved, _partialRemovedNotifiers, notifierIds, onSuccess, onError); } - void NotificationService::removeStatusNotifiers(const Address& address) { - addMutexIfNotExist(internal::pathStatus); - auto callback = [pThis = shared_from_this(), address]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathStatus]); - - const std::string hexAddress = ToHex(address.binary()); - if (pThis->_statusNotifiers.find(hexAddress) != pThis->_statusNotifiers.end()) { - pThis->_subscriptionManager->unsubscribe(pThis->_uid, internal::pathStatus, address); - pThis->_statusNotifiers.erase(hexAddress); - } - }; - - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + void NotificationService::addStatusNotifiers(const Address& address, + const std::vector>& notifiers, + std::function onSuccess, + std::function onError) { + addNotifiers(address, internal::pathStatus, _statusNotifiers, notifiers, onSuccess, onError); } - void NotificationService::addCosignatureNotifiers(const Address& address, const std::initializer_list ¬ifiers) { - if (empty(notifiers)) { - XPX_CHAIN_SDK_THROW_1(notification_error, "list of notifiers is empty", __FUNCTION__) - } - - addMutexIfNotExist(internal::pathCosignature); - - auto callback = [pThis = shared_from_this(), address, notifiers]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathCosignature]); - - const std::string hexAddress = ToHex(address.binary()); - if ( pThis->_cosignatureNotifiers.find(hexAddress) != pThis->_cosignatureNotifiers.end() ) { - pThis->_cosignatureNotifiers[hexAddress].insert(pThis->_cosignatureNotifiers[hexAddress].end(), notifiers.begin(), notifiers.end()); - } else { - pThis->_cosignatureNotifiers.insert(std::pair>(hexAddress, notifiers)); - pThis->_subscriptionManager->subscribe(pThis->_uid, internal::pathCosignature, address); - } - }; - - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + void NotificationService::removeStatusNotifiers(const Address& address, + std::function onSuccess, + std::function onError, + const std::vector& notifierIds) { + removeNotifiers(address, internal::pathStatus, _statusNotifiers, notifierIds, onSuccess, onError); } - void NotificationService::removeCosignatureNotifiers(const Address& address) { - addMutexIfNotExist(internal::pathCosignature); - auto callback = [pThis = shared_from_this(), address]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathCosignature]); - - const std::string hexAddress = ToHex(address.binary()); - if (pThis->_cosignatureNotifiers.find(hexAddress) != pThis->_cosignatureNotifiers.end()) { - pThis->_subscriptionManager->unsubscribe(pThis->_uid, internal::pathCosignature, address); - pThis->_cosignatureNotifiers.erase(hexAddress); - } - }; - - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + void NotificationService::addCosignatureNotifiers(const Address& address, + const std::vector>& notifiers, + std::function onSuccess, + std::function onError) { + addNotifiers(address, internal::pathCosignature, _cosignatureNotifiers, notifiers, onSuccess, onError); } - void NotificationService::addDriveStateNotifiers(const Address& address, const std::initializer_list ¬ifiers) { - if (empty(notifiers)) { - XPX_CHAIN_SDK_THROW_1(notification_error, "list of notifiers is empty", __FUNCTION__) - } - - addMutexIfNotExist(internal::pathDriveState); - - auto callback = [pThis = shared_from_this(), address, notifiers]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathDriveState]); - - const std::string hexAddress = ToHex(address.binary()); - if ( pThis->_driveStateNotifiers.find(hexAddress) != pThis->_driveStateNotifiers.end() ) { - pThis->_driveStateNotifiers[hexAddress].insert(pThis->_driveStateNotifiers[hexAddress].end(), notifiers.begin(), notifiers.end()); - } else { - pThis->_driveStateNotifiers.insert(std::pair>(hexAddress, notifiers)); - pThis->_subscriptionManager->subscribe(pThis->_uid, internal::pathDriveState, address); - } - }; - - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + void NotificationService::removeCosignatureNotifiers(const Address& address, + std::function onSuccess, + std::function onError, + const std::vector& notifierIds) { + removeNotifiers(address, internal::pathCosignature, _cosignatureNotifiers, notifierIds, onSuccess, onError); } - void NotificationService::removeDriveStateNotifiers(const Address& address) { - addMutexIfNotExist(internal::pathDriveState); - auto callback = [pThis = shared_from_this(), address]() { - std::lock_guard lock(*pThis->_notifiersMutexes[internal::pathDriveState]); + void NotificationService::addDriveStateNotifiers(const Address& address, + const std::vector>& notifiers, + std::function onSuccess, + std::function onError) { + addNotifiers(address, internal::pathDriveState, _driveStateNotifiers, notifiers, onSuccess, onError); + } - const std::string hexAddress = ToHex(address.binary()); - if (pThis->_driveStateNotifiers.find(hexAddress) != pThis->_driveStateNotifiers.end()) { - pThis->_subscriptionManager->unsubscribe(pThis->_uid, internal::pathDriveState, address); - pThis->_driveStateNotifiers.erase(hexAddress); - } - }; + void NotificationService::removeDriveStateNotifiers(const Address& address, + std::function onSuccess, + std::function onError, + const std::vector& notifierIds) { + removeNotifiers(address, internal::pathDriveState, _driveStateNotifiers, notifierIds, onSuccess, onError); + } - if (!_isInitialized) { - initialize(callback); - } else { - callback(); - } + void NotificationService::connect(std::function callback) { + _connectionCallback = callback; + run(); } } \ No newline at end of file diff --git a/src/sdk/client/storage_service.cpp b/src/sdk/client/storage_service.cpp new file mode 100644 index 0000000..2e6f48e --- /dev/null +++ b/src/sdk/client/storage_service.cpp @@ -0,0 +1,105 @@ + +/* +*** Copyright 2019 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +*/ + +#include +#include +#include +#include +#include +#include + +using namespace xpx_chain_sdk; + +using internal::json::dto::from_json; +using internal::json::dto::transactions_from_json; +using internal::json::dto::DriveDto; +using internal::json::dto::drives_page::DrivesPageDto; +using internal::json::dto::DownloadChannelDto; +using internal::json::dto::download_channels_page::DownloadChannelsPageDto; +using internal::json::dto::ReplicatorDto; +using internal::json::dto::replicators_page::ReplicatorsPageDto; + + +StorageService::StorageService( + const Config& config, + std::shared_ptr context +) : + _config(std::move(config)), + _context(std::move(context)) +{}; + +Drive StorageService::getDriveById(const std::string& id) { + std::stringstream path; + path << "bcdrives/" << id; + + RequestParamsBuilder builder(_config); + builder.setPath(path.str()); + builder.setMethod(internal::network::HTTPRequestMethod::GET); + + std::string response = internal::network::performHTTPRequest(_context, builder.getRequestParams()); + return from_json(response); +} + +drives_page::DrivesPage StorageService::getDrives(const DrivesPageOptions& options) { + std::stringstream path; + path << "bcdrives"; + + RequestParamsBuilder builder(_config); + builder.setPath(path.str(), options.toMap()); + builder.setMethod(internal::network::HTTPRequestMethod::GET); + + std::string response = internal::network::performHTTPRequest(_context, builder.getRequestParams()); + return from_json(response); +} + +Replicator StorageService::getReplicatorById(const std::string &id) { + std::stringstream path; + path << "replicators/" << id; + + RequestParamsBuilder builder(_config); + builder.setPath(path.str()); + builder.setMethod(internal::network::HTTPRequestMethod::GET); + + std::string response = internal::network::performHTTPRequest(_context, builder.getRequestParams()); + return from_json(response); +} + +replicators_page::ReplicatorsPage StorageService::getReplicators(const ReplicatorsPageOptions& options) { + std::stringstream path; + path << "replicators"; + + RequestParamsBuilder builder(_config); + builder.setPath(path.str(), options.toMap()); + builder.setMethod(internal::network::HTTPRequestMethod::GET); + + std::string response = internal::network::performHTTPRequest(_context, builder.getRequestParams()); + return from_json(response); +} + +DownloadChannel StorageService::getDownloadChannelById(const std::string &id) { + std::stringstream path; + path << "download_channels/" << id; + + RequestParamsBuilder builder(_config); + builder.setPath(path.str()); + builder.setMethod(internal::network::HTTPRequestMethod::GET); + + std::string response = internal::network::performHTTPRequest(_context, builder.getRequestParams()); + return from_json(response); +} + +download_channels_page::DownloadChannelsPage StorageService::getDownloadChannels(const DownloadChannelsPageOptions& options) { + std::stringstream path; + path << "download_channels"; + + RequestParamsBuilder builder(_config); + builder.setPath(path.str(), options.toMap()); + builder.setMethod(internal::network::HTTPRequestMethod::GET); + + std::string response = internal::network::performHTTPRequest(_context, builder.getRequestParams()); + return from_json(response); +} \ No newline at end of file diff --git a/src/sdk/client/supercontract_v2_service.cpp b/src/sdk/client/supercontract_v2_service.cpp new file mode 100644 index 0000000..20c72ee --- /dev/null +++ b/src/sdk/client/supercontract_v2_service.cpp @@ -0,0 +1,41 @@ +/* +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +*/ + +#include +#include + +#include +#include + +#include +#include + +using namespace xpx_chain_sdk; +using namespace xpx_chain_sdk::internal::json::dto; + +using xpx_chain_sdk::internal::json::Parser; +using xpx_chain_sdk::internal::json::dto::from_json; + +SuperContractV2Service::SuperContractV2Service( + const Config& config, + std::shared_ptr context +) : + _config(std::move(config)), + _context(std::move(context)) +{}; + +//SuperContractV2 SuperContractV2Service::getSuperContractByKey(const std::string& contractKey) { +// std::stringstream path; +// path << "supercontracts/" << contractKey; +// +// RequestParamsBuilder builder(_config); +// builder.setPath(path.str()); +// builder.setMethod(internal::network::HTTPRequestMethod::GET); +// +// std::string response = internal::network::performHTTPRequest(_context, builder.getRequestParams()); +// auto result = from_json(response); +// return result; +//} diff --git a/src/sdk/client/transaction_service.cpp b/src/sdk/client/transaction_service.cpp index 96a278b..e881650 100644 --- a/src/sdk/client/transaction_service.cpp +++ b/src/sdk/client/transaction_service.cpp @@ -23,7 +23,7 @@ namespace xpx_chain_sdk { using internal::json::dto::MultipleTransactionStatusDto; TransactionService::TransactionService( - std::shared_ptr config, + const Config& config, std::shared_ptr context) :_config(config), _context(context) {} std::shared_ptr TransactionService::getTransactionInfo(TransactionGroup group, const std::string &id) { @@ -100,8 +100,6 @@ namespace xpx_chain_sdk { std::string payloadStr = bytes_to_string(payload); requestJson = R"({"payload":")" + payloadStr + "\"}"; - std::cout << requestJson << std::endl; - std::string path = "transactions"; RequestParamsBuilder builder(_config); @@ -109,55 +107,42 @@ namespace xpx_chain_sdk { builder.setMethod(internal::network::HTTPRequestMethod::PUT); builder.setRequestBody(requestJson); - try { - internal::network::performHTTPRequest(_context, builder.getRequestParams()); - } - catch(std::exception& e) { - std::cout << e.what() << std::endl; - throw e; - } + internal::network::performHTTPRequest(_context, builder.getRequestParams()); + return true; } bool TransactionService::announceAggregateBoundedTransaction(const std::vector &payload) { std::string requestJson; std::string payloadStr = bytes_to_string(payload); - requestJson = "{\"payload\":" + payloadStr + "}"; + requestJson = R"({"payload":")" + payloadStr + "\"}"; - std::string path = "transaction/partial"; + std::string path = "transactions/partial"; RequestParamsBuilder builder(_config); builder.setPath(path); builder.setMethod(internal::network::HTTPRequestMethod::PUT); builder.setRequestBody(requestJson); - try { - internal::network::performHTTPRequest(_context, builder.getRequestParams()); - } - catch(std::exception& e) { - throw e; - } + internal::network::performHTTPRequest(_context, builder.getRequestParams()); + return true; } bool TransactionService::announceCosignatureTransaction(const std::vector &payload) { std::string requestJson; std::string payloadStr = bytes_to_string(payload); - requestJson = "{\"payload\":" + payloadStr + "}"; + requestJson = R"({"payload":")" + payloadStr + "\"}"; - std::string path = "transaction/cosignature"; + std::string path = "transactions/cosignature"; RequestParamsBuilder builder(_config); builder.setPath(path); builder.setMethod(internal::network::HTTPRequestMethod::PUT); builder.setRequestBody(requestJson); - try { - internal::network::performHTTPRequest(_context, builder.getRequestParams()); - } - catch(std::exception& e) { - throw e; - } + internal::network::performHTTPRequest(_context, builder.getRequestParams()); + return true; } diff --git a/src/sdk/crypto/private_key.cpp b/src/sdk/crypto/private_key.cpp index f398ccc..de448b3 100644 --- a/src/sdk/crypto/private_key.cpp +++ b/src/sdk/crypto/private_key.cpp @@ -23,7 +23,7 @@ namespace xpx_chain_sdk { PrivateKey::PrivateKey(const supplier& generator) { - std::generate_n(key_.begin(), (long int) key_.end(), generator); + std::generate_n(key_.begin(), (long int) *(key_.end()), generator); } PrivateKey::PrivateKey(PrivateKey&& rhs) noexcept: PrivateKey(rhs.key_.data(), rhs.key_.size()) diff --git a/src/sdk/model/account/address.cpp b/src/sdk/model/account/address.cpp index 727b29c..6a14583 100644 --- a/src/sdk/model/account/address.cpp +++ b/src/sdk/model/account/address.cpp @@ -137,7 +137,7 @@ namespace xpx_chain_sdk { Address Address::FromHex(const std::string& hexAddress) { AddressData addressData; ParseHexStringIntoContainer(hexAddress.c_str(), hexAddress.size(), addressData); - return Address(addressData); + return { addressData }; } bool Address::DecodeAndCheck(std::string_view encodedAddress, AddressData& addressData) diff --git a/src/sdk/model/transaction/automatic_execution_transaction.cpp b/src/sdk/model/transaction/automatic_execution_transaction.cpp new file mode 100644 index 0000000..b9c6c4f --- /dev/null +++ b/src/sdk/model/transaction/automatic_execution_transaction.cpp @@ -0,0 +1,24 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ + +#include + +namespace xpx_chain_sdk { + + template + const Key& TAutomaticExecutionsPaymentTransaction::contractKey() const { + return contractKey_; + } + + + template + uint32_t TAutomaticExecutionsPaymentTransaction::automaticExecutionsNumber() const { + return automaticExecutionsNumber_; + } + + template class TAutomaticExecutionsPaymentTransaction; + template class TAutomaticExecutionsPaymentTransaction; +} \ No newline at end of file diff --git a/src/sdk/model/transaction/create_liquidity_provider_transaction.cpp b/src/sdk/model/transaction/create_liquidity_provider_transaction.cpp new file mode 100644 index 0000000..54cffdd --- /dev/null +++ b/src/sdk/model/transaction/create_liquidity_provider_transaction.cpp @@ -0,0 +1,60 @@ +/** +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#include + +namespace xpx_chain_sdk { + + template + MosaicId TCreateLiquidityProviderTransaction::providerMosaicId() const + { + return providerMosaicId_; + } + + template + Amount TCreateLiquidityProviderTransaction::currencyDeposit() const + { + return currencyDeposit_; + } + + template + Amount TCreateLiquidityProviderTransaction::initialMosaicsMinting() const + { + return initialMosaicsMinting_; + } + + template + uint32_t TCreateLiquidityProviderTransaction::slashingPeriod() const + { + return slashingPeriod_; + } + + template + uint16_t TCreateLiquidityProviderTransaction::windowSize() const + { + return windowSize_; + } + + template + const Key& TCreateLiquidityProviderTransaction::slashingAccount() const + { + return slashingAccount_; + } + + template + uint32_t TCreateLiquidityProviderTransaction::alpha() const + { + return alpha_; + } + + template + uint32_t TCreateLiquidityProviderTransaction::beta() const + { + return beta_; + } + + template class TCreateLiquidityProviderTransaction; + template class TCreateLiquidityProviderTransaction; +} diff --git a/src/sdk/model/transaction/create_transaction.cpp b/src/sdk/model/transaction/create_transaction.cpp index 27eccbb..212428e 100644 --- a/src/sdk/model/transaction/create_transaction.cpp +++ b/src/sdk/model/transaction/create_transaction.cpp @@ -207,16 +207,15 @@ namespace xpx_chain_sdk { namespace internal { void InitMosaicDefinitionTransactionDTO(TDto& dto, uint32_t mosaicNonce, MosaicId mosaicId, - MosaicFlags flags, const MosaicProperties& mosaicProperties, TArgs&&... args) { - dto.template set<"nonce"_>(mosaicNonce); + dto.template set<"mosaicNonce"_>(mosaicNonce); dto.template set<"mosaicId"_>(mosaicId); dto.template set<"optionalPropertiesCount"_>(mosaicProperties.size() - 2); - dto.template set<"flags"_>(flags);// TODO:(mosaicProperties.flags()); + dto.template set<"flags"_>(mosaicProperties.flags()); dto.template set<"divisibility"_>(mosaicProperties.divisibility()); - + std::for_each(mosaicProperties.optionalBegin(), mosaicProperties.end(), [&dto](const auto& property) { dto.template value<"optionalProperties"_>().push_back(MosaicPropertyDTO{ property.id, property.value }); }); @@ -294,7 +293,23 @@ namespace xpx_chain_sdk { namespace internal { InitTransactionDTO(dto, TransactionType::Secret_Proof, std::forward(args)...); } - + + template + void InitStoragePaymentTransactionDTO(TDto& dto, + const Key& driveKey, + const Amount& storageUnits, + TArgs&&... args) + { + if (driveKey.empty()) { + XPX_CHAIN_SDK_THROW(transaction_error, "empty drive key in storage payment transaction"); + } + + dto.template set<"driveKey"_>(driveKey); + dto.template set<"storageUnits"_>(storageUnits); + + InitTransactionDTO(dto, TransactionType::Storage_Payment, std::forward(args)...); + } + template void InitTransferTransactionDTO(TDto& dto, const Address& recipient, @@ -312,7 +327,7 @@ namespace xpx_chain_sdk { namespace internal { std::vector dtoMosaics; for (const auto& mosaic: mosaics) { - dtoMosaics.push_back(MosaicDTO{ mosaic.id, mosaic.amount }); + dtoMosaics.emplace_back( mosaic.id, mosaic.amount ); } dto.template set<"recipient"_>(recipient.binary()); @@ -443,7 +458,7 @@ namespace xpx_chain_sdk { namespace internal { EmbeddedMosaicDefinitionTransactionDTO dto; InitMosaicDefinitionTransactionDTO( - dto, tx->mosaicNonce(), tx->mosaicId(), tx -> flags(), tx->mosaicProperties(), + dto, tx->mosaicNonce(), tx->mosaicId(), tx->mosaicProperties(), tx->signer().publicKey(), tx->networkId()); AppendDtoData(dto, payload); @@ -537,27 +552,73 @@ namespace xpx_chain_sdk { namespace internal { } template - void InitPrepareBcDriveTransactionDTO(TDto& dto, - uint64_t driveSize, - uint16_t replicatorCount, - TArgs&&... args) + void InitPrepareBcDriveTransactionDTO(TDto& dto, + uint64_t driveSize, + const Amount& verificationFeeAmount, + uint16_t replicatorCount, + TArgs&&... args) { dto.template set<"driveSize"_>(driveSize); + dto.template set<"verificationFeeAmount"_>(verificationFeeAmount); dto.template set<"replicatorCount"_>(replicatorCount); InitTransactionDTO(dto, TransactionType::Prepare_Bc_Drive, std::forward(args)...); } + template + void InitCreateLiquidityProviderTransactionDTO(TDto& dto, + const MosaicId providerMosaicId, + const Amount currencyDeposit, + const Amount initialMosaicsMinting, + const uint32_t slashingPeriod, + const uint16_t windowSize, + const Key& slashingAccount, + const uint32_t alpha, + const uint32_t beta, + TArgs&&... args) + { + dto.template set<"providerMosaicId"_>(providerMosaicId); + dto.template set<"currencyDeposit"_>(currencyDeposit); + dto.template set<"initialMosaicsMinting"_>(initialMosaicsMinting); + dto.template set<"slashingPeriod"_>(slashingPeriod); + dto.template set<"windowSize"_>(windowSize); + dto.template set<"slashingAccount"_>(slashingAccount); + dto.template set<"alpha"_>(alpha); + dto.template set<"beta"_>(beta); + + InitTransactionDTO(dto, TransactionType::Create_Liquidity_Provider, std::forward(args)...); + } + + template + void InitManualRateChangeTransactionDTO(TDto& dto, + const MosaicId providerMosaicId, + const bool currencyBalanceIncrease, + const Amount currencyBalanceChange, + const bool mosaicBalanceIncrease, + const Amount mosaicBalanceChange, + TArgs&&... args) + { + dto.template set<"providerMosaicId"_>(providerMosaicId); + dto.template set<"currencyBalanceIncrease"_>(currencyBalanceIncrease); + dto.template set<"currencyBalanceChange"_>(currencyBalanceChange); + dto.template set<"mosaicBalanceIncrease"_>(mosaicBalanceIncrease); + dto.template set<"mosaicBalanceChange"_>(mosaicBalanceChange); + + InitTransactionDTO(dto, TransactionType::Manual_Rate_Change, std::forward(args)...); + } + template - void InitDataModificationTransactionDTO(TDto& dto, - const Key& driveKey, - const Hash256& downloadDataCdi, - uint64_t uploadSize, - TArgs&&... args) + void InitDataModificationTransactionDTO(TDto& dto, + const Key& driveKey, + const Hash256& downloadDataCdi, + uint64_t uploadSize, + const Amount& feedbackFeeAmount, + TArgs&&... args) { dto.template set<"driveKey"_>(driveKey); dto.template set<"downloadDataCdi"_>(downloadDataCdi); dto.template set<"uploadSize"_>(uploadSize); + dto.template set<"feedbackFeeAmount"_>(feedbackFeeAmount); InitTransactionDTO(dto, TransactionType::Data_Modification, std::forward(args)...); } @@ -566,30 +627,94 @@ namespace xpx_chain_sdk { namespace internal { void InitDownloadTransactionDTO(TDto& dto, const Key& driveKey, uint64_t downloadSize, - const Amount& transactionFee, + const Amount& feedbackFeeAmount, + uint16_t listOfPublicKeysSize, + const std::vector& listOfPublicKeys, TArgs&&... args) { dto.template set<"driveKey"_>(driveKey); dto.template set<"downloadSize"_>(downloadSize); - dto.template set<"transactionFee"_>(transactionFee); + dto.template set<"feedbackFeeAmount"_>(feedbackFeeAmount); + dto.template set<"listOfPublicKeysSize"_>(listOfPublicKeysSize); + dto.template set<"listOfPublicKeys"_>(listOfPublicKeys); + dto.template isSet<"listOfPublicKeys"_>() = true; InitTransactionDTO(dto, TransactionType::Download, std::forward(args)...); } + template + void InitDownloadPaymentTransactionDTO(TDto& dto, + const Hash256& downloadChannelId, + uint64_t downloadSize, + const Amount& feedbackFeeAmount, + TArgs&&... args) + { + if (downloadChannelId.empty()) { + XPX_CHAIN_SDK_THROW(transaction_error, "empty download channel id in download payment transaction"); + } + + dto.template set<"downloadChannelId"_>(downloadChannelId); + dto.template set<"downloadSize"_>(downloadSize); + dto.template set<"feedbackFeeAmount"_>(feedbackFeeAmount); + + InitTransactionDTO(dto, TransactionType::Download_Payment, std::forward(args)...); + } + + template + void InitDriveClosureTransactionDTO(TDto& dto, + const Key& driveKey, + TArgs&&... args) + { + if (driveKey.empty()) { + XPX_CHAIN_SDK_THROW(transaction_error, "empty drive key in drive closure transaction"); + } + + dto.template set<"driveKey"_>(driveKey); + + InitTransactionDTO(dto, TransactionType::Drive_Closure, std::forward(args)...); + } + template void InitDataModificationApprovalTransactionDTO(TDto& dto, - const Key& driveKey, - const Hash256& dataModificationId, - const Hash256& fileStructureCdi, - uint64_t fileStructureSize, - uint64_t usedDriveSize, - TArgs&&... args) + const Key& driveKey, + const Hash256& dataModificationId, + const Hash256& fileStructureCdi, + uint8_t modificationStatus, + uint64_t fileStructureSizeBytes, + uint64_t metaFilesSizeBytes, + uint64_t usedDriveSizeBytes, + uint8_t judgingKeysCount, + uint8_t overlappingKeysCount, + uint8_t judgedKeysCount, + uint16_t opinionElementCount, + const std::vector& publicKeys, + const std::vector& signatures, + const std::vector& presentOpinions, + const std::vector& opinions, + TArgs&&... args) { dto.template set<"driveKey"_>(driveKey); dto.template set<"dataModificationId"_>(dataModificationId); dto.template set<"fileStructureCdi"_>(fileStructureCdi); - dto.template set<"fileStructureSize"_>(fileStructureSize); - dto.template set<"usedDriveSize"_>(usedDriveSize); + dto.template set<"modificationStatus"_>(modificationStatus); + dto.template set<"fileStructureSizeBytes"_>(fileStructureSizeBytes); + dto.template set<"metaFilesSizeBytes"_>(metaFilesSizeBytes); + dto.template set<"usedDriveSizeBytes"_>(usedDriveSizeBytes); + dto.template set<"judgingKeysCount"_>(judgingKeysCount); + dto.template set<"overlappingKeysCount"_>(overlappingKeysCount); + dto.template set<"judgedKeysCount"_>(judgedKeysCount); + dto.template set<"opinionElementCount"_>(opinionElementCount); + dto.template set<"publicKeys"_>(publicKeys); + dto.template isSet<"publicKeys"_>() = true; + + dto.template set<"signatures"_>(signatures); + dto.template isSet<"signatures"_>() = true; + + dto.template set<"presentOpinions"_>(presentOpinions); + dto.template isSet<"presentOpinions"_>() = true; + + dto.template set<"opinions"_>(opinions); + dto.template isSet<"opinions"_>() = true; InitTransactionDTO(dto, TransactionType::Data_Modification_Approval, std::forward(args)...); } @@ -606,13 +731,29 @@ namespace xpx_chain_sdk { namespace internal { InitTransactionDTO(dto, TransactionType::Data_Modification_Cancel, std::forward(args)...); } + template + void InitFinishDownloadTransactionDTO(TDto& dto, + const Hash256& downloadChannelId, + const Amount& feedbackFeeAmount, + TArgs&&... args) + { + if (downloadChannelId.empty()) { + XPX_CHAIN_SDK_THROW(transaction_error, "empty download channel id in finish download transaction"); + } + + dto.template set<"downloadChannelId"_>(downloadChannelId); + dto.template set<"feedbackFeeAmount"_>(feedbackFeeAmount); + + InitTransactionDTO(dto, TransactionType::Finish_Download, std::forward(args)...); + } + template - void InitReplicatorOnboardingTransactionDTO(TDto& dto, - const Amount& capacity, - const Key& nodeBootKey, - const Hash256& message, - const Signature& messageSignature, - TArgs&&... args) + void InitReplicatorOnboardingTransactionDTO(TDto& dto, + const Amount& capacity, + const Key& nodeBootKey, + const Hash256& message, + const Signature& messageSignature, + TArgs&&... args) { dto.template set<"capacity"_>(capacity); dto.template set<"nodeBootKey"_>(nodeBootKey); @@ -622,6 +763,152 @@ namespace xpx_chain_sdk { namespace internal { InitTransactionDTO(dto, TransactionType::Replicator_Onboarding, std::forward(args)...); } + template + void InitReplicatorOffboardingTransactionDTO(TDto& dto, + const Key& driveKey, + TArgs&&... args) + { + dto.template set<"driveKey"_>(driveKey); + + InitTransactionDTO(dto, TransactionType::Replicator_Offboarding, std::forward(args)...); + } + + template + void InitDeployContractTransactionDTO(TDto& dto, + const Key& driveKey, + const std::string& fileName, + const std::string& functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + const MosaicContainer& servicePayments, + const std::string& automaticExecutionsFileName, + const std::string& automaticExecutionsFunctionName, + const Amount& automaticExecutionsCallPayment, + const Amount& automaticDownloadCallPayment, + uint32_t automaticExecutionsNumber, + const Key& assignee, + TArgs&&... args) + { + std::vector dtoServicePayments; + for (const auto& servicePayment: servicePayments) { + dtoServicePayments.emplace_back( servicePayment.id, servicePayment.amount ); + } + + dto.template set<"driveKey"_>(driveKey); + dto.template set<"fileNameSize"_>(fileName.size()); + dto.template set<"fileName"_>(fileName); + dto.template set<"functionNameSize"_>(functionName.size()); + dto.template set<"functionName"_>(functionName); + dto.template set<"actualArgumentsSize"_>(actualArguments.size()); + dto.template set<"actualArguments"_>(actualArguments); + dto.template set<"executionCallPayment"_>(executionCallPayment); + dto.template set<"downloadCallPayment"_>(downloadCallPayment); + dto.template set<"servicePaymentsCount"_>(servicePayments.size()); + dto.template set<"servicePayments"_>(std::move(dtoServicePayments)); + dto.template set<"automaticExecutionsFileNameSize"_>(automaticExecutionsFileName.size()); + dto.template set<"automaticExecutionsFileName"_>(automaticExecutionsFileName); + dto.template set<"automaticExecutionsFunctionNameSize"_>(automaticExecutionsFunctionName.size()); + dto.template set<"automaticExecutionsFunctionName"_>(automaticExecutionsFunctionName); + dto.template set<"automaticExecutionsCallPayment"_>(automaticExecutionsCallPayment); + dto.template set<"automaticDownloadCallPayment"_>(automaticDownloadCallPayment); + dto.template set<"automaticExecutionsNumber"_>(automaticExecutionsNumber); + dto.template set<"assignee"_>(assignee); + + InitTransactionDTO(dto, TransactionType::Deploy_Contract, std::forward(args)...); + } + + template + void InitManualCallTransactionDTO(TDto& dto, + const Key& contractKey, + const std::string& fileName, + const std::string& functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + const MosaicContainer& servicePayments, + TArgs&&... args) + { + std::vector dtoServicePayments; + for (const auto& servicePayment: servicePayments) { + dtoServicePayments.emplace_back( servicePayment.id, servicePayment.amount ); + } + + dto.template set<"contractKey"_>(contractKey); + dto.template set<"fileNameSize"_>(fileName.size()); + dto.template set<"fileName"_>(fileName); + dto.template set<"functionNameSize"_>(functionName.size()); + dto.template set<"functionName"_>(functionName); + dto.template set<"actualArgumentsSize"_>(actualArguments.size()); + dto.template set<"actualArguments"_>(actualArguments); + dto.template set<"executionCallPayment"_>(executionCallPayment); + dto.template set<"downloadCallPayment"_>(downloadCallPayment); + dto.template set<"servicePaymentsCount"_>(servicePayments.size()); + dto.template set<"servicePayments"_>(std::move(dtoServicePayments)); + + InitTransactionDTO(dto, TransactionType::Manual_Call, std::forward(args)...); + } + + template + void InitAutomaticExecutionsPaymentTransactionDTO(TDto& dto, + const Key& contractKey, + uint32_t automaticExecutionsNumber, + TArgs&&... args) + { + dto.template set<"contractKey"_>(contractKey); + dto.template set<"automaticExecutionsNumber"_>(automaticExecutionsNumber); + + InitTransactionDTO(dto, TransactionType::Automatic_Executions_Payment, std::forward(args)...); + } + + template + void InitStreamStartTransactionDTO(TDto &dto, + const Key &driveKey, + const uint64_t expectedUploadSizeMegabytes, + const uint16_t folderNameSize, + const Amount &feedbackFeeAmount, + const std::vector& folderName, + TArgs &&... args) + { + dto.template set<"driveKey"_>(driveKey); + dto.template set<"expectedUploadSizeMegabytes"_>(expectedUploadSizeMegabytes); + dto.template set<"folderNameSize"_>(folderNameSize); + dto.template set<"feedbackFeeAmount"_>(feedbackFeeAmount); + dto.template set<"folderName"_>(folderName); + + InitTransactionDTO(dto, TransactionType::Stream_Start, std::forward(args)...); + } + + template + void InitStreamFinishTransactionDTO(TDto &dto, + const Key &driveKey, + const Hash256 &streamId, + const uint64_t actualUploadSizeMegabytes, + const Hash256 &streamStructureCdi, + TArgs &&... args) + { + dto.template set<"driveKey"_>(driveKey); + dto.template set<"streamId"_>(streamId); + dto.template set<"actualUploadSize"_>(actualUploadSizeMegabytes); + dto.template set<"streamStructureCdi"_>(streamStructureCdi); + + InitTransactionDTO(dto, TransactionType::Stream_Finish, std::forward(args)...); + } + + template + void InitStreamPaymentTransactionDTO(TDto &dto, + const Key &driveKey, + const Hash256 &streamId, + const uint64_t additionalUploadSizeMegabytes, + TArgs &&... args) + { + dto.template set<"driveKey"_>(driveKey); + dto.template set<"streamId"_>(streamId); + dto.template set<"additionalUploadSize"_>(additionalUploadSizeMegabytes); + + InitTransactionDTO(dto, TransactionType::Stream_Payment, std::forward(args)...); + } + template void InitReplicatorsCleanupTransactionDTO(TDto& dto, const std::vector& replicatorKeys, @@ -791,7 +1078,6 @@ namespace xpx_chain_sdk { namespace internal { std::unique_ptr CreateMosaicDefinitionTransactionImpl(uint32_t mosaicNonce, MosaicId mosaicId, - MosaicFlags flags, MosaicProperties mosaicProperties, std::optional maxFee, std::optional deadline, @@ -802,10 +1088,10 @@ namespace xpx_chain_sdk { namespace internal { { MosaicDefinitionTransactionDTO dto; InitMosaicDefinitionTransactionDTO( - dto, mosaicNonce, mosaicId, flags, mosaicProperties, maxFee, deadline, networkId, signer, signature); + dto, mosaicNonce, mosaicId, mosaicProperties, maxFee, deadline, networkId, signer, signature); return CreateTransaction( - dto, signer, signature, info, mosaicNonce, mosaicId, flags, std::move(mosaicProperties)); + dto, signer, signature, info, mosaicNonce, mosaicId, std::move(mosaicProperties)); } std::unique_ptr @@ -907,7 +1193,25 @@ namespace xpx_chain_sdk { namespace internal { return CreateTransaction( dto, signer, signature, info, secretHashAlgorithm, secretHash, secret); } - + + std::unique_ptr + CreateStoragePaymentTransactionImpl(const Key& driveKey, + const Amount& storageUnits, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer, + const std::optional& signature, + const std::optional& info) + { + StoragePaymentTransactionDTO dto; + InitStoragePaymentTransactionDTO( + dto, driveKey, storageUnits, maxFee, deadline, networkId, signer, signature); + + return CreateTransaction( + dto, signer, signature, info, driveKey, storageUnits); + } + std::unique_ptr CreateTransferTransactionImpl(const Address& recipient, MosaicContainer mosaics, @@ -949,46 +1253,99 @@ namespace xpx_chain_sdk { namespace internal { } std::unique_ptr - CreatePrepareBcDriveTransactionImpl(uint64_t driveSize, - uint16_t replicatorCount, - std::optional maxFee, - std::optional deadline, - std::optional networkId, - const std::optional& signer, - const std::optional& signature, - const std::optional& info) + CreatePrepareBcDriveTransactionImpl(uint64_t driveSize, + const Amount& verificationFeeAmount, + uint16_t replicatorCount, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer, + const std::optional& signature, + const std::optional& info) { PrepareBcDriveTransactionDTO dto; InitPrepareBcDriveTransactionDTO( - dto, driveSize, replicatorCount, maxFee, deadline, networkId, signer, signature); + dto, driveSize, verificationFeeAmount, replicatorCount, maxFee, deadline, networkId, signer, signature); return CreateTransaction( - dto, signer, signature, info, driveSize, replicatorCount); - } + dto, signer, signature, info, driveSize, verificationFeeAmount, replicatorCount); + } + + std::unique_ptr + CreateCreateLiquidityProviderTransactionImpl(const MosaicId providerMosaicId, + const Amount currencyDeposit, + const Amount initialMosaicsMinting, + const uint32_t slashingPeriod, + const uint16_t windowSize, + const Key& slashingAccount, + const uint32_t alpha, + const uint32_t beta, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer, + const std::optional& signature, + const std::optional& info) + { + CreateLiquidityProviderTransactionDTO dto; + InitCreateLiquidityProviderTransactionDTO( + dto, providerMosaicId, currencyDeposit, initialMosaicsMinting, slashingPeriod, + windowSize, slashingAccount, alpha, beta, maxFee, deadline, networkId, signer, signature); + + return CreateTransaction( + dto, signer, signature, info, providerMosaicId, currencyDeposit, initialMosaicsMinting, + slashingPeriod, windowSize, slashingAccount, alpha, beta); + } + + std::unique_ptr + CreateManualRateChangeTransactionImpl(const MosaicId providerMosaicId, + const bool currencyBalanceIncrease, + const Amount currencyBalanceChange, + const bool mosaicBalanceIncrease, + const Amount mosaicBalanceChange, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer, + const std::optional& signature, + const std::optional& info) + { + ManualRateChangeTransactionDTO dto; + InitManualRateChangeTransactionDTO( + dto, providerMosaicId, currencyBalanceIncrease, currencyBalanceChange, + mosaicBalanceIncrease, mosaicBalanceChange, maxFee, deadline, networkId, signer, signature); + + return CreateTransaction( + dto, signer, signature, info, providerMosaicId, currencyBalanceIncrease, + currencyBalanceChange, mosaicBalanceIncrease, mosaicBalanceChange); + } std::unique_ptr - CreateDataModificationTransactionImpl(const Key& driveKey, - const Hash256& downloadDataCdi, - uint64_t uploadSize, - std::optional maxFee, - std::optional deadline, - std::optional networkId, - const std::optional& signer, - const std::optional& signature, - const std::optional& info) + CreateDataModificationTransactionImpl(const Key& driveKey, + const Hash256& downloadDataCdi, + uint64_t uploadSize, + const Amount& feedbackFeeAmount, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer, + const std::optional& signature, + const std::optional& info) { DataModificationTransactionDTO dto; InitDataModificationTransactionDTO( - dto, driveKey, downloadDataCdi, uploadSize, maxFee, deadline, networkId, signer, signature); + dto, driveKey, downloadDataCdi, uploadSize, feedbackFeeAmount, maxFee, deadline, networkId, signer, signature); return CreateTransaction( - dto, signer, signature, info, driveKey, downloadDataCdi, uploadSize); + dto, signer, signature, info, driveKey, downloadDataCdi, uploadSize, feedbackFeeAmount); } std::unique_ptr CreateDownloadTransactionImpl(const Key& driveKey, - uint64_t downloadSize, - const Amount& transactionFee, + uint64_t downloadSize, + const Amount& feedbackFeeAmount, + uint16_t listOfPublicKeysSize, + const std::vector& listOfPublicKeys, std::optional maxFee, std::optional deadline, std::optional networkId, @@ -998,31 +1355,81 @@ namespace xpx_chain_sdk { namespace internal { { DownloadTransactionDTO dto; InitDownloadTransactionDTO( - dto, driveKey, downloadSize, transactionFee, maxFee, deadline, networkId, signer, signature); + dto, driveKey, downloadSize, feedbackFeeAmount, listOfPublicKeysSize, listOfPublicKeys, maxFee, deadline, networkId, signer, signature); return CreateTransaction( - dto, signer, signature, info, driveKey, downloadSize, transactionFee); - } + dto, signer, signature, info, driveKey, downloadSize, feedbackFeeAmount, listOfPublicKeysSize, listOfPublicKeys); + } + + std::unique_ptr + CreateDownloadPaymentTransactionImpl(const Hash256& downloadChannelId, + uint64_t downloadSize, + const Amount& feedbackFeeAmount, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer, + const std::optional& signature, + const std::optional& info) + { + DownloadPaymentTransactionDTO dto; + InitDownloadPaymentTransactionDTO( + dto, downloadChannelId, downloadSize, feedbackFeeAmount, maxFee, deadline, networkId, signer, signature); + + return CreateTransaction( + dto, signer, signature, info, downloadChannelId, downloadSize, feedbackFeeAmount); + } + + std::unique_ptr + CreateDriveClosureTransactionImpl(const Key& driveKey, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer, + const std::optional& signature, + const std::optional& info) + { + DriveClosureTransactionDTO dto; + InitDriveClosureTransactionDTO( + dto, driveKey, maxFee, deadline, networkId, signer, signature); + + return CreateTransaction( + dto, signer, signature, info, driveKey); + } std::unique_ptr - CreateDataModificationApprovalTransactionImpl(const Key& driveKey, - const Hash256& dataModificationId, - const Hash256& fileStructureCdi, - uint64_t fileStructureSize, - uint64_t usedDriveSize, - std::optional maxFee, - std::optional deadline, - std::optional networkId, - const std::optional& signer, - const std::optional& signature, - const std::optional& info) + CreateDataModificationApprovalTransactionImpl(const Key& driveKey, + const Hash256& dataModificationId, + const Hash256& fileStructureCdi, + uint8_t modificationStatus, + uint64_t fileStructureSizeBytes, + uint64_t metaFilesSizeBytes, + uint64_t usedDriveSizeBytes, + uint8_t judgingKeysCount, + uint8_t overlappingKeysCount, + uint8_t judgedKeysCount, + uint16_t opinionElementCount, + const std::vector& publicKeys, + const std::vector& signatures, + const std::vector& presentOpinions, + const std::vector& opinions, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer, + const std::optional& signature, + const std::optional& info) { DataModificationApprovalTransactionDTO dto; InitDataModificationApprovalTransactionDTO( - dto, driveKey, dataModificationId, fileStructureCdi, fileStructureSize, usedDriveSize, maxFee, deadline, networkId, signer, signature); + dto, driveKey, dataModificationId, fileStructureCdi, modificationStatus, fileStructureSizeBytes, metaFilesSizeBytes, usedDriveSizeBytes, judgingKeysCount, + overlappingKeysCount, judgedKeysCount, opinionElementCount, publicKeys, signatures, presentOpinions, opinions, maxFee, + deadline, networkId, signer, signature); return CreateTransaction( - dto, signer, signature, info, driveKey, dataModificationId, fileStructureCdi, fileStructureSize, usedDriveSize); + dto, signer, signature, info, driveKey, dataModificationId, fileStructureCdi, modificationStatus, fileStructureSizeBytes, + metaFilesSizeBytes, usedDriveSizeBytes, judgingKeysCount, overlappingKeysCount, judgedKeysCount, opinionElementCount, + publicKeys, signatures, presentOpinions, opinions); } std::unique_ptr @@ -1043,17 +1450,35 @@ namespace xpx_chain_sdk { namespace internal { dto, signer, signature, info, driveKey, dataModificationId); } + std::unique_ptr + CreateFinishDownloadTransactionImpl(const Hash256& downloadChannelId, + const Amount& feedbackFeeAmount, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer, + const std::optional& signature, + const std::optional& info) + { + FinishDownloadTransactionDTO dto; + InitFinishDownloadTransactionDTO( + dto, downloadChannelId, feedbackFeeAmount, maxFee, deadline, networkId, signer, signature); + + return CreateTransaction( + dto, signer, signature, info, downloadChannelId, feedbackFeeAmount); + } + std::unique_ptr - CreateReplicatorOnboardingTransactionImpl(const Amount& capacity, - const Key& nodeBootKey, - const Hash256& message, - const Signature& messageSignature, - std::optional maxFee, - std::optional deadline, - std::optional networkId, - const std::optional& signer, - const std::optional& signature, - const std::optional& info) + CreateReplicatorOnboardingTransactionImpl(const Amount& capacity, + const Key& nodeBootKey, + const Hash256& message, + const Signature& messageSignature, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer, + const std::optional& signature, + const std::optional& info) { ReplicatorOnboardingTransactionDTO dto; InitReplicatorOnboardingTransactionDTO( @@ -1079,6 +1504,209 @@ namespace xpx_chain_sdk { namespace internal { return CreateTransaction( dto, signer, signature, info, replicatorKeys); } + + std::unique_ptr + CreateReplicatorOffboardingTransactionImpl(const Key& driveKey, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer, + const std::optional& signature, + const std::optional& info) + { + ReplicatorOffboardingTransactionDTO dto; + InitReplicatorOffboardingTransactionDTO( + dto, driveKey, maxFee, deadline, networkId, signer, signature); + + return CreateTransaction( + dto, signer, signature, info, driveKey); + } + + std::unique_ptr + CreateDeployContractTransactionImpl(const Key& driveKey, + const std::string& fileName, + const std::string& functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + MosaicContainer servicePayments, + const std::string& automaticExecutionsFileName, + const std::string& automaticExecutionsFunctionName, + const Amount& automaticExecutionsCallPayment, + const Amount& automaticDownloadCallPayment, + uint32_t automaticExecutionsNumber, + const Key& assignee, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer, + const std::optional& signature, + const std::optional& info) + { + DeployContractTransactionDTO dto; + InitDeployContractTransactionDTO( + dto, + driveKey, + fileName, + functionName, + actualArguments, + executionCallPayment, + downloadCallPayment, + servicePayments, + automaticExecutionsFileName, + automaticExecutionsFunctionName, + automaticExecutionsCallPayment, + automaticDownloadCallPayment, + automaticExecutionsNumber, + assignee, + maxFee, + deadline, + networkId, + signer, + signature); + + return CreateTransaction( + dto, + signer, + signature, + info, + driveKey, + fileName, + functionName, + actualArguments, + executionCallPayment, + downloadCallPayment, + servicePayments, + automaticExecutionsFileName, + automaticExecutionsFunctionName, + automaticExecutionsCallPayment, + automaticDownloadCallPayment, + automaticExecutionsNumber, + assignee); + } + + std::unique_ptr + CreateManualCallTransactionImpl(const Key& contractKey, + const std::string& fileName, + const std::string& functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + MosaicContainer servicePayments, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer, + const std::optional& signature, + const std::optional& info) + { + ManualCallTransactionDTO dto; + InitManualCallTransactionDTO( + dto, + contractKey, + fileName, + functionName, + actualArguments, + executionCallPayment, + downloadCallPayment, + servicePayments, + maxFee, + deadline, + networkId, + signer, + signature); + + return CreateTransaction( + dto, + signer, + signature, + info, + contractKey, + fileName, + functionName, + actualArguments, + executionCallPayment, + downloadCallPayment, + servicePayments); + } + + std::unique_ptr + CreateAutomaticExecutionsPaymentTransactionImpl(const Key& contractKey, + uint32_t automaticExecutionsNumber, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer, + const std::optional& signature, + const std::optional& info) + { + AutomaticExecutionsPaymentTransactionDTO dto; + InitAutomaticExecutionsPaymentTransactionDTO( + dto, contractKey, automaticExecutionsNumber, maxFee, deadline, networkId, signer, signature); + + return CreateTransaction( + dto, signer, signature, info, contractKey, automaticExecutionsNumber); + } + + std::unique_ptr + CreateStreamStartTransactionImpl(const Key &driveKey, + const uint64_t expectedUploadSizeMegabytes, + const uint16_t folderNameSize, + const Amount &feedbackFeeAmount, + const std::vector& folderName, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional &signer, + const std::optional &signature, + const std::optional &info) + { + StreamStartTransactionDTO dto; + InitStreamStartTransactionDTO( + dto, driveKey, expectedUploadSizeMegabytes, folderNameSize, feedbackFeeAmount, folderName, maxFee, deadline, networkId, signer, signature); + + return CreateTransaction( + dto, signer, signature, info, driveKey, expectedUploadSizeMegabytes, folderNameSize, feedbackFeeAmount, folderName); + } + + std::unique_ptr + CreateStreamFinishTransactionImpl(const Key &driveKey, + const Hash256 &streamId, + const uint64_t actualUploadSizeMegabytes, + const Hash256 &streamStructureCdi, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional &signer, + const std::optional &signature, + const std::optional &info) + { + StreamFinishTransactionDTO dto; + InitStreamFinishTransactionDTO( + dto, driveKey, streamId, actualUploadSizeMegabytes, streamStructureCdi, maxFee, deadline, networkId, signer, signature); + + return CreateTransaction( + dto, signer, signature, info, driveKey, streamId, actualUploadSizeMegabytes, streamStructureCdi); + } + + std::unique_ptr + CreateStreamPaymentTransactionImpl(const Key &driveKey, + const Hash256 &streamId, + const uint64_t additionalUploadSizeMegabytes, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional &signer, + const std::optional &signature, + const std::optional &info) + { + StreamPaymentTransactionDTO dto; + InitStreamPaymentTransactionDTO( + dto, driveKey, streamId, additionalUploadSizeMegabytes, maxFee, deadline, networkId, signer, signature); + + return CreateTransaction( + dto, signer, signature, info, driveKey, streamId, additionalUploadSizeMegabytes); + } }} @@ -1269,29 +1897,28 @@ namespace xpx_chain_sdk { std::unique_ptr CreateMosaicDefinitionTransaction(uint32_t mosaicNonce, MosaicId mosaicId, - MosaicFlags flags, MosaicProperties mosaicProperties, std::optional maxFee, std::optional deadline, std::optional networkId) { return CreateMosaicDefinitionTransactionImpl( - mosaicNonce, mosaicId, flags, std::move(mosaicProperties), maxFee, deadline, networkId); + mosaicNonce, mosaicId, std::move(mosaicProperties), maxFee, deadline, networkId); } std::unique_ptr CreateEmbeddedMosaicDefinitionTransaction(uint32_t mosaicNonce, MosaicId mosaicId, - MosaicFlags flags, + Amount mosaicSupply, MosaicProperties mosaicProperties, const Key& signer, std::optional networkId) { EmbeddedMosaicDefinitionTransactionDTO dto; - InitMosaicDefinitionTransactionDTO(dto, mosaicNonce, mosaicId, flags, mosaicProperties, signer, networkId); + InitMosaicDefinitionTransactionDTO(dto, mosaicNonce, mosaicId, mosaicProperties, signer, networkId); return CreateTransaction( - dto, mosaicNonce, mosaicId, flags, std::move(mosaicProperties)); + dto, mosaicNonce, mosaicId, std::move(mosaicProperties)); } std::unique_ptr @@ -1449,6 +2076,27 @@ namespace xpx_chain_sdk { return CreateTransaction(dto, secretHashAlgorithm, secretHash, secret); } + std::unique_ptr + CreateStoragePaymentTransaction(const Key& driveKey, + const Amount& storageUnits, + std::optional maxFee, + std::optional deadline, + std::optional networkId) + { + return CreateStoragePaymentTransactionImpl(driveKey, storageUnits, maxFee, deadline, networkId); + } + + std::unique_ptr + CreateEmbeddedStoragePaymentTransaction(const Key& driveKey, + const Amount& storageUnits, + const Key& signer, + std::optional networkId) + { + EmbeddedStoragePaymentTransactionDTO dto; + InitStoragePaymentTransactionDTO(dto, driveKey, storageUnits, signer, networkId); + return CreateTransaction(dto, driveKey, storageUnits); + } + std::unique_ptr CreateTransferTransaction(const Address& recipient, MosaicContainer mosaics, @@ -1493,139 +2141,301 @@ namespace xpx_chain_sdk { } std::unique_ptr - CreatePrepareBcDriveTransaction(uint64_t driveSize, - uint16_t replicatorCount, - std::optional maxFee, - std::optional deadline, - std::optional networkId) + CreatePrepareBcDriveTransaction(uint64_t driveSize, + const Amount& verificationFeeAmount, + uint16_t replicatorCount, + std::optional maxFee, + std::optional deadline, + std::optional networkId) { - return CreatePrepareBcDriveTransactionImpl(driveSize, replicatorCount, maxFee, deadline, networkId); + return CreatePrepareBcDriveTransactionImpl(driveSize, verificationFeeAmount, replicatorCount, maxFee, deadline, networkId); } std::unique_ptr - CreateEmbeddedPrepareBcDriveTransaction(uint64_t driveSize, - uint16_t replicatorCount, - const Key& signer, - std::optional networkId) + CreateEmbeddedPrepareBcDriveTransaction(uint64_t driveSize, + const Amount& verificationFeeAmount, + uint16_t replicatorCount, + const Key& signer, + std::optional networkId) { EmbeddedPrepareBcDriveTransactionDTO dto; - InitPrepareBcDriveTransactionDTO(dto, driveSize, replicatorCount, signer, networkId); - return CreateTransaction(dto, driveSize, replicatorCount); - } + InitPrepareBcDriveTransactionDTO(dto, driveSize, verificationFeeAmount, replicatorCount, signer, networkId); + return CreateTransaction(dto, driveSize, verificationFeeAmount, replicatorCount); + } + + std::unique_ptr + CreateCreateLiquidityProviderTransaction(const MosaicId providerMosaicId, + const Amount currencyDeposit, + const Amount initialMosaicsMinting, + const uint32_t slashingPeriod, + const uint16_t windowSize, + const Key& slashingAccount, + const uint32_t alpha, + const uint32_t beta, + std::optional maxFee, + std::optional deadline, + std::optional networkId) + { + return CreateCreateLiquidityProviderTransactionImpl(providerMosaicId, currencyDeposit, initialMosaicsMinting, + slashingPeriod, windowSize, slashingAccount, alpha, beta, maxFee, deadline, networkId); + } + + std::unique_ptr + CreateEmbeddedCreateLiquidityProviderTransaction(const MosaicId providerMosaicId, + const Amount currencyDeposit, + const Amount initialMosaicsMinting, + const uint32_t slashingPeriod, + const uint16_t windowSize, + const Key& slashingAccount, + const uint32_t alpha, + const uint32_t beta, + const Key& signer, + std::optional networkId) + { + EmbeddedCreateLiquidityProviderTransactionDTO dto; + InitCreateLiquidityProviderTransactionDTO(dto, providerMosaicId, currencyDeposit, initialMosaicsMinting, + slashingPeriod, windowSize, slashingAccount, alpha, beta, signer, networkId); + return CreateTransaction(dto, providerMosaicId, currencyDeposit, + initialMosaicsMinting, slashingPeriod, windowSize, slashingAccount, alpha, beta); + } + + std::unique_ptr + CreateManualRateChangeTransaction(const MosaicId providerMosaicId, + const bool currencyBalanceIncrease, + const Amount currencyBalanceChange, + const bool mosaicBalanceIncrease, + const Amount mosaicBalanceChange, + std::optional maxFee, + std::optional deadline, + std::optional networkId) + { + return CreateManualRateChangeTransactionImpl(providerMosaicId, currencyBalanceIncrease, + currencyBalanceChange, mosaicBalanceIncrease, mosaicBalanceChange, maxFee, deadline, networkId); + } + + std::unique_ptr + CreateEmbeddedManualRateChangeTransaction(const MosaicId providerMosaicId, + const bool currencyBalanceIncrease, + const Amount currencyBalanceChange, + const bool mosaicBalanceIncrease, + const Amount mosaicBalanceChange, + const Key& signer, + std::optional networkId) + { + EmbeddedManualRateChangeTransactionDTO dto; + InitManualRateChangeTransactionDTO(dto, providerMosaicId, currencyBalanceIncrease, currencyBalanceChange, + mosaicBalanceIncrease, mosaicBalanceChange, signer, networkId); + + return CreateTransaction(dto, providerMosaicId, currencyBalanceIncrease, + currencyBalanceChange, mosaicBalanceIncrease, mosaicBalanceChange); + } std::unique_ptr - CreateDataModificationTransaction(const Key& driveKey, - const Hash256& downloadDataCdi, - uint64_t uploadSize, - std::optional maxFee, - std::optional deadline, - std::optional networkId) + CreateDataModificationTransaction(const Key& driveKey, + const Hash256& downloadDataCdi, + uint64_t uploadSize, + const Amount& feedbackFeeAmount, + std::optional maxFee, + std::optional deadline, + std::optional networkId) { - return CreateDataModificationTransactionImpl(driveKey, downloadDataCdi, uploadSize, maxFee, deadline, networkId); + return CreateDataModificationTransactionImpl(driveKey, downloadDataCdi, uploadSize, feedbackFeeAmount, maxFee, deadline, networkId); } std::unique_ptr - CreateEmbeddedDataModificationTransaction(const Key& driveKey, - const Hash256& downloadDataCdi, - uint64_t uploadSize, - const Key& signer, - std::optional networkId) + CreateEmbeddedDataModificationTransaction(const Key& driveKey, + const Hash256& downloadDataCdi, + uint64_t uploadSize, + const Amount& feedbackFeeAmount, + const Key& signer, + std::optional networkId) { EmbeddedDataModificationTransactionDTO dto; - InitDataModificationTransactionDTO(dto, driveKey, downloadDataCdi, uploadSize, signer, networkId); - return CreateTransaction(dto, driveKey, downloadDataCdi, uploadSize); + InitDataModificationTransactionDTO(dto, driveKey, downloadDataCdi, uploadSize, feedbackFeeAmount, signer, networkId); + return CreateTransaction(dto, driveKey, downloadDataCdi, uploadSize, feedbackFeeAmount); } std::unique_ptr CreateDownloadTransaction(const Key& driveKey, - uint64_t downloadSize, - const Amount& transactionFee, + uint64_t downloadSize, + const Amount& feedbackFeeAmount, + uint16_t listOfPublicKeysSize, + const std::vector& listOfPublicKeys, std::optional maxFee, std::optional deadline, std::optional networkId) { - return CreateDownloadTransactionImpl(driveKey, downloadSize, transactionFee, maxFee, deadline, networkId); + return CreateDownloadTransactionImpl(driveKey, downloadSize, feedbackFeeAmount, listOfPublicKeysSize, listOfPublicKeys, maxFee, deadline, networkId); } std::unique_ptr CreateEmbeddedDownloadTransaction(const Key& driveKey, uint64_t downloadSize, - const Amount& transactionFee, + const Amount& feedbackFeeAmount, + uint16_t listOfPublicKeysSize, + const std::vector& listOfPublicKeys, const Key& signer, std::optional networkId) { EmbeddedDownloadTransactionDTO dto; - InitDownloadTransactionDTO(dto, driveKey, downloadSize, transactionFee, signer, networkId); - return CreateTransaction(dto, driveKey, downloadSize, transactionFee); - } + InitDownloadTransactionDTO(dto, driveKey, downloadSize, feedbackFeeAmount, listOfPublicKeysSize, listOfPublicKeys, signer, networkId); + return CreateTransaction(dto, driveKey, downloadSize, feedbackFeeAmount, listOfPublicKeysSize, listOfPublicKeys); + } + + std::unique_ptr + CreateDownloadPaymentTransaction(const Hash256& downloadChannelId, + uint64_t downloadSize, + const Amount& feedbackFeeAmount, + std::optional maxFee, + std::optional deadline, + std::optional networkId) + { + return CreateDownloadPaymentTransactionImpl(downloadChannelId, downloadSize, feedbackFeeAmount, maxFee, deadline, networkId); + } + + std::unique_ptr + CreateEmbeddedDownloadPaymentTransaction(const Hash256& downloadChannelId, + uint64_t downloadSize, + const Amount& feedbackFeeAmount, + const Key& signer, + std::optional networkId) + { + EmbeddedDownloadPaymentTransactionDTO dto; + InitDownloadPaymentTransactionDTO(dto, downloadChannelId, downloadSize, feedbackFeeAmount, signer, networkId); + return CreateTransaction(dto, downloadChannelId, downloadSize, feedbackFeeAmount); + } + + std::unique_ptr + CreateDriveClosureTransaction(const Key& driveKey, + std::optional maxFee, + std::optional deadline, + std::optional networkId) + { + return CreateDriveClosureTransactionImpl(driveKey, maxFee, deadline, networkId); + } + + std::unique_ptr + CreateEmbeddedDriveClosureTransaction(const Key& driveKey, + const Key& signer, + std::optional networkId) + { + EmbeddedDriveClosureTransactionDTO dto; + InitDriveClosureTransactionDTO(dto, driveKey, signer, networkId); + return CreateTransaction(dto, driveKey); + } std::unique_ptr - CreateDataModificationApprovalTransaction(const Key& driveKey, - const Hash256& dataModificationId, - const Hash256& fileStructureCdi, - uint64_t fileStructureSize, - uint64_t usedDriveSize, - std::optional maxFee, - std::optional deadline, - std::optional networkId) - { - return CreateDataModificationApprovalTransactionImpl(driveKey, dataModificationId, fileStructureCdi, fileStructureSize, usedDriveSize, maxFee, deadline, networkId); + CreateDataModificationApprovalTransaction(const Key& driveKey, + const Hash256& dataModificationId, + const Hash256& fileStructureCdi, + uint8_t modificationStatus, + uint64_t fileStructureSizeBytes, + uint64_t metaFilesSizeBytes, + uint64_t usedDriveSizeBytes, + uint8_t judgingKeysCount, + uint8_t overlappingKeysCount, + uint8_t judgedKeysCount, + uint16_t opinionElementCount, + const std::vector& publicKeys, + const std::vector& signatures, + const std::vector& presentOpinions, + const std::vector& opinions, + std::optional maxFee, + std::optional deadline, + std::optional networkId) + { + return CreateDataModificationApprovalTransactionImpl(driveKey, dataModificationId, fileStructureCdi, modificationStatus, fileStructureSizeBytes, metaFilesSizeBytes, usedDriveSizeBytes, judgingKeysCount, + overlappingKeysCount, judgedKeysCount, opinionElementCount, publicKeys, signatures, presentOpinions, opinions, + maxFee, deadline, networkId); } std::unique_ptr - CreateEmbeddedDataModificationApprovalTransaction(const Key& driveKey, - const Hash256& dataModificationId, - const Hash256& fileStructureCdi, - uint64_t fileStructureSize, - uint64_t usedDriveSize, - const Key& signer, - std::optional networkId) + CreateEmbeddedDataModificationApprovalTransaction(const Key& driveKey, + const Hash256& dataModificationId, + const Hash256& fileStructureCdi, + uint8_t modificationStatus, + uint64_t fileStructureSizeBytes, + uint64_t metaFilesSizeBytes, + uint64_t usedDriveSizeBytes, + uint8_t judgingKeysCount, + uint8_t overlappingKeysCount, + uint8_t judgedKeysCount, + uint16_t opinionElementCount, + const std::vector& publicKeys, + const std::vector& signatures, + const std::vector& presentOpinions, + const std::vector& opinions, + const Key& signer, + std::optional networkId) { EmbeddedDataModificationApprovalTransactionDTO dto; - InitDataModificationApprovalTransactionDTO(dto, driveKey, dataModificationId, fileStructureCdi, fileStructureSize, usedDriveSize, signer, networkId); - return CreateTransaction(dto, driveKey, dataModificationId, fileStructureCdi, fileStructureSize, usedDriveSize); + InitDataModificationApprovalTransactionDTO(dto, driveKey, dataModificationId, fileStructureCdi, modificationStatus, fileStructureSizeBytes, metaFilesSizeBytes, usedDriveSizeBytes, judgingKeysCount, + overlappingKeysCount, judgedKeysCount, opinionElementCount, publicKeys, signatures, presentOpinions, opinions, signer, networkId); + return CreateTransaction(dto, driveKey, dataModificationId, fileStructureCdi, modificationStatus, fileStructureSizeBytes, metaFilesSizeBytes, usedDriveSizeBytes, judgingKeysCount, + overlappingKeysCount, judgedKeysCount, opinionElementCount, publicKeys, signatures, presentOpinions, opinions); } std::unique_ptr - CreateDataModificationCancelTransaction(const Key& driveKey, - const Hash256& dataModificationId, - std::optional maxFee, - std::optional deadline, - std::optional networkId) + CreateDataModificationCancelTransaction(const Key& driveKey, + const Hash256& dataModificationId, + std::optional maxFee, + std::optional deadline, + std::optional networkId) { return CreateDataModificationCancelTransactionImpl(driveKey, dataModificationId, maxFee, deadline, networkId); } std::unique_ptr - CreateEmbeddedDataModificationCancelTransaction(const Key& driveKey, - const Hash256& dataModificationId, - const Key& signer, - std::optional networkId) + CreateEmbeddedDataModificationCancelTransaction(const Key& driveKey, + const Hash256& dataModificationId, + const Key& signer, + std::optional networkId) { EmbeddedDataModificationCancelTransactionDTO dto; InitDataModificationCancelTransactionDTO(dto, driveKey, dataModificationId, signer, networkId); return CreateTransaction(dto, driveKey, dataModificationId); } + std::unique_ptr + CreateFinishDownloadTransaction(const Hash256& downloadChannelId, + const Amount& feedbackFeeAmount, + std::optional maxFee, + std::optional deadline, + std::optional networkId) + { + return CreateFinishDownloadTransactionImpl(downloadChannelId, feedbackFeeAmount, maxFee, deadline, networkId); + } + + std::unique_ptr + CreateEmbeddedFinishDownloadTransaction(const Hash256& downloadChannelId, + const Amount& feedbackFeeAmount, + const Key& signer, + std::optional networkId) + { + EmbeddedFinishDownloadTransactionDTO dto; + InitFinishDownloadTransactionDTO(dto, downloadChannelId, feedbackFeeAmount, signer, networkId); + return CreateTransaction(dto, downloadChannelId, feedbackFeeAmount); + } + std::unique_ptr - CreateReplicatorOnboardingTransaction(const Amount& capacity, - const Key& nodeBootKey, - const Hash256& message, - const Signature& messageSignature, - std::optional maxFee, - std::optional deadline, - std::optional networkId) + CreateReplicatorOnboardingTransaction(const Amount& capacity, + const Key& nodeBootKey, + const Hash256& message, + const Signature& messageSignature, + std::optional maxFee, + std::optional deadline, + std::optional networkId) { return CreateReplicatorOnboardingTransactionImpl(capacity, nodeBootKey, message, messageSignature, maxFee, deadline, networkId); } std::unique_ptr - CreateEmbeddedReplicatorOnboardingTransaction(const Amount& capacity, - const Key& nodeBootKey, - const Hash256& message, - const Signature& messageSignature, - const Key& signer, - std::optional networkId) + CreateEmbeddedReplicatorOnboardingTransaction(const Amount& capacity, + const Key& nodeBootKey, + const Hash256& message, + const Signature& messageSignature, + const Key& signer, + std::optional networkId) { EmbeddedReplicatorOnboardingTransactionDTO dto; InitReplicatorOnboardingTransactionDTO(dto, capacity, nodeBootKey, message, messageSignature, signer, networkId); @@ -1650,4 +2460,230 @@ namespace xpx_chain_sdk { InitReplicatorsCleanupTransactionDTO(dto, replicatorKeys, signer, networkId); return CreateTransaction(dto, replicatorKeys); } + + std::unique_ptr + CreateReplicatorOffboardingTransaction(const Key& driveKey, + std::optional maxFee, + std::optional deadline, + std::optional networkId) + { + return CreateReplicatorOffboardingTransactionImpl(driveKey, maxFee, deadline, networkId); + } + + std::unique_ptr + CreateEmbeddedReplicatorOffboardingTransaction(const Key& driveKey, + const Key& signer, + std::optional networkId) + { + EmbeddedReplicatorOffboardingTransactionDTO dto; + InitReplicatorOffboardingTransactionDTO(dto, driveKey, signer, networkId); + return CreateTransaction(dto, driveKey); + } + + std::unique_ptr + CreateDeployContractTransaction(const Key& driveKey, + const std::string& fileName, + const std::string& functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + MosaicContainer servicePayments, + const std::string& automaticExecutionsFileName, + const std::string& automaticExecutionsFunctionName, + const Amount& automaticExecutionsCallPayment, + const Amount& automaticDownloadCallPayment, + uint32_t automaticExecutionsNumber, + const Key& assignee, + std::optional maxFee, + std::optional deadline, + std::optional networkId) + { + return CreateDeployContractTransactionImpl( + driveKey, fileName, functionName, actualArguments, executionCallPayment, downloadCallPayment, servicePayments, + automaticExecutionsFileName, automaticExecutionsFunctionName, automaticExecutionsCallPayment, automaticDownloadCallPayment, + automaticExecutionsNumber, assignee, maxFee, deadline, networkId); + } + + std::unique_ptr + CreateEmbeddedDeployContractTransaction(const Key& driveKey, + const std::string& fileName, + const std::string& functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + MosaicContainer servicePayments, + const std::string& automaticExecutionsFileName, + const std::string& automaticExecutionsFunctionName, + const Amount& automaticExecutionsCallPayment, + const Amount& automaticDownloadCallPayment, + uint32_t automaticExecutionsNumber, + const Key& assignee, + const Key& signer, + std::optional networkId) + { + EmbeddedDeployContractTransactionDTO dto; + InitDeployContractTransactionDTO( + dto, + driveKey, + fileName, + functionName, + actualArguments, + executionCallPayment, + downloadCallPayment, + servicePayments, + automaticExecutionsFileName, + automaticExecutionsFunctionName, + automaticExecutionsCallPayment, + automaticDownloadCallPayment, + automaticExecutionsNumber, + assignee, + signer, + networkId); + return CreateTransaction( + dto, + driveKey, + fileName, + functionName, + actualArguments, + executionCallPayment, + downloadCallPayment, + servicePayments, + automaticExecutionsFileName, + automaticExecutionsFunctionName, + automaticExecutionsCallPayment, + automaticDownloadCallPayment, + automaticExecutionsNumber, + assignee); + } + + std::unique_ptr + CreateManualCallTransaction(const Key& contractKey, + const std::string& fileName, + const std::string& functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + MosaicContainer servicePayments, + std::optional maxFee, + std::optional deadline, + std::optional networkId) + { + return CreateManualCallTransactionImpl( + contractKey, fileName, functionName, actualArguments, executionCallPayment, downloadCallPayment, servicePayments, maxFee, deadline, networkId); + } + + std::unique_ptr + CreateEmbeddedManualCallTransaction(const Key& contractKey, + const std::string& fileName, + const std::string& functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + MosaicContainer servicePayments, + const Key& signer, + std::optional networkId) + { + EmbeddedManualCallTransactionDTO dto; + InitManualCallTransactionDTO( + dto, contractKey, fileName, functionName, actualArguments, executionCallPayment, downloadCallPayment, servicePayments, signer, networkId); + return CreateTransaction( + dto, contractKey, fileName, functionName, actualArguments, executionCallPayment, downloadCallPayment, servicePayments); + } + + std::unique_ptr + CreateAutomaticExecutionsPaymentTransaction(const Key& contractKey, + uint32_t automaticExecutionsNumber, + std::optional maxFee, + std::optional deadline, + std::optional networkId) + { + return CreateAutomaticExecutionsPaymentTransactionImpl(contractKey, automaticExecutionsNumber, maxFee, deadline, networkId); + } + + std::unique_ptr + CreateEmbeddedAutomaticExecutionsPaymentTransaction(const Key& contractKey, + uint32_t automaticExecutionsNumber, + const Key& signer, + std::optional networkId) + { + EmbeddedAutomaticExecutionsPaymentTransactionDTO dto; + InitAutomaticExecutionsPaymentTransactionDTO(dto, contractKey, automaticExecutionsNumber, signer, networkId); + return CreateTransaction(dto, contractKey, automaticExecutionsNumber); + } + + + std::unique_ptr + CreateStreamStartTransaction(const Key &driveKey, + const uint64_t expectedUploadSizeMegabytes, + const uint16_t folderNameSize, + const Amount &feedbackFeeAmount, + const std::vector& folderName, + std::optional maxFee, + std::optional deadline, + std::optional networkId) + { + return CreateStreamStartTransactionImpl(driveKey, expectedUploadSizeMegabytes, folderNameSize, feedbackFeeAmount, folderName, maxFee, deadline, networkId); + } + + std::unique_ptr + CreateEmbeddedStreamStartTransaction(const Key &driveKey, + const uint64_t expectedUploadSizeMegabytes, + const uint16_t folderNameSize, + const Amount &feedbackFeeAmount, + const std::vector& folderName, + const Key &signer, + std::optional networkId) + { + EmbeddedStreamStartTransactionDTO dto; + InitStreamStartTransactionDTO(dto, driveKey, expectedUploadSizeMegabytes, folderNameSize, feedbackFeeAmount, folderName, signer, networkId); + return CreateTransaction(dto, driveKey, expectedUploadSizeMegabytes, folderNameSize, feedbackFeeAmount, folderName); + } + + std::unique_ptr + CreateStreamFinishTransaction(const Key& driveKey, + const Hash256& streamId, + const uint64_t actualUploadSizeMegabytes, + const Hash256& streamStructureCdi, + std::optional maxFee, + std::optional deadline, + std::optional networkId) + { + return CreateStreamFinishTransactionImpl(driveKey, streamId, actualUploadSizeMegabytes, streamStructureCdi, maxFee, deadline, networkId); + } + + std::unique_ptr + CreateEmbeddedStreamFinishTransaction(const Key& driveKey, + const Hash256& streamId, + const uint64_t actualUploadSizeMegabytes, + const Hash256& streamStructureCdi, + const Key &signer, + std::optional networkId) + { + EmbeddedStreamFinishTransactionDTO dto; + InitStreamFinishTransactionDTO(dto, driveKey, streamId, actualUploadSizeMegabytes, streamStructureCdi, signer, networkId); + return CreateTransaction(dto, driveKey, streamId, actualUploadSizeMegabytes, streamStructureCdi); + } + + std::unique_ptr + CreateStreamPaymentTransaction(const Key &driveKey, + const Hash256 &streamId, + const uint64_t additionalUploadSizeMegabytes, + std::optional maxFee, + std::optional deadline, + std::optional networkId) + { + return CreateStreamPaymentTransactionImpl(driveKey, streamId, additionalUploadSizeMegabytes, maxFee, deadline, networkId); + } + + std::unique_ptr + CreateEmbeddedStreamPaymentTransaction(const Key &driveKey, + const Hash256 &streamId, + const uint64_t additionalUploadSizeMegabytes, + const Key &signer, + std::optional networkId) + { + EmbeddedStreamPaymentTransactionDTO dto; + InitStreamPaymentTransactionDTO(dto, driveKey, streamId, additionalUploadSizeMegabytes, signer, networkId); + return CreateTransaction(dto, driveKey, streamId, additionalUploadSizeMegabytes); + } } diff --git a/src/sdk/model/transaction/create_transaction.h b/src/sdk/model/transaction/create_transaction.h index 37920c9..5f0a471 100644 --- a/src/sdk/model/transaction/create_transaction.h +++ b/src/sdk/model/transaction/create_transaction.h @@ -17,13 +17,26 @@ #include #include #include +#include #include #include +#include +#include #include #include +#include +#include #include #include +#include #include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -81,33 +94,70 @@ namespace xpx_chain_sdk { namespace internal { using SecretProofTransactionImpl = TTransactionImpl; using EmbeddedSecretProofTransactionImpl = TTransactionImpl; - + + using StoragePaymentTransactionImpl = TTransactionImpl; + using EmbeddedStoragePaymentTransactionImpl = TTransactionImpl; + using TransferTransactionImpl = TTransactionImpl; using EmbeddedTransferTransactionImpl = TTransactionImpl; using PrepareBcDriveTransactionImpl = TTransactionImpl; using EmbeddedPrepareBcDriveTransactionImpl = TTransactionImpl; + using CreateLiquidityProviderTransactionImpl = TTransactionImpl; + using EmbeddedCreateLiquidityProviderTransactionImpl = TTransactionImpl; + + using ManualRateChangeTransactionImpl = TTransactionImpl; + using EmbeddedManualRateChangeTransactionImpl = TTransactionImpl; + using DataModificationTransactionImpl = TTransactionImpl; using EmbeddedDataModificationTransactionImpl = TTransactionImpl; using DownloadTransactionImpl = TTransactionImpl; using EmbeddedDownloadTransactionImpl = TTransactionImpl; + using DownloadPaymentTransactionImpl = TTransactionImpl; + using EmbeddedDownloadPaymentTransactionImpl = TTransactionImpl; + + using DriveClosureTransactionImpl = TTransactionImpl; + using EmbeddedDriveClosureTransactionImpl = TTransactionImpl; + using DataModificationApprovalTransactionImpl = TTransactionImpl; using EmbeddedDataModificationApprovalTransactionImpl = TTransactionImpl; using DataModificationCancelTransactionImpl = TTransactionImpl; using EmbeddedDataModificationCancelTransactionImpl = TTransactionImpl; + using FinishDownloadTransactionImpl = TTransactionImpl; + using EmbeddedFinishDownloadTransactionImpl = TTransactionImpl; + using ReplicatorOnboardingTransactionImpl = TTransactionImpl; using EmbeddedReplicatorOnboardingTransactionImpl = TTransactionImpl; using ReplicatorsCleanupTransactionImpl = TTransactionImpl; using EmbeddedReplicatorsCleanupTransactionImpl = TTransactionImpl; - - - + + using ReplicatorOffboardingTransactionImpl = TTransactionImpl; + using EmbeddedReplicatorOffboardingTransactionImpl = TTransactionImpl; + + using DeployContractTransactionImpl = TTransactionImpl; + using EmbeddedDeployContractTransactionImpl = TTransactionImpl; + + using ManualCallTransactionImpl = TTransactionImpl; + using EmbeddedManualCallTransactionImpl = TTransactionImpl; + + using AutomaticExecutionsPaymentTransactionImpl = TTransactionImpl; + using EmbeddedAutomaticExecutionsPaymentTransactionImpl = TTransactionImpl; + + using StreamStartTransactionImpl = TTransactionImpl; + using EmbeddedStreamStartTransactionImpl = TTransactionImpl; + + using StreamFinishTransactionImpl = TTransactionImpl; + using EmbeddedStreamFinishTransactionImpl = TTransactionImpl; + + using StreamPaymentTransactionImpl = TTransactionImpl; + using EmbeddedStreamPaymentTransactionImpl = TTransactionImpl; + std::unique_ptr CreateAccountLinkTransactionImpl(AccountLinkTransactionAction action, const Key& remoteAccountKey, @@ -196,7 +246,6 @@ namespace xpx_chain_sdk { namespace internal { std::unique_ptr CreateMosaicDefinitionTransactionImpl(uint32_t mosaicNonce, MosaicId mosaicId, - MosaicFlags flags, MosaicProperties mosaicProperties, std::optional maxFee, std::optional deadline, @@ -259,7 +308,17 @@ namespace xpx_chain_sdk { namespace internal { const std::optional& signer = std::nullopt, const std::optional& signature = std::nullopt, const std::optional& info = std::nullopt); - + + std::unique_ptr + CreateStoragePaymentTransactionImpl(const Key& driveKey, + const Amount& storageUnits, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer = std::nullopt, + const std::optional& signature = std::nullopt, + const std::optional& info = std::nullopt); + std::unique_ptr CreateTransferTransactionImpl(const Address& recipient, MosaicContainer mosaics, @@ -284,29 +343,62 @@ namespace xpx_chain_sdk { namespace internal { std::unique_ptr CreatePrepareBcDriveTransactionImpl(uint64_t driveSize, - uint16_t replicatorCount, - std::optional maxFee, - std::optional deadline, - std::optional networkId, - const std::optional& signer = std::nullopt, - const std::optional& signature = std::nullopt, - const std::optional& info = std::nullopt); + const Amount& verificationFeeAmount, + uint16_t replicatorCount, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer = std::nullopt, + const std::optional& signature = std::nullopt, + const std::optional& info = std::nullopt); + + std::unique_ptr + CreateCreateLiquidityProviderTransactionImpl(const MosaicId providerMosaicId, + const Amount currencyDeposit, + const Amount initialMosaicsMinting, + const uint32_t slashingPeriod, + const uint16_t windowSize, + const Key& slashingAccount, + const uint32_t alpha, + const uint32_t beta, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer = std::nullopt, + const std::optional& signature = std::nullopt, + const std::optional& info = std::nullopt); + + std::unique_ptr + CreateManualRateChangeTransactionImpl(const MosaicId providerMosaicId, + const bool currencyBalanceIncrease, + const Amount currencyBalanceChange, + const bool mosaicBalanceIncrease, + const Amount mosaicBalanceChange, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer = std::nullopt, + const std::optional& signature = std::nullopt, + const std::optional& info = std::nullopt); std::unique_ptr - CreateDataModificationTransactionImpl(const Key& driveKey, - const Hash256& downloadDataCdi, - uint64_t uploadSize, - std::optional maxFee, - std::optional deadline, - std::optional networkId, - const std::optional& signer = std::nullopt, - const std::optional& signature = std::nullopt, - const std::optional& info = std::nullopt); + CreateDataModificationTransactionImpl(const Key& driveKey, + const Hash256& downloadDataCdi, + uint64_t uploadSize, + const Amount& feedbackFeeAmount, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer = std::nullopt, + const std::optional& signature = std::nullopt, + const std::optional& info = std::nullopt); std::unique_ptr CreateDownloadTransactionImpl(const Key& driveKey, - uint64_t downloadSize, - const Amount& transactionFee, + uint64_t downloadSize, + const Amount& feedbackFeeAmount, + uint16_t listOfPublicKeysSize, + const std::vector& listOfPublicKeys, std::optional maxFee, std::optional deadline, std::optional networkId, @@ -314,18 +406,48 @@ namespace xpx_chain_sdk { namespace internal { const std::optional& signature = std::nullopt, const std::optional& info = std::nullopt); + std::unique_ptr + CreateDownloadPaymentTransactionImpl(const Hash256& downloadChannelId, + uint64_t downloadSize, + const Amount& feedbackFeeAmount, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer = std::nullopt, + const std::optional& signature = std::nullopt, + const std::optional& info = std::nullopt); + + std::unique_ptr + CreateDriveClosureTransactionImpl(const Key& driveKey, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer = std::nullopt, + const std::optional& signature = std::nullopt, + const std::optional& info = std::nullopt); + std::unique_ptr - CreateDataModificationApprovalTransactionImpl(const Key& driveKey, - const Hash256& dataModificationId, - const Hash256& fileStructureCdi, - uint64_t fileStructureSize, - uint64_t usedDriveSize, - std::optional maxFee, - std::optional deadline, - std::optional networkId, - const std::optional& signer = std::nullopt, - const std::optional& signature = std::nullopt, - const std::optional& info = std::nullopt); + CreateDataModificationApprovalTransactionImpl(const Key& driveKey, + const Hash256& dataModificationId, + const Hash256& fileStructureCdi, + uint8_t modificationStatus, + uint64_t fileStructureSizeBytes, + uint64_t metaFilesSizeBytes, + uint64_t usedDriveSizeBytes, + uint8_t judgingKeysCount, + uint8_t overlappingKeysCount, + uint8_t judgedKeysCount, + uint16_t opinionElementCount, + const std::vector& publicKeys, + const std::vector& signatures, + const std::vector& presentOpinions, + const std::vector& opinions, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer = std::nullopt, + const std::optional& signature = std::nullopt, + const std::optional& info = std::nullopt); std::unique_ptr CreateDataModificationCancelTransactionImpl(const Key& driveKey, @@ -337,24 +459,125 @@ namespace xpx_chain_sdk { namespace internal { const std::optional& signature = std::nullopt, const std::optional& info = std::nullopt); + std::unique_ptr + CreateFinishDownloadTransactionImpl(const Hash256& downloadChannelId, + const Amount& feedbackFeeAmount, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer = std::nullopt, + const std::optional& signature = std::nullopt, + const std::optional& info = std::nullopt); + std::unique_ptr - CreateReplicatorOnboardingTransactionImpl(const Amount& capacity, - const Key& nodeBootKey, - const Hash256& message, - const Signature& messageSignature, - std::optional maxFee, - std::optional deadline, - std::optional networkId, - const std::optional& signer = std::nullopt, - const std::optional& signature = std::nullopt, - const std::optional& info = std::nullopt); + CreateReplicatorOnboardingTransactionImpl(const Amount& capacity, + const Key& nodeBootKey, + const Hash256& message, + const Signature& messageSignature, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer = std::nullopt, + const std::optional& signature = std::nullopt, + const std::optional& info = std::nullopt); std::unique_ptr CreateReplicatorsCleanupTransactionImpl(const std::vector& replicatorKeys, - std::optional maxFee, - std::optional deadline, - std::optional networkId, - const std::optional& signer = std::nullopt, - const std::optional& signature = std::nullopt, - const std::optional& info = std::nullopt); + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer = std::nullopt, + const std::optional& signature = std::nullopt, + const std::optional& info = std::nullopt); + + std::unique_ptr + CreateReplicatorOffboardingTransactionImpl(const Key& driveKey, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer = std::nullopt, + const std::optional& signature = std::nullopt, + const std::optional& info = std::nullopt); + + std::unique_ptr + CreateDeployContractTransactionImpl(const Key& driveKey, + const std::string& fileName, + const std::string& functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + MosaicContainer servicePayments, + const std::string& automaticExecutionsFileName, + const std::string& automaticExecutionsFunctionName, + const Amount& automaticExecutionsCallPayment, + const Amount& automaticDownloadCallPayment, + uint32_t automaticExecutionsNumber, + const Key& assignee, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer = std::nullopt, + const std::optional& signature = std::nullopt, + const std::optional& info = std::nullopt); + + std::unique_ptr + CreateManualCallTransactionImpl(const Key& contractKey, + const std::string& fileName, + const std::string& functionName, + const std::vector& actualArguments, + const Amount& executionCallPayment, + const Amount& downloadCallPayment, + MosaicContainer servicePayments, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer = std::nullopt, + const std::optional& signature = std::nullopt, + const std::optional& info = std::nullopt); + + std::unique_ptr + CreateAutomaticExecutionsPaymentTransactionImpl(const Key& contractKey, + uint32_t automaticExecutionsNumber, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional& signer = std::nullopt, + const std::optional& signature = std::nullopt, + const std::optional& info = std::nullopt); + + std::unique_ptr + CreateStreamStartTransactionImpl(const Key &driveKey, + const uint64_t expectedUploadSizeMegabytes, + const uint16_t folderNameSize, + const Amount &feedbackFeeAmount, + const std::vector& folderName, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional &signer = std::nullopt, + const std::optional &signature = std::nullopt, + const std::optional &info = std::nullopt); + + std::unique_ptr + CreateStreamFinishTransactionImpl(const Key& driveKey, + const Hash256& streamId, + const uint64_t actualUploadSizeMegabytes, + const Hash256& streamStructureCdi, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional &signer = std::nullopt, + const std::optional &signature = std::nullopt, + const std::optional &info = std::nullopt); + + std::unique_ptr + CreateStreamPaymentTransactionImpl(const Key &driveKey, + const Hash256 &streamId, + const uint64_t additionalUploadSizeMegabytes, + std::optional maxFee, + std::optional deadline, + std::optional networkId, + const std::optional &signer = std::nullopt, + const std::optional &signature = std::nullopt, + const std::optional &info = std::nullopt); }} diff --git a/src/sdk/model/transaction/data_modification_approval_transaction.cpp b/src/sdk/model/transaction/data_modification_approval_transaction.cpp index ca4b2be..40dcda8 100644 --- a/src/sdk/model/transaction/data_modification_approval_transaction.cpp +++ b/src/sdk/model/transaction/data_modification_approval_transaction.cpp @@ -25,18 +25,78 @@ namespace xpx_chain_sdk { return fileStructureCdi_; } + template + uint8_t TDataModificationApprovalTransaction::modificationStatus() const + { + return modificationStatus_; + } + template - uint64_t TDataModificationApprovalTransaction::fileStructureSize() const + uint64_t TDataModificationApprovalTransaction::fileStructureSizeBytes() const { return fileStructureSize_; } + template + uint64_t TDataModificationApprovalTransaction::metaFilesSizeBytes() const + { + return metaFilesSize_; + } + template - uint64_t TDataModificationApprovalTransaction::usedDriveSize() const + uint64_t TDataModificationApprovalTransaction::usedDriveSizeBytes() const { return usedDriveSize_; } + template + uint8_t TDataModificationApprovalTransaction::judgingKeysCount() const + { + return judgingKeysCount_; + } + + template + uint8_t TDataModificationApprovalTransaction::overlappingKeysCount() const + { + return overlappingKeysCount_; + } + + template + uint8_t TDataModificationApprovalTransaction::judgedKeysCount() const + { + return judgedKeysCount_; + } + + template + uint8_t TDataModificationApprovalTransaction::opinionElementCount() const + { + return opinionElementCount_; + } + + template + std::vector TDataModificationApprovalTransaction::publicKeys() const + { + return publicKeys_; + } + + template + std::vector TDataModificationApprovalTransaction::signatures() const + { + return signatures_; + } + + template + std::vector TDataModificationApprovalTransaction::presentOpinions() const + { + return presentOpinions_; + } + + template + std::vector TDataModificationApprovalTransaction::opinions() const + { + return opinions_; + } + template class TDataModificationApprovalTransaction; template class TDataModificationApprovalTransaction; } diff --git a/src/sdk/model/transaction/data_modification_transaction.cpp b/src/sdk/model/transaction/data_modification_transaction.cpp index 0df7ca5..9587caa 100644 --- a/src/sdk/model/transaction/data_modification_transaction.cpp +++ b/src/sdk/model/transaction/data_modification_transaction.cpp @@ -25,6 +25,12 @@ namespace xpx_chain_sdk { return uploadSize_; } + template + const Amount& TDataModificationTransaction::feedbackFeeAmount() const + { + return feedbackFeeAmount_; + } + template class TDataModificationTransaction; template class TDataModificationTransaction; } diff --git a/src/sdk/model/transaction/deploy_contract_transaction.cpp b/src/sdk/model/transaction/deploy_contract_transaction.cpp new file mode 100644 index 0000000..9858bef --- /dev/null +++ b/src/sdk/model/transaction/deploy_contract_transaction.cpp @@ -0,0 +1,77 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ + +#include + +namespace xpx_chain_sdk { + template + const xpx_chain_sdk::Key &xpx_chain_sdk::TDeployContractTransaction::driveKey() const { + return driveKey_; + } + + template + const std::string &xpx_chain_sdk::TDeployContractTransaction::fileName() const { + return fileName_; + } + + template + const std::string &xpx_chain_sdk::TDeployContractTransaction::functionName() const { + return functionName_; + } + + template + const std::vector& xpx_chain_sdk::TDeployContractTransaction::actualArguments() const { + return actualArguments_; + } + + template + const Amount& xpx_chain_sdk::TDeployContractTransaction::executionCallPayment() const { + return executionCallPayment_; + } + + template + const Amount& xpx_chain_sdk::TDeployContractTransaction::downloadCallPayment() const { + return downloadCallPayment_; + } + + template + const MosaicContainer& xpx_chain_sdk::TDeployContractTransaction::servicePayments() const { + return servicePayments_; + } + + template + const std::string &xpx_chain_sdk::TDeployContractTransaction::automaticExecutionsFileName() const { + return automaticExecutionsFileName_; + } + + template + const std::string &xpx_chain_sdk::TDeployContractTransaction::automaticExecutionsFunctionName() const { + return automaticExecutionsFunctionName_; + } + + template + const Amount & xpx_chain_sdk::TDeployContractTransaction::automaticExecutionsCallPayment() const { + return automaticExecutionsCallPayment_; + } + + template + const Amount & xpx_chain_sdk::TDeployContractTransaction::automaticDownloadCallPayment() const { + return automaticDownloadCallPayment_; + } + + template + uint32_t xpx_chain_sdk::TDeployContractTransaction::automaticExecutionsNumber() const { + return automaticExecutionsNumber_; + } + + template + const xpx_chain_sdk::Key &xpx_chain_sdk::TDeployContractTransaction::assignee() const { + return assignee_; + } + + template class TDeployContractTransaction; + template class TDeployContractTransaction; +} \ No newline at end of file diff --git a/src/sdk/model/transaction/download_payment_transaction.cpp b/src/sdk/model/transaction/download_payment_transaction.cpp new file mode 100644 index 0000000..c267a56 --- /dev/null +++ b/src/sdk/model/transaction/download_payment_transaction.cpp @@ -0,0 +1,30 @@ +/** +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#include + +namespace xpx_chain_sdk { + + template + const Hash256& TDownloadPaymentTransaction::downloadChannelId() const + { + return downloadChannelId_; + } + + template + uint64_t TDownloadPaymentTransaction::downloadSize() const + { + return downloadSize_; + } + + template + const Amount& TDownloadPaymentTransaction::feedbackFeeAmount() const + { + return feedbackFeeAmount_; + } + + template class TDownloadPaymentTransaction; + template class TDownloadPaymentTransaction; +} diff --git a/src/sdk/model/transaction/download_transaction.cpp b/src/sdk/model/transaction/download_transaction.cpp index a1a0fbc..a138e3d 100644 --- a/src/sdk/model/transaction/download_transaction.cpp +++ b/src/sdk/model/transaction/download_transaction.cpp @@ -6,23 +6,35 @@ #include namespace xpx_chain_sdk { - + + template + const Key& TDownloadTransaction::driveKey() const + { + return driveKey_; + } + template - const Key& TDownloadTransaction::driveKey() const + uint64_t TDownloadTransaction::downloadSize() const { - return driveKey_; + return downloadSize_; } template - uint64_t TDownloadTransaction::downloadSize() const + const Amount& TDownloadTransaction::feedbackFeeAmount() const { - return downloadSize_; + return feedbackFeeAmount_; } + template + uint16_t TDownloadTransaction::listOfPublicKeysSize() const + { + return listOfPublicKeysSize_; + } + template - const Amount& TDownloadTransaction::transactionFee() const + std::vector TDownloadTransaction::listOfPublicKeys() const { - return transactionFee_; + return listOfPublicKeys_; } template class TDownloadTransaction; diff --git a/src/sdk/model/transaction/drive_closure_transaction.cpp b/src/sdk/model/transaction/drive_closure_transaction.cpp new file mode 100644 index 0000000..5c2f10a --- /dev/null +++ b/src/sdk/model/transaction/drive_closure_transaction.cpp @@ -0,0 +1,18 @@ +/** +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#include + +namespace xpx_chain_sdk { + + template + const Key& TDriveClosureTransaction::driveKey() const + { + return driveKey_; + } + + template class TDriveClosureTransaction; + template class TDriveClosureTransaction; +} diff --git a/src/sdk/model/transaction/finish_download_transaction.cpp b/src/sdk/model/transaction/finish_download_transaction.cpp new file mode 100644 index 0000000..b892dbd --- /dev/null +++ b/src/sdk/model/transaction/finish_download_transaction.cpp @@ -0,0 +1,24 @@ +/** +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#include + +namespace xpx_chain_sdk { + + template + const Hash256& TFinishDownloadTransaction::downloadChannelId() const + { + return downloadChannelId_; + } + + template + const Amount& TFinishDownloadTransaction::feedbackFeeAmount() const + { + return feedbackFeeAmount_; + } + + template class TFinishDownloadTransaction; + template class TFinishDownloadTransaction; +} diff --git a/src/sdk/model/transaction/manual_call_transaction.cpp b/src/sdk/model/transaction/manual_call_transaction.cpp new file mode 100644 index 0000000..0444821 --- /dev/null +++ b/src/sdk/model/transaction/manual_call_transaction.cpp @@ -0,0 +1,47 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ + +#include + +namespace xpx_chain_sdk { + template + const Key& TManualCallTransaction::contractKey() const { + return contractKey_; + } + + template + const std::string& TManualCallTransaction::fileName() const { + return fileName_; + } + + template + const std::string& TManualCallTransaction::functionName() const { + return functionName_; + } + + template + const std::vector& TManualCallTransaction::actualArguments() const { + return actualArguments_; + } + + template + const Amount& TManualCallTransaction::executionCallPayment() const { + return executionCallPayment_; + } + + template + const Amount& TManualCallTransaction::downloadCallPayment() const { + return downloadCallPayment_; + } + + template + const MosaicContainer& TManualCallTransaction::servicePayments() const { + return servicePayments_; + } + + template class TManualCallTransaction; + template class TManualCallTransaction; +} diff --git a/src/sdk/model/transaction/manual_rate_change_transaction.cpp b/src/sdk/model/transaction/manual_rate_change_transaction.cpp new file mode 100644 index 0000000..12cb272 --- /dev/null +++ b/src/sdk/model/transaction/manual_rate_change_transaction.cpp @@ -0,0 +1,42 @@ +/** +*** Copyright 2022 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#include + +namespace xpx_chain_sdk { + + template + MosaicId TManualRateChangeTransaction::providerMosaicId() const + { + return providerMosaicId_; + } + + template + bool TManualRateChangeTransaction::currencyBalanceIncrease() const + { + return currencyBalanceIncrease_; + } + + template + Amount TManualRateChangeTransaction::currencyBalanceChange() const + { + return currencyBalanceChange_; + } + + template + bool TManualRateChangeTransaction::mosaicBalanceIncrease() const + { + return mosaicBalanceIncrease_; + } + + template + Amount TManualRateChangeTransaction::mosaicBalanceChange() const + { + return mosaicBalanceChange_; + } + + template class TManualRateChangeTransaction; + template class TManualRateChangeTransaction; +} diff --git a/src/sdk/model/transaction/mosaic_definition_transaction.cpp b/src/sdk/model/transaction/mosaic_definition_transaction.cpp index 9127ed1..f5cfb42 100644 --- a/src/sdk/model/transaction/mosaic_definition_transaction.cpp +++ b/src/sdk/model/transaction/mosaic_definition_transaction.cpp @@ -18,12 +18,6 @@ namespace xpx_chain_sdk { { return mosaicId_; } - - template - MosaicFlags TMosaicDefinitionTransaction::flags() const - { - return flags_; - } template const MosaicProperties& TMosaicDefinitionTransaction::mosaicProperties() const diff --git a/src/sdk/model/transaction/prepare_bc_drive_transaction.cpp b/src/sdk/model/transaction/prepare_bc_drive_transaction.cpp index 6b9c292..588ad5b 100644 --- a/src/sdk/model/transaction/prepare_bc_drive_transaction.cpp +++ b/src/sdk/model/transaction/prepare_bc_drive_transaction.cpp @@ -13,6 +13,12 @@ namespace xpx_chain_sdk { return driveSize_; } + template + Amount TPrepareBcDriveTransaction::verificationFeeAmount() const + { + return verificationFeeAmount_; + } + template uint16_t TPrepareBcDriveTransaction::replicatorCount() const { diff --git a/src/sdk/model/transaction/replicator_offboarding_transaction.cpp b/src/sdk/model/transaction/replicator_offboarding_transaction.cpp new file mode 100644 index 0000000..29e2974 --- /dev/null +++ b/src/sdk/model/transaction/replicator_offboarding_transaction.cpp @@ -0,0 +1,18 @@ +/** +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#include + +namespace xpx_chain_sdk { + + template + const Key& TReplicatorOffboardingTransaction::driveKey() const + { + return driveKey_; + } + + template class TReplicatorOffboardingTransaction; + template class TReplicatorOffboardingTransaction; +} diff --git a/src/sdk/model/transaction/storage_payment_transaction.cpp b/src/sdk/model/transaction/storage_payment_transaction.cpp new file mode 100644 index 0000000..2b4c3ad --- /dev/null +++ b/src/sdk/model/transaction/storage_payment_transaction.cpp @@ -0,0 +1,24 @@ +/** +*** Copyright 2021 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#include + +namespace xpx_chain_sdk { + + template + const Key& TStoragePaymentTransaction::driveKey() const + { + return driveKey_; + } + + template + const Amount& TStoragePaymentTransaction::storageUnitsAmount() const + { + return storageUnits_; + } + + template class TStoragePaymentTransaction; + template class TStoragePaymentTransaction; +} diff --git a/src/sdk/model/transaction/stream_finish_transaction.cpp b/src/sdk/model/transaction/stream_finish_transaction.cpp new file mode 100644 index 0000000..2652e70 --- /dev/null +++ b/src/sdk/model/transaction/stream_finish_transaction.cpp @@ -0,0 +1,32 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#include + +namespace xpx_chain_sdk { + + template + const Key& TStreamFinishTransaction::driveKey() const { + return driveKey_; + } + + template + const Hash256& TStreamFinishTransaction::streamId() const { + return streamId_; + } + + template + uint64_t TStreamFinishTransaction::actualUploadSizeMegabytes() const { + return actualUploadSizeMegabytes_; + } + + template + const Hash256& TStreamFinishTransaction::streamStructureCdi() const { + return streamStructureCdi_; + } + + template class TStreamFinishTransaction; + template class TStreamFinishTransaction; +} diff --git a/src/sdk/model/transaction/stream_payment_transaction.cpp b/src/sdk/model/transaction/stream_payment_transaction.cpp new file mode 100644 index 0000000..cfe2778 --- /dev/null +++ b/src/sdk/model/transaction/stream_payment_transaction.cpp @@ -0,0 +1,27 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#include + +namespace xpx_chain_sdk { + + template + const Key& TStreamPaymentTransaction::driveKey() const { + return driveKey_; + } + + template + const Hash256& TStreamPaymentTransaction::streamId() const { + return streamId_; + } + + template + uint64_t TStreamPaymentTransaction::additionalUploadSizeMegabytes() const { + return additionalUploadSizeMegabytes_; + } + + template class TStreamPaymentTransaction; + template class TStreamPaymentTransaction; +} diff --git a/src/sdk/model/transaction/stream_start_transaction.cpp b/src/sdk/model/transaction/stream_start_transaction.cpp new file mode 100644 index 0000000..b7c7c51 --- /dev/null +++ b/src/sdk/model/transaction/stream_start_transaction.cpp @@ -0,0 +1,37 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ +#include + +namespace xpx_chain_sdk { + + template + const Key& TStreamStartTransaction::driveKey() const { + return driveKey_; + } + + template + uint64_t TStreamStartTransaction::expectedUploadSizeMegabytes() const { + return expectedUploadSizeMegabytes_; + } + + template + std::vector TStreamStartTransaction::folderName() const { + return folderName_; + } + + template + uint16_t TStreamStartTransaction::folderNameSize() const { + return folderNameSize_; + } + + template + const Amount& TStreamStartTransaction::feedbackFeeAmount() const { + return feedbackFeeAmount_; + } + + template class TStreamStartTransaction; + template class TStreamStartTransaction; +} diff --git a/src/sdk/model/transaction/successful_end_batch_execution_transaction.cpp b/src/sdk/model/transaction/successful_end_batch_execution_transaction.cpp new file mode 100644 index 0000000..4e3f18c --- /dev/null +++ b/src/sdk/model/transaction/successful_end_batch_execution_transaction.cpp @@ -0,0 +1,56 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ + +#include + +namespace xpx_chain_sdk { + template + const Key& TSuccessfulEndBatchExecutionTransaction::contractKey() const { + return contractKey_; + } + + template + uint64_t TSuccessfulEndBatchExecutionTransaction::batchId() const { + return batchId_; + } + + template + const Hash256& TSuccessfulEndBatchExecutionTransaction::storageHash() const { + return storageHash_; + } + + template + uint64_t TSuccessfulEndBatchExecutionTransaction::usedSizeBytes() const { + return usedSizeBytes_; + } + + template + uint64_t TSuccessfulEndBatchExecutionTransaction::metaFilesSizeBytes() const { + return metaFilesSizeBytes_; + } + + template + const uint64_t TSuccessfulEndBatchExecutionTransaction::automaticExecutionsNextBlockToCheck() const { + return automaticExecutionsNextBlockToCheck_; + } + + template + const std::array& TSuccessfulEndBatchExecutionTransaction::proofOfExecutionVerificationInformation() const { + return proofOfExecutionVerificationInformation_; + } + + template + const std::vector& TSuccessfulEndBatchExecutionTransaction::callDigests() const { + return callDigests_; + } + + template + const std::vector& TSuccessfulEndBatchExecutionTransaction::opinions() const { + return opinions_; + } + template class TSuccessfulEndBatchExecutionTransaction; + template class TSuccessfulEndBatchExecutionTransaction; +} \ No newline at end of file diff --git a/src/sdk/model/transaction/transaction_type.cpp b/src/sdk/model/transaction/transaction_type.cpp index 422d2e4..6101f77 100644 --- a/src/sdk/model/transaction/transaction_type.cpp +++ b/src/sdk/model/transaction/transaction_type.cpp @@ -6,70 +6,104 @@ #include namespace xpx_chain_sdk { - - const char* GetTransactionName(TransactionType type) - { - switch (type) { - case TransactionType::Transfer: return "transfer"; - case TransactionType::Mosaic_Definition: return "mosaic definition"; - case TransactionType::Mosaic_Supply_Change: return "mosaic supply change"; - case TransactionType::Mosaic_Levy_Change: return "mosaic levy change"; - case TransactionType::Register_Namespace: return "register namespace"; - case TransactionType::Address_Alias: return "address alias"; - case TransactionType::Mosaic_Alias: return "mosaic alias"; - case TransactionType::Modify_Multisig_Account: return "modify multisig account"; - case TransactionType::Aggregate_Complete: return "aggregate complete"; - case TransactionType::Aggregate_Bonded: return "aggregate bonded"; - case TransactionType::Lock_Funds: return "lock funds"; - case TransactionType::Address_Property: return "address property"; - case TransactionType::Mosaic_Property: return "mosaic property"; - case TransactionType::Transaction_Property: return "transaction property"; - case TransactionType::Secret_Lock: return "secret lock"; - case TransactionType::Secret_Proof: return "secret proof"; - case TransactionType::Account_Link: return "account link"; - case TransactionType::Prepare_Bc_Drive: return "prepare bc drive"; - case TransactionType::Data_Modification: return "data modification"; - case TransactionType::Download: return "download"; - case TransactionType::Data_Modification_Approval: return "data modification approval"; - case TransactionType::Data_Modification_Cancel: return "data modification cancel"; - case TransactionType::Replicator_Onboarding: return "replicator onboarding"; - case TransactionType::Replicators_Cleanup: return "replicators cleanup"; - default: break; - } - - return "unknown"; - } - - uint8_t GetTransactionVersion(TransactionType type) - { - switch (type) { - case TransactionType::Transfer: return 3; - case TransactionType::Mosaic_Definition: return 3; - case TransactionType::Mosaic_Supply_Change: return 2; - case TransactionType::Mosaic_Levy_Change: return 0; - case TransactionType::Register_Namespace: return 2; - case TransactionType::Address_Alias: return 1; - case TransactionType::Mosaic_Alias: return 1; - case TransactionType::Modify_Multisig_Account: return 3; - case TransactionType::Aggregate_Complete: return 2; - case TransactionType::Aggregate_Bonded: return 2; - case TransactionType::Lock_Funds: return 1; - case TransactionType::Address_Property: return 1; - case TransactionType::Mosaic_Property: return 1; - case TransactionType::Transaction_Property: return 1; - case TransactionType::Secret_Lock: return 1; - case TransactionType::Secret_Proof: return 1; - case TransactionType::Account_Link: return 2; - case TransactionType::Prepare_Bc_Drive: return 1; - case TransactionType::Data_Modification: return 1; - case TransactionType::Download: return 1; - case TransactionType::Data_Modification_Approval: return 1; - case TransactionType::Data_Modification_Cancel: return 1; - case TransactionType::Replicator_Onboarding: return 2; - case TransactionType::Replicators_Cleanup: return 1; - default: break; - } - - return 0; - } + + const char* GetTransactionName(TransactionType type) + { + switch (type) { + case TransactionType::Transfer: return "transfer"; + case TransactionType::Mosaic_Definition: return "mosaic definition"; + case TransactionType::Mosaic_Supply_Change: return "mosaic supply change"; + case TransactionType::Mosaic_Levy_Change: return "mosaic levy change"; + case TransactionType::Register_Namespace: return "register namespace"; + case TransactionType::Address_Alias: return "address alias"; + case TransactionType::Mosaic_Alias: return "mosaic alias"; + case TransactionType::Modify_Multisig_Account: return "modify multisig account"; + case TransactionType::Aggregate_Complete: return "aggregate complete"; + case TransactionType::Aggregate_Bonded: return "aggregate bonded"; + case TransactionType::Lock_Funds: return "lock funds"; + case TransactionType::Address_Property: return "address property"; + case TransactionType::Mosaic_Property: return "mosaic property"; + case TransactionType::Transaction_Property: return "transaction property"; + case TransactionType::Secret_Lock: return "secret lock"; + case TransactionType::Secret_Proof: return "secret proof"; + case TransactionType::Storage_Payment: return "storage payment"; + case TransactionType::Account_Link: return "account link"; + case TransactionType::Prepare_Bc_Drive: return "prepare bc drive"; + case TransactionType::Data_Modification: return "data modification"; + case TransactionType::Download: return "download"; + case TransactionType::Download_Payment: return "download payment"; + case TransactionType::Drive_Closure: return "drive closure"; + case TransactionType::Data_Modification_Approval: return "data modification approval"; + case TransactionType::Data_Modification_Cancel: return "data modification cancel"; + case TransactionType::Create_Liquidity_Provider: return "create liquidity provider"; + case TransactionType::Manual_Rate_Change: return "manual rate change"; + case TransactionType::Finish_Download: return "finish download"; + case TransactionType::Replicator_Onboarding: return "replicator onboarding"; + case TransactionType::Replicator_Offboarding: return "replicator offboarding"; + case TransactionType::Deploy_Contract: return "Deploy Contract"; + case TransactionType::Manual_Call: return "Manual Call"; + case TransactionType::Automatic_Executions_Payment: return "Automatic Executions Payment"; + case TransactionType::Successful_End_Batch_Execution: return "Successful End Batch Execution"; + case TransactionType::Unsuccessful_End_Batch_Execution: return "Unsuccessful End Batch Execution"; + case TransactionType::End_Batch_Execution_Single: return "End Batch Execution Single"; + case TransactionType::Synchronization_Single: return "Synchronization Single"; + case TransactionType::Stream_Start: return "Stream Start"; + case TransactionType::Stream_Finish: return "Stream Finish"; + case TransactionType::Stream_Payment: return "Stream Payment"; + case TransactionType::Replicators_Cleanup: return "Replicators Cleanup"; + default: break; + } + + return "unknown"; + } + + uint8_t GetTransactionVersion(TransactionType type) + { + switch (type) { + case TransactionType::Transfer: return 3; + case TransactionType::Mosaic_Definition: return 3; + case TransactionType::Mosaic_Supply_Change: return 2; + case TransactionType::Mosaic_Levy_Change: return 0; + case TransactionType::Register_Namespace: return 2; + case TransactionType::Address_Alias: return 1; + case TransactionType::Mosaic_Alias: return 1; + case TransactionType::Modify_Multisig_Account: return 3; + case TransactionType::Aggregate_Complete: return 2; + case TransactionType::Aggregate_Bonded: return 2; + case TransactionType::Lock_Funds: return 1; + case TransactionType::Address_Property: return 1; + case TransactionType::Mosaic_Property: return 1; + case TransactionType::Transaction_Property: return 1; + case TransactionType::Secret_Lock: return 1; + case TransactionType::Secret_Proof: return 1; + case TransactionType::Storage_Payment: return 1; + case TransactionType::Account_Link: return 2; + case TransactionType::Prepare_Bc_Drive: return 1; + case TransactionType::Data_Modification: return 1; + case TransactionType::Download: return 1; + case TransactionType::Download_Payment: return 1; + case TransactionType::Drive_Closure: return 1; + case TransactionType::Data_Modification_Approval: return 1; + case TransactionType::Data_Modification_Cancel: return 1; + case TransactionType::Create_Liquidity_Provider: return 1; + case TransactionType::Manual_Rate_Change: return 1; + case TransactionType::Finish_Download: return 1; + case TransactionType::Replicator_Onboarding: return 2; + case TransactionType::Replicator_Offboarding: return 1; + case TransactionType::Deploy_Contract: return 1; + case TransactionType::Manual_Call: return 1; + case TransactionType::Automatic_Executions_Payment: return 1; + case TransactionType::Successful_End_Batch_Execution: return 1; + case TransactionType::Unsuccessful_End_Batch_Execution: return 1; + case TransactionType::End_Batch_Execution_Single: return 1; + case TransactionType::Synchronization_Single: return 1; + case TransactionType::Stream_Start: return 1; + case TransactionType::Stream_Finish: return 1; + case TransactionType::Stream_Payment: return 1; + case TransactionType::Replicators_Cleanup: return 1; + default: break; + } + + return 0; + } } \ No newline at end of file diff --git a/src/sdk/model/transaction/transaction_utils.cpp b/src/sdk/model/transaction/transaction_utils.cpp index 50f04e4..42c7ebd 100644 --- a/src/sdk/model/transaction/transaction_utils.cpp +++ b/src/sdk/model/transaction/transaction_utils.cpp @@ -39,13 +39,13 @@ namespace xpx_chain_sdk { namespace internal { if (transaction->type() != TransactionType::Aggregate_Complete && transaction->type() != TransactionType::Aggregate_Bonded) { - return RawBuffer(data.data() + Tx_Signed_Data_Start, data.size() - Tx_Signed_Data_Start); + return { data.data() + Tx_Signed_Data_Start, data.size() - Tx_Signed_Data_Start }; } else { auto aggregateTx = dynamic_cast(transaction); assert(data.size() >= aggregateTx->payloadSize() + Aggregate_Tx_Payload_Start); size_t cosignaturesSize = data.size() - (aggregateTx->payloadSize() + Aggregate_Tx_Payload_Start); - return RawBuffer(data.data() + Tx_Signed_Data_Start, data.size() - Tx_Signed_Data_Start - cosignaturesSize); + return { data.data() + Tx_Signed_Data_Start, data.size() - Tx_Signed_Data_Start - cosignaturesSize }; } } diff --git a/src/sdk/model/transaction/unsuccessful_end_batch_execution_transaction.cpp b/src/sdk/model/transaction/unsuccessful_end_batch_execution_transaction.cpp new file mode 100644 index 0000000..74803ef --- /dev/null +++ b/src/sdk/model/transaction/unsuccessful_end_batch_execution_transaction.cpp @@ -0,0 +1,37 @@ +/** +*** Copyright 2023 ProximaX Limited. All rights reserved. +*** Use of this source code is governed by the Apache 2.0 +*** license that can be found in the LICENSE file. +**/ + +#include + +namespace xpx_chain_sdk { + template + const Key& TUnsuccessfulEndBatchExecutionTransaction::contractKey() const { + return contractKey_; + } + + template + uint64_t TUnsuccessfulEndBatchExecutionTransaction::batchId() const { + return batchId_; + } + + template + const uint64_t TUnsuccessfulEndBatchExecutionTransaction::automaticExecutionsNextBlockToCheck() const { + return automaticExecutionsNextBlockToCheck_; + } + + template + const std::vector& TUnsuccessfulEndBatchExecutionTransaction::callDigests() const { + return callDigests_; + } + + template + const std::vector& TUnsuccessfulEndBatchExecutionTransaction::opinions() const { + return opinions_; + } + + template class TUnsuccessfulEndBatchExecutionTransaction; + template class TUnsuccessfulEndBatchExecutionTransaction; +} \ No newline at end of file diff --git a/src/sdk/service/binary_serialization.cpp b/src/sdk/service/binary_serialization.cpp index c8313c9..77a7dbf 100644 --- a/src/sdk/service/binary_serialization.cpp +++ b/src/sdk/service/binary_serialization.cpp @@ -174,7 +174,10 @@ namespace xpx_chain_sdk { return CreateTransaction( dto, binaryData, - dto.template value<"nonce"_>(), dto.template value<"mosaicId"_>(), dto.template value<"flags"_>(), MosaicProperties(std::move(properties))); + dto.template value<"mosaicNonce"_>(), + dto.template value<"mosaicId"_>(), + MosaicProperties(std::move(properties)) + ); } template< @@ -236,11 +239,25 @@ namespace xpx_chain_sdk { std::unique_ptr CreateSecretProofTransaction(const TDto& dto, RawBuffer binaryData) { return CreateTransaction( - dto, binaryData, - dto.template value<"hashAlgorithm"_>(), dto.template value<"secret"_>(), - dto.template value<"proof"_>()); + dto, binaryData, + dto.template value<"hashAlgorithm"_>(), + dto.template value<"secret"_>(), + dto.template value<"proof"_>()); } - + + template< + typename TDto, + typename TImpl = std::conditional_t, + StoragePaymentTransactionImpl, + EmbeddedStoragePaymentTransactionImpl>> + std::unique_ptr CreateStoragePaymentTransaction(const TDto& dto, RawBuffer binaryData) + { + return CreateTransaction( + dto, binaryData, + dto.template value<"driveKey"_>(), + dto.template value<"storageUnits"_>()); + } + template< typename TDto, typename TImpl = std::conditional_t, @@ -292,20 +309,60 @@ namespace xpx_chain_sdk { { return CreateTransaction( dto, binaryData, - dto.template value<"driveSize"_>(), dto.template value<"replicatorCount"_>()); + dto.template value<"driveSize"_>(), + dto.template value<"verificationFeeAmount"_>(), + dto.template value<"replicatorCount"_>()); } + template< + typename TDto, + typename TImpl = std::conditional_t, + CreateLiquidityProviderTransactionImpl, + EmbeddedCreateLiquidityProviderTransactionImpl>> + std::unique_ptr CreateCreateLiquidityProviderTransaction(const TDto& dto, RawBuffer binaryData) + { + return CreateTransaction( + dto, binaryData, + dto.template value<"providerMosaicId"_>(), + dto.template value<"currencyDeposit"_>(), + dto.template value<"initialMosaicsMinting"_>(), + dto.template value<"slashingPeriod"_>(), + dto.template value<"windowSize"_>(), + dto.template value<"slashingAccount"_>(), + dto.template value<"alpha"_>(), + dto.template value<"beta"_>()); + } + + template< + typename TDto, + typename TImpl = std::conditional_t, + ManualRateChangeTransactionImpl, + EmbeddedManualRateChangeTransactionImpl>> + std::unique_ptr CreateManualRateChangeTransaction(const TDto& dto, RawBuffer binaryData) + { + return CreateTransaction( + dto, binaryData, + dto.template value<"providerMosaicId"_>(), + dto.template value<"currencyBalanceIncrease"_>(), + dto.template value<"currencyBalanceChange"_>(), + dto.template value<"mosaicBalanceIncrease"_>(), + dto.template value<"mosaicBalanceChange"_>()); + } + template< typename TDto, typename TImpl = std::conditional_t, DataModificationTransactionImpl, EmbeddedDataModificationTransactionImpl>> - std::unique_ptr CreateDataModificationTransaction(const TDto& dto, RawBuffer binaryData) - { - return CreateTransaction( - dto, binaryData, - dto.template value<"driveKey"_>(), dto.template value<"downloadDataCdi"_>(), dto.template value<"uploadSize"_>()); - } + std::unique_ptr CreateDataModificationTransaction(const TDto& dto, RawBuffer binaryData) + { + return CreateTransaction( + dto, binaryData, + dto.template value<"driveKey"_>(), + dto.template value<"downloadDataCdi"_>(), + dto.template value<"uploadSize"_>(), + dto.template value<"feedbackFeeAmount"_>()); + } template< typename TDto, @@ -315,10 +372,40 @@ namespace xpx_chain_sdk { std::unique_ptr CreateDownloadTransaction(const TDto& dto, RawBuffer binaryData) { return CreateTransaction( - dto, binaryData, - dto.template value<"driveKey"_>(), dto.template value<"downloadSize"_>(), dto.template value<"transactionFee"_>()); + dto, binaryData, + dto.template value<"driveKey"_>(), + dto.template value<"downloadSize"_>(), + dto.template value<"feedbackFeeAmount"_>(), + dto.template value<"listOfPublicKeysSize"_>(), + dto.template value<"listOfPublicKeys"_>()); } + template< + typename TDto, + typename TImpl = std::conditional_t, + DownloadPaymentTransactionImpl, + EmbeddedDownloadPaymentTransactionImpl>> + std::unique_ptr CreateDownloadPaymentTransaction(const TDto& dto, RawBuffer binaryData) + { + return CreateTransaction( + dto, binaryData, + dto.template value<"downloadChannelId"_>(), + dto.template value<"downloadSize"_>(), + dto.template value<"feedbackFeeAmount"_>()); + } + + template< + typename TDto, + typename TImpl = std::conditional_t, + DriveClosureTransactionImpl, + EmbeddedDriveClosureTransactionImpl>> + std::unique_ptr CreateDriveClosureTransaction(const TDto& dto, RawBuffer binaryData) + { + return CreateTransaction( + dto, binaryData, + dto.template value<"driveKey"_>()); + } + template< typename TDto, typename TImpl = std::conditional_t, @@ -326,10 +413,23 @@ namespace xpx_chain_sdk { EmbeddedDataModificationApprovalTransactionImpl>> std::unique_ptr CreateDataModificationApprovalTransaction(const TDto& dto, RawBuffer binaryData) { - return CreateTransaction( - dto, binaryData, - dto.template value<"driveKey"_>(), dto.template value<"dataModificationId"_>(), dto.template value<"fileStructureCdi"_>(), - dto.template value<"fileStructureSize"_>(), dto.template value<"usedDriveSize"_>()); + return CreateTransaction( + dto, binaryData, + dto.template value<"driveKey"_>(), + dto.template value<"dataModificationId"_>(), + dto.template value<"fileStructureCdi"_>(), + dto.template value<"modificationStatus"_>(), + dto.template value<"fileStructureSizeBytes"_>(), + dto.template value<"metaFilesSizeBytes"_>(), + dto.template value<"usedDriveSizeBytes"_>(), + dto.template value<"judgingKeysCount"_>(), + dto.template value<"overlappingKeysCount"_>(), + dto.template value<"judgedKeysCount"_>(), + dto.template value<"opinionElementCount"_>(), + dto.template value<"publicKeys"_>(), + dto.template value<"signatures"_>(), + dto.template value<"presentOpinions"_>(), + dto.template value<"opinions"_>()); } template< @@ -344,6 +444,19 @@ namespace xpx_chain_sdk { dto.template value<"driveKey"_>(), dto.template value<"dataModificationId"_>()); } + template< + typename TDto, + typename TImpl = std::conditional_t, + FinishDownloadTransactionImpl, + EmbeddedFinishDownloadTransactionImpl>> + std::unique_ptr CreateFinishDownloadTransaction(const TDto& dto, RawBuffer binaryData) + { + return CreateTransaction( + dto, binaryData, + dto.template value<"downloadChannelId"_>(), + dto.template value<"feedbackFeeAmount"_>()); + } + template< typename TDto, typename TImpl = std::conditional_t, @@ -370,7 +483,135 @@ namespace xpx_chain_sdk { dto, binaryData, dto.template value<"replicatorKeys"_>()); } - + + template< + typename TDto, + typename TImpl = std::conditional_t, + ReplicatorOffboardingTransactionImpl, + EmbeddedReplicatorOffboardingTransactionImpl>> + std::unique_ptr CreateReplicatorOffboardingTransaction(const TDto& dto, RawBuffer binaryData) + { + return CreateTransaction( + dto, binaryData, + dto.template value<"driveKey"_>()); + } + + template< + typename TDto, + typename TImpl = std::conditional_t, + DeployContractTransactionImpl, + EmbeddedDeployContractTransactionImpl>> + std::unique_ptr CreateDeployContractTransaction(const TDto& dto, RawBuffer binaryData) + { + MosaicContainer servicePayments; + for (const auto& servicePaymentDTO: dto.template value<"servicePayments"_>()) { + servicePayments.insert(Mosaic{ servicePaymentDTO.template value<"id"_>(), servicePaymentDTO.template value<"amount"_>() }); + } + if (servicePayments.size() != dto.template value<"servicePayments"_>().size()) { + return nullptr; + } + + return CreateTransaction( + dto, binaryData, + dto.template value<"driveKey"_>(), + dto.template value<"fileName"_>(), + dto.template value<"functionName"_>(), + dto.template value<"actualArguments"_>(), + dto.template value<"executionCallPayment"_>(), + dto.template value<"downloadCallPayment"_>(), + std::move(servicePayments), + dto.template value<"automaticExecutionsFileName"_>(), + dto.template value<"automaticExecutionsFunctionName"_>(), + dto.template value<"automaticExecutionsCallPayment"_>(), + dto.template value<"automaticDownloadCallPayment"_>(), + dto.template value<"automaticExecutionsNumber"_>(), + dto.template value<"assignee"_>()); + } + + template< + typename TDto, + typename TImpl = std::conditional_t, + ManualCallTransactionImpl, + EmbeddedManualCallTransactionImpl>> + std::unique_ptr CreateManualCallTransaction(const TDto& dto, RawBuffer binaryData) + { + MosaicContainer servicePayments; + for (const auto& servicePaymentDTO: dto.template value<"servicePayments"_>()) { + servicePayments.insert(Mosaic{ servicePaymentDTO.template value<"id"_>(), servicePaymentDTO.template value<"amount"_>() }); + } + if (servicePayments.size() != dto.template value<"servicePayments"_>().size()) { + return nullptr; + } + + return CreateTransaction( + dto, binaryData, + dto.template value<"contractKey"_>(), + dto.template value<"fileName"_>(), + dto.template value<"functionName"_>(), + dto.template value<"actualArguments"_>(), + dto.template value<"executionCallPayment"_>(), + dto.template value<"downloadCallPayment"_>(), + std::move(servicePayments)); + } + + template< + typename TDto, + typename TImpl = std::conditional_t, + AutomaticExecutionsPaymentTransactionImpl, + EmbeddedAutomaticExecutionsPaymentTransactionImpl>> + std::unique_ptr CreateAutomaticExecutionsPaymentTransaction(const TDto& dto, RawBuffer binaryData) + { + return CreateTransaction( + dto, binaryData, + dto.template value<"contractKey"_>(), + dto.template value<"automaticExecutionsNumber"_>()); + } + + template< + typename TDto, + typename TImpl = std::conditional_t, + StreamStartTransactionImpl, + EmbeddedStreamStartTransactionImpl>> + std::unique_ptr CreateStreamStartTransaction(const TDto& dto, RawBuffer binaryData) + { + return CreateTransaction( + dto, binaryData, + dto.template value<"driveKey"_>(), + dto.template value<"expectedUploadSizeMegabytes"_>(), + dto.template value<"folderNameSize"_>(), + dto.template value<"feedbackFeeAmount"_>(), + dto.template value<"folderName"_>()); + } + + template< + typename TDto, + typename TImpl = std::conditional_t, + StreamFinishTransactionImpl, + EmbeddedStreamFinishTransactionImpl>> + std::unique_ptr CreateStreamFinishTransaction(const TDto& dto, RawBuffer binaryData) + { + return CreateTransaction( + dto, binaryData, + dto.template value<"driveKey"_>(), + dto.template value<"streamId"_>(), + dto.template value<"actualUploadSize"_>(), + dto.template value<"streamStructureCdi"_>()); + } + + template< + typename TDto, + typename TImpl = std::conditional_t, + StreamPaymentTransactionImpl, + EmbeddedStreamPaymentTransactionImpl>> + std::unique_ptr CreateStreamPaymentTransaction(const TDto& dto, RawBuffer binaryData) + { + return CreateTransaction( + dto, binaryData, + dto.template value<"driveKey"_>(), + dto.template value<"streamId"_>(), + dto.template value<"additionalUploadSize"_>()); + } + bool ReadEmbeddedTransactions(RawBuffer data, EmbeddedTransactions& embeddedTransactions) { EmbeddedTransactionDTO header; @@ -533,6 +774,17 @@ namespace xpx_chain_sdk { break; } + case TransactionType::Storage_Payment: + { + EmbeddedStoragePaymentTransactionDTO dto; + result = Parser::Read(dto, data, startPos); + + if (result) { + embeddedTransaction = CreateStoragePaymentTransaction(dto, RawBuffer{}); + } + + break; + } case TransactionType::Transfer: { EmbeddedTransferTransactionDTO dto; @@ -555,6 +807,28 @@ namespace xpx_chain_sdk { break; } + case TransactionType::Create_Liquidity_Provider: + { + EmbeddedCreateLiquidityProviderTransactionDTO dto; + result = Parser::Read(dto, data, startPos); + + if (result) { + embeddedTransaction = CreateCreateLiquidityProviderTransaction(dto, RawBuffer{}); + } + + break; + } + case TransactionType::Manual_Rate_Change: + { + EmbeddedManualRateChangeTransactionDTO dto; + result = Parser::Read(dto, data, startPos); + + if (result) { + embeddedTransaction = CreateManualRateChangeTransaction(dto, RawBuffer{}); + } + + break; + } case TransactionType::Data_Modification: { EmbeddedDataModificationTransactionDTO dto; @@ -577,6 +851,28 @@ namespace xpx_chain_sdk { break; } + case TransactionType::Download_Payment: + { + EmbeddedDownloadPaymentTransactionDTO dto; + result = Parser::Read(dto, data, startPos); + + if (result) { + embeddedTransaction = CreateDownloadPaymentTransaction(dto, RawBuffer{}); + } + + break; + } + case TransactionType::Drive_Closure: + { + EmbeddedDriveClosureTransactionDTO dto; + result = Parser::Read(dto, data, startPos); + + if (result) { + embeddedTransaction = CreateDriveClosureTransaction(dto, RawBuffer{}); + } + + break; + } case TransactionType::Data_Modification_Approval: { EmbeddedDataModificationApprovalTransactionDTO dto; @@ -599,6 +895,17 @@ namespace xpx_chain_sdk { break; } + case TransactionType::Finish_Download: + { + EmbeddedFinishDownloadTransactionDTO dto; + result = Parser::Read(dto, data, startPos); + + if (result) { + embeddedTransaction = CreateFinishDownloadTransaction(dto, RawBuffer{}); + } + + break; + } case TransactionType::Replicator_Onboarding: { EmbeddedReplicatorOnboardingTransactionDTO dto; @@ -621,6 +928,83 @@ namespace xpx_chain_sdk { break; } + case TransactionType::Deploy_Contract: + { + EmbeddedDeployContractTransactionDTO dto; + result = Parser::Read(dto, data, startPos); + + if (result) { + embeddedTransaction = CreateDeployContractTransaction(dto, RawBuffer{}); + } + + break; + } + case TransactionType::Manual_Call: + { + EmbeddedManualCallTransactionDTO dto; + result = Parser::Read(dto, data, startPos); + + if (result) { + embeddedTransaction = CreateManualCallTransaction(dto, RawBuffer{}); + } + + break; + } + case TransactionType::Automatic_Executions_Payment: + { + EmbeddedAutomaticExecutionsPaymentTransactionDTO dto; + result = Parser::Read(dto, data, startPos); + + if (result) { + embeddedTransaction = CreateAutomaticExecutionsPaymentTransaction(dto, RawBuffer{}); + } + + break; + } + case TransactionType::Replicator_Offboarding: + { + EmbeddedReplicatorOffboardingTransactionDTO dto; + result = Parser::Read(dto, data, startPos); + + if (result) { + embeddedTransaction = CreateReplicatorOffboardingTransaction(dto, RawBuffer{}); + } + + break; + } + case TransactionType::Stream_Start: + { + EmbeddedStreamStartTransactionDTO dto; + result = Parser::Read(dto, data, startPos); + + if (result) { + embeddedTransaction = CreateStreamStartTransaction(dto, RawBuffer{}); + } + + break; + } + case TransactionType::Stream_Finish: + { + EmbeddedStreamFinishTransactionDTO dto; + result = Parser::Read(dto, data, startPos); + + if (result) { + embeddedTransaction = CreateStreamFinishTransaction(dto, RawBuffer{}); + } + + break; + } + case TransactionType::Stream_Payment: + { + EmbeddedStreamPaymentTransactionDTO dto; + result = Parser::Read(dto, data, startPos); + + if (result) { + embeddedTransaction = CreateStreamPaymentTransaction(dto, RawBuffer{}); + } + + break; + } default: { return false; @@ -852,6 +1236,18 @@ namespace xpx_chain_sdk { break; } + case TransactionType::Storage_Payment: + { + StoragePaymentTransactionDTO dto; + parseResult = Parser::Read(dto, data); + RawBuffer binaryData(data.data(), parseResult.processedSize()); + + if (binaryData.size() == dto.value<"size"_>()) { + transaction = CreateStoragePaymentTransaction(dto, binaryData); + } + + break; + } case TransactionType::Transfer: { TransferTransactionDTO dto; @@ -876,6 +1272,30 @@ namespace xpx_chain_sdk { break; } + case TransactionType::Create_Liquidity_Provider: + { + CreateLiquidityProviderTransactionDTO dto; + parseResult = Parser::Read(dto, data); + RawBuffer binaryData(data.data(), parseResult.processedSize()); + + if (binaryData.size() == dto.value<"size"_>()) { + transaction = CreateCreateLiquidityProviderTransaction(dto, binaryData); + } + + break; + } + case TransactionType::Manual_Rate_Change: + { + ManualRateChangeTransactionDTO dto; + parseResult = Parser::Read(dto, data); + RawBuffer binaryData(data.data(), parseResult.processedSize()); + + if (binaryData.size() == dto.value<"size"_>()) { + transaction = CreateManualRateChangeTransaction(dto, binaryData); + } + + break; + } case TransactionType::Data_Modification: { DataModificationTransactionDTO dto; @@ -900,6 +1320,30 @@ namespace xpx_chain_sdk { break; } + case TransactionType::Download_Payment: + { + DownloadPaymentTransactionDTO dto; + parseResult = Parser::Read(dto, data); + RawBuffer binaryData(data.data(), parseResult.processedSize()); + + if (binaryData.size() == dto.value<"size"_>()) { + transaction = CreateDownloadPaymentTransaction(dto, binaryData); + } + + break; + } + case TransactionType::Drive_Closure: + { + DriveClosureTransactionDTO dto; + parseResult = Parser::Read(dto, data); + RawBuffer binaryData(data.data(), parseResult.processedSize()); + + if (binaryData.size() == dto.value<"size"_>()) { + transaction = CreateDriveClosureTransaction(dto, binaryData); + } + + break; + } case TransactionType::Data_Modification_Approval: { DataModificationApprovalTransactionDTO dto; @@ -924,6 +1368,18 @@ namespace xpx_chain_sdk { break; } + case TransactionType::Finish_Download: + { + FinishDownloadTransactionDTO dto; + parseResult = Parser::Read(dto, data); + RawBuffer binaryData(data.data(), parseResult.processedSize()); + + if (binaryData.size() == dto.value<"size"_>()) { + transaction = CreateFinishDownloadTransaction(dto, binaryData); + } + + break; + } case TransactionType::Replicator_Onboarding: { ReplicatorOnboardingTransactionDTO dto; @@ -948,6 +1404,90 @@ namespace xpx_chain_sdk { break; } + case TransactionType::Deploy_Contract: + { + DeployContractTransactionDTO dto; + parseResult = Parser::Read(dto, data); + RawBuffer binaryData(data.data(), parseResult.processedSize()); + + if (binaryData.size() == dto.value<"size"_>()) { + transaction = CreateDeployContractTransaction(dto, binaryData); + } + + break; + } + case TransactionType::Manual_Call: + { + ManualCallTransactionDTO dto; + parseResult = Parser::Read(dto, data); + RawBuffer binaryData(data.data(), parseResult.processedSize()); + + if (binaryData.size() == dto.value<"size"_>()) { + transaction = CreateManualCallTransaction(dto, binaryData); + } + + break; + } + case TransactionType::Automatic_Executions_Payment: + { + AutomaticExecutionsPaymentTransactionDTO dto; + parseResult = Parser::Read(dto, data); + RawBuffer binaryData(data.data(), parseResult.processedSize()); + + if (binaryData.size() == dto.value<"size"_>()) { + transaction = CreateAutomaticExecutionsPaymentTransaction(dto, binaryData); + } + + break; + } + case TransactionType::Replicator_Offboarding: + { + ReplicatorOffboardingTransactionDTO dto; + parseResult = Parser::Read(dto, data); + RawBuffer binaryData(data.data(), parseResult.processedSize()); + + if (binaryData.size() == dto.value<"size"_>()) { + transaction = CreateReplicatorOffboardingTransaction(dto, binaryData); + } + + break; + } + case TransactionType::Stream_Start: + { + StreamStartTransactionDTO dto; + parseResult = Parser::Read(dto, data); + RawBuffer binaryData(data.data(), parseResult.processedSize()); + + if (binaryData.size() == dto.value<"size"_>()) { + transaction = CreateStreamStartTransaction(dto, binaryData); + } + + break; + } + case TransactionType::Stream_Finish: + { + StreamFinishTransactionDTO dto; + parseResult = Parser::Read(dto, data); + RawBuffer binaryData(data.data(), parseResult.processedSize()); + + if (binaryData.size() == dto.value<"size"_>()) { + transaction = CreateStreamFinishTransaction(dto, binaryData); + } + + break; + } + case TransactionType::Stream_Payment: + { + StreamPaymentTransactionDTO dto; + parseResult = Parser::Read(dto, data); + RawBuffer binaryData(data.data(), parseResult.processedSize()); + + if (binaryData.size() == dto.value<"size"_>()) { + transaction = CreateStreamPaymentTransaction(dto, binaryData); + } + + break; + } default: { break; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 1b101d2..f85e566 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.9) +cmake_minimum_required(VERSION 3.10) include_directories(${PROJECT_SOURCE_DIR}/include ${PROJECT_SOURCE_DIR}/src) diff --git a/tests/client/transaction_service_tests.cpp b/tests/client/transaction_service_tests.cpp index 00a8cd8..d438b91 100644 --- a/tests/client/transaction_service_tests.cpp +++ b/tests/client/transaction_service_tests.cpp @@ -5,6 +5,7 @@ **/ #include +#include #include "../config.h" namespace xpx_chain_sdk::tests { @@ -13,7 +14,32 @@ namespace xpx_chain_sdk::tests { ClientData clientData; auto client = xpx_chain_sdk::getClient(std::make_shared(getTestConfiguration())); - auto account = getTestAccount(clientData.privateKey); + + auto account = [privateKey = clientData.privateKey]() { + std::shared_ptr account = std::make_shared( + [privateKey](xpx_chain_sdk::PrivateKeySupplierReason reason, + xpx_chain_sdk::PrivateKeySupplierParam param) { + xpx_chain_sdk::Key key; + xpx_chain_sdk::ParseHexStringIntoContainer(privateKey.c_str(),privateKey.size(), key); + return xpx_chain_sdk::PrivateKey(key.data(), key.size()); + }); + return account; + }(); + + auto announceNewTransaction = [](const std::vector& binaryData, const std::string& hash) { + try { + EXPECT_TRUE(client->transactions()->announceNewTransaction(binaryData)); + + std::cout << "announced new transaction: " << hash << std::endl; + } + catch (std::exception &e) { + std::cout << e.what() << std::endl; + } + }; + + auto onError = [](auto errorCode) { + std::cout << "error code: " << errorCode << std::endl; + }; TEST(TEST_CLASS, getAnyTransactionInfo) { Address recipient(clientData.publicKeyContainer); @@ -32,28 +58,30 @@ namespace xpx_chain_sdk::tests { std::unique_lock lock(receivedMutex); std::condition_variable receivedCheck; - ConfirmedAddedNotifier notifier = [&transferTransaction, &receivedCheck, &isReceived](const TransactionNotification& notification) { + Notifier notifier([&transferTransaction, &receivedCheck, &isReceived, recipient](const notifierId& id, const TransactionNotification& notification) { if (notification.meta.hash == ToHex(transferTransaction->hash())) { EXPECT_EQ(ToHex(transferTransaction->hash()), notification.meta.hash); auto transactionInfo = client->transactions()->getAnyTransactionInfo(notification.meta.hash); - EXPECT_EQ(TransactionType::Transfer,transactionInfo.get()->type); + EXPECT_EQ(TransactionType::Transfer, transactionInfo.get()->type); + + client->notifications()->removeConfirmedAddedNotifiers(recipient, [](){}, onError, { id }); isReceived = true; receivedCheck.notify_all(); } - }; + }); - client->notifications()->addConfirmedAddedNotifiers(recipient, {notifier}); + auto onSuccess = [binaryData = transferTransaction->binary(), hash = ToHex(transferTransaction->hash())](){ + announceNewTransaction(binaryData, hash); + }; - EXPECT_TRUE(client->transactions()->announceNewTransaction(transferTransaction->binary())); + client->notifications()->addConfirmedAddedNotifiers(recipient, {notifier}, onSuccess, onError); receivedCheck.wait_for(lock, std::chrono::seconds(60), [&isReceived]() { return isReceived; }); - client->notifications()->removeConfirmedAddedNotifiers(recipient); - EXPECT_TRUE(isReceived); } @@ -74,28 +102,30 @@ namespace xpx_chain_sdk::tests { std::unique_lock lock(receivedMutex); std::condition_variable receivedCheck; - ConfirmedAddedNotifier notifier = [&transferTransaction, &receivedCheck, &isReceived](const TransactionNotification& notification) { + Notifier notifier([&transferTransaction, &receivedCheck, &isReceived, recipient](const notifierId& id, const TransactionNotification& notification) { if (notification.meta.hash == ToHex(transferTransaction->hash())) { EXPECT_EQ(ToHex(transferTransaction->hash()), notification.meta.hash); auto transactionInfo = client->transactions()->getTransactionInfo(TransactionGroup::Confirmed, notification.meta.hash); EXPECT_EQ(TransactionType::Transfer,transactionInfo.get()->type); + client->notifications()->removeConfirmedAddedNotifiers(recipient, [](){}, onError, { id }); + isReceived = true; receivedCheck.notify_all(); } - }; + }); - client->notifications()->addConfirmedAddedNotifiers(recipient, {notifier}); + auto onSuccess = [binaryData = transferTransaction->binary(), hash = ToHex(transferTransaction->hash())](){ + announceNewTransaction(binaryData, hash); + }; - EXPECT_TRUE(client->transactions()->announceNewTransaction(transferTransaction->binary())); + client->notifications()->addConfirmedAddedNotifiers(recipient, {notifier}, onSuccess, onError); receivedCheck.wait_for(lock, std::chrono::seconds(60), [&isReceived]() { return isReceived; }); - client->notifications()->removeConfirmedAddedNotifiers(recipient); - EXPECT_TRUE(isReceived); } @@ -116,28 +146,30 @@ namespace xpx_chain_sdk::tests { std::unique_lock lock(receivedMutex); std::condition_variable receivedCheck; - ConfirmedAddedNotifier notifier = [&transferTransaction, &receivedCheck, &isReceived](const TransactionNotification& notification) { + Notifier notifier([&transferTransaction, &receivedCheck, &isReceived, recipient](const notifierId& id, const TransactionNotification& notification) { if (notification.meta.hash == ToHex(transferTransaction->hash())) { EXPECT_EQ(ToHex(transferTransaction->hash()), notification.meta.hash); auto transactionsInfos = client->transactions()->getTransactionInfos(TransactionGroup::Confirmed, {notification.meta.hash}); EXPECT_EQ(1, transactionsInfos.transactions.size()); + client->notifications()->removeConfirmedAddedNotifiers(recipient, [](){}, onError, { id }); + isReceived = true; receivedCheck.notify_all(); } - }; + }); - client->notifications()->addConfirmedAddedNotifiers(recipient, {notifier}); + auto onSuccess = [binaryData = transferTransaction->binary(), hash = ToHex(transferTransaction->hash())](){ + announceNewTransaction(binaryData, hash); + }; - EXPECT_TRUE(client->transactions()->announceNewTransaction(transferTransaction->binary())); + client->notifications()->addConfirmedAddedNotifiers(recipient, {notifier}, onSuccess, onError); receivedCheck.wait_for(lock, std::chrono::seconds(60), [&isReceived]() { return isReceived; }); - client->notifications()->removeConfirmedAddedNotifiers(recipient); - EXPECT_TRUE(isReceived); } @@ -158,7 +190,7 @@ namespace xpx_chain_sdk::tests { std::unique_lock lock(receivedMutex); std::condition_variable receivedCheck; - ConfirmedAddedNotifier notifier = [&transferTransaction, &receivedCheck, &isReceived](const TransactionNotification& notification) { + Notifier notifier([&transferTransaction, &receivedCheck, &isReceived, recipient](const notifierId& id, const TransactionNotification& notification) { if (notification.meta.hash == ToHex(transferTransaction->hash())) { EXPECT_EQ(ToHex(transferTransaction->hash()), notification.meta.hash); @@ -166,21 +198,23 @@ namespace xpx_chain_sdk::tests { EXPECT_EQ(notification.meta.hash,transactionStatus.hash); EXPECT_EQ(TransactionGroup::Confirmed,TransactionService::transactionGroupFromString(transactionStatus.group)); + client->notifications()->removeConfirmedAddedNotifiers(recipient, [](){}, onError, { id }); + isReceived = true; receivedCheck.notify_all(); } - }; + }); - client->notifications()->addConfirmedAddedNotifiers(recipient, {notifier}); + auto onSuccess = [binaryData = transferTransaction->binary(), hash = ToHex(transferTransaction->hash())](){ + announceNewTransaction(binaryData, hash); + }; - EXPECT_TRUE(client->transactions()->announceNewTransaction(transferTransaction->binary())); + client->notifications()->addConfirmedAddedNotifiers(recipient, {notifier}, onSuccess, onError); receivedCheck.wait_for(lock, std::chrono::seconds(60), [&isReceived]() { return isReceived; }); - client->notifications()->removeConfirmedAddedNotifiers(recipient); - EXPECT_TRUE(isReceived); } @@ -201,7 +235,7 @@ namespace xpx_chain_sdk::tests { std::unique_lock lock(receivedMutex); std::condition_variable receivedCheck; - ConfirmedAddedNotifier notifier = [&transferTransaction, &receivedCheck, &isReceived](const TransactionNotification& notification) { + Notifier notifier([&transferTransaction, &receivedCheck, &isReceived, recipient](const notifierId& id, const TransactionNotification& notification) { if (notification.meta.hash == ToHex(transferTransaction->hash())) { EXPECT_EQ(ToHex(transferTransaction->hash()), notification.meta.hash); @@ -210,21 +244,23 @@ namespace xpx_chain_sdk::tests { EXPECT_EQ(notification.meta.hash,transactionStatuses.statuses[0].hash); EXPECT_EQ(TransactionGroup::Confirmed,TransactionService::transactionGroupFromString(transactionStatuses.statuses[0].group)); + client->notifications()->removeConfirmedAddedNotifiers(recipient, [](){}, onError, { id }); + isReceived = true; receivedCheck.notify_all(); } - }; + }); - client->notifications()->addConfirmedAddedNotifiers(recipient, {notifier}); + auto onSuccess = [binaryData = transferTransaction->binary(), hash = ToHex(transferTransaction->hash())](){ + announceNewTransaction(binaryData, hash); + }; - EXPECT_TRUE(client->transactions()->announceNewTransaction(transferTransaction->binary())); + client->notifications()->addConfirmedAddedNotifiers(recipient, {notifier}, onSuccess, onError); receivedCheck.wait_for(lock, std::chrono::seconds(60), [&isReceived]() { return isReceived; }); - client->notifications()->removeConfirmedAddedNotifiers(recipient); - EXPECT_TRUE(isReceived); } diff --git a/tests/config.h b/tests/config.h index 949087f..5f64a66 100644 --- a/tests/config.h +++ b/tests/config.h @@ -29,20 +29,4 @@ namespace xpx_chain_sdk::tests { return config; } - - static std::shared_ptr getTestAccount(const std::string &privateKey) { - std::shared_ptr account = std::make_shared( - [&privateKey](xpx_chain_sdk::PrivateKeySupplierReason reason, - xpx_chain_sdk::PrivateKeySupplierParam param) { - xpx_chain_sdk::Key key; - if (reason == xpx_chain_sdk::PrivateKeySupplierReason::Transaction_Signing) { - xpx_chain_sdk::ParseHexStringIntoContainer(privateKey.c_str(), - privateKey.size(), key); - } - - return xpx_chain_sdk::PrivateKey(key.data(), key.size()); - }); - - return account; - } }