DeFi Deep Dive

How to do DeFi in ~7 steps down the rabbit hole

Over the past week around the start of November 2021, I have decided to learn a little bit more about the current state of decentralized finance (DeFi), with a focus on the various blockchain “features” to get a better pulse of the current state of the market. I have been somewhat invested in a few cryptocurrencies that I was not very familiar with but they SEEMED to have decent staking rewards (more on this later) at more that what a bank would give – on Kraken up to 20% for Kava as an example (and it was not required to claim any rewards; restaking seemed to happen automatically with the exception of Ethereum, also more on this later).

Step 1: Need a New Wallet

I had the same wallet(s) for up to 10 years and they were starting to look outdated! At one point, I tried opening up my Ethereum Mist wallet and it was so old that it couldn’t connect to the network, but I did at least claim some bitcoin forks by exporting my private keys of a swept (IMPORTANT!) wallet about a month ago, which meant I had a bit of extra crypto to play with.

After sorting out all these wallets and sending to various exchanges, getting kicked off Binance, and doing some traditional CeFi (centralized Finance, i.e. aforementioned exchanges such as Kraken, Binance, and others) trading, I started to read about DeFi and pretty much watched every video on Finematics.

It was a prerequisite for me to get a new wallet that was DeFi friendly. So I ended up trying Trust Wallet as I was interested in Kava, since I literally have stake in it. The setup process was very straightforward and I was able to transfer some coins from the various centralized exchanges to this multi-coin wallet with very little effort (the only pain point being copying addresses from mobile app to my desktop session – I used a Google Drive document for this).

Step 2: Peruse a Platform (Kava)

Once I had some Kava in my “Trust-y” new wallet, I was able use WalletConnect to link to the Kava app in a very simple but new to me way, by scanning the QR code on my desktop with my phone camera. I started by essentially loading up funds from my wallet to the platform; its interesting how your Kava balance can still reflect in the Trust Wallet app too. I tried the various platforms, Mint, Lend, and Swap (specifically adding liquidity to a pool), and was so very impressed at the transaction speed and low cost, but not so impressed about the reward vesting period and deceiving APY numbers – you have to vest for 1 year to get the displayed APY, otherwise 1 month vesting only gets you between 1/5th or 1/10th depending.

The mint feature I thought is a pretty clever way to not have to pay capital gains tax, so thats what I did, minted some USDX using Kava as collateral to play around with the Lend and Swap functionality.

I thought this was pretty cool, but what else is there?

Step 3: Do a dApp

I checked out a bunch…I don’t remember them all but the short of it is, in the current state (November 2021), the ERC-20 (Ethereum based) ones are basically unusable if you aren’t a whale. I mean that the gas fees were so high >$50 worth of ETH per smart contract that it just isn’t worth it when I was spending less than a penny worth of Kava in my previous experiment. Nonetheless, for curiosity, I spent a small fortune on fees to try out pooling some AMPL Ampleforth on AAVE as the APY numbers were insane. I don’t think I will be seeing those returns but it was a YOLO bet that I allowed myself to do because I found a few ETH in an old wallet the other day.

The only time I felt I could condone the use of any dApp using my Trust Wallet was when they leveraged Binance Smart Chain. There the fees were much more reasonable, but because I can’t use Binance, it is a relative pain to get BNB to convert to Smart Chain so I ended it here. It seemed like Kava was the way to go, but it also felt lacking. What made it so easy/fast? Turns out it was built on Cosmos, so thats what I looked at next.

Step 4: Covering the Chain (Cosmos)

So would you believe that I also was staking ATOM (Cosmos) on Kraken at a mere 7% reward rate (I thought this was pretty, pretty good before). A bit more reading later and I found myself wanting to unstake my ATOM and play around with the new-ish Emeris platform they have built…

Step 1: Need a New Wallet (again)

Nope not a typo. Emeris required Keplr wallet to integrate…I’ve come this far so I unstaked some ATOM and deposited it into the Keplr wallet, lets see what this can do.

Already able to stake directly in the wallet using validator of your choice at a higher APY than the 7% I was getting on Kraken? Ok, lets try it – not sure how I feel yet about having to claim the staking rewards. Time will tell on this one.

Looking  through the various (all Cosmos chain? I mean Kava is on the list) supported cryptocurrencies, I was shocked at some of the staking yields, again, time will tell but I understand they payout at “epoch” daily which is 5PM UTC? Please “Do Your Own Research” on this. It sounded like Osmosis was the one to look at next.

Step 5: Crossing Chains (IBC transfers)

What I really like about Cosmos (Emeris) is that you can mostly intuitively move assets between blockchains (pay close attention to which blockchain you have selected as Akash seems to default and I may have mistaken sent to the wrong chain once). The fee is pretty low at the lowest setting, ~9 cents, and it was relatively fast ~9 seconds.







Step 6: O! cOSMOSis!

It took me a while but I eventually realized the cleverness of the name! I will leave this step with one simple image with the caveat that every transaction I have done so far has been FREE!





Step 7: Checking

Let’s just say my deep dive ended with me getting a crypto backed Visa debit card from by staking some CRO. I feel as though this is rather gimmicky (they have gamified missions that give you rewards), but decent exchange that I may provide a more detailed write-up on once I receive my card.

Automated Green House

The greenhouse needs to be self sustaining and tolerant to drops in temperature and light condition. It can be scaled up and/or out for larger and/or varied environments.

A temperature/humidity sensor will monitor conditions polling every n minutes and a minimum/maximum can be set. Upon trigger of a low temperature event, a relay will trigger heat. A high threshold will trigger a fan, and optionally an automatic window opener.

A moisture sensor (hydrometer) will be used to monitor the soil conditions once or twice daily. The optimal moisture level will need to be calibrated by watering plants to their ideal moisture conditions. If the moisture level drops below the ideal threshold, a subroutine will run to trigger a pump to irrigate the soil, monitoring the moisture level once per second until the ideal threshold has been re-established. A rain catcher could be implemented for the pump to draw water from, with the heat from the greenhouse melting snow in the winter. Alternatively, a water source will need to be provided but is out of the scope of this implementation.

A light sensor will be used to monitor the light levels at regular intervals. The aim is to conserve energy usage while ensuring plants get the optimal amount of light throughout a preset time window. If during the window, the light drops below a set threshold (calibrated depending on required growing conditions). A relay will trigger the lights to turn on. If using lighting that does not cycle well, the light threshold should be calibrated to below the amount of light at sunrise/sunset. Otherwise, shade/overcast lighting conditions should be used to supplement available light throughout the light time window. Furthermore, this can be expanded to multiple lighting channels to control color temperature for encouraging vegetative growth or flowering (for example MH vs. HPS HID lights, or blue vs. red LED). A simpler separate system can be used which would involve a garden timer powering lights to produce the minimum light requirements to keep the plants in their light cycle time requirements. If using a 16/8 light/dark cycle, calculate the minimum day length of the winter solstice and power off the lights between this day’s sunrise and sunset times. Adjust start/end times accordingly as the light/dark cycle requirements change – note this will require manual intervention if not integrating into the system as above.

A camera can be used to detect motion if required, or to track progress of plant growth remotely. The sensors will also report near real-time data allowing override of lighting, water, temperature ahead of the pre-determined action intervals.

This system can be modified to aggregate data from multiple sensors to obtain an actionable average value for any given parameter, or, could be multiplexed into zones as required. A combination of these to methods could be used, for example, having a single heat source, but multiple channel lighting and irrigation. Of course, this would increase the complexity of the system and may exceed the IO capabilities of the interface. Instead, multiple standalone systems could be deployed, in a modular fashion, not leveraging all of the available capabilities of the system, provided there is at least one system functioning for each of the required parameters – temperature, moisture, and light.

Materials req’d (minimum)
Raspberry Pi – recommended Pi Zero WH ~$20
Temperature/Humidity sensor (1 GPIO) – ~$2
Heater – appropriate wattage to heat area to required temperature above frost at <100% utilization Fan - USB fan could be modified to be used without requiring relay Moisture sensor (1 GPIO?) - ~$3 each on Amazon Water pump - ~$4 each on Amazon for low voltage Tubing - Appropriate size for pump and environment, optional irrigation kits can be used which contain T-adapters an various nozzles such as: Light sensor (1 GPIO?) - ~$10 or build your own with a photo-resistor Lights - LED recommended, ideally able to produce >25000 lux for all plants within the growing area. Wattage/lumen calculations exist based on growing area and distance from light source but expect at least 30W per sq. ft.
Relay x4 (4 GPIO) – ~$2+ per channel depending on number of channels

Technical details
We can re-use the 2-3 power GPIO pins (Ground, 3.3v, 5v) so we only require 1 pin for each sensor/relay.

It is possible to leverage low voltage pumps (3-5v) which would not require a relay, assuming there is enough available current to power the pump(s). This assumes we can default a 5v pin to OFF/DOWN. Otherwise, we are limited to initializing a 3.3v pin and setting ON/UP for the duration of the watering period. For simplicity, we will be using 3.3v power in a miniaturized proof of concept which can be directly expanded to use any voltage pump(s) via a relay.

Automated Irrigation
The moisture sensor requires 3.3v and ground, plus an pin (IN) for DO (digital output). The sensor is calibrated via a physical resistor to set the threshold. Once the threshold is met it triggers an event on the pin. This would be considered the trigger to stop the water flow. There need to be a fail-safe to prevent the condition where the cable is disconnected and no voltage is present on the line. This could be accomplished by leveraging the AO (analog output) on the sensor and an ADC (Analog to Digital Converter) to determine there is a valid reading. Alternatively, we can set a maximum water on duration to prevent over watering in the case of a sensor issue.
The water pump can be triggered by an event listener which fires when the moisture sensor reaches the low threshold. A maximum duration will be set to prevent over watering, and in the event of the maximum duration being reached, an alert should be generated for manual intervention due to the possibility of one of the following: 1) moisture sensor or pump failure/disconnect, 2) water reservoir out of water. For scenario 1, we can add some redundancy by adding multiple sensors and pumps for each channel and aggregating the sensor data using an !AND logic gate configuration where both sensors would be required to be reporting below the threshold for the watering even to occur. In scenario 2, we can mitigate this by either using a separate moisture sensor in the reservoir, mounted above the pump where there is enough volume of water to perform at least one watering cycle, or a water level sensor. Furthermore, the maximum duration event should be logged an logic should be implemented to alter watering behavior to prevent over-watering in the event of sensor configuration issues. An alternative, would be to override to a scheduled duration in the event of this type of issue. The water pump requires GROUND plus 1 OUT pin which will supply 3.3v directly to the pump or to a relay if a higher volume pump is required.

Heat and Fan
This is simply achieved by relays and polling withing appropriate intervals (~1 minute):
import RPi.GPIO as GPIO
import Adafruit_DHT
import time
mintemp = 10
maxtemp = 40

humidity, temperature = Adafruit_DHT.read_retry([PIN?], [PIN?])

if temperature < mintemp: GPIO.cleanup() GPIO.setmode(GPIO.BCM) GPIO.setup(heat,GPIO.OUT) GPIO.output(heat,GPIO.HIGH) if temperature > maxtemp:

NOTE: requires the Adafruit_DHT library

Similar to above except using light sensor. Since a light sensor has not been obtained at this time, a start and end time will be used for the lights. This requires some manipulation of the datetime string (import datetime) and could be expanded to multiple morning/evening schedules. Ideally, once the light sensor is obtained it will be calibrated to the minimum amount of light and a not-before and not-after time of day will be configured. When the available light drops below the threshold it would trigger the lights. To prevent the lights from cycling too frequently, a longer polling interval should be used since the lights will need to be turned off to meter the newly available light. If the start time is 6AM and the light is below the threshold, the lights will be turned on. If we check the light hourly, at 7AM the lights will turn off and a metering will occur. At this time there may still not be enough light so the lights will turn on again. At 8AM we may have enough light, so the lights would turn off and stay off. Later in the day around sunset we may drop below the threshold, perhaps 9PM the lights turn on again but at 10PM they need to turn off. Once 10PM hits, it will be after the not-after time and the light will turn off until the next day 6AM not-before time.

Real-time metrics and interaction
In addition to the less frequent polling, we will check all sensors at a regular interval, likely once per minute. All data will be sent to a web service via variables in a querystring such as https://server/agh?temperature=20&light=1&water=1&reservoir=1&heat=0&fan=0&pump=0
This call will also allow for any variables to be updated, which can be done using either a database or plain text file on the server. A web interface will report the values as well. The text file might look something like agh.txt:
lastupdated=2019-07-22 16:00:00

This can be accomplished using urllib2:
import urllib2
url = https://server/agh?temperature=20&light=1&water=1&reservoir=1&heat=0&fan=0&pump=0
response = urllib2.urlopen(url)

The response can be parsed for the appropriate values and previous/default values can be used in event of a loss of connectivity to the server (the server can also be localhost if no network connectivity is available, however variables could only be modified upon restoration of connectivity).

