import {
type Address,
hexToString,
parseEventLogs,
parseUnits,
stringToHex,
} from 'viem';
const abi = [
{ type: 'function', name: 'decimals', stateMutability: 'view', inputs: [], outputs: [{ type: 'uint8' }] },
{ type: 'function', name: 'transferWithMemo', stateMutability: 'nonpayable', inputs: [
{ name: 'to', type: 'address' },
{ name: 'amount', type: 'uint256' },
{ name: 'memo', type: 'bytes32' },
], outputs: [{ type: 'bool' }] },
{ type: 'event', name: 'Memo', inputs: [
{ name: 'caller', type: 'address', indexed: true },
{ name: 'memo', type: 'bytes32', indexed: true },
] },
] as const;
export async function payWithMemo(token: Address, merchant: Address) {
const decimals = await publicClient.readContract({
address: token, abi, functionName: 'decimals',
});
const payment = await publicClient.simulateContract({
account: walletClient.account,
address: token,
abi,
functionName: 'transferWithMemo',
args: [merchant, parseUnits('25', decimals), stringToHex('order-8842', { size: 32 })],
});
const hash = await walletClient.writeContract(payment.request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
const [memo] = parseEventLogs({ abi, logs: receipt.logs, eventName: 'Memo' });
const orderId = hexToString(memo.args.memo, { size: 32 }).replace(/\0+$/, '');
console.log(orderId); // "order-8842"
}