Tutorial 7: Oracles
You can use an oracle when your smart contract needs to consume data from the outside world.
Learn about zkOracles in this 5-minute video:
Open the example project in GitHub Codespaces. GitHub starts a container with Node.js 22 in the examples/zkapps/07-oracles folder, installs the dependencies and builds the project. This takes some minutes. Then, in the terminal, run cd contracts, then npm test. Some tests make proofs, and these tests take several minutes.
You must have a GitHub account. The codespace uses the free monthly quota of your account. Stop or delete the codespace when you are done.
Prerequisites
-
Make sure you have the zkApp CLI installed:
$ npm install -g zkapp-cli -
Ensure your environment meets the Prerequisites for zkApp Developer Tutorials.
-
Use Node.js 22.19.5 or later. o1js 3 requires it.
This tutorial has been tested with:
- o1js version
3.0.0 - Node.js versions
22and24
The example project is built and tested in CI: the smart contract tests run against a local blockchain, and the oracle's signing logic is tested offline with o1js.
High-Level Overview
In this tutorial, you are going to build an oracle that retrieves data from the REST API and you also are going to write the smart contract that consumes information from this oracle.
- Retrieve data from the REST API that provides mock credit score information for two users: one with a high credit score (the user with
id=1) and one with a low credit score (any otherid). - The smart contract consumes this information and allows users to prove their credit score is at or above a certain threshold (for example, 700 or higher).
Using the smart contract, users can generate an attestation that their credit score is above a certain value. To maintain their privacy, users can prove this fact to a third party without sharing the exact credit score or other personal information.
This tutorial uses a mock credit score API as the data source and provides a foundation to create an oracle for any type of data. Just alter the code to query data from whatever source you need, any other REST API, for example.
How Oracles Work
Oracles connect blockchain smart contracts with the outside world to get data on chain.
Mina smart contract computation run off-chain and make it possible to prove that the expected computation was run on private data without revealing the data itself. When the smart contract consumes data from a third-party source, you want to verify that this data is authentic and was provided by the expected source.
The Mina roadmap includes zkOracles to allow a zkApp to consume data trustlessly from any HTTPS data source. The oracle design described in this tutorial is typically operated by the zkApp developer. The oracle fetches and signs the desired data, and then a zkApp can consume this data and verify the signature to ensure that the data was provided by the expected source.
Data providers can also operate as response signers like the one described to provide users with an oracle that does not require them to trust an intermediary. In other words, if a credit score or other data provider chooses to sign response data themselves, users can consume data from that source without trusting anybody besides the data provider they already trust to provide correct data.
Design
This simple oracle design:
- Fetches data from the desired REST API source
- Signs it using a Mina-compatible private key
- Returns the data, signature, and public key associated with the private key
- Allows the signature to be verified by the zkApp
Code
The oracle is a Next.js project: see the complete project. It runs as a Vercel Function.
The route handler reads the user query parameter and returns the signed response:
export function GET(request: NextRequest) {
const searchParams = new URLSearchParams(request.nextUrl.search);
return NextResponse.json(
getSignedCreditScore(+(searchParams.get('user') ?? 0)),
{ status: 200 }
);
}
The signing logic gets the credit score of the user and signs the user id and the credit score, in that order, with the oracle's private key:
export function getSignedCreditScore(userId: number) {
// The private key of our account. When running locally the hardcoded key will
// be used. In production the key will be loaded from a Vercel environment
// variable. The public key of the hardcoded key is
// B62qphyUJg3TjMKi74T2rF8Yer5rQjBr1UyEG7Wg9XEYAHjaSiSqFv1, which is not the
// key of the demo oracle that the smart contract trusts.
let privateKey =
process.env.PRIVATE_KEY ??
'EKF65JKw9Q1XWLDZyZNGysBbYG21QbJf3a4xnEoZPZ28LKYGMw53';
// We get the users credit score. In this case it's 787 for user 1, and 536
// for anybody else :)
const knownCreditScore = (userId: number) => (userId === 1 ? 787 : 536);
// Compute the users credit score
const creditScore = knownCreditScore(userId);
// Use our private key to sign an array of numbers containing the users id and
// credit score
const signature = client.signFields(
[BigInt(userId), BigInt(creditScore)],
privateKey
);
return {
data: { id: userId, creditScore: creditScore },
signature: signature.signature,
publicKey: signature.publicKey,
};
}
The smart contract verifies the signature on the same two fields, in the same order. If the oracle signs different fields, or the same fields in a different order, the smart contract rejects the signature.
You can adapt this code to create oracles for other API sources. For example, if you want your smart contract to ingest price feed data from an exchange, query the exchange API, sign the results, and return a response in the following response format.
Response Format
The oracle returns a JSON-formatted response with these top-level properties:
data: An object of the information you are interested in and can have any form.signature: A signature for thedataobject created using the oracle operator's private key. Smart contracts use this signature to verify that data was provided by the expected source.publicKey: The public key of the oracle is the same for all requests to this oracle.
The following example is a response from the oracle for the user with the id of 1. In the real world, this id might be a social security number or a similar identifier. Notice that the data property contains their credit score and user id.
The demo oracle for user with id 1 is available at https://07-oracles.vercel.app/api/credit-score?user=1 and shows this response:
{
"data": { "id": 1, "creditScore": 787 },
"signature": "7mXGPCbSJUiYgZnGioezZm7GCy46CEUbgcCH9nrJYXQQiwwVrA5wemBX4T1XFHUw62oR2324QNnkUVXW6yYQLsPsqxZ3nsYR",
"publicKey": "B62qoAE4rBRuTgC42vqvEyUqCGhaZsW58SKVW4Ht8aYqP9UTvxFWBgy"
}
The user with an id of 2 has a credit score that is below the threshold specified in the smart contract.
The demo oracle for user with id 2 with a lower credit score is available at https://07-oracles.vercel.app/api/credit-score?user=2 and shows this response:
{
"data": { "id": 2, "creditScore": 536 },
"signature": "7mXXnqMx6YodEkySD3yQ5WK7CCqRL1MBRTASNhrm48oR4EPmenD2NjJqWpFNZnityFTZX5mWuHS1WhRnbdxSTPzytuCgMGuL",
"publicKey": "B62qoAE4rBRuTgC42vqvEyUqCGhaZsW58SKVW4Ht8aYqP9UTvxFWBgy"
}
While the first user has a credit score of 787, the second user has a credit score of 536. The signature is also changed. This makes sense because the payload is different from what is received in the first response. Finally, notice that the publicKey is the same because in each case we are querying data from the same provider.
Run the oracle yourself
The demo oracle at https://07-oracles.vercel.app is a deployment of the oracle directory of the example project. To run the same oracle on your computer, clone the docs repository and start the oracle:
git clone https://github.com/MinaProtocol/docs2.git
cd docs2/examples/zkapps/07-oracles/oracle
npm install
npm run dev
The oracle starts on port 3000. Open http://localhost:3000/api/credit-score?user=1 to see the signed response.
The oracle signs with the private key in the PRIVATE_KEY environment variable. Without it, the oracle signs with a built-in development key. The public key of the development key is B62qphyUJg3TjMKi74T2rF8Yer5rQjBr1UyEG7Wg9XEYAHjaSiSqFv1. The demo oracle signs with its own private key, whose public key is B62qoAE4rBRuTgC42vqvEyUqCGhaZsW58SKVW4Ht8aYqP9UTvxFWBgy. The smart contract in this tutorial trusts only this key, so it rejects the signatures of the development key.
The oracle reads a NETWORK_KIND environment variable and gives it to the mina-signer client, but the variable does not change the signatures. signFields() in mina-signer always signs with the testnet signature prefix, and Signature.verify() in o1js checks that prefix.
Generate a key pair for your oracle
To make the smart contract trust your own oracle, give the oracle a key pair of its own and tell the contract its public key.
-
Generate a Mina-compatible public/private key pair. In the
oracledirectory, run:npm run keygenThis command runs the code in the keygen.js file of the oracle
Next.jsproject and prints the key pair. -
Set the
PRIVATE_KEYenvironment variable of the oracle to the private key. For a local run, create a file named.env.localin theoracledirectory with one line,PRIVATE_KEY=EK..., or set the variable on the command line:PRIVATE_KEY=EK... npm run devFor a deployment on Vercel, set
PRIVATE_KEYas an environment variable of the project. Do not commit the private key. -
Set
ORACLE_PUBLIC_KEYinsrc/OracleExample.tsto the public key. This is the smart contract file that you write in Smart Contract, in your07-oraclesproject. In the example repository, the file is in thecontractsdirectory.
The tests in OracleExample.test.ts (see Test your smart contract) are written for the demo oracle: they hardcode its public key and two of its signatures, and the actual API requests group fetches from https://07-oracles.vercel.app. After you switch to your own key, update ORACLE_PUBLIC_KEY in the test, replace the hardcoded signatures with signatures from your oracle, and point the fetch() calls at http://localhost:3000.
In the example repository, the oracle test the demo oracle responses in the tutorial verify against the contract key in oracle/test/signCreditScore.test.mjs reads ORACLE_PUBLIC_KEY from contracts/src/OracleExample.ts. It also fails after the key change until you replace its two demo signatures with signatures from your oracle.
Smart Contract
Now that you have an oracle that returns signed data, you can write a smart contract that uses this data.
Create a project
-
Create or change to a directory where you have write privileges.
-
Create a project by using the
zk projectcommand:$ zk project --ui none 07-oraclesThis command creates the zkApp project without a UI, because this tutorial does not need one.
-
Change into the
07-oraclesdirectory. -
The zkApp CLI can create the project with an earlier o1js. In
package.json, set theo1jsversion inpeerDependenciesto^3.0.0, then run:$ npm install -
In
package.json, change thetestscript to:"test": "npm run build && node --test build/src/*.test.js",The zkApp CLI
0.23.0writes thetestscript asfind build/src -name '*.test.js' -exec node --test {} \;. With\;,findignores the exit code ofnode --test, sonpm run testexits with code 0 even when a test fails.
For this tutorial, you run commands from the root of the 07-oracles directory.
Each time you make changes, then build or deploy, the TypeScript code is compiled into JavaScript in the build directory.
Prepare the project
The files in the src directory contain the TypeScript code for the smart contract.
-
Delete the default generated files and their compiled output in
buildby running:$ rm -rf build
$ rm src/Add.ts
$ rm src/Add.test.ts
$ rm src/AddZkProgram.ts
$ rm src/interact.tsIf your version of the zkApp CLI does not create
src/AddZkProgram.ts, skip that command.The
zk projectcommand builds the project when it creates it, andtscdoes not delete old files frombuild. Withoutrm -rf build, the compiledbuild/src/Add.test.jsstays, andnpm run teststill runs it. -
Create the
OracleExample.tsfile and generate the corresponding test file:$ zk file OracleExample -
Change
src/index.tsto:src/index.tsimport { OracleExample } from './OracleExample.js';
export { OracleExample };
Write the smart contract
You can find the complete code for this smart contract here.
Paste the following content into the src/OracleExample.ts file:
import {
Field,
SmartContract,
state,
State,
method,
PublicKey,
Signature,
} from 'o1js';
// The public key of our trusted data provider
const ORACLE_PUBLIC_KEY =
'B62qoAE4rBRuTgC42vqvEyUqCGhaZsW58SKVW4Ht8aYqP9UTvxFWBgy';
export class OracleExample extends SmartContract {
// Define zkApp state
// Define zkApp events
init() {
// Initialize zkApp state
super.init();
}
@method async verify(id: Field, creditScore: Field, signature: Signature) {
// Get the oracle public key from the zkApp state
// Evaluate whether the signature is valid for the provided data
// Check that the signature is valid
// Check that the provided credit score is 700 or higher
// Emit an event containing the verified user's id
}
}
This completes the basic setup for the smart contract. For details on the init() method, see Tutorial 1: Hello World.
On-Chain State
The smart contract stores the public key for the oracle that you retrieve data from as the on-chain state. This makes the public key available when end users run the smart contract. The smart contract then uses this public key to verify the signature of the data to confirm it came from the expected source.
In the src/OracleExample.ts file:
// Define zkApp state
@state(PublicKey) oraclePublicKey = State<PublicKey>();
Use the init method to initialize the oraclePublicKey to the credit score oracle's public key.
init() {
// Initialize zkApp state
super.init();
// Set the oracle public key as zkApp on-chain state
this.oraclePublicKey.set(PublicKey.fromBase58(ORACLE_PUBLIC_KEY));
}
Emit Events
The smart contract checks that a user has a credit score above a certain threshold. But, how can the user prove it?
To expose the result to the outside world, you can emit events. Events allow smart contracts to publish arbitrary messages that anybody can verify without requiring them to be stored in the state of a zkApp account. This property makes events ideal for communication with other parties of your application that don't live on-chain, like the UI or even an external service.
This code adds an events object to the smart contract class to define the names and types of the events it can emit:
// Define zkApp events
events = {
verified: Field,
};
Define the verify() method
Next you would like to verify that user's credit score is above 700.
The verify() method is defined like any other TypeScript method, except that it must have the @method decorator in front of it that tells o1js that this method can be invoked by users when they interact with the smart contract.
@method async verify(id: Field, creditScore: Field, signature: Signature) {
...
}
Pass in these arguments:
id: The id of the user whose credit score is requested to prevent bad actors from querying somebody else's data and claiming it as their own.creditScore: The credit score of the user that is a number between 350 and 800 (this tutorial uses mock credit scores).signature: A cryptographic signature of oracle'sdataobject (idandcreditScore). This is what the smart contract uses to verify that the data was provided by the expected source.
The verify() method does not return any values or change any contract state. It only emits a verified event with the user's id if their credit score is 700 or higher.
Fetch the oracle's public key
To get the oracle's public key from the on-chain state, verify the signature of data from the oracle:
// Get the oracle public key from the zkApp state
const oraclePublicKey = this.oraclePublicKey.get();
this.oraclePublicKey.requireEquals(oraclePublicKey);
The requireEquals() method invocation ensures that the public key that is retrieved at execution time is the same as the public key that exists within the zkApp account on the Mina network when the transaction is processed by the network.
Verify the signature
To ensure that the signature was from our expected source, verify that the signature on the oracle's data object (id and creditScore) is valid for the expected public key. This code returns true if the signature is valid, and false if it is not.
// Evaluate whether the signature is valid for the provided data
const validSignature = signature.verify(oraclePublicKey, [id, creditScore]);
You always want to make it impossible to generate a valid zero knowledge proof if validSignature is false. You can do this with assertTrue(). If the signature is invalid, this throws an exception and makes it impossible to generate a valid zero knowledge proof and proceed with transaction creation.
// Check that the signature is valid
validSignature.assertTrue();
Verify the credit score is 700 or higher
You want the verify() method to emit an event only if the user's credit score is 700 or higher. To ensure that this condition is met, call assertGreaterThanOrEqual() (assert greater than or equal to) on creditScore.
// Check that the provided credit score is 700 or higher
creditScore.assertGreaterThanOrEqual(Field(700));
These assert methods create a constraint that makes it impossible for users to generate a valid zero knowledge proof unless their condition is met. Without a valid zero knowledge proof (or a signature) it's impossible to generate a valid Mina transaction. Users can call the smart contract method and send a valid transaction only if they have a valid signature from the expected oracle and a credit score 700 or above.
Emit a verified event
With this foundation, you can emit a verified event.
- The first argument to
emitEvent()is an arbitrary string name, because a smart contract could emit more than one type of event. - The second argument can be any value, as long as it matches the type defined for the event.
In this case, the event has the Field type, but it could be a more complicated type built on Fields, if the situation called for it.
Emitted events can be fetched using the Archive-Node-API.
// Emit an event containing the verified user's id
this.emitEvent('verified', id);
The complete smart contract:
import {
Field,
SmartContract,
state,
State,
method,
PublicKey,
Signature,
} from 'o1js';
// The public key of our trusted data provider
const ORACLE_PUBLIC_KEY =
'B62qoAE4rBRuTgC42vqvEyUqCGhaZsW58SKVW4Ht8aYqP9UTvxFWBgy';
export class OracleExample extends SmartContract {
// Define zkApp state
@state(PublicKey) oraclePublicKey = State<PublicKey>();
// Define zkApp events
events = {
verified: Field,
};
init() {
// Initialize zkApp state
super.init();
// Set the oracle public key as zkApp on-chain state
this.oraclePublicKey.set(PublicKey.fromBase58(ORACLE_PUBLIC_KEY));
}
@method async verify(id: Field, creditScore: Field, signature: Signature) {
// Get the oracle public key from the zkApp state
const oraclePublicKey = this.oraclePublicKey.get();
this.oraclePublicKey.requireEquals(oraclePublicKey);
// Evaluate whether the signature is valid for the provided data
const validSignature = signature.verify(oraclePublicKey, [id, creditScore]);
// Check that the signature is valid
validSignature.assertTrue();
// Check that the provided credit score is 700 or higher
creditScore.assertGreaterThanOrEqual(Field(700));
// Emit an event containing the verified user's id
this.emitEvent('verified', id);
}
}
Test your smart contract
You can find the complete code for the smart contract tests here.
When you ran the zk file OracleExample command, the zkApp CLI automatically generated a test file src/OracleExample.test.ts. The generated file is a placeholder, and the zkApp CLI 0.23.0 writes it in a style that does not compile in the project it creates, so you must replace its content.
Replace the content of the src/OracleExample.test.ts file with:
import assert from 'node:assert';
import { beforeEach, describe, it } from 'node:test';
import {
AccountUpdate,
Field,
Mina,
PrivateKey,
PublicKey,
Signature,
} from 'o1js';
import { OracleExample } from './OracleExample.js';
let proofsEnabled = false;
// The public key of our trusted data provider
const ORACLE_PUBLIC_KEY =
'B62qoAE4rBRuTgC42vqvEyUqCGhaZsW58SKVW4Ht8aYqP9UTvxFWBgy';
describe('OracleExample', () => {
let deployerAccount: Mina.TestPublicKey,
deployerKey: PrivateKey,
senderAccount: Mina.TestPublicKey,
senderKey: PrivateKey,
zkAppAddress: PublicKey,
zkAppPrivateKey: PrivateKey,
zkApp: OracleExample;
beforeEach(async () => {
if (proofsEnabled) await OracleExample.compile();
const Local = await Mina.LocalBlockchain({ proofsEnabled });
Mina.setActiveInstance(Local);
deployerAccount = Local.testAccounts[0];
deployerKey = deployerAccount.key;
senderAccount = Local.testAccounts[1];
senderKey = senderAccount.key;
zkAppPrivateKey = PrivateKey.random();
zkAppAddress = zkAppPrivateKey.toPublicKey();
zkApp = new OracleExample(zkAppAddress);
});
async function localDeploy() {
const txn = await Mina.transaction(deployerAccount, async () => {
AccountUpdate.fundNewAccount(deployerAccount);
await zkApp.deploy();
});
await txn.prove();
// this tx needs .sign(), because `deploy()` adds an account update that requires signature authorization
await txn.sign([deployerKey, zkAppPrivateKey]).send();
}
// Calls verify() and returns the id in the emitted `verified` event.
async function verifyAndReadEvent(
id: Field,
creditScore: Field,
signature: Signature
) {
const txn = await Mina.transaction(senderAccount, async () => {
await zkApp.verify(id, creditScore, signature);
});
await txn.prove();
await txn.sign([senderKey]).send();
const events = await zkApp.fetchEvents();
return events[0].event.data.toFields(null)[0];
}
it('generates and deploys the `OracleExample` smart contract', async () => {
await localDeploy();
const oraclePublicKey = zkApp.oraclePublicKey.get();
assert.deepStrictEqual(
oraclePublicKey,
PublicKey.fromBase58(ORACLE_PUBLIC_KEY)
);
});
describe('hardcoded values', () => {
it('emits an `id` event containing the users id if their credit score is 700 or higher and the provided signature is valid', async () => {
await localDeploy();
const id = Field(1);
const creditScore = Field(787);
const signature = Signature.fromBase58(
'7mXGPCbSJUiYgZnGioezZm7GCy46CEUbgcCH9nrJYXQQiwwVrA5wemBX4T1XFHUw62oR2324QNnkUVXW6yYQLsPsqxZ3nsYR'
);
const verifiedEventValue = await verifyAndReadEvent(
id,
creditScore,
signature
);
assert.deepStrictEqual(verifiedEventValue, id);
});
it('throws an error if the credit score is below 700 even if the provided signature is valid', async () => {
await localDeploy();
const id = Field(2);
const creditScore = Field(536);
const signature = Signature.fromBase58(
'7mXXnqMx6YodEkySD3yQ5WK7CCqRL1MBRTASNhrm48oR4EPmenD2NjJqWpFNZnityFTZX5mWuHS1WhRnbdxSTPzytuCgMGuL'
);
await assert.rejects(
Mina.transaction(senderAccount, async () => {
await zkApp.verify(id, creditScore, signature);
}),
/expected 700 <= 536/
);
});
it('throws an error if the credit score is 700 or higher and the provided signature is invalid', async () => {
await localDeploy();
const id = Field(1);
const creditScore = Field(787);
const signature = Signature.fromBase58(
'7mXPv97hRN7AiUxBjuHgeWjzoSgL3z61a5QZacVgd1PEGain6FmyxQ8pbAYd5oycwLcAbqJLdezY7PRAUVtokFaQP8AJDEGX'
);
await assert.rejects(
Mina.transaction(senderAccount, async () => {
await zkApp.verify(id, creditScore, signature);
}),
/Bool\.assertTrue/
);
});
});
describe('actual API requests', () => {
it('emits an `id` event containing the users id if their credit score is 700 or higher and the provided signature is valid', async () => {
await localDeploy();
const response = await fetch(
'https://07-oracles.vercel.app/api/credit-score?user=1'
);
const data = await response.json();
const id = Field(data.data.id);
const creditScore = Field(data.data.creditScore);
const signature = Signature.fromBase58(data.signature);
const verifiedEventValue = await verifyAndReadEvent(
id,
creditScore,
signature
);
assert.deepStrictEqual(verifiedEventValue, id);
});
it('throws an error if the credit score is below 700 even if the provided signature is valid', async () => {
await localDeploy();
const response = await fetch(
'https://07-oracles.vercel.app/api/credit-score?user=2'
);
const data = await response.json();
const id = Field(data.data.id);
const creditScore = Field(data.data.creditScore);
const signature = Signature.fromBase58(data.signature);
await assert.rejects(
Mina.transaction(senderAccount, async () => {
await zkApp.verify(id, creditScore, signature);
}),
/expected 700 <= 536/
);
});
});
});
The tests use the Node.js built-in test runner (node:test) and node:assert, the same as the project that the zkApp CLI creates. Each failure test waits for the rejected transaction with await assert.rejects(..., /message/) and checks the error message. Without await, the test checks nothing and passes even when the transaction succeeds.
To run the tests:
- Save the
OracleExample.test.tsfile. - Run
npm install. - Run
npm run test.
The tests in the actual API requests group call the demo oracle at https://07-oracles.vercel.app, so they need network access. Writing a test that calls an API is generally not a best practice, but it's convenient for the sake of this tutorial. You can also mock your HTTP requests.
Congratulations! You have just built a simple oracle using o1js and the Mina blockchain. You can find the complete code for this example here.
Check out Tutorial 8: Custom Tokens to learn how to create and manage a token of your own.