Skip to content

Interacting with Smart Contracts

Chain of Industry edited this page Dec 1, 2022 · 8 revisions

Interacting with Smart Contracts Instructions

Overview

This section shows you how to interact with Smart Contracts (SC) on MultiversX Blockchain. To interact with a SC, a user needs to be already connected. See the Connect Maiar section on how to connect the user wallet.

SC example

For example purpose the following Adder SC is used:

#![no_std]

elrond_wasm::imports!();

/// One of the simplest smart contracts possible,
/// it holds a single variable in storage, which anyone can increment.
#[elrond_wasm::derive::contract]
pub trait Adder 
{
    #[init]
    fn init(&self, initial_value: BigUint) 
    {
        self.sum().set(initial_value);
    }

    #[view(getSum)]
    #[storage_mapper("sum")]
    fn sum(&self) -> SingleValueMapper<BigUint>;

    /// Add desired amount to the storage variable.
    #[endpoint]
    fn add(&self, value: BigUint) 
    {
        self.sum().update(|sum| *sum += value);
    }
}

The contract needs to be published on MultiversX Network, and you can get its address from Elrond Explorer

A SC has 3 main methods types:

#[init] Called automatically when SC is first deployed.
#[view(methodName)] Used to query SC values. These methods do not require a transaction to call. They usually offer information about SC status and values stored.
#[endpont] SC execution methods. They can only be called inside a transaction.

Query a Smart Contract

To get any information about SC, a query needs to be performed

/// <summary>
/// Make a smart contract query
/// </summary>
/// <typeparam name="T">Query response type</typeparam>
/// <param name="scAddress">The address of the smart contract</param>
/// <param name="methodName">The method to call</param>
/// <param name="QueryComplete">Callback to get the result of the query after finished</param>
/// <param name="outputType">Type of expected result</param>
/// <param name="args">The list of arguments</param>        
public static void MakeSCQuery<T>(string scAddress, string methodName, UnityAction<OperationStatus, string, T> QueryComplete, TypeValue outputType, params IBinaryType[] args) where T : IBinaryType

To be more clear, here is a full example of usage:

//Method call. This will call the getSum method from the above SC
//If the method you are calling has no parameters, send null as a param 
MultiversXUnityTools.Manager.MakeSCQuery("erd1qqqqqqqqqqqqqpgqmm2m825y2t9nya0yqeg3nqlh2q50e7pd0eqq98uw2e", "getSum", QueryComplete, TypeValue.BigUintTypeValue);

/// <summary>
/// Triggered when Smart contract query is complete
/// </summary>
/// <param name="operationStatus">Completed, In progress or Error</param>
/// <param name="message">additional message</param>
/// <param name="data">deserialized returned data</param>
private void QueryComplete(OperationStatus operationStatus, string message, NumericValue data)
{
      if (operationStatus == OperationStatus.Complete)
      {
            scResultText.text = "Current sum: " + data;
      }
      else
      {
            scResultText.text = message;
      }
}

Call a Smart Contract Method

A Smart Contract method call will execute a code inside the Smart Contract. The data payload of the transaction delivers these calls to the blockchain so it needs to be signed by the user. From Unity, a SC call looks like this:

/// <summary>
/// Call a smart contract method
/// </summary>
/// <param name="scAddress">The address of the smart contract</param>
/// <param name="methodName">The method to call</param>
/// <param name="gas">The gas required to execute the called SC method</param>
/// <param name="CallStatus">Callback to get the result of the call</param>
/// <param name="args">The list of arguments. Can be:</param>
/// Address
/// BooleanValue
/// BytesValue
/// EnumValue
/// MultiValue
/// NumericValue
/// OptionValue
/// StructValue
/// TokenIdentifierValue
public static void CallSCMethod(string scAddress, string methodName, long gas, UnityAction<OperationStatus, string> CallStatus, params IBinaryType[] args)
 

A smart contract call works exactly like a simple transaction that, on success, results in contract execution.
For more details, here is a full example of calling the 'add' method from the example contract, adding 10 to the final sum. Around 1500000 gas units are needed to execute that method. See Gas Cost page for more details on what gas is and how to determine the required value.

//Method call
MultiversXUnityTools.Manager.CallSCMethod("erd1qqqqqqqqqqqqqpgqmm2m825y2t9nya0yqeg3nqlh2q50e7pd0eqq98uw2e", "add", 1500000, CallStatus, NumericValue.BigIntValue(10));

/// <summary>
/// Listener for the call response
/// </summary>
/// <param name="operationStatus">Completed, In progress or Error</param>
/// <param name="message">additional message</param>
private void CallStatus(MultiversXUnityTools.OperationStatus operationStatus, string message)
{
      if (operationStatus == MultiversXUnityTools.OperationStatus.Complete)
      {
            //on operation status Complete the message is the transaction hash
            txHash = message;
            Debug.Log("Tx Hash: " + txHash);
            //check the CheckTransactionStatus page for more info
            MultiversXUnityTools.Manager.CheckTransactionStatus(txHash, SCTransactionListener, 1);
      }
      if (operationStatus == MultiversXUnityTools.OperationStatus.Error)
      {
            //do something
      }
}


/// <summary>
/// Listener for the SC transaction status 
/// </summary>
/// <param name="operationStatus">Completed, In progress or Error</param>
/// <param name="message">additional message</param>
private void SCTransactionListener(MultiversXUnityTools.OperationStatus operationStatus, string message)
{
      if (operationStatus == MultiversXUnityTools.OperationStatus.Complete)
      {
             Manager.RefreshAccount();
      }
      else
      {
            //do something
      }
}

After CallSCMethod is called, the Maiar app receives a notification to sign the transaction. If the user approves the transaction, the signature will be automatically applied, and the transaction will be sent to the MultiversX Blockchain for processing. In this case, an operationStatus of Complete is received. If the user declines to sign or an error occurs, an operationStatus of Error is received.

With these two methods, you are able to interact with any SC from the MultiversX Blockchain. You just need to input the parameters accordingly.

This concludes the blockchain interaction section.

Check: All API Methods