Power Considerations
In addition to the materials costs, there may be a significant cost to operate a large scale setup due to power consumption requirements. The main factors contributing to this are heat and lights. We also need to consider the limitations of a typical 15A circuit. If heat and lights are required on the same circuit we are limited to approximately a 5×5 ft. (25 sq. ft.) growing area. This would allow for the required ~750 watts of lighting and a ~1000w heater which should be enough to heat a slightly larger than 25 sq ft room with moderate insulation. If heat can be supplemented from another source, and we only require lighting, we could potentially expand to 8×8 (64 sq. ft.) area or more, depending on supplemental light from the sun, and other factors related to the light requirements of the plants.
In the worst case scenario, it would cost up to 8 dollars per day in energy costs for only 25 sq. ft. if you had to run 1000 watts of heat around the clock and 750 watts of lights for 16 hours per day assuming 20 cents per KWh electricity cost. This is not feasible, but on the other hand, if heat is not a consideration, and there is a sufficient amount of light, a 64 sq. ft. growing area could be operated at 12+ hours of light per day by running up to 1800 watts of lights for around 4 hours each day during the winter months where the day light is only ~8 hours for under $2 per day. Using similar numbers for the 5×5 area would be well under $1 per day. An average setup could expect to cost between $1-8 per day in power costs meaning anywhere from $300 to $3000+ per year. The absolute lowest cost could be achieved by only using this solution to keep plants alive through the winter and not try to flower, meaning less heat and light requirements (above frost, and supplemental light to keep vegetative growth, at least 12+ hours per day).

Pappardelle e fagioli

1 can Romano beans
Half can tomato
Tomato sauce to taste
1-2 packages pappardelle
Eggs (optional)
Onion/garlic/meat (optional)
oil/spices to taste Food process/blend beans and tomato (and optionally eggs)
In saucepan, heat oil and brown any onion/garlic/meat
Add food processed mix to saucepan and simmer (until eggs and meat are fully cooked if using these ingredients)
Boil water, salt, and add pappardelle – cooking al dente, drain water and add enough sauce to fully cover each noodle as the processed bean will cause significant reduction

Cooking with an Italiennium: Pasta al forno con animale

A recipe.

Why? Because my Nonna doesn’t cook anymore and my parents don’t understand the internet. So, I decided to take what I learned on Sundays and make it my own/bring it into the 21st (but pre-millennial) century.

The ingredients.

~1 can diced tomato
Favorite pasta sauce (store bought or home made)
~1 pound ricotta cheese
a few pounds of assorted cheeses (mozzarella, and similar)
as much hard cheese as you can afford (parmasean, reggiano, asiago, or similar – to taste)
a lot of ground animal meats (beef, veal, and similar)
(Spicy) Italian sausages
Cubed stewing meats (optional)
Eggs (optional)
1-2 pounds elicodali, rigatoni, pennoni, or other large cylindrical pasta
olives/sundried tomato (optional – to taste)
oil/spices to taste (black pepper, various “Italian” herbs)
onion/garlic/zucchini or similar vegetable (optional – to taste)

The scientific method (the recipe).

In a very large saucepan or stock pot, heat oil and lightly brown and spice onion/garlic/zucchini, ground meats, sausage, and cubed meats, optionally draining excess water/fats if not lean.
Add favorite pasta sauce and diced tomato (and optionally eggs, olives/sundried tomato), simmering for many hours uncovered until the cubed meat is tender and sauce is cooked down to optimal flavor and texture.
Remove sausages and cut into ~1 inch slices, adding back into sauce.
Preheat oven to ~400F and begin boiling water.
While waiting for the oven to preheat and water to boil, grate all but the hard cheese into a multi-cheese blend.
Lightly salt boiling water (or heavily if you are not using olives), adding chosen pasta.
Add ricotta cheese to the sauce mix and stir until the chunks are at a desired size, distributed evenly throughout, you may turn off the heat at this time.
Coat a very large/deep ‘metal oval oven roaster’ or casserole dish with some oil to prevent pasta from sticking to the sides.

IMPORTANT: Deliberately undercook pasta, draining before it has reached al dente, you will need to work quickly to perform the next step so that the pasta does not dry out/stick. Optionally, you could drain approximately 1/n of the pasta at a time (where n is equal to the number of layers of alternating pasta/cheese/sauce you choose dependent on how deep your oven container is) 2-4 is an acceptable range for n.

For each layer n:
Distribute 1/n pasta in container, covering with approximately 1/n of the sauce mixture, followed by approximately 1/(n+1) of the multi-cheese blend, then grate a small amount of hard cheeses for additional flavor. Ensure the pasta is fully covered with sauce. Repeat for the remaining layers.

Add the remaining ~1/n cheese so that there is approximately double the amount of cheese on the top compared to each of the layers, then grate some more of the remaining hard cheese before placing uncovered in the oven.

Bake for at least 20 minutes, until cheese begins to brown, optionally changing to broil during the last few minutes of cooking.

Remove from oven and use a metal serving utensil to cut through the layers without disturbing the baked cheese and serve. This dish can be very flavorful (see salty) so you may want to serve with only a small amount of fresh ground pepper and additional grated hard cheese.

Serves many meat lovers.