I use below code for sending transaction in MATIC in Matic Mumbai network.
BigInteger gasPrice = client.ethGasPrice().send().getGasPrice();
BigInteger nonce = client.ethGetTransactionCount(credentials.getAddress(),
DefaultBlockParameterName.LATEST).send().getTransactionCount();
RawTransaction rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, GAS_LIMIT, "0x9f58989539B8c90cdDE06Cb568e41e3DeB73df90", new BigInteger("1"));
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, 80001l, credentials);
String hexValue = Numeric.toHexString(signedMessage);
EthSendTransaction response = client.ethSendRawTransaction(hexValue).sendAsync().get();
At https://mumbai.polygonscan.com/ I see that transaction was performed in wei. But wallet currency is MATIC.
How can I select currency in transaction using web3j. Thanks
Related
I am executing functions of a smart contract through web3j using the following code :
Credentials creds = getCredentialsFromPrivateKey("private-key");
RawTransactionManager manager = new RawTransactionManager(web3j, creds);
String contractAddress = "0x1278f8c858d799fe1010cfc0d1eeb56508243a4d";
BigInteger sum = new BigInteger("10000000000"); // amount you want to send
String data = encodeTransferData(sum);
BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();
BigInteger gasLimit = BigInteger.valueOf(120000); // set gas limit here
EthSendTransaction transaction = manager.sendTransaction(gasPrice, gasLimit, contractAddress, data, null);
System.out.println(transaction.getTransactionHash());
It executes fine and the function is run, however i don't know how to read the output given by the contract, how can i read that output ?
this will return the hex value of the function call
private static List<Type> executeCall(Function function) throws IOException {
String encodedFunction = FunctionEncoder.encode(function);
org.web3j.protocol.core.methods.response.EthCall ethCall = web3j.ethCall(
Transaction.createEthCallTransaction(
"0x753ebAf6F6D5C2e3E6D469DEc5694Cd3Aa1A0c21", "0x47480bac30de77cd030b8a8dad2d6a2ecdb7f27a", encodedFunction),
DefaultBlockParameterName.LATEST)
.send();
String value = ethCall.getValue();
System.out.println(value);
System.out.println(FunctionReturnDecoder.decode(value, function.getOutputParameters()));
return FunctionReturnDecoder.decode(value, function.getOutputParameters());
}
Ethereum transaction hash is the unique id of the transaction. With this transaction hash, you can query the transaction status from the network.
The underlying JSON-RPC call is called eth_getTransactionReceipt. Here is Web3.js documentation.
If your smart contract emits events, you can also read those.
I’m using Hyperledger Fabric Java SDK to get a transaction by txId. The return object includes Transaction Information.
TransactionInfo txInfo = channel.queryTransactionByID(txId);
Common.Envelope envelope = txInfo.getEnvelope();
Common.Payload payload = Common.Payload.parseFrom(envelope.getPayload());
The Payload message includes headers and data. I can parse headers by using Common.Header.ChannelHeader and Common.Header.SignatureHeader.
Common.ChannelHeader channelHeader = Common.ChannelHeader.parseFrom(payload.getHeader().getChannelHeader());
Common.SignatureHeader signatureHeader = Common.SignatureHeader.parseFrom(payload.getHeader().getSignatureHeader());
The problem is, I cannot see any message type to get data from Payload.
My expectation would be like,
SomeMessage someMsg = SomeMessage.parseFrom(payload.getData());
What is the ideal approach to get a data object?
Thanks to Driden Myung's tip, Finally found a way to parse QSCC responses into TxReadWriteSet or even KVRWSet !!
Here is an example:
TransactionInfo txInfo = channel.queryTransactionByID(txId);
Common.Envelope envelope = txInfo.getEnvelope();
Common.Payload payload = Common.Payload.parseFrom(envelope.getPayload());
FabricTransaction.Transaction transaction = FabricTransaction.Transaction.parseFrom(payload.getData());
FabricTransaction.TransactionAction action = transaction.getActionsList().get(0); // 0 is a index
FabricTransaction.ChaincodeActionPayload chaincodeActionPayload = FabricTransaction.ChaincodeActionPayload.parseFrom(action.getPayload());
FabricProposalResponse.ProposalResponsePayload prp = FabricProposalResponse.ProposalResponsePayload.parseFrom(chaincodeActionPayload.getAction().getProposalResponsePayload());
FabricProposal.ChaincodeAction ca = FabricProposal.ChaincodeAction.parseFrom(prp.getExtension());
Rwset.TxReadWriteSet txrws = Rwset.TxReadWriteSet.parseFrom(ca.getResults());
TxReadWriteSetInfo txrwsInfo = new TxReadWriteSetInfo(txrws);
KvRwset.KVRWSet kvrwSet = txrwsInfo.getNsRwsetInfo(0).getRwset();
KvRwset.KVWrite kvWrite = kvrwSet.getWrites(0);
String writeVal = kvWrite.getValue().toStringUtf8();
I found the answer.
FabricTransaction.Transaction transaction = FabricTransaction.Transaction.parseFrom(payload.getData());
After that,
FabricTransaction.TransactionAction action = transaction.getActionsList().get(index);
FabricTransaction.ChaincodeActionPayload chaincodeActionPayload = FabricTransaction.ChaincodeActionPayload.parseFrom(action.getPayload());
chaincodeActionPayload.getAction().getEndorsementsList().forEach(endorsement -> {
// This is my current point
???? endorser = ????.parseFrom(endorsement.getEndorser());
});
Let me add if I can find more. Anybody add comments welcome.
We have faced a similar problem to get the request data from a transaction.
The following code will help to get the transaction request data of a transaction
Fabric SDK version : 2.1.4
// get transaction from transaction ID
TransactionInfo txInfo = channel.queryTransactionByID(txId);
// transaction is stored inside the envelope containing the payload and signature
Common.Envelope envelope = txInfo.getEnvelope();
// parse payload from the envelope
Common.Payload payload = Common.Payload.parseFrom(envelope.getPayload());
// payload contains Header and Data. We are parsing data to get the transaction
TransactionPackage.Transaction transaction = TransactionPackage.Transaction.parseFrom(payload.getData());
// get first action from the transaction action list. it contains input and other details
TransactionPackage.TransactionAction action = transaction.getActionsList().get(0); // 0 is a index
// chaincode action payload contains input parameters. So we are taking the action payload
TransactionPackage.ChaincodeActionPayload chaincodeActionPayload = TransactionPackage.ChaincodeActionPayload.parseFrom(action.getPayload());
// chaincode ProposalPayload contains Input and TransientMap. We are parsing actionPayload to proposalPayload
ProposalPackage.ChaincodeProposalPayload prp = ProposalPackage.ChaincodeProposalPayload.parseFrom(chaincodeActionPayload.getChaincodeProposalPayload());
// parse the input to chaincodeInvocationSpec so that we can unmarshal the input
Chaincode.ChaincodeInvocationSpec chaincodeInvocationSpec = Chaincode.ChaincodeInvocationSpec.parseFrom(prp.getInput());
// get the input and parse the arg list and get input arguments
chaincodeInvocationSpec.getChaincodeSpec().getInput().getArgsList().get(ChaincodeInput.ARGS_FIELD_NUMBER).toStringUtf8();
I am creating a wallet from mnemonics,for ethereum i have used web3j library for generating mnemonics,address and its private key and now for bitcoin i want to use the same generated mnemonics to generate bitcoin address and its private key for bitcoin i am using Bitcoinj library but not able to get its address and key.
I also tried Walletappkit but its generating address without getting mnemonics so is there any way of using mnemonics in Walletappkit so i can get bitcoin address and sync the bitcoin chain for transactions.
Also is there any way of using walletappkit without syncing and gets bitcoin detail like its balance and transaction info.
Below is the code how I created ethereum wallet and its mnemonic key using web3j and bitcoinj.
val wallet = WalletUtils.generateBip39Wallet("", File(path))
val mnemonics = wallet.mnemonic
// bitcoinj
var seed = DeterministicSeed(wallet.mnemonic, null, "", 1409478661L)
val chain = DeterministicKeyChain.builder().seed(seed).build()
val keyPath = HDUtils.parsePath("M/44H/60H/0H/0/0")
val key = chain.getKeyByPath(keyPath, true)
val privKey = key.privKey
// Web3j
val credentials = Credentials.create(privKey.toString(16))
val eth_address = credentials.address
I'm not sure if I correctly understand what you want to do, but if you want to restore/create a Bitcoinj wallet from a mnemonic seed, then there's an official example for this here:
// Here we restore our wallet from a seed with no passphrase. Also have a look at the BackupToMnemonicSeed.java example that shows how to backup a wallet by creating a mnemonic sentence.
String seedCode = "yard impulse luxury drive today throw farm pepper survey wreck glass federal";
String passphrase = "";
Long creationtime = 1409478661L;
DeterministicSeed seed = new DeterministicSeed(seedCode, null, passphrase, creationtime);
// The wallet class provides a easy fromSeed() function that loads a new wallet from a given seed.
Wallet wallet = Wallet.fromSeed(params, seed, Script.ScriptType.P2PKH);
you can use bitcore.js for generating mnemonics. I am sharing the link of npm package please have a look.
var Mnemonic = require('bitcore-mnemonic');
var code = new Mnemonic(Mnemonic.Words.SPANISH);
code.toString();
var xpriv = code.toHDPrivateKey();
I have a confusion with Braintree. When a customer orders certain item on site, he makes a charge on BT with his credit card and I need to check this payment via Java client. I found the following code:
Transaction transaction = gateway.transaction().find("the_transaction_id");
But I need to search by orderId, a special ID that my system issues on every order event. How to do that in BT with Java API?
Although you may be able to persist the orderId on the Braintree side, I don't readily see a way to perform a lookup on it directly.
Here's how we handle it:
Persist your orderId with the transaction ID that you get back from Braintree. When you need to do your check, look up your table using the orderId, find the transactionId, and call the same find() method to find the payment.
I'd imagine you'd do something like:
//some paymentService
public Result<Transaction> sale(BigDecimal amount,
String nonce,
String firstName,
String lastName,
String postalCode) {
TransactionRequest request = new TransactionRequest()
.customer()
.firstName(firstName)
.lastName(lastName)
.done()
.billingAddress()
.firstName(firstName)
.lastName(lastName)
.postalCode(postalCode)
.done()
.type(Type.SALE)
.amount(amount)
.paymentMethodNonce(nonce)
.options()
.submitForSettlement(true)
.done();
return gateway.transaction().sale(request);
}
//and then...
Result<Transaction> result = paymentService.sale(amount, nonce, firstName, lastName, postalCode);
if (result.isSuccess()) {
Transaction transaction = result.getTarget();
String transactionId = transaction.getId(); //persist this ID and your orderId together in your DB
...
}
//when you need to find payment details, it'd be like:
Order order = someService.find(orderId);
PaymentHistory paymentHistory = order.getPaymentHistory();
String transactionId = paymentHistory.getTransactionId();
Transaction transaction = gateway.transaction().find(transactionId);
From the url
https://javamail.java.net/nonav/docs/api/com/sun/mail/pop3/package-summary.html,
You can also pre-fetch all the UIDs for all messages like this:
FetchProfile fp = new FetchProfile();
fp.add(UIDFolder.FetchProfileItem.UID);
folder.fetch(folder.getMessages(), fp);
Then use the technique above to get the UID for each message. This is similar to the technique used with the UIDFolder interface supported by IMAP, but note that POP3 UIDs are strings, not integers like IMAP UIDs. See the POP3 spec for details.
From this, https://www.ietf.org/rfc/rfc1939.txt,
In number 7, there's an example of what I need.
Examples:
S: +OK POP3 server ready <1896.697170952#dbc.mtview.ca.us>
C: APOP mrose c4c9334bac560ecc979e58001b3e22fb
S: +OK maildrop has 1 message (369 octets)
In this example, the shared secret is the string `tan-
staaf'. Hence, the MD5 algorithm is applied to the string
<1896.697170952#dbc.mtview.ca.us>tanstaaf
which produces a digest value of
c4c9334bac560ecc979e58001b3e22fb //this is what we need in Java
After this, how do we get the MessageID / UID of each message?
Sample Message ID that I need. A fuego.mail Library that was deprecated was providing us this before:
<F855F5879C6E754E9DE37F2E7D0762327C942B43#GADC-EMB099.ap.abc.com>
UPDATE
I got a 3 digit integer i.e. 561 when using this
Store store = emailSession.getStore(MAILSTORETYPE);
store.connect(HOST, USERNAME, PASSWORD);
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
FetchProfile fp = new FetchProfile();
fp.add(UIDFolder.FetchProfileItem.UID);
emailFolder.fetch(emailFolder.getMessages(), fp);
POP3Folder pf =(POP3Folder)emailFolder;
Message[] messages = emailFolder.getMessages();
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
String uid = pf.getUID(message);
System.out.println(uid);