Skip to content

Commit

Permalink
Fix #90 - Fix pylint errors (#93)
Browse files Browse the repository at this point in the history
Fix #90
  • Loading branch information
trentmc authored Aug 24, 2023
1 parent 0827faf commit ca22d47
Show file tree
Hide file tree
Showing 37 changed files with 193 additions and 163 deletions.
8 changes: 4 additions & 4 deletions pdr_backend/dfbuyer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def numbers_with_sum(n: int, k: int) -> List[int]:
if n == 1:
return [k]
# If n > k, it's impossible to generate n positive integers summing to k.
elif n > k:
if n > k:
return []

# Generate n-1 unique random integers between 1 and k-1
Expand All @@ -57,13 +57,13 @@ def numbers_with_sum(n: int, k: int) -> List[int]:
return [a[i + 1] - a[i] for i in range(len(a) - 1)]


""" Get all intresting topics that we can predict. Like ETH-USDT, BTC-USDT """
# Get all intresting topics that we can predict. Like ETH-USDT, BTC-USDT
topics: Dict[str, dict] = {}


def process_block(block):
"""Process each contract and see if we need to submit"""
global topics
""" Process each contract and see if we need to submit """
if not topics:
topics = query_predictContracts(
subgraph_url,
Expand All @@ -82,7 +82,7 @@ def process_block(block):
topics, estimated_week_start, owner, subgraph_url
)
print(f"consume_so_far:{consume_so_far}")
consume_left = float(getenv("WEEKLY_SPEND_LIMIT", 0)) - consume_so_far
consume_left = float(getenv("WEEKLY_SPEND_LIMIT", "0")) - consume_so_far
print(f"consume_left:{consume_left}")
if consume_left <= 0:
return
Expand Down
7 changes: 1 addition & 6 deletions pdr_backend/dfbuyer/subgraph.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
import json
import os
import requests
import web3

from pdr_backend.util.subgraph import query_subgraph


