How to read smart contracts

Assets/Emergence/Samples/Examples/ReadingContracts.cs

In decentralized applications, you often need to interact with smart contracts to perform various operations, such as querying data or executing transactions. Reading smart contracts allows you to obtain information stored on the blockchain without modifying the contract's state. This is particularly useful when you need to display the data in your application or make decisions based on the contract's current state.

The example provided at the path above demonstrates how to read smart contracts using the EmergenceSDK in Unity. The example provided shows how to load a deployed contract, create a ContractInfo object, and call the ReadMethod to execute a smart contract method.

First, import the necessary namespaces:

using EmergenceSDK.Internal.Utils;
using EmergenceSDK.ScriptableObjects;
using EmergenceSDK.Services;
using EmergenceSDK.Types.Responses;
using UnityEngine;

These namespaces contain various utilities, scriptable objects, services, and response types needed to interact with the EmergenceSDK in Unity.

Next, define a new class called ContractTest, which inherits from MonoBehaviour. This allows you to attach this script to a GameObject in Unity.

public class ContractTest : MonoBehaviour
{
    // This must be set in the inspector
    public DeployedSmartContract deployedContract;
    
    // Public string array that is used as input data for the smart contract method
    public string[] data = new string[] { "1" };

    private IContractService contractService;

    ...
}

Declare the following variables:

  • deployedContract: A public DeployedSmartContract variable that must be set in the Unity inspector. There are examples that you can use in the sample project.

  • data: A public string array that serves as input data for the smart contract method, this will need to change based on the contract chosen.

  • contractService: A private IContractService 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 EmergenceServices class.

public void Awake()
{
    contractService = EmergenceServices.GetService<IContractService>();
}

The Start method is called at the beginning of the script's execution. Here, we call the ReadContract method to initiate the contract reading process.

public void Start()
{
    ReadContract();
}

The ReadContract method loads the contract using the deployedContract variable and calls the Load method once it's loaded.

public void ReadContract()
{
    contractService.LoadContract(deployedContract.contractAddress, deployedContract.contract.ABI, 
        deployedContract.contract.name, Load, ErrorLogger.LogError);
}

The Load method creates a ContractInfo object with the smart contract address, method name, network name, and default node URL. It then calls the ReadMethod method to execute the smart contract method defined in the ABI with the input data.

private void Load()
{
    var contractInfo = new ContractInfo(deployedContract.contractAddress, "[METHOD NAME]",
        deployedContract.chain.networkName, deployedContract.chain.DefaultNodeURL);

    contractService.ReadMethod<BaseResponse<string>, string[]>(contractInfo, data, ReadSuccess, ErrorLogger.LogError);
}

The ReadSuccess method is called when the ReadMethod method executes successfully. It logs the response to the console.

private void ReadSuccess<T>(T response)
{
    Debug.Log($"{response}");
}

By following this example, you can read smart contracts in your Unity project using the EmergenceSDK. The process involves loading a deployed contract, creating a ContractInfo object, and calling the ReadMethod to execute a smart contract method with the provided input data. This allows you to retrieve information from the smart contract without modifying its state, which is useful for displaying data in your application or making decisions based on the contract's current state.

Full code:

using EmergenceSDK.Internal.Utils;
using EmergenceSDK.ScriptableObjects;
using EmergenceSDK.Services;
using EmergenceSDK.Types.Responses;
using UnityEngine;

namespace EmergenceSDK
{
    public class ContractTest : MonoBehaviour
    {
        // This must be set in the inspector
        public DeployedSmartContract deployedContract;
        
        // Public string array that is used as input data for the smart contract method
        public string[] data = new string[] { "1" };

        private IContractService contractService;
        
        public void Awake()
        {
            contractService = EmergenceServices.GetService<IContractService>();
        }

        public void Start()
        {
            ReadContract();
        }

        public void ReadContract()
        {
            // Loads the contract using the deployedContract variable and calls the Load method once it's loaded
            contractService.LoadContract(deployedContract.contractAddress, deployedContract.contract.ABI, 
                deployedContract.contract.name, Load, ErrorLogger.LogError);
        }

        // This method is called once the contract is loaded
        private void Load()
        {
            // Creates a ContractInfo object with the smart contract address, method name, network name, and default node URL
            var contractInfo = new ContractInfo(deployedContract.contractAddress, "[METHOD NAME]",
                deployedContract.chain.networkName, deployedContract.chain.DefaultNodeURL);

            // Calls the ReadMethod method to execute the smart contract method defined in the ABI with an empty input parameter
            contractService.ReadMethod<BaseResponse<string>, string[]>(contractInfo, data, ReadSuccess, ErrorLogger.LogError);
        }

        // This method is called when the ReadMethod method executes successfully
        private void ReadSuccess<T>(T response)
        {
            // Logs the response to the console
            Debug.Log($"{response}");
        }
    }
}

Last updated