Part 4: Writing Onchain

In the previous parts, you successfully fetched offchain data and read from a smart contract. Now, you'll complete the "Onchain Calculator" by writing your computed result back to the blockchain.

What you'll do

  • Use the CalculatorConsumer contract to receive workflow results
  • Modify your workflow to write data to the blockchain using the EVM capability
  • Execute your first onchain write transaction through CRE
  • Verify your result on the blockchain

Step 1: The consumer contract

To write data onchain, your workflow needs a target smart contract (a "consumer contract"). For this guide, we have pre-deployed a simple CalculatorConsumer contract on the Sepolia testnet. This contract is designed to receive and store the calculation results from your workflow.

Here is the source code for the contract so you can see how it works:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import {ReceiverTemplate} from "./ReceiverTemplate.sol";

/**
 * @title CalculatorConsumer (Testing Version)
 * @notice This contract receives reports from a CRE workflow and stores the results of a calculation onchain.
 * @dev Inherits from ReceiverTemplate which provides security checks. The forwarder address must be
 * configured at deployment. Additional security checks (workflowId, workflowName, author) can be enabled via setter
 * functions.
 */
contract CalculatorConsumer is ReceiverTemplate {
  // Struct to hold the data sent in a report from the workflow
  struct CalculatorResult {
    uint256 offchainValue;
    int256 onchainValue;
    uint256 finalResult;
  }

  // --- State Variables ---
  CalculatorResult public latestResult;
  uint256 public resultCount;
  mapping(uint256 => CalculatorResult) public results;

  // --- Events ---
  event ResultUpdated(uint256 indexed resultId, uint256 finalResult);

  /**
   * @notice Constructor requires the forwarder address for security
   * @param _forwarderAddress The address of the Chainlink Forwarder contract (for testing: MockForwarder)
   * @dev The forwarder address enables the first layer of security - only the forwarder can call onReport.
   * Additional security checks can be configured after deployment using setter functions.
   */
  constructor(
    address _forwarderAddress
  ) ReceiverTemplate(_forwarderAddress) {}

  /**
   * @notice Implements the core business logic for processing reports.
   * @dev This is called automatically by ReceiverTemplate's onReport function after security checks.
   */
  function _processReport(
    bytes calldata report
  ) internal override {
    // Decode the report bytes into our CalculatorResult struct
    CalculatorResult memory calculatorResult = abi.decode(report, (CalculatorResult));

    // --- Core Logic ---
    // Update contract state with the new result
    resultCount++;
    results[resultCount] = calculatorResult;
    latestResult = calculatorResult;

    emit ResultUpdated(resultCount, calculatorResult.finalResult);
  }

  // This function is a "dry-run" utility. It allows an offchain system to check
  // if a prospective result is an outlier before submitting it for a real onchain update.
  // It is also used to guide the binding generator to create a method that accepts the CalculatorResult struct.
  function isResultAnomalous(
    CalculatorResult memory _prospectiveResult
  ) public view returns (bool) {
    // A result is not considered anomalous if it's the first one.
    if (resultCount == 0) {
      return false;
    }

    // Business logic: Define an anomaly as a new result that is more than double the previous result.
    // This is just one example of a validation rule you could implement.
    return _prospectiveResult.finalResult > (latestResult.finalResult * 2);
  }
}

The contract is already deployed for you on Sepolia at the following address: 0x95e10BaC2B89aB4D8508ccEC3f08494FcB3D23cb. You will use this address in your configuration file.

Step 2: Update your workflow configuration

Add the CalculatorConsumer contract address to your config.staging.json:

{
  "schedule": "*/30 * * * * *",
  "apiUrl": "https://api.mathjs.org/v4/?expr=randomInt(1,101)",
  "evms": [
    {
      "storageAddress": "0xa17CF997C28FF154eDBae1422e6a50BeF23927F4",
      "calculatorConsumerAddress": "0x95e10BaC2B89aB4D8508ccEC3f08494FcB3D23cb",
      "chainName": "ethereum-testnet-sepolia",
      "gasLimit": "500000"
    }
  ]
}

