desmos-labs / desmos

Improving the well-being of users on social networks through the blockchain technology.
https://desmos.network
Apache License 2.0
105 stars 48 forks source link

Getting an error while trying to create post with desmjs library. #1340

Open sundayonah opened 4 months ago

sundayonah commented 4 months ago

So basically while going through the desmjs docs, i found that i have to create subspaceId,

creating subspaceId

useEffect(() => { const initializeClient = async () => { const mnemonic = "" const rpcEndpoint = "http://127.0.0.1:26657"; const gasPrice = GasPrice.fromString("0.025stake"); const signer = await OfflineSignerAdapter.fromMnemonic(SigningMode.DIRECT, mnemonic); const [account] = await signer.getAccounts();

  console.log("Account fetched:", account);
  if (!account.address.startsWith("desmos")) {
    throw new Error("Invalid account address format");
  }

  setAccount(account);
  const desmosClient = await DesmosClient.connectWithSigner(rpcEndpoint, signer, { gasPrice });

  console.log("DesmosClient initialized", desmosClient);
  console.log("Account data:", account);

  setClient(desmosClient);

  // Attempt to create a subspace
  const createSubspaceMsg: MsgCreateSubspaceEncodeObject = {
    typeUrl: "/desmos.subspaces.v3.MsgCreateSubspace",
    value: MsgCreateSubspace.fromPartial({
      creator: account.address,
      name: "Test Subspace",
      description: "This is a test subspace",
    }),
  };

  console.log("Create subspace message:", createSubspaceMsg);

    const userAddress = account.address
    console.log(userAddress)
  try {
    const subspaceResult = await desmosClient.signAndBroadcast(userAddress, [createSubspaceMsg], "auto");
    console.log("Subspace creation result:", subspaceResult);
    // assertIsDeliverTxSuccess(subspaceResult);

    // // Extract subspace ID from the raw log events
    // const events = subspaceResult.events || [];
    // const subspaceIdEvent = events.find(
    //   (event) =>
    //     event.type === "created_subspace" &&
    //     event.attributes.some((attr) => attr.key === "subspace_id")
    // );

    // if (subspaceIdEvent) {
    //   const subspaceIdAttr = subspaceIdEvent.attributes.find((attr) => attr.key === "subspace_id");
    //   if (subspaceIdAttr) {
    //     setSubspaceId(Long.fromString(subspaceIdAttr.value)); // Convert string to Long type
    //     console.log(`Subspace ID: ${subspaceIdAttr.value}`);
    //   } else {
    //     console.error("Subspace ID attribute not found in event");
    //   }
    // } else {
    //   console.error("Created subspace event not found");
    // }
  } catch (error) {
    console.error("Failed to create subspace:", error);
  }
};

initializeClient();

}, []);

the error i have been getting

VM41549 page.tsx:206 Failed to create subspace: Error: Query failed with (6): rpc error: code = Unknown desc = invalid owner address: invalid address [desmos-labs/desmos/v7/x/subspaces/types/msgs.go:95] With gas wanted: '0' and gas used: '1168' : unknown request at QueryClient.queryAbci (queryclient.js:118:19) at async Object.request (utils.js:35:30) at async Object.simulate (queries.js:50:34) at async DesmosClient.simulate (signingcosmwasmclient.js:90:29) at async DesmosClient.signAndBroadcast (desmosclient.js:74:35) at async initializeClient (VM41549 page.tsx:182:40)

The function below is for creating post

const handleSubmit = async (event: React.FormEvent) => { event.preventDefault();

// Ensure client and subspaceId are ready
if (!client || !subspaceId) {
  alert("Client not initialized or subspace not selected");
  return;
}

console.log({client, subspaceId})

try {
  const msg: MsgCreatePostEncodeObject = {
    typeUrl: "/desmos.posts.v3.MsgCreatePost",
    value: MsgCreatePost.fromPartial({
      subspaceId, // Use state variable here
      sectionId: 0,
      text: postText,
      author: account?.address,
      replySettings: ReplySetting.REPLY_SETTING_EVERYONE,
    })
  };

  const result = await client.signAndBroadcast(account?.address || "", [msg], "auto");
  assertIsDeliverTxSuccess(result);

  alert("Post created successfully!");
} catch (error) {
  console.error("Failed to create post:", error);
  alert("Failed to create post. See console for details.");
}

};

dadamu commented 4 months ago

Hey, the owner field is missing in your code for MsgCreateSubspace:

const createSubspaceMsg: MsgCreateSubspaceEncodeObject = {
    typeUrl: "/desmos.subspaces.v3.MsgCreateSubspace",
    value: MsgCreateSubspace.fromPartial({
      creator: account.address,
      name: "Test Subspace",
      description: "This is a test subspace",
      owner: account.address, // this field must be included
    }),
  };
sundayonah commented 4 months ago
owner: account.address,

@dadamu thank you very much, i have successfully create post. it works

sundayonah commented 4 months ago
owner: account.address,

@dadamu thank you very much, i have successfully create post. it works

since you are here i would like to share this,

trying to connectWallet, after clicking the conectWallet button the qrcode pop-up i scanned it with trust wallet mobile app

i got this pop-up on my mobile Dapp uses unSupported version of(1) walletConnect

below is the snippet code `"use client";

import { useCallback, useEffect, useState } from "react"; import { AppBar, Button, Toolbar, Typography } from "@mui/material"; import { SignerStatus } from "@desmoslabs/desmjs"; import { useDesmosContext } from "../context/desmos"; import { useWalletConnectContext } from "../context/walletconnect"; import useSignerStatus from "../hooks/useSignerStatus"; import { WalletConnectConnector } from "@web3-react/walletconnect-connector";

export default function Header() {

const [address, setAddress] = useState(""); const { connect, disconnect, signer } = useDesmosContext(); const { signClient } = useWalletConnectContext(); const signerStatus = useSignerStatus();

useEffect(() => { if (signer !== undefined && signerStatus === SignerStatus.Connected) { signer.getAccounts().then((accounts) => { setAddress(accounts[0].address); }); } else { setAddress(""); } }, [signer, signerStatus]);

const connectDisabled = signClient === undefined || (signerStatus !== SignerStatus.Connected && signerStatus !== SignerStatus.NotConnected);

  // Configure WalletConnect connector

const walletConnect = new WalletConnectConnector({ rpc: { 1: "https://mainnet.infura.io/v3/........" }, bridge: "https://bridge.walletconnect.org", qrcode: true, // pollingInterval: 12000, });

// Function to connect to MetaMask async function connectWallet() { try { // Attempt to activate the WalletConnect connector await walletConnect.activate(); console.log("Connected to MetaMask"); } catch (error) { console.error("Failed to connect to MetaMask", error); } }`

Thanks

dadamu commented 4 months ago

@sundayonah Please use walletconnectv2 please. https://github.com/desmos-labs/desmjs/tree/main/packages/walletconnect-v2

sundayonah commented 4 months ago

@sundayonah Please use walletconnectv2 please. https://github.com/desmos-labs/desmjs/tree/main/packages/walletconnect-v2

Thanks

sundayonah commented 4 months ago

I am running desmos node locally, and i have been able to create several posts successfully. is their way i can display all the posts. during my research i found this

desmos query posts post [subspace-id] [post-id] [flags]

i run it in terminal, it successfully display the post, how do i do the same UI, so i can see the posts created.

Thanks @dadamu

dadamu commented 4 months ago

You can use desmos query posts posts [subspace-id] --limit [total-count]

sundayonah commented 4 months ago

Thanks @dadamu