GithubHelp home page GithubHelp logo

caver-java's Introduction

No Maintenance Intended

NO LONGER MAINTAINED

Since the launch of Kaia Blockchain this repository has been parked in favour of the new open-source projects in Kaia's Github. Contributors have now moved there continuing with massive open-source contributions to our blockchain ecosystem. Please visit the new repository at kaia/caver-java to continue contributing and to access the latest updates. A big thank you to everyone who has contributed to this repository. For more information about Klaytn's chain merge with Finschia blockchain please refer to the launching of Kaia blockchain - kaia.io.


CircleCI Gitter

caver-java: Caver Java Klaytn Dapp API

caver-java is a lightweight, high modular, convenient Java and Android library to interact with clients (nodes) on the Klaytn network: This library is an interface which allows Java applications to easily communicate with Klaytn network.

Features

  • Complete implementation of Klaytn’s JSON-RPC client API over HTTP and IPC
  • Support of Klaytn transaction, account, and account key types
  • Auto-generation of Java smart contract wrapper to deploy and execute a smart contract from native Java code
  • Creation of a new wallet and managing Klaytn wallets
  • Command line tools
  • Android compatible

Getting started

Installation

add a Repository

To install caver-java, you should add a jitpack repository for IPFS feature.

maven

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

gradle

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

add a dependency

maven

<dependency>
    <groupId>com.klaytn.caver</groupId>
    <artifactId>core</artifactId>
    <version>X.X.X</version>
</dependency>

gradle

compile 'com.klaytn.caver:core:X.X.X'

If you want to use Android dependency, just append -android at the end of version. (e.g. 1.5.4-android)

You can find latest caver-java version at release page.

Start a Client

If you want to run your own EN (Endpoint Node), see EN Operation Guide to set up.

Caver caver = new Caver(Caver.DEFAULT_URL);

Transactions

When you send transactions, caver-java provides easy-to-use wrapper classes.

Here's an example of transferring KLAY using keystore.json and ValueTransfer class:

Caver caver = new Caver(Caver.DEFAULT_URL);

//Read keystore json file.
File file = new File("./keystore.json");

//Decrypt keystore.
ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
KeyStore keyStore = objectMapper.readValue(file, KeyStore.class);
AbstractKeyring keyring = KeyringFactory.decrypt(keyStore, "password");

//Add to caver wallet.
caver.wallet.add(keyring);

BigInteger value = new BigInteger(Utils.convertToPeb(BigDecimal.ONE, "KLAY"));

//Create a value transfer transaction
ValueTransfer valueTransfer = new ValueTransfer.Builder()
        .setKlaytnCall(caver.rpc.getKlay())
        .setFrom(keyring.getAddress())
        .setTo("0x8084fed6b1847448c24692470fc3b2ed87f9eb47")
        .setValue(value)
        .setGas(BigInteger.valueOf(25000))
        .build();

//Sign to the transaction
valueTransfer.sign(keyring);

//Send a transaction to the klaytn blockchain platform (Klaytn)
Bytes32 result = caver.rpc.klay.sendRawTransaction(valueTransfer.getRawTransaction()).send();
if(result.hasError()) {
    throw new RuntimeException(result.getError().getMessage());
}

//Check transaction receipt.
TransactionReceiptProcessor transactionReceiptProcessor = new PollingTransactionReceiptProcessor(caver, 1000, 15);
TransactionReceipt.TransactionReceiptData transactionReceipt = transactionReceiptProcessor.waitForTransactionReceipt(result.getResult());

If you have address and private key(s) of keyring, you can make keyring directly through KeyringFactory.create.

<valueUnit> means a unit of value that is used in Klaytn. It is defined as an enum type. Examples of possible values are as below.

PEB, KPEB, MPEB, GPEB, STON, UKLAY, MKLAY, KLAY, KKLAY, MKLAY, GKLAY

If <valueUnit> is not given as a parameter, default unit of <value> is PEB. You can use Utils.convertToPeb or Utils.convertFromPeb to easily convert a value to another unit like below.

