Skip to content

Commit

Permalink
Merge pull request #1980 from gitcoinco/kevin/gas-guzzlers
Browse files Browse the repository at this point in the history
gas guzzlers in gas station
  • Loading branch information
owocki authored Aug 10, 2018
2 parents f170eba + fa49a6a commit 2132072
Show file tree
Hide file tree
Showing 7 changed files with 289 additions and 169 deletions.
1 change: 1 addition & 0 deletions app/app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@
url(r'^gas/intro/?', dashboard.gas_views.gas_intro, name='gas_intro'),
url(r'^gas/calculator/?', dashboard.gas_views.gas_calculator, name='gas_calculator'),
url(r'^gas/history/?', dashboard.gas_views.gas_history_view, name='gas_history_view'),
url(r'^gas/guzzlers/?', dashboard.gas_views.gas_guzzler_view, name='gas_guzzler_view'),
url(r'^gas/?', dashboard.gas_views.gas, name='gas'),

# images
Expand Down
59 changes: 50 additions & 9 deletions app/dashboard/gas_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@
from django.conf import settings
from django.core.cache import cache
from django.template.response import TemplateResponse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _

from economy.utils import convert_amount
from gas.models import GasGuzzler
from gas.utils import conf_time_spread, gas_advisories, gas_history, recommend_min_gas_price_to_confirm_in_time

from .helpers import get_bounty_data_for_activity, handle_bounty_views
Expand All @@ -34,6 +36,16 @@

confirm_time_minutes_target = 4

lines = {
1: 'red',
5: 'orange',
60: 'green',
90: 'steelblue',
105: 'purple',
120: '#dddddd',
180: 'black',
}


def get_history_cached(breakdown, i):
timeout = 60 * 60 * 3
Expand Down Expand Up @@ -154,19 +166,48 @@ def gas_calculator(request):
return TemplateResponse(request, 'gas_calculator.html', context)


def gas_guzzler_view(request):
breakdown = request.GET.get('breakdown', 'hourly')
breakdown_ui = breakdown.replace('ly', '') if breakdown != 'daily' else 'day'
num_guzzlers = 10
gas_histories = {}
_lines = {}
top_guzzlers = GasGuzzler.objects.filter(created_on__gt=timezone.now()-timezone.timedelta(minutes=60)).order_by('-pct_total')[0:num_guzzlers]
counter = 0
colors = [val for key, val in lines.items()]
for guzzler in top_guzzlers:
address = guzzler.address
_lines[address] = colors[counter % len(colors)]
gas_histories[address] = []
for og in GasGuzzler.objects.filter(address=address).order_by('created_on'):
if not og.created_on.hour < 1 and breakdown in ['daily', 'weekly']:
continue
if not og.created_on.weekday() < 1 and breakdown in ['weekly']:
continue
unit = int((timezone.now() - og.created_on).seconds / 3600)
gas_histories[address].append([float(og.pct_total), unit])
counter += 1


max_y = 100
context = {
'title': _('Gas Guzzlers'),
'card_desc': _('View the gas guzzlers on the Ethereum Network'),
'max': max_y,
'lines': _lines,
'gas_histories': gas_histories,
'breakdown': breakdown,
'breakdown_ui': breakdown_ui,
'granularity_options': ['hourly', 'daily', 'weekly'],
}

return TemplateResponse(request, 'gas_guzzler.html', context)


def gas_history_view(request):
breakdown = request.GET.get('breakdown', 'hourly')
gas_histories = {}
max_y = 0
lines = {
1: 'red',
5: 'orange',
60: 'green',
90: 'steelblue',
105: 'purple',
120: '#dddddd',
180: 'black',
}
for i in lines.keys():
gas_histories[i] = get_history_cached(breakdown, i)
for gh in gas_histories[i]:
Expand Down
174 changes: 174 additions & 0 deletions app/dashboard/templates/shared/gas_history.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
{% comment %}
Copyright (C) 2018 Gitcoin Core

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
{% endcomment %}

<style> /* set the CSS */

.axis {
font-family: Arial, Helvetica, sans-serif;
font-size: .8em;
}

.line {
fill: none;
stroke: steelblue;
stroke-width: 2px;
}
{% for key, val in lines.items %}
.line.line_{{key}} {
stroke: {{val}};
}
{% endfor %}
div.tooltip {
position: absolute;
max-width: 300px;
padding: 3px 6px;
color: grey;
font-family: 'Droid Sans Mono', monospace;
font-size: .7em;
background: whitesmoke;
border: 1px solid grey;
border-radius: 3px;
pointer-events: none;
z-index: 9999;
}
@media screen and (min-width: 901px) {
#key {
right: 100px;
float: right;
top: 270px;
position: absolute;
}
}
@media screen and (max-width: 900px) {
#key {
position: initial;
}
}
#key{
text-align: right;
}
#key p{
margin: 0px;
font-size: 12px;
}

</style>

<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

var tooltip;

tooltip = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);

var margin = {top: 20, right: 20, bottom: 50, left: 70},
width = window.innerWidth - 100 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var initialWidth = width;
var xScale = d3.scaleLinear().range([width, 0]);
var yScale = d3.scaleLinear().range([height, 0]);

