DeFi update

PRIA Burns Frontrunning Bots

Yesterday while I was puttering about on Telegram, I noticed a couple of large PRIA orders come through via a bot channel that I have pulled up. What immediatley struck me was that two of the three transactions were by the same address, a purchase and a sale, right before an after a larger order. It was apparent that this was a bot order trying to front run a transaction on the Uniswap pool, likely because of high slippage on the order.

What the bot owner didn’t account for was PRIA’s transaction burn. Between four and six percent of the purchased tokens were burned on during the attempt, resulting in about half an eth’s worth of loss for the bot. Oops.

This is part of a bigger problem in the Ethereum ecosystem, and why it’s considered an adversarial system. All transactions get sent to the mempool before they are mined in a block, which gives bots the opportunity to watch the mempool for transactions and try to front run it by submitting another transaction with slightly more gas.

Some have called this aspect of Ethereum’s architecture “the Dark Forest”. There’s a fascinating write up about it here that everyone should read if you haven’t already: Escaping The Dark Forest.

Another dev on the PRIA project has been trying to do KEEPR jobs the past few days and said that it is nearly impossible because everything keeps getting fronted as well. I’m not sure what the solution is to fix this problem, other than having private mem pools available via large mining pools, as mentioned in the article above.

At some point I need to dive into what solutions are being proposed by the Ethereum community, and compare how it’s handled in other L1 solutions like PolkaDot or Cosmos.

Value DeFi exit

A few months ago I tried staking some USDC in the Value DeFi seed pool v2, which was supposed to be earning 23% APY. The pool is closing, which I happened upon just by chance, and I just withdrew my funds for some underwhelming results.

I got my stake out, minus a bunch of gas fees, and got a couple bucks worth of $YFV back, which I then had to swap for $VALUE. Ok, I guess. I’ll just sit on this forever and see if it ever turns into anything.

The lesson here is that DeFi does not reward the timid. If you have less than a thousand dollars, you’re probably better off just keeping your money in BlockFi. Unless you’re a complete degen and want to ape into something with insane APY and risk getting rug pulled.

Currently, my main vault holdings are in the Yearn sBTC Curve vault. After that, it’s the Yearn BUSD vault. I’ve also got some Link in their yaLINK vault, which isn’t doing too well at the moment, but I can’t be bothered to move it right now.

My main strategy at the moment is to move funds that are locked into the Lending Club accounts I have earmarked for my kids, into stablecoins into various vaults. (This is on top of the BTC that I DCA for them into their BlockFi accounts.) I’m also trying to figure out the best way to maintain my cash flow between my expenses and lending platform. Moving in and out of vaults is expensive, so I’m trying to figure out the best way to do that. Quarterly, maybe? Keeping funds that need to be converted to cash in BlockFi for easy ACH back to fiat.

Keeping track of everything is proving to be quite the chore. I’m using a Notion database, but keeping track of where funds go, where they originated from (in the case of kids and other family members), and fees associated with the various conversions is a bit of a mess right now.

And tracking the value of the shares of these vaults outside of something like Zapper or DeBank is difficult. Right now I have no idea whether keeping cash in BlockFi at a stable eight percent with no fees is a better idea than trying to chase twenty percent plus with all the variability, contract risk, and fees.

I’ll keep working on a solution though. If you have one, please leave suggestions in the comments.

Uniswap limit orders

Most people who are used to trading on centralized exchanges are familiar with using limit orders, where one is able to set orders that are off from the market price. Automated market makers such as Uniswap don’t have these features, which makes trading Uniswap-only pairs a bit of a problem, especially when one is trying to take advantage of volatile tokens such as $PRIA.

I’ve been looking for ways to set limit orders with Uniswap, and after several dead ends I’ve found two that may work. One is an on-chain protocol, the other is a bot.

On-chain method

Pine.Finance calls itself an AMM order engine. They only support limit orders on Uniswap v1 and v2, but they say they plan on adding stop loss and market functionality across the DEX space, like Aave, Balancer, and others. In order to use it, you have to submit the input token along with your order details through an on-chain transaction, then wait. When the price hits the target, Pine’s network relayer’s should execute the transaction.

There’s a lot more detail in the link above. What is important to note is that each order gets its own order vault, meaning that your order input funds will be stored in a discrete Ethereum address. You can see them on chain.

The project is in beta, and hasn’t been audited, so this one is use at your own risk. I did go ahead and put in a very small order that I’m still waiting on to execute. The gas cost was nominal, about as much as a standard transfer, but I’ll also have to pay gas if I want to cancel the order. This is similar to the way that on-chain DEX like iDEX or Metamask have worked in the past, although Pine is a custodial solution, probably a requirement of the fact that the relayer pays the gas when they execute the trade (and arbitrages the difference).

[Update: Pine replied wanted to clarify the custodial claims:

I’ll need some more time to delve into the process used here. What I am sure of is that during the order process, a deterministic funds vault is created, and tokens are transferred to this vault. Even trusting that these funds are self-custodial, they are removed from the user’s wallet. This may be similar to how 0x works, as mentioned below, and I promise to do more research and follow up on this. ]

Bot method

LimitSwap is a Uniswap limit order bot that is available on Github. After downloading, you’ll need to export your private keys and configure several settings to get things up and running. Set the tokens you want to trade, set your prices, and then let it go. You’ll also need to hold LimitSwap’s $LIMIT token in your wallet in order for the bot to function.

That’s the promise, anyways. I wasn’t willing to actually give it a shot. The project’s sole developer, who goes by the handle Crypt0Gnome, seem legit, but has taken steps to obfuscate his code. I understand his motives is to fund his development efforts via the $LIMIT token and prevent people from easily modifying his code to circumvent this requirement, but I’m not willing to trust my private keys with something like that.

I won’t go too far into the technical details but to say that he’s written the bot in Python using a Flask front-end and packaged all the dependencies in the zip file. This may make it easy for Windows users to get up and running, but shocked me a bit when I went to download the source code and found an empty repo.

I’m not trying to be unjustly harsh here, Crypt0Gnome seems to be sincere and to be community focused. However, in addition to the closed source nature of the project, I did find the Flask interface buggy and less than polished, and it was hard to justify digging into it when all I wanted to do was set a single limit order for a small amount. I do hope Crypt0Gnome can find a way to fund his project and open it up so that others might contribute to it as well. We’ll see.

The search continues

So while I’ve decided to do a small test transaction with Pine for now, I’m still looking for other solutions, preferably non custodial ones. The 0x protocol may offer a solution if one can find relayers supporting the tokens one wishes to trade, but I’ll need to do more research on that front to say more.

The bot approach would also be preferred over a custodial, on-chain solution if one is willing to maintain the bot, but a closed source solution with a single dev is a bit to risky for me to use, let alone recommend to others.

Google is a graveyard of dead links and others looking for solutions to this problem, so there is a need for it, but for now it seems that there is no good solution. I’ll keep searching and will probably do more research into both of these solutions for a future update.

Quick PRIA Update

Spent some more time working on TheGraph today. Managed to get a subgraph up that shows PRIA transfers. I’ve got to study GraphQL to figure out how to use this, and modify the schema to make it usable. I think a lot of people want to see the top holders by address, and I’d like there to be a way to query the top burnable addresses. I thought of an incentive app that would use these results and allow people to push a button to sign a transaction to burn them, whilst reimbursing them for the gas plus a bonus.

It sounds like something that could be done, although it might need another contract deployed to pull it off properly. These kind of proposals should be voted on by the community, so I really think the first order of business is some kind of DAO or other voting mechanism among PRIA LP providers. If you’ve got experience with doing so, let me know.

Right now the liquidity pool is the only safe haven for tokens, but given the possibility for divergence loss during the run up, there might need to be a better way to incentivize liquidity. That also brings up another point as well: the deflationary phase might cause additional divergence, but on a net positive on the Eth side. The way I understand it, the Uniswap stake loses ETH value compared to hodling as the price appreciates, but loses value slower as the price depreciates. This needs further exploration before I can speak with certainty.

Image for post
The above chart shows an ETH/DAI pairing. Source: Understanding Uniswap Returns

It looks like there are many ways to play this game, and the more time I spend on it the more avenues I see.

I’m not gonna shill given all the uncertainty in the market, especially given the fact that US elections are less than a week away. That said, I’m pleasantly glad to see that PRIA is holding up well. There seems to be healthy liquidity and volume, and the TG/CT communities are pretty active. And we’re not even at 80k supply yet!

Source: Uniswap pair info

That said, my main holdings are still in BTC, and to a smaller extent, ETH. I’m very anxious about the election and what effects it’s having and will continue to have over the next few weeks. I’ve spent the last few months exiting from traditional equities, AMZN, NVIDA, TSLA, hoarding cash in anticipation of a buying opportunity. This week’s pullback, caused by lockdowns in Europe, no sign to COVID cases in US, and failure to launch a second stimulus package, was enough for me to pull the trigger. I’m all in.

So right now, a majority of holdings are in BTC, but I’ve got even more in my tax advantaged retirement account that is in Grayscales GBTC, ETHE, and GDLC products. I’ve also got mining companies like CAN, RIOT, and MARA, and Canadian-based exchange Voyager.

My bags are packed. Now I just need to sleep for a year.

Irresponsibly long

flying plane with contrail during nighttime

Today has been crazy. I woke up this morning to find that $BTC had made a bit of a run overnight, making a nice wick up from $11.2 to $11.4. I’m sitting on some cash in my IRA, and I was very tempted to add to my $GBTC position at market open. It seems like we’re at a turning point, and that things are going to move very, very quickly. As a reminder, in 2017, the price went from $11.6 to 19.8 in two days.

Ultimately, I didn’t do anything, which is fine, even though we had some healthy price action today. I often joke about being all-in on crypto, but it’s really not a joke. I’ve got some equity in my house, along with a mortgage, but pretty much all of my liquid assets are in crypto. Most of it is in BTC, and I’ve got Eth and other alts as well. I’ve got the bulk of my savings in my IRA savings. Most of it is rolled over from my 401k from my corporate days, and it has the benefit of allowing me tax-free gains. I don’t have exact percentages, but about a third of that is in $GBTC. Over the years I’ve been adding positions in $MARA, $RIOT, and Hive Blockchain, and I’ve recently opened positions into $ETHE and $GDLC.

So I’m pretty invested in the success of BTC right now. I understand that having all this money in correlated assets like this doesn’t spread the risk at all, but it feels better than putting it all in GBTC.

Until recently, the long-term plan for the liquid assets had been to wait until they were enough to pay off my debts, mainly the mortgage and student loan debt. I actually have a whiteboard on the fridge with the break-even numbers written down. I update the debts whenever a new statement comes in, and I’ve been updating the BTC price first thing every morning.

Now though, I can’t imagine actually selling everything. I do plan on taking some profits at a certain point, I have a target. But with the recent rise of DeFi platforms for lending and interest, it seems like a better approach to try and leverage some of these platforms to generate income.

That’s the difference between being rich and having wealth. It might take me longer to get to the point where I’ll have enough to live off the interest generated by lending, but if everything goes the way I anticipate, then selling my bitcoin to pay off my debts early could well be one of the worst financial mistakes I ever make.

A lesson: about eight years ago I needed a new car. I had been driving a $1500 Ford Escort for several years that I had bought after my last car had been repossessed. It was a junker. The insulation around the doors was torn out, so every time it rained water would pour in on me from above. After several years getting my life back together after a business bankruptcy, I decided that it was time for an upgrade. I decided to get a used BMW, and set my budget at $7500. After weeks of searching, I found the perfect car, but it was $8500. I decided to sell a small stake of some Netflix stock that had done very well, and used it to buy the car.

I loved the car, but fifteen year old BMWs need a lot of work, and I probably put another $3-5k into that car before I got rid of it three years ago. Before I did, I looked back at the price of that thousand dollars worth of Netflix stock that I sold and calculated the value.

Eighteen thousand dollars.

So yea, the next six months might see my holdings get to the point where I could liquidate them, pay half to Uncle Sam, and pay off all my debt. But now, I fully expect bitcoin to go 4x from that point, enough to generate income for the rest of my life. Enough FU money to say “no” to almost anything, and have the financial freedom and independence that most can only dream about.

My dad recently retired, my mom did so a few years ago, and my wife’s parents did so recently as well. They worked their entire lives, making a life for themselves and raising us right. And my wife and I have been fortunate beyond belief to be not only surviving during this pandemic, but thriving. We talk every day about what’s going on, and I’m more confident that ever that our plans are going to work out.

Crypto Twitter is abuzz right now, and everyone is excited. I’m trying to remain calm and prepare for the craziness that is going to happen when BTC hits another all time high. It’s going to happen fast.

Even now, at the end of the day, bitcoin is still minting new yearly highs. I only hope that the feeling I feel right now isn’t greed, it’s opportunity.

This Saturday, Halloween, is the anniversary of the Bitcoin whitepaper. Satoshi had a strike of genius timing the halvings around the US Presidential elections. I’m not sure how much of what we’re seeing is in anticipation of a Trump or a Biden win, but the divergence to the stock market, which is reacting negatively to a rise in COVID cases, could just be the start.

I’ve been packing for this rocket ship for years, during this entire bull market. The fuel is loaded, the trajectory is set, and I’m strapped into my seat listening to the countdown. Now I’m searching my mind wondering if there’s room enough for a little bit more mass, an extra oomph that will take us out of the solar system and get us to Alpha Centauri a little bit faster.

I, and you, better act fast, cause liftoff ain’t gonna wait for either of us.

PRIA explainer webcast

I finally got around to doing a $PRIA explainer video with @EnderleTres, A.K.A CryptoDaddio last night. We talked for about a half hour.

https://www.youtube.com/watch?v=n2l91CNjXIw

I didn’t want to dox myself. Instead of a disguise I wound up buying a copy of FaceRig, and made gave the interview as a Marvin The Martian type character. It came out all right. The program is pretty genius, although lighting, glasses and headset complicate the face tracking. The girls wouldn’t leave it alone while I was setting it up. There’s lots of princess models and anime characters.


And just to point out how Wild West crypto and DeFi is right now, just this morning I learned the Harvest.Finance got hacked for $25 million.

Harvest explained the attack here, and has moved to protect the other funds (thread).

And I know a lot of devs and hackers will be going through the history here to figure out how these flash loan attacks work.

Unpacking PRIA

Yesterday I was a bit of a mess, as I made the mistake of watching the presidential debate the night before and stayed up way too late. I’ve been doing very badly with my habits lately. I spent most of the day in a funk.

After I woke up, the first thing i did was checked the price of $PRIA. It was up another $20, and peaked at $83 early before settling back down. It’s quite the run over the last few days and has left me in a bit of an awkward position, of being in a winning position and indecisive about what to do next.

There was a flurry of activity in the Telegram group, and a load of drama after someone decided to copy and paste the PRIA token contract code into another token. They called it a fork, but they didn’t know what they were doing. For one, they didn’t change the date that allowed one to burn the owner functions, like setting the airdrop address and exempting the Uniswap pools from the inactivity burn. Dr. Mantis, the creator of PRIA, saw this and pulled the killswitch, and banned a bunch of people from the Telegram group as a result.

Despite my inability to focus yesterday, I did manage to get some work for Zombie, LLC, and I did continue coding on my PRIA bot. At this point I’m not sure that my strategy will ever be profitable, since others seem to be running some sort of similar strategy. I’m having some trouble with dependencies in my Node project, and am running into some issues with the fact that I seem to have wound up with both web3 and ethers, and am having some bugs due to there being several big number packages in the modules, one of which seems to be an older version. I thought that I would be able to simulate the PRIA contract code in Javascript in order to get an accurate payout of the airdrop as it cycles to the next two hundred slots, but achieving precision is proving difficult.

My involvement with the project is also making me somewhat uncomfortable. I got involved cause I wanted to understand the contract code, and I seem to have put myself the position of being a community leader. I’ve been messaging with the creator constantly with questions about how things work, and have been answering questions in the group to explain how things work. I have been rewarded eight times over what I initially put in as a test.

As a result I’m basically looking at a month’s salary for the last week’s efforts. And the truth is, I am still very skeptical about this project. It’s about a tenth of the way through this turn one burn cycle, and despite the flurry of activity, I’m still not convinced it has enough gas to get there and back, let alone all the way through one of these “ultracycles”. Some of the moonboy chatter that I’m seeing is not really anything I want to be associated with, and I feel like I’m in a very, very tough spot.

When it comes down to it, PRIA is a game, and it’s an insanely complicated one. People are throwing numbers out like $100 or $1000 or higher, and one of the problems I have is that there are many, many fresh faces that are coming in here trying to get on board with this. I’m gauging my assessment based on the number of Twitter followers that I see shilling.

I don’t want to be a part of it, but I already am a part of it, so what do I do about that?

Two nights ago, during the debate, I was in telegram chat trying to make some of these concerns known, trying to advise caution. At one point I mentioned that the creator “erred” by not making the contract upgradable, and some people got really panicky. “Why admin FUD,” or “why mod FUD,” went up. A couple people, more experienced in the space I guess, DMed me to say they understood or agreed with me. My final word on the matter was that the project was going to survive or not in spite of what I had to say on the matter.

So I was a bit shocked when I woke up to see another twenty dollar pump.

I don’t want to do price projections, but I may as well. I’m paying attention to the ETH pair. We’ll see what it does here on the short term.

Chart via DexTools

The uptrend line hits 1:1 with ETH near the end of the month, which seems impossible, granted. If there’s a lot of volume that drives the supply down fast enough, it may drive the price upward, but I don’t think the trend is going to hold. This level does seem to be pretty good support, we’ll see if it holds or if we trend sideways for a while. The market cap has dropped from $5.2 million down to $4.2, and with the supply floor on this turn set to 10,000 PRIA, does that mean that we could see $400-500 PRIA?

I’m not sure, but for now, I’m content to let my bags sit for a few more days and see what happens. This turn might take a while, and we’ll see how things go for now.


Finally, a quick look at the weekly $BTC chart, just for a bit of perspective. We’ve got another day and a half to close this last candle, which could be the highest weekly close since November 27, 2017.

Numbers in Etherum and Javascript

So I feel like I made some significant progress today after going through this piece on numbers in Ethereum and Javascript. It’s quite a bit of trouble, especially because of the way that numbers and storage is returned from web3 call() and getStorageAt() functions.

Case in point, I’m trying to compute the sum of a Ethereum amount multiplied by a percentage. Both values are stored in wei, which has eighteen decimal points. If one simply multiplies the two together, you get a rate that is actually off by another 10^18, so the result of the division needs to be divided by this factor before it is returned.

The web3 library in Javascript relies on BN.js, which stands for big number. It doesn’t work on decimals, they have to be passed as strings. So I can’t just pass 10**18 to make a big number, I have to return it as a string.

let BN = web3.utils.BN;
let decimal = new BN((10**18).toString())
let balance = new BN("196144358288748402370");
let rate = new BN("2500000000000000");
let result = balance.mul(rate).div(decimal);
console.log("Result: " + web3.utils.fromWei(result));
> Result: 0.490360895721871005

Performing this percentage calculation in Vyper is simple arithmetic, where all the numbers are uint256.

res: uint256 = (balance * pct) / 10 ** 18

Wash trading PRIA for airdrop slots

Things are nuts right now.

I’ve spent most of my time thinking about PRIA and how to game it. I there’s a way to compute the minimum future airdrop payout. By comparing that to the current price and gas costs of a transaction, one can sell the future payout for ETH, burn that eth for gas on a transfer, and will be guaranteed at least the same amount of PRIA back in a future airdrop, two hundred blocks later. That’s the plan at least.

I’m still working out the calculations. I can only estimate the gas as this point, and I’ve still got to simulate the transfer cost, which includes burn, treasury and airdrop fees. This holds increases at some point during the airdrop cycle, so the question is whether I code this up in the main Javascript module that I’m creating, or set up an actual contract in Truffle that I can run it against. I’m not sure yet.

What I do know is I woke up this morning to find a huge run up on price. Gas costs are still high enough that it means flooding the airdrop queue will cost more than the ultimate payout, but if one assumes that PRIAs deflationary price action will continue, then one may be willing to risk more.

We’re also talking profitability from a minimum future payout. One can assume that the actual future payout will be higher than the minimum, since any transaction with a fee larger than the airdrop payout will increase the airdrop balance, not drain it.

I have also determined that flooding the entire airdrop queue in one transaction is likely impossible, due to gas costs, and I believe the upper bound is around 20 at a time. Still, I should be possible to sell PRIA on Uniswap, and self transfer enough to qualify for a spot on the queue in one transaction. One could cover gas costs, and insure that you get back at least as much as the total costs, both the gas fees and any transfer funds.

