Skip to content

Instantly share code, notes, and snippets.

@nobodyme
Created March 14, 2019 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nobodyme/6c1492fc931bb5d81723ee2131904b0a to your computer and use it in GitHub Desktop.
Save nobodyme/6c1492fc931bb5d81723ee2131904b0a to your computer and use it in GitHub Desktop.
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