def test_soliditySha3_ens(self, web3, types, values, expected): with ens_addresses(web3, { 'one.eth': "0x49EdDD3769c0712032808D86597B84ac5c2F5614", 'two.eth': "0xA6b759bBbf4B59D24acf7E06e79f3a5D104fdCE5", }): # when called as class method, any name lookup attempt will fail with pytest.raises(InvalidAddress): Web3.soliditySha3(types, values) # when called as instance method method, ens lookups can succeed actual = web3.soliditySha3(types, values) assert actual == expected
def hash_balance_data( transferred_amount: typing.TokenAmount, locked_amount: typing.TokenAmount, locksroot: typing.Locksroot, ) -> str: return Web3.soliditySha3( ['uint256', 'uint256', 'bytes32'], [transferred_amount, locked_amount, locksroot], )
def test_labelhash(ens, label, expected_hash): if isinstance(expected_hash, type): with pytest.raises(expected_hash): ens.labelhash(label) else: labelhash = ens.labelhash(label) assert isinstance(labelhash, bytes) hash_hex = Web3.toHex(labelhash) assert hash_hex == expected_hash
def bytes32(val): if isinstance(val, int): result = Web3.toBytes(val) else: raise TypeError('val %r could not be converted to bytes') if len(result) < 32: return result.rjust(32, b'\0') else: return result
def hash_balance_data( transferred_amount: TokenAmount, locked_amount: TokenAmount, locksroot: Locksroot, ) -> bytes: assert locksroot != b'' assert len(locksroot) == 32 if transferred_amount == 0 and locked_amount == 0 and locksroot == EMPTY_HASH: return EMPTY_HASH return Web3.soliditySha3( # pylint: disable=no-value-for-parameter ['uint256', 'uint256', 'bytes32'], [transferred_amount, locked_amount, locksroot], )
def test_eth_account_sign_transaction_from_eth_test(acct, transaction_info): expected_raw_txn = transaction_info['signed'] key = transaction_info['key'] transaction = dissoc(transaction_info, 'signed', 'key', 'unsigned') # validate r, in order to validate the transaction hash # There is some ambiguity about whether `r` will always be deterministically # generated from the transaction hash and private key, mostly due to code # author's ignorance. The example test fixtures and implementations seem to agree, so far. # See ecdsa_raw_sign() in /eth_keys/backends/native/ecdsa.py signed = acct.signTransaction(transaction, key) assert signed.r == Web3.toInt(hexstr=expected_raw_txn[-130:-66]) # confirm that signed transaction can be recovered to the sender expected_sender = acct.privateKeyToAccount(key).address assert acct.recoverTransaction(signed.rawTransaction) == expected_sender
def test_set_address(ens, name, full_name, namehash_hex): assert ens.address(name) is None owner = ens.owner('tester') ens.setup_address(name, TEST_ADDRESS) assert ens.address(name) == TEST_ADDRESS # check that .eth is only appended if guess_tld is True namehash = Web3.toBytes(hexstr=namehash_hex) normal_name = ens.nameprep(full_name) if ens.nameprep(name) == normal_name: assert ens.address(name, guess_tld=False) == TEST_ADDRESS else: assert ens.address(name, guess_tld=False) is None # check that the correct namehash is set: assert ens.resolver(normal_name).addr(namehash) == TEST_ADDRESS # check that the correct owner is set: assert ens.owner(name) == owner ens.setup_address(name, None) assert ens.address(name) is None
def check_gas_reserve(raiden): """ Check periodically for gas reserve in the account """ while True: has_enough_balance, estimated_required_balance = gas_reserve.has_enough_gas_reserve( raiden, channels_to_open=0, ) estimated_required_balance_eth = Web3.fromWei(estimated_required_balance, 'ether') if not has_enough_balance: log.info('Missing gas reserve', required_wei=estimated_required_balance) click.secho( ( 'WARNING\n' "Your account's balance is below the estimated gas reserve of " f'{estimated_required_balance_eth} eth. This may lead to a loss of ' 'of funds because your account will be unable to perform on-chain ' 'transactions. Please add funds to your account as soon as possible.' ), fg='red', ) gevent.sleep(CHECK_GAS_RESERVE_INTERVAL)
def test_setup_name(ens, name, normalized_name, namehash_hex): address = ens.web3.eth.accounts[3] assert not ens.name(address) owner = ens.owner('tester') ens.setup_name(name, address) assert ens.name(address) == normalized_name # check that .eth is only appended if guess_tld is True if ens.nameprep(name) != normalized_name: assert ens.address(name, guess_tld=False) is None # check that the correct namehash is set: node = Web3.toBytes(hexstr=namehash_hex) assert ens.resolver(normalized_name).addr(node) == address # check that the correct owner is set: assert ens.owner(name) == owner ens.setup_name(None, address) ens.setup_address(name, None) assert not ens.name(address) assert not ens.address(name)
def test_to_hex_cleanup_only(val, expected): assert Web3.toHex(hexstr=val) == expected
def test_to_hex(val, expected): assert Web3.toHex(val) == expected
def test_to_int_text(val, expected): if isinstance(expected, type): with pytest.raises(expected): Web3.toInt(text=val) else: assert Web3.toInt(text=val) == expected
def toBytes(self): return Web3.toBytes(text=self.name).ljust(32, bytes(1))
except: return -1 def verifyHash(hash): contract = infura.eth.contract(address=CONTRACT, abi=ABI) try: return contract.functions.getHash(hash).call() except: return -1 input = sys.stdin.read() input = json.loads(input) infura = Web3(HTTPProvider(INFURA_URL)) w3 = Web3(Web3.IPCProvider("~/.ethereum/geth.ipc")) if "operation" not in input: raise Exception("Operation was not specified.") elif input["operation"] == "store": operationResult = storeHash(input["block_hash"]) result = {} if operationResult == -1: result["success"] = False else: result["success"] = True result["address"] = CONTRACT result["tx_hash"] = operationResult print(json.dumps(result))
def test_to_text_hexstr(val, expected): assert Web3.toText(hexstr=val) == expected
def redeem_coin(request, shortcode): if request.body: status = 'OK' body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) address = body['address'] try: coin = CoinRedemption.objects.get(shortcode=shortcode) address = Web3.toChecksumAddress(address) if hasattr(coin, 'coinredemptionrequest'): status = 'error' message = 'Bad request' else: abi = json.loads( '[{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"version","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_subtractedValue","type":"uint256"}],"name":"decreaseApproval","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_addedValue","type":"uint256"}],"name":"increaseApproval","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"payable":false,"stateMutability":"nonpayable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[],"name":"MintFinished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]' ) # Instantiate Colorado Coin contract contract = w3.eth.contract(coin.contract_address, abi=abi) tx = contract.functions.transfer( address, coin.amount * 10**18).buildTransaction({ 'nonce': w3.eth.getTransactionCount( settings.COLO_ACCOUNT_ADDRESS), 'gas': 40000, 'gasPrice': recommend_min_gas_price_to_confirm_in_time(5) * 10**9 }) signed = w3.eth.account.signTransaction( tx, settings.COLO_ACCOUNT_PRIVATE_KEY) transaction_id = w3.eth.sendRawTransaction( signed.rawTransaction).hex() CoinRedemptionRequest.objects.create(coin_redemption=coin, ip=get_ip(request), sent_on=timezone.now(), txid=transaction_id, txaddress=address) message = transaction_id except CoinRedemption.DoesNotExist: status = 'error' message = 'Bad request' except Exception as e: status = 'error' message = str(e) #http response response = { 'status': status, 'message': message, } return JsonResponse(response) try: coin = CoinRedemption.objects.get(shortcode=shortcode) params = { 'class': 'redeem', 'title': 'Coin Redemption', 'coin_status': 'PENDING' } try: coin_redeem_request = CoinRedemptionRequest.objects.get( coin_redemption=coin) params['colo_txid'] = coin_redeem_request.txid except CoinRedemptionRequest.DoesNotExist: params['coin_status'] = 'INITIAL' return TemplateResponse(request, 'yge/redeem_coin.html', params) except CoinRedemption.DoesNotExist: raise Http404
from dashboard.notifications import maybe_market_tip_to_email, maybe_market_tip_to_github, maybe_market_tip_to_slack from dashboard.utils import get_bounty, getBountyID, has_tx_mined from dashboard.utils import process_bounty as web3_process_bounty from gas.utils import conf_time_spread, eth_usd_conv_rate, recommend_min_gas_price_to_confirm_in_time from github.utils import get_auth_url, get_github_emails, get_github_primary_email, is_github_token_valid from marketing.models import Keyword from ratelimit.decorators import ratelimit from retail.helpers import get_ip from web3 import HTTPProvider, Web3 logging.basicConfig(level=logging.DEBUG) confirm_time_minutes_target = 60 # web3.py instance w3 = Web3(HTTPProvider(settings.WEB3_HTTP_PROVIDER)) def send_tip(request): """Handle the first stage of sending a tip.""" params = { 'issueURL': request.GET.get('source'), 'title': 'Send Tip', 'class': 'send', } return TemplateResponse(request, 'yge/send1.html', params) @require_POST @csrf_exempt
import json from solc import compile_source from web3 import Web3, HTTPProvider web3 = Web3(HTTPProvider("http://localhost:8545")) # Solidity source code contract_source_code = ''' pragma solidity ^0.4.0; contract SimpleStorage { uint storedData; function set(uint x) public { storedData = x; } function get() public view returns (uint) { return storedData; } } ''' web3.eth.defaultAccount = web3.eth.accounts[0] compiled_sol = compile_source(contract_source_code) abi = compiled_sol['<stdin>:SimpleStorage']['abi'] bytecode = compiled_sol['<stdin>:SimpleStorage']['bin'] # txHash = web3.eth.contract(abi=abi,bytecode=bytecode).deploy(transaction={ 'from' : web3.eth.accounts[0], 'gas' : 500000 }) # print(txHash)
def file_vow(self, vow: Vow) -> Transact: assert isinstance(vow, Vow) return Transact(self, self.web3, self.abi, self.address, self._contract, 'file(bytes32,address)', [Web3.toBytes(text="vow"), vow.address.address])
def fromBytes(ilk: bytes): assert (isinstance(ilk, bytes)) name = Web3.toText(ilk.strip(bytes(1))) return Ilk(name)
def rho(self, ilk: Ilk) -> int: assert isinstance(ilk, Ilk) return Web3.toInt(self._contract.call().ilks(ilk.toBytes())[1])
def test_to_bytes_hexstr(val, expected): assert Web3.toBytes(hexstr=val) == expected
def test_to_text_identity(): assert Web3.toText(text='pass-through') == 'pass-through'
import json from web3 import Web3 import pytz from datetime import datetime #setup ganache_url = "http://127.0.0.1:7545" web3 = Web3(Web3.HTTPProvider(ganache_url)) #Check if node is connected print(web3.isConnected()) #define signing account for transactions web3.eth.defaultAccount = web3.eth.accounts[0] print(web3.eth.accounts[0]) print(web3.eth.accounts[1]) #define smart contract account - different address for each deployment address = web3.toChecksumAddress('0x3B79cab73D2d22EB642c32c06a10FF8f4A4e09Ef') #how to import abi and bytecode using truffle PATH_TRUFFLE_WK = 'C:/Users/Inessa/Desktop/4th_Year/FYP/Methodology_Eth/energy' truffleFile = json.load(open(PATH_TRUFFLE_WK + '/build/contracts/Energy.json')) abi = truffleFile['abi'] bytecode = truffleFile['bytecode'] #fetch the smart contract contract = web3.eth.contract(address=address, abi=abi) ## Test 1: reading data from smart contract, simple Peer contract
greeting = 'Hello'; } function setGreeting(string _greeting) public { greeting = _greeting; } function greet() constant returns (string) { return greeting; } } """ # above is deployed here: contract_address = '0x31bd34ef7dbd96a20098b7a5aaf67a45bbef2726' contract_address = Web3.toChecksumAddress(contract_address) # here is the ABI of the contract: abi = """ [ { "constant": false, "inputs": [ { "name": "_greeting", "type": "string" } ], "name": "setGreeting", "outputs": [], "payable": false,
def __init__(self, mainnet=False): if mainnet: self.w3 = Web3(Web3.HTTPProvider(self.URL_MAINNET)) else: self.w3 = Web3(Web3.HTTPProvider(self.URL_TESTNET)) super().__init__()
# The smart contract address of the token you want to trade # On EtherDelta.com, click "Tokens" in the top-right hand corner, # click the token you want to trade and copy-paste the 0x... address. # Example: Smart Contract: 0x9742fa8cb51d294c8267ddfead8582e16f18e421 token = "0x5ca9a71b1d01849c0a95490cc00559717fcf0d1d" # Aeternity token #token = "0xaec2e87e0a235266d9c5adc9deb4b2e29b54d009" # SNGLS # EtherDelta contract address # This rarely changes. addressEtherDelta = '0x8d12A197cB00D4747a1fe03395095ce2A5CC6819' # etherdelta_2's contract address ######################## # END OF CONFIGURATION # ######################## # Global API interfaces web3 = Web3(HTTPProvider('http://35.205.255.115:8545')) # Global lists of sells, buys and trades that are always sorted and updated whenever data comes in orders_sells = [] orders_buys = [] trades = [] def updateOrders(newOrders): global orders_sells, orders_buys, token, userAccount # Parse the sells new_sells = newOrders['sells'] valid_new_sells = [ x for x in new_sells if x['tokenGive'].lower() == token.lower() and float(x['ethAvailableVolumeBase']) >= 0.001
def __init__(self, args: list, **kwargs): parser = argparse.ArgumentParser(prog='ddex-market-maker-keeper') parser.add_argument("--rpc-host", type=str, default="localhost", help="JSON-RPC host (default: `localhost')") parser.add_argument("--rpc-port", type=int, default=8545, help="JSON-RPC port (default: `8545')") parser.add_argument("--rpc-timeout", type=int, default=10, help="JSON-RPC timeout (in seconds, default: 10)") parser.add_argument( "--eth-from", type=str, required=True, help="Ethereum account from which to send transactions") parser.add_argument( "--exchange-address", type=str, required=True, help="Ethereum address of the 0x Exchange contract") parser.add_argument( "--ddex-api-server", type=str, default='https://api.ddex.io', help="Address of the Ddex API (default: 'https://api.ddex.io')") parser.add_argument( "--ddex-api-timeout", type=float, default=9.5, help="Timeout for accessing the Ddex API (in seconds, default: 9.5)" ) parser.add_argument( "--pair", type=str, required=True, help="Token pair (sell/buy) on which the keeper will operate") parser.add_argument("--buy-token-address", type=str, required=True, help="Ethereum address of the buy token") parser.add_argument("--sell-token-address", type=str, required=True, help="Ethereum address of the sell token") parser.add_argument("--config", type=str, required=True, help="Bands configuration file") parser.add_argument("--price-feed", type=str, required=True, help="Source of price feed") parser.add_argument( "--price-feed-expiry", type=int, default=120, help="Maximum age of the price feed (in seconds, default: 120)") parser.add_argument("--spread-feed", type=str, help="Source of spread feed") parser.add_argument( "--spread-feed-expiry", type=int, default=3600, help="Maximum age of the spread feed (in seconds, default: 3600)") parser.add_argument("--order-history", type=str, help="Endpoint to report active orders to") parser.add_argument( "--order-history-every", type=int, default=30, help= "Frequency of reporting active orders (in seconds, default: 30)") parser.add_argument("--gas-price", type=int, default=0, help="Gas price (in Wei)") parser.add_argument( "--smart-gas-price", dest='smart_gas_price', action='store_true', help= "Use smart gas pricing strategy, based on the ethgasstation.info feed" ) parser.add_argument( "--refresh-frequency", type=int, default=3, help="Order book refresh frequency (in seconds, default: 3)") parser.add_argument("--debug", dest='debug', action='store_true', help="Enable debug output") self.arguments = parser.parse_args(args) setup_logging(self.arguments) self.web3 = kwargs['web3'] if 'web3' in kwargs else Web3( HTTPProvider( endpoint_uri= f"http://{self.arguments.rpc_host}:{self.arguments.rpc_port}", request_kwargs={"timeout": self.arguments.rpc_timeout})) self.web3.eth.defaultAccount = self.arguments.eth_from self.our_address = Address(self.arguments.eth_from) self.pair = self.arguments.pair.upper() self.token_buy = ERC20Token(web3=self.web3, address=Address( self.arguments.buy_token_address)) self.token_sell = ERC20Token(web3=self.web3, address=Address( self.arguments.sell_token_address)) self.bands_config = ReloadableConfig(self.arguments.config) self.price_max_decimals = None self.amount_max_decimals = None self.gas_price = GasPriceFactory().create_gas_price(self.arguments) self.price_feed = PriceFeedFactory().create_price_feed(self.arguments) self.spread_feed = create_spread_feed(self.arguments) self.order_history_reporter = create_order_history_reporter( self.arguments) self.history = History() self.zrx_exchange = ZrxExchange(web3=self.web3, address=Address( self.arguments.exchange_address)) self.ddex_api = DdexApi(self.web3, self.arguments.ddex_api_server, self.arguments.ddex_api_timeout) self.order_book_manager = OrderBookManager( refresh_frequency=self.arguments.refresh_frequency, max_workers=1) self.order_book_manager.get_orders_with( lambda: self.ddex_api.get_orders(self.pair)) self.order_book_manager.cancel_orders_with( lambda order: self.ddex_api.cancel_order(order.order_id)) self.order_book_manager.enable_history_reporting( self.order_history_reporter, self.our_buy_orders, self.our_sell_orders) self.order_book_manager.start()
def send(conn, addr1, addr2, v): value = Web3.toWei(v, 'ether') return conn.eth.sendTransaction({'from': addr1, 'to': addr2, 'value': value})
import json import os from constants import BTC, BTCTEST, ETH from pprint import pprint from bit import PrivateKeyTestnet from bit.network import NetworkAPI from web3 import Web3, middleware, Account from web3.gas_strategies.time_based import medium_gas_price_strategy from web3.middleware import geth_poa_middleware from eth_account import Account # Connect Web3 w3 = Web3(Web3.HTTPProvider(os.getenv("WEB3_PROVIDER", "http://localhost:8545"))) w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545")) w3.middleware_onion.inject(geth_poa_middleware, layer=0) # Current block number w3.eth.blockNumber # Set Gas Price Strategy w3.eth.setGasPriceStrategy(medium_gas_price_strategy) # Mnemonic Phrase mnemonic = os.getenv("MNEMONIC" , "abuse blood note choice garbage spot ice roast smoke yard foster chuckle') coin = ETH mnemonic=mnemonic depth=3
def calculate_device_registration_hash(timestamp: int, identifier: UUID, cloud_messaging_token: str, safes: Sequence[str], prefix: str = 'gnosis-safe') -> HexBytes: safes_to_str = ''.join(sorted(safes)) str_to_sign = f'{prefix}{timestamp}{identifier}{cloud_messaging_token}{safes_to_str}' return Web3.keccak(text=str_to_sign)
import subprocess import json import os from constants import * from bit import wif_to_key, PrivateKeyTestnet from bit.network import NetworkAPI from web3 import Web3 from web3.middleware import geth_poa_middleware from eth_account import Account # In[118]: w3 = Web3(Web3.HTTPProvider("https://kovan.infura.io/v3/1fa351728e874efcac3aabd55f70a089")) mnem = os.getenv('MNEMONIC') php = 'php.exe ./hd-wallet-derive/hd-wallet-derive.php' # In[119]: def derive_wallets(mnemonic, coin, numderive): cmd = f'{php} -g --mnemonic={mnem} --numderive='+str(numderive)+' --coin='+str(coin)+' --cols=all --format=jsonpretty' p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) (output, err) = p.communicate() return json.loads(output) coins = {'eth':derive_wallets(mnemonic=mnem,coin=ETH,numderive=3),'btc-test': derive_wallets(mnemonic=mnem,coin=BTCTEST,numderive=3)}
def test_to_int_hexstr(val, expected): assert Web3.toInt(hexstr=val) == expected
from web3 import Web3 import json with open("./build/contracts/Voting.json", 'r') as f: js = json.load(f) abi = js['abi'] address = js['networks']['5777']['address'].upper() w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:9545")) w3.eth.defaultAccount = w3.eth.accounts[0] adr = w3.toChecksumAddress(address) voting = w3.eth.contract(address=adr, abi=abi) # tx_hash = voting.functions.addElection(5,"테스트테스",123,456) # tx_hash = tx_hash.transact() tx_hash = voting.functions.addCandidate(4, "a", "a", 5) tx_hash = tx_hash.transact() # w3.eth.waitForTransactionReceipt(tx_hash) election = voting.functions.getLastElection().call() print(election)
def test_to_hex_text(val, expected): assert Web3.toHex(text=val) == expected
def __init__(self, args: list, **kwargs): parser = argparse.ArgumentParser(prog='etherdelta-market-maker-keeper') parser.add_argument("--rpc-host", type=str, default="localhost", help="JSON-RPC host (default: `localhost')") parser.add_argument("--rpc-port", type=int, default=8545, help="JSON-RPC port (default: `8545')") parser.add_argument("--rpc-timeout", type=int, default=10, help="JSON-RPC timeout (in seconds, default: 10)") parser.add_argument( "--eth-from", type=str, required=True, help="Ethereum account from which to send transactions") parser.add_argument("--tub-address", type=str, required=True, help="Ethereum address of the Tub contract") parser.add_argument("--etherdelta-address", type=str, required=True, help="Ethereum address of the EtherDelta contract") parser.add_argument( "--etherdelta-socket", type=str, required=True, help="Ethereum address of the EtherDelta API socket") parser.add_argument( "--etherdelta-number-of-attempts", type=int, default=3, help= "Number of attempts of running the tool to talk to the EtherDelta API socket" ) parser.add_argument( "--etherdelta-retry-interval", type=int, default=10, help= "Retry interval for sending orders over the EtherDelta API socket") parser.add_argument( "--etherdelta-timeout", type=int, default=120, help="Timeout for sending orders over the EtherDelta API socket") parser.add_argument("--config", type=str, required=True, help="Bands configuration file") parser.add_argument("--price-feed", type=str, required=True, help="Source of price feed") parser.add_argument( "--price-feed-expiry", type=int, default=120, help="Maximum age of the price feed (in seconds, default: 120)") parser.add_argument("--order-age", type=int, required=True, help="Age of created orders (in blocks)") parser.add_argument( "--order-expiry-threshold", type=int, default=0, help= "Remaining order age (in blocks) at which order is considered already expired, which" " means the keeper will send a new replacement order slightly ahead" ) parser.add_argument( "--order-no-cancel-threshold", type=int, default=0, help= "Remaining order age (in blocks) below which keeper does not try to cancel orders," " assuming that they will probably expire before the cancel transaction gets mined" ) parser.add_argument( "--eth-reserve", type=float, required=True, help= "Amount of ETH which will never be deposited so the keeper can cover gas" ) parser.add_argument( "--min-eth-balance", type=float, default=0, help="Minimum ETH balance below which keeper will cease operation") parser.add_argument( "--min-eth-deposit", type=float, required=True, help= "Minimum amount of ETH that can be deposited in one transaction") parser.add_argument( "--min-sai-deposit", type=float, required=True, help= "Minimum amount of SAI that can be deposited in one transaction") parser.add_argument( '--cancel-on-shutdown', dest='cancel_on_shutdown', action='store_true', help= "Whether should cancel all open orders on EtherDelta on keeper shutdown" ) parser.add_argument( '--withdraw-on-shutdown', dest='withdraw_on_shutdown', action='store_true', help= "Whether should withdraw all tokens from EtherDelta on keeper shutdown" ) parser.add_argument("--gas-price", type=int, default=0, help="Gas price (in Wei)") parser.add_argument( "--smart-gas-price", dest='smart_gas_price', action='store_true', help= "Use smart gas pricing strategy, based on the ethgasstation.info feed" ) parser.add_argument("--debug", dest='debug', action='store_true', help="Enable debug output") parser.set_defaults(cancel_on_shutdown=False, withdraw_on_shutdown=False) self.arguments = parser.parse_args(args) setup_logging(self.arguments) self.web3 = kwargs['web3'] if 'web3' in kwargs else Web3( HTTPProvider( endpoint_uri= f"http://{self.arguments.rpc_host}:{self.arguments.rpc_port}", request_kwargs={"timeout": self.arguments.rpc_timeout})) self.web3.eth.defaultAccount = self.arguments.eth_from self.our_address = Address(self.arguments.eth_from) self.tub = Tub(web3=self.web3, address=Address(self.arguments.tub_address)) self.sai = ERC20Token(web3=self.web3, address=self.tub.sai()) self.gem = ERC20Token(web3=self.web3, address=self.tub.gem()) self.bands_config = ReloadableConfig(self.arguments.config) self.eth_reserve = Wad.from_number(self.arguments.eth_reserve) self.min_eth_balance = Wad.from_number(self.arguments.min_eth_balance) self.min_eth_deposit = Wad.from_number(self.arguments.min_eth_deposit) self.min_sai_deposit = Wad.from_number(self.arguments.min_sai_deposit) self.gas_price = GasPriceFactory().create_gas_price(self.arguments) self.price_feed = PriceFeedFactory().create_price_feed( self.arguments.price_feed, self.arguments.price_feed_expiry, self.tub) if self.eth_reserve <= self.min_eth_balance: raise Exception( "--eth-reserve must be higher than --min-eth-balance") assert (self.arguments.order_expiry_threshold >= 0) assert (self.arguments.order_no_cancel_threshold >= self.arguments.order_expiry_threshold) self.etherdelta = EtherDelta(web3=self.web3, address=Address( self.arguments.etherdelta_address)) self.etherdelta_api = EtherDeltaApi( client_tool_directory="lib/pymaker/utils/etherdelta-client", client_tool_command="node main.js", api_server=self.arguments.etherdelta_socket, number_of_attempts=self.arguments.etherdelta_number_of_attempts, retry_interval=self.arguments.etherdelta_retry_interval, timeout=self.arguments.etherdelta_timeout) self.our_orders = list()
def test_to_bytes_primitive(val, expected): assert Web3.toBytes(val) == expected
def test_sha3_text(message, digest): assert Web3.sha3(text=message) == digest
def test_to_bytes_text(val, expected): assert Web3.toBytes(text=val) == expected
def test_sha3_hexstr(hexstr, digest): assert Web3.sha3(hexstr=hexstr) == digest
def test_to_text(val, expected): assert Web3.toText(val) == expected
def test_sha3_primitive_invalid(primitive, exception): with pytest.raises(exception): Web3.sha3(primitive)
def getBalance(self): wei_balance = self.web3.eth.getBalance(self.address) ether_balance = Web3.fromWei(wei_balance, unit='ether') return ether_balance
def toBytes(self): addr_str = self.address.address return Web3.toBytes(hexstr='0x' + addr_str[2:].zfill(64))
def web3(geth_process, endpoint_uri, event_loop): event_loop.run_until_complete(wait_for_ws(endpoint_uri, event_loop)) _web3 = Web3(Web3.WebsocketProvider(endpoint_uri)) return _web3
def run_test(self): sponsor_whitelist_contract_addr = Web3.toChecksumAddress( "8ad036480160591706c831f0da19d1a424e39469") collateral_per_storage_key = 10**18 // 16 upper_bound = 5 * 10**7 file_dir = os.path.dirname(os.path.realpath(__file__)) control_contract_file_path = os.path.dirname( os.path.realpath(__file__)).split("/") control_contract_file_path.pop(-1) control_contract_file_path.extend( ["internal_contract", "metadata", "SponsorWhitelistControl.json"]) control_contract_file_path = "/".join(control_contract_file_path) control_contract_dict = json.loads( open(os.path.join(control_contract_file_path), "r").read()) control_contract = get_contract_instance( contract_dict=control_contract_dict) test_contract = get_contract_instance( abi_file=os.path.join( file_dir, "contracts/commission_privilege_test_abi.json"), bytecode_file=os.path.join( file_dir, "contracts/commission_privilege_test_bytecode.dat"), ) start_p2p_connection(self.nodes) self.log.info("Initializing contract") genesis_key = self.genesis_priv_key genesis_addr = encode_hex(self.genesis_addr) self.log.info("genesis_addr={}".format(genesis_addr)) nonce = 0 gas_price = 1 gas = 50000000 block_gen_thread = BlockGenThread(self.nodes, self.log) block_gen_thread.start() self.tx_conf = { "from": Web3.toChecksumAddress(genesis_addr), "nonce": int_to_hex(nonce), "gas": int_to_hex(gas), "gasPrice": int_to_hex(gas_price), "chainId": 0 } # Setup balance for node 0 node = self.nodes[0] client = RpcClient(node) (addr1, priv_key1) = client.rand_account() self.log.info("addr1={}".format(addr1)) tx = client.new_tx(sender=genesis_addr, priv_key=genesis_key, value=10**6, nonce=self.get_nonce(self.genesis_addr), receiver=addr1) client.send_tx(tx, True) assert_equal(client.get_balance(addr1), 10**6) # setup contract transaction = self.call_contract_function( contract=test_contract, name="constructor", args=[], sender_key=self.genesis_priv_key) contract_addr = self.wait_for_tx([transaction], True)[0]['contractCreated'] self.log.info("contract_addr={}".format(contract_addr)) assert_equal(client.get_balance(contract_addr), 0) # sponsor the contract succeed b0 = client.get_balance(genesis_addr) self.call_contract_function( contract=control_contract, name="set_sponsor_for_gas", args=[Web3.toChecksumAddress(contract_addr), upper_bound], value=10**18, sender_key=self.genesis_priv_key, contract_addr=sponsor_whitelist_contract_addr, wait=True) assert_equal(client.get_sponsor_balance_for_gas(contract_addr), 10**18) assert_equal(client.get_sponsor_for_gas(contract_addr), genesis_addr) assert_equal(client.get_sponsor_gas_bound(contract_addr), upper_bound) assert_equal(client.get_balance(genesis_addr), b0 - 10**18 - gas + 12500000) # set privilege for addr1 b0 = client.get_balance(genesis_addr) c0 = client.get_collateral_for_storage(genesis_addr) self.call_contract_function(contract=test_contract, name="add", args=[Web3.toChecksumAddress(addr1)], sender_key=genesis_key, contract_addr=contract_addr, wait=True, check_status=True) assert_equal(client.get_balance(genesis_addr), b0 - gas + 12500000 - collateral_per_storage_key) assert_equal(client.get_collateral_for_storage(genesis_addr), c0 + collateral_per_storage_key) # addr1 call contract with privilege without enough cfx for gas fee sb = client.get_sponsor_balance_for_gas(contract_addr) b1 = client.get_balance(addr1) self.call_contract_function(contract=test_contract, name="foo", args=[], sender_key=priv_key1, contract_addr=contract_addr, wait=True, check_status=True) assert_equal(client.get_balance(addr1), 10**6) assert_equal(client.get_sponsor_balance_for_gas(contract_addr), sb - gas + 12500000) self.log.info("Pass")
def test_sha3_raise_if_hexstr_and_text(): with pytest.raises(TypeError): Web3.sha3(hexstr='0x', text='')
def test_sha3_raise_if_no_args(): with pytest.raises(TypeError): Web3.sha3()
def test_sha3_primitive(primitive, digest): assert Web3.sha3(primitive) == digest
def fromBytes(urn: bytes): assert isinstance(urn, bytes) address = Address(Web3.toHex(urn[-20:])) return Urn(address)
def test_sha3_raise_if_primitive_and(kwargs): # must not set more than one input with pytest.raises(TypeError): Web3.sha3('', **kwargs)
""" Author: Aleksandra Sokolowska for Validity Labs AG """ from web3 import Web3 from organize import * import sys import time import json #uncomment one of the options below # 1. connection via Infura web3 = Web3( Web3.HTTPProvider( "https://mainnet.infura.io/v3/ba1c59965f3341d581b8e0284afda3f7")) # 2. or connection via local node #web3 = Web3(Web3.IPCProvider('/your-path-to/geth.ipc')) user = sys.argv[1] start_time = time.time() start = 8974000 tokens = {} output_every = 100 count = 0 #loop over all blocks erc_topic = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' with open('erc.json', 'r') as f: