要部署调用智能合约首先我们要有一个完整的智能合约文件 *.sol
第一步安装solc web3j环境
solc环境
npm install -g solc
web3j环境
brew tap web3j/web3j
brew install web3j
solc <contract>.sol --bin --abi --optimize -o <output-dir>/
example:
solc erc20_example.sol --bin --abi --optimize -o .
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
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();
}
}
}