How to write to a smart contract
EmergenceSDK/Samples/CoreSamples/Scripts/Examples/WritingContracts.cs
Writing to smart contracts is an essential part of interacting with decentralized applications. It allows you to modify the state of the contract by executing transactions and invoking methods that change the data stored on the blockchain. This is useful when you need to store new information, update existing data, or execute specific functions within your application.
The example provided at the path above demonstrates how to write to smart contracts using the EmergenceSDK in Unity. The provided example shows how to create a ContractInfo
object, and call the WriteMethod
to execute a smart contract method with the provided input data.
First, import the necessary namespaces:
These namespaces contain various utilities, scriptable objects and services needed to interact with the EmergenceSDK in Unity.
Next, define a new class called WritingContracts
, which inherits from MonoBehaviour
. This allows you to attach this script to a GameObject in Unity.
Declare the following variables:
deployedContract
: A publicDeployedSmartContract
variable that must be set in the Unity inspector. There are examples that you can use in the sample project.body
: A public string array that serves as input data for the smart contract method, this will need to change based on the contract chosen.value
: A public string that serves as input data for the smart contract method, this will need to change based on the contract chosen.contractService
: A privateIContractService
variable for interacting with the contract-related services provided by EmergenceSDK.
In the Awake
method, initialize the contractService
variable by getting the IContractService
instance from the EmergenceServiceProvider
class.
The Start
method is called at the beginning of the script's execution. Here, we call the WriteContract
method to initiate the contract writing process.
The WriteContract
method creates ContractInfo using the deployedContract
variable and calls contractService.WriteMethod once its created. ContractService.WriteMethod takes a callback method to be used upon successful contract write. We'll use OnWriteSuccess for this.
The OnWriteSuccess
method is called when the WriteMethod
method executes successfully. It logs the response to the console.
By following this example, you can write to smart contracts in your Unity project using the EmergenceSDK. The process involves creating a ContractInfo
object, and calling the WriteMethod
to execute a smart contract method with the provided input data. This allows you to modify the contract's state, store new information, update existing data, or execute specific functions within your application.
Full code:
Last updated