web3j contract 使用方法

web3j contract 使用方法

solidity

solc环境
npm install -g solc
web3j环境
brew tap web3j/web3j
brew install web3j
  • 第二步编译合约。得到abi bin。
solc <contract>.sol --bin --abi --optimize -o <output-dir>/

example:
solc erc20_example.sol --bin --abi --optimize -o .
  • 第三步生成java文件。
web3j solidity generate [--javaTypes|--solidityTypes] /path/to/<smart-contract>.bin /path/to/<smart-contract>.abi -o /path/to/src/main/java -p com.your.organisation.name

example:
web3j solidity generate --javaTypes TokenERC20.bin TokenERC20.abi -o . -p TokenERC20.java
  • 第四步使用上一步生成的java文件 创建、调用合约
public class SolSample {
    public static void main(String[] args) {
        deploy();
        use();
    }

    private static void deploy() {
        Web3j web3j = Web3j.build(new HttpService(Environment.RPC_URL));
        Credentials credentials = null;//可以根据私钥生成
        RemoteCall<TokenERC20> deploy = TokenERC20.deploy(web3j, credentials,
                Convert.toWei("10", Convert.Unit.GWEI).toBigInteger(),
                BigInteger.valueOf(3000000),
                BigInteger.valueOf(5201314),
                "my token", "mt");
        try {
            TokenERC20 tokenERC20 = deploy.send();
            tokenERC20.isValid();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void use() {
        Web3j web3j = Web3j.build(new HttpService(Environment.RPC_URL));
        String contractAddress = null;
        Credentials credentials = null;//可以根据私钥生成
        TokenERC20 contract = TokenERC20.load(contractAddress, web3j, credentials,
                Convert.toWei("10", Convert.Unit.GWEI).toBigInteger(),
                BigInteger.valueOf(100000));
        String myAddress = null;
        String toAddress = null;
        BigInteger amount = BigInteger.ONE;
        try {
            BigInteger balance = contract.balanceOf(myAddress).send();
            TransactionReceipt receipt = contract.transfer(toAddress, amount).send();
            //etc..
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/u011181222/article/details/81263615
今日推荐