Beispiel #1
0
    def __init__(self,
                 private_key: str = None,
                 key_password_path: str = None,
                 channel_manager_address: str = None,
                 web3: Web3 = None) -> None:
        is_hex_key = is_hex(private_key) and len(
            remove_0x_prefix(private_key)) == 64
        is_path = os.path.exists(private_key)
        assert is_hex_key or is_path, 'Private key must either be a hex key or a file path.'

        # Load private key from file if none is specified on command line.
        if is_path:
            private_key = get_private_key(private_key, key_password_path)
            assert private_key is not None, 'Could not load private key from file.'

        self.channels = []  # type: List[Channel]

        # Create web3 context if none is provided, either by using the proxies' context or creating
        # a new one.
        if not web3:
            web3 = Web3(HTTPProvider(WEB3_PROVIDER_DEFAULT))

        channel_manager_address = to_checksum_address(
            channel_manager_address or NETWORK_CFG.CHANNEL_MANAGER_ADDRESS)

        self.context = Context(private_key, web3, channel_manager_address)

        self.sync_channels()
Beispiel #2
0
def _connect_into_web3():
    """Connect into web3 of the testnet.

    * bloxberg:
    __ https://bloxberg.org
    """
    if not env.IS_EBLOCPOA or env.IS_GETH_TUNNEL:
        if env.IS_BLOXBERG:
            cfg.w3 = Web3(HTTPProvider("https://core.bloxberg.org"))
        else:
            cfg.w3 = Web3(HTTPProvider(f"http://localhost:{env.RPC_PORT}"))
    else:
        web3_ipc_path = env.DATADIR.joinpath("geth.ipc")
        cfg.w3 = Web3(IPCProvider(web3_ipc_path))
        # inject the poa compatibility middleware to the innermost layer
        cfg.w3.middleware_onion.inject(geth_poa_middleware, layer=0)
Beispiel #3
0
def get_contract():
    r = requests.get('http://localhost:8900/contract')
    contractAddress = r.json()['address']
    abi = r.json()['abi']
    w3 = Web3(HTTPProvider("http://localhost:8545"))
    fContract = w3.eth.contract(contractAddress, abi=abi)
    return (w3, fContract)
Beispiel #4
0
def get_contract():
    r = requests.get(settings.CONTRACT_ADDRESS + "/contract")
    contractAddress = r.json()['address']
    abi = r.json()['abi']
    w3 = Web3(HTTPProvider(settings.RPC_ADDRESS))
    fContract = w3.eth.contract(contractAddress,abi=abi)
    return (w3,fContract)
Beispiel #5
0
def web3(use_tester, mine_sync_event):
    if use_tester:
        provider = EthereumTesterProvider()
        web3 = Web3(provider)
        x = web3.testing.mine

        def mine_patched(self, count):
            x(count)
            mine_sync_event.set()
            gevent.sleep(0)  # switch context
            mine_sync_event.clear()

        web3.testing.mine = types.MethodType(
            mine_patched, web3.testing.mine
        )

        # Tester chain uses Transaction to send and validate transactions but does not support
        # EIP-155 yet. This patches the sender address recovery to handle EIP-155.
        sender_property_original = Transaction.sender.fget

        def sender_property_patched(self: Transaction):
            if self._sender:
                return self._sender

            if self.v and self.v >= 35:
                v = bytes([self.v])
                r = self.r.to_bytes(32, byteorder='big')
                s = self.s.to_bytes(32, byteorder='big')
                raw_tx = Transaction(
                    self.nonce, self.gasprice, self.startgas, self.to, self.value, self.data,
                    (self.v - 35) // 2, 0, 0
                )
                msg = keccak256(rlp.encode(raw_tx))
                self._sender = decode_hex(addr_from_sig(r + s + v, msg))
                return self._sender
            else:
                return sender_property_original(self)

        Transaction.sender = property(
            sender_property_patched,
            Transaction.sender.fset,
            Transaction.sender.fdel
        )

        # add faucet account to tester
        ethereum.tester.accounts.append(decode_hex(FAUCET_ADDRESS))
        ethereum.tester.keys.append(decode_hex(FAUCET_PRIVKEY))

        # make faucet rich
        web3.eth.sendTransaction({'to': FAUCET_ADDRESS, 'value': FAUCET_ALLOWANCE})

    else:
        rpc = HTTPProvider('localhost', 8545)
        web3 = Web3(rpc)

    yield web3

    if use_tester:
        ethereum.tester.accounts.remove(decode_hex(FAUCET_ADDRESS))
        ethereum.tester.keys.remove(decode_hex(FAUCET_PRIVKEY))
Beispiel #6
0
 def __init__(self, rpc_addr, remote_url):
     self.w3 = Web3(HTTPProvider(rpc_addr))
     self.remote_url = remote_url
     r = requests.get(remote_url)
     self.contract_abi = r.json()['abi']
     self.contract_address = r.json()['address']
     self.contract_bin = r.json()['bin']
     self.contract_address = self.w3.toChecksumAddress(
         self.contract_address)
     self.contract = self.w3.eth.contract(self.contract_address,
                                          abi=self.contract_abi,
                                          bytecode=self.contract_bin)
Beispiel #7
0
def web3(use_tester: bool, faucet_private_key: str, faucet_address: str,
         ethereum_tester):
    if use_tester:
        provider = EthereumTesterProvider(ethereum_tester)
        web3 = Web3(provider)

        # Tester chain uses Transaction to send and validate transactions but does not support
        # EIP-155 yet. This patches the sender address recovery to handle EIP-155.
        sender_property_original = Transaction.sender.fget

        def sender_property_patched(self: Transaction):
            if self._sender:
                return self._sender

            if self.v and self.v >= 35:
                v = bytes([self.v])
                r = self.r.to_bytes(32, byteorder='big')
                s = self.s.to_bytes(32, byteorder='big')
                raw_tx = Transaction(self.nonce, self.gasprice, self.startgas,
                                     self.to, self.value, self.data,
                                     (self.v - 35) // 2, 0, 0)
                msg = keccak256(rlp.encode(raw_tx))
                self._sender = decode_hex(
                    address_from_signature(r + s + v, msg))
                return self._sender
            else:
                return sender_property_original(self)

        Transaction.sender = property(sender_property_patched,
                                      Transaction.sender.fset,
                                      Transaction.sender.fdel)

        # add faucet account to tester
        ethereum_tester.add_account(faucet_private_key)

        # make faucet rich
        ethereum_tester.send_transaction({
            'from':
            ethereum_tester.get_accounts()[0],
            'to':
            faucet_address,
            'gas':
            21000,
            'value':
            FAUCET_ALLOWANCE
        })

    else:
        rpc = HTTPProvider(WEB3_PROVIDER_DEFAULT)
        web3 = Web3(rpc)

    yield web3
Beispiel #8
0
def main():
    db = dataset.connect('sqlite:///database/users.db')
    table = db['users']
    w3 = Web3(HTTPProvider('http://localhost:7545'))
    contract_address = "0xCE7001904DfF8adF14C92243306BCb39879fEb7A"
    deposit_block_check = 0
    exit_block_check = 0

    with open("../dlan-network/build/Contracts/DlanCore.json") as f:
        info_json = json.load(f)
    abi = info_json["abi"]

    my_contract = w3.eth.contract(address=contract_address, abi=abi)
    while True:
        deposit_events = my_contract.events.Deposited().createFilter(
            fromBlock=deposit_block_check).get_all_entries()
        if deposit_events:
            for deposit in deposit_events:
                print(deposit['args'])
                print(deposit['blockNumber'])
                address = deposit['args']['owner']
                amount = deposit['args']['_numberOfDlanTokens']
                table.insert(
                    dict(
                        address=address,
                        bal=amount,
                        signature=
                        'd956de560b45429ea0a8a64afafe4b0a3b0e5c54d0f4ca5c1a760af1a6cdcf6b4c8d58a14f5b482f6d2750ac076723a89554c5c19efab2441ceeaac6a82c27f51b'
                    ))
            deposit_block_check = int(deposit['blockNumber']) + 1
        exit_events = my_contract.events.Exiting().createFilter(
            fromBlock=exit_block_check).get_all_entries()
        if exit_events:
            for ex in exit_events:
                print(ex['args'])
                address = ex['args']['owner']
                amount = ex['args']['bal']
                user = table.find_one(address=address)
                if amount != user['bal']:
                    print('SUBMIT CHALLENGE!')
                    print('User claims: %s' % amount)
                    print('Database shows: %s' % user['bal'])
                    challenge = my_contract.functions.challenge(
                        user['address'], user['bal'],
                        user['signature']).call()
                else:
                    print('User exit matches database - Allow exit')
                    challenge = my_contract.functions.challenge(
                        user['address'], user['bal'],
                        user['signature']).call()
            exit_block_check = int(ex['blockNumber']) + 1
        time.sleep(15)
Beispiel #9
0
 def init_contract():
     #w3 = Web3(EthereumTesterProvider())
     #w3 = Web3(HTTPProvider('http://localhost:8545'))
     EthWorker.w3 = Web3(HTTPProvider('https://rinkeby.infura.io/v3/41da39ce9cfc46cd98721b029811d43f'))
     # inject the poa compatibility middleware to the innermost layer
     EthWorker.w3.middleware_stack.inject(geth_poa_middleware, layer=0)
     #compiled_sol = EthWorker.compile_source_file()
     #contract_id, contract_interface = compiled_sol.popitem()
     abi_text = EthWorker.abi
     EthWorker.store_var_contract = EthWorker.w3.eth.contract(
         address= EthWorker.w3.toChecksumAddress(EthWorker.contract_address),
         #abi=contract_interface['abi']
         abi=abi_text
     )
Beispiel #10
0
def init_contract(node_address=NODE,
                  contract_address=CONTRACT,
                  contract_data=COMPILED_CONTRACT,
                  is_poa=True):
    web3_inst = Web3(HTTPProvider(node_address))

    web3_inst.eth.setGasPriceStrategy(rpc_gas_price_strategy)
    # web3_inst.eth.setGasPriceStrategy(fast_gas_price_strategy)
    # web3_inst.eth.setGasPriceStrategy(medium_gas_price_strategy)

    web3_inst.middleware_stack.add(simple_cache_middleware)
    web3_inst.middleware_stack.add(latest_block_based_cache_middleware)
    web3_inst.middleware_stack.add(time_based_cache_middleware)

    if is_poa:
        web3_inst.middleware_stack.inject(geth_poa_middleware, layer=0)

    with open(contract_data, 'r') as contract_definition:
        contract_json = json.load(contract_definition)
    contract_obj = web3_inst.eth.contract(address=contract_address,
                                          abi=contract_json['abi'])

    return contract_obj, web3_inst
def send():
    total = request.args.get('total')
    contractAddress = '0xd5855dcce8933cea211fed171a31f19703a3f8be'
    web3 = Web3(HTTPProvider('https://ropsten.infura.io/v2QCDR7v7cgH6fy0y171'))
    abi = json.loads(
        '[{"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":"success","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":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"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"},{"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"}]'
    )

    fContract = web3.eth.contract(abi, contractAddress)
    print(
        'Account balance',
        fContract.call({
            'from': '0xFed55B453dBb0589ec5433a9318C09f1766D7dAb'
        }).balanceOf('0xFed55B453dBb0589ec5433a9318C09f1766D7dAb'))
    call_data = fContract.encodeABI(
        'transfer', ["0xa5Acc472597C1e1651270da9081Cc5a0b38258E3",
                     int(total)])

    tx = Transaction(
        nonce=web3.eth.getTransactionCount(
            '0xFed55B453dBb0589ec5433a9318C09f1766D7dAb'),
        gasprice=21000,
        startgas=100000,
        to='0xa5Acc472597C1e1651270da9081Cc5a0b38258E3',
        value=0,
        data=call_data,
    )

    tx.sign('d2432061d3a6cab6a2f3f635c5dda4bb5c0b9c64285c2aa11d586402f66f0507')
    raw_tx = rlp.encode(tx)
    raw_tx_hex = web3.toHex(raw_tx)
    print(raw_tx_hex)
    hash = web3.eth.sendRawTransaction(raw_tx_hex)

    print("hash is : ", hash)
    return jsonify({'receipt': hash})
Beispiel #12
0
}
'''
'''This is a contract on Ropsten with 2 contracts deployed
7/13- 	From - 0x939DD3E2DE8f472573364B3df1337857E758d90D
	createdContract - (returned: 0xc248de0871522e2487ce434465ec9c2a1ab6b4e6)
7/13- 	From - 0xE5078b80b08bD7036fc0f7973f667b6aa9B4ddBE
	createdContract - (returned: 0xf73629a8721355ee121c00bbed11a675fdf45bb3)

'''

from web3 import Web3
import json
from web3.providers.rpc import HTTPProvider

contractAddress = '0x54cb60793be0616a5f59816b350158f48d42cce5'
web3 = Web3(HTTPProvider('https://ropsten.infura.io'))
with open('factory.json', 'r') as abi_definition:
    abi = json.load(abi_definition)
print(web3.eth.blockNumber)

#abi is swap API created from factory
fContract = web3.eth.contract(abi, contractAddress)
print('Creator', fContract.call().creator)
print('Contracts', fContract.call().newContracts)
var1 = fContract.call()._oracleName
var2 = fContract.call().oracleName
print(fContract)

print()
print('var1', var1)
print()
Beispiel #13
0
import threading
import random

config = json.load(open('config.json'))
network = config['network']
address = config['address']
privkey = config['privkey']
http_addr = config[network]['http']
wss_addr = config[network]['wss']
printer_addr = config['printer'][network]
printer_sushi_addr = config['printer_sushi']
printer_abi = json.load(open('abi/printer.json'))

uni = UniswapV2Client(address, privkey, http_addr)

w3 = Web3(HTTPProvider(http_addr, request_kwargs={'timeout': 6000}))
ws = Web3(WebsocketProvider(wss_addr))

pairABI = json.load(open('abi/IUniswapV2Pair.json'))['abi']
erc20abi = json.load(open('./abi/erc20.abi'))
printer = w3.eth.contract(address=printer_addr, abi=printer_abi)
printer_sushi = w3.eth.contract(address=printer_sushi_addr, abi=printer_abi)

usdc = config['usdc'][network]
ycrv = config['ycrv'][network]
weth = config['weth'][network]
usdt = config['usdt'][network]
dai = config['dai'][network]
yycrv = w3.toChecksumAddress("0x199ddb4bdf09f699d2cf9ca10212bd5e3b570ac2")

basicTokens = {
Beispiel #14
0
def main(args):
    # logging.WARNING=30
    level = logging.WARNING - args.verbose * 10
    common_handler = logging.StreamHandler()
    common_handler.setFormatter(
        logging.Formatter('<%(levelname)s>: %(message)s'))
    LOGGER.addHandler(common_handler)
    LOGGER.setLevel(level)

    my_account_id, my_private_key = \
        decode_keyfile(args.keyfile) if args.keyfile \
        else login(args.name, args.pkey)

    gas_handler = logging.FileHandler(
        GAS_LOGGING_FILEPATH_FORMAT.format(user=my_account_id))
    gas_handler.setFormatter(logging.Formatter('%(asctime)s %(message)s'))
    GASLOG.addHandler(gas_handler)
    GASLOG.setLevel(logging.DEBUG if args.gaslog else logging.WARNING)

    if args.endpoint_uri:
        provider = HTTPProvider(args.endpoint_uri)
    else:
        # GASリミットの上限をデフォルトより大きく設定
        provider = EthereumTesterProvider(ethereum_tester=EthereumTester(
            backend=PyEVMBackend(
                genesis_parameters=PyEVMBackend._generate_genesis_params(
                    overrides={'gas_limit': 4500000}))))

    viewer_io = None
    if args.input or args.output:
        viewer_io = FileViewerIO(args.input, args.output)

    controller = Controller(my_account_id,
                            my_private_key,
                            provider,
                            dev=args.dev,
                            vio=viewer_io,
                            hookurl=args.webhook)

    # webhookを待ち受けるサーバアドレスがあれば起動
    if args.server:
        try:
            WebhookReceiver().start(args.server)
        except ValueError as err:
            LOGGER.error('failed to parse url: %s', err)

    # MISPのオプションが指定されていれば、MISPのtokenの発行
    if args.misp:
        controller.disseminate_mispdata()

    signal.signal(signal.SIGINT, controller.exit_handler)
    if args.command:
        try:
            controller.menu(args.command)
        except EOFError:
            pass
        signal.raise_signal(signal.SIGINT)
    while True:
        try:
            controller.menu()
        except EOFError:
            continue  # keep on going
Beispiel #15
0
from web3 import Web3
import json
from web3.providers.rpc import HTTPProvider
contractAddress = '0xd5855dcce8933cea211fed171a31f19703a3f8be'
web3 = Web3(HTTPProvider('https://ropsten.infura.io/v2QCDR7v7cgH6fy0y171'))

abi= json.loads('[{"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":"success","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":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"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"},{"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"}]')
fContract = web3.eth.contract(abi,contractAddress)
print('call',fContract.call({'from': '0xFed55B453dBb0589ec5433a9318C09f1766D7dAb'}).balanceOf('0xFed55B453dBb0589ec5433a9318C09f1766D7dAb'))
Beispiel #16
0
from web3 import Web3
import json
import sys
import ipfsapi
from web3.providers.rpc import HTTPProvider

api = ipfsapi.connect('127.0.0.1', 5001)
contractAddress = '0x1B76Ee1946dD680a5E53a8D3C483DA96500583fa'
web3 = Web3(HTTPProvider('https://kovan.infura.io/'))

if web3.eth.blockNumber == 0:
    print('error')
    sys.exit()
else:
    print(web3.eth.blockNumber)

with open('papyrABI.json', 'r') as abi_definition:
    abi = json.load(abi_definition)

gContract = web3.eth.contract(contractAddress, abi=abi)
i = 0
while 0 == 0:
    fileName = "content/" + gContract.call().getHash(
        i)[1] + " " + gContract.call().getHash(i)[2] + ".txt"
    fileContent = api.cat(gContract.call().getHash(i)[0])
    f = open(fileName, 'w')
    f.write(str(fileContent))
    f.close()
    i += 1
Beispiel #17
0
ADDRESS = "Your Checksummed Address(must have capital Checksummed letters)"
PASSPHRASE = "the passphrase used on your node to import the private key"


def wait_for_transaction(web3, txn_hash, timeout=300):
    with gevent.Timeout(timeout):
        while True:
            txn_receipt = web3.eth.getTransactionReceipt(txn_hash)
            if txn_receipt is not None:
                break
            gevent.sleep(1)

    return txn_receipt


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

abi = [{
    "constant":
    False,
    "inputs": [{
        "name": "addr",
        "type": "address"
    }, {
        "name": "postid",
        "type": "uint256"
    }],
    "name":
    "claimFollowerReward",
    "outputs": [],
Beispiel #18
0
import time

from src.eth_indexing.event_scanner import EventScanner
from src.tasks.cache_user_balance import get_token_address
from src.tasks.celery_app import celery
from src.utils.config import shared_config
from src.utils.helpers import load_eth_abi_values
from src.utils.redis_constants import index_eth_last_completion_redis_key
from web3 import Web3
from web3.providers.rpc import HTTPProvider

logger = logging.getLogger(__name__)

CHAIN_REORG_SAFETY_BLOCKS = 10

provider = HTTPProvider(
    shared_config["web3"]["eth_provider_url"])  # type: ignore

# Remove the default JSON-RPC retry middleware
# as it correctly cannot handle eth_getLogs block range
# throttle down.
provider.middlewares.clear()  # type: ignore

web3 = Web3(provider)

# Prepare stub ERC-20 contract object
eth_abi_values = load_eth_abi_values()
AUDIO_TOKEN_CONTRACT = web3.eth.contract(
    abi=eth_abi_values["AudiusToken"]["abi"])

AUDIO_CHECKSUM_ADDRESS = get_token_address(web3, shared_config)
Beispiel #19
0
import json
import web3
from web3 import Web3
from web3.providers.rpc import HTTPProvider



web3 = Web3(HTTPProvider('http://89.223.65.203:9549'))  # drop out port 9549 (port for Rinkeby Full),  8545 port for Mainnet, 9547 port for Rinkeby LES
# web3 = Web3(Web3.WebsocketProvider("ws://89.223.65.203:9546"))  # 9546 port for Rinkeby,  8546 port for Mainnet (not working with the current version)




# print('unlock account:', web3.personal.unlockAccount('0xfa11d0AC741eCCe206250E62A3D9725f56498674', 'Lord2015')) # print command shows result "True" in console
#
# print(web3.eth.accounts)
# print('balance 0 (eth):', web3.fromWei(web3.eth.getBalance(web3.eth.accounts[0]), "ether"))  # shows account 0 balance
# print('balance 1 (eth):', web3.fromWei(web3.eth.getBalance(web3.eth.accounts[1]), "ether"))  # shows account 1 balance
# print('balance 2 (eth):', web3.fromWei(web3.eth.getBalance(web3.eth.accounts[2]), "ether"))  # shows account 2 balance



# 0xfa11d0AC741eCCe206250E62A3D9725f56498674', '0xF80D808dC3aC390aDd0e2677dA8b3B66c44c43Cf', '0x0345a4cFeD4782A902fB11014C2c997190e5794a



# abi = [{"constant":True,"inputs":[],"name":"promoCreatedCount","outputs":[{"name":"","type":"uint256"}],"payable":False,"stateMutability":"view","type":"function"},{"constant":True,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":False,"stateMutability":"pure","type":"function"},{"constant":False,"inputs":[{"name":"_to","type":"address"},{"name":"_tokenId","type":"uint256"}],"name":"approve","outputs":[],"payable":False,"stateMutability":"nonpayable","type":"function"},{"constant":True,"inputs":[],"name":"ceoAddress","outputs":[{"name":"","type":"address"}],"payable":False,"stateMutability":"view","type":"function"},{"constant":False,"inputs":[{"name":"_to","type":"address"}],"name":"payout","outputs":[],"payable":False,"stateMutability":"nonpayable","type":"function"},{"constant":True,"inputs":[],"name":"implementsERC721","outputs":[{"name":"","type":"bool"}],"payable":False,"stateMutability":"pure","type":"function"},{"constant":True,"inputs":[],"name":"totalSupply","outputs":[{"name":"total","type":"uint256"}],"payable":False,"stateMutability":"view","type":"function"},{"constant":False,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":False,"stateMutability":"nonpayable","type":"function"},{"constant":True,"inputs":[{"name":"_tokenId","type":"uint256"}],"name":"getPerson","outputs":[{"name":"personName","type":"string"},{"name":"sellingPrice","type":"uint256"},{"name":"owner","type":"address"}],"payable":False,"stateMutability":"view","type":"function"},{"constant":False,"inputs":[{"name":"_newCEO","type":"address"}],"name":"setCEO","outputs":[],"payable":False,"stateMutability":"nonpayable","type":"function"},{"constant":False,"inputs":[{"name":"_newCOO","type":"address"}],"name":"setCOO","outputs":[],"payable":False,"stateMutability":"nonpayable","type":"function"},{"constant":False,"inputs":[{"name":"_owner","type":"address"},{"name":"_name","type":"string"},{"name":"_price","type":"uint256"}],"name":"createPromoPerson","outputs":[],"payable":False,"stateMutability":"nonpayable","type":"function"},{"constant":False,"inputs":[{"name":"_name","type":"string"}],"name":"createContractPerson","outputs":[],"payable":False,"stateMutability":"nonpayable","type":"function"},{"constant":True,"inputs":[{"name":"_tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"name":"owner","type":"address"}],"payable":False,"stateMutability":"view","type":"function"},{"constant":True,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":False,"stateMutability":"view","type":"function"},{"constant":True,"inputs":[{"name":"_owner","type":"address"}],"name":"tokensOfOwner","outputs":[{"name":"ownerTokens","type":"uint256[]"}],"payable":False,"stateMutability":"view","type":"function"},{"constant":True,"inputs":[{"name":"","type":"uint256"}],"name":"personIndexToApproved","outputs":[{"name":"","type":"address"}],"payable":False,"stateMutability":"view","type":"function"},{"constant":True,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":False,"stateMutability":"pure","type":"function"},{"constant":True,"inputs":[],"name":"NAME","outputs":[{"name":"","type":"string"}],"payable":False,"stateMutability":"view","type":"function"},{"constant":False,"inputs":[{"name":"_to","type":"address"},{"name":"_tokenId","type":"uint256"}],"name":"transfer","outputs":[],"payable":False,"stateMutability":"nonpayable","type":"function"},{"constant":True,"inputs":[{"name":"","type":"uint256"}],"name":"personIndexToOwner","outputs":[{"name":"","type":"address"}],"payable":False,"stateMutability":"view","type":"function"},{"constant":True,"inputs":[],"name":"cooAddress","outputs":[{"name":"","type":"address"}],"payable":False,"stateMutability":"view","type":"function"},{"constant":False,"inputs":[{"name":"_tokenId","type":"uint256"}],"name":"takeOwnership","outputs":[],"payable":False,"stateMutability":"nonpayable","type":"function"},{"constant":True,"inputs":[{"name":"_tokenId","type":"uint256"}],"name":"priceOf","outputs":[{"name":"price","type":"uint256"}],"payable":False,"stateMutability":"view","type":"function"},{"constant":False,"inputs":[{"name":"_tokenId","type":"uint256"}],"name":"purchase","outputs":[],"payable":True,"stateMutability":"payable","type":"function"},{"constant":True,"inputs":[],"name":"SYMBOL","outputs":[{"name":"","type":"string"}],"payable":False,"stateMutability":"view","type":"function"},{"inputs":[],"payable":False,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":False,"inputs":[{"indexed":False,"name":"tokenId","type":"uint256"},{"indexed":False,"name":"name","type":"string"},{"indexed":False,"name":"owner","type":"address"}],"name":"Birth","type":"event"},{"anonymous":False,"inputs":[{"indexed":False,"name":"tokenId","type":"uint256"},{"indexed":False,"name":"oldPrice","type":"uint256"},{"indexed":False,"name":"newPrice","type":"uint256"},{"indexed":False,"name":"prevOwner","type":"address"},{"indexed":False,"name":"winner","type":"address"},{"indexed":False,"name":"name","type":"string"}],"name":"TokenSold","type":"event"},{"anonymous":False,"inputs":[{"indexed":False,"name":"from","type":"address"},{"indexed":False,"name":"to","type":"address"},{"indexed":False,"name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":False,"inputs":[{"indexed":True,"name":"owner","type":"address"},{"indexed":True,"name":"approved","type":"address"},{"indexed":False,"name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"}]


# Contr = web3.eth.contract(0xe76f0275872b7038e0c24093fc81bd8549728a19)
#!/usr/bin/env python3

from os.path import expanduser

from web3 import Web3
from web3.providers.rpc import HTTPProvider

_path = expanduser("~/.eblocpoa/keystore/UTC--2020-03-18T13-02-58.306094822Z--d118b6ef83ccf11b34331f1e7285542ddf70bc49")
w3 = Web3(HTTPProvider("127.0.0.1:8545"))
# w3 = Web3(Web3.HTTPProvider("https://core.bloxberg.org"))

with open(_path) as keyfile:
    encrypted_key = keyfile.read()
    private_key = w3.eth.account.decrypt(encrypted_key, "alper")

print(private_key.hex())


# Enter the password to unlock this account:
# SUCCESS: Keystore '~/.eblocpoa/keystore/UTC--2020-03-18T13-02-58.306094822Z--d118b6ef83ccf11b34331f1e7285542ddf70bc49' has been imported with the id 'alper'
Beispiel #21
0
import datetime
import random
import time
import json
import requests

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "game.settings")
django.setup()

from game.models import Players, TopUps, Ticker, Payouts
from django.conf import settings

from web3 import Web3, Account
from web3.providers.rpc import HTTPProvider

w3 = Web3(HTTPProvider(settings.ETHEREUM_PROVIDER))

import logging
logger = logging.getLogger(__name__)

TICKER_ADDRESS = "https://api.coinmarketcap.com/v1/ticker/"


def update_ticker(currency):

    ticker_address = TICKER_ADDRESS + currency + "/"
    resp = requests.get(ticker_address)
    price_usd = resp.json()[0]['price_usd']

    ticker, created = Ticker.objects.get_or_create(currency=currency)
    ticker.price = price_usd