stepper-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "{}"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 The STEPPER Authors
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,53 @@
1
+ STEPPER
2
+ Copyright 2026 The STEPPER Authors
3
+
4
+ This product includes software developed for the STEPPER project
5
+ (https://steppercpu.tech).
6
+
7
+ Licensed under the Apache License, Version 2.0. You may obtain a copy of
8
+ the License in the LICENSE file at the root of this repository, or at
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ --------------------------------------------------------------------------
12
+ The name, and what the licence does not cover
13
+ --------------------------------------------------------------------------
14
+
15
+ The Apache License covers the code: the netlist, the toolchain, the
16
+ contracts, the site and everything that builds them. Fork it, run it, sell
17
+ what you make with it. That is the point of publishing it.
18
+
19
+ It does not cover the name or the marks. Section 6 of the License grants no
20
+ trademark rights, and this notice records what those are:
21
+
22
+ - the name STEPPER, and the part names ST-8 and ST-16 as used for this
23
+ project
24
+ - the ticker STEP
25
+ - the logo and mark, in every size and format under public/brand/ and
26
+ brand/source/
27
+ - the domain steppercpu.tech and the social accounts named on it
28
+
29
+ A fork is welcome to be a processor on a chain. It may not present itself
30
+ as this one. The reason is narrow and worth stating plainly: this project
31
+ is associated with a token, and a fork wearing its name and mark would be
32
+ indistinguishable from it at exactly the moment that distinction matters
33
+ most to somebody deciding what to buy.
34
+
35
+ Reasonable and customary use in describing origin is expressly permitted
36
+ by Section 6 and is not affected by anything above. Saying "derived from
37
+ STEPPER", or naming it in documentation, comparison or commentary, needs no
38
+ permission from anyone.
39
+
40
+ --------------------------------------------------------------------------
41
+ Third-party material
42
+ --------------------------------------------------------------------------
43
+
44
+ There is none. Every file in this repository was written for STEPPER.
45
+
46
+ The 2,161-gate netlist in public/scripts/st8-data.js is composed by
47
+ tools/build-netlist.js from a single NAND primitive, and the contracts are
48
+ generated from that same table.
49
+
50
+ Build-time dependencies (solc, ethers, the ethereumjs EVM) are declared in
51
+ package.json under devDependencies. npm fetches them; they are not vendored
52
+ here, they never ship to a browser, and each carries its own licence in
53
+ node_modules.
package/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # stepper-sdk
2
+
3
+ The STEPPER ST-8 processor, as a library: 2,161 NAND gates and 167
4
+ flip-flops, evaluated one clock edge at a time.
5
+
6
+ ```
7
+ npm i stepper-sdk
8
+ ```
9
+
10
+ ## Run a program
11
+
12
+ ```js
13
+ const stepper = require("stepper-sdk");
14
+
15
+ const { rom } = stepper.assemble(`
16
+ loop: in r0
17
+ out r0
18
+ jmp loop
19
+ `);
20
+
21
+ const r = stepper.run(rom, { cycles: 12, inValue: 42 });
22
+ console.log(r.out, r.cycles, r.gates);
23
+ ```
24
+
25
+ `run()` evaluates the shipped gate list in topological order and latches
26
+ every flip-flop at once. It is not a model of an instruction set: the
27
+ instruction set is what falls out of the gates.
28
+
29
+ ## Verify a chip on chain
30
+
31
+ ```js
32
+ const result = await stepper.verify("0x…");
33
+ console.log(result.ok, result.cyclesReplayed);
34
+ ```
35
+
36
+ A chip is deterministic and all of its inputs are public. `program()`
37
+ returns its ROM; every `step()` emits `Stepped(sponsor, cycle, outPort,
38
+ inValue)`. ROM plus those events is the complete tape the machine ran on,
39
+ so `verify()` fetches both, replays the whole history on the netlist in
40
+ this package, and checks two things:
41
+
42
+ - the final cycle, program counter, output and flags match `snapshot()`
43
+ - **every logged output matches**, cycle by cycle, not just the last one
44
+
45
+ Nothing in that calculation trusts us. The netlist is here, the events come
46
+ from whatever node you name, and the arithmetic happens on your machine.
47
+
48
+ ## What is not here
49
+
50
+ No launch function, no signer, no key handling. This package reads and
51
+ computes. It cannot spend.
52
+
53
+ ## API
54
+
55
+ | | |
56
+ | --- | --- |
57
+ | `assemble(source)` | ST-8 assembly to a ROM |
58
+ | `run(rom, opts)` | run it on the netlist |
59
+ | `programs()` | the shipped programs, as source |
60
+ | `readChip(addr, opts)` | cycle, pc, out, flags, registers, ROM |
61
+ | `history(addr, opts)` | every `Stepped` event, in cycle order |
62
+ | `decodeStepped(log)` | one raw log to its fields |
63
+ | `verify(addr, opts)` | replay the history and check the chain agrees |
64
+ | `Machine`, `loadNetlist` | the evaluator, for building your own loop |
65
+
66
+ `opts.rpc` names the node. It defaults to Robinhood Chain mainnet.
67
+
68
+ ## Licence
69
+
70
+ Apache-2.0. The name and marks are reserved under section 6; see NOTICE.
package/index.js ADDED
@@ -0,0 +1,96 @@
1
+ /**
2
+ * stepper-sdk — the ST-8 processor, as a library.
3
+ *
4
+ * const stepper = require("stepper-sdk");
5
+ *
6
+ * Four things, and they compose:
7
+ *
8
+ * assemble() ST-8 assembly to a ROM
9
+ * Machine the 2,161-gate netlist, evaluated one clock edge at a time
10
+ * readChip() what a chip on the chain currently says about itself
11
+ * verify() replay its whole history and check the chain agrees
12
+ *
13
+ * The netlist in this package is the gate list a synthesis pass produced, not
14
+ * a model of an instruction set. Every cycle is computed by evaluating those
15
+ * gates in topological order and latching every flip-flop at once, which is
16
+ * why the answer it gives is the same answer the contract gives.
17
+ *
18
+ * There is no launch function, no signer and no key handling anywhere in here.
19
+ * This package reads and computes; it cannot spend. If you want to deploy a
20
+ * chip, the launchpad does that and it does it from your own wallet.
21
+ */
22
+
23
+ "use strict";
24
+
25
+ var machine = require("./lib/netlist/machine.js");
26
+ var asm = require("./lib/netlist/asm.js");
27
+ var chain = require("./lib/chain/chain.js");
28
+ var proof = require("./lib/chain/verify.js");
29
+
30
+ /**
31
+ * Assemble ST-8 source into a ROM.
32
+ * @returns {{rom: number[], labels: object, listing: string[]}}
33
+ */
34
+ function assemble(source) {
35
+ return asm.assemble(source);
36
+ }
37
+
38
+ /**
39
+ * Run a ROM on the real netlist.
40
+ *
41
+ * @param {number[]} rom
42
+ * @param {object} [opts] { cycles = 40, inValue = 0, onCycle }
43
+ * @returns {{cycles: number, halted: boolean, pc, out, carry, zero, registers, switched}}
44
+ */
45
+ function run(rom, opts) {
46
+ var o = opts || {};
47
+ var D = machine.loadNetlist();
48
+ var m = new machine.Machine(D, rom);
49
+ var limit = o.cycles === undefined ? 40 : o.cycles;
50
+ var halted = false;
51
+
52
+ m.inPort = o.inValue || 0;
53
+ for (var i = 0; i < limit; i++) {
54
+ m.step();
55
+ if (o.onCycle) {
56
+ o.onCycle({
57
+ cycle: m.cycle, pc: m.pc(), out: m.out(),
58
+ carry: !!m.carry(), zero: !!m.zero(),
59
+ switched: m.switched, halted: m.halted(),
60
+ });
61
+ }
62
+ if (m.halted()) { halted = true; break; }
63
+ }
64
+
65
+ var regs = [];
66
+ for (i = 0; i < D.regs.length; i++) regs.push(m.reg(i));
67
+
68
+ return {
69
+ cycles: m.cycle, halted: halted,
70
+ pc: m.pc(), out: m.out(),
71
+ carry: !!m.carry(), zero: !!m.zero(),
72
+ registers: regs, switched: m.switched,
73
+ gates: D.gateCount,
74
+ };
75
+ }
76
+
77
+ /** The programs this processor ships with, as source. */
78
+ function programs() {
79
+ return asm.sources;
80
+ }
81
+
82
+ module.exports = {
83
+ assemble: assemble,
84
+ run: run,
85
+ programs: programs,
86
+
87
+ Machine: machine.Machine,
88
+ loadNetlist: machine.loadNetlist,
89
+
90
+ readChip: chain.readChip,
91
+ history: chain.history,
92
+ decodeStepped: chain.decodeStepped,
93
+ ABI: chain.ABI,
94
+
95
+ verify: proof.verify,
96
+ };
package/lib/abi.js ADDED
@@ -0,0 +1,38 @@
1
+ // Generated by tools/build-contract.js. Do not edit by hand.
2
+ //
3
+ // Every selector here is keccak256 of the signature beside it, computed at
4
+ // build time and checked against published vectors first. None of it is
5
+ // copied from another project, which is why this file exists: the page used
6
+ // to send tick(uint256,uint8) at a contract whose function is step().
7
+ //
8
+ // The layout below is the ST-8's. A chip built on a later generation
9
+ // reports its own through spec(), which is why the contracts stopped
10
+ // hardcoding these and the page reads them from here only as a default.
11
+ window.ST8_ABI = {
12
+ step: "0x3a1cde75", // step(uint256)
13
+ snapshot: "0x9711715a", // snapshot()
14
+ registers: "0xa0d3d084", // registers()
15
+ state: "0xc19d93fb", // state()
16
+ ram: "0x1fc4b242", // ram(uint256)
17
+ program: "0xc860ebc6", // program()
18
+ spec: "0xf448c9bc", // spec()
19
+ launch: "0x73a28fbd", // launch(bytes,(string,string,string,string,(string,string,string,string,string),address,uint16,bool,bytes32,bytes32),uint256,address)
20
+ tokenURI: "0xc87b56dd", // tokenURI(uint256)
21
+ records: "0x34461067", // records(uint256)
22
+ idOfChip: "0x8bc56e80", // idOfChip(address)
23
+ totalChips: "0x2ddbd13a", // total()
24
+ launchFee: "0xcf3cf573", // launchFee()
25
+ canLaunch: "0x58373f04", // canLaunch(address)
26
+ previewLaunchEconomics: "0xf718b78c", // previewLaunchEconomics(uint256,address)
27
+ launchConfigCount: "0xae72d871", // launchConfigCount()
28
+
29
+ steppedTopic: "0xed5cd9f6d6997b24d4fe100f731d98974dc1b7603f1cf2982be98d1826c9ef48",
30
+ // keccak256 of Stepped(address,uint40,uint256,uint256)
31
+
32
+ // Where each field sits inside the packed state word. Contiguous, so the
33
+ // page reads them the same way the contract does: a shift and a mask.
34
+ stateBits: 167,
35
+ pc: { shift: 128, width: 10 },
36
+ out: { shift: 138, width: 8 },
37
+ cf: 146, zf: 147, halt: 148,
38
+ };
@@ -0,0 +1,198 @@
1
+ /**
2
+ * chain.js — reading a chip off the chain.
3
+ *
4
+ * Read-only by construction. There is no signing here, no key handling and no
5
+ * transaction builder, so there is no code path in this package that can spend
6
+ * anything. That is a deliberate property rather than an omission: a library
7
+ * people are asked to install in order to check our claims should not also be
8
+ * a library that could move their money.
9
+ *
10
+ * Everything is decoded by hand from `eth_call` and `eth_getLogs`. The
11
+ * selectors are not written down here — they come from abi.js, which is
12
+ * generated from the contract signatures by the same keccak the contracts use,
13
+ * and checked against published vectors before it is written. A hand-copied
14
+ * selector is how a page ends up calling a function that does not exist.
15
+ */
16
+
17
+ "use strict";
18
+
19
+ var fs = require("node:fs");
20
+ var path = require("node:path");
21
+
22
+ /** abi.js is written for a browser. Handing it an object called window is the
23
+ whole of the port, exactly as machine.js does for the netlist. */
24
+ function loadAbi() {
25
+ var places = [
26
+ path.join(__dirname, "..", "..", "public", "scripts", "abi.js"),
27
+ path.join(__dirname, "..", "abi.js"),
28
+ path.join(__dirname, "abi.js"),
29
+ ];
30
+ var file = places.filter(function (p) { return fs.existsSync(p); })[0];
31
+ if (!file) throw new Error("abi.js is missing. Run `npm run abi` first.");
32
+ var win = {};
33
+ new Function("window", fs.readFileSync(file, "utf8"))(win);
34
+ return win.ST8_ABI;
35
+ }
36
+
37
+ var ABI = loadAbi();
38
+
39
+ var DEFAULT_RPC = "https://rpc.mainnet.chain.robinhood.com";
40
+
41
+ /* ------------------------------------------------------------- the wire */
42
+
43
+ var nextId = 0;
44
+
45
+ async function rpc(url, method, params) {
46
+ var res = await fetch(url, {
47
+ method: "POST",
48
+ headers: { "content-type": "application/json" },
49
+ body: JSON.stringify({ jsonrpc: "2.0", id: ++nextId, method: method, params: params || [] }),
50
+ });
51
+ if (!res.ok) throw new Error(method + ": HTTP " + res.status);
52
+ var body = await res.json();
53
+ if (body.error) {
54
+ var e = new Error(body.error.message || "rpc error");
55
+ e.code = body.error.code;
56
+ throw e;
57
+ }
58
+ return body.result;
59
+ }
60
+
61
+ function ethCall(url, to, data) {
62
+ return rpc(url, "eth_call", [{ to: to, data: data }, "latest"]);
63
+ }
64
+
65
+ /* ------------------------------------------------------------ decoding */
66
+
67
+ function word(hex, i) {
68
+ return hex.slice(2 + i * 64, 2 + (i + 1) * 64);
69
+ }
70
+ function toBig(w) { return BigInt("0x" + w); }
71
+ function toNum(w) { return Number(BigInt("0x" + w)); }
72
+
73
+ /** A dynamic `bytes` return: an offset, a length, then the bytes. */
74
+ function decodeBytes(hex) {
75
+ var at = Number(toBig(word(hex, 0))) / 32;
76
+ var len = Number(toBig(word(hex, at)));
77
+ var start = 2 + (at + 1) * 64;
78
+ return hex.slice(start, start + len * 2);
79
+ }
80
+
81
+ /** A dynamic `uint256[]` return. */
82
+ function decodeUintArray(hex) {
83
+ var at = Number(toBig(word(hex, 0))) / 32;
84
+ var len = Number(toBig(word(hex, at)));
85
+ var out = [];
86
+ for (var i = 0; i < len; i++) out.push(toBig(word(hex, at + 1 + i)));
87
+ return out;
88
+ }
89
+
90
+ /**
91
+ * The ROM, as the machine wants it.
92
+ *
93
+ * `program()` hands back the ROM as bytes, four to a word, big-endian. The
94
+ * evaluator indexes words, so this is the one place the two representations
95
+ * are reconciled.
96
+ */
97
+ function romFromBytes(hexNoPrefix) {
98
+ var rom = [];
99
+ for (var i = 0; i + 8 <= hexNoPrefix.length; i += 8) {
100
+ rom.push(parseInt(hexNoPrefix.slice(i, i + 8), 16));
101
+ }
102
+ return rom;
103
+ }
104
+
105
+ function pad32(address) {
106
+ return address.replace(/^0x/, "").toLowerCase().padStart(64, "0");
107
+ }
108
+
109
+ /* -------------------------------------------------------------- reading */
110
+
111
+ /**
112
+ * Everything a chip will tell you about itself in one round of calls.
113
+ *
114
+ * `snapshot()` is used rather than unpacking `state()` by hand, because the
115
+ * contract already knows where its own fields sit and a second opinion about
116
+ * that is a second thing that can be wrong.
117
+ */
118
+ async function readChip(address, opts) {
119
+ var url = (opts && opts.rpc) || DEFAULT_RPC;
120
+
121
+ var snap = await ethCall(url, address, ABI.snapshot);
122
+ var regs = await ethCall(url, address, ABI.registers);
123
+ var prog = await ethCall(url, address, ABI.program);
124
+
125
+ return {
126
+ address: address,
127
+ cycle: toNum(word(snap, 0)),
128
+ pc: toNum(word(snap, 1)),
129
+ out: toNum(word(snap, 2)),
130
+ carry: toNum(word(snap, 3)) === 1,
131
+ zero: toNum(word(snap, 4)) === 1,
132
+ halted: toNum(word(snap, 5)) === 1,
133
+ registers: decodeUintArray(regs).map(Number),
134
+ rom: romFromBytes(decodeBytes(prog)),
135
+ };
136
+ }
137
+
138
+ /** One `Stepped` log, as the fields the event declares. */
139
+ function decodeStepped(log) {
140
+ return {
141
+ sponsor: "0x" + log.topics[1].slice(26),
142
+ cycle: Number(BigInt(log.topics[2])),
143
+ outPort: Number(BigInt("0x" + word(log.data, 0))),
144
+ inValue: Number(BigInt("0x" + word(log.data, 1))),
145
+ block: Number(BigInt(log.blockNumber)),
146
+ tx: log.transactionHash,
147
+ };
148
+ }
149
+
150
+ /**
151
+ * Every `Stepped` this chip has emitted.
152
+ *
153
+ * Scanned backwards in windows from the head of the chain, and — this is the
154
+ * part that makes it terminate honestly — the chip has already said how many
155
+ * there should be. `snapshot()` reports the cycle count, one event was emitted
156
+ * per cycle, so the scan stops when it has that many rather than when it runs
157
+ * out of patience. A short answer is then a real finding rather than the scan
158
+ * having given up early.
159
+ */
160
+ async function history(address, opts) {
161
+ var o = opts || {};
162
+ var url = o.rpc || DEFAULT_RPC;
163
+ var want = o.expect;
164
+ var span = o.window || 50000;
165
+
166
+ var head = Number(BigInt(await rpc(url, "eth_blockNumber")));
167
+ var to = head;
168
+ var found = [];
169
+ var floor = o.fromBlock === undefined ? 0 : o.fromBlock;
170
+
171
+ while (to >= floor && (want === undefined || found.length < want)) {
172
+ var from = Math.max(floor, to - span + 1);
173
+ var logs = await rpc(url, "eth_getLogs", [{
174
+ address: address,
175
+ topics: [ABI.steppedTopic],
176
+ fromBlock: "0x" + from.toString(16),
177
+ toBlock: "0x" + to.toString(16),
178
+ }]);
179
+ for (var i = 0; i < logs.length; i++) found.push(decodeStepped(logs[i]));
180
+ if (from === floor) break;
181
+ to = from - 1;
182
+ }
183
+
184
+ found.sort(function (a, b) { return a.cycle - b.cycle; });
185
+ return found;
186
+ }
187
+
188
+ module.exports = {
189
+ ABI: ABI,
190
+ DEFAULT_RPC: DEFAULT_RPC,
191
+ rpc: rpc,
192
+ ethCall: ethCall,
193
+ readChip: readChip,
194
+ history: history,
195
+ decodeStepped: decodeStepped,
196
+ romFromBytes: romFromBytes,
197
+ pad32: pad32,
198
+ };