Step 3: Update your workflow logic

Now modify your workflow to write the final result to the contract. Writing onchain involves a two-step process:

  1. Generate a signed report: Use runtime.report() to create a cryptographically signed report from your workflow data
  2. Submit the report: Use evmClient.writeReport() to submit the signed report to the consumer contract

The TypeScript SDK uses Viem's encodeAbiParameters to properly encode the struct data according to the contract's ABI before generating the report.

Replace the entire content of onchain-calculator/my-calculator-workflow/main.ts with this final version.

Note: Lines highlighted in green indicate new or modified code compared to Part 3.

onchain-calculator/my-calculator-workflow/main.ts
Typescript
1 import {
2 CronCapability,
3 HTTPClient,
4 EVMClient,
5 handler,
6 consensusMedianAggregation,
7 Runner,
8 type NodeRuntime,
9 type Runtime,
10 getNetwork,
11 LAST_FINALIZED_BLOCK_NUMBER,
12 encodeCallMsg,
13 bytesToHex,
14 hexToBase64,
15 } from "@chainlink/cre-sdk"
16 import { encodeAbiParameters, parseAbiParameters, encodeFunctionData, decodeFunctionResult, zeroAddress } from "viem"
17 import { Storage } from "../contracts/abi"
18
19 type EvmConfig = {
20 chainName: string
21 storageAddress: string
22 calculatorConsumerAddress: string
23 gasLimit: string
24 }
25
26 type Config = {
27 schedule: string
28 apiUrl: string
29 evms: EvmConfig[]
30 }
31
32 // MyResult struct now holds all the outputs of our workflow.
33 type MyResult = {
34 offchainValue: bigint
35 onchainValue: bigint
36 finalResult: bigint
37 txHash: string
38 }
39
40 const initWorkflow = (config: Config) => {
41 const cron = new CronCapability()
42
43 return [handler(cron.trigger({ schedule: config.schedule }), onCronTrigger)]
44 }
45
46 const onCronTrigger = (runtime: Runtime<Config>): MyResult => {
47 const evmConfig = runtime.config.evms[0]
48
49 // Convert the human-readable chain name to a chain selector
50 const network = getNetwork({
51 chainFamily: "evm",
52 chainSelectorName: evmConfig.chainName,
53 isTestnet: true,
54 })
55 if (!network) {
56 throw new Error(`Unknown chain name: ${evmConfig.chainName}`)
57 }
58
59 // Step 1: Fetch offchain data
60 const offchainValue = runtime.runInNodeMode(fetchMathResult, consensusMedianAggregation())().result()
61
62 runtime.log(`Successfully fetched offchain value: ${offchainValue}`)
63
64 // Step 2: Read onchain data using the EVM client
65 const evmClient = new EVMClient(network.chainSelector.selector)
66
67 const callData = encodeFunctionData({
68 abi: Storage,
69 functionName: "get",
70 })
71
72 const contractCall = evmClient
73 .callContract(runtime, {
74 call: encodeCallMsg({
75 from: zeroAddress,
76 to: evmConfig.storageAddress as `0x${string}`,
77 data: callData,
78 }),
79 blockNumber: LAST_FINALIZED_BLOCK_NUMBER,
80 })
81 .result()
82
83 const onchainValue = decodeFunctionResult({
84 abi: Storage,
85 functionName: "get",
86 data: bytesToHex(contractCall.data),
87 }) as bigint
88
89 runtime.log(`Successfully read onchain value: ${onchainValue}`)
90
91 // Step 3: Calculate the final result
92 const finalResultValue = onchainValue + offchainValue
93
94 runtime.log(`Final calculated result: ${finalResultValue}`)
95
96 // Step 4: Write the result to the consumer contract
97 const txHash = updateCalculatorResult(
98 runtime,
99 network.chainSelector.selector,
100 evmConfig,
101 offchainValue,
102 onchainValue,
103 finalResultValue
104 )
105
106 // Step 5: Log and return the final, consolidated result.
107 const finalWorkflowResult: MyResult = {
108 offchainValue,
109 onchainValue,
110 finalResult: finalResultValue,
111 txHash,
112 }
113
114 runtime.log(
115 `Workflow finished successfully! offchainValue: ${offchainValue}, onchainValue: ${onchainValue}, finalResult: ${finalResultValue}, txHash: ${txHash}`
116 )
117
118 return finalWorkflowResult
119 }
120
121 const fetchMathResult = (nodeRuntime: NodeRuntime<Config>): bigint => {
122 const httpClient = new HTTPClient()
123
124 const req = {
125 url: nodeRuntime.config.apiUrl,
126 method: "GET" as const,
127 }
128
129 const resp = httpClient.sendRequest(nodeRuntime, req).result()
130 const bodyText = new TextDecoder().decode(resp.body)
131 const val = BigInt(bodyText.trim())
132
133 return val
134 }
135
136 // updateCalculatorResult handles the logic for writing data to the CalculatorConsumer contract.
137 function updateCalculatorResult(
138 runtime: Runtime<Config>,
139 chainSelector: bigint,
140 evmConfig: EvmConfig,
141 offchainValue: bigint,
142 onchainValue: bigint,
143 finalResult: bigint
144 ): string {
145 runtime.log(`Updating calculator result for consumer: ${evmConfig.calculatorConsumerAddress}`)
146
147 const evmClient = new EVMClient(chainSelector)
148
149 // Encode the CalculatorResult struct according to the contract's ABI
150 const reportData = encodeAbiParameters(
151 parseAbiParameters("uint256 offchainValue, int256 onchainValue, uint256 finalResult"),
152 [offchainValue, onchainValue, finalResult]
153 )
154
155 runtime.log(
156 `Writing report to consumer contract - offchainValue: ${offchainValue}, onchainValue: ${onchainValue}, finalResult: ${finalResult}`
157 )
158
159 // Step 1: Generate a signed report using the consensus capability
160 const reportResponse = runtime
161 .report({
162 encodedPayload: hexToBase64(reportData),
163 encoderName: "evm",
164 signingAlgo: "ecdsa",
165 hashingAlgo: "keccak256",
166 })
167 .result()
168
169 // Step 2: Submit the report to the consumer contract
170 const writeReportResult = evmClient
171 .writeReport(runtime, {
172 receiver: evmConfig.calculatorConsumerAddress,
173 report: reportResponse,
174 gasConfig: {
175 gasLimit: evmConfig.gasLimit,
176 },
177 })
178 .result()
179
180 runtime.log("Waiting for write report response")
181
182 const txHash = bytesToHex(writeReportResult.txHash || new Uint8Array(32))
183 runtime.log(`Write report transaction succeeded: ${txHash}`)
184 runtime.log(`View transaction at https://sepolia.etherscan.io/tx/${txHash}`)
185 return txHash
186 }
187
188 export async function main() {
189 const runner = await Runner.newRunner<Config>()
190 await runner.run(initWorkflow)
191 }
192

Key TypeScript SDK features for writing:

  • encodeAbiParameters(): From Viem, encodes structured data according to a contract's ABI
  • parseAbiParameters(): From Viem, defines the parameter types for encoding
  • runtime.report(): Generates a signed report using the consensus capability
  • writeReport(): EVMClient method for submitting the signed report to a consumer contract
  • txHash: The transaction hash returned after a successful write operation

Step 4: Run the simulation and review the output

Run the simulation from your project root directory (the onchain-calculator/ folder). Because there is only one trigger, the simulator runs it automatically.

cre workflow simulate my-calculator-workflow --target staging-settings --broadcast

Your workflow will now show the complete end-to-end execution, including the final log of the MyResult object containing the transaction hash.

Workflow compiled
2026-01-09T17:52:05Z [SIMULATION] Simulator Initialized

2026-01-09T17:52:05Z [SIMULATION] Running trigger trigger=cron-trigger@1.0.0
2026-01-09T17:52:06Z [USER LOG] Successfully fetched offchain value: 68
2026-01-09T17:52:06Z [USER LOG] Successfully read onchain value: 22
2026-01-09T17:52:06Z [USER LOG] Final calculated result: 90
2026-01-09T17:52:06Z [USER LOG] Updating calculator result for consumer: 0x95e10BaC2B89aB4D8508ccEC3f08494FcB3D23cb
2026-01-09T17:52:06Z [USER LOG] Writing report to consumer contract - offchainValue: 68, onchainValue: 22, finalResult: 90
2026-01-09T17:52:12Z [USER LOG] Waiting for write report response
2026-01-09T17:52:12Z [USER LOG] Write report transaction succeeded: 0x6346d9eeca2f2875131d38aa9903a216f16e3cc7188f0ac6a1d5cd1fcbfbf9e6
2026-01-09T17:52:12Z [USER LOG] View transaction at https://sepolia.etherscan.io/tx/0x6346d9eeca2f2875131d38aa9903a216f16e3cc7188f0ac6a1d5cd1fcbfbf9e6
2026-01-09T17:52:12Z [USER LOG] Workflow finished successfully! offchainValue: 68, onchainValue: 22, finalResult: 90, txHash: 0x6346d9eeca2f2875131d38aa9903a216f16e3cc7188f0ac6a1d5cd1fcbfbf9e6

Workflow Simulation Result:
 {
  "finalResult": 90,
  "offchainValue": 68,
  "onchainValue": 22,
  "txHash": "0x6346d9eeca2f2875131d38aa9903a216f16e3cc7188f0ac6a1d5cd1fcbfbf9e6"
}

2026-01-09T17:52:12Z [SIMULATION] Execution finished signal received
2026-01-09T17:52:12Z [SIMULATION] Skipping WorkflowEngineV2
  • [USER LOG]: You can see all of your logger.info() calls showing the complete workflow execution, including the offchain value (68), onchain value (22), final calculation (90), and the transaction hash.
  • [SIMULATION]: These are system-level messages from the simulator showing its internal state.
  • Workflow Simulation Result: This is the final return value of your workflow. The MyResult object contains all the values (68 + 22 = 90) and the transaction hash confirming the write operation succeeded.

Step 5: Verify the result onchain

1. Check the Transaction

In your terminal output, you'll see a clickable URL to view the transaction on Sepolia Etherscan:

[USER LOG] View transaction at https://sepolia.etherscan.io/tx/0x...

Click the URL (or copy and paste it into your browser) to see the full details of the transaction your workflow submitted.

What are you seeing on a blockchain explorer?

You'll notice the transaction's to address is not the CalculatorConsumer contract you intended to call. Instead, it's to a Forwarder contract. Your workflow sends a secure report to the Forwarder, which then verifies the request and makes the final call to the CalculatorConsumer on your workflow's behalf. To learn more, see the Onchain Write guide.

2. Check the contract state

While your wallet interacted with the Forwarder, the CalculatorConsumer contract's state was still updated. You can verify this change directly on Etherscan:

  • Navigate to the CalculatorConsumer contract address: 0x95e10BaC2B89aB4D8508ccEC3f08494FcB3D23cb.
  • Expand the latestResult function and click Query. The values should match the finalResult, offchainValue, and onchainValue from your workflow logs.

This completes the end-to-end loop: triggering a workflow, fetching data, reading onchain state, and verifiably writing the result back to a public blockchain.

To learn more about implementing consumer contracts and the secure write process, see these guides:

Next steps

You've now mastered the complete CRE development workflow!

Get the latest Chainlink content straight to your inbox.