-
Notifications
You must be signed in to change notification settings - Fork 3
/
average.circuit.ts
71 lines (61 loc) · 2.58 KB
/
average.circuit.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import {
add,
sub,
mul,
div,
checkLessThan,
addToCallback,
CircuitValue,
CircuitValue256,
constant,
witness,
getAccount,
} from "@axiom-crypto/client";
// For type safety, define the input types to your circuit here.
// These should be the _variable_ inputs to your circuit. Constants can be hard-coded into the circuit itself.
export interface CircuitInputs {
blockNumber: CircuitValue;
address: CircuitValue;
}
// Default inputs to use for compiling the circuit. These values should be different than the inputs fed into
// the circuit at proving time.
export const defaultInputs = {
"blockNumber": 4000000,
"address": "0xEaa455e4291742eC362Bc21a8C46E5F2b5ed4701"
}
// The function name `circuit` is searched for by default by our Axiom CLI; if you decide to
// change the function name, you'll also need to ensure that you also pass the Axiom CLI flag
// `-f <circuitFunctionName>` for it to work
export const circuit = async (inputs: CircuitInputs) => {
// Number of samples to take. Note that this must be a constant value and NOT an input because the size of
// the circuit must be known at compile time.
const samples = 8;
// Number of blocks between each sample.
const spacing = 900;
// Validate that the block number is greater than the number of samples times the spacing
if (inputs.blockNumber.value() <= (samples * spacing)) {
throw new Error("Block number must be greater than the number of samples times the spacing");
}
// Perform the block number validation in the circuit as well
checkLessThan(mul(samples, spacing), inputs.blockNumber);
// Get account balance at the sample block numbers
let sampledAccounts = new Array(samples);
for (let i = 0; i < samples; i++) {
const sampleBlockNumber: CircuitValue = sub(inputs.blockNumber, mul(spacing, i));
const account = getAccount(sampleBlockNumber, inputs.address);
sampledAccounts[i] = account;
}
// Accumulate all of the balances to the `total` value
let total = constant(0);
for (const account of sampledAccounts) {
const balance: CircuitValue256 = await account.balance();
total = add(total, balance.lo());
}
// Divide the total amount by the number of samples to get the average value
const average: CircuitValue = div(total, samples);
// We call `addToCallback` on all values that we would like to be passed to our contract after the circuit has
// been proven in ZK. The values can then be handled by our contract once the prover calls the callback function.
addToCallback(inputs.blockNumber);
addToCallback(inputs.address);
addToCallback(average);
};