def get_partner_status(address, identity_workspace_contract, mode): # on obtient la liste des partners avec le Relay qui a une cle 1 acct = Account.from_key(mode.relay_private_key) mode.w3.eth.defaultAccount = acct.address contract = mode.w3.eth.contract(identity_workspace_contract, abi=constante.workspace_ABI) partner_list = contract.functions.getKnownPartnershipsContracts().call() liste = ["Unknown", "Authorized", "Pending", "Rejected", "Removed", ] for partner_workspace_contract in partner_list: try: authorization_index = contract.functions.getPartnership(partner_workspace_contract).call()[1] except Exception as ex: logging.error('E = %s',ex) return None, None partner_address = contractsToOwners(partner_workspace_contract, mode) if partner_address == address : local_status = liste[authorization_index] break identity_address = contractsToOwners(identity_workspace_contract, mode) identity_private_key = privatekey.get_key(identity_address, 'private_key', mode) if identity_private_key : acct = Account.from_key(identity_private_key) mode.w3.eth.defaultAccount = acct.address contract = mode.w3.eth.contract(partner_workspace_contract,abi=constante.workspace_ABI) partner_status = liste[contract.functions.getMyPartnershipStatus().call()] else : partner_status = None return local_status, partner_status
def get_partners(self, mode): # on obtient la liste des partners avec le Relay qui a une cle 1 self.partners = [] acct = Account.from_key(mode.relay_private_key) mode.w3.eth.defaultAccount = acct.address contract = mode.w3.eth.contract(self.workspace_contract, abi=constante.workspace_ABI) try: partners_list = contract.functions.getKnownPartnershipsContracts( ).call() except: return False liste = [ "Unknown", "Authorized", "Pending", "Rejected", "Removed", ] for partner_workspace_contract in partners_list: try: authorization_index = contract.functions.getPartnership( partner_workspace_contract).call()[1] except Exception as ex: logging.warning(ex) return False partner_username = ns.get_username_from_resolver( partner_workspace_contract, mode) if authorization_index != 4 and partner_username: # only if not "Removed" and parner is known in the database partner_address = contractsToOwners(partner_workspace_contract, mode) partner_publickey = mode.w3.soliditySha3(['address'], [partner_address]) self.partners.append({ 'address': partner_address, 'publickey': partner_publickey, 'workspace_contract': partner_workspace_contract, 'username': partner_username, 'authorized': liste[authorization_index], 'status': 'Not available' }) # on met a jour le status avec un acces par le owner au partnership dans le contract du partner if self.private_key: acct = Account.from_key(self.private_key_value) mode.w3.eth.defaultAccount = acct.address for index in range(0, len(self.partners)): contract = mode.w3.eth.contract( self.partners[index]['workspace_contract'], abi=constante.workspace_ABI) self.partners[index]['status'] = liste[ contract.functions.getMyPartnershipStatus().call()] else: logging.warning( 'status des partnerships impossible a obtenir, private key not found' ) return True
def check_private_key(private_key: str) -> str: """ Ethereum private key validator for ArgParse :param private_key: Ethereum Private key :return: Ethereum Private key """ try: Account.from_key(private_key) except (ValueError, Error): # TODO Report `Error` exception as a bug of eth_account raise argparse.ArgumentTypeError( f'{private_key} is not a valid private key') return private_key
def place_order(self, order: Order, private_key: HexStr) -> Union[HexStr, ErrorResponse]: """ Place order. If `feeAmount=0` in Order it will be calculated calling `get_fee(order)` :return: UUID for the order as an hex hash """ assert (order["buyAmount"] and order["sellAmount"] ), "Order buyAmount and sellAmount cannot be empty" url = self.base_url + "orders/" order["feeAmount"] = order["feeAmount"] or self.get_fee(order) signable_bytes = order.signable_bytes(domain=self.domain_separator) signable_hash = Web3.keccak(signable_bytes) message = encode_defunct(primitive=signable_hash) signed_message = Account.from_key(private_key).sign_message(message) data_json = { "sellToken": order["sellToken"].lower(), "buyToken": order["buyToken"].lower(), "sellAmount": str(order["sellAmount"]), "buyAmount": str(order["buyAmount"]), "validTo": order["validTo"], "appData": HexBytes(order["appData"]).hex() if isinstance( order["appData"], bytes) else order["appData"], "feeAmount": str(order["feeAmount"]), "kind": order["kind"], "partiallyFillable": order["partiallyFillable"], "signature": signed_message.signature.hex(), "signingScheme": "ethsign", "from": Account.from_key(private_key).address, } r = requests.post(url, json=data_json) if r.ok: return HexStr(r.json()) else: return ErrorResponse(r.json())
def is_partner(address, identity_workspace_contract, mode): # on obtient la liste des partners avec le Relay qui a une cle 1 acct = Account.from_key(mode.relay_private_key) mode.w3.eth.defaultAccount = acct.address contract = mode.w3.eth.contract(identity_workspace_contract, abi=constante.workspace_ABI) partner_list = contract.functions.getKnownPartnershipsContracts().call() liste = [ "Unknown", "Authorized", "Pending", "Rejected", "Removed", ] for partner_workspace_contract in partner_list: try: authorization_index = contract.functions.getPartnership( partner_workspace_contract).call()[1] except Exception as ex: logging.error('Error : %s', ex) return False partner_address = contractsToOwners(partner_workspace_contract, mode) if partner_address == address and liste[ authorization_index] == 'Authorized': return True return False
def transfer_workspace(address_from, private_key, address_to, mode): workspace_contract = ownersToContracts(address_from, mode) contract = mode.w3.eth.contract(mode.foundation_contract, abi=constante.foundation_ABI) #setup default account for previous address acct = Account.from_key(private_key) mode.w3.eth.defaultAccount = acct.address nonce = mode.w3.eth.getTransactionCount(address_from) txn = contract.functions.transferOwnershipInFoundation( workspace_contract, address_to).buildTransaction({ 'chainId': mode.CHAIN_ID, 'gas': 800000, 'gasPrice': mode.w3.toWei(mode.GASPRICE, 'gwei'), 'nonce': nonce, }) signed_txn = mode.w3.eth.account.signTransaction(txn, private_key) mode.w3.eth.sendRawTransaction(signed_txn.rawTransaction) hash1 = mode.w3.toHex(mode.w3.keccak(signed_txn.rawTransaction)) receipt = mode.w3.eth.waitForTransactionReceipt(hash1, timeout=2000, poll_latency=1) if not receipt['status']: return False return True
def btn_login_fuc(self): if self.splitter.widget(1).objectName() == 'Ui_Filekey': if self.splitter.widget(1).lineEdit.text().endswith(".json") ==False: reply = QMessageBox.warning(self, "警告", "请选择KEYFILE文件!") return if self.splitter.widget(1).lineEdit_2.text() == '': reply = QMessageBox.warning(self, "警告", "KEYFILE密码不能为空,请输入!") return with open(self.splitter.widget(1).lineEdit.text().replace("/", "\\"), 'r') as f: wallet = json.load(f) try: priv_key = Account.decrypt(wallet, self.splitter.widget(1).lineEdit_2.text()).hex() account = Account.privateKeyToAccount(priv_key) except Exception as e: reply = QMessageBox.warning(self, "警告", str(e)) return if self.splitter.widget(1).objectName() == 'Ui_Private': if self.splitter.widget(1).lineEdit_2.text() =='': reply = QMessageBox.warning(self, "警告", "private不能为空,请输入!") return try: account = Account.from_key(self.splitter.widget(1).lineEdit_2.text()) except Exception as e: reply = QMessageBox.warning(self, "警告", str(e)) return mainwindow.address = account.address mainwindow.private = account._key_obj mainwindow.public = account._key_obj.public_key # print(account.address,account._key_obj,account._key_obj.public_key) mainwindow.lineEdit_2.setText(str(account.address)) mainwindow.show() self.close()
def AddressWithChecksumFromPrivateKey(private_key: str)-> str: """ Get the Address with checksum from Private Key """ if private_key==None: raise ValueError('private_key is None') return AddressWithChecksum(str(Account.from_key(private_key).address))
def main(): dai = Contract.from_explorer("0x6B175474E89094C44Da98b954EedeAC495271d0F") dai_deposit = Contract.from_explorer( "0xF6f4526a05a38198dBEddFc226d30dbb5419951F") dai_vault = Contract.from_explorer( "0xBFa4D8AA6d8a379aBFe7793399D3DdaCC5bBECBB") user = accounts.load( click.prompt("Account", type=click.Choice(accounts.load()))) # account_name = input(f"What account to use?: ") # user = accounts.load(account_name) signer = Account.from_key(user.private_key) balance = dai.balanceOf(user) print("DAI balance:", balance.to("ether")) amount = click.prompt("Deposit amount", type=click.FloatRange(min=0)) amount = min(Wei(f"{amount} ether"), balance) permit = build_permit(str(user), str(dai_deposit), dai) signed = signer.sign_message(permit) if click.confirm("Send transaction?"): dai_deposit.deposit( amount, [user, dai_deposit, 0, 0, True, signed.v, signed.r, signed.s], {"from": user}, ) vault_balance = dai_vault.balanceOf(user) print("yvDAI balance", vault_balance.to("ether"))
def generate_dev_accounts( mnemonic: str = DEFAULT_TEST_MNEMONIC, number_of_accounts: int = DEFAULT_NUMBER_OF_TEST_ACCOUNTS, hd_path_format="m/44'/60'/0'/{}", ) -> List[GeneratedDevAccount]: """ Create accounts from the given test mnemonic. Use these accounts (or the mnemonic) in chain-genesis for testing providers. Args: mnemonic (str): mnemonic phrase or seed words. number_of_accounts (int): Number of accounts. Defaults to ``10``. hd_path_format (str): Hard Wallets/HD Keys derivation path format. Defaults to ``"m/44'/60'/0'/{}"``. Returns: List[:class:`~ape.utils.GeneratedDevAccount`]: List of development accounts. """ seed = seed_from_mnemonic(mnemonic, "") accounts = [] for i in range(number_of_accounts): hd_path = HDPath(hd_path_format.format(i)) private_key = HexBytes(hd_path.derive(seed)).hex() address = Account.from_key(private_key).address accounts.append(GeneratedDevAccount(address, private_key)) return accounts
def send_tokens(self, to: str, amount: int, erc20_address: str, private_key: str, nonce: Optional[int] = None, gas_price: Optional[int] = None, gas: Optional[int] = None) -> bytes: """ Send tokens to address :param to: :param amount: :param erc20_address: :param private_key: :param nonce: :param gas_price: :param gas: :return: tx_hash """ erc20 = get_erc20_contract(self.w3, erc20_address) account = Account.from_key(private_key) tx_options = {'from': account.address} if nonce: tx_options['nonce'] = nonce if gas_price: tx_options['gasPrice'] = gas_price if gas: tx_options['gas'] = gas tx = erc20.functions.transfer(to, amount).buildTransaction(tx_options) return self.ethereum_client.send_unsigned_transaction( tx, private_key=private_key)
def invoice_register(c): w3 = create_w3() contract = create_invoice_registry(w3) owner_key = os.getenv('chainvoice_qadmin_private_key') owner = Account.from_key(owner_key) debug(w3.eth.getBalance(owner.address)) other_address = os.getenv('chainvoice_other_address') debug(owner.address) debug(other_address) invoice_id = uuid4().int token_id = 1 invoice_amount = 1000 contract_call = contract.contract.functions.registerInvoice1( invoice_id, other_address, token_id, invoice_amount) nonce = w3.eth.getTransactionCount(owner.address) txn = contract_call.buildTransaction({ 'nonce': nonce, 'gas': 1000000, }) signed_txn = w3.eth.account.sign_transaction(txn, private_key=owner.key) txn_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction) txn_receipt = w3.eth.waitForTransactionReceipt(txn_hash) debug(invoice_id) print(f'txn_receipt: {txn_receipt}') print(f"transaction status: {txn_receipt['status']}") debug(contract.contract.functions.invoices(invoice_id).call())
async def publish(self, filename, magnet, private_key): """Publish draft post by magnet. - content contract `post()` - push to known nodes """ account = Account.from_key(private_key) # log.info("Post to contract from %s", account.address) await self.app.contract.post_service.post( address=account.address, private_key=private_key, reply_to=b'0', magnet=bytes.fromhex(magnet), size=os.path.getsize(filename), author=account.address) # log.info("Schedule distribution...") # make a look like a file was downloaded pub = Publication(magnet=magnet, reply_to='0x', retention=12, source='0x', size=os.path.getsize(filename)) await self.app.db.publications.store(pub) target_filename = self.app.storage.get_absolute_path(magnet) self.app.log.warning("Target filename: %s", target_filename) target_filename.parent.mkdir(parents=True) os.rename(filename, target_filename) self.app.log.warning("Emit DownloadFinished event for %s", magnet) await self.app.emit(DownloadFinished(publication=pub)) self.app.log.info("Starting file distribution") # distribute file over network await self.app.peering.distribute(target_filename, magnet) self.app.log.info("Finish publishing")
def get_party_account(party_record) -> LocalAccount: # TODO: check address exists # TODO: check key exists account_address = PartyService.get_party_address(party_record) account_key = secret_service.get_secret_value(account_address) account = Account.from_key(account_key) return account
def test_order_started_processor(): config_file = app.config["AQUARIUS_CONFIG_FILE"] web3 = setup_web3(config_file) test_account1 = Account.from_key( os.environ.get("EVENTS_TESTS_PRIVATE_KEY", None)) dt_address = deploy_datatoken(web3, test_account1, "TT1", "TT1Symbol") es_instance = Mock() es_instance.read.return_value = { "sample_asset": "mock", "stats": { "orders": 0 } } es_instance.update.return_value = None price_json = { "value": 12.4, "tokenAddress": "test", "tokenSymbol": "test2" } processor = OrderStartedProcessor(dt_address, es_instance, 0, 0) with patch( "aquarius.events.processors.get_number_orders_price") as no_mock: no_mock.return_value = 3, price_json updated_asset = processor.process() assert es_instance.update.called_once() assert updated_asset["stats"]["orders"] == 3 assert updated_asset["stats"]["price"] == price_json
def import_private_key(trustline_files): private_key = read_private_key() account = Account.from_key(private_key) click.echo(f"Read private key for address {account.address}") password = read_password() trustline_files.store(account, password)
def key_to_account(coin, priv_key): '''Converts the private key string in a child key to an account object that bit or web3.py can use to do transactions''' if coin == ETH: return Account.from_key(priv_key) elif coin == BTCTEST: return bit.PrivateKeyTestnet(priv_key)
def test_approveRequest_failure(wallet_contract, w3): account = Account.from_key(keys[2]) transaction = wallet_contract.functions.makeRequest( name="Test Business", description="To get some test data").buildTransaction({ 'from': accounts[2], 'nonce': w3.eth.getTransactionCount(accounts[2]), 'value': Web3.toWei(.5, 'ether') }) signed = account.sign_transaction(transaction) tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction) w3.eth.waitForTransactionReceipt(tx_hash) try: # if this approve goes through it means this test failed wallet_contract.functions.approveRequest(1).call({ 'from': accounts[2], 'nonce': w3.eth.getTransactionCount(accounts[2]) }) assert False except: assert True
def AddressFromPrivateKey(private_key: str)-> str: """ Get the Addres from Private Key """ if private_key==None: raise ValueError('private_key is None') return Address(str(Account.from_key(private_key).address))
def wallet_contract(factory_contract, w3, compiled_contract): value = w3.toWei(.6, 'ether') transaction = factory_contract.functions.createWallet( name="John Test", home="1 Main St, San Francisco, CA", tin="000-99-8888", phone="732-555-0055").buildTransaction({ 'from': accounts[1], 'value': value, 'nonce': w3.eth.getTransactionCount(accounts[1]) }) acct = Account.from_key(keys[1]) signed = acct.sign_transaction(transaction) w3.eth.sendRawTransaction(signed.rawTransaction) #w3.eth.waitForTransactionReceipt(tx_hash) walletContract = compiled_contract['<stdin>:KYC_Wallet'] address = factory_contract.functions.getDeployedWallets().call()[0] Contract = w3.eth.contract(abi=walletContract['abi'], address=address) return Contract
class Command(BaseCommand): help = 'Deploys master copy using first unlocked account on the node if `ganache -d` is found and contract ' \ 'is not deployed. If not you need to set a private key using `--deployer-key`' GANACHE_FIRST_ACCOUNT_KEY = '0x4f3edf983ac636a65a842ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d' DEFAULT_ACCOUNT = Account.from_key(GANACHE_FIRST_ACCOUNT_KEY) def add_arguments(self, parser): # Positional arguments parser.add_argument('--deployer-key', help='Private key for deployer') def handle(self, *args, **options): ethereum_client = EthereumClientProvider() deployer_key = options['deployer_key'] deployer_account = Account.from_key(deployer_key) if deployer_key else self.DEFAULT_ACCOUNT master_copies_with_deploy_fn = { settings.SAFE_CONTRACT_ADDRESS: Safe.deploy_master_contract, settings.SAFE_V1_0_0_CONTRACT_ADDRESS: Safe.deploy_old_master_contract, settings.SAFE_PROXY_FACTORY_ADDRESS: ProxyFactory.deploy_proxy_factory_contract, } for master_copy_address, deploy_fn in master_copies_with_deploy_fn.items(): self.stdout.write(self.style.SUCCESS(f'Checking if contract was already deployed on ' f'{master_copy_address}')) if ethereum_client.is_contract(master_copy_address): self.stdout.write(self.style.NOTICE(f'Master copy was already deployed on {master_copy_address}')) else: self.stdout.write(self.style.SUCCESS(f'Deploying contract using deployer account, ' f'address={master_copy_address} not found')) master_copy_address = deploy_fn(ethereum_client, deployer_account=deployer_account).contract_address self.stdout.write(self.style.SUCCESS(f'Contract has been deployed on {master_copy_address}'))
def __init__(self): # Load config files with open('./config.json') as f: self.config = json.load(f) with open('./pancakeswap_abi.json') as f: self.pancakeswap_abi = json.load(f) # Connect to BSC node self.w3 = Web3(Web3.WebsocketProvider( 'wss://silent-old-pine.bsc.quiknode.pro/50d141387da957f5bd76a5018ec2fd33a7c48dfe/')) # Pancakeswap Router Address self.pancakeswapAddress = "0x10ED43C718714eb63d5aA57B78B54704E256024E" self.pancake_contract = self.w3.eth.contract( address=self.pancakeswapAddress, abi=self.pancakeswap_abi) # Read wallet private key self.account = Account.from_key(config["PRIVATE_KEY"]) # Chain ID of Binance Smart Chain mainnet self.chainId = "0x38" self.bnb_address = Web3.toChecksumAddress( "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c") self.gasLimit = 4000000
def __init__(self, w3: Web3, rootchain_address: AnyAddress, private_key: bytes): self._w3 = w3 self._rootchain = self._w3.eth.contract(rootchain_address, **rootchain_interface) self._acct = Account.from_key(private_key) # Allow web3 to autosign with account middleware = construct_sign_and_send_raw_middleware(private_key) self._w3.middleware_onion.add(middleware) # Set up dats structures self.pending_deposits = { } # Dict mapping tokenId to deposit txn in Rootchain contract self.deposits = {} # Dict mapping tokenId to last known txn self.transactions = [TokenToTxnHashIdSMT() ] # Ordered list of block txn dbs self.last_sync_time = self._w3.eth.blockNumber # Add listeners (dict of filters: callbacks) self.listeners = {} # Add listener for deposits self.listeners[self._rootchain.events.DepositAdded.createFilter( fromBlock=self._w3.eth.blockNumber)] = self.addDeposit # Add listener for deposit cancellations self.listeners[self._rootchain.events.DepositCancelled.createFilter( fromBlock=self._w3.eth.blockNumber, )] = self.remDeposit # Add listener for challenging withdrawals self.listeners[self._rootchain.events.ExitStarted.createFilter( fromBlock=self._w3.eth.blockNumber, )] = self.checkExit # Add listener for finalized withdrawals self.listeners[self._rootchain.events.ExitFinished.createFilter( fromBlock=self._w3.eth.blockNumber, )] = self.remDeposit
def _try_validate_ethereum_private_key_path(private_key_path: str) -> None: """ Try to validate a private key. :param private_key_path: the path to the private key. :return: None :raises: an exception if the private key is invalid. """ try: with open(private_key_path, "r") as key: data = key.read() Account.from_key(data) except Exception as e: logger.error( "This is not a valid private key file: '{}'\n Exception: '{}'". format(private_key_path, e)) sys.exit(1)
def __init__(self, ethereum_client: EthereumClient, gas_station: GasStation, redis: Redis, funder_private_key: str, max_eth_to_send: int): self.ethereum_client = ethereum_client self.gas_station = gas_station self.redis = redis self.funder_account = Account.from_key(funder_private_key) self.max_eth_to_send = max_eth_to_send
def test_deploy_datatoken_fails(): config_file = app.config["AQUARIUS_CONFIG_FILE"] web3 = setup_web3(config_file) test_account1 = Account.from_key(os.environ.get("EVENTS_TESTS_PRIVATE_KEY", None)) with patch.object(type(web3.eth), "getTransactionReceipt") as mock: mock.side_effect = Exception() with pytest.raises(Exception, match="tx not found"): deploy_datatoken(web3, test_account1, "TT1", "TT1Symbol")
def __init__(self, gas_station: GasStation, ethereum_client: EthereumClient, redis: Redis, safe_valid_contract_addresses: Set[str], proxy_factory_address: str, tx_sender_private_key: str): self.gas_station = gas_station self.ethereum_client = ethereum_client self.redis = redis self.safe_valid_contract_addresses = safe_valid_contract_addresses self.proxy_factory = ProxyFactory(proxy_factory_address, self.ethereum_client) self.tx_sender_account = Account.from_key(tx_sender_private_key)
def init_account(self, private, public): '''Create the Account object with the given private key.''' acct = Account.from_key(private) public = self.toChecksumAddress(public) assert public == acct.address, 'Address does not match the private key.' self._address = acct.address self._nonce = self.eth.getTransactionCount(self.address) return acct
def validate_refund_receiver(self, refund_receiver): relay_sender_address = Account.from_key( settings.SAFE_TX_SENDER_PRIVATE_KEY).address if refund_receiver and refund_receiver not in (NULL_ADDRESS, relay_sender_address): raise ValidationError( f'Refund Receiver must be empty, 0x00...00 address or Relay Service Sender Address: ' f'${relay_sender_address}') return refund_receiver
async def get_oracle_accounts() -> Dict[str, LocalAccount]: """Create oracle and verify oracle accounts.""" oracle_accounts = {} for network in ENABLED_NETWORKS: oracle = Account.from_key(NETWORKS[network]["ORACLE_PRIVATE_KEY"]) oracle_accounts[network] = oracle await check_oracle_account(network, oracle) return oracle_accounts