This process would theoretically allow someone to accumulate PRIA with zero capital risk. They would basically be arbitraging the costs now for the expected payout on the next airdrop cycle.

$PRIA price chart

On top of all this, it looks like $BTC has crossed a critical threshold. I had to zoom out on the weekly to get a bit of perspective on this.

Not only have we broached the critical rsistance line at $12,060, but we’re also about to break through a multi-year uptrend support that was only breached by the COVID-dump. We saw a little bit of action above this line a few months ago. And yes, I know these kinds of lines on a log scale aren’t sustainable, but it’s clear to me that we are in a bull market.

The orange line at the top is a moving profit-taking target based on the Mayer Multiple, the factor of price to the 200-day moving average. I calculated the 2017 peak to be around 2.8 times, so when we get to that price level, I plan to take some profits.

I had that feeling this morning that things were happening. Recently, I saw a Tweet that said if you feel like bragging, then it’s time to sell.

I’m starting to feel that way right now.

Calling Ethereum contract methods in Javascript

I am still trying to wrap my head around Javascript’s Promises and how to use them properly. I did make some progress today and managed to get some data off of the PRIA contract using web3.

A lot of my confusion stems from the behavior of the JS arrow function. I now understand it in relation to a Python lambda function. And now that I’ve figured out how to create an anonymous async function in Javascript, I think I’ve opened another door in my mind that is going to make this a bit easier to work with. I feel like I’ve leveled up.

I’ve create a small class that I can use to pull the data from the chain. I’m using Alchemy’s API to do this, my key is stored in an .env file.

// pria.js

require('dotenv').config()

const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
const web3 = createAlchemyWeb3(process.env.ALCHEMY_URL);
const priaContract = "0xb9871cb10738eada636432e86fc0cb920dc3de24";
const PRIA_ABI = [{"OMITTED FOR BREVITY"}] // copied from Remix or Etherscan

class Pria {
    constructor() {
        this.contract = web3.eth.Contract(PRIA_ABI, priaContract);
        this.airdrop_threshold = "2500000000000000";

        (async () => {
            await this.init();
            console.log(this.airdropAddressCount);
            console.log(this.burnRate);
            console.log(this.minimumForAirdrop);
            console.log(this.totalSupply);
            console.log(this.tx_n);
        })();
    }

    async init() {
        this.airdropAddressCount = await this.contract.methods.airdropAddressCount().call();
        this.burnRate = await this.contract.methods.burnRate().call();
        this.minimumForAirdrop = await this.contract.methods.minimum_for_airdrop().call();
        this.totalSupply = await this.contract.methods.totalSupply().call();
        this.tx_n = await this.contract.methods.tx_n().call();
        return true;
    }
}

There are various ways to call async functions from a class constructor. I’m probably not doing it very elegantly, but I think I understand the how to use immediately invoked function expressions. These self-executing anonymous functions remind me a lot of Lisp and lambda calculus.

I’ll be using the Pria class within additional code to calculate the cost of spamming the PRIA airdrop list as I described earlier. There are additional state variables that I need to retrieve from the contract. These aren’t public, so I’ll have to do some more hacking to pull them directly from storage, after I figure out where to look.

Once that’s done I’ll have my application logic code compute the cost of two hundred transactions and compute the price to dump all the gained tokens on Uniswap. Then the exciting part will be waiting for it to become profitable.

Evil ether auction

Thinking about the game theory behind PRIA has taken up most of my thoughts lately, and I recently had an idea that I wanted to jot down quickly.

A recent Bankless post send me down a series of links to the diabolical dollar auction, which is also called an all-pay auction. It’s actually quite evil. The only way to win is not to play, otherwise, players will wind up overpaying. There are variations on this, depending on whether you have one player or just two, or if all losing bids get paid or whether just the the top two. There’s also a variant where the bidders have to pay a fee to bid. In all of these variations, the winner is usually the one running the auction.

A cursory search shows several variations on auction contracts in Ethereum, including a way to do a blind one. However, I couldn’t find any examples of anyone implementing such a contract in real life.

So, is it possible to arrange an ether auction? Yes, I’m fairly certain. Would it work, maybe. It might even be possible to create an auction factory that creates a new auction after the last one is done, spawning a new auction and siphoning off gas from the bids each time someone interacts with it. Would it be ethical?

Probably not.