5

I would like to use web3j and to execute the functions of contracts that are found on Binance Smart Chain. How is this done ?

Would it be just

Web3j web3 = Web3j.build(new HttpService("https://bsc-dataseed.binance.org/"))

Then, how do I set the chain ID to 0x38 ?

3
  • 2
    The chain id is needed when u sign a transaction, when you init the transaction manger , there is a param called chainId of type Long
    – Majd TL
    Commented Apr 17, 2021 at 22:43
  • 1
    github.com/web3j/web3j/blob/master/core/src/main/java/org/web3j/… there are other types to transaction managers , u can also use raw transaction without manager and give the chain id in the sign method, I can provide an example but in about 12 h
    – Majd TL
    Commented Apr 17, 2021 at 22:49
  • 1
    @MajdTL Please provide an example, if not for me, then for others who are looking for answers. Thank you! Commented Apr 17, 2021 at 23:22

1 Answer 1

7

If you are using the smart contact wrapper then you usually need to give one of the available transaction managers as a parameter and then give the chain Id when you initialize it

Web3j web3 = Web3j.build(new HttpService("https://bsc-dataseed.binance.org/"));
long chainId = 56;
FastRawTransactionManager txMananger = new FastRawTransactionManager(web3, <your-credentials-instance>, chainId);
MyContract contract = new MyContract(<address of contract>, web3, txManager, new DefaultGasProvider());
contract.transfer(........);

if you are not using the web3j wrapper and build your transaction manually then:

Web3j web3 = Web3j.build(new HttpService("https://bsc-dataseed.binance.org/"));
long chainId = 56;
RawTransaction rawTransaction = RawTransaction.createTransaction(<address-nonce>, <gas price as big integer>, <gas limit as big integer>, <contract address>, <endcoded function of contract>);
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId , <you Credentials>);
String hexValue = Numeric.toHexString(signedMessage);
EthSendTransaction transactionResponse = web3 .ethSendRawTransaction(hexValue).sendAsync().get();
1
  • 1
    Thank you. (some characters to fill in the necessary length to add a comment) Commented Apr 18, 2021 at 22:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.