Start, list, and cache conversations with XMTP
Most of the time, when interacting with the network, you'll want to do it through conversations. Conversations are between two wallet addresses.
Check if an address is on the network
First you need to check if the address you want to message is on the XMTP network. You can do this by calling client.canMessage
with the address you want to message.
const isOnNetwork = await client.canMessage(
"0x3F11b27F323b62B159D2642964fa27C46C841897",
{ env: "production" },
);
You can bulk check addresses up to 1k at the same time.
const areOnNetwork = await client.canMessage([
"address1",
"address2",
"...",
"address1000",
]);
Be sure to provide error messaging when a user enters an address in the To field and the address hasn't yet created an XMTP identity.
Start a new conversation
You can create a new conversation with any address activated on the XMTP network. To learn more about supported addresses, see Chains.
const newConversation = await xmtp.conversations.newConversation(
"0x937C0d4a6294cdfa575de17382c7076b579DC176",
);
List existing conversations
You can get a list of all conversations that have one or more messages.
These conversations include all conversations for a user regardless of which app created the conversation. This functionality provides the concept of a portable inbox, which enables a user to access all of their conversations in any app built with XMTP.
To provide a user-friendly cold start (first load), display a "Loading conversations" status message and a progress bar.
const allConversations = await xmtp.conversations.list();
// Say gm to everyone you've been chatting with
for (const conversation of allConversations) {
console.log(`Saying GM to ${conversation.peerAddress}`);
await conversation.send("gm");
}
Cache the conversation list
When running in a browser, conversations are cached in LocalStorage
by default. Running client.conversations.list()
will update that cache and persist the results to the browser's LocalStorage
. The data stored in LocalStorage
is encrypted and signed using the Keystore's identity key so that attackers cannot read the sensitive contents or tamper with them. Caching the conversation list can improve performance by up to 90%.
To disable this behavior, set the persistConversations
client option to false
.
const clientWithNoCache = await Client.create(signer, {
persistConversations: false,
});