Utils.convertToPeb("1", KLAY).toBigInteger();  // 1000000000000000000
Utils.convertFromPeb("1000000000000000000", KLAY).toBigInteger();  // 1

Fee Delegation

Klaytn provides Fee Delegation feature. Here's an example code. When you are a sender:

Caver caver = new Caver(Caver.DEFAULT_URL);
SingleKeyring senderKeyring = KeyringFactory.createFromPrivateKey("0x{privateKey}");
caver.wallet.add(senderKeyring);

FeeDelegatedValueTransfer feeDelegatedValueTransfer = new FeeDelegatedValueTransfer.Builder()
        .setKlaytnCall(caver.rpc.klay)
        .setFrom(senderKeyring.getAddress())
        .setTo("0x176ff0344de49c04be577a3512b6991507647f72")
        .setValue(BigInteger.valueOf(1))
        .setGas(BigInteger.valueOf(30000))
        .build();

caver.wallet.sign(senderKeyring.getAddress(), feeDelegatedValueTransfer);
String rlpEncoded = feeDelegatedValueTransfer.getRLPEncoding();
System.out.println(rlpEncoded);

After signing a transaction, the sender can get the RLP-encoded string through feeDelegatedValueTransfer.getRLPEncoding(). Then, the sender sends the transaction to the fee payer who will pay for the transaction fee instead.

When you are a fee payer:

Caver caver = new Caver(Caver.DEFAULT_URL);

SingleKeyring feePayerKeyring = KeyringFactory.createFromPrivateKey("0x{privateKey}");
caver.wallet.add(feePayerKeyring);

String rlpEncoded = "0x{RLP-encoded string}"; // The result of feeDelegatedValueTransfer.getRLPEncoding() in above example
FeeDelegatedValueTransfer feeDelegatedValueTransfer = FeeDelegatedValueTransfer.decode(rlpEncoded);
feeDelegatedValueTransfer.setFeePayer(feePayerKeyring.getAddress());

caver.wallet.signAsFeePayer(feePayerKeyring.getAddress(), feeDelegatedValueTransfer);

TransactionReceiptProcessor receiptProcessor = new PollingTransactionReceiptProcessor(caver, 1000, 15);

String rlpEncoded = feeDelegatedValueTransfer.getRLPEncoding();

try {
  // Send the transaction using `caver.rpc.klay.sendRawTransaction`.
  Bytes32 sendResult = caver.rpc.klay.sendRawTransaction(rlpEncoding).send();
  if(sendResult.hasError()) {
    //do something to handle error

  }

  String txHash = sendResult.getResult();
  TransactionReceipt.TransactionReceiptData receiptData = receiptProcessor.waitForTransactionReceipt(txHash);
} catch (IOException | TransactionException e) {
  // do something to handle exception.
}

After the fee payer gets the transaction from the sender, the fee payer can sign with signAsFeePayer. For more information about Klaytn transaction types, visit Transactions.

Klaytn Accounts

An account in Klaytn is a data structure containing information about a person's balance or a smart contract. If you require further information about Klaytn accounts, you can refer to the Accounts.

Account Key

An account key represents the key structure associated with an account. Each account key has its own unique role. To get more details about the Klaytn account key, please read Account Key. These are 6 types of Account Keys in Klaytn:

  • AccountKeyNil
  • AccountKeyLegacy
  • AccountKeyPublic
  • AccountKeyFail
  • AccountKeyWeightedMultiSig
  • AccountKeyRoleBased

If you want to update the key of the given account, follow below steps :

  1. Create new private key(s) to use
  2. Create a keyring instance using the new private key(s) and the account address to update. After the AccountKey has been successfully updated in Klaytn, you can use the Keyring instance created here.
  3. To update the AccountKey of Klaytn Account, create an Account instance using the toAccount function.
  4. Create an AccountUpdate transaction (AccountUpdate/FeeDelegatedAccountUpdate/FeeDelegatedAccountUpdateWithRatio).
  5. Sign the AccountUpdate transaction
  6. Send signed transaction through caver.rpc.klay.sendRawTransaction
Caver caver = new Caver(Caver.BAOBAB_URL);
SingleKeyring senderKeyring = KeyringFactory.createFromPrivateKey("0x{privateKey}");
caver.wallet.add(senderKeyring);

String newPrivateKey = KeyringFactory.generateSingleKey();
SingleKeyring newKeyring = KeyringFactory.createFromPrivateKey(newPrivateKey);

Account account = newKeyring.toAccount();

AccountUpdate accountUpdate = new AccountUpdate.Builder()
        .setKlaytnCall(caver.rpc.klay)
        .setFrom(senderKeyring.getAddress())
        .setAccount(account)
        .setGas(BigInteger.valueOf(50000))
        .build();

try {
    caver.wallet.sign(senderKeyring.getAddress(), accountUpdate);
    String rlpEncoded = accountUpdate.getRLPEncoding();

    Bytes32 sendResult = caver.rpc.klay.sendRawTransaction(rlpEncoded).send();
    if(sendResult.hasError()) {
        //do something to handle error
    }

    String txHash = sendResult.getResult();

    TransactionReceiptProcessor receiptProcessor = new PollingTransactionReceiptProcessor(caver, 1000, 15);
    TransactionReceipt.TransactionReceiptData receiptData = receiptProcessor.waitForTransactionReceipt(txHash);
} catch (IOException | TransactionException e) {
    // do something to handle exception.
}

senderKeyring = caver.wallet.updateKeyring(newKeyring);

Manage Contracts using Java Smart Contract Wrappers

Caver supports Contract class to make it easy to interact with smart contract in Klaytn. Before generating a wrapper code, you need to compile the smart contract first (Note: This will only work if solidity compiler is installed in your computer).

$ solc --abi --bin ./test.sol

You can create a contract instance as below using the result of compiling the smart contract:

Caver caver = new Caver(Caver.DEFAULT_URL);
try {
    Contract contract = new Contract(caver, ABI);
    contract.getMethods().forEach((methodName, contractMethod) -> {
        System.out.println("methodName : " + methodName + ", ContractMethod : " + contractMethod);
    });
    System.out.println("ContractAddress : " + contract.getContractAddress());
} catch (IOException e) {
    //handle exception..
}

If you want to deploy the smart contract at Baobab testnet, you could do like this:

Caver caver = new Caver(Caver.DEFAULT_URL);
SingleKeyring deployer = KeyringFactory.createFromPrivateKey("0x{private key}");
caver.wallet.add(deployer);
try {
    Contract contract = new Contract(caver, ABI);
    ContractDeployParams params = new ContractDeployParams(byteCode, null);
    SendOptions sendOptions = new SendOptions();
    sendOptions.setFrom(deployer.getAddress());
    sendOptions.setGas(BigInteger.valueOf(40000))
    
    Contract newContract = contract.deploy(params, sendOptions);
    System.out.println("Contract address : " + newContract.getContractAddress());
} catch (IOException | TransactionException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
    //handle exception..
}

After the smart contract has been deployed, you can load the smart contract as below:

Caver caver = new Caver(Caver.DEFAULT_URL);
String contractAddress = "0x3466D49256b0982E1f240b64e097FF04f99Ed4b9";
try {
    Contract contract = new Contract(caver, ABI, contractAddress);
    contract.getMethods().forEach((methodName, contractMethod) -> {
        System.out.println("methodName : " + methodName + ", ContractMethod : " + contractMethod);
    });
    System.out.println("ContractAddress : " + contract.getContractAddress());
} catch (IOException e) {
    //handle exception..
}

To transact with a smart contract:

Caver caver = new Caver(Caver.DEFAULT_URL);
SingleKeyring executor = KeyringFactory.createFromPrivateKey("0x{private key}");
caver.wallet.add(executor);
try {
    Contract contract = new Contract(caver, ABI, '0x{address in hex}');
    
    SendOptions sendOptions = new SendOptions();
    sendOptions.setFrom(executor.getAddress());
    sendOptions.setGas(BigInteger.valueOf(40000))
    TransactionReceipt.TransactionReceiptData receipt = contract.getMethod("set").send(Arrays.asList("testValue"), sendOptions);
    } catch (IOException | TransactionException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
    //handle exception..
}

Filters

TBD

Web3j Similarity

We made caver-java as similar as possible to web3j for easy usability.

/* start a client */
Web3j web3 = Web3j.build(new HttpService(<endpoint>)); // Web3j
Caver caver = Caver.build(new HttpService(<endpoint>)); // caver-java

/* get nonce */
BigInteger nonce = web3j.ethGetTransactionCount(<address>, <blockParam>).send().getTransactionCount(); // Web3j
Quantity nonce = caver.klay().getTransactionCount(<address>, <blockParam>).send().getValue(); // caver-java

/* convert unit */
Convert.toWei("1.0", Convert.Unit.ETHER).toBigInteger(); // Web3j
Convert.toPeb("1.0", Convert.Unit.KLAY).toBigInteger(); // caver-java
 
/* generate wallet file */
WalletUtils.generateNewWalletFile(<password>, <filepath>); // Web3j
KlayWalletUtils.generateNewWalletFile(<address>, <password>, <filepath>); // caver-java

/* load credentials */
Credentials credentials = WalletUtils.loadCrendetials(<password>, <filepath>"); // Web3j
KlayCredentials credentials = KlayWalletUtils.loadCredentials(<password>, <filepath>); // caver-java
                                                      
/* Value Transfer */
TransactionReceipt transactionReceipt = Transfer.sendFunds(...),send(); // Web3j
KlayTransactionReceipt.TransactionReceipt transactionReceipt = ValueTransfer.create(...).sendFunds(...).send(); // caver-java

Command-line Tool

A caver-java fat jar is distributed with open repository. The 'caver-java' allows you to generate Solidity smart contract function wrappers from the command line:

  • Generate Solidity smart contract function wrappers Installation
$ brew tap klaytn/klaytn
$ brew install caver-java

After installation you can run command 'caver-java'

$ caver-java solidity generate -b <smart-contract>.bin -a <smart-contract>.abi -o <outputPath> -p <packagePath>

Related projects

caver-js for a javascript

Build instructions

TBD

Snapshot dependencies

TBD

Thanks to

  • The web3j project for the inspiration. 🙂

caver-java's People

Contributors

aeharvlee avatar ayo-klaytn avatar ehnuje avatar iv0rish avatar jaychoi1736 avatar jimni1222 avatar kjeom avatar kjhman21 avatar klaytndev avatar leejh903 avatar neoofklaytn avatar skkwon80 avatar sotatek-hautran3 avatar sunghwanjo avatar whoisxx avatar zacscoding avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

caver-java's Issues

sendRawTransaction

TxTypeLegacyTransaction

{"method":"klay_sendRawTransaction","id":1,"jsonrpc":"2.0","params":["0xf872808504a817c80082ea60a0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff80808207f6a0064267f4913b14fc14ad8837cb9f34d0a64bd8af0197a1c6826b77af2ecd11aba06f54bfc30bc03e5b6d7e0cae1d047ba42ca1b047f148864066e9fe8253241956"]}

{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"rlp: input string too long for common.Address, decoding into (types.Transaction)(types.TxInternalDataSerializer)(types.TxInternalDataLegacy).Recipient"}}

https://api.baobab.klaytn.net:8651/

invalid unit price

This is the parameter
gas price 25000000000
limit 21000
chainId 8217
request

{
"id": "1",
"jsonrpc": "2.0",
"method": "klay_sendRawTransaction",
"params": [
"0x08f885238505d21dba00825208940282c0f32b1816dfdb0ba60059a4f25109a73fc1872386f26fc1000094d73d9aa55abbd6cfbed3e9ad7f8be2f6d83c70dcf847f845824056a087fc7935f42ff1ea908960cb7175a768ccb3f77b219cd913ca8038a9f4deabc2a023d1183bca467003397c7c71f4336de09397c444684d39afe78a01753d3fae5a"
]
}

response:
{
"jsonrpc": "2.0",
"id": "1",
"error": {
"code": -32000,
"message": "invalid unit price"
}
}

RPC:https://api.baobab.klaytn.net:8651/

https://github.com/klaytn/caver-java/issues/142#issuecomment-657300291

https://docs.klaytn.com/bapp/sdk/caver-js/v1.4.1#caution-when-sending-a-transaction-to-klaytn
The document link is invalid

Expose javadoc comments of private fields to the getter and setter method

There are JavaDoc comments on the private fields in the TransactionData type.

https://github.com/klaytn/caver-java/blob/dev/core/src/main/java/com/klaytn/caver/methods/response/Transaction.java#L37

But the official JavaDoc site of caver-java does not show the information: https://javadoc.io/doc/com.klaytn.caver/core/latest/com/klaytn/caver/methods/response/Transaction.TransactionData.html

Also, IDEs like IntelliJ show the document of getter or setter when using the functions in code.
However, it does not show the doc in the private fields.

The comments in the private fields will help programmers significantly.
If we expose the docs more programmer-friendly, many programmers will be happier.

Implementation of KCT (Fungible/Non Fungible token in Klaytn)

Is your request related to a problem? Please describe.
Implementation to easily use Fungible / Non Fungible tokens in Klaytn

Describe the solution you'd like
Implement new classes to handle Fungible / Non Fungible tokens

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

ValueTransfer static method do not have a parameter to put chainId

Describe the bug
When use ValueTransfer model to sendFunds(), It does not have a parameter to put chainId. So, default chainId(Baobab) is put when sending transaction. It has same issue when using static method in SmartContract, Account, Cancel as well.

How to reproduce
Just send transactions using static method in ValueTransfer which does not use Baobab chainId.

Expected behavior
I want to put another chainId.

Attachments
none

Environment (please complete the following information)

  • caver-java v1.0.0
  • macOS Mojave v10.14.5

Additional context
none

caver-java cli generates class using deprecated api

Dependency

  • (gradle) com.klaytn.caver:core:1.9.0
  • (cli) caver-java 1.9.0, manually built.

Q. 1
I generated a java class with caver-java cli.
but with this, creates class with deprecated api (extends SmartContract, KlayCredentials, KlayTransactionReceipt...)
I downloaded caver-java 1.9.0 source code zip from release tab

Q. 2
And deploying contract with generated class is impossible.
It throws NullPointerException.
is this sdk's bug?

java.lang.NullPointerException: Cannot invoke "com.klaytn.caver.Klay.getTransactionCount(String, org.web3j.protocol.core.DefaultBlockParameter)" because the return value of "com.klaytn.caver.Caver.klay()" is null
at com.klaytn.caver.tx.manager.GetNonceProcessor.getNonce(GetNonceProcessor.java:39) ~[core-1.9.0.jar:na]
at com.klaytn.caver.tx.manager.TransactionManager.sign(TransactionManager.java:176) ~[core-1.9.0.jar:na]
at com.klaytn.caver.tx.manager.TransactionManager.executeTransaction(TransactionManager.java:74) ~[core-1.9.0.jar:na]
at com.klaytn.caver.tx.ManagedTransaction.send(ManagedTransaction.java:51) ~[core-1.9.0.jar:na]
at com.klaytn.caver.tx.SmartContract.executeTransaction(SmartContract.java:392) ~[core-1.9.0.jar:na]
at com.klaytn.caver.tx.SmartContract.create(SmartContract.java:422) ~[core-1.9.0.jar:na]
at com.klaytn.caver.tx.SmartContract.deploy(SmartContract.java:451) ~[core-1.9.0.jar:na]
at com.klaytn.caver.tx.SmartContract.lambda$deployRemoteCall$10(SmartContract.java:499) ~[core-1.9.0.jar:na]
at org.web3j.protocol.core.RemoteCall.send(RemoteCall.java:42) ~[core-4.8.8.jar:na]
~~

Implementation of SDK common architecture

Is your request related to a problem? Please describe.
Implement the SDK's common architecture.

Describe the solution you'd like
Implement the SDK's common architecture

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context

  • AccountKey
  • Account
  • Keyring
  • KeyringContainer
  • Transaction
  • TransactionHasher
  • RPC
  • Contract / ABI

Address validation

Describe the bug
KlayWalletUtils.isValidAddress function returns 'true' with less than 20-bytes address.

How to reproduce

String shortAddress =  "0xe3ac552937b4ecc36891d5f37b189f8636e49f";
 assertFalse("longAddress: " + longAddress, KlayWalletUtils.isValidAddress(shortAddress));

Expected behavior
return false

Attachments
If applicable, add data, logs or screenshots to help explain your problem.

Environment (please complete the following information)

  • caver-java v1.3.2
  • macOS/10.15

Additional context
Add any other context about the problem here.

same code, but execute Transaction fail

hello
my project work two env: prod, dev

before I issue this: #134
that is dev env.

yesterday, we publish same code to prod env. but execute Transaction fail.

prod env address:
https://scope.klaytn.com/account/0x506E1da423F51F160E5A7d1e62dF52C2F3F3f0A8?tabId=txList

first. I think, diff is not execute AccountUpdateTransaction.

so, do AccountUpdateTransaction with AccountKeyPublic.

but get below error.

String rawTransaction = "0xf8ac458505d21dba00830186a094a01efa8e7d3014a920f21487d7662db2800d031280b844a9059cbb00000000000000000000000080f4009fb84eb6a151565657fb272bb9f016efb6000000000000000000000000000000000000000000000000000000746a528800824055a0487c471f388d3f6d97f71e393a5790e106a6356defdb664e5849a95b32473deaa026ec7a537a2320e93fc73f0648bd555243cf871613f4b91dc75026c2b99f9f31";

String rawTransaction = "0xf8ac438505d21dba00830186a094a01efa8e7d3014a920f21487d7662db2800d031280b844a9059cbb000000000000000000000000e0711069b41397827fdfc3f31c901018e4301500000000000000000000000000000000000000000000000000000000746a528800824056a0076b0e1ed07104a1517fc0fa327753b49a8e188ca93f7b6cb64f40dba349366ea009e9e1e00255d0b0fd98ce0ee9ddfde129bffc8a45f93a45d49322efb5d0f1f7";

String rawTransaction = "0xf8ac458505d21dba00830186a094a01efa8e7d3014a920f21487d7662db2800d031280b844a9059cbb00000000000000000000000080f4009fb84eb6a151565657fb272bb9f016efb6000000000000000000000000000000000000000000000000000000746a528800824055a0487c471f388d3f6d97f71e393a5790e106a6356defdb664e5849a95b32473deaa026ec7a537a2320e93fc73f0648bd555243cf871613f4b91dc75026c2b99f9f31";

return error info:

-32000
a legacy transaction must be with a legacy account key
null

I try do AccountUpdateTransaction with AccountKeyLegacy

execute three rawTransaction, then getTransactionByHash, but get none data.

please help.

Can't import caver-java:core v1.0.1 from Maven Repository

Describe the bug
In maven repository, caver-java:core v1.0.1 does not exist. Other modules(codegen, console) exists.

How to reproduce
Steps to reproduce the behavior:
just import caver-java:core from mavenCentral in 'build.gradle' file.
implementation "com.klaytn.caver:core:1.0.1

Expected behavior
I cannot import caver-java:core module. So caver-java:core dependencies are not added.

Attachments
you can check released caver-java:core version in maven central(https://mvnrepository.com/artifact/com.klaytn.caver/core)

Environment (please complete the following information)

  • caver-java v1.0.1
  • macOS/10.14

Additional context
Bintray, Jcenter has caver-java:core v.1.0.1. So if I import dependencies from Jcenter, It works fine.

Adding a Gitter badge

Is your request related to a problem? Please describe.
There is no Gitter badge

Describe the solution you'd like
Add a Gitter badge

Describe alternatives you've considered
N/A

Additional context
N/A

How to call the contract for transfer

I created a coin myself。
How do I transfer coins to another address。
Best to provide a Java demo。

I am constructing a LegacyTransaction or SmartContractExecution object but I did not find the parameters of the contract address

Failed to deploy/execute SmartContract via SmartContract class

Describe the bug
SmartContract instance create a transaction with the TransactionTransformer when you deploy or run the actual smart contract internally.

Currently gasPrice is fixed at 25Ston with TransactionTransformer.
And TransactionTransformer does not receive gasPrice as a parameter in create function. To set custom gas price, call gasPrice (BigInteger) function separately.

When creating TransactionTransformer in SmartContract, only create function is used.

Therefore, even if you pass the gasProvider as a parameter(when you create SmartContract instance), it uses a fixed 25Ston without using it.

How to reproduce
Use SmartContract to deploy SmartContract to Node whose gas unit price is not 25Ston.

Expected behavior
gasPrice must be set using the value of gasProvider.

Attachments
If applicable, add data, logs or screenshots to help explain your problem.

Environment (please complete the following information)

  • caver-java v1.3.1
  • macOS/10.14

Additional context
Add any other context about the problem here.

Implement new klaynamespace APIs

  • caver.rpc.klay.getHeader
  • caver.rpc.klay.getHeaderByNumber
  • caver.rpc.klay.getHeaderByHash
  • caver.rpc.klay.getFeeHistory
  • caver.rpc.klay.getMaxPriorityPerGas
  • caver.rpc.klay.createAccessList

Subtask of #286
Related PR: #290

cc. @sirano11

Implement of options object for caver.ipfs

Is your request related to a problem? Please describe.
Some IPFS node require their auth.
So our ipfs module also should support a feature for this.

Describe the solution you'd like

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Release caver-java v1.9.0

JSON RPC Layer
Add effectiveGasPrice field to the return object of caver.rpc.klay.getTransactionReceipt

Transaction Layer
Implement tx.getSuggestedGasPrice → Depends on hard fork, returns suggested gas price

Modify optional field setting logic
(Before KIP-71 Hardfork) header.baseFeePerGas == undefined || header.baseFeePerGas =< 0

  • tx.type == EthereumDynamicFeeTx
    • maxPriorityFeePerGas == undefined → set with return value of caver.rpc.klay.getMaxPriorityFeePerGas
    • maxFeePerGas == undefined → set with return value of caver.rpc.klay.getGasPrice
  • tx.type != EthereumDynamicFeeTx
    • gasPrice == undefined → set with return value of caver.rpc.klay.getGasPrice
      (After KIP-71 Hardfork) header.baseFeePerGas != undefined || header.baseFeePerGas > 0
  • tx.type == EthereumDynamicFeeTx
    • maxPriorityFeePerGas == undefined → set with return value of caver.rpc.klay.getMaxPriorityFeePerGas (Klaytn will ignore this)
    • maxFeePerGas → set with baseFee * 2
  • tx.type != EthereumDynamicFeeTx
    • gasPrice == undefined → set with baseFee * 2
  • Modify tx.fillTransaction logic for dynamic base fee → use tx.getSuggestedGasPrice

TxTypeLegacyTransaction

request

{"method":"klay_sendRawTransaction","id":1,"jsonrpc":"2.0","params":["0xf86e808504a817c80082ea6094958e2e083d6a16799e4d588015153ee429508d4f880de0b6b3a7640000808207f5a08638176342e6b99bc93d1dbda15aa5572e68e87b198efb68b8559ec24363f3d0a06b173d8f4ac24f50420d9a4b6f4cbb2f571883e00eb0b5343bb9b2ae9f5492eb"]}

response:
{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"invalid unit price"}}

RPC:https://api.baobab.klaytn.net:8651

TxTypeValuetransfer error!

I made a TxTypeValuetransfer myself, but the api sendRawTransaction called failed, could you help me? Thx!

