def main(): parser = ArgumentParser() parser.add_argument("--proxy", required=True) parser.add_argument("--minter", required=True) parser.add_argument("--minted-value", required=False, type=int, default=MINTED_VALUE) parser.add_argument("--minted-folder", required=True) parser.add_argument("--minted-count", required=False, type=int) args = parser.parse_args() logging.basicConfig(level=logging.DEBUG) proxy = ElrondProxy(args.proxy) bunch = BunchOfTransactions() minter = Account(pem_file=args.minter) minted_repository = AccountsRepository(args.minted_folder) if args.minted_count: minted_repository.generate_accounts(args.minted_count) minter.sync_nonce(proxy) nonce = minter.nonce value = args.minted_value for minted in minted_repository.get_all(): bunch.add(minter, minted.address.bech32(), nonce, value, "", GAS_PRICE, GAS_LIMIT) nonce += 1 bunch.send(proxy)
def prepare_args_for_stake(args: Any): validators_file = ValidatorsFile(args.validators_file) reward_address = args.reward_address # TODO: Refactor, so that only address is received here. if args.pem: account = Account(pem_file=args.pem) elif args.keyfile and args.passfile: account = Account(key_file=args.keyfile, pass_file=args.passfile) num_of_nodes = validators_file.get_num_of_nodes() stake_data = 'stake@' + binascii.hexlify(num_of_nodes.to_bytes(1, byteorder="little")).decode() validators_list = validators_file.get_validators_list() for validator in validators_list: # get validator validator_pem = validator.get("pemFile") validator_pem = path.join(path.dirname(args.validators_file), validator_pem) seed, bls_key = parse_validator_pem(validator_pem) signed_message = sign_message_with_bls_key(account.address.pubkey().hex(), seed.hex()) stake_data += f"@{bls_key}@{signed_message}" if reward_address: reward_address = Address(args.reward_address) stake_data += '@' + reward_address.hex() args.receiver = AUCTION_SMART_CONTRACT_ADDRESS args.data = stake_data if args.estimate_gas: args.gas_limit = estimate_system_sc_call(args, MetaChainSystemSCsCost.STAKE, num_of_nodes)
def prepare_args_for_add_nodes(args: Any): validators_file = ValidatorsFile(args.validators_file) # TODO: Refactor, so that only address is received here. if args.using_delegation_manager: account = Account(address=args.delegation_contract) elif args.pem: account = Account(pem_file=args.pem) elif args.keyfile and args.passfile: account = Account(key_file=args.keyfile, pass_file=args.passfile) add_nodes_data = "addNodes" num_of_nodes = validators_file.get_num_of_nodes() for validator in validators_file.get_validators_list(): # get validator validator_pem = validator.get("pemFile") validator_pem = path.join(path.dirname(args.validators_file), validator_pem) seed, bls_key = parse_validator_pem(validator_pem) signed_message = sign_message_with_bls_key(account.address.pubkey().hex(), seed.decode('ascii')) add_nodes_data += f"@{bls_key}@{signed_message}" args.receiver = args.delegation_contract args.data = add_nodes_data if args.estimate_gas: args.gas_limit = estimate_system_sc_call(args, MetaChainSystemSCsCost.DELEGATION_OPS, num_of_nodes + 1)
def setUp(self): self.testdata = Path(__file__).parent.joinpath("testdata") self.environment = DebugEnvironment() self.alice = Account( "aaaaaaaa112233441122334411223344112233441122334411223344aaaaaaaa") self.bob = Account( "bbbbbbbb112233441122334411223344112233441122334411223344bbbbbbbb") self.carol = Account( "cccccccc112233441122334411223344112233441122334411223344cccccccc") self.david = Account( "dddddddd112233441122334411223344112233441122334411223344dddddddd")
def prepare_and_send_transaction(args): proxy = ElrondProxy(args.proxy) # Need to sync nonce owner = Account(pem_file=args.pem) owner.sync_nonce(proxy) args.nonce = owner.nonce prepared = do_prepare_transaction(args) tx_hash = prepared.send(proxy) print(tx_hash) return tx_hash
def compute_dns_address_for_shard_id(shard_id) -> Address: deployer_pubkey_prefix = InitialDNSAddress[:len(InitialDNSAddress) - ShardIdentiferLen] deployer_pubkey = deployer_pubkey_prefix + bytes([0, shard_id]) deployer = Account(address=Address(deployer_pubkey)) deployer.nonce = 0 # Workaround: currently, in erdpy, in order to compute the address of a contract, one has to create an instance of the class "SmartContract". # This might change in the future. contract = SmartContract() contract.owner = deployer contract.compute_address() return contract.address
def main(): logging.basicConfig(level=logging.DEBUG) parser = ArgumentParser() parser.add_argument("--proxy", default="https://testnet-api.elrond.com") parser.add_argument("--keyfile", help="wallet JSON keyfile", required=True) parser.add_argument("--passfile", help="wallet password file", required=True) parser.add_argument("--reward-address", required=True, help="the reward address") parser.add_argument("--validators-file", required=True, help="validators JSON file (with links to PEM files)") parser.add_argument("--value", required=True, help="the value to stake") args = parser.parse_args() args.estimate_gas = True args.pem = None proxy = ElrondProxy(args.proxy) network = proxy.get_network_config() args.chain = network.chain_id args.gas_price = network.min_gas_price args.version = network.min_tx_version print("Reward address:") print(Address(args.reward_address).bech32()) confirm_continuation() prepare_args_for_stake(args) print("Transaction data:") print(args.data) confirm_continuation() print("Elrond Proxy (or Observer) address:", args.proxy) print("Chain ID:", args.chain) confirm_continuation() print("Value to stake:") print(int(args.value) / int(math.pow(10, 18)), "ERD") confirm_continuation() node_operator = Account(key_file=args.keyfile, pass_file=args.passfile) node_operator.sync_nonce(proxy) args.nonce = node_operator.nonce tx = do_prepare_transaction(args) tx.dump_to(sys.stdout) print("Transaction will now be sent.") confirm_continuation() tx.send(proxy) print("Done.")
def deploy_smart_contract(args): logger.debug("deploy_smart_contract") project_directory = args.project pem_file = args.pem proxy_url = args.proxy arguments = args.arguments gas_price = args.gas_price gas_limit = args.gas_limit value = args.value metadata_upgradeable = args.metadata_upgradeable # TODO: apply guards project = load_project(project_directory) bytecode = project.get_bytecode() metadata = CodeMetadata(metadata_upgradeable) contract = SmartContract(bytecode=bytecode, metadata=metadata) environment = TestnetEnvironment(proxy_url) owner = Account(pem_file=pem_file) def flow(): tx_hash, address = environment.deploy_contract(contract, owner, arguments, gas_price, gas_limit, value) logger.info("Tx hash: %s", tx_hash) logger.info("Contract address: %s", address) utils.dump_out_json({ "tx": tx_hash, "contract": address.bech32() }, args.outfile) environment.run_flow(flow)
def upgrade_smart_contract(args): logger.debug("upgrade_smart_contract") contract_address = args.contract project_directory = args.project pem_file = args.pem proxy_url = args.proxy arguments = args.arguments gas_price = args.gas_price gas_limit = args.gas_limit value = args.value metadata_upgradeable = args.metadata_upgradeable project = load_project(project_directory) bytecode = project.get_bytecode() metadata = CodeMetadata(metadata_upgradeable) contract = SmartContract(contract_address, bytecode=bytecode, metadata=metadata) environment = TestnetEnvironment(proxy_url) caller = Account(pem_file=pem_file) def flow(): tx_hash = environment.upgrade_contract(contract, caller, arguments, gas_price, gas_limit, value) logger.info("Tx hash: %s", tx_hash) environment.run_flow(flow)
def get_users() -> Dict[str, Account]: result = OrderedDict() for pem_file in sorted(utils.list_files(_get_users_folder(), ".pem")): nickname = Path(pem_file).stem account = Account(pem_file=pem_file) result[nickname] = account return result
def get_validator_wallets(num_validators: int) -> Dict[str, Account]: result = {} for i in range(0, num_validators): pem_file = get_validator_wallet_file(i) nickname = "validator{:02}".format(i) account = Account(pem_file=pem_file) result[nickname] = account return result
def dispatch_transactions(self, args): data = self._read_json_file() txs = data[self._TXS_FIELD_NAME] txs_index = self._read_index() total_txs = len(txs) - txs_index if total_txs == 0 or len(txs) == 0: logger.info("No transactions to dispatch") return proxy = ElrondProxy(args.proxy) # Need to sync nonce owner = Account(pem_file=args.pem) owner.sync_nonce(proxy) nonce = owner.nonce old_nonce = nonce print(nonce) bunch = BunchOfTransactions() idx = txs_index while idx < len(txs): tx = txs[idx] bunch.add(owner, tx["receiver"], nonce, tx["value"], tx["data"], tx["gasPrice"], tx["gasLimit"]) # increment nonce nonce += 1 idx += 1 logger.info(f"Sending {total_txs} transactions") try: num_sent, hashes = bunch.send(proxy) except Exception: logger.error("No valid transactions to send") num_sent = 0 hashes = [] logger.info(f"{num_sent} transactions were accepted by observers") for key in hashes: print(f"tx {txs_index+int(key)}: hash => {hashes[key]}") utils.write_file(self.txs_info_file_path, f"index:{len(txs)}") # wait until transactions are executed _wait_to_execute_txs(proxy, owner, old_nonce + num_sent)
def main(): parser = ArgumentParser() parser.add_argument("--proxy", default="https://testnet-gateway.elrond.com") parser.add_argument("--pem", required=True) parser.add_argument( "--batch-size", type=int, default=50, help="how many transactions to send before recalling nonce") parser.add_argument( "--sleep-before-recall", type=int, default=15, help="how many seconds to sleep before recalling nonce") parser.add_argument( "--sleep-after-tx", required=True, help="how many seconds to sleep after sending a transaction") args = parser.parse_args() logging.basicConfig(level=logging.WARNING) print("Press CTRL+C to stop the script execution") proxy = ElrondProxy(args.proxy) sender = Account(pem_file=args.pem) batch_size = int(args.batch_size) sleep_after_tx = int(args.sleep_after_tx) sleep_before_recall = int(args.sleep_before_recall) while True: print( f"Sleeping {sleep_before_recall} seconds before recalling nonce and sending {batch_size} transactions..." ) time.sleep(sleep_before_recall) try: sender.sync_nonce(proxy) print(f"Sender nonce recalled: nonce={sender.nonce}.") send_txs(proxy, sender, batch_size, sleep_after_tx) except errors.ProxyRequestError as err: logger.error(err)
def do_prepare_transaction(args: Any) -> Transaction: account = Account() if args.pem: account = Account(pem_file=args.pem, pem_index=args.pem_index) elif args.keyfile and args.passfile: account = Account(key_file=args.keyfile, pass_file=args.passfile) tx = Transaction() tx.nonce = int(args.nonce) tx.value = args.value tx.sender = account.address.bech32() tx.receiver = args.receiver tx.gasPrice = int(args.gas_price) tx.gasLimit = int(args.gas_limit) tx.data = args.data tx.chainID = args.chain tx.version = int(args.version) tx.sign(account) return tx
def myflow(): alice = Account( "aaaaaaaa112233441122334411223344112233441122334411223344aaaaaaaa") tx, address = environment.deploy_contract(contract, owner=alice, arguments=["0x64"]) logger.info("Tx hash: %s", tx) logger.info("Contract address: %s", address) querySum() environment.execute_contract(contract, alice, "add", arguments=["100"]) querySum()
def main(): pem_file_name = "walletKey.pem" pem_path = "~/Elrond/testnet/filegen/output" pem_file = path.join(pem_path, pem_file_name) parser = ArgumentParser() parser.add_argument("--proxy", default="http://localhost:7950") args = parser.parse_args() shard0_index = get_index_by_shard_id(pem_file, 0) shard1_index = get_index_by_shard_id(pem_file, 1) logging.basicConfig(level=logging.DEBUG) proxy = ElrondProxy(args.proxy) network = proxy.get_network_config() alice = Account(pem_file=pem_file, pem_index=shard0_index) bob = Account(pem_file=pem_file, pem_index=shard1_index) bob.sync_nonce(proxy) innerTx = Transaction() innerTx.nonce = bob.nonce innerTx.value = "0" innerTx.sender = bob.address.bech32() innerTx.receiver = "erd1qqqqqqqqqqqqqpgqrchxzx5uu8sv3ceg8nx8cxc0gesezure5awqn46gtd" # shard 2 address innerTx.gasPrice = 1000000000 innerTx.gasLimit = 500000000 innerTx.chainID = network.chain_id innerTx.version = network.min_tx_version innerTx.data = "version" innerTx.sign(bob) alice.sync_nonce(proxy) wrapperTx = Transaction() wrapperTx.nonce = alice.nonce wrapperTx.value = "0" wrapperTx.sender = alice.address.bech32() wrapperTx.receiver = bob.address.bech32() wrapperTx.gasPrice = 1000000000 wrapperTx.gasLimit = 501109000 wrapperTx.chainID = network.chain_id wrapperTx.version = network.min_tx_version wrapperTx.wrap_inner(innerTx) wrapperTx.sign(alice) wrapperTx.send(proxy)
def test_compute_address(self): contract = SmartContract() contract.owner = Account("93ee6143cdc10ce79f15b2a6c2ad38e9b6021c72a1779051f47154fd54cfbd5e") contract.owner.nonce = 0 contract.compute_address() self.assertEqual("00000000000000000500bb652200ed1f994200ab6699462cab4b1af7b11ebd5e", contract.address.hex()) self.assertEqual("erd1qqqqqqqqqqqqqpgqhdjjyq8dr7v5yq9tv6v5vt9tfvd00vg7h40q6779zn", contract.address.bech32()) contract.owner.nonce = 1 contract.compute_address() self.assertEqual("000000000000000005006e4f90488e27342f9a46e1809452c85ee7186566bd5e", contract.address.hex()) self.assertEqual("erd1qqqqqqqqqqqqqpgqde8eqjywyu6zlxjxuxqfg5kgtmn3setxh40qen8egy", contract.address.bech32())
def get_validators(num_validators: int) -> Dict[str, Tuple[str, Account]]: result = {} for i in range(0, num_validators): validator_pem_file = get_validator_key_file(i) _, pubkey = pem.parse_validator_pem(validator_pem_file) pem_file = get_validator_wallet_file(i) nickname = "validator{:02}".format(i) account = Account(pem_file=pem_file) result[nickname] = [pubkey, account] return result
def myflow(): # First, we deploy the contract in the name of Alice. alice = Account("aaaaaaaa112233441122334411223344112233441122334411223344aaaaaaaa") tx, address = environment.deploy_contract(contract, owner=alice) logger.info("Tx hash: %s", tx) logger.info("Contract address: %s", address) # Secondly, we execute a pure function of the contract. answer = environment.query_contract(contract, "getUltimateAnswer")[0] answer_bytes = base64.b64decode(answer) answer_hex = answer_bytes.hex() answer_int = int(answer_hex, 16) logger.info(f"Answer: {answer_bytes}, {answer_hex}, {answer_int}")
def main(): logging.basicConfig(level=logging.WARNING) parser = ArgumentParser() parser.add_argument("--proxy", default="http://myproxy:8079") parser.add_argument("--pem", required=True) args = parser.parse_args() items = payload.splitlines() items = [item.strip() for item in items if item] items = [parse_item(item) for item in items] print(len(items)) proxy = ElrondProxy(args.proxy) sender = Account(pem_file=args.pem) sender.sync_nonce(proxy) bunch = BunchOfTransactions() chain_id = "1" tx_version = 1 data = "foobar" gas_limit = 50000 + len(data) * 1500 cost = 0 for address, value in items: print(address, value) bunch.add(sender, address.bech32(), sender.nonce, str(value), data, GAS_PRICE, gas_limit, chain_id, tx_version) sender.nonce += 1 cost += value cost += gas_limit * GAS_PRICE print("Cost", cost) num_txs, _ = bunch.send(proxy) print("Sent", num_txs)
def _prepare_sender(args: Any) -> Account: if args.pem: sender = Account(pem_file=args.pem, pem_index=args.pem_index) elif args.keyfile and args.passfile: sender = Account(key_file=args.keyfile, pass_file=args.passfile) else: raise errors.NoWalletProvided() sender.nonce = args.nonce if args.recall_nonce: sender.sync_nonce(ElrondProxy(args.proxy)) return sender
def main(): parser = ArgumentParser() parser.add_argument("--proxy", default="https://api.elrond.com") parser.add_argument("--pem", required=True) args = parser.parse_args() logging.basicConfig(level=logging.WARNING) print("Press CTRL+C to stop the script execution") proxy = ElrondProxy(args.proxy) sender = Account(pem_file=args.pem) while True: sleep_time = 15 print(f"Sleeping {sleep_time} seconds...") time.sleep(sleep_time) try: sender.sync_nonce(proxy) print(f"Sender nonce recalled: nonce={sender.nonce}.") send_txs(proxy, sender, 100) except errors.ProxyRequestError as err: logger.error(err)
def parse_args_for_stake(args: Any): validators_file = args.validators_file validators_data = _read_json_file(validators_file) reward_address = args.reward_address if args.pem: account = Account(pem_file=args.pem) elif args.keyfile and args.passfile: account = Account(key_file=args.keyfile, pass_file=args.passfile) num_of_nodes = len(validators_data.get("validators", [])) stake_data = 'stake@' + binascii.hexlify( num_of_nodes.to_bytes(1, byteorder="little")).decode() for validator in validators_data.get("validators", []): # get validator validator_pem = validator.get("pemFile") validator_pem = path.join(path.dirname(validators_file), validator_pem) seed, bls_key = parse_validator_pem(validator_pem) signed_message = sign_message_with_bls_key( account.address.pubkey().hex(), seed.hex()) stake_data += f"@{bls_key}@{signed_message}" if reward_address: reward_address = Address(args.reward_address) stake_data += '@' + reward_address.hex() args.receiver = _STAKE_SMART_CONTRACT_ADDRESS args.data = stake_data if args.estimate_gas: args.gas_limit = estimate_system_sc_call(args, MetaChainSystemSCsCost.STAKE, num_of_nodes) return args
def prepare_nonce_in_args(args: Any): if args.recall_nonce: if args.pem: account = Account(pem_file=args.pem, pem_index=args.pem_index) elif args.keyfile and args.passfile: account = Account(key_file=args.keyfile, pass_file=args.passfile) else: raise errors.NoWalletProvided() account.sync_nonce(ElrondProxy(args.proxy)) args.nonce = account.nonce
def call_smart_contract(args): logger.debug("call_smart_contract") contract_address = args.contract pem_file = args.pem proxy_url = args.proxy function = args.function arguments = args.arguments gas_price = args.gas_price gas_limit = args.gas_limit value = args.value contract = SmartContract(contract_address) environment = TestnetEnvironment(proxy_url) caller = Account(pem_file=pem_file) def flow(): tx_hash = environment.execute_contract(contract, caller, function, arguments, gas_price, gas_limit, value) logger.info("Tx hash: %s", tx_hash) environment.run_flow(flow)
def setUp(self): super().setUp() self.alice = Account( pem_file=str(self.devnet_wallets.joinpath("users", "alice.pem")))
help="Proxy URL", default=config.get_proxy()) parser.add_argument("--contract", help="Existing contract address") parser.add_argument("--pem", help="PEM file", required=True) args = parser.parse_args() logging.basicConfig(level=logging.INFO) proxy = ElrondProxy(args.proxy) network = proxy.get_network_config() chain = network.chain_id gas_price = network.min_gas_price tx_version = network.min_tx_version environment = TestnetEnvironment(args.proxy) user = Account(pem_file=args.pem) project = ProjectRust(Path(__file__).parent.parent) bytecode = project.get_bytecode() # We initialize the smart contract with an actual address if IF was previously deployed, # so that we can start to interact with it ("query_flow") contract = SmartContract(address=args.contract) def deploy_flow(): global contract # For deploy, we initialize the smart contract with the compiled bytecode contract = SmartContract(bytecode=bytecode) tx, address = environment.deploy_contract(contract=contract,
def __init__(self, proxy=BC_PROXY, pem_file=ADMIN_PEMFILE): self._proxy = ElrondProxy(proxy) self.chain_id = self._proxy.get_chain_id() self.environment = TestnetEnvironment(proxy) log("Initialisation de l'admin avec " + pem_file) self._sender = Account(pem_file=pem_file)
# erdpy new --template simple-counter --directory ./examples hello # Create a project object afterwards project = ProjectClang("./examples/contracts/mycounter") # This will build the smart contract. # If the buildchain is missing, it will be installed automatically. project.build() # We can inspect the bytecode like this: bytecode = project.get_bytecode() logger.info("Bytecode: %s", bytecode) # Now, we create a environment which intermediates deployment and execution environment = TestnetEnvironment(args.proxy) bob = Account(pem_file=args.pem) contract = SmartContract() # A flow defines the desired steps to interact with the contract. def deploy_flow(): global contract # For deploy, we initialize the smart contract with the compiled bytecode contract = SmartContract(bytecode=bytecode) tx, address = environment.deploy_contract(contract, owner=bob) logger.info("Tx hash: %s", tx) logger.info("Contract address (hex): %s", address.hex()) logger.info("Contract address (bech32): %s", address.bech32()) def query_flow():
""" import requests import time from erdpy.accounts import Account from erdpy.transactions import Transaction from erdpy.proxy import ElrondProxy sender = "erd1hpu42hjnx6hm8fjv48cff2qmmqwjh7w3wzf00v2m538w5x2jcnpqhgsggr" wallet1 = "erd1wcpwsg6ysjrgea7zuhj3f8xzzyhdjv8t65me574h52f99he0tltsvq474v" wallet2 = "erd1gjkd9lajx530ny84clqld7m6l869mz2hgdjlkpkqdtq40334ty4s625sd4" wallet3 = "erd1l32u0h5nhcwrq2ts0rkhnanndwgt06jgd2z275zf8ey39lvxy6fsl6fmc2" urlBalance = "https://devnet-api.elrond.com/address/" + sender + "/balance" urlNonce = "https://devnet-api.elrond.com/address/" + sender + "/nonce" account = Account(key_file="erdjsonexample.json", # replace these place holders with your .json and password files pass_file="password.txt") def main(): tx1() tx2() tx3() def getbalance(): # access JSOn content response = requests.get(urlBalance) data = response.json() # parse json and convert result to int x = int((data["data"]["balance"]))