Full-Stack Starknet:
Completed code on GitHub here.
This part of the series will start the application that runs on our raspberry pi. By the end of this post, you'll know how to create and sign StarkNet transactions from python.
First, we'll initialize the project using Poetry:
This should autogenerate a pyproject.toml
. Here, we can add the dependencies and common dev tasks:
Aside: FastAPI was chosen because it's quick to get started and gives us interactive API documentation out of the box for easy testing. This will all run locally, so the signing keys never leave the car.
Create an app
folder with the following structure:
Themain.py
module is the primary entrypoint to the application:
Running the dev
task will start the application locally, auto-reloading on save:
Now that we've got the application skeleton, we can start iterating on the functionality.
The starknet.py package is a clean way to access our contract from within our application logic. Although similar to the library used in our contract unit tests, starknet.py is a separate project with more fully-featured abstractions & tools.
Modifying our main.py
a little bit, set up a temporary endpoint to try querying some testnet data:
This fetches the block containing our contract deployment (from Part 1):
To start, we'll have two endpoints:
POST /api/register
โ registers the host vehiclePOST /api/commit
โ hashes recent vehicle data, then signs & commits it to StarkNetOur primary application logic will live inside the POST /api/commit
endpoint. Later, we'll configure a simple cron to hit it on a schedule.
For the sake of simplicity, we'll keep a lot of things hardcoded initially.
Calling the endpoint and waiting a little while, we get the transaction hash as a response:
The explorer may be lagging behind a little, but it will eventually catch up and display the registration transaction. Returning to the #readContract tab of your contract's page, we can query for the owner of vehicle 1
โฆ and see our public key as the owner!
Calling it again, we get the expected error:
Moving on to the core loop, the POST /api/commit
endpoint will be called periodically. This triggers:
attest_state
contract functionAfter invoking it and waiting for a minute or two, we see:
Once that transaction confirms and is included in an L2 block, a query for the vehicle's nonce shows it's been updated, along with the state at nonce 0:
๐ It works! We now have a deployed contract and the start of an application that can interact with it.
As for periodically reading from diagnotics from the OBD2 port, it's pretty straight forward and not very interesting soooโฆ
๐