环境:mac os & android studio
官网:here
以太坊 web3j for java 配置和使用<1>: here
以太坊 web3j for java 使用 - 为用户创建凭证credentials <2>:here
本文还是使用MetaCoin.sol
pragma solidity ^0.4.2;
contract MetaCoin {
mapping (address => uint) balances;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
function MetaCoin() {
balances[tx.origin] = 10000;
}
function sendCoin(address receiver, uint amount) returns(bool sufficient) {
if (balances[msg.sender] < amount) return false;
balances[msg.sender] -= amount;
balances[receiver] += amount;
Transfer(msg.sender, receiver, amount);
return true;
}
function getBalance(address addr) returns(uint) {
return balances[addr];
}
}
solc .sol --bin --abi --optimize -o /
====>生产 .abi 和 .bin 文件
例如,在MetaCoin.sol文件目录下输入:
solc MetaCoin.sol --bin --abi --optimize -o /Users/pro/Desktop
web3j solidity generate [--javaTypes|--solidityTypes] /path/to/.bin /path/to/.abi -o /path/to/src/main/java -p com.your.organisation.name
例如:
然后将生成的 .java文件导入到安卓项目中。
YourSmartContract contract = YourSmartContract.deploy(
, , GAS_PRICE, GAS_LIMIT,
[,]
, ..., ).send();
例如:
MetaCoin contract = MetaCoin.deploy(web3, credentials, GAS_PRICE, GAS_LIMIT).send();
System.out.println(contract.getContractAddress());
或者可以加载已经部署在私有链上面的合约:
YourSmartContract contract = YourSmartContract.load(
"0x|", web3j, credentials, GAS_PRICE, GAS_LIMIT);
例如:
AllBikeShared contract = AllBikeShared.load("0x055a864a5f39f9eecd17e729e2cfc4fb6b12c19b", web3, credentials, GAS_PRICE, GAS_LIMIT);
1.call 的方式,不改变智能合约的状态
Type result = contract.someMethod(, ...).send();
例如:
BigInteger result = contract.getUserCount().send();