zubayr khalid
zubayr khalid

Reputation: 13

React interact with Ink! contract

I am trying to interact with a simple flipper contract written in rust ink! and deployed in local node in substrate chain. I am running the substrate local node as well.

I have the default flipper contract with get and flip functions.

I have started the substrate local node and deployed the contract there. I have also copied the contract abi json in react folder.

so note: the contract is deployed in localnode in substrate chain and the localnode is started.

The code in brief is:

    const CONTRACT_ADDRESS = "...";

    const [modalOpen, setModalOpen] = useState(false);
    const [account, setAccount] = useState(null);
    const [api, setApi] = useState(null);
    const [contract, setContract] = useState(null);

    const handleWalletConnect = async (walletType) => {
    if (walletType === "polkadot") {
        try {
        const extensions = await web3Enable("BitCross.fi");
        if (extensions.length === 0) {
            setAccount(-1);
            setModalOpen(false);
        }

        const accounts = await web3Accounts();
        if (accounts.length > 0) {
            const account = accounts[0];
            setAccount(account.address);
            sessionStorage.setItem("account_address", account.address);
            setModalOpen(false);

            const wsProvider = new WsProvider("ws://127.0.0.1:9944");
            const api = await ApiPromise.create({ provider: wsProvider });
            const contract = new ContractPromise(
            api,
            contractAbi,
            CONTRACT_ADDRESS
            );

            setApi(api);
            setContract(contract);
        } else {
            setAccount(-1);
            setModalOpen(false);
        }
        } catch (error) {
        setAccount(-1);
        setModalOpen(false);
        }
    }
    };

    const handleGet = async () => {
    if (!contract || !api || !account) return;

    try {
        const { result, output } = await contract.query.get(account, {});
        console.log(result, output);

        if (result.isOk) {
        console.log("Get operation result:", output?.toHuman());
        } else {
        console.error("Error querying get function:", result.asError);
        }
    } catch (error) {
        console.error("Get operation failed:", error);
    }
    };

When calling the handleGet, I am getting:

Type {registry: TypeRegistry, createdAtHash: undefined, initialU8aLength: 7, isStorageFallback: undefined, __internal__def: {…}, …}
null

So output is returning 'null`.

I think I am missing something.

Upvotes: 0

Views: 27

Answers (0)

Related Questions