// define the line
var valueline = d3.line()
.x(function(d) { return xScale(d.confirmation_time); })
.y(function(d) { return yScale(d.gas_price); });

var svg = d3.select("#graph")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

{% for key, gas_history in gas_histories.items %}
var source = {{gas_history | safe}};
data = []
source.forEach(function(d) {
d['confirmation_time'] = parseFloat(d[1])
d['gas_price'] = parseFloat(d[0]);
d.splice(0,2);
data.push(d);
});

xScale.domain([0, d3.max(data, function(d) { return d.confirmation_time; })]).nice();
yScale.domain([0, d3.max(data, function(d) { return {{max}}; })]).nice();

svg.append("path")
.data([data])
.attr("class", "line line_{{key}}")
.attr("d", valueline);

{% endfor %}

// x Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(xScale));

// text label for the x axis
svg.append("text")
.attr("transform",
"translate(" + (width/2) + " ," +
(height + margin.top + 20) + ")")
.style("text-anchor", "middle")
.attr("class", "axis")
.attr("class", "x-title")
.text("{{breakdown_ui}}-ago");

// y Axis
svg.append("g")
.call(d3.axisLeft(yScale));

// text label for the y axis
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x",0 - (height / 2))
.attr("dy", "2em")
.attr("class", "axis")
.style("text-anchor", "middle")
.text("Gas Price (gwei)");

function resize() {
var newWidth = window.innerWidth - 100 - margin.left - margin.right;
var height = 500 - margin.top - margin.bottom;
if(newWidth < initialWidth) { // initialWidth determines max width of parent div in a way

// Update the range of the scale with new width/height
xScale.range([newWidth, 0]);
yScale.range([height, 0]);

svg.select(".x.axis") // resizes x axis
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(xScale));

svg.select(".x-title") // resizes the positioning of the x axis title
.attr("transform","translate(" + (newWidth/2) + " ," + (height + margin.top + 20) + ")")
.style("text-anchor", "middle");

svg.append("path") // updates line data to conform
.data([data])
.attr("class", "line line_{{key}}")
.attr("d", valueline);
}
}
// Call the resize function whenever a resize event occurs
d3.select(window).on('resize', resize);

</script>
3 changes: 3 additions & 0 deletions app/dashboard/templates/shared/gas_nav.html
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@
<li>
<a href="{% url 'gas_history_view' %}">Price History</a>
</li>
<li>
<a href="{% url 'gas_guzzler_view' %}">Gas Guzzlers</a>
</li>
<li>
<a href="{% url 'gas_calculator' %}"> Gitcoin Contract Gas Cost Calculator</a>
</li>
Expand Down
8 changes: 5 additions & 3 deletions app/retail/management/commands/warm_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,11 @@ def handle(self, *args, **options):
paths = [reverse('results') + f"/{pl}" for pl in programming_languages]
paths.append(reverse('results'))
paths.append(reverse('activity'))
paths.append(reverse('gas_history_view'))
paths.append(reverse('gas_history_view') + "?breakdown=daily")
paths.append(reverse('gas_history_view') + "?breakdown=weekly")
for name in ['gas_history_view', 'gas_guzzler_view']:
path = reverse(name)
paths.append(path)
paths.append(path + "?breakdown=daily")
paths.append(path + "?breakdown=weekly")
paths.append(reverse('gas'))

# warm the paths
Expand Down
55 changes: 55 additions & 0 deletions app/retail/templates/gas_guzzler.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
{% extends 'onepager/base.html' %}
{% load i18n static %}
{% block 'scripts' %}
<script src="{% static "v2/js/jquery.js"%}"></script>
{% endblock %}
<!-- Main -->

{% block 'world' %}
<canvas id="world" style="position:absolute; top:0px; left: 0px;">
</canvas>
{% endblock %}

{% block 'main' %}

<section id=main>
{% include 'shared/gas_nav.html' %}

<h1> {% trans "Gas Guzzlers" %} ({{breakdown}}) <span id="alpha">{% trans "Alpha" %}</span> </h1>
<p>These are the addresses that are using the most gas</p>
<ul class="gas_nav small">
{% for granularity in granularity_options %}
<li>
<a href="{%url 'gas_guzzler_view'%}?breakdown={{granularity}}">{{granularity}} view</a>
</li>
{% endfor %}
</ul>


<div id="key">
{% for key, val in lines.items %}
<p style="color:{{val}}">{% trans "Address no. " %} {{key}} {% trans "." %}</p>
{% endfor %}
</div>

{% if gas_histories == '[]' %}
<p>
{% blocktrans %} We are unable to sync gas data at this time. We recommend you check out <a href="https://ethgasstation.info/predictionTable.php" target="_blank" rel="noopener noreferrer">ETH Gas Station</a> instead.{% endblocktrans %}
</p>
{% else %}
<svg id="graph"></svg>
{% include 'shared/gas_history.html' %}
{% include 'shared/disqus.html' with page_url='https://gitcoin.co/gas/history?' %}

</div>

</div>
<script>
</script>


{% endif %}

</section>

{% endblock %}
Loading

0 comments on commit 2132072

Please sign in to comment.