const { encodeFunctionData } = require('viem')
// Replace with your contract address
const ERC20_CONTRACT_ADDRESS = '0x0000000000000000000000000000000000000000'
// Replace with your loyalty currency ID
const LOYALTY_CURRENCY_ID = 'YOUR_LOYALTY_CURRENCY_ID'
module.exports.handler = async (input, output) => {
let operations = []
// Parse input if it's a string
if (typeof input === 'string') {
try {
let parsed = JSON.parse(input)
if (typeof parsed === 'string') {
parsed = JSON.parse(parsed)
}
input = parsed
} catch (err) {
output.setResult({
message: 'Invalid JSON input',
error: err,
input: input,
operations,
})
return output.buildOutput()
}
}
if (!Array.isArray(input)) {
output.setResult({
message: 'Expected input to be an array of events',
input: input,
operations,
})
return output.buildOutput()
}
const mintABI = [
{
inputs: [
{ internalType: 'address', name: 'to', type: 'address' },
{ internalType: 'uint256', name: 'amount', type: 'uint256' },
],
name: 'mint',
outputs: [],
stateMutability: 'nonpayable',
type: 'function',
},
]
const burnABI = [
{
inputs: [
{ internalType: 'address', name: 'from', type: 'address' },
{ internalType: 'uint256', name: 'amount', type: 'uint256' },
],
name: 'burn',
outputs: [],
stateMutability: 'nonpayable',
type: 'function',
},
]
try {
for (const event of input) {
if (!event.data) continue
const dataItem = event.data
const tokenAmount = BigInt(dataItem.amount) * BigInt(10) ** BigInt(18)
// Replace with your loyalty currency ID
if (dataItem.loyaltyCurrencyId !== LOYALTY_CURRENCY_ID) {
continue
}
let operationType = null
if (dataItem.direction === 'credit') {
operationType = 'mint'
} else if (dataItem.direction === 'debit') {
operationType = 'burn'
} else {
continue
}
const walletAddress = dataItem.loyaltyAccount?.user?.walletAddress
if (!walletAddress) continue
let data
if (operationType === 'mint') {
data = encodeFunctionData({
abi: mintABI,
functionName: 'mint',
args: [walletAddress, tokenAmount.toString()],
})
} else if (operationType === 'burn') {
data = encodeFunctionData({
abi: burnABI,
functionName: 'burn',
args: [walletAddress, tokenAmount.toString()],
})
}
output.addTransaction({
to: ERC20_CONTRACT_ADDRESS,
data: data,
value: '0x0',
})
}
output.setResult({
message: 'Token transactions created.',
operations,
})
return output.buildOutput()
} catch (error) {
console.error('Error in user code:', error)
throw error
}
}