def exploit(): assert w3.isConnected() latest_block = w3.eth.getBlock("latest") latest_block_hash = latest_block["hash"] keccak256 = keccak.new(digest_bits=256) keccak256.update(latest_block_hash)
def _get_auto_provider(provider_uri): from web3.auto import w3 # how-automated-detection-works: https://web3py.readthedocs.io/en/latest/providers.html connected = w3.isConnected() if not connected: raise ProviderError( 'Cannot auto-detect node. Provide a full URI instead.') return w3.provider
def initContract(item): # w3 = Web3('https://mainnet.infura.io/v3/30636a84ebb34a1f8d0966c88134ade3') print('w3.isConnected()', w3, w3.isConnected()) tokenContract = w3.eth.contract(abi=erc20Abi, address=item['token']) vaultContract = w3.eth.contract(abi=vaultAbi, address=item['vault']) strategyContract = None if item['strategy']: strategyContract = w3.eth.contract(abi=strategyAbi, address=item['strategy']) return tokenContract, vaultContract, strategyContract
def main(): print(w3.isConnected()) block_filter = w3.eth.filter('latest') tx_filter = w3.eth.filter('pending') loop = asyncio.get_event_loop() try: loop.run_until_complete( asyncio.gather(log_loop(block_filter, 'block', 2), log_loop(tx_filter, 'txn', 2))) finally: loop.close()
def _get_infura_provider(self): # https://web3py.readthedocs.io/en/latest/providers.html#infura-mainnet infura_envvar = 'WEB3_INFURA_API_SECRET' if infura_envvar not in os.environ: raise self.InterfaceError( f'{infura_envvar} must be set in order to use an Infura Web3 provider.' ) from web3.auto.infura import w3 connected = w3.isConnected() if not connected: raise self.InterfaceError( 'Cannot auto-detect node. Provide a full URI instead.') return w3.provider
def main(): print(w3.isConnected()) latest_block = w3.eth.blockNumber print('latest block: {}'.format(latest_block)) time.sleep(2) while True: new_latest_block = w3.eth.blockNumber get_transaction(latest_block, new_latest_block) latest_block = new_latest_block time.sleep(2)
InfuraProjectId = '1761beb5aae7459b83afd64e8f1003fc' import os os.environ['WEB3_INFURA_PROJECT_ID'] = InfuraProjectId from web3.auto.infura import w3 print(w3.isConnected()) address = '0xDE9d2de48969B86826da4336F389c21e2d1c9812' privateKey = '0x48bd694bbfd4f2816b4355776d3c403449d95298a0cc4835e0372447013e84de' w3.eth.defaultAccount = address w3.eth.account.privateKeyToAccount(privateKey) ret = w3.eth.sendTransaction({ 'to': '0x839d2Cb7a7c568a51731B2bDFA186Bd22b803F61', 'value': 100 }) w3.eth.accounts.wallet.add({address: address, privateKey: privateKey})
from web3.exceptions import InfuraKeyNotFound import sys try: from web3.auto.infura import w3 '''export WEB3_INFURA_PROJECT_ID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX''' except InfuraKeyNotFound as err: print(err) print( "Run `export WEB3_INFURA_PROJECT_ID=xxxxxxxx` where xxxxxxxx is your infura project id.", 'For more information visit: https://web3py.readthedocs.io/en/latest/providers.html#infura-mainnet' ) sys.exit() if not w3.isConnected(): print('Connection failed') from decimal import Decimal from web3 import Web3 def sign_transfer(private_key, from_address, to_address, amount): gas = 21000 # minimum gas_price = w3.eth.gas_price amount_wei = Web3.toWei(Decimal(amount), 'ether') value = amount_wei - gas * gas_price if value < 0: raise Exception('amount is too small') return w3.eth.account.sign_transaction( {
import json import time import os import boto3 from config import config os.environ['INFURA_API_KEY'] = config["INFURA_API_KEY"] from web3.auto.infura import w3 if __name__ == "__main__": assert (w3.isConnected()) run = True # aws aws_client = boto3.client( 'dynamodb', aws_access_key_id=config["AWS_ACCESS_KEY_ID"], aws_secret_access_key=config["AWS_SECRET_ACCESS_KEY"], region_name='us-east-2') # contract kleros_json = open(file='contracts/Kleros.json') abi = json.loads(kleros_json.read())['abi'] kleros_contract = w3.eth.contract(address=w3.toChecksumAddress( config['KLEROS_CONTRACT_ADDRESS']), abi=abi) # disputes cache closed_disputes = {}
from web3.auto.infura import w3 #from web3.auto import w3 print(w3.isConnected()) print(w3.eth.getBlock('latest'))
return li_dif def config_check(self): private_key_exists = len(privateKey) != 0 tokens_populated = self.tokens != any if not private_key_exists: print("Generate a new private key") if not tokens_populated: print("Load tokens please") return private_key_exists and tokens_populated if __name__ == '__main__': oneInch = OneInch() print("Web3 Connected: {}".format(w3.isConnected())) # oneInch.load_tokens() w3.middleware_onion.add(middleware.time_based_cache_middleware) w3.middleware_onion.add(middleware.latest_block_based_cache_middleware) w3.middleware_onion.add(middleware.simple_cache_middleware) w3.eth.setGasPriceStrategy(fast_gas_price_strategy) while True: action = input("\nWhat should I do?\n[LIST]List Tokens\n[LOAD]Load Tokens\n[GENERATE] generate new private key" "\n[PRINT] print current pub address\n[APPROVE] approve token for swap (format: approve <token> " "<quantity>)\n[QUOTE] request a quote using the 1inch contract (format: quote <from_token> " "<to_token> <quantity>)\n[BALANCE] print current Eth balance (format: balance)" "\n[TOKENBALANCE] print current token balance (format: tokenbalance <token>)\n[API] probe 1inch " "for an arbitrage opportunity (format: api <from_token> <to_token> <quantity>)" "\n[ALLOWANCE] check allowance for a specific token (format: allowance <token>)\n[TOKEN] print " "token info (format: token <token>)\n[SWAP] performs an actual swap, if from_token is not Eth, " "don't forget to approve first (format: swap <from_token> <to_token> <quantity>)\nType your "
def test_connect_w3_autobahn(self): from autobahn.xbr import make_w3 w3 = make_w3(self.gw_config) self.assertTrue(w3.isConnected())
def test_connect_w3_infura_auto(self): from web3.auto.infura import w3 self.assertTrue(w3.isConnected())
def _bridge(address, private_key): # Get private key for Talao Wallet global Talao_wallet_ethereum_private_key keys = json.load(open('./keys.json')) Talao_wallet_ethereum_private_key = keys['ethereum'][ 'talao_wallet_ethereum_private_key'] print('wallet private key = ', Talao_wallet_ethereum_private_key) # confirm that the connection succeeded if not w3.isConnected(): print('Blockchain non connectée') return False # get current vault deposit on TALAO token smart contract on Ethereum contract = w3.eth.contract(Talao_token_contract, abi=constante.Talao_Token_ABI) vault_deposit = contract.functions.vaultDeposit().call() """ # Get estimate of Eth to transfer response = requests.get('https://ethgasstation.info/json/ethgasAPI.json') gas_price = int((int(response.json()['safeLow'])/10)) print('gas price safeLow = ', gas_price, ' gwei') value = (115000 + 30000) * w3.toWei(gas_price, 'gwei') print('to be transfered to address (Ether) = ',w3.fromWei(value, 'ether')) # Transfert Eth to address to complete create workspace transaction if _ether_transfer(address, value) is None : print('pb transfer Eth') return False # Transfert Talao token to complete create workspace transaction if _token_transfer(address, vault_deposit) is None : print('pb trasnfer token') return False # Create Vault Access on Ethereum Talao Token smart contract if _createVaultAccess(address, private_key) is None : print('pb create vault access') return False # Get Eth back to Talao Wallet if get_back_eth(address, private_key) is None : print('pb get back ether') return False print('Ethereum Talao Token synchronization is over for ', address) """ # en attendant que les transaction fee baissent...on transfer les token du vault depsoit sur le token response = requests.get('https://ethgasstation.info/json/ethgasAPI.json') gas_price = int((int(response.json()['safeLow']) / 10)) print('Warning : gas price safeLow = ', gas_price, ' gwei') if gas_price > 40: gas_price = 40 address_to = Talao_token_contract value = vault_deposit contract = w3.eth.contract(Talao_token_contract, abi=constante.Talao_Token_ABI) nonce = w3.eth.getTransactionCount(Talao_wallet_ethereum) print('Warning : nonce =', nonce) txn = contract.functions.transfer(address_to, value).buildTransaction({ 'chainId': 1, 'gas': 100000, 'gasPrice': w3.toWei(gas_price, 'gwei'), 'nonce': nonce, }) signed_txn = w3.eth.account.signTransaction( txn, Talao_wallet_ethereum_private_key) try: w3.eth.sendRawTransaction(signed_txn.rawTransaction) hash = w3.toHex(w3.keccak(signed_txn.rawTransaction)) print('Warning : token transfer transaction brdge_ethereum.py= ', hash) #receipt = w3.eth.waitForTransactionReceipt( # hash, timeout=2000, poll_latency=1) #if receipt['status'] == 0: # print('transaction failed') # return None #print('Ethereum Talao Token synchronization is done for ', address) return hash except: print('transaction refused') return None
import datetime from web3.auto.infura import w3 import peewee from configs.config_django import mysql_kwargs with open('public/abi/yfii/iUSDT.json') as f: abi = f.read() assert w3.isConnected() pool3 = w3.eth.contract(abi=abi, address='0x72Cf258c852Dc485a853370171d46B9D29fD3184') origin_price = pool3.functions.getPricePerFullShare().call() # print(origin_price, type(origin_price)) db = peewee.MySQLDatabase(**mysql_kwargs) class Abi_tokenprice(peewee.Model): name = peewee.CharField(verbose_name='名称', max_length=20) signal = peewee.CharField(verbose_name='signal', max_length=20) origin_price = peewee.BigIntegerField(verbose_name='原始价格') roi_week = peewee.FloatField('roi_week') created_time = peewee.DateTimeField(verbose_name='创建时间') class Meta: database = db now = datetime.datetime.now() yesterday = now - datetime.timedelta(days=1)
import importlib import json import prettytable import urllib.request from modules import * from http.cookiejar import CookieJar from web3.auto.infura import w3 from urllib.request import build_opener from termcolor import colored from urllib.error import HTTPError from pushbullet.pushbullet import PushBullet with open('keys.txt', 'r') as myfile: keys = json.load(myfile) if w3.isConnected() == True: print("The bot is connected to the ethereum network") time.sleep(1) else: print("The bot can't connect to the eth network") quit() unitroller = keys["unitroller"] abisite = keys["abi"] with urllib.request.urlopen(abisite) as url: abi = json.loads(url.read()) contract = w3.eth.contract(address=unitroller, abi=abi) apiKey = keys["pushbullet-api"]
def init(): if not w3.isConnected(): raise Exception('Not connected')