import { TaskContext, OnchainEvent } from "compose";
import {
fetchLatestRandomness,
toBytes32,
toBytes,
DRAND_CHAIN_INFO,
} from "../lib/drand.ts";
const CONTRACT_ADDRESS = "0xYOUR_DEPLOYED_CONTRACT_ADDRESS";
export async function main(context: TaskContext, event?: OnchainEvent) {
const { fetch, evm, logEvent } = context;
// Extract request ID from the event
const requestId = event?.topics[1] ? BigInt(event.topics[1]) : 0n;
// Fetch randomness from drand
const drandResponse = await fetchLatestRandomness(fetch);
await logEvent({
code: "DRAND_FETCHED",
message: `Fetched drand round ${drandResponse.round}`,
data: JSON.stringify({ round: drandResponse.round }),
});
// Get wallet and instantiate typed contract (generated from src/contracts/RandomnessConsumer.json)
const wallet = await evm.wallet({
name: "randomness-fulfiller",
});
const contract = new evm.contracts.RandomnessConsumer(
CONTRACT_ADDRESS,
evm.chains.baseSepolia,
wallet
);
// Fulfill the randomness request on-chain
const { hash } = await contract.fulfillRandomness(
requestId.toString(),
toBytes32(drandResponse.randomness),
drandResponse.round,
toBytes(drandResponse.signature)
);
await logEvent({
code: "RANDOMNESS_FULFILLED",
message: `Fulfilled request ${requestId} in tx ${hash}`,
data: JSON.stringify({
requestId: requestId.toString(),
txHash: hash,
}),
});
return {
success: true,
requestId: requestId.toString(),
transactionHash: hash,
drand: {
round: String(drandResponse.round),
randomness: toBytes32(drandResponse.randomness),
chainHash: DRAND_CHAIN_INFO.hash,
},
};
}