use of com.hedera.hashgraph.sdk.AccountBalance in project hedera-sdk-java by hashgraph.
the class ScheduledTransactionMultiSigThresholdExample method main.
// public static void main(String[] args) throws PrecheckStatusException, IOException, TimeoutException, ReceiptStatusException {
public static void main(String[] args) throws PrecheckStatusException, TimeoutException, ReceiptStatusException {
Client client = Client.forName(HEDERA_NETWORK);
// Defaults the operator account ID and key such that all generated transactions will be paid for
// by this account and be signed by this key
client.setOperator(OPERATOR_ID, OPERATOR_KEY);
// Generate four new Ed25519 private, public key pairs.
PrivateKey[] privateKeys = new PrivateKey[4];
PublicKey[] publicKeys = new PublicKey[4];
for (int i = 0; i < 4; i++) {
PrivateKey key = PrivateKey.generateED25519();
privateKeys[i] = key;
publicKeys[i] = key.getPublicKey();
System.out.println("public key " + (i + 1) + ": " + publicKeys[i]);
System.out.println("private key " + (i + 1) + ": " + privateKeys[i]);
}
// require 3 of the 4 keys we generated to sign on anything modifying this account
KeyList transactionKey = KeyList.withThreshold(3);
Collections.addAll(transactionKey, publicKeys);
TransactionResponse transactionResponse = new AccountCreateTransaction().setKey(transactionKey).setInitialBalance(Hbar.fromTinybars(1)).setAccountMemo("3-of-4 multi-sig account").execute(client);
// This will wait for the receipt to become available
TransactionReceipt txAccountCreateReceipt = transactionResponse.getReceipt(client);
AccountId multiSigAccountId = Objects.requireNonNull(txAccountCreateReceipt.accountId);
System.out.println("3-of-4 multi-sig account ID: " + multiSigAccountId);
AccountBalance balance = new AccountBalanceQuery().setAccountId(multiSigAccountId).execute(client);
System.out.println("Balance of account " + multiSigAccountId + ": " + balance.hbars.toTinybars() + " tinybar.");
// schedule crypto transfer from multi-sig account to operator account
TransactionResponse transferToSchedule = new TransferTransaction().addHbarTransfer(multiSigAccountId, Hbar.fromTinybars(-1)).addHbarTransfer(Objects.requireNonNull(client.getOperatorAccountId()), Hbar.fromTinybars(1)).schedule().freezeWith(client).sign(// add 1 signature`
privateKeys[0]).execute(client);
TransactionReceipt txScheduleReceipt = transferToSchedule.getReceipt(client);
System.out.println("Schedule status: " + txScheduleReceipt.status);
ScheduleId scheduleId = Objects.requireNonNull(txScheduleReceipt.scheduleId);
System.out.println("Schedule ID: " + scheduleId);
TransactionId scheduledTxId = Objects.requireNonNull(txScheduleReceipt.scheduledTransactionId);
System.out.println("Scheduled tx ID: " + scheduledTxId);
// add 2 signature
TransactionResponse txScheduleSign1 = new ScheduleSignTransaction().setScheduleId(scheduleId).freezeWith(client).sign(privateKeys[1]).execute(client);
TransactionReceipt txScheduleSign1Receipt = txScheduleSign1.getReceipt(client);
System.out.println("1. ScheduleSignTransaction status: " + txScheduleSign1Receipt.status);
// add 3 signature
TransactionResponse txScheduleSign2 = new ScheduleSignTransaction().setScheduleId(scheduleId).freezeWith(client).sign(privateKeys[2]).execute(client);
TransactionReceipt txScheduleSign2Receipt = txScheduleSign2.getReceipt(client);
System.out.println("2. ScheduleSignTransaction status: " + txScheduleSign2Receipt.status);
// query schedule
ScheduleInfo scheduleInfo = new ScheduleInfoQuery().setScheduleId(scheduleId).execute(client);
System.out.println(scheduleInfo);
// query triggered scheduled tx
TransactionRecord recordScheduledTx = new TransactionRecordQuery().setTransactionId(scheduledTxId).execute(client);
System.out.println(recordScheduledTx);
}
use of com.hedera.hashgraph.sdk.AccountBalance in project hedera-sdk-java by hashgraph.
the class ScheduledTransferExample method main.
public static void main(String[] args) throws TimeoutException, PrecheckStatusException, ReceiptStatusException {
Client client = Client.forName(HEDERA_NETWORK);
// Defaults the operator account ID and key such that all generated transactions will be paid for
// by this account and be signed by this key
client.setOperator(OPERATOR_ID, OPERATOR_KEY);
Objects.requireNonNull(client.getOperatorAccountId());
/*
* A scheduled transaction is a transaction that has been proposed by an account,
* but which requires more signatures before it will actually execute on the Hedera network.
*
* For example, if Alice wants to transfer an amount of Hbar to Bob, and Bob has
* receiverSignatureRequired set to true, then that transaction must be signed by
* both Alice and Bob before the transaction will be executed.
*
* To solve this problem, Alice can propose the transaction by creating a scheduled
* transaction on the Hedera network which, if executed, would transfer Hbar from
* Alice to Bob. That scheduled transaction will have a ScheduleId by which we can
* refer to that scheduled transaction. Alice can communicate the ScheduleId to Bob, and
* then Bob can use a ScheduleSignTransaction to sign that scheduled transaction.
*
* Bob has a 30 minute window in which to sign the scheduled transaction, starting at the
* moment that Alice creates the scheduled transaction. If a scheduled transaction
* is not signed by all of the necessary signatories within the 30 minute window,
* that scheduled transaction will expire, and will not be executed.
*
* Once a scheduled transaction has all of the signatures necessary to execute, it will
* be executed on the Hedera network automatically. If you create a scheduled transaction
* on the Hedera network, but that transaction only requires your signature in order to
* execute and no one else's, that scheduled transaction will be automatically
* executed immediately.
*/
PrivateKey bobsKey = PrivateKey.generateED25519();
AccountId bobsId = new AccountCreateTransaction().setReceiverSignatureRequired(true).setKey(bobsKey).setInitialBalance(new Hbar(10)).freezeWith(client).sign(bobsKey).execute(client).getReceipt(client).accountId;
Objects.requireNonNull(bobsId);
System.out.println("Alice's ID: " + client.getOperatorAccountId().toStringWithChecksum(client));
System.out.println("Bob's ID: " + bobsId.toStringWithChecksum(client));
AccountBalance bobsInitialBalance = new AccountBalanceQuery().setAccountId(bobsId).execute(client);
System.out.println("Bob's initial balance:");
System.out.println(bobsInitialBalance);
TransferTransaction transferToSchedule = new TransferTransaction().addHbarTransfer(client.getOperatorAccountId(), new Hbar(-10)).addHbarTransfer(bobsId, new Hbar(10));
System.out.println("Transfer to be scheduled:");
System.out.println(transferToSchedule);
/*
* The payerAccountId is the account that will be charged the fee
* for executing the scheduled transaction if/when it is executed.
* That fee is separate from the fee that we will pay to execute the
* ScheduleCreateTransaction itself.
*
* To clarify: Alice pays a fee to execute the ScheduleCreateTransaction,
* which creates the scheduled transaction on the Hedera network.
* She specifies when creating the scheduled transaction that Bob will pay
* the fee for the scheduled transaction when it is executed.
*
* If payerAccountId is not specified, the account who creates the scheduled transaction
* will be charged for executing the scheduled transaction.
*/
ScheduleId scheduleId = new ScheduleCreateTransaction().setScheduledTransaction(transferToSchedule).setPayerAccountId(bobsId).execute(client).getReceipt(client).scheduleId;
Objects.requireNonNull(scheduleId);
System.out.println("The scheduleId is: " + scheduleId.toStringWithChecksum(client));
/*
* Bob's balance should be unchanged. The transfer has been scheduled, but it hasn't been executed yet
* because it requires Bob's signature.
*/
AccountBalance bobsBalanceAfterSchedule = new AccountBalanceQuery().setAccountId(bobsId).execute(client);
System.out.println("Bob's balance after scheduling the transfer (should be unchanged):");
System.out.println(bobsBalanceAfterSchedule);
/*
* Once Alice has communicated the scheduleId to Bob, Bob can query for information about the
* scheduled transaction.
*/
ScheduleInfo scheduledTransactionInfo = new ScheduleInfoQuery().setScheduleId(scheduleId).execute(client);
System.out.println("Info about scheduled transaction:");
System.out.println(scheduledTransactionInfo);
/*
* getScheduledTransaction() will return an SDK Transaction object identical to the transaction
* that was scheduled, which Bob can then inspect like a normal transaction.
*/
Transaction<?> scheduledTransaction = scheduledTransactionInfo.getScheduledTransaction();
// We happen to know that this transaction is (or certainly ought to be) a TransferTransaction
if (scheduledTransaction instanceof TransferTransaction) {
TransferTransaction scheduledTransfer = (TransferTransaction) scheduledTransaction;
System.out.println("The scheduled transfer transaction from Bob's POV:");
System.out.println(scheduledTransfer);
} else {
System.out.println("The scheduled transaction was not a transfer transaction.");
System.out.println("Something has gone horribly wrong. Crashing...");
System.exit(-1);
}
new ScheduleSignTransaction().setScheduleId(scheduleId).freezeWith(client).sign(bobsKey).execute(client).getReceipt(client);
AccountBalance balanceAfterSigning = new AccountBalanceQuery().setAccountId(bobsId).execute(client);
System.out.println("Bob's balance after signing the scheduled transaction:");
System.out.println(balanceAfterSigning);
ScheduleInfo postTransactionInfo = new ScheduleInfoQuery().setScheduleId(scheduleId).execute(client);
System.out.println("Info on the scheduled transaction, executedAt should no longer be null:");
System.out.println(postTransactionInfo);
// Clean up
new AccountDeleteTransaction().setTransferAccountId(client.getOperatorAccountId()).setAccountId(bobsId).freezeWith(client).sign(bobsKey).execute(client).getReceipt(client);
client.close();
}
use of com.hedera.hashgraph.sdk.AccountBalance in project hedera-sdk-java by hashgraph.
the class ValidateChecksumExample method main.
public static void main(String[] args) throws TimeoutException, PrecheckStatusException {
Client client = Client.forName(HEDERA_NETWORK);
// Defaults the operator account ID and key such that all generated transactions will be paid for
// by this account and be signed by this key
client.setOperator(OPERATOR_ID, OPERATOR_KEY);
/*
* Entity IDs, such as TokenId and AccountId, can be constructed from strings.
* For example, the AccountId.fromString(inputString) static method will attempt to parse
* the input string and construct the expected AccountId object, and will throw an
* IllegalArgumentException if the string is incorrectly formatted.
*
* From here on, we'll talk about methods on accountId, but equivalent methods exist
* on every entity ID type.
*
* fromString() expects the input to look something like this: "1.2.3-asdfg".
* Here, 1 is the shard, 2 is the realm, 3 is the number, and "asdfg" is the checksum.
*
* The checksum can be used to ensure that an entity ID was inputted correctly.
* For example, if the string being parsed is from a config file, or from user input,
* it could contain typos.
*
* You can use accountId.getChecksum() to get the checksum of an accountId object that was constructed
* using fromString(). This will be the checksum from the input string. fromString() will merely
* parse the string and create an AccountId object with the expected shard, realm, num, and checksum
* values. fromString() will NOT verify that the AccountId maps to a valid account on the Hedera
* network, and it will not verify the checksum.
*
* To verify a checksum, call accountId.validateChecksum(client). If the checksum
* is invalid, validateChecksum() will throw a BadEntityIdException, otherwise it will return normally.
*
* The validity of a checksum depends on which network the client is connected to (EG mainnet or
* testnet or previewnet). For example, a checksum that is valid for a particular shard/realm/num
* on mainnet will be INVALID for the same shard/realm/num on testnet.
*
* As far as fromString() is concerned, the checksum is optional.
* If you use fromString() to generate an AccountId from a string that does not include a checksum,
* such as "1.2.3", fromString() will work, but a call to the getChecksum() method on the resulting
* AccountId object will return null.
*
* Generally speaking, AccountId objects can come from three places:
* 1) AccountId.fromString(inString)
* 2) new AccountId(shard, realm, num)
* 3) From the result of a query
*
* In the first case, the AccountId object will have a checksum (getChecksum() will not return null) if
* the input string included a checksum, and it will not have a checksum if the string did not
* include a checksum.
*
* In the second and third cases, the AccountId object will not have a checksum.
*
* If you call accountId.validateChecksum(client) and accountId has no checksum to validate,
* validateChecksum() will silently pass, and will not throw an exception.
*
* accountId.toString() will stringify the account ID with no checksum,
* accountId.toStringWithChecksum(client) will stringify the account ID with the correct checksum
* for that shard/realm/num on the client's network.
*/
System.out.println("An example of manual checksum validation:");
while (true) {
try {
System.out.print("Enter an account ID with checksum: ");
String inString = INPUT_SCANNER.nextLine();
// Throws IllegalArgumentException if incorrectly formatted
AccountId id = AccountId.fromString(inString);
System.out.println("The ID with no checksum is " + id.toString());
System.out.println("The ID with the correct checksum is " + id.toStringWithChecksum(client));
if (id.getChecksum() == null) {
System.out.println("You must enter a checksum.");
continue;
}
System.out.println("The checksum entered was " + id.getChecksum());
// Throws BadEntityIdException if checksum is incorrect
id.validateChecksum(client);
AccountBalance balance = new AccountBalanceQuery().setAccountId(id).execute(client);
System.out.println(balance);
// exit the loop
break;
} catch (IllegalArgumentException exc) {
System.out.println(exc.getMessage());
} catch (BadEntityIdException exc) {
System.out.println(exc.getMessage());
System.out.println("You entered " + exc.shard + "." + exc.realm + "." + exc.num + "-" + exc.presentChecksum + ", the expected checksum was " + exc.expectedChecksum);
}
}
/*
* It is also possible to perform automatic checksum validation.
*
* Automatic checksum validation is disabled by default, but it can be enabled with
* client.setAutoValidateChecksums(true). You can check whether automatic checksum
* validation is enabled with client.isAutoValidateChecksumsEnabled().
*
* When this feature is enabled, the execute() method of a transaction or query
* will automatically check the validity of checksums on any IDs in the
* transaction or query. It will throw an IllegalArgumentException if an
* invalid checksum is encountered.
*/
System.out.println("An example of automatic checksum validation:");
client.setAutoValidateChecksums(true);
while (true) {
try {
System.out.print("Enter an account ID with checksum: ");
AccountId id = AccountId.fromString(INPUT_SCANNER.nextLine());
if (id.getChecksum() == null) {
System.out.println("You must enter a checksum.");
continue;
}
AccountBalance balance = new AccountBalanceQuery().setAccountId(id).execute(client);
System.out.println(balance);
// exit the loop
break;
} catch (IllegalArgumentException exc) {
System.out.println(exc.getMessage());
}
}
System.out.println("Example complete!");
client.close();
}
use of com.hedera.hashgraph.sdk.AccountBalance in project hedera-sdk-java by hashgraph.
the class AccountAliasExample method main.
public static void main(String[] args) throws TimeoutException, PrecheckStatusException, ReceiptStatusException {
Client client = Client.forName(HEDERA_NETWORK);
// Defaults the operator account ID and key such that all generated transactions will be paid for
// by this account and be signed by this key
client.setOperator(OPERATOR_ID, OPERATOR_KEY);
/*
* Hedera supports a form of lazy account creation.
*
* You can "create" an account by generating a private key, and then deriving the public key,
* without any need to interact with the Hedera network. The public key more or less acts as the user's
* account ID. This public key is an account's aliasKey: a public key that aliases (or will eventually alias)
* to a Hedera account.
*
* An AccountId takes one of two forms: a normal AccountId with a null aliasKey member takes the form 0.0.123,
* while an account ID with a non-null aliasKey member takes the form
* 0.0.302a300506032b6570032100114e6abc371b82dab5c15ea149f02d34a012087b163516dd70f44acafabf7777
* Note the prefix of "0.0." indicating the shard and realm. Also note that the aliasKey is stringified
* as a hex-encoded ASN1 DER representation of the key.
*
* An AccountId with an aliasKey can be used just like a normal AccountId for the purposes of queries and
* transactions, however most queries and transactions involving such an AccountId won't work until Hbar has
* been transferred to the aliasKey account.
*
* There is no record in the Hedera network of an account associated with a given aliasKey
* until an amount of Hbar is transferred to the account. The moment that Hbar is transferred to that aliasKey
* AccountId is the moment that that account actually begins to exist in the Hedera ledger.
*/
System.out.println("\"Creating\" a new account");
PrivateKey privateKey = PrivateKey.generateED25519();
PublicKey publicKey = privateKey.getPublicKey();
// Assuming that the target shard and realm are known.
// For now they are virtually always 0 and 0.
AccountId aliasAccountId = publicKey.toAccountId(0, 0);
System.out.println("New account ID: " + aliasAccountId);
System.out.println("Just the aliasKey: " + aliasAccountId.aliasKey);
/*
* Note that no queries or transactions have taken place yet.
* This account "creation" process is entirely local.
*
* AccountId.fromString() can construct an AccountId with an aliasKey.
* It expects a string of the form 0.0.123 in the case of a normal AccountId, or of the form
* 0.0.302a300506032b6570032100114e6abc371b82dab5c15ea149f02d34a012087b163516dd70f44acafabf7777
* in the case of an AccountId with aliasKey. Note the prefix of "0.0." to indicate the shard and realm.
*
* If the shard and realm are known, you may use PublicKey.fromString().toAccountId() to construct the
* aliasKey AccountId
*/
AccountId fromString = AccountId.fromString("0.0.302a300506032b6570032100114e6abc371b82dab5c15ea149f02d34a012087b163516dd70f44acafabf7777");
AccountId fromKeyString = PublicKey.fromString("302a300506032b6570032100114e6abc371b82dab5c15ea149f02d34a012087b163516dd70f44acafabf7777").toAccountId(0, 0);
System.out.println("Transferring some Hbar to the new account");
new TransferTransaction().addHbarTransfer(OPERATOR_ID, new Hbar(10).negated()).addHbarTransfer(aliasAccountId, new Hbar(10)).execute(client).getReceipt(client);
AccountBalance balance = new AccountBalanceQuery().setAccountId(aliasAccountId).execute(client);
System.out.println("Balances of the new account: " + balance);
AccountInfo info = new AccountInfoQuery().setAccountId(aliasAccountId).execute(client);
System.out.println("Info about the new account: " + info);
/*
* Note that once an account exists in the ledger, it is assigned a normal AccountId, which can be retrieved
* via an AccountInfoQuery.
*
* Users may continue to refer to the account by its aliasKey AccountId, but they may also
* now refer to it by its normal AccountId
*/
System.out.println("The normal account ID: " + info.accountId);
System.out.println("The alias key: " + info.aliasKey);
System.out.println("Example complete!");
client.close();
}
Aggregations