Skip to content

Instantly share code, notes, and snippets.

@GalloDaSballo
Last active August 6, 2022 17:38
Show Gist options
  • Save GalloDaSballo/1f86b550b45975445848bec61353f45e to your computer and use it in GitHub Desktop.
Save GalloDaSballo/1f86b550b45975445848bec61353f45e to your computer and use it in GitHub Desktop.
Compare order of operations with wdiv and wmul
from random import seed
from random import random
NUMBER_OF_SIMS = 100_000
TOKEN_AMOUNT_MIN = 0
TOKEN_AMOUNT_MAX = 10 ** 26
"""
uint256 inkAtEnd = uint256(artIn).wdiv(auction_.art).wmul(auction_.ink);
"""
def wmul(x, y):
"""
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x * y;
unchecked { z /= 1e18; }
}
"""
z = x * y
z = z // 10 ** 18
return z
def wdiv(x , y):
"""
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = (x * 1e18) / y;
}
"""
z = x * 10 ** 18 // y
return z
def simulation():
artIn = int(random() * TOKEN_AMOUNT_MAX) + TOKEN_AMOUNT_MIN
art = int(random() * TOKEN_AMOUNT_MAX) + TOKEN_AMOUNT_MIN
ink = int(random() * TOKEN_AMOUNT_MAX) + TOKEN_AMOUNT_MIN
total = artIn + art + ink
## uint256 inkAtEnd = uint256(artIn).wdiv(auction_.art).wmul(auction_.ink);
inkAtEnd_code = wmul(wdiv(artIn, art), ink)
## uint256 inkAtEnd = uint256(artIn).wmul(auction_.ink).wdiv(auction_.art);
inkAtEnd_reverse = wdiv(wmul(artIn, ink), art)
inkAtEnd_python = int(artIn * ink / art)
diff = inkAtEnd_code - inkAtEnd_python
diff_hypothetical = inkAtEnd_reverse - inkAtEnd_python
diff_of_methods = inkAtEnd_code - inkAtEnd_reverse
## Extra logs for small sims
if (NUMBER_OF_SIMS < 11):
print("diff")
print(diff)
print("diff_hypothetical")
print(diff_hypothetical)
print("diff_of_methods")
print(diff_of_methods)
print("python_diff")
print(diff - diff_hypothetical)
diff_of_diffs = diff_of_methods
return diff_of_diffs
def main():
counter = 0
relative_cumulative = 0
for x in range(NUMBER_OF_SIMS):
dust = simulation()
if dust != 0:
counter += 1
relative_cumulative += dust
print("counter")
print(counter)
print("relative_cumulative")
print(relative_cumulative)
print("avg relative cumulative")
print(relative_cumulative / NUMBER_OF_SIMS)
print("As % of 1e18")
print(relative_cumulative / NUMBER_OF_SIMS / 10 ** 18 * 100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment