Skip to main content

dApp Usage

Here are some examples of how to use the Massa Web3 API for dApp development.

Calling a smart contract

Full code of the Age dApp is available here.

The age smart contract stores the name and age of persons. This snippets shows how to call the smart contract and change the age value of Alice.

After creating a react app and setting up the Massa Web3 API as described in the installation section, we can call the smart contract method changeAge like this:

let args = new Args().addString(inputName).addU32(newAge);
let opId = await client.smartContracts().callSmartContract({
targetAddress: CONTRACT_ADDRESS,
targetFunction: "changeAge",
parameter: args.serialize(),
maxGas: BigInt(1000000),
coins: BigInt(0),
fee: BigInt(0),
});

Github redirection

Since that method requires a string and an integer as parameters, we need to serialize them first. The Args class provides a convenient way to do that. You can learn more about Args via the source code and its usage with the examples.

Reading a smart contract value

You can directly read smart contract datastore values with the readSmartContractData method, which does not require any gas or fee:

const res = await client.smartContracts().readSmartContract({
maxGas: BigInt(1000000),
targetAddress: CONTRACT_ADDRESS,
targetFunction: "getAge",
parameter: new Args().addString(inputName).serialize(),
});

const age = res.returnValue;
info

Since the getAge method doesn't change the state of the smart contract, we don't need to use a client with an account linked to it.