Front-end app: smart contract interaction

Learn how to query a contract's state and send signed transactions in your front-end application.

Intro

In this tutorial, you will learn how to make the front-end of your App interact with smart contracts using @polkadot/api-contractarrow-up-right, more specifically:

  • how to read values stored in your smart contract

  • how to send signed transactions to your smart contract

circle-info

Before we start, you may want to check out our Bulletin Board Examplearrow-up-right repository. It is a simple yet comprehensive tutorial dApp that can be used to learn more about writing smart contracts in ink! and how to build your first dApp on the Aleph Zero ecosystem, or simply bootstrap your project. All the code snippets in this tutorial come from this repository.

circle-info

It is also worth checking out the Aleph Zero Signer Integration tutorial: it could be a good starting point for you.

circle-info

For beginners: blocks like this contain some explanation about basic concepts. If you're an experienced developer, please feel free to skip them.

Connect to a deployed smart contract

circle-info

For beginners: when interacting with the blockchain, you actually connect to a single node running as part of the network. The states of the nodes are constantly being synchronized by the protocol, so it doesn't matter which node you connect to.

If you're using the public Aleph Zero endpoints described below, you connect to a single endpoint that serves as an umbrella for a few nodes run by the Aleph Zero Foundation: it will automatically choose the best endpoint.

The first step will be to create an API instance to connect to a running node. For that, we need a provider: the default instance of WsProvider connects to "ws://127.0.0.1:9944" which usually is your local node's endpoint. For Aleph Zero Testnet use "wss://ws.test.azero.dev" and for Aleph Zero Mainnet: "wss://ws.azero.dev".

import { ApiPromise, WsProvider } from '@polkadot/api';
...

const APP_PROVIDER_URL = "ws://127.0.0.1:9944";

const wsProvider = new WsProvider(APP_PROVIDER_URL);
const api = await ApiPromise.create({ provider: wsProvider });

The @polkadot/api-contract comes with 4 general helpers (see the docsarrow-up-right). Here, we are using ContractPromise which allows us to interact with already deployed contracts.

circle-info

For beginners: the contract's ABI (Application Binary Interface) is a JSON file describing, among other things, what methods are available, what selectors they have, what are the parameters and return types and so on. It also contains the docstrings you put in your code that will be displayed by the Contracts UIarrow-up-right if you choose to use it.

Importantly, the terms ABI and metadata are used interchangeably in this context.

To create the contract-api instance, we will need the contract's address and ABI. The contract ABI can be found in the artifacts generated when building the contract (see Creating your first contract).

Query a contract state

circle-info

For beginners: for the purpose of this tutorial, we can assume that an extrinsic is the same as a transaction that you send to the blockchain. If you want to read more, please refer to the Substrate documentation on extrinsicsarrow-up-right.

The concept of gas (fees for executing transactions) is approached slightly differently to what you may be used to from EVM-based chains: gas is a two-dimensional value and there's no concept of gas price (it is calculated based only on how much resources are used + an optional tip). To learn more, please refer to the Substrate documentation of transaction feesarrow-up-right.

Under the hood, querying a contract is an extrinsic dry run. It is not submitted on the chain, however, it requires to specify the gasLimit which refers to the maximum resources used by a contract call. Because we are not submitting an extrinsic to the chain (we're only performing a dry-run), it is safe to use sufficiently high values to ensure that the call won’t be reverted. For contract calls, Substrate uses a 2-dimensional weight (gas) system which consists of:

  • refTime: the amount of computational time used for execution, in picoseconds;

  • proofSize: the amount of storage in bytes that a transaction is allowed to read.

In this example, we call the contract method getByAccount which takes one argument accountId. For simplicity, we are using the contract address as the caller.

Contract query results in ContractCallOutcomearrow-up-right. If the query is successful, you can extract the return value from the output object. See how it can be done herearrow-up-right.

Send signed transaction to a contract

circle-info

For beginners: we can assume that, in the context of smart contracts, a signed transaction will be needed whenever we want to call a method that modifies the smart contract's state. These will be the methods that use &mut self as the first argument.

Signing account

To sign a transaction, we need a wallet. To keep this example simple, we will use @polkadot/extension-dapparrow-up-right to retrieve wallet providers added to the app page and assume that there’s at least one account. See the Aleph Zero Signer Integration tutorial for more information.

Gas estimation

To sign and send a transaction to a contract, we should estimate values for gasLimit. Although the unused gas is refunded after the call, it is good practice to specify a reasonable gasLimit for transactions. As shown here, this (gasRequired) can be estimated with contract.query.[method]. Here is an alternative way of how to do it using api.call.contractsApi.call<ContractExecResult>.

circle-exclamation
circle-info

For beginners: the term message below refers to the methods of the smart contract marked with the #[ink(message)] macro: these will be the contract's methods that are callable from outside of the contract. In most cases, the terms [contract] message and method will be used interchangeably.

The first step is to get AbiMessagearrow-up-right for the contract method. The function below searches for the method in the contract ABI and returns it if found.

The getGasLimit(...) function below estimates the gasRequired for this contract call which should be sufficient to cover the gas fees when submitting the actual extrinsic. There are also other contract call options which can be adjusted:

  • storageDepositLimit - The maximum amount of balance that can be charged/reserved for the storage consumed.

  • value - The balance (in native currency, AZERO in our case) to transfer from the caller to the contract. Non-zero values here apply only to methods marked with the #[ink(message, payable)] macro.

Sign and send the transaction

Function sendPost(...) puts all the pieces together. It calls the payable method on the contract post(expiresAfter: u32, postText: String) and handles the result.

To learn more about how to handle transaction events see Transaction Subscriptionsarrow-up-right. Also, see how it is done in the Bulletin Board Examplearrow-up-right.

circle-exclamation

Closing remarks

We hope that this tutorial helped you learn more about how to interact with smart contracts in the front-end application. You shouldn't stop here! Check out other resources that may help you extend your dApp:

Last updated

Was this helpful?