Example #1
0
    def __init__(self, args: list, **kwargs):
        parser = argparse.ArgumentParser(prog='oasis-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("--eth-key", type=str, nargs='*',
                            help="Ethereum private key(s) to use (e.g. 'key_file=aaa.json,pass_file=aaa.pass')")

        parser.add_argument("--tub-address", type=str, required=False,
                            help="Ethereum address of the Tub contract")

        parser.add_argument("--oasis-address", type=str, required=True,
                            help="Ethereum address of the OasisDEX contract")

        parser.add_argument("--oasis-support-address", type=str, required=False,
                            help="Ethereum address of the OasisDEX support contract")

        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("--buy-token-name", type=str, required=True,
                            help="Ethereum address of the buy token")

        parser.add_argument("--sell-token-name", type=str, required=True,
                            help="Ethereum address of the sell token")
        
        parser.add_argument("--buy-token-decimals", type=int, required=True,
                            help="Ethereum address of the buy token")

        parser.add_argument("--sell-token-decimals", type=int, 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("--control-feed", type=str,
                            help="Source of control feed")

        parser.add_argument("--control-feed-expiry", type=int, default=86400,
                            help="Maximum age of the control feed (in seconds, default: 86400)")

        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("--round-places", type=int, default=2,
                            help="Number of decimal places to round order prices to (default=2)")

        parser.add_argument("--min-eth-balance", type=float, default=0,
                            help="Minimum ETH balance below which keeper will cease operation")

        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("--ethgasstation-api-key", type=str, default=None, help="ethgasstation API key")

        parser.add_argument("--refresh-frequency", type=int, default=10,
                            help="Order book refresh frequency (in seconds, default: 10)")

        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
        register_keys(self.web3, self.arguments.eth_key)
        self.our_address = Address(self.arguments.eth_from)
        self.otc = MatchingMarket(web3=self.web3,
                                  address=Address(self.arguments.oasis_address),
                                  support_address=Address(self.arguments.oasis_support_address)
                                    if self.arguments.oasis_support_address else None)

        tub = Tub(web3=self.web3, address=Address(self.arguments.tub_address)) \
            if self.arguments.tub_address is not None else None

        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.buy_token = Token(name=self.arguments.buy_token_name, address=Address(self.arguments.buy_token_address), decimals=self.arguments.buy_token_decimals)
        self.sell_token = Token(name=self.arguments.sell_token_name, address=Address(self.arguments.sell_token_address), decimals=self.arguments.sell_token_decimals)
        self.min_eth_balance = Wad.from_number(self.arguments.min_eth_balance)
        self.bands_config = ReloadableConfig(self.arguments.config)
        self.gas_price = GasPriceFactory().create_gas_price(self.arguments)
        self.price_feed = PriceFeedFactory().create_price_feed(self.arguments, tub)
        self.spread_feed = create_spread_feed(self.arguments)
        self.control_feed = create_control_feed(self.arguments)
        self.order_history_reporter = create_order_history_reporter(self.arguments)

        self.history = History()
        self.order_book_manager = OrderBookManager(refresh_frequency=self.arguments.refresh_frequency)
        self.order_book_manager.get_orders_with(lambda: self.our_orders())
        self.order_book_manager.place_orders_with(self.place_order_function)
        self.order_book_manager.cancel_orders_with(self.cancel_order_function)
        self.order_book_manager.enable_history_reporting(self.order_history_reporter, self.our_buy_orders, self.our_sell_orders)
        self.order_book_manager.start()
Example #2
0
 def __init__(self):
     super().__init__(HTTPProvider('null'))
     self.provider = None
Example #3
0
def run_app(
    address: Address,
    keystore_path: str,
    gas_price: Callable,
    eth_rpc_endpoint: str,
    user_deposit_contract_address: Optional[UserDepositAddress],
    api_address: Endpoint,
    rpc: bool,
    rpccorsdomain: str,
    sync_check: bool,
    console: bool,
    password_file: TextIO,
    web_ui: bool,
    datadir: Optional[str],
    matrix_server: str,
    network_id: ChainID,
    environment_type: Environment,
    unrecoverable_error_should_crash: bool,
    pathfinding_service_address: str,
    pathfinding_max_paths: int,
    enable_monitoring: bool,
    resolver_endpoint: str,
    default_reveal_timeout: BlockTimeout,
    default_settle_timeout: BlockTimeout,
    routing_mode: RoutingMode,
    flat_fee: Tuple[Tuple[TokenAddress, FeeAmount], ...],
    proportional_fee: Tuple[Tuple[TokenAddress, ProportionalFeeAmount], ...],
    proportional_imbalance_fee: Tuple[Tuple[TokenAddress, ProportionalFeeAmount], ...],
    blockchain_query_interval: float,
    cap_mediation_fees: bool,
    **kwargs: Any,  # FIXME: not used here, but still receives stuff in smoketest
) -> App:
    # pylint: disable=too-many-locals,too-many-branches,too-many-statements,unused-argument

    token_network_registry_deployed_at: Optional[BlockNumber]
    smart_contracts_start_at: BlockNumber

    if datadir is None:
        datadir = os.path.join(os.path.expanduser("~"), ".raiden")

    account_manager = AccountManager(keystore_path)
    web3 = Web3(HTTPProvider(rpc_normalized_endpoint(eth_rpc_endpoint)))

    check_sql_version()
    check_ethereum_has_accounts(account_manager)
    check_ethereum_client_is_supported(web3)
    check_ethereum_network_id(network_id, web3)

    address, privatekey = get_account_and_private_key(account_manager, address, password_file)

    api_host, api_port = split_endpoint(api_address)

    if not api_port:
        api_port = DEFAULT_HTTP_SERVER_PORT

    domain_list = []
    if rpccorsdomain:
        if "," in rpccorsdomain:
            for domain in rpccorsdomain.split(","):
                domain_list.append(str(domain))
        else:
            domain_list.append(str(rpccorsdomain))

    # Set up config
    fee_config = prepare_mediation_fee_config(
        cli_token_to_flat_fee=flat_fee,
        cli_token_to_proportional_fee=proportional_fee,
        cli_token_to_proportional_imbalance_fee=proportional_imbalance_fee,
        cli_cap_mediation_fees=cap_mediation_fees,
    )
    rest_api_config = RestApiConfig(
        rest_api_enabled=rpc,
        web_ui_enabled=rpc and web_ui,
        cors_domain_list=domain_list,
        eth_rpc_endpoint=eth_rpc_endpoint,
        host=api_host,
        port=api_port,
    )

    config = RaidenConfig(
        chain_id=network_id,
        environment_type=environment_type,
        reveal_timeout=default_reveal_timeout,
        settle_timeout=default_settle_timeout,
        console=console,
        mediation_fees=fee_config,
        unrecoverable_error_should_crash=unrecoverable_error_should_crash,
        resolver_endpoint=resolver_endpoint,
        rest_api=rest_api_config,
    )
    config.blockchain.query_interval = blockchain_query_interval
    config.services.monitoring_enabled = enable_monitoring
    config.services.pathfinding_max_paths = pathfinding_max_paths
    config.transport.server = matrix_server

    contracts = load_deployed_contracts_data(config, network_id)

    rpc_client = JSONRPCClient(
        web3=web3,
        privkey=privatekey,
        gas_price_strategy=gas_price,
        block_num_confirmations=DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS,
    )

    token_network_registry_deployed_at = None
    if "TokenNetworkRegistry" in contracts:
        token_network_registry_deployed_at = BlockNumber(
            contracts[CONTRACT_TOKEN_NETWORK_REGISTRY]["block_number"]
        )

    if token_network_registry_deployed_at is None:
        smart_contracts_start_at = get_smart_contracts_start_at(network_id)
    else:
        smart_contracts_start_at = token_network_registry_deployed_at

    proxy_manager = ProxyManager(
        rpc_client=rpc_client,
        contract_manager=ContractManager(config.contracts_path),
        metadata=ProxyManagerMetadata(
            token_network_registry_deployed_at=token_network_registry_deployed_at,
            filters_start_at=smart_contracts_start_at,
        ),
    )

    api_server: Optional[APIServer] = None
    if config.rest_api.rest_api_enabled:
        api_server = start_api_server(
            rpc_client=rpc_client, config=config.rest_api, eth_rpc_endpoint=eth_rpc_endpoint
        )

    if sync_check:
        check_synced(rpc_client)

    # The user has the option to launch Raiden with a custom
    # user deposit contract address. This can be used to load
    # the addresses for the rest of the deployed contracts.
    # The steps done here make sure that if a UDC address is provided,
    # the address has to be valid and all the connected contracts
    # are configured properly.
    # If a UDC address was not provided, Raiden would fall back
    # to using the ones deployed and provided by the raiden-contracts package.
    if user_deposit_contract_address is not None:
        if not is_address(user_deposit_contract_address):
            raise RaidenError("The user deposit address is invalid")

        deployed_addresses = load_deployment_addresses_from_udc(
            proxy_manager=proxy_manager,
            user_deposit_address=user_deposit_contract_address,
            block_identifier=BLOCK_ID_LATEST,
        )
    else:
        deployed_addresses = load_deployment_addresses_from_contracts(contracts=contracts)

    # Load the available matrix servers when no matrix server is given
    # The list is used in a PFS check
    if config.transport.server == MATRIX_AUTO_SELECT_SERVER:
        fetch_available_matrix_servers(config.transport, environment_type)

    raiden_bundle = raiden_bundle_from_contracts_deployment(
        proxy_manager=proxy_manager,
        token_network_registry_address=deployed_addresses.token_network_registry_address,
        secret_registry_address=deployed_addresses.secret_registry_address,
    )

    services_bundle = services_bundle_from_contracts_deployment(
        config=config,
        deployed_addresses=deployed_addresses,
        proxy_manager=proxy_manager,
        routing_mode=routing_mode,
        pathfinding_service_address=pathfinding_service_address,
        enable_monitoring=enable_monitoring,
    )

    check_ethereum_confirmed_block_is_not_pruned(
        jsonrpc_client=rpc_client,
        secret_registry=raiden_bundle.secret_registry,
        confirmation_blocks=config.blockchain.confirmation_blocks,
    )

    database_path = Path(
        os.path.join(
            datadir,
            f"node_{pex(address)}",
            f"netid_{network_id}",
            f"network_{pex(raiden_bundle.token_network_registry.address)}",
            f"v{RAIDEN_DB_VERSION}_log.db",
        )
    )
    config.database_path = database_path

    print(f"Raiden is running in {environment_type.value.lower()} mode")
    print(
        "\nYou are connected to the '{}' network and the DB path is: {}".format(
            ID_TO_CHAINNAME.get(network_id, network_id), database_path
        )
    )

    matrix_transport = setup_matrix(
        config.transport, config.services, environment_type, routing_mode
    )

    event_handler: EventHandler = RaidenEventHandler()

    # User should be told how to set fees, if using default fee settings
    log.debug("Fee Settings", fee_settings=fee_config)
    has_default_fees = (
        len(fee_config.token_to_flat_fee) == 0
        and len(fee_config.token_to_proportional_fee) == 0
        and len(fee_config.token_to_proportional_imbalance_fee) == 0
    )
    if has_default_fees:
        click.secho(
            "Default fee settings are used. "
            "If you want use Raiden with mediation fees - flat, proportional and imbalance fees - "
            "see https://raiden-network.readthedocs.io/en/latest/overview_and_guide.html#firing-it-up",  # noqa: E501
            fg="yellow",
        )

    # Only send feedback when PFS is used
    if routing_mode == RoutingMode.PFS:
        event_handler = PFSFeedbackEventHandler(event_handler)

    message_handler = MessageHandler()

    one_to_n_address = (
        services_bundle.one_to_n.address if services_bundle.one_to_n is not None else None
    )
    monitoring_service_address = (
        services_bundle.monitoring_service.address
        if services_bundle.monitoring_service is not None
        else None
    )
    raiden_app = App(
        config=config,
        rpc_client=rpc_client,
        proxy_manager=proxy_manager,
        query_start_block=smart_contracts_start_at,
        default_registry=raiden_bundle.token_network_registry,
        default_secret_registry=raiden_bundle.secret_registry,
        default_service_registry=services_bundle.service_registry,
        default_user_deposit=services_bundle.user_deposit,
        default_one_to_n_address=one_to_n_address,
        default_msc_address=monitoring_service_address,
        transport=matrix_transport,
        raiden_event_handler=event_handler,
        message_handler=message_handler,
        routing_mode=routing_mode,
        api_server=api_server,
    )

    raiden_app.start()

    if config.pfs_config is not None:
        # This has to be done down here since there is a circular dependency
        # between the PFS and Transport
        pfs_broadcast_room_key = make_room_alias(config.chain_id, PATH_FINDING_BROADCASTING_ROOM)
        check_pfs_transport_configuration(
            pfs_info=config.pfs_config.info,
            pfs_was_autoselected=(pathfinding_service_address == MATRIX_AUTO_SELECT_SERVER),
            transport_pfs_broadcast_room_id=matrix_transport.broadcast_rooms[
                pfs_broadcast_room_key
            ].room_id,
            matrix_server_url=matrix_transport.server_url,
            matrix_server_was_autoselected=(config.transport.server == MATRIX_AUTO_SELECT_SERVER),
        )

    return raiden_app
Example #4
0
import json
from web3 import Web3, HTTPProvider
import sys
from flask import Flask, render_template

# ----- Connect to smart contract -----

# setup web3 instance using ganache
ganache_url = "http://127.0.0.1:8545"
w3 = Web3(HTTPProvider(ganache_url))
if w3.isConnected():
    print("Web3 Connected")
else:
    sys.exit("Couldn't connect to the blockchain via web3")
# set default account
w3.eth.defaultAccount = w3.eth.accounts[0]

# contract details
contract_path = './SmartContract/truffle/build/contracts/oceanCoin.json'
fp = open('./SmartContract/address.dat', 'r')
contract_address = fp.read()
fp.close()
print("Contract Address: ", contract_address)

# open compiled file and get abi & bytecode
truffleFile = json.load(open(contract_path))
abi = truffleFile['abi']
bytecode = truffleFile['bytecode']

# contract interface
oceanCoin = w3.eth.contract(address=contract_address, abi=abi)
Example #5
0
from pwn import *
from web3 import Web3, HTTPProvider
from solc import compile_files
import os
import time

myAddress = '0xB3580FB6944BC704149CE71DF2247897755Ba7d7'
myKey = '0x7613f3f0e75e124b78280cde672d5870ea87ebdea19aca556e1c6a720e8fbe82'
w3 = Web3(
    HTTPProvider(
        r'https://ropsten.infura.io/v3/6a17ad8ec1ff4b5c97d809725b515aac'))


def call(function, value):
    txn = function.buildTransaction({
        'value':
        w3.toWei(value, 'ether'),
        'nonce':
        w3.eth.getTransactionCount(myAddress),
        'gas':
        int(w3.eth.getBlock("latest").gasLimit * 0.9),
        'gasPrice':
        w3.toWei('1000', 'gwei')
    })
    sign = w3.eth.account.sign_transaction(txn, myKey)
    return w3.eth.sendRawTransaction(sign.rawTransaction)


os.environ[
    'SOLC_BINARY'] = '/mnt/c/Users/B10515025/Desktop/NTUST_CTF/HW3/solc.exe'
ALL_OUTPUT_VALUES = (
import json
from web3 import Web3, HTTPProvider, IPCProvider
from web3.middleware import geth_poa_middleware
import os
from os.path import join, dirname
from dotenv import load_dotenv

load_dotenv(join(dirname(__file__), '.env'))

if(os.environ.get("WEB3_USE_IPC") == False):
    web3 = Web3(HTTPProvider(os.environ.get("WEB3_HTTP_PROVIDER_URL")))
else:
    web3 = Web3(IPCProvider(os.environ.get("WEB3_IPC_PROVIDER_URL")))

if(os.environ.get("WEB3_MIDDLEWARE_ONION_INJECT")):    
    web3.middleware_onion.inject(geth_poa_middleware, layer=0)

web3.eth.defaultAccount = web3.eth.accounts[2]

with open('../build/contracts/ClientExample3.json') as file:
    contract_json = json.load(file)
    contract_abi = contract_json['abi']

AcriaClient = web3.eth.contract(address=os.environ.get("ACRIA_CLIENT_ADDRESS"), abi=contract_abi)

zBytes = "USD/GBP"
len1 = len(zBytes)

if len1 > 8:
    print('input string length: '+ str(len1)+ ' is too long')
    zBytes32 = zBytes[:8]
Example #7
0
#!/usr/bin/env python3
import time
from web3 import Web3, HTTPProvider
from hour_log_process import update_price


web3_rpc = Web3(HTTPProvider('http://192.168.0.4:8545'))
print(web3_rpc.isConnected())

while True:
    print(str(format(round(update_price("ethereum")),',')).rjust(6))
    a = web3_rpc.eth.syncing
    if a is False:
        print("Local Node Done Syncing")
        break
    print(a['highestBlock']-a['currentBlock'], "blocks left to catch up")
    time.sleep(60)
Example #8
0
    def __init__(self, args: list, **kwargs):
        parser = argparse.ArgumentParser(prog='mpx-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(
            "--eth-key",
            type=str,
            nargs='*',
            help=
            "Ethereum private key(s) to use (e.g. 'key_file=aaa.json,pass_file=aaa.pass')"
        )

        parser.add_argument(
            "--mpx-api-server",
            type=str,
            default='https://api.mpexchange.io',
            help=
            "Address of the MPX API server (default: 'https://api.mpexchange.io')"
        )

        parser.add_argument(
            "--mpx-api-timeout",
            type=float,
            default=9.5,
            help="Timeout for accessing the MPX API (in seconds, default: 9.5)"
        )

        parser.add_argument(
            "--exchange-address",
            type=str,
            required=True,
            help="Ethereum address of the Mpx Exchange contract")

        parser.add_argument("--fee-address",
                            type=str,
                            required=True,
                            help="Ethereum address of the Mpx Fee contract")

        parser.add_argument(
            "--pair",
            type=str,
            required=True,
            help="Token pair (sell/buy) on which the keeper will operate")

        parser.add_argument("--sell-token-address",
                            type=str,
                            required=True,
                            help="Ethereum address of the Sell Token")

        parser.add_argument("--buy-token-address",
                            type=str,
                            required=True,
                            help="Ethereum address of the Buy Token")

        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("--ethgasstation-api-key",
                            type=str,
                            default=None,
                            help="ethgasstation API key")

        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("--control-feed",
                            type=str,
                            help="Source of control feed")

        parser.add_argument(
            "--control-feed-expiry",
            type=int,
            default=86400,
            help="Maximum age of the control feed (in seconds, default: 86400)"
        )

        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(
            "--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)
        register_keys(self.web3, self.arguments.eth_key)

        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.gas_price = GasPriceFactory().create_gas_price(
            self.web3, self.arguments)
        self.price_feed = PriceFeedFactory().create_price_feed(self.arguments)
        self.spread_feed = create_spread_feed(self.arguments)
        self.control_feed = create_control_feed(self.arguments)
        self.order_history_reporter = create_order_history_reporter(
            self.arguments)

        self.history = History()

        self.zrx_exchange = ZrxExchangeV2(web3=self.web3,
                                          address=Address(
                                              self.arguments.exchange_address))
        self.mpx_api = MpxApi(api_server=self.arguments.mpx_api_server,
                              zrx_exchange=self.zrx_exchange,
                              fee_recipient=Address(
                                  self.arguments.fee_address),
                              timeout=self.arguments.mpx_api_timeout,
                              our_address=self.arguments.eth_from)

        self.zrx_relayer_api = ZrxRelayerApiV2(
            exchange=self.zrx_exchange,
            api_server=self.arguments.mpx_api_server)
        self.zrx_api = ZrxApiV2(zrx_exchange=self.zrx_exchange,
                                zrx_api=self.zrx_relayer_api)

        markets = self.mpx_api.get_markets()['data']
        market = next(
            filter(
                lambda item: item['attributes']['pair-name'] == self.arguments.
                pair, markets))

        self.pair = MpxPair(self.arguments.pair, self.token_buy.address,
                            int(market['attributes']['base-token-decimals']),
                            self.token_sell.address,
                            int(market['attributes']['quote-token-decimals']))

        self.order_book_manager = OrderBookManager(
            refresh_frequency=self.arguments.refresh_frequency)
        self.order_book_manager.get_orders_with(lambda: self.get_orders())
        self.order_book_manager.get_balances_with(lambda: self.get_balances())
        self.order_book_manager.cancel_orders_with(self.cancel_order_function)
        self.order_book_manager.place_orders_with(self.place_order_function)
        self.order_book_manager.enable_history_reporting(
            self.order_history_reporter, self.our_buy_orders,
            self.our_sell_orders)
        self.order_book_manager.start()
Example #9
0
    def attempt_connect(
            self,
            name: NodeName,
            ethrpc_endpoint: str,
            mainnet_check: bool = True,
    ) -> Tuple[bool, str]:
        """Attempt to connect to a particular node type

        For our own node if the given rpc endpoint is not the same as the saved one
        the connection is re-attempted to the new one
        """
        message = ''
        node_connected = self.web3_mapping.get(name, None) is not None
        own_node_already_connected = (
            name == NodeName.OWN and
            self.own_rpc_endpoint == ethrpc_endpoint and
            node_connected
        )
        if own_node_already_connected or (node_connected and name != NodeName.OWN):
            return True, 'Already connected to an ethereum node'

        try:
            parsed_eth_rpc_endpoint = urlparse(ethrpc_endpoint)
            if not parsed_eth_rpc_endpoint.scheme:
                ethrpc_endpoint = f"http://{ethrpc_endpoint}"
            provider = HTTPProvider(
                endpoint_uri=ethrpc_endpoint,
                request_kwargs={'timeout': self.eth_rpc_timeout},
            )
            ens = ENS(provider)
            web3 = Web3(provider, ens=ens)
            web3.middleware_onion.inject(http_retry_request_middleware, layer=0)
        except requests.exceptions.ConnectionError:
            message = f'Failed to connect to ethereum node {name} at endpoint {ethrpc_endpoint}'
            log.warning(message)
            return False, message

        if web3.isConnected():
            # Also make sure we are actually connected to the Ethereum mainnet
            synchronized = True
            msg = ''
            if mainnet_check:
                network_id = int(web3.net.version)
                if network_id != 1:
                    message = (
                        f'Connected to ethereum node {name} at endpoint {ethrpc_endpoint} but '
                        f'it is not on the ethereum mainnet. The chain id '
                        f'the node is in is {network_id}.'
                    )
                    log.warning(message)
                    return False, message

                current_block = web3.eth.blockNumber  # pylint: disable=no-member
                try:
                    latest_block = self.query_eth_highest_block()
                except RemoteError:
                    msg = 'Could not query latest block'
                    log.warning(msg)
                    synchronized = False
                else:
                    synchronized, msg = _is_synchronized(current_block, latest_block)

            if not synchronized:
                self.msg_aggregator.add_warning(
                    f'We could not verify that ethereum node {name} is '
                    'synchronized with the ethereum mainnet. Balances and other queries '
                    'may be incorrect.',
                )

            log.info(f'Connected ethereum node {name} at {ethrpc_endpoint}')
            self.web3_mapping[name] = web3
            return True, ''
        else:
            message = f'Failed to connect to ethereum node {name} at endpoint {ethrpc_endpoint}'
            log.warning(message)

        # If we get here we did not connnect
        return False, message
Example #10
0
from web3 import Web3, HTTPProvider
import requests
import yaml
from time import sleep
import json
from multiprocessing.dummy import Pool as ThreadPool
import itertools
from tqdm import tqdm

with open("config.yml", 'r') as config:
    cfg = yaml.load(config, Loader=yaml.FullLoader)

eth_provider = str(cfg["eth_provider_url"])
w3 = Web3(HTTPProvider(eth_provider))
file_name = cfg["file_name"]
csv_delimiter = str(cfg["csv_delimiter"])
csv_file_name = file_name + ".csv"
recipient_address = str(cfg["recipient_address"])
eth_gas_limit = int(cfg["eth_gas_limit"])
eth_gas_price = int(cfg["manual_gas_price"] * 1e9)
wait_for_gasprice_value = int(cfg["wait_for_gasprice_value"] * 1e9)
wait_for_gasprice = str(cfg["wait_for_gasprice"])
sleep_before_tx = cfg["sleep_before_tx"]
threads_count = int(cfg["threads_count"])

contract_address = Web3.toChecksumAddress(
    "0x1cc4426e36faeff09963d6b8b2da3b45f2f1deeb")
with open("utils/balance_checker_ABI.json") as f:
    info_json = json.load(f)
abi = info_json
contract = w3.eth.contract(contract_address, abi=abi)
Example #11
0
import json
from web3 import Web3, HTTPProvider

# truffle development blockchain address
blockchain_address = 'http://127.0.0.1:9545'
web3 = Web3(HTTPProvider(blockchain_address))

web3.eth.defaultAccount = web3.eth.accounts[0]

compiled_contract_path = '../build/contracts/AcriaMain.json'

deployed_contract_address = '0x25339522Df3d615ed729F6c0380B94E93B4eAE64'

with open(compiled_contract_path) as file:
    contract_json = json.load(file)
    contract_abi = contract_json['abi']

AcriaMain = web3.eth.contract(address=deployed_contract_address,
                              abi=contract_abi)

zBytes = "BTC/USD"
len1 = len(zBytes)

if len1 > 32:
    print('input string length: ' + str(len1) + ' is too long')
    zBytes32 = zBytes[:32]
else:
    print('input string length: ' + str(len1) + ' is too short')
    print('More characters needed: ' + str(32 - len1))
    zBytes32 = zBytes.ljust(32, ' ')
Example #12
0
 def __init__(self, root_chain_provider=HTTPProvider('http://localhost:8545'), child_chain_url="http://localhost:8546/jsonrpc"):
     deployer = Deployer(root_chain_provider)
     self.root_chain = deployer.get_contract_at_address("RootChain", CONTRACT_ADDRESS, concise=True)
     self.child_chain = ChildChainService(child_chain_url)
Example #13
0
def start_mining(ip, capture_ip):
    web3 = Web3(HTTPProvider('http://{}:8545'.format(ip)))
    web3.miner.setEtherBase(capture_ip)
    web3.miner.start(4)
    return web3.eth.mining
Example #14
0
#!/usr/bin/env python3

import time
import sys
import json
import math
import traceback
import os
import pandas as pd
import numpy as np
from web3 import Web3, HTTPProvider

node_url = os.getenv('ETH_NODE_URL', 'http://localhost:8545')
web3 = Web3(HTTPProvider(node_url))

### These are the threholds used for % blocks accepting to define the recommended gas prices. can be edited here if desired

SAFELOW = 35
STANDARD = 60
FAST = 90


class Timers():
    """
    class to keep track of time relative to network block
    """
    def __init__(self, start_block):
        self.start_block = start_block
        self.current_block = start_block
        self.process_block = start_block
Example #15
0
import argparse
from web3 import Web3, HTTPProvider
import json
import time
import sys, os
sys.path.append(
    os.path.join(os.path.dirname(__file__), 'D:/Проекты/Green_wave/src'))
import service_function

network_config = open('network.json', 'r')
rpcUrl = str(json.load(network_config)['rpcUrl'])

web3 = Web3(HTTPProvider(rpcUrl))


def key_to_value(args):
    if (args.deploy != " "):
        f = open('network.json', 'r')
        private_key = str(json.load(f)['privKey'])
        private_key_for_senders_account = private_key
        addressUser = Web3.toChecksumAddress(
            web3.eth.account.privateKeyToAccount(
                '0x' + str(private_key_for_senders_account)).address)

        with open("carscoins.bin") as bin_file:
            content = json.loads(bin_file.read())
            bytecode = content['object']

        with open("carscoins.abi") as abi_file:
            abi = json.loads(abi_file.read())
import json
import time

from eth_utils import to_checksum_address
from web3 import Web3, HTTPProvider
from web3.contract import ConciseContract
from web3.middleware import geth_poa_middleware

# Solidity source code

# web3.py instance
# w3 = Web3(HTTPProvider('http://localhost:8545'))  # ganache or
w3 = Web3(HTTPProvider('https://ropsten.infura.io/NiFrWVGDUTero8xrCJF8'))

w3.middleware_stack.inject(geth_poa_middleware, layer=0)

# BasicToken abi
with open('build/contracts/BasicToken.json', 'r') as f:
    contract_meta_json = json.loads(f.read())
    contract_abi = contract_meta_json['abi']
    contract_bin = contract_meta_json['bytecode']

contract = w3.eth.contract(abi=contract_abi, bytecode=contract_bin)

# # Get contract address
# tx_hash = contract.deploy(transaction={'from': '0x8F8d1bc97E8939e3932BfBeb923A1B2B972D5A9A', 'gas': 41000})
#
# while True:
#     tx_receipt = w3.eth.getTransactionReceipt(tx_hash)
#     if tx_receipt is not None:
#         break
Example #17
0
from tinydb.operations import delete
from OneBitRangeProof import VerifyRangeProofs, GetMerkelProof, ExtractProof

CT_Validator_Options = {
        #Percentage of proofs to verify 0-100
        'pct_proof_check': 100,

        #Finalize all proofs, even if they are not our own (No benefit to me)
        'finalize_all_proofs': True,

        #Proof Data Source
        'pull_proof_data_from_event': False
    }
    
#Connect to local node
w3 = Web3(HTTPProvider("http://127.0.0.1:8545"))
assert(w3.isConnected())
w3.middleware_stack.inject(geth_poa_middleware, layer=0)

#Unlock account
accounts = w3.personal.listAccounts
assert(len(accounts) > 0)
account = accounts[0]
pwd = getpass()
assert(w3.personal.unlockAccount(account, pwd))
del pwd

#Load contract address and abi
with open("RangeProofRegistryABI.json") as f:
    contract_json = json.load(f)
from web3 import Web3, HTTPProvider
import urllib3
from solc import compile_source

urllib3.disable_warnings()
web3 = Web3(
    HTTPProvider('https://ropsten.infura.io/xxxxxxxxxx', {'verify': False}))

private_key = '0x000000000000000000000000000000'
account = web3.eth.account.privateKeyToAccount(private_key)
web3.eth.defaultAccount = account.address

challenge_contract_address = '0x000000000000000000000000000'
with open('challenge.sol', 'r') as f:
    contract_source_code = f.read()

compiled_sol = compile_source(contract_source_code,
                              allow_paths='.')['<stdin>:TokenSaleChallenge']


def send_transaction_sync(tx, args={}):
    args['nonce'] = web3.eth.getTransactionCount(account.address)
    signed_txn = account.signTransaction(tx.buildTransaction(args))
    tx_hash = web3.eth.sendRawTransaction(signed_txn.rawTransaction)
    return web3.eth.waitForTransactionReceipt(tx_hash)


contract = web3.eth.contract(abi=compiled_sol['abi'],
                             address=challenge_contract_address)

min_token_number_with_overflow = 2**256 // 10**18 + 1
Example #19
0
import src.txFunction as txF
from web3 import Web3, HTTPProvider, IPCProvider, WebsocketProvider
import sys

w3 = Web3(HTTPProvider('http://localhost:8545'))

dst = sys.argv[1]
block_start = int(sys.argv[2])
block_end = int(sys.argv[3])

txF.extractTx(w3, dst, block_start, block_end)
Example #20
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import queue
import threading
import pymongo
import datetime
import cfscrape
import re
import time

from web3 import Web3, HTTPProvider
from bson.decimal128 import Decimal128
from pymongo import MongoClient

web3 = Web3(HTTPProvider('http://127.0.0.1:8545'))
latestBlock = web3.eth.getBlock('latest')
exitFlag = 0

retries = 10
timeout = 1  # seconds
wait = 2  # seconds


def init():
    if web3.eth.syncing == False:
        print('Ethereum blockchain is up-to-date.')
        print('Latest block: ' +
              str(latestBlock.number) + ' (' + datetime.datetime.fromtimestamp(
                  int(latestBlock.timestamp)).strftime('%d-%m-%Y %H:%M:%S') +
              ')\n')
Example #21
0
    def __init__(self, args: list, **kwargs):
        parser = argparse.ArgumentParser(prog='tethfinex-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(
            "--eth-key",
            type=str,
            nargs='*',
            help=
            "Ethereum private key(s) to use (e.g. 'key_file=aaa.json,pass_file=aaa.pass')"
        )

        parser.add_argument(
            "--exchange-address",
            type=str,
            required=True,
            help="Ethereum address of the 0x Exchange contract")

        parser.add_argument("--tub-address",
                            type=str,
                            required=False,
                            help="Ethereum address of the Tub contract")

        parser.add_argument(
            "--tethfinex-api-server",
            type=str,
            default='https://api.ethfinex.com',
            help=
            "Address of the Trustless Ethfinex API server (default: 'https://api.ethfinex.com')"
        )

        parser.add_argument(
            "--tethfinex-timeout",
            type=float,
            default=9.5,
            help="Timeout for accessing the IDEX 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("--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("--control-feed",
                            type=str,
                            help="Source of control feed")

        parser.add_argument(
            "--control-feed-expiry",
            type=int,
            default=86400,
            help="Maximum age of the control feed (in seconds, default: 86400)"
        )

        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("--ethgasstation-api-key",
                            type=str,
                            default=None,
                            help="ethgasstation API key")

        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")

        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)
        register_keys(self.web3, self.arguments.eth_key)

        tub = Tub(web3=self.web3, address=Address(self.arguments.tub_address)) \
            if self.arguments.tub_address is not None else None
        self.sai = ERC20Token(web3=self.web3, address=tub.sai())
        self.price_feed = PriceFeedFactory().create_price_feed(
            self.arguments, tub)

        self.bands_config = ReloadableConfig(self.arguments.config)
        self.gas_price = GasPriceFactory().create_gas_price(self.arguments)
        self.spread_feed = create_spread_feed(self.arguments)
        self.control_feed = create_control_feed(self.arguments)
        self.order_history_reporter = create_order_history_reporter(
            self.arguments)

        self.history = History()
        self.tethfinex_exchange = ZrxExchange(
            web3=self.web3, address=Address(self.arguments.exchange_address))
        self.tethfinex_api = TEthfinexApi(
            self.tethfinex_exchange,
            self.arguments.tethfinex_api_server,
            timeout=self.arguments.tethfinex_timeout)

        config = self.tethfinex_api.get_config()['0x']
        self.fee_address = Address(config['ethfinexAddress'])

        token_registry = config['tokenRegistry']
        token_sell = self.token_sell()
        token_buy = self.token_buy()
        self.token_sell_wrapper = TEthfinexToken(
            self.web3, Address(token_registry[token_sell]['wrapperAddress']),
            token_sell)
        self.token_buy_wrapper = TEthfinexToken(
            self.web3, Address(token_registry[token_buy]['wrapperAddress']),
            token_buy)

        pair = self.pair()

        self.order_book_manager = OrderBookManager(
            refresh_frequency=self.arguments.refresh_frequency, max_workers=1)
        self.order_book_manager.get_orders_with(
            lambda: self.tethfinex_api.get_orders(pair))
        self.order_book_manager.cancel_orders_with(
            lambda order: self.tethfinex_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()
Example #22
0
import os
import time
from web3 import Web3, HTTPProvider
from pyflex import Address
from pyflex.gf import SAFE
from pyflex.deployment import GfDeployment
from pyflex.keys import register_keys

if len(sys.argv) != 2:
    print("usage: python can_liq_safe.py <safe addr>")
    sys.exit()

ETH_RPC_URL = os.environ['ETH_RPC_URL']

web3 = Web3(
    HTTPProvider(endpoint_uri=ETH_RPC_URL, request_kwargs={"timeout": 60}))
while web3.eth.syncing:
    print("Node is syncing")
    time.sleep(5)

geb = GfDeployment.from_node(web3, 'rai')

collateral = geb.collaterals['ETH-A']
collateral_type = geb.safe_engine.collateral_type(
    collateral.collateral_type.name)
rate = collateral_type.accumulated_rate

safe = geb.safe_engine.safe(collateral_type, Address(sys.argv[1]))

if not geb.liquidation_engine.can_liquidate(collateral_type, safe):
    print("SAFE can't be liquidated.")
Example #23
0
from kudos.models import BulkTransferCoupon
from marketing.mails import (
    grant_cancellation,
    new_grant,
    new_grant_admin,
    new_supporter,
    subscription_terminated,
    support_cancellation,
    thank_you_for_supporting,
)
from marketing.models import Keyword, Stat
from retail.helpers import get_ip
from web3 import HTTPProvider, Web3

logger = logging.getLogger(__name__)
w3 = Web3(HTTPProvider(settings.WEB3_HTTP_PROVIDER))

clr_matching_banners_style = 'pledging'
matching_live = '($200K matching live now!) '
total_clr_pot = 200000
clr_round = 4
clr_active = True

if True:
    clr_matching_banners_style = 'results'
    matching_live = ''


def get_keywords():
    """Get all Keywords."""
    return json.dumps([

f1=open("./contract.abi",'r')
f2=open("./contract.adr",'r')
#Load contract ABI, Address
abi=eval(f1.read())
adr=f2.read().rstrip('\n')
f2.close()
f1.close()

#Set Account Password, RPC geth URL
passwd="jj"
rpc_url = "http://localhost:8545"


w3 = Web3(HTTPProvider(rpc_url))
w3.geth.personal.unlockAccount(w3.eth.accounts[0],passwd,15000)
# set pre-funded account as sender
w3.eth.defaultAccount = w3.eth.accounts[0]
checker = w3.eth.contract(address=adr, abi=abi)

def createFile(userId,fileHash):
	tx_hash=checker.functions.createFile(userId,fileHash).transact()
	#tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash,600)
def updateFile(fileId,fileHash):
	tx_hash=checker.functions.updateFile(fileId,fileHash).transact()
	#tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash,600)
def deleteFile(fileId):
	tx_hash=checker.functions.deleteFile(fileId).transact()
	#tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash,600)
import time

from web3 import HTTPProvider
from web3 import Web3

from core.contracts import RobotLiabilityFactoryContract, RobotLiabilityContract
from core.utils import MultihashConverter

__author__ = 'Xomak'

web3_rpc_url = "http://localhost:8545/"
factory_contract_address = "0x12301cb37191136a70c2cb8c5ec1240b69ad3668"
sender_address = "0x7262e87595e3bb70f31cc465b28b2b8b2355faa3"

active_liability = None
web3 = Web3(HTTPProvider(web3_rpc_url, request_kwargs={'timeout': 60}))
ipfs_client = ipfsapi.connect()

factory_contract = RobotLiabilityFactoryContract(web3,
                                                 factory_contract_address,
                                                 sender_address)
active_liabilities = []


def callback(block):
    print("New block")
    new_contracts = factory_contract.get_new_contracts(sender_address)
    for contract_address in new_contracts:
        print("New contract: " + contract_address)
        active_liabilities.append(
            RobotLiabilityContract(web3, contract_address, sender_address))
Example #26
0
 def __init__(self, ethereum_url, user_address) -> None:
     self.contract_interface = self._load_contract_interface()
     self.w3 = Web3(HTTPProvider(ethereum_url))
     self.user_address = user_address
Example #27
0
file_acc = open(chain_location + chain_name + "/py_script_info/list_smgw.csv",
                "r")
list_acc = func_fileIO.readStringArrayFromFile(file_acc)
file_acc.close()

# load generation curves
file_gen = open(chain_location + chain_name + "/py_script_info/input_gen.csv",
                "r")
list_gen = func_fileIO.readFloatArrayFromFile(file_gen)
file_gen.close()
pv_curve, chp_curve = list_gen[0], list_gen[1]

# connect to chain
# Establish RPC connection with running node.

web3 = Web3(HTTPProvider("http://localhost:8501"))
pw = "reghee"

# configure smart contract (already deployed on chain manually)

contract_address = web3.toChecksumAddress(
    0x5e00292eb39f84d94a452866a8cd9c4d0aa7fc65)
contract_abi = json.loads(abi_smartcert.returnABIstr())
contract = web3.eth.contract(abi=contract_abi, address=contract_address)

for entry in list_acc:
    func_BC.py_addSMGW(web3, contract, web3.toChecksumAddress(entry[0]),
                       web3.toChecksumAddress(entry[4]), pw)

# wait for new block before beginning simulation
func_BC.py_waitForNextBlock(
Example #28
0
# Created by PyCharm.
# User: shehin . F.N
# Date: 2/5/18
# Time: 12:07 PM

from web3 import Web3, HTTPProvider
from flask import Flask, request, jsonify
from tasks import celery_app, celery_update_wallet

provider = HTTPProvider('http://127.0.0.1:8545')
web3 = Web3(provider)
app = Flask(__name__)


@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers',
                         'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods',
                         'GET,PUT,POST,DELETE,OPTIONS')
    return response


@app.route("/updateWallet", methods=['POST', 'GET'])
def updateWallet():
    req = request.form.to_dict(flat=True)
    result = celery_update_wallet.delay(req['blockNumber'])
    data = {
        'success': True,
        'status_code': '200',
Example #29
0

def get_price():
    # Retrieve latest FLX price from coingecko
    resp = requests.get('https://api.coingecko.com/api/v3/simple/price', params={'ids': 'reflexer-ungovernance-token', 'vs_currencies': 'usd'})
    return resp.json()['reflexer-ungovernance-token']['usd']

"""
Sample auction input:

{'id': '1', 'bid_amount': '3.000000000000000000000000000000000000000000000', 'amount_to_sell': '439.000000000000000000', 'block_time': 1652104620, 'auction_deadline': 1652363564, 'price': '0.006833712984054669', 'bid_decrease': '1.030000000000000000', 'high_bidder': '0x6073E8FE874B53732b5DdD469a2De4047f33C64B', 'debt_auction_house': '0x6AcE594C5A421E468c13715AD62A183200C320a6'}
"""

current_flx_usd_price = get_price()

web3 = Web3(HTTPProvider(os.environ['ETH_RPC_URL']))
geb = GfDeployment.from_node(web3, 'rai')
redemption_price = geb.oracle_relayer.redemption_price()

# FLX Price to bid
MAXIMUM_FLX_MULTIPLIER = 0.90  # Buy FLX for 90% of current price

# Custom bid decrease 
# The minimum auction bid decrease can be low, setting a higher one can prevent too many bids
# If you want to always use the minimum bid decrease allowed, set this to 0
MY_BID_DECREASE = 1.03

for auction_input in sys.stdin:
    auction_state = json.loads(auction_input)

    # If we are already the high bidder, do nothing
Example #30
0
import sys
import json
import math
import traceback
import os
import pandas as pd
import numpy as np
from web3 import Web3, HTTPProvider
## newly added packages for api
import click
import logging
from threading import Thread
from sanic import Sanic, response
from retry import retry

web3 = Web3(HTTPProvider('https://bsc-dataseed2.binance.org'))
### These are the threholds used for % blocks accepting to define the recommended gas prices. can be edited here if desired

app = Sanic()
log = logging.getLogger('sanic.error')
app.config.LOGO = ''
stats = {}

SAFELOW = 35
STANDARD = 60
FAST = 90

class Timers():
    """
    class to keep track of time relative to network block
    """