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 })
54 if (!network) {
55 throw new Error(`Unknown chain name: ${evmConfig.chainName}`)
56 }
57 ​
58 // Step 1: Start the offchain fetch
59 const offchainPromise = runtime.runInNodeMode(fetchMathResult, consensusMedianAggregation())()
60 ​
61 // Step 2: Read onchain data using the EVM client
62 const evmClient = new EVMClient(network.chainSelector.selector)
63 ​
64 const callData = encodeFunctionData({
65 abi: Storage,
66 functionName: "get",
67 })
68 ​
69 const contractCallPromise = evmClient.callContract(runtime, {
70 call: encodeCallMsg({
71 from: zeroAddress,
72 to: evmConfig.storageAddress as `0x${string}`,
73 data: callData,
74 }),
75 blockNumber: LAST_FINALIZED_BLOCK_NUMBER,
76 })
77 ​
78 // Collect both independent results in a fixed order
79 const offchainValue = offchainPromise.result()
80 runtime.log(`Successfully fetched offchain value: ${offchainValue}`)
81 ​
82 const contractCall = contractCallPromise.result()
83 ​
84 const onchainValue = decodeFunctionResult({
85 abi: Storage,
86 functionName: "get",
87 data: bytesToHex(contractCall.data),
88 }) as bigint
89 ​
90 runtime.log(`Successfully read onchain value: ${onchainValue}`)
91 ​
92 // Step 3: Calculate the final result
93 const finalResultValue = onchainValue + offchainValue
94 ​
95 runtime.log(`Final calculated result: ${finalResultValue}`)
96 ​
97 // Step 4: Write the result to the consumer contract
98 const txHash = updateCalculatorResult(
99 runtime,
100 network.chainSelector.selector,
101 evmConfig,
102 offchainValue,
103 onchainValue,
104 finalResultValue
105 )
106 ​
107 // Step 5: Log and return the final, consolidated result.
108 const finalWorkflowResult: MyResult = {
109 offchainValue,
110 onchainValue,
111 finalResult: finalResultValue,
112 txHash,
113 }
114 ​
115 runtime.log(
116 `Workflow finished successfully! offchainValue: ${offchainValue}, onchainValue: ${onchainValue}, finalResult: ${finalResultValue}, txHash: ${txHash}`
117 )
118 ​
119 return finalWorkflowResult
120 }
121 ​
122 const fetchMathResult = (nodeRuntime: NodeRuntime<Config>): bigint => {
123 const httpClient = new HTTPClient()
124 ​
125 const req = {
126 url: nodeRuntime.config.apiUrl,
127 method: "GET" as const,
128 }
129 ​
130 const resp = httpClient.sendRequest(nodeRuntime, req).result()
131 const bodyText = new TextDecoder().decode(resp.body)
132 const val = BigInt(bodyText.trim())
133 ​
134 return val
135 }
136 ​
137 // updateCalculatorResult handles the logic for writing data to the CalculatorConsumer contract.
138 function updateCalculatorResult(
139 runtime: Runtime<Config>,
140 chainSelector: bigint,
141 evmConfig: EvmConfig,
142 offchainValue: bigint,
143 onchainValue: bigint,
144 finalResult: bigint
145 ): string {
146 runtime.log(`Updating calculator result for consumer: ${evmConfig.calculatorConsumerAddress}`)
147 ​
148 const evmClient = new EVMClient(chainSelector)
149 ​
150 // Encode the CalculatorResult struct according to the contract's ABI
151 const reportData = encodeAbiParameters(
152 parseAbiParameters("uint256 offchainValue, int256 onchainValue, uint256 finalResult"),
153 [offchainValue, onchainValue, finalResult]
154 )
155 ​
156 runtime.log(
157 `Writing report to consumer contract - offchainValue: ${offchainValue}, onchainValue: ${onchainValue}, finalResult: ${finalResult}`
158 )
159 ​
160 // Step 1: Generate a signed report using the consensus capability
161 const reportResponse = runtime
162 .report({
163 encodedPayload: hexToBase64(reportData),
164 encoderName: "evm",
165 signingAlgo: "ecdsa",
166 hashingAlgo: "keccak256",
167 })
168 .result()
169 ​
170 // Step 2: Submit the report to the consumer contract
171 const writeReportResult = evmClient
172 .writeReport(runtime, {
173 receiver: evmConfig.calculatorConsumerAddress,
174 report: reportResponse,
175 gasConfig: {
176 gasLimit: evmConfig.gasLimit,
177 },
178 })
179 .result()
180 ​
181 runtime.log("Waiting for write report response")
182 ​
183 const txHash = bytesToHex(writeReportResult.txHash || new Uint8Array(32))
184 runtime.log(`Write report transaction succeeded: ${txHash}`)
185 runtime.log(`View transaction at https://sepolia.etherscan.io/tx/${txHash}`)
186 return txHash
187 }
188 ​
189 export async function main() {
190 const runner = await Runner.newRunner<Config>()
191 await runner.run(initWorkflow)
192 }
193 ​

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!

  • Before You Build: Don't skip this — critical tips before building your own workflows.

Get the latest Chainlink content straight to your inbox.