### Go SDK Quick Start Guide: Connect, Wallet, Transactions, and Smart Contracts Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/go/page.mdx This comprehensive Go SDK example demonstrates the core functionalities for interacting with the Kleverchain. It covers setting up the network provider, loading a user wallet from a mnemonic, synchronizing the account, and performing various transactions including KLV transfers, smart contract deployment from a WASM file, and smart contract invocation with parameters. ```Go package main import ( "fmt" "time" "github.com/klever-io/klever-go-sdk/core/wallet" "github.com/klever-io/klever-go-sdk/provider" "github.com/klever-io/klever-go-sdk/provider/network" "github.com/klever-io/klever-go-sdk/provider/utils" ) func main() { ///////////////////////////////////////////////////////// ////////// Setup to connect to the kleverchain ////////// ///////////////////////////////////////////////////////// // Utility to create a network configuration net := network.NewNetworkConfig(network.TestNet) // Utility to create a http client plug and playh to interact with the kleverchain hc := utils.NewHttpClient(10 * time.Second) // Instantiates a new provider to interact with the kleverchain with specific network configuration and http client kc, err := provider.NewKleverChain(net, hc) if err != nil { panic(err) } ///////////////////////////////////////////////////////// // Preparing user account to interact with Kleverchain // ///////////////////////////////////////////////////////// // Loads user wallet from mnemonic w, err := wallet.NewWalletFromMnemonic("my wallet mnemonic separated by spaces") if err != nil { panic(err) } // Getting account from wallet acc, err := w.GetAccount() if err != nil { panic(err) } // Sync account with the kleverchain err = acc.Sync(kc) if err != nil { panic(err) } ///////////////////////////////////////////////////////// //// Creating, signing and broadcasting transactions /// ///////////////////////////////////////////////////////// // Send (transfer) example with fee payment in some KDA instead of KLV // Create a base transaction baseTransfer := acc.NewBaseTX() // Set a custom kda to kdaFee field on baseTX baseTransfer.KdaFee = "KDA-AB12" // Get the transfer receiver wallet and its account address rw, _ := wallet.NewWalletFromPEM("./path/to/receiver/wallet.pem") rAcc, _ := rw.GetAccount() // Create the transaction tx, err := kc.Send(baseTransfer, rAcc.Address().Bech32(), 10, "KLV") if err != nil { panic(err) } // Sign the transaction with the sender wallet err = tx.Sign(w) if err != nil { panic(err) } transferHash, err := tx.Broadcast(kc) if err != nil { panic(err) } fmt.Printf("Transfer transaction hash: %s\n", transferHash) // Deploy smart contract example baseScDeploy := acc.NewBaseTX() deployTx, err := kc.DeploySmartContract( baseScDeploy, "./path/to/sc/wasm/file/lottery-kda.wasm", true, true, true, true, "", ) if err != nil { panic(err) } err = deployTx.Sign(w) if err != nil { panic(err) } deployHash, err := deployTx.Broadcast(kc) if err != nil { panic(err) } fmt.Printf("Smart contract deploy hash: %s\n", deployHash) // Invoke smart contract example baseScInvoke := acc.NewBaseTX() timeStamp := time.Now().Unix() lotteryDuration := int64(120) // 120 seconds -> 2 minutes lotteryDeadline := fmt.Sprintf("optionu64:%d", timeStamp+lotteryDuration) invokeTx, err := kc.InvokeSmartContract( baseScInvoke, "klv1qqqqqqqqqqqqqy0ur5m4rtc0ntr4act4ddres5", "createLotteryPool", map[string]int64{}, "string:demo", "tokenidentifier:KLV", "N:10000000", "E:0", lotteryDeadline, "E:0", "E:0", "E:0", ) if err != nil { panic(err) } err = invokeTx.Sign(w) if err != nil { panic(err) } invokeHash, err := invokeTx.Broadcast(kc) if err != nil { panic(err) } fmt.Printf("Smart contract invoke hash: %s\n", invokeHash) } ``` -------------------------------- ### Verify Klever Wallet Installation in JavaScript Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/quickstart/page.mdx This snippet checks for the presence of the `window.klever` object, indicating if Klever Wallet is installed in the user's browser. It is highly recommended for better user experience and error handling. This ensures the application only proceeds if the wallet is available. ```JavaScript if (typeof window.klever !== 'undefined') { console.log('Klever Wallet is installed!') } ``` -------------------------------- ### Initialize KleverChain SDK Provider in C# Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/csharp/page.mdx This snippet demonstrates how to instantiate the KleverChain SDK provider. It requires a `NetworkConfig` to specify the target network (e.g., TestNet), enabling interaction with the blockchain. ```C# // Create a network configuration for TestNet var provider = new KleverProvider(new NetworkConfig(Network.TestNet)); ``` -------------------------------- ### Kleverchain C# SDK: Full Flow Example (Account, Transfer, Smart Contract) Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/csharp/page.mdx This comprehensive C# example demonstrates a complete interaction flow with the Kleverchain TestNet. It covers setting up the provider, deriving and synchronizing a user account from a mnemonic, performing a KLV token transfer with a KDA fee, deploying a WebAssembly (WASM) smart contract, and invoking a method on an existing smart contract. Error handling is included for each transaction type. ```C# using System; using System.Threading.Tasks; using System.Collections.Generic; using kleversdk.core; using kleversdk.provider; using System.IO; class Program { static async Task Main(string[] args) { ///////////////////////////////////////////////////////// ////////// Setup to connect to the kleverchain ////////// ///////////////////////////////////////////////////////// // Create a network configuration for TestNet var provider = new KleverProvider(new NetworkConfig(Network.TestNet)); ///////////////////////////////////////////////////////// // Preparing user account to interact with Kleverchain // ///////////////////////////////////////////////////////// // Load user wallet from mnemonic var wallet = Wallet.DeriveFromMnemonic("my wallet mnemonic separated by spaces"); var account = wallet.GetAccount(); // Sync account with the kleverchain await account.Sync(provider); ///////////////////////////////////////////////////////// //// Creating, signing and broadcasting transactions //// ///////////////////////////////////////////////////////// // Transfer example with KDA fee instead of KLV try { // Create a transfer transaction var tx = await provider.Send( account.Address.Bech32, account.Nonce, "klv1receiving_address", 10, "KLV", "KDA-AB12" // KDA fee ); // Sign and broadcast the transaction var decoded = await provider.Decode(tx); var signature = wallet.SignHex(decoded.Hash); tx.AddSignature(signature); var transferHash = await provider.Broadcast(tx); Console.WriteLine($"Transfer transaction hash: {transferHash}"); } catch (Exception e) { Console.WriteLine($"Error in transfer: {e.Message}"); } // Deploy smart contract example try { byte[] contractBytes = File.ReadAllBytes("./path/to/sc/wasm/file/lottery-kda.wasm"); var deployParams = new List(); string parameters = SmartContract.ToEncodeDeploySmartContract( contractBytes, deployParams, true, true, true, true ); var deployTx = await provider.SmartContract( account.Address.Bech32, account.Nonce, null, 1, // Deploy Type "", // Empty address for deployment new Dictionary(), parameters ); var decodedDeploy = await provider.Decode(deployTx); var deploySignature = wallet.SignHex(decodedDeploy.Hash); deployTx.AddSignature(deploySignature); var deployHash = await provider.Broadcast(deployTx); Console.WriteLine($"Smart contract deploy hash: {deployHash}"); } catch (Exception e) { Console.WriteLine($"Error in deployment: {e.Message}"); } // Invoke smart contract example try { long timestamp = DateTimeOffset.Now.ToUnixTimeSeconds() + 120; // 2 minutes var scParamsLottery = new List { new[] { "string", "demo" }, new[] { "tokenidentifier", "KLV" }, new[] { "N", "10000000" }, new[] { "E", "" }, new[] { "optionu64", $"{timestamp}" }, new[] { "E", "" }, new[] { "E", "" }, new[] { "E", "" } }; string parameters = SmartContract.ToEncodeInvokeSmartContract( "createLotteryPool", scParamsLottery ); var invokeTx = await provider.SmartContract( account.Address.Bech32, account.Nonce, null, 0, // Invoke Type "klv1qqqqqqqqqqqqqy0ur5m4rtc0ntr4act4ddres5", new Dictionary(), parameters ); var decodedInvoke = await provider.Decode(invokeTx); var invokeSignature = wallet.SignHex(decodedInvoke.Hash); invokeTx.AddSignature(invokeSignature); var invokeHash = await provider.Broadcast(invokeTx); Console.WriteLine($"Smart contract invoke hash: {invokeHash}"); } catch (Exception e) { Console.WriteLine($"Error in invocation: {e.Message}"); } } } ``` -------------------------------- ### Create, Sign, and Broadcast a KLV Transfer Transaction in C# Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/csharp/page.mdx This example illustrates the process of creating a KLV transfer transaction, signing it with the user's wallet, and broadcasting it to the KleverChain network. It also demonstrates how to specify a KDA token for the transaction fee instead of the default KLV. ```C# // Create a transfer transaction var tx = await provider.Send( account.Address.Bech32, account.Nonce, "klv1receiving_address", 10, "KLV", "KDA-AB12" // KDA fee ); // Sign and broadcast the transaction var decoded = await provider.Decode(tx); var signature = wallet.SignHex(decoded.Hash); tx.AddSignature(signature); var transferHash = await provider.Broadcast(tx); ``` -------------------------------- ### Generate Klever Blockchain Address using JavaScript SDK Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/getting-started-with-klever-blockchain/page.mdx This JavaScript code snippet demonstrates how to programmatically create a new Klever Blockchain address and generate a corresponding private key using the `@klever/sdk` library. It shows the process of importing the SDK, generating a key pair for KLV and KDA tokens, and then logging the generated account details (private key and address) to the console. Users must install the `@klever/sdk` package to use this functionality. ```javascript //import the sdk var sdk = require("@klever/sdk"); //create a new klever account for klv and kda tokens var klvAccount = await sdk.utils.generateKeyPair() //check your private key and address console.log(klvAccount) ``` -------------------------------- ### Load Wallet and Sync Account with KleverChain in C# Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/csharp/page.mdx This code shows how to load a user wallet from a mnemonic phrase and then synchronize the account details with the KleverChain network. This step is crucial for performing transactions and querying account balances. ```C# // Load user wallet from mnemonic var wallet = Wallet.DeriveFromMnemonic("my wallet mnemonic separated by spaces"); var account = wallet.GetAccount(); // Sync account with the kleverchain await account.Sync(provider); ``` -------------------------------- ### Install KleverChain SDK for Web Applications Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/introduction-to-kleverchain-sdk/page.mdx Commands to install the KleverChain SDK for web applications using npm or yarn. This SDK provides a quick and easy way to make contract calls directly to the Klever blockchain from a browser environment. ```bash $ npm install @klever/sdk-web ``` ```bash $ yarn add @klever/sdk-web ``` -------------------------------- ### Clone Klever Contract Example Repository Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/tutorials/crowdfunding/page.mdx This command clones the `kvm-contract-example` repository from GitHub, which contains the necessary project structure for the Crowdfunding contract tutorial. ```bash git clone https://github.com/klever-io/kvm-contract-example ``` -------------------------------- ### Invoke a Smart Contract Function on KleverChain in C# Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/csharp/page.mdx This example demonstrates how to invoke a specific function on an already deployed smart contract. It covers creating and encoding the function's parameters, then constructing, signing, and broadcasting the invocation transaction to the KleverChain. ```C# long timestamp = DateTimeOffset.Now.ToUnixTimeSeconds() + 120; // 2 minutes var scParamsLottery = new List { new[] { "string", "demo" }, new[] { "tokenidentifier", "KLV" }, new[] { "N", "10000000" }, new[] { "E", "" }, new[] { "optionu64", $"{timestamp}" }, new[] { "E", "" }, new[] { "E", "" }, new[] { "E", "" } }; string parameters = SmartContract.ToEncodeInvokeSmartContract( "createLotteryPool", scParamsLottery ); var invokeTx = await provider.SmartContract( account.Address.Bech32, account.Nonce, null, 0, // Invoke Type "klv1qqqqqqqqqqqqqy0ur5m4rtc0ntr4act4ddres5", new Dictionary(), parameters ); var decodedInvoke = await provider.Decode(invokeTx); var invokeSignature = wallet.SignHex(decodedInvoke.Hash); invokeTx.AddSignature(invokeSignature); var invokeHash = await provider.Broadcast(invokeTx); ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/klever-io/klever-docs/blob/develop/README.md These commands install all required project dependencies using either npm or Yarn. Installing dependencies is crucial for the project to run correctly. ```bash npm install ``` ```bash yarn ``` -------------------------------- ### Define and Export Page Metadata Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/getting-started-with-klever-blockchain/page.mdx This JavaScript snippet demonstrates how to define and export page-level metadata, such as the title and description, which is commonly used by documentation frameworks or static site generators to configure page properties. ```JavaScript export const metadata = {'title': 'getting-started-with-klever-blockchain', 'description': 'Content for getting-started-with-klever-blockchain'} ``` -------------------------------- ### Rust Test Setup for Klever Smart Contract Scenarios Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/testing/scenarios/running-scenarios/page.mdx This Rust code snippet demonstrates how to set up and run Klever smart contract scenarios within a Rust project. It shows how to initialize the `ScenarioWorld` for both Go and Rust backends and how to define test functions to execute specific scenario JSON files, including an example of an ignored test using `#[ignore]` annotation. ```Rust use klever_sc_scenario::*; fn world() -> ScenarioWorld { ScenarioWorld::vm_go() // For the Go backend // OR // ScenarioWorld::new() // For the Rust backend } #[test] fn my_contract_go() { world().run("scenarios/my_contract.scen.json"); } #[test] #[ignore = "Reason to ignore"] fn ignored_test_go() { world().run("scenarios/ignored_test.scen.json"); } ``` -------------------------------- ### Instantiating KleverChain SDK Provider in Go Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/go/page.mdx This snippet demonstrates how to initialize a new KleverChain SDK provider. It involves creating a network configuration (e.g., TestNet) and an HTTP client, then using them to instantiate the `KleverChain` provider. This setup is essential for interacting with the KleverChain network. ```Go // Utility to create a network configuration net := network.NewNetworkConfig(network.TestNet) // Utility to create a http client plug and playh to interact with the kleverchain hc := utils.NewHttpClient(10 * time.Second) // Instantiates a new provider to interact with the kleverchain with specific network configuration and http client kc, err := provider.NewKleverChain(net, hc) if err != nil { panic(err) } ``` -------------------------------- ### Clone and Navigate to Klever Documentation Repository Source: https://github.com/klever-io/klever-docs/blob/develop/README.md These commands clone the Klever documentation project from its GitHub repository and then change the current directory to the project folder. This is the initial setup step for local development. ```bash git clone https://github.com/klever-io/klever-docs.git ``` ```bash cd klever-docs ``` -------------------------------- ### Run Klever Documentation Development Server Source: https://github.com/klever-io/klever-docs/blob/develop/README.md This command starts the Next.js development server locally, making the documentation site accessible in your browser at http://localhost:3000. It enables live reloading for development. ```bash npm run dev ``` -------------------------------- ### Sending a Kleverchain Transaction with Message (C#) Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/unity/page.mdx Provides a step-by-step example of sending a transaction with a message on Kleverchain. It covers getting the account, preparing the transaction, decoding, signing, and broadcasting it using `KleverProvider` and `Wallet`. ```csharp Account acc = wallet.GetAccount(); string message = "Be Klever!" string toAddress = "other address here"; var tx = await kleverProvider.SendWithMessage(acc.Address.Bech32,acc.Nonce,toAddress,0.000001f,message); var decoded = await this.kleverProvider.Decode(tx); var signature = wallet.SignHex(decoded.Hash); tx.AddSignature(signature); var broadcastResult = await this.kleverProvider.Broadcast(tx); Debug.Log(broadcastResult.String()); ``` -------------------------------- ### Deploy a Smart Contract to KleverChain in C# Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/csharp/page.mdx This snippet details the process of deploying a smart contract to KleverChain. It involves reading the WASM bytecode, encoding deployment parameters, and then creating, signing, and broadcasting the deployment transaction. Ensure the WASM file path is correct. ```C# byte[] contractBytes = File.ReadAllBytes("./path/to/sc/wasm/file/lottery-kda.wasm"); var deployParams = new List(); string parameters = SmartContract.ToEncodeDeploySmartContract( contractBytes, deployParams, true, true, true, true ); var deployTx = await provider.SmartContract( account.Address.Bech32, account.Nonce, null, 1, // Deploy Type "", // Empty address for deployment new Dictionary(), parameters ); var decodedDeploy = await provider.Decode(deployTx); var deploySignature = wallet.SignHex(decodedDeploy.Hash); deployTx.AddSignature(deploySignature); var deployHash = await provider.Broadcast(deployTx); ``` -------------------------------- ### Install KleverChain SDK for NodeJS Applications Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/introduction-to-kleverchain-sdk/page.mdx Commands to install the KleverChain SDK for NodeJS applications using npm or yarn. NodeJS version 18.0.0 or above is required to use this SDK for direct contract calls from a server environment. ```bash $ npm install @klever/sdk-node ``` ```bash $ yarn add @klever/sdk-node ``` -------------------------------- ### Example JSON ABI for an Adder Smart Contract Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/data/ABI/page.mdx A concrete JSON example of an ABI for a simple 'Adder' smart contract. It demonstrates the `buildInfo`, `docs`, `name`, `constructor` with an `initial_value` input, and `endpoints` including `getSum` (readonly) and `add` (mutable) with their respective inputs and outputs. This example illustrates the structure defined in the ABI specification. ```json { "buildInfo": { "rustc": { "version": "1.71.0-nightly", "commitHash": "a2b1646c597329d0a25efa3889b66650f65de1de", "commitDate": "2023-05-25", "channel": "Nightly", "short": "rustc 1.71.0-nightly (a2b1646c5 2023-05-25)" }, "contractCrate": { "name": "adder", "version": "0.0.0", "gitVersion": "v0.43.2-5-gfe62c37d2" }, "framework": { "name": "klever-sc", "version": "0.43.2" } }, "docs": [ "One of the simplest smart contracts possible,", "it holds a single variable in storage, which anyone can increment." ], "name": "Adder", "constructor": { "inputs": [ { "name": "initial_value", "type": "BigUint" } ], "outputs": [] }, "endpoints": [ { "name": "getSum", "mutability": "readonly", "inputs": [], "outputs": [ { "type": "BigUint" } ] }, { "docs": ["Add desired amount to the storage variable."], "name": "add", "mutability": "mutable", "inputs": [ { "name": "value", "type": "BigUint" } ], "outputs": [] } ], "events": [], "kdaAttributes": [], "types": {} } ``` -------------------------------- ### Define Smart Contract Constructor with `#[init]` Annotation Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/reference/annotations/page.mdx Every smart contract requires a constructor, marked by the `#[init]` annotation, which executes only once upon deployment. This constructor is also invoked during smart contract upgrades, ensuring single-time execution. ```Rust #[klever_sc::contract] pub trait Example { #[init] fn this_is_the_constructor( constructor_arg_1: u32, constructor_arg_2: BigUint) { // ... } } ``` -------------------------------- ### Start Klever Blockchain Services with Docker Compose Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/create-local-testnet/page.mdx This bash command executes the `docker-compose up` command with the `-d` flag. This starts all services defined in the `docker-compose.yaml` file in detached mode, allowing them to run in the background without occupying the terminal. ```bash docker-compose up -d ``` -------------------------------- ### Klever Smart Contract Parameter Encoding Prefixes Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/csharp/page.mdx This table specifies the required encoder type prefixes for various value types when preparing parameters for smart contract deployment or invocation on the Klever blockchain. Using the correct prefix ensures proper data serialization and deserialization for smart contract interactions. ```APIDOC Value Type | Encoder Type Prefix BigInteger | bi, BI, n, N, bigNumber, BigNumber, BigInt, BigUint Int64 | i, I, i64, I64, int64 Uint64 | u, U, u64, U64, uint64 Int32 | i32, I32, int32, isize Uint32 | u32, U32, uint32, usize String/Buffer | s, S, string, ManagedBuffer, String, bytes TokenIdentifer | TokenIdentifer Address | a, A, address, Address Boolean | bool Empty argument | 0, e, E, empty ``` -------------------------------- ### Example JSON Output for `sc-meta local-deps` Command Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/config-and-tooling/CLI/page.mdx This JSON snippet provides an abridged example of the output generated by the `sc-meta local-deps` command. It illustrates the structure of the dependency report, including the root path, the specific contract path, the common dependency path, and a list of detected local dependencies with their respective depths within the project hierarchy. ```JSON { "root": "/home/user/klever/klever-io/klever-vm-sdk-rsexchange-sc/", "contractPath": "/home/user/klever/klever-io/klever-vm-sdk-rsexchange-sc/dex/pair", "commonDependencyPath": "/home/user/klever/klever-io/klever-vm-sdk-rsexchange-sc", "dependencies": [ { "path": "common/common_errors", "depth": 1 }, { "path": "common/common_structs", "depth": 1 }, { "path": "common/modules/legacy_token_decode_module", "depth": 3 }, { "path": "common/modules/locking_module", "depth": 2 }, { "path": "common/modules/math", "depth": 2 } ] } ``` -------------------------------- ### Install klever-sc-meta CLI Tool Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/config-and-tooling/page.mdx This command installs the `klever-sc-meta` smart contract management tool globally using Cargo. The `--locked` flag ensures that the exact dependency versions from `Cargo.lock` are used, promoting reproducible builds. ```bash cargo install klever-sc-meta --locked ``` -------------------------------- ### Verify Node.js Installation Source: https://github.com/klever-io/klever-docs/blob/develop/README.md This command checks the installed version of Node.js on your system. It's a prerequisite for running the Klever documentation project, which requires Node.js version 20 or higher. ```bash node -v ``` -------------------------------- ### Required Nuget Packages for Klever SDK in Unity Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/unity/page.mdx Lists the necessary .dll files and their versions to integrate the Klever SDK into a Unity project. These packages can be downloaded from Nuget or obtained from the Unity example project. ```text kleversdk.dll - ^0.0.2 dotnetstandard-bip39.dll - ^1.0.2 BouncyCastle.Crypto.dll - ^1.8.9 ``` -------------------------------- ### Example Klever Node Addresses and BLS Keys Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/create-local-testnet/page.mdx This example shows the generated addresses and BLS keys for two validator nodes (Node 0 and Node 1). These keys are crucial for identifying and securing the nodes within the Klever blockchain network. ```text Node 0: - Address 0: klv1lay4f5657l535g7j5nx8wenhqvlhjune2zfvt94sv5kv7qk3snwqajpux3 - BLS 0: 158449b4219fff1151d2e0eaf50c63cb95ba8b582ac2ff5429f90f500dd816068ac071c5a13490b65296b22a5fb0ab07359029a3fce0761441dd2c820713e52fc0a8ef3b9a0d8af28c9f2b74b5a5542956e481e596911b559b8c76cb66fa0685 Node 1: - Address 1: klv14nwrysndqs29wvvskwk8lq3ch9v4jatf6l6mxa6vrj9wylt0gxssw0xvmm - BLS 1: 9eb5fe005d5ad50a621ac9728ed2dcaf780c1d69fae86399997d0b9bc3f53c1b968a56a048f083b60290ebd037267f12a2965220100e85324b3a68fd940574873b7bed6d6cdf66fa404f337e52e306010d8297f0d89c9b04e4514c7c7536d293 ``` -------------------------------- ### Example Klever `genesis.json` Node Entry Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/create-local-testnet/page.mdx This JSON snippet shows the structure for a single node entry within the `genesis.json` file. It defines the validator's address, KLV and KFI balances, and self-delegation details, which are crucial for initializing the blockchain state. ```json { "address": "klv1vx2j8lwdskc9z5mr9z2ttlpfpaf6dkxes7mf7zg883x2lcl5m9dselkspy", // Validator Address "balance": 3323333333333333, // KLV Balance "kfiBalance": 7000000000000, // KFI Balance "delegation": { // Delegation List "address": "klv1vx2j8lwdskc9z5mr9z2ttlpfpaf6dkxes7mf7zg883x2lcl5m9dselkspy", // Self Delegation "value": 10000000000000 } } ``` -------------------------------- ### List Available Klever Smart Contract Templates (`templates`) Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/config-and-tooling/CLI/page.mdx The `templates` command provides a list of all available smart contract templates that can be used with the `new` command. This helps developers choose an appropriate starting point for their projects. The list can be filtered by framework version. ```text crypto-zombies empty adder ``` ```APIDOC templates command parameters: --tag: The framework version on which the contracts should be created. Defaults to the latest released version. ``` -------------------------------- ### Klever SDK Node.js: Common Transaction Flow Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/node.js/page.mdx This example demonstrates the standard process for building, signing, and broadcasting a transaction using the Klever SDK for Node.js. It initializes an account with a private key, constructs a transfer transaction, signs it, and then broadcasts it to the network. ```TypeScript import { Account, TransactionType } from '@klever/sdk-node' const payload = { amount, receiver, kda, } const privateKey = 'yourPrivateKey' const account = new Account(privateKey) await account.ready const unsignedTx = await account.buildTransaction([ { payload, type: TransactionType.Transfer, }, ]) const signedTx = await account.signTransaction(unsignedTx) const broadcastRes = await account.broadcastTransactions([signedTx]) console.log(broadcastRes) ``` -------------------------------- ### Initializing KleverProvider for Network Interaction (C#) Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/unity/page.mdx Demonstrates how to instantiate the `KleverProvider` class, which is essential for interacting with the Kleverchain SDK. It shows setting up the network configuration for TestNet and how to switch to MainNet. ```csharp using kleversdk.core; using kleversdk.provider; using kleversdk.provider.Dto; private KleverProvider kleverProvider; private void Awake(){ // need to instantiate the kleverProvider to use the kleverchain sdk environment = new NetworkConfig(kleversdk.provider.Network.TestNet); kleverProvider = new KleverProvider(environment); } ``` ```csharp environment = new NetworkConfig(kleversdk.provider.Network.MainNet) ``` -------------------------------- ### Access User's Klever Wallet Account in JavaScript Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/quickstart/page.mdx This code initializes the Klever Wallet session and retrieves the user's wallet address. It's crucial to only initiate this connection in response to direct user action, such as a connect button click. The connect button should be disabled while the request is pending to prevent multiple attempts. ```JavaScript await window.klever.initialize(); const address = await window.klever.getWalletAddress(); if (!address || address.length === 0) { throw new Error("Session not properly initialized"); } ``` -------------------------------- ### Equivalent Commands for Building a Single Contract Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/config-and-tooling/CLI/page.mdx Illustrates two equivalent methods for building a single smart contract: using the `sc-meta all` command from the parent directory or directly running `cargo run build` within the contract's meta directory. ```CLI cd my-contract && sc-meta all build ``` ```CLI cd my-contract/meta && cargo run build ``` -------------------------------- ### Define Core Smart Contract Trait with `#[klever_sc::contract]` Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/reference/annotations/page.mdx This annotation is essential for any Rust trait that defines the core endpoints and logic of a smart contract. Each crate should contain only one such trait. It does not accept any additional arguments. ```APIDOC `#[klever_sc::contract]` Purpose: Designates a trait as the main smart contract definition. Constraints: Only one per crate; accepts no arguments. ``` -------------------------------- ### Define Smart Contract Proxy Trait with `#[klever_sc::proxy]` Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/reference/annotations/page.mdx This annotation is used for traits that act as proxies for smart contract calls, automatically generated but manually creatable. It takes no arguments. The same single-annotation-per-module limitation applies as with `contract` and `module`. ```APIDOC `#[klever_sc::proxy]` Purpose: Defines a trait as a proxy for smart contract calls. Constraints: Accepts no arguments. Only one contract, module, or proxy annotation per Rust module unless in separate `mod` blocks. ``` -------------------------------- ### Generate Rust Smart Contract Test Scenario Output Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/reference/rust-testing-framework/page.mdx The `init_test` function serves as the entry point for running the smart contract deployment test. It calls `setup_crowdfunding` to prepare the test environment and then uses `write_mandos_output` to generate a JSON trace file, `_generated_init.scen.json`, for scenario analysis and debugging. ```rust #[test] fn init_test() { let cf_setup = setup_crowdfunding(crowdfunding_kda::contract_obj); cf_setup .blockchain_wrapper .write_mandos_output("_generated_init.scen.json"); } ``` -------------------------------- ### Configure Klever Contract Deployments with Gas and KLV Transfers (Rust) Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/reference/calls/page.mdx This example illustrates how to configure a Klever smart contract deployment by specifying a gas limit and including KLV transfers. It shows chaining `with_klv_transfer` and `with_gas_limit` methods to the `init` call on a contract proxy. ```Rust self.callee_contract_proxy(callee_sc_address) .init(my_biguint_arg) ``` ```Rust self.callee_contract_proxy() .init(my_biguint_arg) .with_klv_transfer(klv_amount) .with_gas_limit(gas_limit) ``` -------------------------------- ### Initializing Klever Wallet from Private Key (C#) Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/unity/page.mdx Shows how to instantiate a `Wallet` object directly using a hexadecimal private key. ```csharp var privateKey = "hex private key" var wallet = new Wallet(privateKey) ``` -------------------------------- ### Klever SC: Log Contract Events with `#[event]` Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/reference/annotations/page.mdx The `#[event]` annotation is used to log actions during contract execution. Events are not stored on-chain but are hashed for verification, providing an auditable trail of contract interactions with indexed parameters for efficient filtering. ```Rust #[event("transfer")] fn transfer_event( &self, #[indexed] from: &ManagedAddress, #[indexed] to: &ManagedAddress, #[indexed] token_id: u32, data: ManagedBuffer, ); ``` -------------------------------- ### Klever SDK Node.js: Quick Send Transaction Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/node.js/page.mdx This example shows a simplified way to send a transaction using the `quickSend` method in the Klever SDK for Node.js. The `quickSend` method combines the steps of building, signing, and broadcasting a transaction into a single call, streamlining the process. ```TypeScript import { Account, TransactionType } from '@klever/sdk-node' const payload = { amount, receiver, kda, } const privateKey = 'yourPrivateKey' const account = new Account(privateKey) await account.ready const broadcastRes = await account.quickSend([ { payload, type: TransactionType.Transfer, }, ]) // the same as buildTransaction + signTransaction + broadcastTransactions console.log(broadcastRes) ``` -------------------------------- ### Configure Crowdfunding Contract Cargo.toml Package and Lib Path Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/tutorials/crowdfunding/page.mdx Modifies the `Cargo.toml` file within the `crowdfunding` contract directory, setting the package name and specifying the main library path as `src/lib.rs`. ```toml [package] name = "crowdfunding" [lib] path = "src/lib.rs" ``` -------------------------------- ### Klever SC: Check and Clear Storage with `#[storage_is_empty]` and `#[storage_clear]` Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/reference/annotations/page.mdx These annotations provide utilities for managing contract storage. `#[storage_is_empty]` checks if a storage key is empty, returning a boolean. `#[storage_clear]` removes the value associated with a specified storage key. ```Rust #[storage_is_empty("opt_addr")] fn is_empty_opt_addr(&self) -> bool; #[storage_clear("field_to_clear")] fn clear_storage_value(&self); ``` -------------------------------- ### Secure Klever Wallet Application with Message Signature Verification in JavaScript Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/quickstart/page.mdx This snippet enhances application security by verifying the integrity of the user's wallet through a signed message. After retrieving the user's address, a message is signed by the user and then validated. This step adds an extra layer of account validation beyond just retrieving the address. ```JavaScript // ... const messageToSign = 'Validate this message to proceed.' const signedMessage = await window.klever.signMessage(messageToSign) const isValid = await window.klever.validateSignature( messageToSign, signedMessage, address, ) if (!isValid) { throw new Error('Invalid signature') } ``` -------------------------------- ### Configure Root Cargo.toml Members for Crowdfunding Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/tutorials/crowdfunding/page.mdx Updates the `Cargo.toml` file at the project root to include the `contracts/crowdfunding` and `contracts/crowdfunding/meta` directories as members, enabling multi-package workspace management. ```toml members = ["contracts/crowdfunding", "contracts/crowdfunding/meta"] ``` -------------------------------- ### Klever SC: Write Data with `#[storage_set]` Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/reference/annotations/page.mdx This annotation writes data to contract storage. It supports direct key-value assignments and can be used for simple types or complex structures. Caution is advised with key naming to prevent unintended data overwrites. ```Rust #[klever_sc::contract] pub trait Adder { #[storage_set("sum")] fn set_sum(&self, sum: &BigUint); #[storage_set("example_map")] fn set_value(&self, key_1: u32, key_2: u32, value: &SerializableType); } ``` -------------------------------- ### Retrieve Data from Smart Contract Storage using `#[storage_get]` Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/reference/annotations/page.mdx This annotation simplifies data management by retrieving values from contract storage based on a specified key. It is applied to methods that define how data is fetched, ensuring proper serialization and deserialization. ```Rust #[klever_sc::contract] pub trait Adder { #[view(getSum)] #[storage_get("sum")] fn get_sum(&self) -> BigUint; #[storage_get("example_map")] fn get_value(&self, key_1: u32, key_2: u32) -> SerializableType; } ``` -------------------------------- ### Basic Smart Contract Build Command (Shell) Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/config-and-tooling/build-reference/page.mdx To build a smart contract, navigate to its crate and execute this shell command. It initiates the compilation process for the contract. ```sh sc-meta all build ``` -------------------------------- ### Klever SC: Map Storage Keys with `#[storage_mapper]` Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/reference/annotations/page.mdx This annotation handles multiple storage keys for reading and writing data. It allows defining mappers like `SingleValueMapper` for individual values or `LinkedListMapper` for collections, providing flexible data access patterns. ```Rust #[storage_mapper("user_status")] fn user_status(&self) -> SingleValueMapper; #[storage_mapper("list_mapper")] fn list_mapper(&self, sub_key: usize) -> LinkedListMapper; ``` -------------------------------- ### Invoke a Smart Contract with CallValues on KleverChain in C# Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/csharp/page.mdx This snippet illustrates how to invoke a smart contract function while simultaneously sending KLV tokens as `CallValues` within the same transaction. It's useful for smart contract interactions that require an attached value. ```C# List scParamsDice = new List { new string[] { "i32", "1" }, new string[] { "i32", "32"}, }; string parameters = SmartContract.ToEncodeInvokeSmartContract( "bet", scParamsDice ); var callValue = new Dictionary { }; callValue.Add("KLV", 10); var invokeTx = await provider.SmartContract( account.Address.Bech32, account.Nonce, null, 0, // Invoke Type "klv1qqqqqqqqqqqqqpgq0k4yvl0f8dsxvaaym9gukkc6rh4flgk0annq4w060n", callValue, parameters ); var decodedInvoke = await provider.Decode(invokeTx); var invokeSignature = wallet.SignHex(decodedInvoke.Hash); invokeTx.AddSignature(invokeSignature); var invokeHash = await provider.Broadcast(invokeTx); ``` -------------------------------- ### Configure Klever Blockchain Genesis `nodesSetup.json` Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/create-local-testnet/page.mdx This snippet illustrates the basic blockchain configurations and initial list of nodes for a Klever localnet. It defines parameters like `startTime`, `slotInterval`, `slotsPerEpoch`, `consensusGroupSize`, `chainID`, and an array of `initialNodes` with their public keys and addresses. ```json { "startTime": 1720483200, // Genesis start time "slotInterval": 4000, // Time of a slot (block) "slotsPerEpoch": 20, // How many slot a epoch have. slotInterval * slotsPerEpoch = EpochInterval "consensusGroupSize": 3, // Consensus Size "minNodes": 3, // Min Nodes "chainID": "79652", "minTransactionVersion": 1, "klvDenomination": 6, "initialNodes": [ // Initial Nodes List { "pubkey": "807cf3168ec886165ac2128c77354bfd80004bfc0ac2a9f3a2b24f0805071a8bc352020338de993ca3bd85a4efe757124553ca9bc65de2c28f5450a42cbdc82bb7ad14857ddfea6577e6859de2d07e89ed663951ca55c6892deafc7c5f4a4807", // BLS "address": "klv1y6snwael5jpfgfzrf3wzlsddhwew93v2lf5wda6uz9u2ep9e8uvsehufg6" // Address } ] } ``` ```json { "startTime": 1720477239, "slotInterval": 4000, "slotsPerEpoch": 20, "consensusGroupSize": 2, "minNodes": 2, "chainID": "4123", "minTransactionVersion": 1, "klvDenomination": 6, "initialNodes": [ { "pubkey": "158449b4219fff1151d2e0eaf50c63cb95ba8b582ac2ff5429f90f500dd816068ac071c5a13490b65296b22a5fb0ab07359029a3fce0761441dd2c820713e52fc0a8ef3b9a0d8af28c9f2b74b5a5542956e481e596911b559b8c76cb66fa0685", "address": "klv1lay4f5657l535g7j5nx8wenhqvlhjune2zfvt94sv5kv7qk3snwqajpux3" }, { "pubkey": "9eb5fe005d5ad50a621ac9728ed2dcaf780c1d69fae86399997d0b9bc3f53c1b968a56a048f083b60290ebd037267f12a2965220100e85324b3a68fd940574873b7bed6d6cdf66fa404f337e52e306010d8297f0d89c9b04e4514c7c7536d293", "address": "klv14nwrysndqs29wvvskwk8lq3ch9v4jatf6l6mxa6vrj9wylt0gxssw0xvmm" } ] } ``` -------------------------------- ### Rust Klever VM Blockchain API: Get Block Random Seed Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/reference/api-functions/page.mdx Returns the block random seed, which can be used for generating random numbers. This seed will be the same for all calls in the current block and can be predicted by someone calling this at the start of the round before interacting with the contract. ```Rust get_block_random_seed() -> ManagedByteArray ``` -------------------------------- ### Designate Trait as Smart Contract Module with `#[klever_sc::module]` Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/reference/annotations/page.mdx Similar to `contract`, this annotation designates a trait as a smart contract module and takes no arguments. A Rust module can only contain one contract, module, or proxy annotation; multiple must be in separate `mod` declarations. ```APIDOC `#[klever_sc::module]` Purpose: Designates a trait as a smart contract module. Constraints: Accepts no arguments. Only one contract, module, or proxy annotation per Rust module unless in separate `mod` blocks. ``` -------------------------------- ### Initializing Klever Wallet from Mnemonic (C#) Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/unity/page.mdx Illustrates how to create a `Wallet` object using a BIP-39 mnemonic seed phrase. It also shows how to specify an optional index for address derivation. ```csharp var mnemonic = "word1 word2 ..." var wallet = Wallet.DeriveFromMnemonic(mnemonic) var otherWallet = Wallet.DeriveFromMnemonic(mnemonic,5) ``` -------------------------------- ### Specifying Arguments for Klever Contract Deployment Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/tutorials/crowdfunding/page.mdx This snippet illustrates the command-line arguments required when deploying a Klever smart contract, specifically for a crowdfunding contract. These arguments define parameters such as service fee, limit, profit address, and claim fee, allowing for precise configuration of the contract's behavior. ```plaintext --args u32:5 --args u32:10 --args a:klv1sr70jktl8rhq37s8htl390qm6mnx4wsdm5e8nykk797d6d3n85vsghyqd4 --args bi:10000000 ``` -------------------------------- ### Get Fixed Number of KDA Transfers (Call Value API) Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/reference/api-functions/page.mdx Returns a fixed number of KDA transfers as an array. This function will signal an error if the actual number of KDA transfers differs from the specified generic parameter 'N'. For example, to expect exactly 3 payments: 'let [payment_a, payment_b, payment_c] = self.call_value().multi_kda();' ```APIDOC multi_kda() -> [KdaTokenPayment; N] ``` -------------------------------- ### Creating, Signing, and Broadcasting Transactions in Go Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/go/page.mdx This snippet details the process of creating, signing, and broadcasting a simple transfer transaction on the KleverChain. It shows how to create a base transaction, customize its fee asset, retrieve a receiver's address from a PEM file, create the transfer transaction, sign it with the sender's wallet, and finally broadcast it to the network. ```Go // Send (transfer) example with fee payment in some KDA instead of KLV // Create a base transaction baseTransfer := acc.NewBaseTX() // Set a custom kda to kdaFee field on baseTX baseTransfer.KdaFee = "KDA-AB12" // Get the transfer receiver wallet and its account address rw, _ := wallet.NewWalletFromPEM("./path/to/receiver/wallet.pem") rAcc, _ := rw.GetAccount() // Create the transaction tx, err := kc.Send(baseTransfer, rAcc.Address().Bech32(), 10, "KLV") if err != nil { panic(err) } // Sign the transaction with the sender wallet err = tx.Sign(w) if err != nil { panic(err) } transferHash, err := tx.Broadcast(kc) if err != nil { panic(err) } fmt.Printf("Transfer transaction hash: %s\n", transferHash) ``` -------------------------------- ### Define Public Smart Contract Methods with `#[endpoint]` and `#[view]` Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/reference/annotations/page.mdx These annotations mark public methods of a contract, making them externally visible. While `#[view]` implies read-only, this is not strictly enforced but is useful for intent. The Rust method name is the default endpoint name, but an explicit name can be specified. Arguments and return types must be serializable or specific endpoint types. ```Rust #[klever_sc::contract] pub trait Example { #[endpoint] fn example(&self) { } #[endpoint(camelCaseEndpointName)] fn snake_case_method_name(&self, value: BigUint) { } fn private_method(&self, value: &BigUint) { } #[view(getData)] fn get_data(&self) -> u32{ 0 } } ``` -------------------------------- ### Define Crowdfunding Meta Package Dependencies Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/tutorials/crowdfunding/page.mdx Defines the `crowdfunding-meta` package and its dependency on the `crowdfunding` contract, specifying its local path for development. ```TOML [package] name = "crowdfunding-meta" [dependencies.crowdfunding] path = ".." ``` -------------------------------- ### Configure Crowdfunding Wasm Cargo.toml Dependencies Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/tutorials/crowdfunding/page.mdx Configures the `Cargo.toml` file for the `crowdfunding-wasm` package, declaring it as a dependency on the main `crowdfunding` contract, with its path relative to the current directory. ```toml # Wasm [package] name = "crowdfunding-wasm" [dependencies.crowdfunding] path = ".." ``` -------------------------------- ### Example Rust Struct Value for Serialization Source: https://github.com/klever-io/klever-docs/blob/develop/src/app/smart-contracts/data/custom-types/page.mdx Provides an example instance of `MyStruct` with specific values, illustrating the data structure before it undergoes serialization. ```Rust MyStruct { int: 0x42, seq: vec![0x1, 0x2, 0x3, 0x4, 0x5], another_byte: 0x6, uint_32: 0x12345, uint_64: 0x123456789, } ```