### Install dependencies using Poetry Source: https://github.com/openhive-network/wax/blob/develop/examples/python/README.md Installs the necessary dependencies for the Python wax library using Poetry. This command ensures that all required packages are available for running the examples. ```bash poetry install ``` -------------------------------- ### Setup and Test Wax Project Source: https://github.com/openhive-network/wax/blob/develop/ts/README.md This section provides bash commands for setting up and testing the Wax project. It includes cloning submodules, installing dependencies with pnpm, building the project, running tests, and executing examples. ```Bash git submodule update --init --progress --depth=1 # Clone HIVE repository containing proto definitions pnpm install npm run build npm run build:test npm run test npm run examples ``` -------------------------------- ### Run a Python example script Source: https://github.com/openhive-network/wax/blob/develop/examples/python/README.md Executes a specified Python example script. This command demonstrates how to run the example scripts provided with the Python wax library, such as 'create_and_sign_transaction.py'. ```bash python create_and_sign_transaction.py ``` -------------------------------- ### Navigate to the examples directory Source: https://github.com/openhive-network/wax/blob/develop/examples/python/README.md Changes the current directory to the 'examples' directory. This step is necessary to execute the example scripts provided with the Python wax library. ```bash cd examples ``` -------------------------------- ### Install Protobuf Compiler (Bash) Source: https://github.com/openhive-network/wax/blob/develop/README.md Installs the protobuf compiler using the apt package manager. This is a prerequisite for building the Wax project. ```bash apt install protobuf-compiler ``` -------------------------------- ### Developer Installation of Wax (Bash) Source: https://github.com/openhive-network/wax/blob/develop/README.md Installs the Wax package using a dedicated script. It's recommended to create a virtual environment before running this script. ```bash ./python/scripts/install_wax.sh ``` -------------------------------- ### Install Poetry (Bash) Source: https://github.com/openhive-network/wax/blob/develop/README.md Installs the Poetry Python dependency management tool. This command downloads and executes the official installation script for Poetry version 2.1.3. ```bash curl -sSL https://install.python-poetry.org | python3 - --version 2.1.3 ``` -------------------------------- ### Run Python Examples (Bash) Source: https://github.com/openhive-network/wax/blob/develop/README.md Executes the Python examples provided within the Wax project. This script is located in the examples/python directory. ```bash ./examples/python/run_example.sh ``` -------------------------------- ### TypeScript Wax Protobuf Transaction Signing with Beekeeper Source: https://github.com/openhive-network/wax/blob/develop/examples/ts/html/README.md Shows an example of protobuf transaction creation and signing using the wax library in cooperation with the Beekeeper package. This facilitates secure transaction signing. ```TypeScript /* * In this file, you can see example protobuf transaction creation along with the example cooperation between wax and beekeeper packages in order to sign the transaction */ // Example usage would involve creating a transaction, serializing it to protobuf, and then signing it using Beekeeper. // For instance: // import { Transaction } from './generated/transaction_pb'; // import { Wax } from '@wax/wax'; // import { Beekeeper } from '@wax/beekeeper'; // // async function signTransaction() { // const waxInstance = new Wax(); // const beekeeperInstance = new Beekeeper(); // // // Create a transaction object // const transaction = new Transaction(); // // ... populate transaction details ... // // const serializedTransaction = waxInstance.serialize(transaction); // const signedTransaction = await beekeeperInstance.signTransaction(serializedTransaction); // console.log('Signed Transaction:', signedTransaction); // } ``` -------------------------------- ### Sign Protobuf Transaction with Wax and Beekeeper Source: https://github.com/openhive-network/wax/blob/develop/examples/ts/html/assets/proto_sign_transaction.example.html This snippet shows the complete process of signing a protobuf transaction. It initializes Beekeeper, creates a wallet session, imports a private key, and then uses Wax to create and sign the transaction. The example logs the resulting signature and transaction ID. ```javascript import { createWaxFoundation, transaction } from '@hiveio/wax'; import beekeeperFactory from '@hiveio/beekeeper'; const txId = '8e78947614be92e77f7db82237e523bdbd7a907b'; const protoTx = transaction.create({ ref_block_num: 19260, ref_block_prefix: 2140466769, expiration: "2016-09-15T19:47:33", operations: [ { vote_operation: { voter: "taoteh1221", author: "ozchartart", permlink: "usdsteem-btc-daily-poloniex-bittrex-technical-analysis-market-report-update-46-glass-half-full-but-the-bottle-s-left-empty-sept", weight: 10000 } } ], extensions: [] }); const OUR_MAINNET_INITMINER_PRIVATE_KEY_DO_NOT_SHARE = "5JNHfZYKGaomSFvd4NUdQ9qMcEAC43kujbfjueTHpVapX1Kzq2n"; // :) const walletName = "pear"; (async() => { // Initialize beekeeper wallet and get public key for signing const beekeeper = await beekeeperFactory(); const session = beekeeper.createSession('pear'); const { wallet } = await session.createWallet(walletName); await wallet.importKey(OUR_MAINNET_INITMINER_PRIVATE_KEY_DO_NOT_SHARE); const [ publicKey ] = wallet.getPublicKeys(); // Create wax base const wax = await createWaxFoundation(); const tx = wax.createTransactionFromProto(protoTx); const signed = tx.sign(wallet, publicKey); console.log(`Your signature for transmitting: "${tx.transaction.signatures[0]}"`); console.log(`Transaction id: ${tx.id} (matches the real one: ${String(tx.id === txId)})`); window.exampleFinished = true; // Optional - just for our test purposes })(); ``` -------------------------------- ### Install Wax with Development Versions Source: https://github.com/openhive-network/wax/blob/develop/ts/README.md This snippet shows how to install the Wax library using npm, including instructions for setting the `@hiveio` scope to use the GitLab registry for development versions. It requires Node.js 20.11 or higher. ```bash echo @hiveio:registry=https://gitlab.syncad.com/api/v4/groups/136/-/packages/npm/ >> .npmrc npm install @hiveio/wax ``` -------------------------------- ### Hive Transaction Signing with Multiple Wallets Source: https://github.com/openhive-network/wax/blob/develop/examples/ts/signature-extension/test/index.html This snippet demonstrates the core logic for creating and signing a Hive transaction using various wallet providers. It includes setup for Hive Keychain, Peak Vault, MetaMask, Beekeeper, and HBAuth, along with functions to initiate the signing process and verify the transaction's authority. ```javascript import { createHiveChain } from "@hiveio/wax"; import { prepareTestingEnvironemnt, voteData } from "../common-data"; import KeychainProvider from "@hiveio/wax-signers-keychain"; import PeakVaultProvider from "@hiveio/wax-signers-peakvault"; import MetaMaskProvider from "@hiveio/wax-signers-metamask"; import BeekeeperProvider from "@hiveio/wax-signers-beekeeper"; import HBAuthProvider from "@hiveio/wax-signers-hb-auth"; import { OfflineClient } from "@hiveio/hb-auth"; const txResult = document.getElementById('tx-result'); const operatingPrivateKeyPlaceholder = document.getElementById('operating-private-key'); const keyMatchingPlaceholder = document.getElementById('key-matching-result'); (async()=> { const testEnv = await prepareTestingEnvironemnt(); const accountName = testEnv.accountName; operatingPrivateKeyPlaceholder.textContent = `${accountName}@${testEnv.role} private key to be imported to wallets: ${testEnv.privateKey}`; const chain = testEnv.configuredChain; const createTransaction = async () => { txResult.textContent = 'Signing...'; const tx = await chain.createTransaction(); tx.pushOperation({ vote_operation: voteData }); console.log(tx.toApi()); console.log(`Sig digest: ${tx.sigDigest}`); console.log(`Legacy Sig digest: ${tx.legacy_sigDigest}`); return tx; }; const verifySignature = async (tx) => { try { const apiJson = tx.toApi(); console.log('Transaction:', apiJson); const hf26SerializationMatch = tx.signatureKeys[0] === testEnv.publicKey; const legacySerializationMatch = tx.legacy_signatureKeys[0] === testEnv.publicKey; if(hf26SerializationMatch || legacySerializationMatch) { const verifyAuthorityResult = await chain.api.database_api.verify_authority({trx: tx.toApiJson(), pack: legacySerializationMatch? 'legacy' : 'hf26'}); keyMatchingPlaceholder.textContent = `Decoded and signing key match. Remote endpoint ${verifyAuthorityResult.valid? "accepted" : "REJECTED"} transaction authority. Transaction has been signed using: ${hf26SerializationMatch? 'HF26' : 'Legacy'} serialization form`; } else { keyMatchingPlaceholder.textContent = `Error: Keys decoded from signature: ${tx.signatureKeys[0]}, ${tx.legacy_signatureKeys[0]} DO NOT MATCH signer key: ${testEnv.publicKey}`; } txResult.textContent = apiJson; } catch (error) { console.error(error); txResult.textContent = `Verify authority faiure. Error: ${error.message}`; } } const sign = async (provider) => { try { console.log("Atttempting to create & sign transaction..."); const tx = await createTransaction(); await tx.sign(provider); await verifySignature(tx); } catch (error) { console.error('Error signing transaction:', error); txResult.textContent = `Error: ${error.message}`; } }; const keychainProvider = KeychainProvider.for(accountName, testEnv.role); window.useKeychain = () => void sign(keychainProvider); let beekeeperProvider; try { beekeeperProvider = await BeekeeperProvider.for(testEnv.preparedBeekeeperWallet, testEnv.publicKey); } catch (error) { console.error('Beekeeper provider not available', error); } const hbAuthClient = new OfflineClient({ chainId: testEnv.configuredChain.chainId, node: testEnv.configuredChain.endpointUrl, workerUrl: './worker.js', sessionTimeout: 900 }); const hbAuthProvider = await HBAuthProvider.for(hbAuthClient, accountName, testEnv.role); try { await hbAuthClient.initialize(); const registeredUser = await hbAuthClient.getRegisteredUserByUsername(accountName); if (registeredUser) await hbAuthClient.authenticate(accountName, "password", testEnv.role); else await hbAuthClient.register(accountName, "password", testEnv.privateKey, testEnv.role); } catch (error) { console.error('Could not initialize hb-auth', error); } const peakVaultProvider = PeakVaultProvider.for(accountName, testEnv.role); let metaMaskProvider; try { metaMaskProvider = await MetaMaskProvider.for(0); await metaMaskProvider.installSnap(); } catch (error) { console.error('Metamask provider not available', error); } window.usePeakVault = () => void sign(peakVaultProvider); window.useMetaMask = () => void sign(metaMaskProvider); window.useBeekeeper = () => void sign(beekeeperProvider); window.useHbAuth = () => void sign(hbAuthProvider); })(); ``` -------------------------------- ### Install Wax Python Package with Pip (Bash) Source: https://github.com/openhive-network/wax/blob/develop/README.md Installs the Wax Python module using pip, specifying custom index URLs and the path to the built wheel file. Replace CREATED-WAX-WHEEL.whl with the actual filename. ```bash python3 -m pip install --index-url $FIRST_INDEX --extra-index-url $SECOND_INDEX --extra-index-url $THIRD_INDEX ./dist/CREATED-WAX-WHEEL.whl ``` -------------------------------- ### Install Project Dependencies with Poetry (Bash) Source: https://github.com/openhive-network/wax/blob/develop/README.md Installs project dependencies using Poetry, excluding the root project package. This is typically done after setting a specific Python interpreter. ```bash poetry -C . install --no-root ``` -------------------------------- ### TypeScript Wax Visitor Example Source: https://github.com/openhive-network/wax/blob/develop/examples/ts/html/README.md Demonstrates creating and using custom visitors for specific operation types within the wax library. This is useful for abstracting and handling different operation patterns. ```TypeScript /* * In this file, you can see how to create and use your custom visitor for given operation types. */ // Example usage would involve defining a visitor class and applying it to operations. // For instance: // class MyVisitor implements Visitor { // visitOperation(op: Operation) { // console.log(`Visiting operation: ${op.type}`); // } // } // const visitor = new MyVisitor(); // operationHandler.accept(visitor); ``` -------------------------------- ### Create and Activate Python Virtual Environment (Bash) Source: https://github.com/openhive-network/wax/blob/develop/README.md Creates a Python virtual environment named 'venv' and activates it. This is a recommended step before installing the Wax package. ```bash python3 -m venv venv source ./venv/bin/activate ``` -------------------------------- ### Install WAX Python Extension Source: https://github.com/openhive-network/wax/blob/develop/python/CMakeLists.txt This CMake INSTALL command specifies how the 'cpp_python_bridge' target should be installed. It defines the destination directories for runtime, library, and archive files. ```cmake INSTALL(TARGETS "cpp_python_bridge" RUNTIME DESTINATION bin LIBRARY DESTINATION lib ARCHIVE DESTINATION lib ) ``` -------------------------------- ### Set WAX_SKIP_BUILD for Developer Installation (Bash) Source: https://github.com/openhive-network/wax/blob/develop/README.md Sets the WAX_SKIP_BUILD environment variable to 'true' to skip the package build process during developer installation. If the package hasn't been built, the installation script will handle it. ```bash export WAX_SKIP_BUILD=true ``` -------------------------------- ### Build Wax Package in Place for Debugging (Bash) Source: https://github.com/openhive-network/wax/blob/develop/README.md Builds the Wax package in place with debugging enabled. This command uses a specific Python interpreter and setup script. ```bash WAX_DEBUG=1 python3.12d setup.py build_ext --inplace ``` -------------------------------- ### Import Wax in Vite (React) Source: https://github.com/openhive-network/wax/blob/develop/examples/ts/react-vite/README.md Demonstrates the correct way to import the Wax library when using Vite with React. It highlights the need to import the dedicated Vite bundle to ensure compatibility and proper functionality. ```javascript import * as wax from '@hiveio/wax/vite'; ``` -------------------------------- ### Wax Authorization with Keychain/PeakVault Source: https://github.com/openhive-network/wax/blob/develop/examples/ts/signature-extension/README.md This example demonstrates how to implement third-party app authorization using Wax, specifically with browser extensions like Keychain or PeakVault. It requires manual user authorization via OAuth and specific configuration of wallets with a custom chain ID and API endpoint. ```javascript import { KeychainSigner } from '@wax-js/wax'; // Example usage (assuming you have a user logged in and a Wax instance) async function authorizeWax() { const wax = new Wax({ // Wax configuration options }); try { const result = await wax.login({ // Login options, e.g., permissions }); console.log('Login successful:', result); // Example of signing a transaction after authorization const transaction = { // transaction details }; const signedTransaction = await wax.api.transact(transaction, { // transaction options }); console.log('Transaction signed:', signedTransaction); } catch (error) { console.error('Authorization or transaction failed:', error); } } ``` -------------------------------- ### CMake Project Setup for Wax WASM Source: https://github.com/openhive-network/wax/blob/develop/ts/wasm/src/CMakeLists.txt This snippet sets up the basic CMake configuration for the Wax WASM project, including minimum CMake version, C++ and C standards, and executable suffixes. It also defines root paths for Wax and Hive projects and includes necessary CMake modules. ```CMake cmake_minimum_required( VERSION 3.22.1 ) set( CMAKE_CXX_STANDARD 17 ) set( CMAKE_CXX_EXTENSIONS OFF ) set( CMAKE_CXX_STANDARD_REQUIRED ON ) set( CMAKE_C_STANDARD 99 ) set( CMAKE_C_STANDARD_REQUIRED ON ) set( CMAKE_EXECUTABLE_SUFFIX "" ) set( WAX_ROOT_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../.." ) SET( HIVE_ROOT_PATH "${WAX_ROOT_PATH}/hive" ) include( ${HIVE_ROOT_PATH}/cmake/hive_targets.cmake ) include( ${HIVE_ROOT_PATH}/programs/beekeeper/beekeeper_wasm/cmake/wasm_project.cmake ) ``` -------------------------------- ### Implement OperationVisitor for Hive Transactions Source: https://github.com/openhive-network/wax/blob/develop/examples/ts/html/assets/visitor.example.html This JavaScript code defines a custom visitor class that extends the OperationVisitor from '@hiveio/wax'. It demonstrates how to implement methods for specific operations like 'comment_operation', 'vote_operation', and 'recurrent_transfer_operation' to process transaction data. ```javascript import { OperationVisitor, comment, vote, transaction, recurrent_transfer } from '@hiveio/wax'; class MyVisitor extends OperationVisitor { comment_operation(op) { return op.author === "alice"; } // This should be never visited in our example limit_order_cancel_operation(op) { return op.orderid === Number.POSITIVE_INFINITY; } vote_operation(op) { return op.voter === "bob"; } recurrent_transfer_operation(op) { // Example json API transforming const jsonData = recurrent_transfer.toJSON(op); return jsonData.to === op.to && jsonData.from === op.from; } } const tx = transaction.create({ ref_block_num: 0, ref_block_prefix: 0, expiration: "1970-01-01T01:00:00", extensions: [], operations: [ { vote_operation: vote.create({ author: "alice", voter: "bob", permlink: "/", weight: 1, }), }, { comment_operation: comment.create({ parent_permlink: "/", parent_author: "", author: "alice", permlink: "/", title: "Best comment", body: "comment", json_metadata: "{}" }) }, { vote_operation: vote.create({ voter: "bob", author: "alice", permlink: "/", weight: 1 }) }, { limit_order_cancel_operation: undefined }, { recurrent_transfer_operation: recurrent_transfer.create({ from: "alice", to: "harry", amount: { nai: "@@000000021", precision: 3, amount: "10" }, memo: "it is only memo", recurrence: 1, executions: 3, extensions: [ { recurrent_transfer_pair_id: { pair_id: 0 } }, { void_t: {} } ] }) } ] }); const visitor = new MyVisitor(); for(const op of tx.operations) { // Undefined on no supported visitor or given operation is undefined const returnData = visitor.accept(op); if(returnData === false) throw new Error("Visitor should return true for supported operations"); } window.exampleFinished = true; // Optional - just for our test purposes ``` -------------------------------- ### TypeScript Wax Protobuf API Response Validation Source: https://github.com/openhive-network/wax/blob/develop/examples/ts/html/README.md Illustrates the usage of the protobuf wax module for data transformation and validation of Hive API responses. This ensures data integrity and adherence to expected formats. ```TypeScript /* * In this file, you can see example protobuf wax module usage along with the data transformation and validation */ // Example usage would involve importing protobuf definitions and using wax to parse and validate API responses. // For instance: // import { ApiResponse } from './generated/api_response_pb'; // import { Wax } from '@wax/wax'; // // async function validateResponse(response: Response) { // const waxInstance = new Wax(); // const buffer = await response.arrayBuffer(); // const apiResponse = waxInstance.deserialize(buffer, ApiResponse); // // Perform validation checks on apiResponse // console.log('API Response validated:', apiResponse.toObject()); // } ``` -------------------------------- ### Set PyPI Index Environment Variables (Bash) Source: https://github.com/openhive-network/wax/blob/develop/README.md Sets environment variables for custom PyPI index URLs. These are used during the installation of the Wax module via pip. ```bash export FIRST_INDEX="https://gitlab.syncad.com/api/v4/projects/362/packages/pypi/simple" export SECOND_INDEX="https://gitlab.syncad.com/api/v4/projects/434/packages/pypi/simple" export THIRD_INDEX="https://gitlab.syncad.com/api/v4/projects/198/packages/pypi/simple" ``` -------------------------------- ### Generate Configuration TypeScript File Source: https://github.com/openhive-network/wax/blob/develop/ts/wasm/src/CMakeLists.txt This CMake snippet generates a TypeScript configuration file based on a template and the project's configuration. It defines the input paths for the configuration header and template, and the output path for the generated TypeScript file, then installs it. ```CMake include("${CMAKE_CURRENT_SOURCE_DIR}/../../../hive/libraries/protocol/get_config.d/generate_get_config.cmake") generate_get_config( "${CMAKE_CURRENT_SOURCE_DIR}/../../../hive/libraries/protocol/include/hive/protocol/config.hpp" # path to config.hpp "${CMAKE_CURRENT_SOURCE_DIR}/get_config.d/config.ts.in" # path to get_config template file "${CMAKE_CURRENT_BINARY_DIR}/config.ts" # output path ) INSTALL( FILES "${CMAKE_CURRENT_BINARY_DIR}/config.ts" COMPONENT "wax_config_ts" DESTINATION . ) ``` -------------------------------- ### Add Custom Operations to Transaction Source: https://github.com/openhive-network/wax/blob/develop/ts/README.md This TypeScript example shows how to add custom operations, specifically a 'follow' operation, to a transaction using the Wax library. It demonstrates creating a transaction with a specific block reference and time, then pushing a `FollowOperation` and authorizing it. ```typescript import { createWaxFoundation, FollowOperation } from '@hiveio/wax'; const wax = await createWaxFoundation(); const tx = wax.createTransactionWithTaPoS('04c507a8c7fe5be96be64ce7c86855e1806cbde3', '2023-11-09T21:51:27'); tx.pushOperation(new FollowOperation().followBlog("initminer", "gtg").authorize("intiminer")); console.info(tx.toApi()); // Print the transaction in the API form ``` -------------------------------- ### Build Wax Python Package (Bash) Source: https://github.com/openhive-network/wax/blob/develop/README.md Builds the Wax Python package from the root project directory. This script generates a wheel file in the ./dist directory. ```bash ./python/scripts/build_wax.sh ``` -------------------------------- ### Wax Transaction Signing with Beekeeper Source: https://github.com/openhive-network/wax/blob/develop/ts/packages/signers-beekeeper/README.md Demonstrates how to use the BeekeeperProvider with the @hiveio/wax library to create, sign, and broadcast a Hive transaction. It shows the import of necessary modules, initialization of the Hive chain, creation of a Beekeeper provider, pushing a vote operation, signing the transaction with the provider, and finally broadcasting the transaction. ```typescript import { createHiveChain } from "@hiveio/wax"; import BeekeeperProvider from "@hiveio/wax-signers-beekeeper"; const chain = await createHiveChain(); const provider = BeekeeperProvider.for(myWallet, "myaccount", "active", chain); // Create a transaction using the Wax Hive chain instance const tx = await chain.createTransaction(); // Perform some operations, e.g. push the vote operation: tx.pushOperation({ vote: { voter: "alice", author: "bob", permlink: "example-post", weight: 10000 } }); // Wait for the keychain to sign the transaction await tx.sign(provider); // broadcast the transaction await chain.broadcast(tx); ``` -------------------------------- ### Sign Hive Transaction with MetaMask Source: https://github.com/openhive-network/wax/blob/develop/ts/packages/signers-metamask/README.md Demonstrates how to create a Hive chain instance, initialize the MetaMask provider, construct a transaction with a vote operation, sign it using MetaMask, and broadcast it. ```typescript import { createHiveChain } from "@hiveio/wax"; import MetaMaskProvider from "@hiveio/wax-signers-metamask"; const chain = await createHiveChain(); const provider = MetaMaskProvider.for(0); // Create a transaction using the Wax Hive chain instance const tx = await chain.createTransaction(); // Perform some operations, e.g. push the vote operation: tx.pushOperation({ vote: { voter: "alice", author: "bob", permlink: "example-post", weight: 10000 } }); // Wait for the keychain to sign the transaction await tx.sign(provider); // broadcast the transaction await chain.broadcast(tx); ``` -------------------------------- ### Configure WAX Project with CMake Source: https://github.com/openhive-network/wax/blob/develop/python/CMakeLists.txt This snippet sets up the basic CMake project for WAX, including the minimum required version, C++ standard, and compiler extensions. It also configures build verbosity and export of compile commands. ```cmake cmake_minimum_required(VERSION 3.22.1) project(wax) SET(CMAKE_POSITION_INDEPENDENT_CODE ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_STANDARD_REQUIRED ON) #set(CMAKE_CXX_FLAGS -g) set(CMAKE_EXPORT_COMPILE_COMMANDS "ON") set(CMAKE_VERBOSE_MAKEFILE "ON") ``` -------------------------------- ### Create and Broadcast Transaction with Wax Source: https://github.com/openhive-network/wax/blob/develop/ts/README.md Demonstrates how to create a transaction, add operations like voting, sign it with a wallet, and broadcast it to the network using the `network_broadcast_api`. ```javascript import { createHiveChain } from '@hiveio/wax'; import beekeeperFactory from '@hiveio/beekeeper'; const bk = await beekeeperFactory(); const chain = await createHiveChain(); // Initialize the wallet const session = bk.createSession("salt"); const { wallet } = await session.createWallet("w0"); const publicKey = await wallet.importKey('5JkFnXrLM2ap9t3AmAxBJvQHF7xSKtnTrCTginQCkhzU5S7ecPT'); // Create transaction const tx = await chain.createTransaction(); // Add operations tx.pushOperation({ vote: { voter: "otom", author: "c0ff33a", permlink: "ewxhnjbj", weight: 2200 } }).sign(wallet, publicKey); // Broadcast await chain.broadcast(tx); ``` -------------------------------- ### Sign Hive Transaction with Keychain Source: https://github.com/openhive-network/wax/blob/develop/ts/packages/signers-keychain/README.md Demonstrates how to use the @hiveio/wax-signers-keychain library to create and sign a Hive transaction using the Keychain browser extension. It involves initializing the Wax chain, creating a transaction, pushing a vote operation, signing with the Keychain provider, and broadcasting the transaction. ```ts import { createHiveChain } from "@hiveio/wax"; import KeychainProvider from "@hiveio/wax-signers-keychain"; const chain = await createHiveChain(); const provider = KeychainProvider.for("myaccount", "active"); // Create a transaction using the Wax Hive chain instance const tx = await chain.createTransaction(); // Perform some operations, e.g. push the vote operation: tx.pushOperation({ vote: { voter: "alice", author: "bob", permlink: "example-post", weight: 10000 } }); // Wait for the keychain to sign the transaction await tx.sign(provider); // broadcast the transaction await chain.broadcast(tx); ``` -------------------------------- ### Copy Header File for WAX Source: https://github.com/openhive-network/wax/blob/develop/python/CMakeLists.txt This command copies the 'cpython_interface.hpp' header file from the source directory to the binary directory, making it available during the build process. ```cmake file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/cpython_interface.hpp DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) ``` -------------------------------- ### Define Boost Components for WAX Source: https://github.com/openhive-network/wax/blob/develop/python/CMakeLists.txt This section lists the Boost components required for the WAX project. These components are appended to a list that will be used during the build process. ```cmake SET( BOOST_COMPONENTS ) LIST( APPEND BOOST_COMPONENTS # atomic chrono context coroutine # date_time filesystem # iostreams # locale # regex system thread # program_options unit_test_framework ) ``` -------------------------------- ### Sign Hive Transaction with HBAuth Source: https://github.com/openhive-network/wax/blob/develop/ts/packages/signers-hb-auth/README.md Demonstrates how to use the HBAuthProvider to sign a Hive transaction. It involves creating a Hive chain instance, initializing the HBAuth provider, creating a transaction, pushing operations, signing with the provider, and broadcasting the transaction. ```typescript import { createHiveChain } from "@hiveio/wax"; import HBAuthProvider from "@hiveio/wax-signers-hb-auth"; const chain = await createHiveChain(); const provider = HBAuthProvider.for(hbAuthClient, "gtg", "posting"); // Create a transaction using the Wax Hive chain instance const tx = await chain.createTransaction(); // Perform some operations, e.g. push the vote operation: tx.pushOperation({ vote: { voter: "alice", author: "bob", permlink: "example-post", weight: 10000 } }); // Wait for the keychain to sign the transaction await tx.sign(provider); // broadcast the transaction await chain.broadcast(tx); ``` -------------------------------- ### Importing @hiveio/wax in Vite for Nuxt Source: https://github.com/openhive-network/wax/blob/develop/examples/ts/nuxt-app/README.md When using @hiveio/wax within a Vite-enabled Nuxt project, it's crucial to import the dedicated Vite bundle. This ensures compatibility and proper functionality. The import should be done using the specific path `@hiveio/wax/vite`. ```javascript import { Wax } from '@hiveio/wax/vite'; ``` -------------------------------- ### Generate TypeScript from ProtoBuf Definitions Source: https://github.com/openhive-network/wax/blob/develop/ts/ARCHITECTURE.md This step involves using the `protoc` compiler with the `ts-proto` extension to transform Hive protocol Protocol Buffer definition files (.proto) into TypeScript code. The generated files contain definitions for blockchain operations and are placed in the `wasm/lib/proto` directory. ```bash protoc --plugin=./node_modules/.bin/protoc-gen-ts_proto --ts_proto_out=wasm/lib/proto ../hive/libraries/protocol/proto ``` -------------------------------- ### Sign Hive Transaction with Peak Vault Source: https://github.com/openhive-network/wax/blob/develop/ts/packages/signers-peakvault/README.md Demonstrates how to use the PeakVaultProvider to sign a Hive transaction. It initializes the Hive chain, creates a transaction, adds a vote operation, signs the transaction using the Peak Vault provider, and then broadcasts the transaction. ```typescript import { createHiveChain } from "@hiveio/wax"; import PeakVaultProvider from "@hiveio/wax-signers-peakvault"; const chain = await createHiveChain(); const provider = PeakVaultProvider.for("myaccount", "active"); // Create a transaction using the Wax Hive chain instance const tx = await chain.createTransaction(); // Perform some operations, e.g. push the vote operation: tx.pushOperation({ vote: { voter: "alice", author: "bob", permlink: "example-post", weight: 10000 } }); // Wait for the keychain to sign the transaction await tx.sign(provider); // broadcast the transaction await chain.broadcast(tx); ``` -------------------------------- ### Set Debug Python Interpreter with Poetry (Bash) Source: https://github.com/openhive-network/wax/blob/develop/README.md Configures Poetry to use a specific debug version of the Python interpreter (e.g., python3.12d) for the virtual environment. Assumes the current directory contains the pyproject.toml file. ```bash poetry -C . env use python3.12d ``` -------------------------------- ### Asynchronous Wax Import in Nuxt Source: https://github.com/openhive-network/wax/blob/develop/examples/ts/nuxt-app/README.md To avoid potential issues with server-side rendering or initial load performance in Nuxt, Wax should be imported asynchronously. This can be achieved using lifecycle hooks like `onBeforeMount` or within your state management solution (e.g., Vuex store). ```javascript // Example using onBeforeMount hook in Vue 3 import { onBeforeMount } from 'vue'; export default { setup() { onBeforeMount(async () => { const { Wax } = await import('@hiveio/wax/vite'); const wax = new Wax(config); // Initialize Wax or perform other actions }); } } ``` -------------------------------- ### Link Options for 'cpp_python_bridge' Source: https://github.com/openhive-network/wax/blob/develop/python/CMakeLists.txt This command sets specific link options for the 'cpp_python_bridge' target, including static linking for libgcc and libstdc++. ```cmake target_link_options("cpp_python_bridge" PRIVATE -static-libgcc -static-libstdc++) ``` -------------------------------- ### Run Test Under Debugger (Bash) Source: https://github.com/openhive-network/wax/blob/develop/README.md Executes a Python test script under a debugger (cygdb). This command specifies the debugger executable, the Python interpreter, and the test script path. ```bash cygdb . -- --args python3.12d ./test_pure_tx.py ``` -------------------------------- ### Set Include Directories for 'cpp_python_bridge' Source: https://github.com/openhive-network/wax/blob/develop/python/CMakeLists.txt This snippet configures the include paths for the 'cpp_python_bridge' target. It includes directories from the current source, parent directories, the core directory, and the Hive chain library. ```cmake target_include_directories("cpp_python_bridge" PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/../" "${CMAKE_CURRENT_SOURCE_DIR}/../core" "${HIVE_ROOT_PATH}/libraries/chain/include" "${GENERATED_ASSERT_ID_DIR}" ) ``` -------------------------------- ### Custom Data Formatting with Wax Source: https://github.com/openhive-network/wax/blob/develop/ts/README.md Shows how to use custom formatters to output data in a specified format. This involves defining a class with methods decorated by `@WaxFormattable` and extending the chain's formatter. ```typescript import { createHiveChain, IWaxBaseInterface, IFormatFunctionArguments, WaxFormattable } from '@hiveio/wax'; const chain = await createHiveChain(); const data = { myCustomProp: 12542 }; class MyFormatters { // Define custom formatters class // This line is optional, you can omit providing the constructor and default contstructor will be used instead // It is to show that you can gain access to the wax interface easily inside the formatters public constructor( private readonly wax: IWaxBaseInterface ) {} @WaxFormattable() // Match this method as `myCustomProp` custom formatter public myCustomProp({ source }: IFormatFunctionArguments): string | void { if(Math.random() > 0.5) // Happy debugging :) return; // No replacement will take place here - that's reason why return type is defined as string and void union console.info(`You are using wax version: ${this.wax.getVersion()}`); return source.myCustomProp.toString(); // return string } } const formatter = chain.formatter.extend(MyFormatters); // Creates and returns new extended formatter object console.info(formatter.waxify`${data}`); // Print formatted data ``` -------------------------------- ### Create and Sign a Hive Transaction Source: https://github.com/openhive-network/wax/blob/develop/ts/README.md This JavaScript code illustrates how to create, validate, and sign a transaction for the Hive chain using the Wax library. It involves initializing the Hive chain interface, importing a wallet key, adding a vote operation, and then signing the transaction. ```javascript import { createHiveChain } from '@hiveio/wax'; import beekeeperFactory from '@hiveio/beekeeper'; const bk = await beekeeperFactory(); const chain = await createHiveChain(); // Initialize the wallet const session = bk.createSession("salt"); const { wallet } = await session.createWallet("w0"); const publicKey = await wallet.importKey('5JkFnXrLM2ap9t3AmAxBJvQHF7xSKtnTrCTginQCkhzU5S7ecPT'); // Create transaction const tx = await chain.createTransaction(); // Add operations and validate tx.pushOperation({ vote: { voter: "otom", author: "c0ff33a", permlink: "ewxhnjbj", weight: 2200 } }).validate(); // Build and sign the transaction object const stx = tx.sign(wallet, publicKey); // show preformatted signed transaction console.info(chain.waxify`${stx}`); ``` -------------------------------- ### Create Python Extension Module 'cpp_python_bridge' Source: https://github.com/openhive-network/wax/blob/develop/python/CMakeLists.txt This CMake command defines the 'cpp_python_bridge' Python extension module. It specifies the source files, including C++ bridge code and headers, and links against the 'hive_protocol' library. ```cmake SET(HIVE_ROOT_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../hive") # this file is generated while performing a cythonize'ing process of the Python extension SET(WAX_CPP_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cpp_python_bridge.cpp") LIST(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake" "${HIVE_ROOT_PATH}/cmake" "${HIVE_ROOT_PATH}/libraries/fc/CMakeModules" "${HIVE_ROOT_PATH}/libraries/fc/GitVersionGen" ) find_package(PythonExtensions REQUIRED) include(hive_targets) file(GLOB HEADERS "${CMAKE_CURRENT_SOURCE_DIR}/../core/*.hpp" "cpython_interface.hpp") add_python_library("cpp_python_bridge" MODULE SOURCES ${WAX_CPP_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/../core/exception.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../core/foundation.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../core/utils.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../core/binary_view_helper.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../core/signing_keys_collector.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../core/minimize_required_signatures_helper.cpp cpython_interface.cpp ${HEADERS} LINK_LIBRARIES hive_protocol) ``` -------------------------------- ### Create Transaction from JSON Data Source: https://github.com/openhive-network/wax/blob/develop/ts/README.md This JavaScript code demonstrates how to create a transaction instance using JSON data. It utilizes the `createWaxFoundation` function from the `@hiveio/wax` library and logs the transaction ID. ```javascript import { createWaxFoundation } from '@hiveio/wax'; const wax = await createWaxFoundation(); const transaction = wax.createTransactionFromJson(`{ "ref_block_num": 19260, "ref_block_prefix": 2140466769, "expiration": "2016-09-15T19:47:33", "operations": [ { "value": { "voter": "taoteh1221", "author": "ozchartart", "permlink": "usdsteem-btc-daily-poloniex-bittrex-technical-analysis-market-report-update-46-glass-half-full-but-the-bottle-s-left-empty-sept", "weight": 10000 }, "type": "vote_operation" } ], "extensions": [] }`); console.info(transaction.id); // "8e78947614be92e77f7db82237e523bdbd7a907b" ``` -------------------------------- ### Add Dependencies for WASM Targets Source: https://github.com/openhive-network/wax/blob/develop/ts/wasm/src/CMakeLists.txt This CMake snippet adds dependencies for the 'wax.web' and 'wax.node' targets, ensuring that the assertion ID verifier components are built before the main WASM targets. ```CMake add_dependencies( wax.web protocol_assertion_id_verifier chain_assertion_id_verifier ) add_dependencies( wax.node protocol_assertion_id_verifier chain_assertion_id_verifier ) ``` -------------------------------- ### Bundle JavaScript and Type Declarations with Rollup Source: https://github.com/openhive-network/wax/blob/develop/ts/ARCHITECTURE.md Rollup is used to bundle the compiled JavaScript sources and type declarations. This process includes copying WASM files and wrappers, bundling the library's 'second layer', transpiling entry files for web and Node.js (adjusting WASM imports), creating a Vite-compatible entry file, and generating a final `index.d.ts` file. ```bash rollup -c ``` -------------------------------- ### Add Subdirectories for OpenHive Libraries Source: https://github.com/openhive-network/wax/blob/develop/python/CMakeLists.txt This snippet adds several subdirectories from the OpenHive project to the CMake build. These include libraries for protocol, fc, schema, chain, and assertion ID verification. ```cmake set( GENERATED_ASSERT_ID_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated_assert_id ) add_subdirectory("${HIVE_ROOT_PATH}/libraries/protocol" ${CMAKE_CURRENT_BINARY_DIR}/protocol) add_subdirectory("${HIVE_ROOT_PATH}/libraries/fc" ${CMAKE_CURRENT_BINARY_DIR}/fc) add_subdirectory("${HIVE_ROOT_PATH}/libraries/schema" ${CMAKE_CURRENT_BINARY_DIR}/schema) add_subdirectory("${HIVE_ROOT_PATH}/libraries/chain" ${CMAKE_CURRENT_BINARY_DIR}/chain EXCLUDE_FROM_ALL) add_subdirectory("${HIVE_ROOT_PATH}/assertion_id_verifier" ${CMAKE_CURRENT_BINARY_DIR}/assertion_id_verifier) ``` -------------------------------- ### CMake Subdirectory and File Globbing for Wax WASM Source: https://github.com/openhive-network/wax/blob/develop/ts/wasm/src/CMakeLists.txt This CMake configuration adds subdirectories for building schema and protocol components, and uses file globbing to collect header files. It also defines source files and include paths essential for the Wax WASM build. ```CMake set( GENERATED_ASSERT_ID_DIR ${CMAKE_CURRENT_BINARY_DIR}/protocol ) add_subdirectory( ${HIVE_ROOT_PATH}/libraries/schema build_schema_minimal ) add_subdirectory( ${HIVE_ROOT_PATH}/libraries/protocol build_protocol_minimal ) set( SKIP_COMPRESSION_DICTIONARIES "TRUE" ) add_subdirectory( ${HIVE_ROOT_PATH}/libraries/chain build_no_chain EXCLUDE_FROM_ALL) add_subdirectory( ${HIVE_ROOT_PATH}/assertion_id_verifier build_assertion_id_verifier_minimal ) file(GLOB HEADERS "core/*.hpp" "${CMAKE_CURRENT_SOURCE_DIR}/*.hpp") set( SOURCES ${WAX_ROOT_PATH}/core/exception.cpp ${WAX_ROOT_PATH}/core/foundation.cpp ${WAX_ROOT_PATH}/core/utils.cpp ${WAX_ROOT_PATH}/core/binary_view_helper.cpp foundation_wasm.cpp wasm_interface.cpp ) set( INCLUDES "${WAX_ROOT_PATH}" "${WAX_ROOT_PATH}/core" "${HIVE_ROOT_PATH}/libraries/chain/include" "${GENERATED_ASSERT_ID_DIR}" ) ``` -------------------------------- ### Compile C++ Core to WASM for Web Browser Source: https://github.com/openhive-network/wax/blob/develop/ts/ARCHITECTURE.md Similar to the Node.js compilation, the Wax C++ core and bridge are compiled to WASM for web browser execution using Emscripten. This produces `wax.web.js`, `wax.common.wasm`, and `wax.common.d.ts`. The `wax.common.wasm` output is identical for both Node.js and web targets. ```bash emcc ... -o wasm/build_wasm/wax.web.js -DWASM_WEB ``` -------------------------------- ### Compile C++ Core to WASM for Node.js Source: https://github.com/openhive-network/wax/blob/develop/ts/ARCHITECTURE.md The Wax C++ core and its TypeScript/C++ bridge are compiled into WebAssembly (WASM) for the Node.js environment using the Emscripten compiler. This process generates `wax.node.js`, `wax.common.wasm`, and `wax.common.d.ts` type declarations, all outputted to the `wasm/build_wasm` directory. ```bash emcc ... -o wasm/build_wasm/wax.node.js -DWASM_NODEJS ``` -------------------------------- ### Optimize Bundled Files with Terser Source: https://github.com/openhive-network/wax/blob/develop/ts/ARCHITECTURE.md A Terser-based script is executed on all bundled files to optimize them for size. This optimization process aims to maintain readability of function and class names in stack traces. ```bash node terser.ts ``` -------------------------------- ### Compile TypeScript/JavaScript Implementation Source: https://github.com/openhive-network/wax/blob/develop/ts/ARCHITECTURE.md After the WASM components are generated, the main TypeScript and JavaScript sources for the Wax library are compiled using the TypeScript compiler (`tsc`). The compilation settings are defined in `tsconfig.json`, and the output is placed in the `wasm/dist/lib` directory. ```bash tsc --project tsconfig.json ``` -------------------------------- ### Define WASM Target for Web Environment Source: https://github.com/openhive-network/wax/blob/develop/ts/wasm/src/CMakeLists.txt This CMake macro defines a WASM target for the web environment. It specifies the target name, environment, link libraries, and linker options, including disabling dynamic execution and allowing memory growth. ```CMake DEFINE_WASM_TARGET_FOR( wax TARGET_ENVIRONMENT "web" LINK_LIBRARIES hive_protocol LINK_OPTIONS -sNO_DYNAMIC_EXECUTION=1 -sALLOW_MEMORY_GROWTH=1 #-gsource-map=inline # show function names: -O0 -g3 --profiling-funcs -sDEMANGLE_SUPPORT=1 ) ```