kandi background
Explore Kits

web3j | Lightweight Java and Android library | Blockchain library

 by   web3j Java Version: v4.9.1 License: Apache-2.0

 by   web3j Java Version: v4.9.1 License: Apache-2.0

Download this library from

kandi X-RAY | web3j Summary

web3j is a Java library typically used in Financial Services, Fintech, Blockchain, Ethereum applications. web3j has no vulnerabilities, it has build file available, it has a Permissive License and it has medium support. However web3j has 62 bugs. You can download it from GitHub, GitLab, Maven.
[![Documentation Status](https://img.shields.io/travis/web3j/web3j-docs?label=docs)](https://docs.web3j.io/) [![Build Status](https://travis-ci.org/web3j/web3j.svg?branch=master)](https://travis-ci.org/web3j/web3j) [![codecov](https://codecov.io/gh/web3j/web3j/branch/master/graph/badge.svg)](https://codecov.io/gh/web3j/web3j) [![Join the chat at https://gitter.im/web3j/web3j](https://img.shields.io/discourse/users?server=https%3A%2F%2Fcommunity.web3labs.com)](https://community.web3labs.com) [![Discord](https://img.shields.io/discord/779382027614158919?label=discord)](https://discord.gg/A9UXfPF2tS).
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • web3j has a medium active ecosystem.
  • It has 3819 star(s) with 1305 fork(s). There are 220 watchers for this library.
  • There were 1 major release(s) in the last 6 months.
  • There are 187 open issues and 814 have been closed. On average issues are closed in 232 days. There are 13 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of web3j is v4.9.1
web3j Support
Best in #Blockchain
Average in #Blockchain
web3j Support
Best in #Blockchain
Average in #Blockchain

quality kandi Quality

  • web3j has 62 bugs (2 blocker, 0 critical, 12 major, 48 minor) and 1833 code smells.
web3j Quality
Best in #Blockchain
Average in #Blockchain
web3j Quality
Best in #Blockchain
Average in #Blockchain

securitySecurity

  • web3j has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • web3j code analysis shows 0 unresolved vulnerabilities.
  • There are 9 security hotspots that need review.
web3j Security
Best in #Blockchain
Average in #Blockchain
web3j Security
Best in #Blockchain
Average in #Blockchain

license License

  • web3j is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
web3j License
Best in #Blockchain
Average in #Blockchain
web3j License
Best in #Blockchain
Average in #Blockchain

buildReuse

  • web3j releases are available to install and integrate.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • Installation instructions, examples and code snippets are available.
  • web3j saves you 23368 person hours of effort in developing the same functionality from scratch.
  • It has 45700 lines of code, 4626 functions and 636 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
web3j Reuse
Best in #Blockchain
Average in #Blockchain
web3j Reuse
Best in #Blockchain
Average in #Blockchain
Top functions reviewed by kandi - BETA

kandi has reviewed web3j and discovered the below as its top functions. This is intended to give you an instant insight into web3j implemented functionality, and help decide if they suit your requirements.

  • Add a constant function .
  • Traverses the data .
  • Make a type reference from a solidity type .
  • Generate static array types .
  • Decodes the input parameters .
  • Create a tuple
  • Compares this tuple with the specified value .
  • Recover from an ECDS signature .
  • This method sends an EIP15 transaction .
  • Decrypts an encrypted key pair .

web3j Key Features

Complete implementation of Ethereum’s [JSON-RPC](https://github.com/ethereum/wiki/wiki/JSON-RPC) client API over HTTP and IPC

Ethereum wallet support

Auto-generation of Java smart contract wrappers to create, deploy, transact with and call smart contracts from native Java code ([Solidity](http://solidity.readthedocs.io/en/latest/using-the-compiler.html#using-the-commandline-compiler) and [Truffle](https://github.com/trufflesuite/truffle-contract-schema) definition formats supported)

Reactive-functional API for working with filters

[Ethereum Name Service (ENS)](https://ens.domains/) support

Support for Parity’s [Personal](https://github.com/paritytech/parity/wiki/JSONRPC-personal-module), and Geth’s [Personal](https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal) client APIs

Support for [Alchemy](https://docs.alchemyapi.io/alchemy/guides/getting-started#web-3-j) and [Infura](https://infura.io/), so you don’t have to run an Ethereum client yourself

Comprehensive integration tests demonstrating a number of the above scenarios

Command line tools

Android compatible

Support for JP Morgan’s Quorum via [web3j-quorum](https://github.com/web3j/quorum)

Support for [EEA Privacy features as described in EEA documentation](https://entethalliance.org/technical-documents/) and implemented in [Hyperledger Besu](https://besu.hyperledger.org/en/latest/Reference/API-Methods/#eea-methods).

[RxJava](https://github.com/ReactiveX/RxJava) for its reactive-functional API

[OKHttp](https://square.github.io/okhttp/) for HTTP connections

[Jackson Core](https://github.com/FasterXML/jackson-core) for fast JSON serialisation/deserialization

[Bouncy Castle](https://www.bouncycastle.org/) ([Spongy Castle](https://rtyley.github.io/spongycastle/) on Android) for crypto

[Jnr-unixsocket](https://github.com/jnr/jnr-unixsocket) for \*nix IPC (not available on Android)

[Java-WebSocket](https://github.com/TooTallNate/Java-WebSocket)

QuickStart

copy iconCopydownload iconDownload
curl -L get.web3j.io | sh && source ~/.web3j/source.sh

Maven

copy iconCopydownload iconDownload
<dependency>
  <groupId>org.web3j</groupId>
  <artifactId>core</artifactId>
  <version>4.8.7</version>
</dependency>

Build instructions

copy iconCopydownload iconDownload
$ ./gradlew check

How to connect Metamask to Web3J (java)

copy iconCopydownload iconDownload
web3.eth.sign(
    web3.utils.sha3(nonce),
    window.userWalletAddress)
.then((message) => {
    console.log(message)
    data['message'] = message // BODY
    var xmlReq = new XMLHttpRequest();
    xmlReq.onreadystatechange = function() {
        if(this.readyState == 4 && this.status == 200) {
            response = this.responseText
            console.log(response)
        }
    };
    xmlReq.open("POST", "/api/users/login", true)
    xmlReq.setRequestHeader('Content-Type', 'application/json')
    xmlReq.send(JSON.stringify(data))
})
public User signin(UserLoginDTO loginDetails, HttpServletResponse response) {
    try {
        // Get the wallet ID and signed message from the body stored in the DTO
        String publicWalletId = loginDetails.getPublicWalletId();
        String message = loginDetails.getMessage();

        // Find the nonce from the DB that was used to sign this message
        User user = userRepository.findByPublicWalletId(publicWalletId);
        String nonce = user.getNonce();

        // Generate the HASH of the Nonce
        byte[] nonceHash = Hash.sha3(nonce.getBytes()) // org.web3j.crypto.Hash

        // Generate the Signature Data
        byte[] signatureBytes = Numeric.hexStringToByteArray(message); // org.web3j.utils.Numeric
        
        byte v = (byte) ((signatureBytes[64] < 27) ? (signatureBytes[64] + 27) : signatureBytes[64]);
        byte[] r = Arrays.copyOfRange(signatureBytes, 0, 32);
        byte[] s = Arrays.copyOfRange(signatureBytes, 32, 64);
        
        SignatureData signatureData = new SignatureData(v, r, s); // org.web3j.crypto.Sign.SignatureData

        // Generate the 4 possible Public Keys
        List<String> recoveredKeys = new ArrayList<>();
        for(int i = 0; i < 4; i++) {
            BigInteger r = new BigInteger(1, signatureData.getR());
            BigInteger s = new BigInteger(1, signatureData.getS());
            ECDSASignature ecdsaSignature = new ECDSASignature(r, s);
            BigInteger recoveredKey = Sign.recoverFromSignature((byte)i, ecdsaSignature, nonceHash);
            if(recoveredKey != null) {
                recoveredKeys.add("0x" + Keys.getAddressFromKey(recoveredKey)); // org.web3j.crypto.Keys
            }
        }

        // Check if one of the generated Keys match the public wallet ID.
        for(String recoveredKey : recoveredKeys) {
            if(recoveredKey.equalsIgnoreCase(publicWalletId)) { 
                // Add Code here to create the JWT and add that to your HttpServletResponse. Not shown here.
                return user;
            }
        }
        throw new CustomException("Message Sign Invalid", HttpStatus.UNAUTHORIZED);
    }
    catch (Exception ex) {
         // Custom Error Handling.
    }
}
-----------------------
web3.eth.sign(
    web3.utils.sha3(nonce),
    window.userWalletAddress)
.then((message) => {
    console.log(message)
    data['message'] = message // BODY
    var xmlReq = new XMLHttpRequest();
    xmlReq.onreadystatechange = function() {
        if(this.readyState == 4 && this.status == 200) {
            response = this.responseText
            console.log(response)
        }
    };
    xmlReq.open("POST", "/api/users/login", true)
    xmlReq.setRequestHeader('Content-Type', 'application/json')
    xmlReq.send(JSON.stringify(data))
})
public User signin(UserLoginDTO loginDetails, HttpServletResponse response) {
    try {
        // Get the wallet ID and signed message from the body stored in the DTO
        String publicWalletId = loginDetails.getPublicWalletId();
        String message = loginDetails.getMessage();

        // Find the nonce from the DB that was used to sign this message
        User user = userRepository.findByPublicWalletId(publicWalletId);
        String nonce = user.getNonce();

        // Generate the HASH of the Nonce
        byte[] nonceHash = Hash.sha3(nonce.getBytes()) // org.web3j.crypto.Hash

        // Generate the Signature Data
        byte[] signatureBytes = Numeric.hexStringToByteArray(message); // org.web3j.utils.Numeric
        
        byte v = (byte) ((signatureBytes[64] < 27) ? (signatureBytes[64] + 27) : signatureBytes[64]);
        byte[] r = Arrays.copyOfRange(signatureBytes, 0, 32);
        byte[] s = Arrays.copyOfRange(signatureBytes, 32, 64);
        
        SignatureData signatureData = new SignatureData(v, r, s); // org.web3j.crypto.Sign.SignatureData

        // Generate the 4 possible Public Keys
        List<String> recoveredKeys = new ArrayList<>();
        for(int i = 0; i < 4; i++) {
            BigInteger r = new BigInteger(1, signatureData.getR());
            BigInteger s = new BigInteger(1, signatureData.getS());
            ECDSASignature ecdsaSignature = new ECDSASignature(r, s);
            BigInteger recoveredKey = Sign.recoverFromSignature((byte)i, ecdsaSignature, nonceHash);
            if(recoveredKey != null) {
                recoveredKeys.add("0x" + Keys.getAddressFromKey(recoveredKey)); // org.web3j.crypto.Keys
            }
        }

        // Check if one of the generated Keys match the public wallet ID.
        for(String recoveredKey : recoveredKeys) {
            if(recoveredKey.equalsIgnoreCase(publicWalletId)) { 
                // Add Code here to create the JWT and add that to your HttpServletResponse. Not shown here.
                return user;
            }
        }
        throw new CustomException("Message Sign Invalid", HttpStatus.UNAUTHORIZED);
    }
    catch (Exception ex) {
         // Custom Error Handling.
    }
}

Interacting With Contract Web3.js

copy iconCopydownload iconDownload
const abi = [{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burnFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}];

Web3js fails to import in Vue3 composition api project

copy iconCopydownload iconDownload
npm i -D @esbuild-plugins/node-globals-polyfill
npm i -D @esbuild-plugins/node-modules-polyfill
import { defineConfig } from 'vite'
import GlobalsPolyfills from '@esbuild-plugins/node-globals-polyfill'
import NodeModulesPolyfills from '@esbuild-plugins/node-modules-polyfill'

export default defineConfig({
  ⋮
  optimizeDeps: {
    esbuildOptions: {
      2️⃣
      plugins: [
        NodeModulesPolyfills(),
        GlobalsPolyfills({
          process: true,
          buffer: true,
        }),
      ],
      3️⃣
      define: {
        global: 'globalThis',
      },
    },
  },
})
import { defineConfig } from 'vite'

export default defineConfig({
  ⋮
  resolve: {
    alias: {
      web3: 'web3/dist/web3.min.js',
    },
  },
})
-----------------------
npm i -D @esbuild-plugins/node-globals-polyfill
npm i -D @esbuild-plugins/node-modules-polyfill
import { defineConfig } from 'vite'
import GlobalsPolyfills from '@esbuild-plugins/node-globals-polyfill'
import NodeModulesPolyfills from '@esbuild-plugins/node-modules-polyfill'

export default defineConfig({
  ⋮
  optimizeDeps: {
    esbuildOptions: {
      2️⃣
      plugins: [
        NodeModulesPolyfills(),
        GlobalsPolyfills({
          process: true,
          buffer: true,
        }),
      ],
      3️⃣
      define: {
        global: 'globalThis',
      },
    },
  },
})
import { defineConfig } from 'vite'

export default defineConfig({
  ⋮
  resolve: {
    alias: {
      web3: 'web3/dist/web3.min.js',
    },
  },
})
-----------------------
npm i -D @esbuild-plugins/node-globals-polyfill
npm i -D @esbuild-plugins/node-modules-polyfill
import { defineConfig } from 'vite'
import GlobalsPolyfills from '@esbuild-plugins/node-globals-polyfill'
import NodeModulesPolyfills from '@esbuild-plugins/node-modules-polyfill'

export default defineConfig({
  ⋮
  optimizeDeps: {
    esbuildOptions: {
      2️⃣
      plugins: [
        NodeModulesPolyfills(),
        GlobalsPolyfills({
          process: true,
          buffer: true,
        }),
      ],
      3️⃣
      define: {
        global: 'globalThis',
      },
    },
  },
})
import { defineConfig } from 'vite'

export default defineConfig({
  ⋮
  resolve: {
    alias: {
      web3: 'web3/dist/web3.min.js',
    },
  },
})
-----------------------
export default defineConfig({
  // ...
  define: {
    'process.env': process.env
  }
})
-----------------------
window.process = {
  ...window.process,
};

Smart Contract could transfer ether to an address, but the balance of that address does not update

copy iconCopydownload iconDownload
await contract.methods.pickWinner().call();

How do I connect to an Infura web socket in Ethers.js?

copy iconCopydownload iconDownload
const provider = new ethers.providers.WebSocketProvider(
  "wss://mainnet.infura.io/ws/v3/<project_id>"
)
// Using a test network
const provider = new ethers.providers.WebSocketProvider(
  "wss://rinkeby.infura.io/ws/v3/<project_id>", "rinkeby"
)
-----------------------
const provider = new ethers.providers.WebSocketProvider(
  "wss://mainnet.infura.io/ws/v3/<project_id>"
)
// Using a test network
const provider = new ethers.providers.WebSocketProvider(
  "wss://rinkeby.infura.io/ws/v3/<project_id>", "rinkeby"
)

How to get a contract by a transaction uising web3j?

copy iconCopydownload iconDownload
const Web3 = require("web3");
const web3 = new Web3("<provider_url>");

// keccak256 of string "Transfer(address,address,uint256)"
const TRANSFER_SIGNATURE = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";

async function run() {
    const txHash = "0xfb4dc20b4a8d0b72442a396aced0fc537de757c6aac69609ab3d09d19f9c9aa8";
    const txReceipt = await web3.eth.getTransactionReceipt(txHash);

    for (let log of txReceipt.logs) {
        if (_isERC20Log(log)) {
            // Unindexed topics are concatenated in the `data` field.
            // There's only one unindexed topic in this case,
            // so you don't need to do any parsing and just use the whole value.
            const amount = web3.utils.hexToNumberString(log.data);
            console.log("ERC20 token amount: ", amount);
            console.log("ERC20 token contract: ", log.address);
        } else if (_isERC721Log(log)) {
            // 3rd indexed topic
            // index 0 of the array is the event signature, see `_isERC721Log()`
            const tokenId = web3.utils.hexToNumberString(log.topics[3]);
            console.log("ERC721 token ID: ", tokenId);
            console.log("ERC721 token contract: ", log.address);
        }
    }
}

function _isERC20Log(log) {
    return (
        log.topics[0] == TRANSFER_SIGNATURE
        && log.topics.length == 3 // index 0 is the signature, and then 2 indexed topics
    );
}

function _isERC721Log(log) {
    return (
        log.topics[0] == TRANSFER_SIGNATURE
        && log.topics.length == 4 // index 0 is the signature, and then 3 indexed topics
    );
}

run();
ERC20 token amount:  40000000000000000000
ERC20 token contract:  0x54a7cee7B02976ACE1bdd4aFad87273251Ed34Cf
ERC721 token ID:  12013
ERC721 token contract:  0x41cB4a771FdD019ADBF4685bd4885fbBeedE1784
-----------------------
const Web3 = require("web3");
const web3 = new Web3("<provider_url>");

// keccak256 of string "Transfer(address,address,uint256)"
const TRANSFER_SIGNATURE = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";

async function run() {
    const txHash = "0xfb4dc20b4a8d0b72442a396aced0fc537de757c6aac69609ab3d09d19f9c9aa8";
    const txReceipt = await web3.eth.getTransactionReceipt(txHash);

    for (let log of txReceipt.logs) {
        if (_isERC20Log(log)) {
            // Unindexed topics are concatenated in the `data` field.
            // There's only one unindexed topic in this case,
            // so you don't need to do any parsing and just use the whole value.
            const amount = web3.utils.hexToNumberString(log.data);
            console.log("ERC20 token amount: ", amount);
            console.log("ERC20 token contract: ", log.address);
        } else if (_isERC721Log(log)) {
            // 3rd indexed topic
            // index 0 of the array is the event signature, see `_isERC721Log()`
            const tokenId = web3.utils.hexToNumberString(log.topics[3]);
            console.log("ERC721 token ID: ", tokenId);
            console.log("ERC721 token contract: ", log.address);
        }
    }
}

function _isERC20Log(log) {
    return (
        log.topics[0] == TRANSFER_SIGNATURE
        && log.topics.length == 3 // index 0 is the signature, and then 2 indexed topics
    );
}

function _isERC721Log(log) {
    return (
        log.topics[0] == TRANSFER_SIGNATURE
        && log.topics.length == 4 // index 0 is the signature, and then 3 indexed topics
    );
}

run();
ERC20 token amount:  40000000000000000000
ERC20 token contract:  0x54a7cee7B02976ACE1bdd4aFad87273251Ed34Cf
ERC721 token ID:  12013
ERC721 token contract:  0x41cB4a771FdD019ADBF4685bd4885fbBeedE1784

Unable to access process variable in Vue3JS Vite project

copy iconCopydownload iconDownload
VITE_WEB3_STORAGE_TOKEN="your_token"
console.log(import.meta.env.VITE_WEB3_STORAGE_TOKEN) // "your_token"
-----------------------
VITE_WEB3_STORAGE_TOKEN="your_token"
console.log(import.meta.env.VITE_WEB3_STORAGE_TOKEN) // "your_token"

Solidity transaction with an unsigned transaction object

copy iconCopydownload iconDownload
pragma solidity ^0.8;

contract MyContract {
    function foo() external {
        address to = payable(address(0x0));
        bytes memory sendData = new bytes(12); // empty 12 byte array
        to.call{value: 1000000000000, gas: 163502}(sendData);
    }
}

How to get tokens transferred in transaction details using web3 js?

copy iconCopydownload iconDownload
const abiJson = [
    {"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"}
];

const contract = new web3.eth.Contract(abiJson, log.address);
const symbol = await contract.methods.symbol().call();

Why am I getting &quot;Error processing transaction request: intrinsic gas too low&quot; error when trying to add tUSDT to a particular account?

copy iconCopydownload iconDownload
final String aliceAddress = ALICE.getAddress();
final String bobAddress = BOB.getAddress();
ContractGasProvider contractGasProvider = new DefaultGasProvider();
HumanStandardToken contract =
        HumanStandardToken.deploy(
                        web3j,
                        ALICE,
                        contractGasProvider,
                        aliceQty,
                        "web3j tokens",
                        BigInteger.valueOf(18),
                        "w3j$")
                .send();

//...

// set an allowance
assertEquals(contract.allowance(aliceAddress, bobAddress).send(), (BigInteger.ZERO));

transferQuantity = BigInteger.valueOf(50);
TransactionReceipt approveReceipt =
        contract.approve(BOB.getAddress(), transferQuantity).send();

HumanStandardToken.ApprovalEventResponse approvalEventValues =
        contract.getApprovalEvents(approveReceipt).get(0);

assertEquals(approvalEventValues._owner, (aliceAddress));
assertEquals(approvalEventValues._spender, (bobAddress));
assertEquals(approvalEventValues._value, (transferQuantity));

assertEquals(contract.allowance(aliceAddress, bobAddress).send(), (transferQuantity));

// perform a transfer as Bob
transferQuantity = BigInteger.valueOf(25);

// Bob requires his own contract instance
HumanStandardToken bobsContract =
        HumanStandardToken.load(
                contract.getContractAddress(), web3j, BOB, STATIC_GAS_PROVIDER);

TransactionReceipt bobTransferReceipt =
        bobsContract.transferFrom(aliceAddress, bobAddress, transferQuantity).send();

HumanStandardToken.TransferEventResponse bobTransferEventValues =
        contract.getTransferEvents(bobTransferReceipt).get(0);
assertEquals(bobTransferEventValues._from, (aliceAddress));
assertEquals(bobTransferEventValues._to, (bobAddress));
assertEquals(bobTransferEventValues._value, (transferQuantity));

//...

Community Discussions

Trending Discussions on web3j
  • ERC20 transferFrom() private key with web3js and metamask
  • How to connect Metamask to Web3J (java)
  • Intellij 2021.3.2, JavaFX Maven project not resolving dependencies correctly
  • Interacting With Contract Web3.js
  • Web3js fails to import in Vue3 composition api project
  • web3js Uniswap handle event log data
  • Smart Contract could transfer ether to an address, but the balance of that address does not update
  • How do I connect to an Infura web socket in Ethers.js?
  • How to get a contract by a transaction uising web3j?
  • Unable to access process variable in Vue3JS Vite project
Trending Discussions on web3j

QUESTION

ERC20 transferFrom() private key with web3js and metamask

Asked 2022-Apr-17 at 03:37

I used the standard IERC20 to create an ERC20 smart contract.

I made a gambling game, that if the current user loses, he/she will have to transfer one token to the dealer (also the deployer aka msg.sender of the smart contract).

With the scenario above, I think that transferFrom("CURRENT_USER_PRIVATEKEY", "DEPLOYER_PUBLICKEY", 1) should be the answer.

However, with web3js and and metamask, I'm not sure how to get the "CURRENT_USER_PRIVATEKEY", since Metamask won't allow web3js to get the private key. In other StackOverflow posts, I found that we can hardcode this privatekey, but it's not ideal for a system with several users. What should I do to execute this transferFrom() function?

Here is my smart contract and code for the transaction:

async playerLoseMoney(){
    // Transfer money from player to the dealer
    const AMOUNT = 1;
    try{
      const contract = await this.getContract(erc20_abi_json);
      const computerChoice = await contract.methods.TransferFrom(
        "0x8a2a3a1dacF2B4b57734eB3DB71c33d3EBe263B6",
        "0xc00432E08770B9be73fB2303203B407d7B2E2cf2",
        AMOUNT
      ).call();
      alert("You lose 1 coin!")
    }catch(err){
      alert(err.stack);
      window.location.reload(); 
    }
  }
contract ERC20Token is IERC20 {
    ....
    function transferFrom(address owner, address buyer, uint256 numTokens) public returns(bool){
        require(numTokens <= balances[owner]);
        require(numTokens <= allowed[owner][msg.sender]);

        balances[owner] = balances[owner].sub(numTokens);
        allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens);
        balances[buyer] = balances[buyer].add(numTokens);
        emit Transfer(owner, buyer, numTokens);
        return true;
    }
}

ANSWER

Answered 2022-Apr-17 at 03:09

Private key gives you control of that account. So instead of using private key, erc20 implements allowance and approve. I explained them here: what approve and allowance methods are really doing in ERC20 Standard?

Basically your account address is allowing contract address for a specified token amount to be withdrawn.

So instead of passing private key, you should be passing the public address

Source https://stackoverflow.com/questions/71893853

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install web3j

The simplest way to start your journey with Web3j is to create a project. We provide this functionality using the [Web3j CLI](http://docs.web3j.io/latest/command_line_tools/). This latter can be installed as follows:.
Web3j includes integration tests for running against a live Ethereum client. If you do not have a client running, you can exclude their execution as per the below instructions.
registry.username
registry.password

Support

Commercial support and training is available from [web3labs.com](https://www.web3labs.com/web3j-sdk).

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Share this Page

share link
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.