### Complete SSE Client Example Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithSSE.md A comprehensive example demonstrating how to initialize the ServerEventsClient, register callbacks for various common event types, start listening, and gracefully stop the listener. ```csharp using System; using System.Threading.Tasks; using Casper.Network.SDK; using Casper.Network.SDK.SSE; using Casper.Network.SDK.Types; public class SseExample { public static async Task Main(string[] args) { var sse = new ServerEventsClient("127.0.0.1", 18101); sse.AddEventCallback(EventType.All, "all-events", (SSEvent evt) => { try { switch (evt.EventType) { case EventType.ApiVersion: Console.WriteLine($"API Version: {evt.Result.GetRawText()}"); break; case EventType.BlockAdded: var block = evt.Parse().Block; Console.WriteLine($"Block #{block.Height} — {block.Hash}"); break; case EventType.TransactionAccepted: var tx = evt.Parse(); Console.WriteLine($"Tx accepted: {tx.Hash}"); break; case EventType.TransactionProcessed: var txProc = evt.Parse(); Console.WriteLine($"Tx processed: {txProc.TransactionHash}"); break; case EventType.DeployAccepted: var deploy = evt.Parse(); Console.WriteLine($"Deploy accepted: {deploy.Hash}"); break; case EventType.DeployProcessed: var deployProc = evt.Parse(); Console.WriteLine($"Deploy processed: {deployProc.DeployHash}"); break; case EventType.FinalitySignature: var sig = evt.Parse(); Console.WriteLine($"Finality for block {sig.BlockHash}"); break; } } catch (Exception ex) { Console.WriteLine($"Error handling {evt.EventType}: {ex.Message}"); } }); sse.StartListening(); Console.WriteLine("Listening. Press Enter to stop."); Console.ReadLine(); await sse.StopListening(); } } ``` -------------------------------- ### Install Casper.Network.SDK via dotnet CLI Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/GettingStarted.md Use the dotnet CLI tool to add the Casper.Network.SDK package to your project on any operating system. ```bash dotnet add package Casper.Network.SDK ``` -------------------------------- ### Initialize Casper Client and Keys Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/counter-contract/README.md Sets up the connection to the Casper node and defines account keys for the example. Ensure PEM files for faucet and user accounts are correctly placed. ```csharp static string nodeAddress = "http://207.154.217.11:11101/rpc"; static string chainName = "casper-net-1"; static NetCasperClient casperSdk = new NetCasperClient(nodeAddress); static KeyPair faucetAcct = KeyPair.FromPem("/tmp/faucetact_sk.pem"); static KeyPair myAccount = KeyPair.FromPem("/tmp/myaccount_sk.pem"); static PublicKey myAccountPK = PublicKey.FromPem("/tmp/myaccount_pk.pem"); ``` -------------------------------- ### Install Casper.Network.SDK via Package Manager Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/GettingStarted.md Use this command in Visual Studio's Package Manager Console to add the SDK to your project. ```powershell Install-Package Casper.Network.SDK ``` -------------------------------- ### Build Casper .NET SDK in Release Mode Source: https://github.com/make-software/casper-net-sdk/blob/master/README.md Build the Casper .NET SDK library using the dotnet CLI. Requires .NET 5.0 or higher installed. ```bash dotnet build --configuration Release ``` -------------------------------- ### Start and Stop Listening for SSE Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithSSE.md Initiate listening for SSE events using StartListening(). This method blocks until StopListening() is called or the connection is lost. Ensure StopListening() is awaited. ```csharp sse.StartListening(); Console.WriteLine("Press Enter to stop listening..."); Console.ReadLine(); await sse.StopListening(); ``` -------------------------------- ### Real-World Example: Watching Multiple Contracts for Events Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/CasperEventStandard.md Loads schemas for two contracts, fetches a transaction, scans its execution result for emitted CES events, and processes a specific event. Includes serialization of all found events to JSON. ```csharp using System.Collections.Generic; using System.Linq; using System.Text.Json; using Casper.Network.SDK; using Casper.Network.SDK.CES; var client = new NetCasperClient("https://node.testnet.casper.network/rpc"); // Load the schema for each contract to watch var minterSchema = await CESContractSchema.LoadAsync( client, "hash-1262d06e53125ea098187fb4d1d5b10a7afed48e5e5eef182ed992fc5b100349"); var cep18Schema = await CESContractSchema.LoadAsync( client, "hash-17cb23ce7b6d663fc82bacbdd56a26dc722cabe7e69c84a3ca729bf3cb7fdc70"); // Fetch a transaction and extract its execution result transforms var getTxResult = await client.GetTransaction( "8e46a16fc8fc15c38405e092959fb20acc44dcfca1d1caecb9bc59d018f50df6"); var txResult = getTxResult.Parse(); // Scan for CES events emitted by either watched contract var events = CESParser.GetEvents( txResult.ExecutionInfo.ExecutionResult.Effect, new List { minterSchema, cep18Schema }); // Work with a specific event var buyEvent = events.FirstOrDefault(e => e.Name == "Buy"); if (buyEvent != null) { Console.WriteLine("Buy token: " + buyEvent["token"].ToGlobalStateKey()); Console.WriteLine("Buy amount: " + buyEvent["amount_token_out"].ToBigInteger()); } // Serialize all events to JSON var json = JsonSerializer.Serialize(events); Console.WriteLine(json); ``` -------------------------------- ### Querying Entity by Public Key Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithAddressableEntity.md Retrieve entity information using a public key. This example demonstrates how to initialize the Casper .NET SDK client, define a public key, and call GetEntity(). Error handling for RPC exceptions is included. ```csharp using System; using System.Threading.Tasks; using Casper.Network.SDK; using Casper.Network.SDK.JsonRpc; using Casper.Network.SDK.Types; public class EntityExample { public static async Task Main(string[] args) { var client = new NetCasperClient("http://127.0.0.1:11101/rpc"); var publicKey = PublicKey.FromHexString( "0184f6d260F4EE6869DDB36affe15456dE6aE045278FA2f467bb677561cE0daD55"); try { var response = await client.GetEntity(publicKey); var entity = response.Parse().Entity; Console.WriteLine($"Protocol version: {entity.ProtocolVersion}"); Console.WriteLine($"Main purse: {entity.MainPurse}"); Console.WriteLine($"Associated keys: {entity.AssociatedKeys.Count}"); Console.WriteLine($"Deployment threshold: {entity.ActionThresholds.Deployment}"); } catch (RpcClientException e) { Console.WriteLine($"RPC Error: {e.RpcError.Message}"); } } } ``` -------------------------------- ### Convert AccountHashKey to CLValue Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Use CLValue.Key() to convert a GlobalStateKey (specifically an AccountHashKey in this example) to a CLValue. This is used when passing keys to smart contracts. ```csharp var publicKey = PublicKey.FromPem("myPublicKey.pem"); var accountHash = new AccountHashKey(publicKey); var accountClValue = CLValue.Key(accountHash); ``` -------------------------------- ### Run NCTL in a Docker Container Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/RunningNctlLocally.md Starts an NCTL Docker container, publishing necessary ports for node communication. Use this to quickly set up a local Casper network environment. ```bash docker run --rm -it --name mynctl -d -p 11101:11101 -p 14101:14101 -p 18101:18101 makesoftware/casper-nctl ``` -------------------------------- ### Example CLValue for Boolean True Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Demonstrates the JSON structure of a CLValue representing a boolean true. ```json { "cl_type":"Bool", "bytes":"01", "parsed":true } ``` -------------------------------- ### Build and Send Native Transfer Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithTransactionV1.md Construct a native CSPR transfer transaction using Transaction.NativeTransferBuilder. This example demonstrates setting source, target, amount, chain name, and payment, then signing and sending the transaction. ```csharp using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Casper.Network.SDK; using Casper.Network.SDK.JsonRpc; using Casper.Network.SDK.Types; using Casper.Network.SDK.Utils; public class TransferExample { public static async Task Main(string[] args) { var client = new NetCasperClient("http://127.0.0.1:11101/rpc"); var chainName = "casper-net-1"; var sourceKey = KeyPair.FromPem("source_sk.pem"); var targetPK = PublicKey.FromPem("target_pk.pem"); var transaction = new Transaction.NativeTransferBuilder() .From(sourceKey.PublicKey) .Target(targetPK) .Amount(25_000_000_000) // 25 CSPR in motes .Id(DateUtils.ToEpochTime(DateTime.Now)) .ChainName(chainName) .Payment(100_000_000, 1) .Build(); transaction.Sign(sourceKey); var response = await client.PutTransaction(transaction); var txHash = response.GetTransactionHash(); Console.WriteLine($"Transaction sent: {txHash}"); // Wait for execution (up to 2 minutes) var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120)); var result = await client.GetTransaction(txHash, tokenSource.Token); var execResult = result.Parse().ExecutionInfo.ExecutionResult; Console.WriteLine($"Cost: {execResult.Cost}"); } } ``` -------------------------------- ### Getting Main Purse URef for Balance Queries Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithAddressableEntity.md Obtain the MainPurse URef for an entity to perform balance queries. This snippet shows how to get the entity information and then use its MainPurse to query the balance. ```csharp var response = await client.GetEntity(publicKey); var mainPurse = response.Parse().Entity.MainPurse; var balanceResponse = await client.QueryBalance(mainPurse); Console.WriteLine($"Balance: {balanceResponse.Parse().BalanceValue} motes"); ``` -------------------------------- ### Build the Key-Value Contract Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/kvstorage-contract/README.md Clone the repository and build the contract using make. This prepares the contract's WASM file for deployment. ```bash git clone https://github.com/casper-ecosystem/kv-storage-contract cd kv-storage-contract make build-contract ``` -------------------------------- ### Get Public Key from Key Pair Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/KeyManagement.md Access the public key associated with a loaded key pair using the `PublicKey` property. ```csharp var faucetPK = keypair.PublicKey; ``` -------------------------------- ### Create and Configure Console Application Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/GettingStarted.md Create a new console application, add the SDK package, and replace Program.cs with this code to connect to the Casper testnet and fetch the latest block height. ```csharp using System; using System.Threading.Tasks; using Casper.Network.SDK; using Casper.Network.SDK.JsonRpc; namespace GetStarted { class Program { static async Task Main(string[] args) { var client = new NetCasperClient("https://rpc.testnet.casperlabs.io/rpc"); try { var response = await client.GetBlock(); var block = response.Parse().Block; Console.WriteLine($"Latest block height: {block.Height}"); Console.WriteLine($"Block hash: {block.Hash}"); } catch (RpcClientException e) { Console.WriteLine($"RPC Error: {e.RpcError.Message}"); } } } } ``` -------------------------------- ### Resume Event Stream from Specific ID Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithSSE.md Initiate listening for BlockAdded events starting from a specified event ID. This is useful for resuming a disconnected stream. ```csharp sse.AddEventCallback(EventType.BlockAdded, "blocks", (SSEvent evt) => { // ... }, startFrom: 12345); ``` -------------------------------- ### Add Casper.Network.SDK Source Reference Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/GettingStarted.md Clone the SDK repository and add a project reference to the Casper.Network.SDK.csproj file. ```bash git clone https://github.com/make-software/casper-net-sdk.git cd your-project dotnet add reference ../casper-net-sdk/Casper.Network.SDK/Casper.Network.SDK.csproj ``` -------------------------------- ### Run the Console Application Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/GettingStarted.md Execute this command in your project directory to run the minimal console application. ```bash dotnet run ``` -------------------------------- ### Build and Deploy ERC-20 Contract Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/erc20-contract/README.md Clones the ERC-20 repository, builds the contract, and deploys it to the network using the Casper .NET SDK. Requires the contract Wasm file and account key pair. ```bash git clone https://github.com/casper-ecosystem/erc20 cd erc20 make prepare make build-contracts ``` -------------------------------- ### Parse TransactionAccepted Event Data (Casper 2.x) Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithSSE.md Handle the TransactionAccepted event on Casper 2.x nodes. This callback parses the SSEvent data into a Transaction object to get the transaction hash. ```csharp sse.AddEventCallback(EventType.TransactionAccepted, "tx-accepted", (SSEvent evt) => { var tx = evt.Parse(); Console.WriteLine($"Transaction accepted: {tx.Hash}"); }); ``` -------------------------------- ### Create Public Key from Raw Bytes with Algorithm Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/KeyManagement.md Create a `PublicKey` object from raw hexadecimal bytes and explicitly specify the algorithm using `FromRawBytes()`. ```csharp var pk2 = PublicKey.FromRawBytes("2629e6d0eed7db2d232b5b0a35d729796bb6f3cbd12811538a61de78c75870ba", KeyAlgo.ED25519); ``` ```csharp var pk3 = PublicKey.FromRawBytes("02793d6a3940502b0946bed65719d3e75d089a25b52a8fc740373c48a8031e83b3", KeyAlgo.SECP256K1); ``` -------------------------------- ### Build and Deploy Counter Contract Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/counter-contract/README.md Compiles the counter contract from its source and deploys the resulting WASM file to the Casper network. It requires the contract WASM file to be present in the working directory. ```bash git clone https://github.com/casper-ecosystem/counter cd counter make build-contract ``` ```csharp public static async Task DeployContract(string wasmFile) { var wasmBytes = await File.ReadAllBytesAsync(wasmFile); var deploy = DeployTemplates.ContractDeploy( wasmBytes, myAccount, 50_000_000_000, chainName); deploy.Sign(myAccount); var putResponse = await casperSdk.PutDeploy(deploy); var deployHash = putResponse.GetDeployHash(); var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120)); var getResponse = await casperSdk.GetDeploy(deployHash, tokenSource.Token); var execResult = getResponse.Parse().ExecutionResults.First(); Console.WriteLine("Deploy COST : " + execResult.Cost); Console.WriteLine("Contract key: " + execResult.Effect.Transforms.First(t => t.Type == TransformType.WriteContract).Key); } ``` -------------------------------- ### Sign a Transaction Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithTransactionV1.md After building a transaction, sign it using the initiator's private key with the `.Sign()` method. Additional approvals for multi-sig can be added using `.AddApproval()`. ```csharp transaction.Sign(keyPair); ``` -------------------------------- ### Create Named Arguments with PublicKey CLValue Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Shows how to create NamedArgs with a CLValue.PublicKey. This is used when public keys need to be passed as deploy arguments. ```csharp var arg1 = new NamedArg("value", pkClValue); ``` -------------------------------- ### Run Casper .NET SDK Tests for netstandard2.0 Source: https://github.com/make-software/casper-net-sdk/blob/master/README.md Run the SDK tests specifically targeting the netstandard2.0 framework. This is useful for compatibility checks. ```bash TEST_FRAMEWORK=netstandard2.0 dotnet test --filter 'TestCategory!~NCTL' ``` -------------------------------- ### Instantiate ServerEventsClient for Casper 1.x Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithSSE.md Create a ServerEventsClient instance to connect to a Casper 1.x node's event stream. Specify nodeVersion: 1 for Casper 1.x compatibility. ```csharp using Casper.Network.SDK.SSE; // Connect to a Casper 1.x node var sseV1 = new ServerEventsClient("127.0.0.1", 18101, nodeVersion: 1); ``` -------------------------------- ### Query Balance by Public Key Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/QueryingBalances.md Use this snippet to query an account's balance by its public key. Ensure the NetCasperClient is initialized with the correct RPC endpoint. ```csharp using System; using System.Threading.Tasks; using Casper.Network.SDK; using Casper.Network.SDK.JsonRpc; using Casper.Network.SDK.Types; public class BalanceExample { public static async Task Main(string[] args) { var client = new NetCasperClient("http://127.0.0.1:11101/rpc"); var publicKey = PublicKey.FromHexString( "0184f6d260F4EE6869DDB36affe15456dE6aE045278FA2f467bb677561cE0daD55"); try { var response = await client.QueryBalance(publicKey); var balance = response.Parse().BalanceValue; Console.WriteLine($"Balance: {balance} motes"); } catch (RpcClientException e) { Console.WriteLine($"RPC Error: {e.RpcError.Message}"); } } } ``` -------------------------------- ### Create Named Arguments with String Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Demonstrates creating NamedArgs where the value is a CLValue.String. This is a common pattern when constructing deploy arguments. ```csharp var namedArgs = new List() { new NamedArg("name", "Weekday"), new NamedArg("value", "Monday") }; ``` -------------------------------- ### Create New SECP256K1 Key Pair Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/KeyManagement.md Use `KeyPair.CreateNew()` with `KeyAlgo.SECP256K1` to generate a new SECP256K1 key pair. ```csharp var anotherKeyPair = KeyPair.CreateNew(KeyAlgo.SECP256K1); ``` -------------------------------- ### Create Named Arguments with AccountHashKey CLValue Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Shows how to create NamedArgs with a CLValue representing an AccountHashKey. This is used when passing account keys as deploy arguments. ```csharp var arg1 = new NamedArg("value", accountClValue); ``` -------------------------------- ### Configure Logging to Standard Output Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/counter-contract/README.md Sets up the Casper client to stream communication logs to the standard output console. This is useful for debugging network interactions. ```csharp LoggerStream = new StreamWriter(Console.OpenStandardOutput()) ``` -------------------------------- ### Deploy Session Code (WASM) Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithTransactionV1.md Use `Transaction.SessionBuilder` to deploy new session code (WASM). Provide the WASM bytes, runtime arguments, chain name, and payment details. The `.InstallOrUpgrade()` method is used for install/upgrade operations. ```csharp var wasmBytes = await File.ReadAllBytesAsync("contract.wasm"); var runtimeArgs = new List { new NamedArg("name", "MyToken"), new NamedArg("symbol", "MTK") }; var transaction = new Transaction.SessionBuilder() .From(deployerKey.PublicKey) .Wasm(wasmBytes) .RuntimeArgs(runtimeArgs) .ChainName(chainName) .Payment(2_500_000_000, 1) .Build(); ``` ```csharp var transaction = new Transaction.SessionBuilder() .From(deployerKey.PublicKey) .Wasm(wasmBytes) .InstallOrUpgrade() .RuntimeArgs(runtimeArgs) .ChainName(chainName) .Payment(2_500_000_000, 1) .Build(); ``` -------------------------------- ### Deploy ERC-20 Contract in C# Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/erc20-contract/README.md Deploys the compiled ERC-20 contract Wasm to the Casper network. Initializes the contract with name, symbol, decimals, and total supply. Requires the contract Wasm file and an account key pair. ```csharp public static async Task DeployERC20Contract(KeyPair accountKey) { var wasmFile = "./erc20_token.wasm"; var wasmBytes = System.IO.File.ReadAllBytes(wasmFile); var header = new DeployHeader() { Account = accountKey.PublicKey, Timestamp = DateUtils.ToEpochTime(DateTime.UtcNow), Ttl = 1800000, ChainName = chainName, GasPrice = 1 }; var payment = new ModuleBytesDeployItem(300_000_000_000); List runtimeArgs = new List(); runtimeArgs.Add(new NamedArg("name", "C# SDK Token")); runtimeArgs.Add(new NamedArg("symbol", "CSSDK")); runtimeArgs.Add(new NamedArg("decimals", (byte) 5)); //u8 runtimeArgs.Add(new NamedArg("total_supply", CLValue.U256(10_000))); var session = new ModuleBytesDeployItem(wasmBytes, runtimeArgs); var deploy = new Deploy(header, payment, session); deploy.Sign(accountKey); await casperSdk.PutDeploy(deploy); var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120)); var deployResponse = await casperSdk.GetDeploy(deploy.Hash, tokenSource.Token); var execResult = deployResponse.Parse().ExecutionResults.First(); Console.WriteLine("Deploy COST : " + execResult.Cost); var contractHash = execResult.Effect.Transforms.First(t => t.Type == TransformType.WriteContract).Key; Console.WriteLine("Contract key: " + contractHash); File.WriteAllText("res_DeployERC20Contract.json", deployResponse.Result.GetRawText()); return (HashKey) contractHash; } ``` -------------------------------- ### Create CLValue Boolean Objects Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Shows how to explicitly create CLValue objects for boolean true and false using the SDK. ```csharp var clTrue = CLValue.Bool(true); var clFalse = CLValue.Bool(false); ``` -------------------------------- ### Format Account Info JSON with jq Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/kvstorage-contract/README.md Uses the 'jq' command-line tool to pretty-print the JSON output from the GetAccountInfo call, making it more readable. ```bash cat res_GetAccountInfo.json | jq ``` -------------------------------- ### Querying Entity by Account Hash Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithAddressableEntity.md Fetch entity details using an AccountHashKey. This snippet shows the initialization of an AccountHashKey and its use with the GetEntity() method. ```csharp var accountHash = new AccountHashKey("account-hash-56befc13a6fd62e18f361700a5e08f966901c34df8041b36ec97d54d605c23de"); var response = await client.GetEntity(accountHash); var entity = response.Parse().Entity; ``` -------------------------------- ### Create NamedArg with BigInteger for Payment Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Illustrates creating a NamedArg for payment using a BigInteger representing 3 CSPR. ```csharp var payment = new NamedArg("payment", new BigInteger(3_000_000_000)); ``` -------------------------------- ### Reference Contracts by Name, Package Hash, or Package Name Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithTransactionV1.md When calling stored contracts, you can reference them using different methods besides by hash. Use `.ByName()`, `.ByPackageHash()`, or `.ByPackageName()` to specify the contract. ```csharp // By contract name (stored in the caller's named keys) .ByName("my_contract") // By package hash, optionally specifying a version .ByPackageHash("hash-...", version: 1) // By package name .ByPackageName("my_package", version: 1) ``` -------------------------------- ### Add Multiple Event Callbacks Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithSSE.md Subscribe to multiple event types, such as DeployAccepted and DeployProcessed, using bitwise flags. Alternatively, use EventType.All to subscribe to all events. ```csharp sse.AddEventCallback( EventType.DeployAccepted | EventType.DeployProcessed, "deploy-cb", (SSEvent evt) => { Console.WriteLine($"Deploy event: {evt.EventType}"); }); ``` -------------------------------- ### Deploy Key-Value Storage Contract Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/kvstorage-contract/README.md Deploys the compiled WASM contract to the Casper network using the ContractDeploy template. It signs the deploy and sends it, then retrieves the contract hash from the execution results. ```csharp public static async Task DeployKVStorageContract() { var wasmFile = "./contract.wasm"; var wasmBytes = System.IO.File.ReadAllBytes(wasmFile); var deploy = DeployTemplates.ContractDeploy( wasmBytes, myAccountPK, 300_000_000_000, chainName); deploy.Sign(myAccount); var response = await casperSdk.PutDeploy(deploy); string deployHash = response.GetDeployHash(); var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120)); var deployResponse = await casperSdk.GetDeploy(deployHash, tokenSource.Token); var execResult = deployResponse.Parse().ExecutionResults.First(); Console.WriteLine("Deploy COST : " + execResult.Cost); var contractHash = execResult.Effect.Transforms.First(t => t.Type == TransformType.WriteContract).Key; Console.WriteLine("Contract key: " + contractHash); return (HashKey)contractHash; } ``` -------------------------------- ### Write Private Key to PEM File Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/KeyManagement.md Save a newly created key pair's private key to a PEM file for future use using the `WriteToPem()` method. ```csharp newKeyPair.WriteToPem("newED25519_sk.pem"); ``` ```csharp anotherKeyPair.WriteToPem("newSECP256K1_sk.pem"); ``` -------------------------------- ### Run Casper .NET SDK Tests (excluding NCTL) Source: https://github.com/make-software/casper-net-sdk/blob/master/README.md Execute the SDK's unit and integration tests, filtering out tests categorized as NCTL. This command is suitable for general testing. ```bash dotnet test --filter 'TestCategory!~NCTL' ``` -------------------------------- ### Create Named Arguments with AccountHashKey Object Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Demonstrates creating NamedArgs directly with an AccountHashKey object. The SDK will automatically convert it to a CLValue.Key. ```csharp var arg2 = new NamedArg("value", accountHash); ``` -------------------------------- ### Read Public Key from PEM File Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/KeyManagement.md Load a public key from a PEM file using the `PublicKey.FromPem()` method. Ensure the file path is correct. ```csharp var pk = PublicKey.FromPem("/tmp/my_pk.pem"); ``` -------------------------------- ### Create Public Key from Hex String with Prefix Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/KeyManagement.md Construct a `PublicKey` object from a hexadecimal string that includes the algorithm identifier prefix as the first byte, using `FromHexString()`. ```csharp var pk = PublicKey.FromHexString("012629e6d0eed7db2d232b5b0a35d729796bb6f3cbd12811538a61de78c75870ba"); ``` -------------------------------- ### Create Named Arguments with CLValue List Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Shows how to create NamedArgs where the value is a CLValue.List. This is used when passing lists of data as deploy arguments. ```csharp var namedArgs = new List() { new NamedArg("name", "MyListOfBytes"), new NamedArg("value", list) }; ``` -------------------------------- ### Retrieve Account Information Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/kvstorage-contract/README.md Fetches and saves the account information, which includes the named keys associated with the account. This is useful for verifying contract deployment and retrieving contract hashes. ```csharp public async static Task GetAccountInfo() { var response = await casperSdk.GetAccountInfo(myAccountPK); File.WriteAllText("res_GetAccountInfo.json", response.Result.GetRawText()); } ``` -------------------------------- ### Create CLValue Numeric Objects Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Demonstrates explicit creation of CLValue objects for various signed and unsigned integer types. ```csharp var myI32 = CLValue.I32(int.MinValue); var myI64 = CLValue.I64(long.MaxValue); var myU8 = CLValue.U8(0x7F); var myU32 = CLValue.U32(0); var myU64 = CLValue.U64(ulong.MaxValue); ``` -------------------------------- ### Create Named Arguments with Byte Array CLValue Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Shows how to create NamedArgs with a CLValue.ByteArray. This is used when passing byte array data as deploy arguments. ```csharp var arg1 = new NamedArg("value", clValue); ``` -------------------------------- ### Build a Native Activate Bid Transaction Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithTransactionV1.md Use `Transaction.NativeActivateBidBuilder` to activate a validator's bid. This transaction requires the validator's public key, chain name, and payment details. No amount is specified as it activates an existing bid. ```csharp var transaction = new Transaction.NativeActivateBidBuilder() .From(validatorKey.PublicKey) .Validator(validatorKey.PublicKey) .ChainName(chainName) .Payment(2_500_000_000, 1) .Build(); ``` -------------------------------- ### Create Named Arguments with PublicKey Object Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Demonstrates creating NamedArgs directly with a PublicKey object. The SDK will automatically convert it to a CLValue.PublicKey. ```csharp var arg2 = new NamedArg("value", publicKey); ``` -------------------------------- ### Send and Monitor a Transaction Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithTransactionV1.md Send a signed transaction to the network using `client.PutTransaction()`. Monitor its execution status by polling `client.GetTransaction()` with a timeout using `CancellationTokenSource`. ```csharp var putResponse = await client.PutTransaction(transaction); var txHash = putResponse.GetTransactionHash(); var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120)); var getResponse = await client.GetTransaction(txHash, tokenSource.Token); var execInfo = getResponse.Parse().ExecutionInfo; Console.WriteLine($ ``` -------------------------------- ### Read Key Pair from PEM File Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/KeyManagement.md Load a key pair from a PEM file using the `KeyPair.FromPem()` method. This is useful for accessing private keys. ```csharp var keypair = KeyPair.FromPem("/tmp/faucetact.pem"); ``` -------------------------------- ### Fund Account with CSPR Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/counter-contract/README.md Initiates a standard transfer of 2500 CSPR from a faucet account to a user account. It signs the deploy, sends it to the network, and polls for completion for up to 120 seconds. ```csharp public static async Task FundAccount() { var deploy = DeployTemplates.StandardTransfer( faucetAcct.PublicKey, myAccountPK, 2500_000_000_000, 100_000_000, chainName); deploy.Sign(faucetAcct); var putResponse = await casperSdk.PutDeploy(deploy); var deployHash = putResponse.GetDeployHash(); var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120)); var getResponse = await casperSdk.GetDeploy(deployHash, tokenSource.Token); var execResult = getResponse.Parse().ExecutionResults.First(); Console.WriteLine("Deploy COST : " + execResult.Cost); } ``` -------------------------------- ### Query Balance Details Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/QueryingBalances.md Retrieve detailed balance information, including total balance, available balance, and total holds, for an account. This uses the `QueryBalanceDetails()` method. ```csharp var response = await client.QueryBalanceDetails(publicKey); var details = response.Parse(); Console.WriteLine($"Total balance: {details.TotalBalance}"); Console.WriteLine($"Available balance: {details.AvailableBalance}"); Console.WriteLine($"Total holds: {details.TotalHolds}"); ``` -------------------------------- ### Set PaymentLimited Mode Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithTransactionV1.md Use the .Payment() method to automatically select PaymentLimited mode for transactions targeting live networks. This method specifies the maximum payment amount and gas price tolerance. ```csharp // PaymentLimited: pay up to 2.5 billion motes, tolerate gas price up to 1 .Payment(2_500_000_000, 1) ``` -------------------------------- ### Run Casper .NET SDK Integration Tests with NCTL Source: https://github.com/make-software/casper-net-sdk/blob/master/README.md Execute integration tests that require a running Casper NCTL network. Ensure the NCTL network is active and nodes are emitting blocks before running. ```bash dotnet test --settings Casper.Network.SDK.Test/test.runsettings --filter 'TestCategory~NCTL' ``` -------------------------------- ### Create Named Arguments with CLValue Map Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Shows how to create NamedArgs where the value is a CLValue.Map. This is used when passing maps of data as deploy arguments. ```csharp var namedArgs = new List() { new NamedArg("name", "MyMap"), new NamedArg("value", map) }; ``` -------------------------------- ### Create Named Arguments with C# Byte Array Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Demonstrates creating NamedArgs directly with a C# byte array. The SDK will automatically convert it to a CLValue.ByteArray. ```csharp var arg2 = new NamedArg("value", bytes); ``` -------------------------------- ### Create New ED25519 Key Pair Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/KeyManagement.md Use `KeyPair.CreateNew()` with `KeyAlgo.ED25519` to generate a new ED25519 key pair. ```csharp var newKeyPair = KeyPair.CreateNew(KeyAlgo.ED25519); ``` -------------------------------- ### Query Balance by Addressable Entity Key (Casper 2.0) Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/QueryingBalances.md Query the balance of a Casper 2.0 entity (account or smart contract) using its entity key. This is the recommended method for Casper 2.0 networks. ```csharp var entityKey = new AddressableEntityKey( "entity-account-56befc13a6fd62e18f361700a5e08f966901c34df8041b36ec97d54d605c23de"); var response = await client.QueryBalance(entityKey); Console.WriteLine($"Entity balance: {response.Parse().BalanceValue} motes"); ``` -------------------------------- ### Create Named Arguments with URef CLValue Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Shows how to create NamedArgs with a CLValue.URef. This is used when URefs need to be passed as deploy arguments. ```csharp var arg3 = new NamedArg("value", urefClValue); ``` -------------------------------- ### Parse DeployAccepted Event Data Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithSSE.md Register a callback to handle the DeployAccepted event and parse the SSEvent data into a DeployAccepted object to retrieve the deploy hash. ```csharp sse.AddEventCallback(EventType.DeployAccepted, "deploy-accepted", (SSEvent evt) => { var deploy = evt.Parse(); Console.WriteLine($"Deploy accepted: {deploy.Hash}"); }); ``` -------------------------------- ### Store a String Value Using Contract Hash Key Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/kvstorage-contract/README.md Stores a string value in the contract using its hash key, which is necessary when deploying from a different account. Requires the contract hash, entry point, and named arguments. ```csharp public async static Task StoreString(HashKey contractHash = null) { var namedArgs = new List() { new NamedArg("name", "WorkingOn"), new NamedArg("value", "Casper .NET SDK") }; var deploy = DeployTemplates.ContractCall(contractHash, "store_string", namedArgs, myAccountPK, 500_000_000, chainName); deploy.Sign(myAccount); var response = await casperSdk.PutDeploy(deploy); var deployHash = response.GetDeployHash(); var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120)); var deployResponse = await casperSdk.GetDeploy(deployHash, tokenSource.Token); File.WriteAllText("res_StoreString.json", deployResponse.Result.GetRawText()); } // Main method // await StoreString(contractHash); ``` -------------------------------- ### Run Casper .NET SDK Integration Tests for netstandard2.0 with NCTL Source: https://github.com/make-software/casper-net-sdk/blob/master/README.md Execute integration tests targeting the netstandard2.0 framework, requiring a running Casper NCTL network. Ensure the NCTL network is active. ```bash TEST_FRAMEWORK=netstandard2.0 dotnet test --settings Casper.Network.SDK.Test/test.runsettings --filter 'TestCategory~NCTL' ``` -------------------------------- ### Instantiate ServerEventsClient for Casper 2.x Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithSSE.md Create a ServerEventsClient instance to connect to a Casper 2.x node's event stream. The default port is 18101. ```csharp using Casper.Network.SDK.SSE; // Connect to a Casper 2.x node (default) var sse = new ServerEventsClient("127.0.0.1", 18101); ``` -------------------------------- ### Query Contract Cost from JSON Response Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/kvstorage-contract/README.md Uses jq to extract the cost from a JSON deploy response file. This is a command-line utility for processing JSON. ```bash cat res_StoreI32.json | jq | grep "cost" ``` -------------------------------- ### Query Balance by Account Hash Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/QueryingBalances.md Retrieve an account's balance using its account hash. This identifier is derived from the account's public key. ```csharp var accountHash = new AccountHashKey("account-hash-56befc13a6fd62e18f361700a5e08f966901c34df8041b36ec97d54d605c23de"); var response = await client.QueryBalance(accountHash); Console.WriteLine($"Balance: {response.Parse().BalanceValue} motes"); ``` -------------------------------- ### Store an Integer Value in KV Storage Contract Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/kvstorage-contract/README.md Calls the 'store_i32' entry point of the kvstorage_contract to store an integer. Requires the Casper SDK and a list of NamedArgs. ```csharp public async static Task StoreI32() { var namedArgs = new List() { new NamedArg("name", "I32MinValue"), new NamedArg("value", int.MinValue) }; await StoreKeyValue("store_i32", namedArgs, "res_StoreI32.json"); } ``` ```csharp private async static Task StoreKeyValue(string entryPoint, List namedArgs, string saveToFile) { var deploy = DeployTemplates.ContractCall("kvstorage_contract", entryPoint, namedArgs, myAccountPK, 1_000_000_000, chainName); deploy.Sign(myAccount); var response = await casperSdk.PutDeploy(deploy); var deployHash = response.GetDeployHash(); var tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(120)); var deployResponse = await casperSdk.GetDeploy(deployHash, tokenSource.Token); if (saveToFile != null) File.WriteAllText(saveToFile, deployResponse.Result.GetRawText()); } ``` -------------------------------- ### Legacy GetBalance Method Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/QueryingBalances.md Use the legacy `GetBalance()` method to directly call the `state_get_balance` RPC method, useful for querying with a specific state root hash. ```csharp var response = await client.GetBalance("uref-...-007", stateRootHash: "..."); Console.WriteLine($"Balance: {response.Parse().BalanceValue}"); ``` -------------------------------- ### Build Transfer with Optional Parameters Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithTransactionV1.md Customize a native transfer by specifying an alternative source purse using URef or a different target entity type like AccountHashKey. An optional transfer ID can also be set for idempotency. ```csharp var transaction = new Transaction.NativeTransferBuilder() .From(sourceKey.PublicKey) .Source(new URef("uref-...-007")) .Target(new AccountHashKey(targetPK)) .Amount(1_000_000_000) .Id(42) .ChainName(chainName) .Payment(100_000_000, 1) .Build(); ``` -------------------------------- ### Check ERC20 Balance with Error Handling Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/erc20-contract/README.md Use this snippet to query an account's balance from an ERC20 contract. It includes a try-catch block to handle potential `RpcClientException` errors, specifically identifying when an allowance or balance entry is not found. ```csharp try { var response = await casperSdk.GetDictionaryItemByContract(contractHash, "balances", dictItem); File.WriteAllText("res_ReadBalance.json", response.Result.GetRawText()); var result = response.Parse(); var balance = result.StoredValue.CLValue.ToBigInteger(); Console.WriteLine("Balance: " + balance.ToString() + " $CSSDK"); } catch (RpcClientException e) { if (e.RpcError.Code == -32003) Console.WriteLine("Allowance not found!"); else throw; } ``` -------------------------------- ### Accessing EraEnd from BlockV1 Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/Casper20MigrationGuide.md Shows how to retrieve the EraEnd object specifically from a BlockV1 instance, which is necessary when dealing with pre-Casper 2.0 blocks. ```csharp if (block.Version == 1) { var blockv1 = (BlockV1)block; var eraEnd = blockv1.Header.EraEnd; // ... } ``` -------------------------------- ### Configure Logging to File Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/counter-contract/README.md Configures the Casper client to append communication logs to a specified file ('netcasper.log'). This is useful for persistent logging and analysis. ```csharp LoggerStream = File.AppendText("netcasper.log") ``` -------------------------------- ### Write Public Key to PEM File Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/KeyManagement.md Save a public key to a PEM file. This can be done directly from a key pair or from a `PublicKey` object. ```csharp newKeyPair.WritePublicKeyToPem("newED25519_pk.pem"); ``` ```csharp newKeyPair.PublicKey.WriteToPem("newED25519_pk2.pem"); ``` -------------------------------- ### Create NamedArg with CLValue U512 for Payment Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Shows how to create a NamedArg for payment using a CLValue U512 object representing 3 CSPR. ```csharp var payment = new NamedArg("payment", cspr3); ``` -------------------------------- ### Recovering Versioned Block Objects Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/Casper20MigrationGuide.md Demonstrates how to cast a generic Block object to its specific version (BlockV1 or BlockV2) based on its Version property for detailed access. ```csharp if (block.Version == 2) { var blockv2 = (BlockV2)block; // ... } else if (block.Version == 1) { var blockv1 = (BlockV1)block; // ... } ``` -------------------------------- ### Build a Native Delegate Transaction Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithTransactionV1.md Use `Transaction.NativeDelegateBuilder` to construct a transaction for delegating tokens to a validator. Ensure all required parameters like delegator, validator, amount, chain name, and payment are provided. ```csharp var transaction = new Transaction.NativeDelegateBuilder() .From(delegatorKey.PublicKey) .Validator(validatorKey.PublicKey) .Amount(500_000_000_000) .ChainName(chainName) .Payment(2_500_000_000, 1) .Build(); ``` -------------------------------- ### Create Named Arguments with URef Object Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Demonstrates creating NamedArgs directly with a URef object. The SDK will automatically convert it to a CLValue.URef. ```csharp var arg4 = new NamedArg("value", uref); ``` -------------------------------- ### Query Balance at Specific Block Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/QueryingBalances.md Query an account's balance at a specific block by providing either the block hash or block height. Defaults to the latest block if not specified. ```csharp // By block hash var response = await client.QueryBalance(publicKey, "block-hash-..."); // By block height var response = await client.QueryBalance(publicKey, 12345UL); ``` -------------------------------- ### Call a Stored Contract Entry Point Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithTransactionV1.md Use `Transaction.ContractCallBuilder` to invoke an entry point in a stored contract. Specify the contract by hash, name, or package, along with the entry point and runtime arguments. ```csharp var runtimeArgs = new List { new NamedArg("recipient", CLValue.Key(new AccountHashKey(recipientPK))), new NamedArg("amount", CLValue.U256(100)) }; var transaction = new Transaction.ContractCallBuilder() .From(senderKey.PublicKey) .ByHash("hash-deadbeef...") .EntryPoint("transfer") .RuntimeArgs(runtimeArgs) .ChainName(chainName) .Payment(2_500_000_000, 1) .Build(); ``` -------------------------------- ### Read ERC-20 Token Balance in C# Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Tutorials/erc20-contract/README.md Reads the balance of ERC-20 tokens for a given public key by querying the 'balances' dictionary of the deployed contract. Requires the contract hash and the public key of the account. ```csharp public static async Task ReadBalance(string contractHash, PublicKey publicKey) { var accountHash = new AccountHashKey(publicKey); var dictItem = Convert.ToBase64String(accountHash.GetBytes()); var response = await casperSdk.GetDictionaryItemByContract(contractHash, "balances", dictItem); File.WriteAllText("res_ReadBalance.json", response.Result.GetRawText()); var result = response.Parse(); var balance = result.StoredValue.CLValue.ToBigInteger(); Console.WriteLine("Balance: " + balance.ToString() + " $CSSDK"); } ``` -------------------------------- ### Handle Step Events Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithSSE.md Register a callback for Step events to log the number of transforms associated with the event. ```csharp sse.AddEventCallback(EventType.Step, "steps", (SSEvent evt) => { var step = evt.Parse(); Console.WriteLine($"Step event with {step.Effect.Count} transforms"); }); ``` -------------------------------- ### Build a Native Withdraw Bid Transaction Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithTransactionV1.md Use `Transaction.NativeWithdrawBidBuilder` to create a transaction for withdrawing a validator's bid. Provide the validator's public key, the amount to withdraw, chain name, and payment information. ```csharp var transaction = new Transaction.NativeWithdrawBidBuilder() .From(validatorKey.PublicKey) .Validator(validatorKey.PublicKey) .Amount(500_000_000_000) .ChainName(chainName) .Payment(2_500_000_000, 1) .Build(); ``` -------------------------------- ### Create CLValue U512 for CSPR Amount Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Shows how to create a CLValue for a CSPR amount using U512 and BigInteger, representing 3 CSPR. ```csharp var cspr3 = CLValue.U512(3_000_000_000); ``` -------------------------------- ### Query Balance by Purse URef Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/QueryingBalances.md Query an account's balance directly using its main purse URef. This method is useful when the URef is already known. ```csharp var mainPurse = new URef("uref-0d0b57865e41b9e39170c038993997af432f66545f56838f1bf602c6d56e0e54-007"); var response = await client.QueryBalance(mainPurse); Console.WriteLine($"Purse balance: {response.Parse().BalanceValue} motes"); ``` -------------------------------- ### Create NamedArg with C# Integer Type Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Shows how to use a C# native integer type directly when creating a NamedArg for contract input. ```csharp var i32Arg = new NamedArg("value", int.MinValue); ``` -------------------------------- ### Convert PublicKey to CLValue Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Use CLValue.PublicKey() to convert a PublicKey object to a CLValue. This is necessary when passing public key information to smart contracts. ```csharp var publicKey = PublicKey.FromPem("myPublicKey.pem"); var pkClValue = CLValue.PublicKey(publicKey); ``` -------------------------------- ### Create CLValue List Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithCLValue.md Use CLValue.List() to create a CLValue of type List, populated with an array of CLValues of the same type. This is used for ordered collections. ```csharp var list = CLValue.List(new[] {CLValue.U8(0x10), CLValue.U8(0x20), CLValue.U8(0x30), CLValue.U8(0x40)}); ``` -------------------------------- ### Querying Entity at a Specific Block Source: https://github.com/make-software/casper-net-sdk/blob/master/Docs/Articles/WorkingWithAddressableEntity.md Fetch entity state at a particular block, either by providing a block hash or a block height. This allows for historical state inspection. ```csharp // By block hash var response = await client.GetEntity(publicKey, "block-hash-..."); // By block height var response = await client.GetEntity(publicKey, 12345UL); ```