コード例 #1
0
def send_transaction(*, web3: Web3, transaction_options: TxParams, private_key=None):
    """
    Send the transaction with given transaction options
    Will either use an account of the node(default), or a local private key(if given) to sign the transaction.
    It will not block until the transaction was successfully mined.

    Returns: The sent transaction hash
    """

    if private_key is not None:
        account = Account.from_key(private_key)

        if (
            "from" in transaction_options
            and transaction_options["from"] != account.address
        ):
            raise ValueError(
                "From can not be set in transaction_options if a private key is used"
            )
        transaction_options["from"] = account.address

        transaction = fill_nonce(web3, transaction_options)
        transaction = fill_transaction_defaults(web3, transaction)
        signed_transaction = account.sign_transaction(transaction)
        tx_hash = web3.eth.sendRawTransaction(signed_transaction.rawTransaction)

    else:
        _set_from_address(web3, transaction_options)
        tx_hash = web3.eth.sendTransaction(transaction_options)

    return tx_hash
コード例 #2
0
    def __init__(
        self,
        config=None,
        spath="",
        privateKey=None,
        keystorefile=None,
        keystore_pwd=None,
        limit=None,
        price=None,
    ):
        """
        :param config: 配置文件路径
        :param spath: 合约源文件目录
        :param privateKey: 部署合约者的私钥
        :param keystorefile: 部署合约者钱包文件
        :param keystore_pwd: 部署合约者钱包密码
        :param provider: 提供者(指定连接到哪个网络中)
        :param limit: 区块gas上限
        :param price: 区块gas价格
        """
        provider = dconfig.provider

        self.gas_limit = limit if limit else dconfig.GAS_LIMIT
        self.gas_price = price if price else Web3.toWei("25", "gwei")
        self.w3 = Web3(HTTPProvider(dconfig.provider))
        # Rinkeby测试网络使用的是POA权威证明, 需要使用这个中间件才能正常工作
        # http://web3py.readthedocs.io/en/stable/middleware.html#geth-style-proof-of-authority
        if provider.startswith("https://rinkeby"):
            self.w3.middleware_stack.inject(geth_poa_middleware, layer=0)

        if privateKey:
            self.account = Account.privateKeyToAccount(privateKey)
        elif keystorefile and keystore_pwd:
            with open(keystorefile) as wf:
                wallet = json.load(wf)
                privateKey = Account.decrypt(wallet, keystore_pwd)
                self.account = Account.privateKeyToAccount(privateKey)
        else:
            raise ValueError(
                "The deployment contract requires a valid address.")
        config = config if config else "deploy_contract.json"
        self.conf = self._load_config(config)
        self.spath = spath
        self.addresses = {}  # 记录发布合约的合约地址
        self.addresses["self"] = self.account.address
        self.prepare_dir()  # 创建abi保存地址
コード例 #3
0
ファイル: wallet.py プロジェクト: kedarmoh/BlockChainUnit19HW
def priv_key_to_account(coin, priv_key):
    if coin == 'ETH':
        return Account.privateKeyToAccount(priv_key)
    elif coin == 'BTCTEST':
        return PrivateKeyTestnet(priv_key)
    else:
        print('Cryptocoin is not valid')
    return None
コード例 #4
0
ファイル: main.py プロジェクト: nialloc/GameOfLife
def get_data():

    
    # not sure if this particular bit is needed, but it referenced in the google cloud function docs
    if request.method == 'OPTIONS':
    # Allows GET requests from any origin with the Content-Type
    # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)

    # Set CORS headers for the main request
    headers = {
        'Access-Control-Allow-Origin': '*'
    }

    cell4 = contract.functions.getCells().call()
    print("cells ", cell4)

    cells = generate_cells(cell4)

    private_key = os.getenv('private_key')
    print('private_key',private_key)

    acct = Account.from_key(private_key)
    caller_address = acct.address
    caller_balance = web3.eth.get_balance(caller_address)
    
    # convert balance into ether..
    caller_balance = str(web3.fromWei(caller_balance,'ether'))
    
    block = web3.eth.blockNumber
    myblock = contract.functions.getMyBlock().call()

    response = {
        'status'          : 'ok',
        'network'         : network_name,
        'block'           : block,
        'myblock'         : myblock,
        'caller_address'  : caller_address,
        'caller_balance'  :  caller_balance,
        'contract_address': deployed_contract_address,
        'contract_balance' : web3.eth.get_balance(deployed_contract_address),
        'target'            : myblock + GAP,
        'rows' : rows,
        'cols' : cols,
        'cells' : cells
        
    }
    return jsonify(response), 200 , headers
コード例 #5
0
def _build_and_sign_transaction(
    function_call, *, web3, transaction_options, private_key
):
    account = Account.from_key(private_key)

    if "from" in transaction_options and transaction_options["from"] != account.address:
        raise ValueError(
            "From can not be set in transaction_options if a private key is used"
        )
    transaction_options["from"] = account.address

    transaction = fill_nonce(web3, function_call.buildTransaction(transaction_options))

    return account.sign_transaction(transaction)
コード例 #6
0
ファイル: demo.py プロジェクト: starkware-libs/cairo-lang
def send_transaction(w3, transaction, sender_account: eth.Account):
    """
    Sends an Ethereum transaction and waits for it to be mined.

    w3: a web3 Ethereum client.
    transaction: the transaction to be sent.
    sender_account: the account sending the transaction.
    """
    transaction_dict = transaction.buildTransaction(
        tx_kwargs(w3, sender_account.address))
    signed_transaction = sender_account.signTransaction(transaction_dict)
    print('Transaction built and signed.')
    tx_hash = w3.eth.sendRawTransaction(
        signed_transaction.rawTransaction).hex()
    print(f'Transaction sent. tx_hash={tx_hash} .')
    receipt = w3.eth.waitForTransactionReceipt(tx_hash)
    print('Transaction successfully mined.')
    return receipt
コード例 #7
0
ファイル: main.py プロジェクト: nialloc/GameOfLife
def do_command(cmd):

    # not sure if this particular bit is needed, but it referenced in the google cloud function docs
    if request.method == 'OPTIONS':
    # Allows GET requests from any origin with the Content-Type
    # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return jsonify({'status':'ok'}), 204, headers

    # Set CORS headers for the main request
    headers = {
        'Access-Control-Allow-Origin': '*'
    }

    if cmd in ['/step','/setcells']:
        pass
    else :
        return jsonify({"unknown cmd":cmd})
        

    private_key = os.getenv('private_key')
    print('private_key',private_key)

    acct = Account.from_key(private_key)
    caller_address = acct.address

    print('caller_address',caller_address)

    nonce = web3.eth.getTransactionCount(caller_address)
    chainId = int(os.getenv('chain_id'))

    gwei = 1_000_000_000
    gasPrice = 1 * gwei

    caller_balance0 = web3.eth.get_balance(caller_address)

    gasPrice = Web3.toWei(1, 'gwei')

    myblock = contract.functions.getMyBlock().call()

    print('myblock',myblock)
    
    if 'setcells' in cmd:
        print("setcells")
    
        data = request.data

        print('type',type(data))
        print('data',data)
        # convert from text to dict 
        try :
            cells = json.loads(data)
            print("cells",cells)
        except Exception as e:
            return jsonify({'status':str(e)})

        # convert array into 4 x 256 bit elements
        try:
            cell4 = generate_cell4(cells['cells'])
            print("cell4",cell4)
        except Exception as e:
            return jsonify({'code':str(e)})


        txn = contract.functions.setCells(cell4[0],cell4[1],cell4[2],cell4[3]).buildTransaction(
            {
                'chainId' : chainId,
                'nonce': nonce,
                'gasPrice': gasPrice,
            }
        )
    else :
        print("starting step..")

        # check when the last step was done
        # compare to current block
        # only execute the step if the time is greater than one minute
        myblock = contract.functions.getMyBlock().call()
        current = web3.eth.blockNumber

        target  = myblock + GAP
        print(f"current {current} target {target}")
        
        if current < target :
            return jsonify({'code':f'current block is {current}, skipping until block {target}'})    

        txn = contract.functions.step().buildTransaction(
            {
                'chainId' : chainId,
                'nonce': nonce,
                'gasPrice': gasPrice,
            }
        )
    print('txn',txn)

    
    signed_txn = web3.eth.account.sign_transaction(
        txn,
        private_key=private_key
    )

    try: 
        result = web3.eth.sendRawTransaction(signed_txn.rawTransaction)
        print('result',result)
        txn['status'] = 'ok'
    except Exception as e:
        print(type(e))
        print(e)
        txn = {'status':str(e)}

    response = txn

    caller_balance1 = web3.eth.get_balance(caller_address)

    
    response['block'] = web3.eth.blockNumber
    response['balance_before'] = caller_balance0
    response['balance_after'] = caller_balance1
    response['cost'] = caller_balance0 - caller_balance1
    response['myblock'] = contract.functions.getMyBlock().call()

    return jsonify(response), 200 , headers