curl -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"klay_sendRawTransaction","params":[08f87c80853a35294400830186a094f90675a56a03f836204d66c0f923e00500ddc90a019451f5b8c864ce3b09a353459f95cf7bf9f840b9e8808207f5a096e433eded5c10c504d9c120bd9655ae327e2c94023ce07637d932a9e7f7980ba063c783c47ece9d77d1f6a9e3181ebe0a210b52ccf98759dc07d9e7d94c521e30],"id":1}' https://api.baobab.klaytn.net:8651

{"jsonrpc":"2.0","error":{"code":-32600,"message":"invalid character '8' after array element"}}

is this client stable? ValueTransferTransaction fail

My project want try use this client, version below:

<dependency>
      <artifactId>core</artifactId>
      <groupId>com.klaytn.caver</groupId>
      <version>1.0.2</version>
    </dependency>

but with below code for transaction fail.

Caver caver = Caver.build(
        new HttpService("https://api.cypress.klaytn.net:8651/", new OkHttpClient.Builder().build(),
            false));
    KlayCredentials credentials = KlayCredentials
        .create("private key");
    TransactionManager transactionManager = new TransactionManager.Builder(caver, credentials)
        .setChaindId(ChainId.MAINNET).build();

    ValueTransferTransaction valueTransferTransaction = ValueTransferTransaction.create(
        credentials.getAddress(),  // fromAddress
        "toAddress",  // toAddress
        Convert.toPeb(BigDecimal.ONE, Convert.Unit.PEB).toBigInteger(),  // value
        BigInteger.valueOf(100_000)  // gasLimit
    );
    ;
    KlayRawTransaction klayRawTransaction = transactionManager.sign(valueTransferTransaction);
    String rawTransaction = klayRawTransaction.getValueAsString();
    System.out.println(rawTransaction);


Bytes32 transactionHash = caver.klay().sendSignedTransaction(rawTransaction).send();
    if (transactionHash.hasError()) {
      Error error = transactionHash.getError();
      System.out.println(error.getCode());
      System.out.println(error.getMessage());
      System.out.println(error.getData());
    } else {
      System.out.println(transactionHash.getResult());
    }

and i also try use ValueTransfer, but fail.

KlayTransactionReceipt.TransactionReceipt transactionReceipt = ValueTransfer
        .create(caver, credentials, ChainId.MAINNET)
        .sendFunds(ValueTransferTransaction.create(
            credentials.getAddress(),  // fromAddress
            "toAddress",  // toAddress
            Convert.toPeb(BigDecimal.ONE, Unit.PEB).toBigInteger(),  // value
            BigInteger.valueOf(100_000)  // gasLimit
        )).send();

Cannot parsing block's transaction list via Klay.getBlockByNumber method.

When I send a request via getBlockByNumber method, fasterxml throw MismatchedInputException.

I guess, API Server response tx hash array for block's transactions so fasterxml cannot deserialize to KlayBlock class because of transactions one of member variables

  • Error log
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.klaytn.caver.methods.response.KlayTransaction$Transaction` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('... some tx hash ... ')
 at [Source: (okio.RealBufferedSource$1); line: 1, column: 1926] (through reference chain: com.klaytn.caver.methods.response.KlayBlock["result"]->com.klaytn.caver.methods.response.KlayBlock$Block["transactions"]->java.util.ArrayList[0])

Transaction decode fail with TxTypeLegacyTransaction

Describe the bug
TransactionDecoder.decode function occur error when transaction is legacy type.

How to reproduce
TxTypeLegacyTransaction tx = /* create a legacy transaction /;
KlayRawTransaction raw = tx.sign(/
sender credential /, / Chain ID */);

TransactionDecoder.decode(raw.getValueAsString()); // NPE

Expected behavior
Without error, return decoded legacy transaction.

Attachments
If applicable, add data, logs or screenshots to help explain your problem.

Environment (please complete the following information)

  • caver-java v1.3.1
  • macOS/10.14

Additional context
Add any other context about the problem here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.