├── .github
└── workflows
│ ├── gradle.yml
│ └── maven-publish.yml
├── .gitignore
├── CHANGELOG.md
├── README.md
├── build.gradle
├── docs
├── GLDToken.json
├── account-management.md
├── batch-rpc.md
├── cfx-address.md
├── contract-interaction.md
├── getting-started.md
├── how-to-publish.md
└── sending-tx.md
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
├── main
└── java
│ └── conflux
│ └── web3j
│ ├── AMNAccount.java
│ ├── Account.java
│ ├── AccountManager.java
│ ├── Cfx.java
│ ├── CfxPubSub.java
│ ├── CfxUnit.java
│ ├── Debug.java
│ ├── HasValue.java
│ ├── Request.java
│ ├── RpcException.java
│ ├── Trace.java
│ ├── Web3.java
│ ├── Web3j.java
│ ├── contract
│ ├── ContractCall.java
│ ├── ERC1155.java
│ ├── ERC20.java
│ ├── ERC721.java
│ ├── ERC777.java
│ ├── abi
│ │ ├── DecodeUtil.java
│ │ └── TupleDecoder.java
│ ├── diagnostics
│ │ └── Recall.java
│ └── internals
│ │ ├── AdminControl.java
│ │ ├── CrossSpaceCall.java
│ │ ├── PoSRegister.java
│ │ ├── SponsorWhitelistControl.java
│ │ └── Staking.java
│ ├── crypto
│ ├── ConfluxBase32.java
│ ├── ConfluxBase32Exception.java
│ ├── Sign.java
│ ├── StructuredData.java
│ └── StructuredDataEncoder.java
│ ├── request
│ ├── Call.java
│ ├── Epoch.java
│ ├── LogFilter.java
│ └── TraceFilter.java
│ ├── response
│ ├── AccountInfo.java
│ ├── AccountPendingInfo.java
│ ├── AccountPendingTransactions.java
│ ├── Action.java
│ ├── BigIntNullableResponse.java
│ ├── BigIntResponse.java
│ ├── Block.java
│ ├── BlockHeader.java
│ ├── BlockRevertRateResponse.java
│ ├── BlockSummary.java
│ ├── BlockTxInnerTrace.java
│ ├── BlockTxTrace.java
│ ├── CfxResponse.java
│ ├── DepositInfo.java
│ ├── FeeHistory.java
│ ├── LocalizedBlockTrace.java
│ ├── LocalizedTrace.java
│ ├── Log.java
│ ├── ParamsOfVote.java
│ ├── PoSAccountReward.java
│ ├── PoSEconomics.java
│ ├── PoSEpochRewards.java
│ ├── Receipt.java
│ ├── RevertLog.java
│ ├── RewardInfo.java
│ ├── SponsorInfo.java
│ ├── Status.java
│ ├── StorageChange.java
│ ├── StorageRoot.java
│ ├── StringListResponse.java
│ ├── StringNullableResponse.java
│ ├── StringResponse.java
│ ├── Subscribe.java
│ ├── SupplyInfo.java
│ ├── Transaction.java
│ ├── Unsubscribe.java
│ ├── UsedGasAndCollateral.java
│ ├── VoteStakeInfo.java
│ └── events
│ │ ├── Epoch.java
│ │ ├── EpochNotification.java
│ │ ├── LogNotification.java
│ │ ├── NewHead.java
│ │ └── NewHeadsNotification.java
│ ├── types
│ ├── AccessListEntry.java
│ ├── Address.java
│ ├── AddressException.java
│ ├── AddressType.java
│ ├── CfxAddress.java
│ ├── RawTransaction.java
│ ├── SendTransactionError.java
│ ├── SendTransactionResult.java
│ └── TransactionBuilder.java
│ └── utils
│ └── Utils.java
└── test
├── java
└── conflux
│ └── web3j
│ ├── crypto
│ ├── ECRecoverTest.java
│ ├── SampleKeys.java
│ ├── SignDataTests.java
│ └── StructuredDataTests.java
│ └── types
│ ├── AddressTests.java
│ ├── CfxBase32Tests.java
│ ├── RPCTests.java
│ └── RawTransactionTests.java
└── resources
└── structured_data_json_files
└── ValidStructuredData.json
/.github/workflows/gradle.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a Java project with Gradle
2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle
3 |
4 | name: Java CI with Gradle
5 |
6 | on:
7 | push:
8 | branches: [ master ]
9 | pull_request:
10 | branches: [ master ]
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 |
17 | steps:
18 | - uses: actions/checkout@v2
19 | - name: Set up JDK 1.8
20 | uses: actions/setup-java@v1
21 | with:
22 | java-version: 1.8
23 | - name: Grant execute permission for gradlew
24 | run: chmod +x gradlew
25 | - name: Build with Gradle
26 | run: ./gradlew build
27 | - name: Build doc Gradle
28 | run: ./gradlew javadoc
29 |
--------------------------------------------------------------------------------
/.github/workflows/maven-publish.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a package using Maven and then publish it to GitHub packages when a release is created
2 | # For more information see: https://github.com/actions/setup-java#apache-maven-with-a-settings-path
3 |
4 | name: Maven Package
5 |
6 | on:
7 | release:
8 | types: [created]
9 |
10 | jobs:
11 | build:
12 |
13 | runs-on: ubuntu-latest
14 |
15 | steps:
16 | - uses: actions/checkout@v2
17 | - name: Set up JDK 1.8
18 | uses: actions/setup-java@v1
19 | with:
20 | java-version: 1.8
21 | server-id: github # Value of the distributionManagement/repository/id field of the pom.xml
22 | settings-path: ${{ github.workspace }} # location for the settings.xml file
23 |
24 | - name: Build with Maven
25 | run: mvn -B package --file pom.xml
26 |
27 | - name: Publish to GitHub Packages Apache Maven
28 | run: mvn deploy -s $GITHUB_WORKSPACE/settings.xml
29 | env:
30 | GITHUB_TOKEN: ${{ github.token }}
31 | MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }}
32 | MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }}
33 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ### Java template
2 | *.class
3 |
4 | # Package Files #
5 | *.jar
6 | *.war
7 | *.ear
8 |
9 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
10 | hs_err_pid*
11 | ### Gradle template
12 | .gradle
13 | /build
14 | /out
15 | */build/
16 | */out/
17 |
18 | # Ignore Gradle GUI config
19 | gradle-app.setting
20 |
21 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
22 | !gradle-wrapper.jar
23 |
24 | # Cache of project
25 | .gradletasknamecache
26 |
27 | # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
28 | # gradle/wrapper/gradle-wrapper.properties
29 |
30 | # Eclipse
31 | .classpath
32 | .settings/
33 | bin
34 | .idea
35 | docs/tmp.md
36 | docs/how-to-publish.md
37 | .vscode
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # CHANGELOG
2 |
3 | ### 1.3.0
4 |
5 | This version add support for [Conflux hardfork v2.4.0](https://doc.confluxnetwork.org/docs/general/hardforks/v2.4), including:
6 |
7 | 1. New added RPC methods: cfx_maxPriorityFeePerGas, cfx_feeHistory, cfx_getFeeBurnt
8 | 2. Support for CIP-1559 transaction
9 |
10 | ### 1.2.10
11 |
12 | 1. Fix SendTransactionError parse method to handle data is null
13 |
14 | ### 1.2.6
15 | * Add support for Batch Requests
16 |
17 | ### 1.2.5
18 |
19 | 1. Add support for internal contract CrossSpaceCall and PoSRegister
20 | 2. Adapt for [CIP-23](https://github.com/Conflux-Chain/CIPs/blob/master/CIPs/cip-23.md)
21 | 3. Fix `blockHead` event subscribe loss bug
22 | 4. Add `random` and `getPrivateKey` to `Account` class
23 |
24 | ### 1.2.0
25 |
26 | * Add support for standard token ERC721, ERC1155
27 |
28 | ### 1.1.1
29 |
30 | * Default gasPrice changed to 1GDrip
31 | * When sending transaction, will get `chainId` from Cfx instance, and using txpool nonce
32 | * blockHeader add two new fields `custom`, `posReference`
33 | * status add two new fields `latestFinalized`, `ethereumSpaceChainId`
34 |
35 | #### Add more RPC methods
36 |
37 | Add support for new methods imported from Conflux v2.0
38 |
39 | 1. `txpool_nextNonce`
40 | 2. `cfx_openedMethodGroups`
41 | 3. `cfx_getPoSEconomics`
42 | 4. `cfx_getPoSRewardByEpoch`
43 |
44 | #### Account
45 |
46 | Several Account method has been removed.
47 |
48 | * getNonce
49 | * setNonce
50 | * waitForNonceUpdated
51 | * waitForNonceUpdated
52 |
53 | ### 1.1.0
54 |
55 | #### Add more RPC methods
56 | 1. `cfx_getEpochReceipts`
57 | 2. `cfx_getAccountPendingInfo`
58 | 3. `cfx_getAccountPendingTransactions`
59 | 4. `trace_block`
60 | 5. `trace_transaction`
61 | 6. `trace_filter`
62 | 7. `cfx_getLogs`'s filter param add one more field 'offset'
63 | 8. `cfx_subscribe epochs` add one more optional tag parameter, available options: `latest_mined`(default value), `latest_state`
64 |
65 | Note: the required RPC service version is `1.1.4` or above.
66 |
67 | #### MISC
68 |
69 | 1. `Account` added method `deploy`, which can used to deploy contract.
70 | 2. `Account` added method `deployFile` which supports to deploy contract with truffle compiled json file.
71 | 3. Internal contract's constructor method omit a parameter `networkId`
72 |
73 | ### 1.0.0
74 |
75 | 1. Class Address support new CIP37 address
76 | 2. Where ever need an address, you should pass an `Address` instance, String address will not work
77 | 3. `getStatus` return a new field `networkId`
78 | 4. `getSupplyInfo` return a new field `totalCirculating`
79 | 5. `Address.validate` has been moved to `AddressType.validateHexAddress`
80 | 6. ERC20Call, ERC20Executor, ERC777Call, ERC777Executor has been removed, you can use the new ERC20, ERC777
81 | 7. AccountManager's constructor add a new parameter `networkId`
82 | 8. `org.web3j:core` updated to version 4.8.4
83 |
84 |
85 | ### 0.9.0
86 |
87 | 1. Tx receipts return more info: txExecErrorMsg, gasCoveredBySponsor, storageCoveredBySponsor, storageCollateralized, storageReleased
88 | 2. Add new RPC methods: cfx_getDepositList, cfx_getVoteList, cfx_getSupplyInfo
89 | 3. Add support for InternalContracts
90 | 4. Merge ERC20, ERC777 call and executor
91 | 5. Update default gasPrice to 1 Drip
92 | 6. Update RawTransaction default chainId to 1029(mainnet)
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * This file was generated by the Gradle 'init' task.
3 | *
4 | * This generated file contains a sample Java Library project to get you started.
5 | * For more details take a look at the Java Libraries chapter in the Gradle
6 | * User Manual available at https://docs.gradle.org/5.6.1/userguide/java_library_plugin.html
7 | */
8 |
9 | plugins {
10 | id 'java-library' // Apply the java-library plugin to add support for Java Library
11 | id 'maven-publish'
12 | id 'signing'
13 | }
14 |
15 | group = 'io.github.conflux-chain'
16 | version = '1.3.0' // SNAPSHOT
17 |
18 | repositories {
19 | // jcenter()
20 | mavenCentral()
21 | }
22 |
23 | dependencies {
24 | // This dependency is exported to consumers, that is to say found on their compile classpath.
25 | api 'org.apache.commons:commons-math3:3.6.1'
26 |
27 | // This dependency is used internally, and not exposed to consumers on their own compile classpath.
28 | implementation 'com.google.guava:guava:28.0-jre'
29 |
30 | compile 'org.web3j:core:4.9.3'
31 |
32 | // Use JUnit test framework
33 | testImplementation 'junit:junit:4.12'
34 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.4.2'
35 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.4.2'
36 | }
37 |
38 | test {
39 | useJUnitPlatform()
40 | }
41 |
42 | tasks.register('sourcesJar', Jar) {
43 | archiveClassifier = 'sources'
44 | from sourceSets.main.allJava
45 | }
46 | tasks.register('javadocJar', Jar) {
47 | archiveClassifier = 'javadoc'
48 | from javadoc.destinationDir
49 | }
50 |
51 | tasks.register('printEnvironmentVariable') {
52 | doLast {
53 | println "MY_ENV_VAR: " + findProperty("signing.secretKey") as String
54 | }
55 | }
56 |
57 | signing {
58 | useInMemoryPgpKeys(
59 | findProperty("signing.secretKey") as String,
60 | findProperty("signing.password") as String
61 | )
62 | sign publishing.publications;
63 | }
64 |
65 | publishing {
66 | publications {
67 | mavenJava(MavenPublication) {
68 | from components.java
69 | artifactId = 'conflux.web3j'
70 | artifact sourcesJar
71 | artifact javadocJar
72 |
73 | versionMapping {
74 | usage('java-api') {
75 | fromResolutionOf('runtimeClasspath')
76 | }
77 | usage('java-runtime') {
78 | fromResolutionResult()
79 | }
80 | }
81 |
82 | pom {
83 | name = 'java-conflux-sdk'
84 | description = 'Java SDK for conflux network'
85 | url = 'https://github.com/Conflux-Chain/java-conflux-sdk'
86 | properties = [
87 | tags: "blockchain, conflux"
88 | ]
89 | licenses {
90 | license {
91 | name = 'GNU General Public License v3.0'
92 | url = 'https://github.com/Conflux-Chain/conflux-rust/blob/master/LICENSE'
93 | }
94 | }
95 | developers {
96 | developer {
97 | id = 'Pana'
98 | name = 'Pana.W'
99 | email = 'pana.wang@outlook.com'
100 | }
101 | }
102 | scm {
103 | connection = 'scm:https://github.com/Conflux-Chain/java-conflux-sdk.git'
104 | developerConnection = 'scm:git://github.com/Conflux-Chain/java-conflux-sdk.git'
105 | url = 'https://github.com/conflux-chain/java-conflux-sdk'
106 | }
107 | }
108 | }
109 | }
110 |
111 | repositories {
112 | maven {
113 | def releasesRepoUrl = "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
114 | def snapshotsRepoUrl = "https://oss.sonatype.org/content/repositories/snapshots"
115 | url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl
116 | name = "OSSRH"
117 | credentials {
118 | username = findProperty("maven.username")
119 | password = findProperty("maven.password")
120 | }
121 | }
122 | }
123 | }
124 |
125 | // ref https://docs.github.com/en/actions/guides/publishing-java-packages-with-gradle
126 |
--------------------------------------------------------------------------------
/docs/account-management.md:
--------------------------------------------------------------------------------
1 | # Account Management
2 |
3 | `java-conflux-sdk` provide basic account management function. Developer can create or import their account(privateKey or keystore file) with class [`Account`](https://javadoc.io/doc/io.github.conflux-chain/conflux.web3j/latest/conflux/web3j/Account.html) or [`AccountManager`](https://javadoc.io/doc/io.github.conflux-chain/conflux.web3j/latest/conflux/web3j/AccountManager.html).
4 | After import accounts can be used to sign transaction (or message) and send them into blockchain network.
5 |
6 | ## AccountManager
7 |
8 | `AccountMananger` can be used to manager all accounts saved in one folder. Accounts are saved in keystore file.
9 | Normal operations are:
10 |
11 | * Initialize AccountManager
12 | * Create new account
13 | * Import account by privateKey or keystore file
14 | * List accounts
15 | * Export account in private key
16 | * Delete account
17 | * Sign transaction or message
18 | * Lock/Unlock
19 |
20 | When working with keystore file, a relative password is required.
21 |
22 | ### Initialize AccountManager
23 |
24 | ```java
25 | import conflux.web3j.AccountManager;
26 |
27 | int testNetChainId = 1;
28 | // create AccountManager instance from the default keystore folder
29 | AccountManager ac = new AccountManager(testNetChainId);
30 | // or create AccountManager install from specify folder
31 | AccountManager ac1 = new AccountManager("/path/tothe/keystore/", testNetChainId);
32 | ```
33 |
34 | ### Create new account
35 |
36 | ```java
37 | Address newCreatedAccountAddress = ac.create("account-pwd");
38 | // The new created account will be saved in a keystore file, encrypted by password
39 | ```
40 |
41 | ### Import account
42 |
43 | ```java
44 | // import private key
45 | Optional
importedAddress = ac.imports("account-private-key", "new-pwd");
46 | // import keystore file
47 | Optoinal importedAddress = ac.imports("keystore-file-path", "origin-pwd", "new-pwd");
48 | ```
49 |
50 | ### Export account privateKey
51 |
52 | ```java
53 | Address addr = new Address("cfxtest:aak2rra2njvd77ezwjvx04kkds9fzagfe6d5r8e957");
54 | String privatekey = ac.exportPrivateKey(addr, "account-pwd");
55 | ```
56 |
57 | ### Sign transaction
58 |
59 | ```java
60 | import conflux.web3j.types.RawTransaction;
61 |
62 | // Construct a rawTx by specify transaction parameters
63 | RawTransaction rawTx = RawTransaction.create(
64 | nonce, // nonce
65 | CfxUnit.DEFAULT_GAS_LIMIT, // gas
66 | to, // to
67 | value, // value
68 | BigInteger.valueOf(0), // storageLimit
69 | currentEpochNumber, // epochHeight
70 | "" // data
71 | );
72 |
73 | Address addr = new Address("cfxtest:aak2rra2njvd77ezwjvx04kkds9fzagfe6d5r8e957");
74 | String signedTx = ac.signTransaction(rawTx, addr, "account-pwd");
75 |
76 | // The signedTx can ben send to blockchain network by calling `cfx_sendRawTransaction` method
77 | ```
78 |
79 | ## Account
80 |
81 | The `Account` class instance can be used to sign and send transactions, it provides several tx send utility methods:
82 |
83 | * transfer
84 | * send
85 | * deploy
86 | * call
87 |
88 | ### Create Account
89 |
90 | ```java
91 | import conflux.web3j.Account;
92 | // create from privateKey
93 | Cfx cfx = Cfx.create("https://test.confluxrpc.com");
94 | Account a1 = Account.create(cfx, "your-private-key");
95 | // Or unlock from AccountManager
96 | Account a2 = Account.unlock(cfx, am, addr, "password");
97 | ```
98 |
99 | ### Sending transactions
100 |
101 | Check [sending transactions](./sending-tx.md) for detail example about sending tx.
--------------------------------------------------------------------------------
/docs/getting-started.md:
--------------------------------------------------------------------------------
1 | # Getting started
2 |
3 | The `java-conflux-sdk` can be used to interact with ConfluxNetwork and is very easy to use.
4 |
5 | ## Invoke RPC methods
6 |
7 | `Conflux` node(or client) provide `JSON-RPC` to enable developer get chain info and send transactions.
8 | The `java-conflux-sdk` provide methods to talk with `Conflux` node JSON-RPC method.
9 |
10 | ### Init client
11 |
12 | To interact with `Conflux` node, an RPC endpoint is needed. You can run your own a node with RPC opened, or use the public RPC
13 | endpoint provide by `Conflux` fund:
14 |
15 | * MainNet(1029): https://main.confluxrpc.com
16 | * TestNet(1): https://test.confluxrpc.com
17 |
18 | Then create a java [`Cfx`](https://javadoc.io/doc/io.github.conflux-chain/conflux.web3j/latest/conflux/web3j/Cfx.html) client, which can be used to invoke RPC methods.
19 |
20 | ```java
21 | import conflux.web3j.Cfx;
22 | import java.math.BigInteger;
23 |
24 | public class Main {
25 | public static void main(String[] args) throws Exception {
26 | try {
27 | System.out.println("Hello conflux-web3j");
28 | Cfx cfx = Cfx.create("https://test.confluxrpc.com");
29 | BigInteger currentEpochNumber = cfx.getEpochNumber().sendAndGet();
30 | System.out.printf("Current epoch number %d \n", currentEpochNumber);
31 | } catch (Exception e) {
32 | e.printStackTrace();
33 | }
34 | }
35 | }
36 | ```
37 |
38 | ### Common RPC methods
39 |
40 | The `Cfx` client can be used to get a lot of blockchain info from node, including the latest epochNumber, block, account balance and nonce,
41 | transaction, receipt etc.
42 |
43 | #### Get account balance and nonce
44 | ```java
45 | import conflux.web3j.types.Address;
46 |
47 | Address addr = new Address("cfxtest:aak2rra2njvd77ezwjvx04kkds9fzagfe6d5r8e957");
48 | BigInteger balance = cfx.getBalance(addr).sendAndGet();
49 | // nonce will be used when sending transaction
50 | BigInteger nonce = cfx.getNonce(addr).sendAndGet();
51 | ```
52 |
53 | #### Get block
54 |
55 | ```java
56 | import conflux.web3j.request.Epoch;
57 | import conflux.web3j.response.Block;
58 | import conflux.web3j.response.BlockSummary;
59 |
60 | Epoch epoch = Epoch.numberOf(1000000);
61 | Optional b1 = cfx.getBlockSummaryByEpoch(epoch).sendAndGet();
62 | // block may get failed
63 | boolean blockRetriveSuccess = b1.isPresent();
64 | Optional blockWithTxDetail = cfx.getBlockByEpoch(epoch).sendAndGet();
65 |
66 | String blockHash = "0xe27f5f566d3f450855e0455ae84c6723ebb477891ffa3ee68af9be518d5b150c";
67 | Optional b3 = cfx.getBlockSummaryByHash(blockHash).sendAndGet();
68 | ```
69 |
70 | #### Get transaction and receipt
71 |
72 | ```java
73 | import conflux.web3j.response.Receipt;
74 | import conflux.web3j.response.Transaction;
75 |
76 | String txhash = "0x1aed92e97aa70dbc629ae37879915340f47b936a15529bd1e3952783a2efbfcd";
77 | Optional tx = cfx.getTransactionByHash(txhash).sendAndGet();
78 | Optional receipt = cfx.getTransactionReceipt(txhash).sendAndGet();
79 | ```
80 |
81 | For complete methods check [fullnode JSONRPC](https://developer.confluxnetwork.org/conflux-doc/docs/json_rpc) doc and [Cfx API](https://javadoc.io/doc/io.github.conflux-chain/conflux.web3j/latest/conflux/web3j/Cfx.html) doc
82 |
83 | ## Base32 address
84 |
85 | `Conflux` use base32 encoded address like `cfxtest:aak2rra2njvd77ezwjvx04kkds9fzagfe6d5r8e957`. The java SDK provide a class `conflux.web3j.types.Address` which can be used to construct, encode, decode address.
86 | For detail usage check [here](./cfx-address.md)
87 |
--------------------------------------------------------------------------------
/docs/how-to-publish.md:
--------------------------------------------------------------------------------
1 | # How to publish
2 |
3 | 1. Update version in build.gradle
4 | 2. 使用 gradle publish 发布到 OSSRH
5 | 3. 到 oss.sonatype.org 的 Staging repositories 把将要发布的版本 close 掉
6 | 4. 待状态变为 closed 后,进行 Release 操作
7 |
8 | ## Configure
9 |
10 | 1. 在发布新版本 artifact 到 maven 之前, 需要对他们进行 sign, 签名需要用到 signingPassword 和 signingKey(pgp key); (PS 忘记如何生成了🤣)
11 | 2. 在发布到 maven 的时候, 需要通过 `oss.sonatype.org` 生成的 accessToken 来登录, 之前是 userName 和 password, 2024.6 后不再支持
--------------------------------------------------------------------------------
/docs/sending-tx.md:
--------------------------------------------------------------------------------
1 | # Sending Transaction
2 |
3 | Sending transaction is the only way to transfer CFX to another account, or change contract's state.
4 | To send a transaction the first step is assemble the necessary info of a tx, including:
5 |
6 | * to
7 | * value
8 | * nonce
9 | * gas
10 | * gasPrice
11 | * storageLimit
12 | * chainId
13 | * epochHeight
14 | * data
15 |
16 | Check [this doc](https://developer.confluxnetwork.org/sending-tx/en/transaction_explain) for detail introduction about transaction.
17 |
18 | Second the tx need to be signed by the sender's private key, and got a signed tx.
19 |
20 | Finally, the signed tx need to be sent to blockchain network by calling the `sendRawTransaction` RPC method.
21 |
22 | `java-conflux-sdk` provide a lot of methods to help developer send transactions.
23 |
24 | ## Quick transfer CFX
25 |
26 | The `account.transfer` method can be used to quickly send CFX to another account by specify the receiver address and amount.
27 |
28 | ```java
29 | import conflux.web3j.CfxUnit;
30 |
31 | Address addr = new Address("cfxtest:aak2rra2njvd77ezwjvx04kkds9fzagfe6d5r8e957");
32 | // transfer 1 CFX to addr, the transaction hash will returned
33 | String hash = account.transfer(addr, CfxUnit.cfx2Drip(1));
34 |
35 | // An optional parameter can be used to specify other fields of a transaction
36 | Account.Option op = new Account.Option();
37 | op.withGasPrice(CfxUnit.DEFAULT_GAS_PRICE); // specify a bigger gasPrice to accelerate transaction
38 | // gas, storageLimit etc can also be specified through op
39 | String hash2 = account.transfer(op, addr, CfxUnit.cfx2Drip(1));
40 | ```
41 |
42 | ## Build tx manually and send
43 |
44 | If developer want more control on the transaction, they can create the RawTransaction and send it by account.
45 |
46 | ```java
47 | import conflux.web3j.types.RawTransaction;
48 | BigInteger nonce = cfx.getNonce(account.getAddress()).sendAndGet();
49 | BigInteger value = CfxUnit.cfx2Drip(1);
50 | BigInteger currentEpochNumber = cfx.getEpochNumber().sendAndGet();
51 |
52 | RawTransaction rawTx = new RawTransaction();
53 | rawTx.setTo(to);
54 | rawTx.setValue(value);
55 | rawTx.setGasPrice(CfxUnit.DEFAULT_GAS_PRICE);
56 | // set all the rest field: nonce, gas, storageLimit ...
57 | // send it with account.send
58 | SendTransactionResult resp1 = account.send(rawTx);
59 |
60 | // or sign it and send
61 | String signedTx = account.sign(rawTx);
62 | SendTransactionResult resp2 = account.send(signedTx);
63 | ```
64 |
65 | [`RawTransaction`](https://javadoc.io/static/io.github.conflux-chain/conflux.web3j/1.1.1/conflux/web3j/types/RawTransaction.html) also provide several methods to help quick build tx:
66 |
67 | `call`, `transfer`, `deploy`
68 |
69 | ## TransactionBuilder
70 |
71 | The [`TransactionBuilder`](https://javadoc.io/doc/io.github.conflux-chain/conflux.web3j/latest/conflux/web3j/types/TransactionBuilder.html) can be used to build a RawTransaction.
72 |
73 | ```java
74 | TransactionBuilder txBuilder = new TransactionBuilder(addr);
75 | txBuilder.withValue(CfxUnit.cfx2Drip(1));
76 | txBuilder.withTo(addr);
77 | // ... other options can goes here
78 | RawTransaction rawTx = txBuilder.build(cfx); // the build method can automatically fill tx fields: nonce, gasPrice, gas, storageLimit, chainId, epochHeight
79 | ```
80 |
81 | ## Deploy contract
82 |
83 | To deploy a contract, a deployment transaction is needed to sent to blockchain, contract's bytecode and constructor parameter(if it has) should be ABI encoded and set as tx's data field.
84 |
85 | ```java
86 | String bytecode = "0x123123...";
87 | String hash = account.deploy(bytecode, arg1, arg2); // pass args if contract constructor has
88 | // an Account.Option also can be specified here
89 | String hash2 = account.deploy(op, bytecode, arg1, arg2);
90 | ```
91 |
92 | ## Change contract's state by calling its method
93 |
94 | To update contract's state a transaction is also needed to be sent. For example if you want transfer your erc20 tokens to another address.
95 | With account.call method we can achieve this.
96 |
97 | ```java
98 | import org.web3j.abi.datatypes.generated.Uint256;
99 |
100 | String hash = account.call(contractAddr, "transfer", addr.getABIAddress(), new Uint256(100));
101 | ```
102 |
103 | There is detail introduction about [how to interact with contract](./contract-interaction.md)
104 |
105 | ## Common errors when sending tx
106 |
107 | Check [here](https://developer.confluxnetwork.org/conflux-doc/docs/RPCs/send_tx_error) for common sending tx error
108 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Conflux-Chain/java-conflux-sdk/e6fd0212960eab506e7f0d5dcb54969bd40b1c45/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.1-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 | # Determine the Java command to use to start the JVM.
86 | if [ -n "$JAVA_HOME" ] ; then
87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
88 | # IBM's JDK on AIX uses strange locations for the executables
89 | JAVACMD="$JAVA_HOME/jre/sh/java"
90 | else
91 | JAVACMD="$JAVA_HOME/bin/java"
92 | fi
93 | if [ ! -x "$JAVACMD" ] ; then
94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
95 |
96 | Please set the JAVA_HOME variable in your environment to match the
97 | location of your Java installation."
98 | fi
99 | else
100 | JAVACMD="java"
101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
102 |
103 | Please set the JAVA_HOME variable in your environment to match the
104 | location of your Java installation."
105 | fi
106 |
107 | # Increase the maximum file descriptors if we can.
108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
109 | MAX_FD_LIMIT=`ulimit -H -n`
110 | if [ $? -eq 0 ] ; then
111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
112 | MAX_FD="$MAX_FD_LIMIT"
113 | fi
114 | ulimit -n $MAX_FD
115 | if [ $? -ne 0 ] ; then
116 | warn "Could not set maximum file descriptor limit: $MAX_FD"
117 | fi
118 | else
119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
120 | fi
121 | fi
122 |
123 | # For Darwin, add options to specify how the application appears in the dock
124 | if $darwin; then
125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
126 | fi
127 |
128 | # For Cygwin or MSYS, switch paths to Windows format before running java
129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
132 | JAVACMD=`cygpath --unix "$JAVACMD"`
133 |
134 | # We build the pattern for arguments to be converted via cygpath
135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
136 | SEP=""
137 | for dir in $ROOTDIRSRAW ; do
138 | ROOTDIRS="$ROOTDIRS$SEP$dir"
139 | SEP="|"
140 | done
141 | OURCYGPATTERN="(^($ROOTDIRS))"
142 | # Add a user-defined pattern to the cygpath arguments
143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
145 | fi
146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
147 | i=0
148 | for arg in "$@" ; do
149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
151 |
152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
154 | else
155 | eval `echo args$i`="\"$arg\""
156 | fi
157 | i=$((i+1))
158 | done
159 | case $i in
160 | (0) set -- ;;
161 | (1) set -- "$args0" ;;
162 | (2) set -- "$args0" "$args1" ;;
163 | (3) set -- "$args0" "$args1" "$args2" ;;
164 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
165 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
166 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
167 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
168 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
169 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
170 | esac
171 | fi
172 |
173 | # Escape application args
174 | save () {
175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
176 | echo " "
177 | }
178 | APP_ARGS=$(save "$@")
179 |
180 | # Collect all arguments for the java command, following the shell quoting and substitution rules
181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
182 |
183 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
184 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
185 | cd "$(dirname "$0")"
186 | fi
187 |
188 | exec "$JAVACMD" "$@"
189 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
34 |
35 | @rem Find java.exe
36 | if defined JAVA_HOME goto findJavaFromJavaHome
37 |
38 | set JAVA_EXE=java.exe
39 | %JAVA_EXE% -version >NUL 2>&1
40 | if "%ERRORLEVEL%" == "0" goto init
41 |
42 | echo.
43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
44 | echo.
45 | echo Please set the JAVA_HOME variable in your environment to match the
46 | echo location of your Java installation.
47 |
48 | goto fail
49 |
50 | :findJavaFromJavaHome
51 | set JAVA_HOME=%JAVA_HOME:"=%
52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
53 |
54 | if exist "%JAVA_EXE%" goto init
55 |
56 | echo.
57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
58 | echo.
59 | echo Please set the JAVA_HOME variable in your environment to match the
60 | echo location of your Java installation.
61 |
62 | goto fail
63 |
64 | :init
65 | @rem Get command-line arguments, handling Windows variants
66 |
67 | if not "%OS%" == "Windows_NT" goto win9xME_args
68 |
69 | :win9xME_args
70 | @rem Slurp the command line arguments.
71 | set CMD_LINE_ARGS=
72 | set _SKIP=2
73 |
74 | :win9xME_args_slurp
75 | if "x%~1" == "x" goto execute
76 |
77 | set CMD_LINE_ARGS=%*
78 |
79 | :execute
80 | @rem Setup the command line
81 |
82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
83 |
84 | @rem Execute Gradle
85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
86 |
87 | :end
88 | @rem End local scope for the variables with windows NT shell
89 | if "%ERRORLEVEL%"=="0" goto mainEnd
90 |
91 | :fail
92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
93 | rem the _cmd.exe /c_ return code!
94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
95 | exit /b 1
96 |
97 | :mainEnd
98 | if "%OS%"=="Windows_NT" endlocal
99 |
100 | :omega
101 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * This file was generated by the Gradle 'init' task.
3 | *
4 | * The settings file is used to specify which projects to include in your build.
5 | *
6 | * Detailed information about configuring a multi-project build in Gradle can be found
7 | * in the user manual at https://docs.gradle.org/5.6.1/userguide/multi_project_builds.html
8 | */
9 |
10 | rootProject.name = 'conflux-web3j'
11 |
--------------------------------------------------------------------------------
/src/main/java/conflux/web3j/AMNAccount.java:
--------------------------------------------------------------------------------
1 | package conflux.web3j;
2 |
3 | import conflux.web3j.types.Address;
4 | import conflux.web3j.types.RawTransaction;
5 | import conflux.web3j.types.SendTransactionError;
6 | import conflux.web3j.types.SendTransactionResult;
7 | import org.web3j.crypto.ECKeyPair;
8 |
9 | import java.math.BigInteger;
10 |
11 | // Auto manage nonce account
12 | public class AMNAccount extends Account {
13 |
14 | private BigInteger nonce;
15 | public AMNAccount(Cfx cfx, Address address, ECKeyPair ecKeyPair) {
16 | super(cfx, address, ecKeyPair);
17 | this.nonce = this.getPoolNonce();
18 | }
19 |
20 | public void setNonce(BigInteger nonce) {
21 | this.nonce = nonce;
22 | }
23 |
24 | public BigInteger getNonce() {
25 | return this.nonce;
26 | }
27 |
28 | private RawTransaction buildRawTransaction(Option option, Address to, String data) {
29 | return super.buildRawTransaction(option, to, data, this.nonce);
30 | }
31 |
32 | public SendTransactionResult send(String signedTx) throws Exception {
33 | SendTransactionResult result = super.send(signedTx);
34 | if (result.getRawError() == null
35 | || result.getErrorType().equals(SendTransactionError.TxAlreadyExists)
36 | || result.getErrorType().equals(SendTransactionError.InvalidNonceAlreadyUsed)) {
37 | this.nonce = this.nonce.add(BigInteger.ONE);
38 | }
39 | return result;
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/conflux/web3j/Cfx.java:
--------------------------------------------------------------------------------
1 | package conflux.web3j;
2 |
3 | import java.io.Closeable;
4 | import java.math.BigDecimal;
5 | import java.math.BigInteger;
6 | import java.util.List;
7 | import java.util.Optional;
8 |
9 | import conflux.web3j.response.*;
10 | import conflux.web3j.types.Address;
11 | import org.web3j.protocol.Web3jService;
12 | import org.web3j.protocol.core.Response;
13 | import org.web3j.protocol.http.HttpService;
14 |
15 | import conflux.web3j.request.Call;
16 | import conflux.web3j.request.Epoch;
17 | import conflux.web3j.request.LogFilter;
18 | import conflux.web3j.types.SendTransactionResult;
19 |
20 | /** Core Conflux JSON-RPC API. */
21 | public interface Cfx extends Closeable, CfxPubSub {
22 |
23 | static Cfx create(String url) {
24 | return new Web3j(new HttpService(url));
25 | }
26 |
27 | static Cfx create(String url, int retry) {
28 | return new Web3j(new HttpService(url), retry, 0);
29 | }
30 |
31 | static Cfx create(String url, int retry, long intervalMillis) {
32 | return new Web3j(new HttpService(url), retry, intervalMillis);
33 | }
34 |
35 | static Cfx create(Web3jService service) {
36 | return new Web3j(service);
37 | }
38 |
39 | static Cfx create(Web3jService service, int retry, long intervalMillis) {
40 | return new Web3j(service, retry, intervalMillis);
41 | }
42 |
43 | BigInteger getNetworkId();
44 |
45 | int getIntNetworkId();
46 |
47 | BigInteger getChainId();
48 |
49 | Request getGasPrice();
50 |
51 | Request getMaxPriorityFeePerGas();
52 |
53 | Request getFeeBurnt();
54 |
55 | Request getEpochNumber(Epoch... epoch);
56 |
57 | Request getBalance(Address address, Epoch... epoch);
58 |
59 | Request, StringNullableResponse> getAdmin(Address address, Epoch... epoch);
60 |
61 | Request getSponsorInfo(Address address, Epoch... epoch);
62 |
63 | Request getStakingBalance(Address address, Epoch... epoch);
64 |
65 | Request getCollateralForStorage(Address address, Epoch... epoch);
66 |
67 | Request getCode(Address address, Epoch... epoch);
68 |
69 | Request, StringNullableResponse> getStorageAt(Address address, String pos, Epoch... epoch);
70 |
71 | Request, StorageRoot.Response> getStorageRoot(Address address, Epoch... epoch);
72 |
73 | Request, BlockSummary.Response> getBlockSummaryByHash(String blockHash);
74 |
75 | Request, Block.Response> getBlockByHash(String blockHash);
76 |
77 | Request, BlockSummary.Response> getBlockSummaryByEpoch(Epoch epoch);
78 |
79 | Request, Block.Response> getBlockByEpoch(Epoch epoch);
80 |
81 | Request getBestBlockHash();
82 |
83 | Request getNonce(Address address, Epoch... epoch);
84 |
85 | Request txpoolNextNonce(Address address);
86 |
87 | Request sendRawTransaction(String hexEncoded);
88 |
89 | Request call(Call request, Epoch... epoch);
90 |
91 | Request, Log.Response> getLogs(LogFilter filter);
92 |
93 | Request, Transaction.Response> getTransactionByHash(String txHash);
94 |
95 | Request estimateGasAndCollateral(Call request, Epoch... epoch);
96 |
97 | Request, Block.ListResponse> getBlocksByEpoch(Epoch epoch);
98 |
99 | Request, Block.ListResponse> getSkippedBlocksByEpoch(Epoch epoch);
100 |
101 | Request, Receipt.Response> getTransactionReceipt(String txHash);
102 |
103 | Request getAccount(Address address, Epoch... epoch);
104 |
105 | Request getInterestRate(Epoch... epoch);
106 |
107 | Request getAccumulateInterestRate(Epoch... epoch);
108 |
109 | Request, BigIntNullableResponse> getConfirmationRisk(String blockHash);
110 |
111 | Request getBlockRevertRate(String blockHash);
112 |
113 | Request getStatus();
114 |
115 | Request, RewardInfo.Response> getReward(Epoch epoch);
116 |
117 | Request getClientVersion();
118 |
119 | Request, DepositInfo.ListResponse> getDepositList(Address address, Epoch... epoch);
120 |
121 | Request, VoteStakeInfo.ListResponse> getVoteList(Address address, Epoch... epoch);
122 |
123 | Request getSupplyInfo(Epoch... epoch);
124 |
125 | Request, AccountPendingInfo.Response> getAccountPendingInfo(Address address);
126 |
127 | Request getAccountPendingTransactions(Address address);
128 |
129 | Request, StringListResponse.Response> rpcModules();
130 |
131 | Request getPoSEconomics();
132 |
133 | Request getPoSRewardByEpoch(Address address, Epoch epoch);
134 |
135 | Request getParamsFromVote(Epoch... epoch);
136 |
137 | Request getFeeHistory(int count, Epoch epoch, List percentiles);
138 |
139 | & HasValue> Request getCustomizedRequest(Class responseType, String method, Object... params);
140 |
141 | default Receipt waitForReceipt(String txHash) throws InterruptedException {
142 | return this.waitForReceipt(txHash, 1000);
143 | }
144 |
145 | default Receipt waitForReceipt(String txHash, long intervalMillis) throws InterruptedException {
146 | Optional receipt = Optional.empty();
147 |
148 | while (!receipt.isPresent()) {
149 | Thread.sleep(intervalMillis);
150 | receipt = this.getTransactionReceipt(txHash).sendAndGet();
151 | }
152 |
153 | return receipt.get();
154 | }
155 |
156 | default void waitForNonce(Address address, BigInteger nonceUntil) throws InterruptedException {
157 | this.waitForNonce(address, nonceUntil, 1000);
158 | }
159 |
160 | default void waitForNonce(Address address, BigInteger nonceUntil, long intervalMillis) throws InterruptedException {
161 | while (this.getNonce(address).sendAndGet().compareTo(nonceUntil) < 0) {
162 | Thread.sleep(intervalMillis);
163 | }
164 | }
165 |
166 | default SendTransactionResult sendRawTransactionAndGet(String hexEncoded) throws RpcException {
167 | StringResponse response = this.sendRawTransaction(hexEncoded).sendWithRetry();
168 |
169 | return response.getError() == null
170 | ? new SendTransactionResult(response.getValue())
171 | : new SendTransactionResult(response.getError());
172 | }
173 |
174 | }
175 |
176 |
177 |
--------------------------------------------------------------------------------
/src/main/java/conflux/web3j/CfxPubSub.java:
--------------------------------------------------------------------------------
1 | package conflux.web3j;
2 |
3 | import conflux.web3j.request.Epoch;
4 | import conflux.web3j.request.LogFilter;
5 | import io.reactivex.Flowable;
6 | import conflux.web3j.response.events.*;
7 |
8 | public interface CfxPubSub {
9 | /**
10 | * Creates a {@link Flowable} instance that emits a notification when a new header is appended
11 | * to a chain, including chain reorganizations.
12 | *
13 | * @return a {@link Flowable} instance that emits a notification for every new header
14 | */
15 | Flowable subscribeNewHeads();
16 |
17 | /**
18 | * Creates a {@link Flowable} instance that emits notifications for logs included in new
19 | * imported blocks.
20 | *
21 | * @param filter only return logs match this filter
22 | * @return a {@link Flowable} instance that emits logs included in new blocks
23 | */
24 | Flowable subscribeLogs(LogFilter filter);
25 |
26 | /**
27 | * Creates a {@link Flowable} instance that emits notifications for epochs
28 | *
29 | * @return a {@link Flowable} instance that emits new epochs
30 | */
31 | Flowable subscribeEpochs(Epoch... epoch);
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/conflux/web3j/CfxUnit.java:
--------------------------------------------------------------------------------
1 | package conflux.web3j;
2 |
3 | import java.math.BigDecimal;
4 | import java.math.BigInteger;
5 |
6 | public class CfxUnit {
7 |
8 | private static final BigInteger DRIPS_PER_CFX_INT = BigInteger.TEN.pow(18);
9 | private static final BigDecimal DRIPS_PER_CFX_DECIMAL = new BigDecimal(DRIPS_PER_CFX_INT);
10 | private static final BigInteger DRIPS_PER_GDRIP = BigInteger.TEN.pow(9);
11 |
12 | public static final BigInteger GDRIP_ONE = BigInteger.TEN.pow(9);
13 | public static final BigInteger GDRIP_TEN = BigInteger.TEN.pow(10);
14 | public static final BigInteger CFX_ONE = BigInteger.TEN.pow(18);
15 |
16 | public static final BigInteger DEFAULT_GAS_PRICE = DRIPS_PER_GDRIP;
17 | public static final BigInteger DEFAULT_GAS_LIMIT = BigInteger.valueOf(21000);
18 |
19 | public static BigInteger cfx2Drip(long cfx) {
20 | return BigInteger.valueOf(cfx).multiply(DRIPS_PER_CFX_INT);
21 | }
22 |
23 | public static BigInteger cfx2Drip(double cfx) {
24 | return BigDecimal.valueOf(cfx).multiply(DRIPS_PER_CFX_DECIMAL).toBigIntegerExact();
25 | }
26 |
27 | public static BigInteger gdrip2Drip(long gdrip) {
28 | return BigInteger.valueOf(gdrip).multiply(DRIPS_PER_GDRIP);
29 | }
30 |
31 | public static BigDecimal drip2Cfx(BigInteger drip) {
32 | return new BigDecimal(drip).divide(DRIPS_PER_CFX_DECIMAL);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/conflux/web3j/Debug.java:
--------------------------------------------------------------------------------
1 | package conflux.web3j;
2 |
3 | import conflux.web3j.request.Epoch;
4 | import conflux.web3j.response.AccountPendingInfo;
5 | import conflux.web3j.response.AccountPendingTransactions;
6 | import conflux.web3j.response.Receipt;
7 | import conflux.web3j.types.Address;
8 |
9 | import java.io.Closeable;
10 | import java.util.List;
11 | import java.util.Optional;
12 |
13 | // debug RPC methods
14 | public interface Debug extends Closeable {
15 | Request>>, Receipt.ListResponse> getEpochReceipts(Epoch epoch);
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/conflux/web3j/HasValue.java:
--------------------------------------------------------------------------------
1 | package conflux.web3j;
2 |
3 | public interface HasValue {
4 | T getValue();
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/conflux/web3j/Request.java:
--------------------------------------------------------------------------------
1 | package conflux.web3j;
2 |
3 | import java.io.IOException;
4 | import java.util.Arrays;
5 |
6 | import org.web3j.protocol.Web3jService;
7 | import org.web3j.protocol.core.Response;
8 |
9 | public class Request & HasValue> extends org.web3j.protocol.core.Request