Build custom content types for use with XMTP
Building a custom content type enables you to manage data in a way that is more personalized or specialized to the needs of your app.
For more common content types, you can usually find a standard or standards-track content type to serve your needs.
If your custom content type generates interest within the developer community, consider proposing it as a standard content type through the XIP process.
This tutorial covers how to build two example custom content types:
A basic example of a custom content type that multiplies two numbers
An advanced example of a custom content type that sends transaction hashes on the Polygon blockchain. This example also describes how to use the custom content type to render the transaction hash.
Basic: Multiply numbers using a custom content type
Build a custom content type to multiply numbers.
- Create the custom content type by creating a new file
- JavaScript
- React
- Kotlin
- Swift
- Dart
- React Native
import { ContentTypeId } from "@xmtp/xmtp-js";
// Create a unique identifier for your content type
const ContentTypeMultiplyNumbers = new ContentTypeId({
authorityId: "your.domain",
typeId: "multiply-number",
versionMajor: 1,
versionMinor: 0,
});
// Define the MultiplyCodec class
class ContentTypeMultiplyNumberCodec {
get contentType() {
return ContentTypeMultiplyNumbers;
}
// The encode method accepts an object with two numbers (a, b) and encodes it as a byte array
encode({ a, b }) {
return {
type: ContentTypeMultiplyNumbers,
parameters: {},
content: new TextEncoder().encode(JSON.stringify({ a, b })),
};
}
// The decode method decodes the byte array, parses the string into numbers (a, b), and returns their product
decode(content: { content: any }) {
const uint8Array = content.content;
const { a, b } = JSON.parse(new TextDecoder().decode(uint8Array));
return a * b;
}
fallback(content: string): string | undefined {
return `Can’t display "${content}". This app doesn’t support "${content}".`;
//return undefined; if you don't want the content type to be displayed.
}
}
import { ContentTypeId } from "@xmtp/react-sdk";
// Create a unique identifier for your content type
const ContentTypeMultiplyNumbers = new ContentTypeId({
authorityId: "your.domain",
typeId: "multiply-number",
versionMajor: 1,
versionMinor: 0,
});
// Define the MultiplyCodec class
class ContentTypeMultiplyNumberCodec {
get contentType() {
return ContentTypeMultiplyNumbers;
}
// The encode method accepts an object with two numbers (a, b) and encodes it as a byte array
encode({ a, b }) {
return {
type: ContentTypeMultiplyNumbers,
parameters: {},
content: new TextEncoder().encode(JSON.stringify({ a, b })),
};
}
// The decode method decodes the byte array, parses the string into numbers (a, b), and returns their product
decode(content: { content: any }) {
const uint8Array = content.content;
const { a, b } = JSON.parse(new TextDecoder().decode(uint8Array));
return a * b;
}
fallback(content: string): string | undefined {
return `Can’t display "${content}". This app doesn’t support "${content}".`;
//return undefined; if you don't want the content type to be displayed.
}
}
import org.xmtp.android.library.codecs.ContentTypeId
import org.xmtp.android.library.codecs.ContentTypeIdBuilder
import org.xmtp.android.library.codecs.ContentCodec
import org.xmtp.android.library.codecs.EncodedContent
import kotlinx.serialization.*
import kotlinx.serialization.json.*
@Serializable
data class NumberPair(val a: Double, val b: Double)
data class MultiplyNumberCodec(
override var contentType: ContentTypeId = ContentTypeIdBuilder.builderFromAuthorityId(
authorityId = "example.com",
typeId = "multiply-number",
versionMajor = 1,
versionMinor = 0
)
) : ContentCodec<Double> {
override fun encode(content: Double): EncodedContent {
// Assuming content is the product of two numbers
val numberPair = NumberPair(content / 2, 2.0) // You need to decide how to represent your numbers
return EncodedContent.newBuilder().also {
it.type = contentType
it.content = Json.encodeToString(numberPair).toByteStringUtf8()
}.build()
}
override fun decode(content: EncodedContent): Double {
val numberPair = Json.decodeFromString<NumberPair>(content.content.toStringUtf8())
return numberPair.a * numberPair.b
}
override fun fallback(content: Double): String? {
return "Error: This app does not support numbers."
}
}
import XMTP
// Define a structure to represent a pair of numbers
struct NumberPair: Codable {
let a: Double
let b: Double
}
struct MultiplyNumberCodec: ContentCodec {
typealias T = Double
var contentType: XMTP.ContentTypeID {
ContentTypeID(authorityID: "example.com", typeID: "multiply-number", versionMajor: 1, versionMinor: 0)
}
func encode(content: Double, client _: Client) throws -> XMTP.EncodedContent {
var encodedContent = EncodedContent()
encodedContent.type = ContentTypeID(authorityID: "example.com", typeID: "multiply-number", versionMajor: 1, versionMinor: 0)
// Assuming content is the product of two numbers, you need to adjust this as per your use case
let numberPair = NumberPair(a: content / 2, b: 2.0)
encodedContent.content = try JSONEncoder().encode(numberPair)
return encodedContent
}
func decode(content: XMTP.EncodedContent, client _: Client) throws -> Double {
let numberPair = try JSONDecoder().decode(NumberPair.self, from: content.content)
return numberPair.a * numberPair.b
}
func fallback(content: Double) throws -> String? {
return "Error: This app does not support numbers."
}
}
import 'dart:convert';
import 'dart:typed_data';
import 'package:xmtp/xmtp.dart' as xmtp;
final contentTypeMultiplyNumbers = xmtp.ContentTypeId(
authorityId: "com.example",
typeId: "multiply-number",
versionMajor: 1,
versionMinor: 0,
);
class NumberPair {
final double a;
final double b;
NumberPair(this.a, this.b);
Map<String, dynamic> toJson() => {
'a': a,
'b': b,
};
factory NumberPair.fromJson(Map<String, dynamic> json) => NumberPair(
(json['a'] as num).toDouble(),
(json['b'] as num).toDouble(),
);
}
class MultiplyNumberCodec extends xmtp.Codec<double> {
xmtp.ContentTypeId get contentType => contentTypeMultiplyNumbers;
Future<double> decode(xmtp.EncodedContent encoded) async {
String jsonString = utf8.decode(encoded.content);
NumberPair numberPair = NumberPair.fromJson(json.decode(jsonString));
return numberPair.a * numberPair.b;
}
Future<xmtp.EncodedContent> encode(double product) async {
// Assuming product is the multiplication of two numbers, adjust as needed
NumberPair numberPair = NumberPair(product / 2, 2.0);
String jsonString = json.encode(numberPair);
return xmtp.EncodedContent(
type: contentTypeMultiplyNumbers,
content: Uint8List.fromList(utf8.encode(jsonString)),
);
}
String? fallback(String content) {
return "Can't display “${content}”. This app doesn’t support “${content}”";
}
}
import { content } from "@xmtp/proto";
type EncodedContent = content.EncodedContent;
type ContentTypeId = content.ContentTypeId;
const ContentTypeMultiplyNumbers = {
authorityId: "yourdomain.org",
typeId: "multiply-numbers",
versionMajor: 1,
versionMinor: 0,
};
class MultiplyNumbersCodec implements JSContentCodec<{ a: number, b: number }> {
contentType = ContentTypeMultiplyNumbers;
// Encode a pair of numbers
encode(content: { a: number, b: number }): EncodedContent {
return {
type: ContentTypeMultiplyNumbers,
parameters: {},
content: new TextEncoder().encode(JSON.stringify(content)),
};
}
// Decode the content and return the product of the two numbers
decode(encodedContent: EncodedContent): number {
const contentStr = new TextDecoder().decode(encodedContent.content);
const { a, b } = JSON.parse(contentStr);
return a * b;
}
fallback(content: { a: number, b: number }): string | undefined {
return "A pair of numbers was sent.";
}
}
- Import and register the custom content type.
- JavaScript
- React Native
import { ContentTypeMultiplyNumberCodec } from "./xmtp-content-type-multiply-number";
const xmtp = await Client.create(signer, {
env: "dev",
});
xmtp.registerCodec(new ContentTypeMultiplyNumberCodec());
import { NumberCodec } from "./xmtp-content-type-number";
const client = await Client.create({
env: "production",
codecs: [new NumberCodec()],
});
- Send a message using the custom content type. This code sample demonstrates how to use the
MultiplyCodec
custom content type to perform multiplication operations.
- React
- React Native
const numbersToMultiply = { a: 3, b: 7 };
conversation.send(numbersToMultiply, {
contentType: ContentTypeMultiplyNumbers,
});
await conversation.send(12, { contentType: ContentTypeNumber });
- To use the result of the multiplication operation, add a renderer for the custom content type.
- JavaScript
- React Native
if (message.contentType.sameAs(ContentTypeMultiplyNumber)) {
return message.content; // 21
}
Because of this message content is now a function which returns the actual content. You can get that content by call message.content()
now instead of message.content . This may involve more filtering on the message side to make sure you are handling different contentTypes appropriately.
if (message.contentTypeId === "yourdomain.org/number:1.0") {
return message.content(); // 12
}
Advanced: Send token transaction hashes
Build a custom content type to send transaction hashes on the Polygon blockchain.
- Create the custom content type by creating a new file,
xmtp-content-type-transaction-hash.tsx
. This file hosts theTransactionHash
class for encoding and decoding the custom content type.
- JavaScript
import { ContentTypeId } from "@xmtp/xmtp-js";
export const ContentTypeTransactionHash = new ContentTypeId({
authorityId: "your.domain",
typeId: "transaction-hash",
versionMajor: 1,
versionMinor: 0,
});
export class ContentTypeTransactionHashCodec {
get contentType() {
return ContentTypeTransactionHash;
}
encode(hash) {
return {
type: ContentTypeTransactionHash,
parameters: {},
content: new TextEncoder().encode(hash),
};
}
decode(content: { content: any }) {
const uint8Array = content.content;
const hash = new TextDecoder().decode(uint8Array);
return hash;
}
}
- Import and register the custom content type.
- JavaScript
import {
ContentTypeTransactionHash,
ContentTypeTransactionHashCodec,
} from "./xmtp-content-type-transaction-hash";
const xmtp = await Client.create(signer, {
env: "dev",
});
xmtp.registerCodec(new ContentTypeTransactionHashCodec());
- Send a message using the custom content type. This code sample demonstrates how to use the
TransactionHash
content type to send a transaction.
- JavaScript
// Create a wallet from a known private key
const wallet = new ethers.Wallet(privateKey);
console.log(`Wallet address: ${wallet.address}`);
//im using a burner wallet with MATIC from a faucet
//https://faucet.polygon.technology/
// Set up provider for Polygon Testnet (Mumbai)
const provider = new ethers.providers.JsonRpcProvider(
"https://rpc-mumbai.maticvigil.com",
);
// Connect the wallet to the provider
const signer = wallet.connect(provider);
// Define the recipient address and amount
const amount = ethers.utils.parseEther("0.01"); // Amount in ETH (0.01 in this case)
// Create a transaction
const transaction = {
to: recipientAddress,
value: amount,
};
// Sign and send the transaction
const tx = await signer.sendTransaction(transaction);
console.log(`Transaction hash: ${tx.hash}`);
const conversation = await xmtp.conversations.newConversation(WALLET_TO);
await conversation
.send(tx.hash, {
contentType: ContentTypeTransactionHash,
})
.then(() => {
console.log("Transaction data sent", tx.hash);
})
.catch((error) => {
console.log("Error sending transaction data: ", error);
});
- To use the result of the hash, add an async renderer for the custom content type.
- JavaScript
if (message.contentType.sameAs(ContentTypeTransactionHash)) {
// Handle ContentTypeAttachment
return (
<TransactionMonitor key={message.id} encodedContent={message.content} />
);
}
const TransactionMonitor = ({ encodedContent }) => {
const [retryCount, setRetryCount] = useState(0);
const [transactionValue, setTransactionValue] = useState(null);
useEffect(() => {
const fetchTransactionReceipt = async () => {
console.log(encodedContent);
const provider = new ethers.providers.JsonRpcProvider(
"https://rpc-mumbai.maticvigil.com",
);
const receipt = await provider.getTransactionReceipt(encodedContent);
const tx = await provider.getTransaction(encodedContent);
if (tx && tx.value) {
setTransactionValue(ethers.utils.formatEther(tx.value));
}
};
fetchTransactionReceipt();
}, [encodedContent, retryCount]);
return transactionValue ? (
<div>Transaction value: {transactionValue} ETH</div>
) : (
<div>
Waiting for transaction to be mined...
<button onClick={() => setRetryCount(retryCount + 1)}>
Refresh Status 🔄
</button>
</div>
);
};