Expand All @@ -12,7 +7,7 @@ def get_consume_so_far(
chunk_size = 1000 # max for subgraph = 1000
offset = 0
consume_so_far = 0
while True:
while True: # pylint: disable=too-many-nested-blocks
query = """
{
predictContracts(skip:%s, first:%s){
Expand Down
2 changes: 1 addition & 1 deletion pdr_backend/dfbuyer/test/conftest.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from pdr_backend.conftest_ganache import *
from pdr_backend.conftest_ganache import * # pylint: disable=wildcard-import
2 changes: 0 additions & 2 deletions pdr_backend/dfbuyer/test/test_main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import random

import pytest

from pdr_backend.dfbuyer.main import numbers_with_sum
Expand Down
54 changes: 26 additions & 28 deletions pdr_backend/models/predictoor_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@


@enforce_types
class PredictoorContract:
class PredictoorContract: # pylint: disable=too-many-public-methods
def __init__(self, config: Web3Config, address: str):
self.config = config
self.contract_address = config.w3.to_checksum_address(address)
Expand Down Expand Up @@ -94,18 +94,17 @@ def buy_and_start_subscription(self, gasLimit=None, wait_for_receipt=True):
"""Buys 1 datatoken and starts a subscription"""
fixed_rates = self.get_exchanges()
if not fixed_rates:
return
return None

(fixed_rate_address, exchange_id) = fixed_rates[0]

# get datatoken price
exchange = FixedRate(self.config, fixed_rate_address)
(
baseTokenAmount,
oceanFeeAmount,
publishMarketFeeAmount,
consumeMarketFeeAmount,
) = exchange.get_dt_price(exchange_id)
(baseTokenAmount, _, _, _) = exchange.get_dt_price(exchange_id)

# approve
self.token.approve(self.contract_instance.address, baseTokenAmount)

# buy 1 DT
gasPrice = self.config.w3.eth.gas_price
provider_fees = self.get_empty_provider_fee()
Expand Down Expand Up @@ -135,7 +134,7 @@ def buy_and_start_subscription(self, gasLimit=None, wait_for_receipt=True):
call_params = {
"from": self.config.owner,
"gasPrice": gasPrice,
# 'nonce': self.config.w3.eth.get_transaction_count(self.config.owner),
# 'nonce': self.config.w3.eth.get_transaction_count(self.config.owner),
}
if gasLimit is None:
try:
Expand All @@ -161,9 +160,9 @@ def buy_many(self, how_many, gasLimit=None, wait_for_receipt=False):
"""Buys multiple accesses and returns tx hashes"""
txs = []
if how_many < 1:
return
return None
print(f"Buying {how_many} accesses....")
for i in range(0, how_many):
for _ in range(0, how_many):
txs.append(self.buy_and_start_subscription(gasLimit, wait_for_receipt))
return txs

Expand All @@ -176,21 +175,17 @@ def get_stake_token(self):
def get_price(self):
fixed_rates = self.get_exchanges()
if not fixed_rates:
return
return None
(fixed_rate_address, exchange_id) = fixed_rates[0]
# get datatoken price
exchange = FixedRate(self.config, fixed_rate_address)
(
baseTokenAmount,
oceanFeeAmount,
publishMarketFeeAmount,
consumeMarketFeeAmount,
) = exchange.get_dt_price(exchange_id)
(baseTokenAmount, _, _, _) = exchange.get_dt_price(exchange_id)
return baseTokenAmount

def get_current_epoch(self) -> int:
# curEpoch returns the timestamp of current candle start
# this function returns the "epoch number" that increases by one each secondsPerEpoch seconds
# this function returns the "epoch number" that increases
# by one each secondsPerEpoch seconds
current_epoch_ts = self.get_current_epoch_ts()
seconds_per_epoch = self.get_secondsPerEpoch()
return int(current_epoch_ts / seconds_per_epoch)
Expand Down Expand Up @@ -248,17 +243,20 @@ def submit_prediction(
wait_for_receipt=True,
):
"""
Submits a prediction with the specified stake amount to the smart contract on the blockchain.
Submits a prediction with the specified stake amount, to the contract.
@param predicted_value: The predicted value (True or False)
@param stake_amount: The amount of ETH to be staked on the prediction
@param prediction_ts: The prediction timestamp, must be the start timestamp of a candle.
@param wait_for_receipt: If True, the function waits for the transaction receipt after submission.
If False, it returns immediately after sending the transaction. Default is True.
@return: If wait_for_receipt is True, returns the transaction receipt.
If wait_for_receipt is False, returns the transaction hash immediately after sending the transaction.
If an exception occurs during the process, returns None.
@param prediction_ts: The prediction timestamp == start a candle.
@param wait_for_receipt:
If True, waits for tx receipt after submission.
If False, immediately after sending the transaction.
Default is True.
@return:
If wait_for_receipt is True, returns the tx receipt.
If False, returns the tx hash immediately after sending.
If an exception occurs during the process, returns None.
"""
amount_wei = self.config.w3.to_wei(str(stake_amount), "ether")

Expand All @@ -279,7 +277,7 @@ def submit_prediction(
try:
txhash = None
if is_sapphire_network(self.config.w3.eth.chain_id):
data = self.contract_instance.encodeABI(
self.contract_instance.encodeABI(
fn_name="submitPredval",
args=[predicted_value, amount_wei, prediction_ts],
)
Expand Down
2 changes: 1 addition & 1 deletion pdr_backend/models/test/conftest.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from pdr_backend.conftest_ganache import *
from pdr_backend.conftest_ganache import * # pylint: disable=wildcard-import
4 changes: 2 additions & 2 deletions pdr_backend/models/test/test_fixed_rate.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
def test_FixedRate(predictoor_contract, web3_config):
exchanges = predictoor_contract.get_exchanges()
address = exchanges[0][0]
id = exchanges[0][1]
id_ = exchanges[0][1]
print(exchanges)
rate = FixedRate(web3_config, address)
assert rate.get_dt_price(id)[0] / 1e18 == approx(3.603)
assert rate.get_dt_price(id_)[0] / 1e18 == approx(3.603)
10 changes: 5 additions & 5 deletions pdr_backend/models/test/test_predictoor_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@

@enforce_types
def test_get_id(predictoor_contract):
id = predictoor_contract.getid()
assert id == 3
id_ = predictoor_contract.getid()
assert id_ == 3


@enforce_types
def test_is_valid_subscription_initially(predictoor_contract):
is_valid_sub = predictoor_contract.is_valid_subscription()
assert is_valid_sub == False
assert not is_valid_sub


@enforce_types
Expand All @@ -42,7 +42,7 @@ def test_buy_and_start_subscription(predictoor_contract):
receipt = predictoor_contract.buy_and_start_subscription()
assert receipt["status"] == 1
is_valid_sub = predictoor_contract.is_valid_subscription()
assert is_valid_sub == True
assert is_valid_sub


@enforce_types
Expand Down Expand Up @@ -130,7 +130,7 @@ def test_submit_prediction_aggpredval_payout(predictoor_contract, ocean_token: T
prediction = predictoor_contract.get_prediction(
soonest_timestamp, predictoor_contract.config.owner
)
assert prediction[0] == True
assert prediction[0]
assert prediction[1] == 1e18

predictoor_contract.config.w3.provider.make_request(
Expand Down
2 changes: 1 addition & 1 deletion pdr_backend/models/token.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,5 @@ def approve(self, spender, amount, wait_for_receipt=True):
if not wait_for_receipt:
return tx
return self.config.w3.eth.wait_for_transaction_receipt(tx)
except:
except: # pylint: disable=bare-except
return None
33 changes: 19 additions & 14 deletions pdr_backend/predictoor/approach1/main.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
from datetime import datetime, timedelta, timezone
from os import getenv
import time
import threading
from threading import Thread
from typing import Dict

from pdr_backend.models.predictoor_contract import PredictoorContract
Expand All @@ -28,8 +25,11 @@


def process_block(block):
"""
Process each contract.
If needed, get a prediction, submit it and claim revenue for past epoch
"""
global topics
""" Process each contract and if needed, get a prediction, submit it and claim revenue for past epoch """
if not topics:
topics = query_predictContracts(
subgraph_url,
Expand All @@ -50,40 +50,45 @@ def process_block(block):
epoch * seconds_per_epoch + seconds_per_epoch - block["timestamp"]
)
print(
f"\t{topic['name']} (at address {topic['address']} is at epoch {epoch}, seconds_per_epoch: {seconds_per_epoch}, seconds_till_epoch_end: {seconds_till_epoch_end}"
f"\t{topic['name']} (at address {topic['address']} "
f"is at epoch {epoch}, seconds_per_epoch: {seconds_per_epoch}"
f", seconds_till_epoch_end: {seconds_till_epoch_end}"
)

if epoch > topic["last_submited_epoch"] and topic["last_submited_epoch"] > 0:
# let's get the payout for previous epoch. We don't care if it fails...
slot = epoch * seconds_per_epoch - seconds_per_epoch
print(
f"Contract:{predictoor_contract.contract_address} - Claiming revenue for slot:{slot}"
f"Contract:{predictoor_contract.contract_address} - "
f"Claiming revenue for slot:{slot}"
)
predictoor_contract.payout(slot, False)

if seconds_till_epoch_end <= int(getenv("SECONDS_TILL_EPOCH_END", 60)):
"""Timestamp of prediction"""
if seconds_till_epoch_end <= int(getenv("SECONDS_TILL_EPOCH_END", "60")):
# Timestamp of prediction
target_time = (epoch + 2) * seconds_per_epoch

"""Let's fetch the prediction """
# Fetch the prediction
(predicted_value, predicted_confidence) = predict_function(
topic, target_time
)
if predicted_value is not None and predicted_confidence > 0:
"""We have a prediction, let's submit it"""
# We have a prediction, let's submit it
stake_amount = (
getenv("STAKE_AMOUNT", 1) * predicted_confidence / 100
) # TODO have a customizable function to handle this
int(getenv("STAKE_AMOUNT", "1")) * predicted_confidence / 100
) # TO DO have a customizable function to handle this
print(
f"Contract:{predictoor_contract.contract_address} - Submiting prediction for slot:{target_time}"
f"Contract:{predictoor_contract.contract_address} - "
f"Submitting prediction for slot:{target_time}"
)
predictoor_contract.submit_prediction(
predicted_value, stake_amount, target_time, True
)
topics[address]["last_submited_epoch"] = epoch
else:
print(
f"We do not submit, prediction function returned ({predicted_value}, {predicted_confidence})"
"We do not submit, prediction function returned "
f"({predicted_value}, {predicted_confidence})"
)


Expand Down
Loading

0 comments on commit ca22d47

Please sign in to comment.