Created
March 14, 2019 14:36
-
-
Save nobodyme/6c1492fc931bb5d81723ee2131904b0a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ZookeeperNonceTransactionManager extends FastRawTransactionManager implements TransactionManager { | |
private static final byte ATTEMPTS = 20; | |
private static final int SLEEP_DURATION = 100; | |
private static volatile BigInteger nonce = BigInteger.valueOf(-1); | |
private final ZookeeperNonce zookeeperNonce; | |
private final TransactionReceiptProcessor transactionReceiptProcessor; | |
@Autowired | |
public ZookeeperNonceTransactionManager( | |
@Qualifier("initWeb3j") Web3j web3j, | |
Credentials credentials, | |
ZookeeperNonce zookeeperNonce | |
) { | |
this(web3j, credentials, zookeeperNonce, new PollingTransactionReceiptProcessor(web3j, SLEEP_DURATION, ATTEMPTS)); | |
} | |
private ZookeeperNonceTransactionManager( | |
@Qualifier("initWeb3j") Web3j web3j, | |
Credentials credentials, | |
ZookeeperNonce zookeeperNonce, | |
TransactionReceiptProcessor trProcessor | |
) { | |
super(web3j, credentials, trProcessor); | |
this.transactionReceiptProcessor = trProcessor; | |
this.zookeeperNonce = zookeeperNonce; | |
} | |
@Override | |
protected synchronized BigInteger getNonce() throws IOException { | |
if (nonce.signum() == -1 || nonce == null) { | |
nonce = super.getNonce(); | |
zookeeperNonce.setNonce(nonce.intValue()); | |
} else { | |
nonce = BigInteger.valueOf(zookeeperNonce.loadNonce()); | |
} | |
return nonce; | |
} | |
@Override | |
public TransactionReceipt executeTransaction( | |
BigInteger gasPrice, BigInteger gasLimit, String to, | |
String data, BigInteger value) throws IOException, TransactionException { | |
boolean increment = true; | |
EthSendTransaction ethSendTransaction = null; | |
try { | |
zookeeperNonce.lock(); | |
ethSendTransaction = this.sendTransaction(gasPrice, gasLimit, to, data, value); | |
} catch (IOException ex) { | |
increment = false; | |
throw new IOException(ex); | |
} finally { | |
zookeeperNonce.unlock(increment); | |
} | |
return this.transactionReceiptProcessor | |
.waitForTransactionReceipt(ethSendTransaction.getTransactionHash()); | |
} | |
@Override | |
public EthSendTransaction sendTransaction( | |
BigInteger gasPrice, | |
BigInteger gasLimit, | |
String to, | |
String data, | |
BigInteger value | |
) throws IOException { | |
return super.sendTransaction( | |
gasPrice, gasLimit.add(BigInteger.valueOf(21_000L)), to, data, value | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment