Skip to content

Instantly share code, notes, and snippets.

@talfco
Last active July 21, 2019 15:37
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 talfco/759977189e2776e50da3b6f63e0a1914 to your computer and use it in GitHub Desktop.
Save talfco/759977189e2776e50da3b6f63e0a1914 to your computer and use it in GitHub Desktop.
ETH2KNC Kyber Swap
private void eth2knc() {
Kyber3j kyber3j = Kyber3j.build(new KyberService(KyberService.KYBER_ROPSTEN));
log.info("Connected to Kyber Network: "+KyberService.KYBER_ROPSTEN);
// Buy KNC from ETH
try {
// Check if token is supported
Currencies currencies = kyber3j.currencies().send();
log.info("Exists Currency KNC: " + currencies.existsCurreny("KNC"));
if (!checkForError(currencies) && currencies.existsCurreny("KNC")) {
// Get buy rates
BuyRate buyRate = kyber3j.buyRate(currencies.getCurrency("KNC").getId(),"1",
false).send();
if (!checkForError(buyRate)) {
Rates rates = buyRate.getData().get(0);
SingleRate singleRate = rates.getSingleRate(0);
log.info("Conversion Rates: " + singleRate.getSrc_qty());
// Get tradeData
// Adjust conversion rates to 97%
singleRate.approximateReceivableToken(0.97);
TradeData tradeData = kyber3j.tradeData(credentials.getAddress(), singleRate, GasPriceRange.medium).send();
if (!checkForError(tradeData)) {
TradeData.TradeDataRecord rec = tradeData.getData().get(0);
RawTransaction rawTransaction = RawTransaction.createTransaction(
rec.getNonceAsBI(), rec.getGasPriceAsBI(), rec.getGasLimitAsBI(),
rec.getTo(), rec.getValueAsBI(), rec.getData());
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signedMessage);
log.info("Signe Message with Hex Value: "+hexValue);
//EthSendTransaction ethTrx = web3j.ethSendRawTransaction(hexValue).send();
EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
log.info("Executed transaction "+ethSendTransaction.getTransactionHash());
// poll for transaction response via org.web3j.protocol.Web3j.ethGetTransactionReceipt(<txHash>)
return;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment