新增web3j-maven-plugin
web3j-maven-plugin是一個maven外掛,可以直接將solidity檔案編譯為檔案Java,方便Java開發者直接進行合約的部署,載入,呼叫。
我們直接將該外掛新增到maven的pom.xml檔案中即可。
<plugin>
<groupId>org.web3j</groupId>
<artifactId>web3j-maven-plugin</artifactId>
<version>4.8.7</version>
<configuration>
<!-- 指定Java版智慧合約生成的位置 -->
<packageName>org.newonexd.ethereumclient.smartContract</packageName>
<soliditySourceFiles>
<!-- solidity原始檔放置位置 -->
<directory>src/main/resources/solc</directory>
<includes>
<!-- 只將字尾為.sol的檔案包括進去 -->
<include>**/*.sol</include>
</includes>
</soliditySourceFiles>
<outputDirectory>
<java>src/main/java</java>
</outputDirectory>
</configuration>
</plugin>
具體檔案位置如下圖所示:
編譯solidity檔案到Java檔案
本文以ERC20.sol檔案為例,將該檔案放置在src/main/resources/solc
資料夾內.Erc20.sol檔案將在檔案末尾貼出。
然後開啟命令列定位到當前pom.xml檔案所在資料夾,執行以下命令:
mvn web3j:generate-sources
輸出以下資訊說明編譯成功:
[INFO] Built Class for contract 'ERC20'
[INFO] No abiSourceFiles directory specified, using default directory [src/main/resources]
[INFO] No abiSourceFiles contracts specified, using the default [**/*.json]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.841 s
[INFO] Finished at: 2022-06-26T11:16:47+08:00
[INFO] ------------------------------------------------------------------------
此時在org.newonexd.ethereumclient.smartContract
資料夾中可以看到生成的Java版智慧合約檔案。
與以太坊進行合約互動
部署合約
在以太坊部署合約需要有一個賬戶,我們透過web3j把賬戶載入進來:
private static final Credentials credentials;
static{
//根據私鑰建立Java賬戶類
credentials = Credentials.create("0x534d8d93a5ef66147e2462682bc524ef490898010a1550955314ffea5f0a8959");
}
我們可以根據私鑰載入賬戶,或者web3j提供了其他方案如ECKeyPair進行賬戶的載入。
賬戶載入成功後,我們也可以直接與以太坊互動查詢Ether餘額:
@GetMapping("/ether")
public BigInteger doGetEther()throws Exception{
//獲取最新的區塊號
BigInteger blockNumber = web3j.ethBlockNumber().sendAsync().get().getBlockNumber();
logger.info("The BlockNumber is: {}",blockNumber);
//生成請求引數
DefaultBlockParameterNumber defaultBlockParameterNumber = new DefaultBlockParameterNumber(blockNumber);
//根據請求引數獲取餘額
EthGetBalance ethGetBalance = web3j.ethGetBalance(credentials.getAddress(),defaultBlockParameterNumber)
.sendAsync().get();
logger.info("Get Account Ether is: {}",ethGetBalance.getBalance());
return ethGetBalance.getBalance();
}
接下來我們進行合約在以太坊上面的部署:
ERC20 contract = ERC20.deploy(web3j,credentials, ERC20.GAS_PRICE,ERC20.GAS_LIMIT,coinName, BigInteger.valueOf(coinTotal),symbol).sendAsync().get();
credentials
是我們剛剛載入的賬戶資訊,也是合約部署者,coinName
是合約中Token名稱,coinTotal
為Token發行量,symbol
為Token簡稱。
僅一行程式碼,我們就可以把合約部署到以太坊上面了。
載入合約
部署完成以後,我們可以直接進行合約的呼叫,但不能每次呼叫合約都對合約進行部署一遍,因此web3j提供了載入合約資訊的功能,我們透過合約地址將合約載入到Java程式中,也可以進行合約的呼叫。具體的載入方法如下:
ERC20.load(contractAddress,web3j,credentials,ERC20.GAS_PRICE,ERC20.GAS_LIMIT);
合約載入成功後,我們同樣可以進行合約的呼叫了。
呼叫合約
具體可以呼叫合約哪些功能,則是根據智慧合約中定義的方法而定了,本文僅列出部分幾個功能。
查詢發行量
ERC20 erc20 = loadContract(contractAddress);
BigInteger coinTotal = erc20.totalSupply().sendAsync().get();
查詢指定賬戶地址下Token數量
ERC20 erc20 = loadContract(contractAddress);
BigInteger balance = erc20.balanceOf(accountAddress).sendAsync().get();
轉賬
ERC20 erc20 = loadContract(contractAddress);
TransactionReceipt transactionReceipt = erc20.transfer(contractAddress,BigInteger.valueOf(tokenValue)).sendAsync().get();
授權他人賬戶一定數量的Token
ERC20 erc20 = loadContract(contractAddress);
TransactionReceipt transactionReceipt = erc20.approve(approveAddress,BigInteger.valueOf(tokenValue)).sendAsync().get();
查詢他人授權當前賬戶的Token數量
ERC20 erc20 = loadContract(contractAddress);
BigInteger allowrance = erc20.allowance(credentials.getAddress(),approveAddress).sendAsync().get();
Erc20原始碼
Erc20 token的程式碼在網路上比較容易找到,官方也有提供,這裡列出一份簡單的程式碼:
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
string private _coinName;
string private _symbol;
uint256 private _decimals = 18;
constructor(string coinName,uint256 totalSupply,string symbol)public{
_coinName = coinName;
_symbol = symbol;
_totalSupply = totalSupply * 10 ** uint256(_decimals);
_balances[msg.sender] = _totalSupply;
}
function coinName()public view returns(string){
return _coinName;
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
require(value <= _balances[msg.sender]);
require(to != address(0));
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
require(account != 0);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(account != 0);
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burnFrom(address account, uint256 amount) internal {
require(amount <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
amount);
_burn(account, amount);
}
}
本文原始碼
/**
* @description erc20控制器
* @author newonexd
* @date 2022/6/22 21:44
*/
@RestController
@RequestMapping("erc20")
public class Erc20Controller {
private static final Logger logger = LoggerFactory.getLogger(Erc20Controller.class);
@Autowired
private Web3j web3j;
private static final Credentials credentials;
static{
//根據私鑰建立Java賬戶類
credentials = Credentials.create("0x534d8d93a5ef66147e2462682bc524ef490898010a1550955314ffea5f0a8959");
}
/**
* @description 獲取該賬戶下的Ether總數
* @author newonexd
* @date 2022/6/22 21:34
* @return BigInteger
*/
@GetMapping("/ether")
public BigInteger doGetEther()throws Exception{
//獲取最新的區塊號
BigInteger blockNumber = web3j.ethBlockNumber().sendAsync().get().getBlockNumber();
logger.info("The BlockNumber is: {}",blockNumber);
//生成請求引數
DefaultBlockParameterNumber defaultBlockParameterNumber = new DefaultBlockParameterNumber(blockNumber);
//根據請求引數獲取餘額
EthGetBalance ethGetBalance = web3j.ethGetBalance(credentials.getAddress(),defaultBlockParameterNumber)
.sendAsync().get();
logger.info("Get Account Ether is: {}",ethGetBalance.getBalance());
return ethGetBalance.getBalance();
}
/**
* @description 部署Erc20 合約
* @author newonexd
* @date 2022/6/22 21:34
* @param coinName Erc20Token 名稱
* @param symbol Erc20Token 簡寫
* @param coinTotal 總髮行量
* @return String 合約地址
*/
@PostMapping("/deployErc20")
public String doDeployErc20(@RequestParam(value = "coinName")String coinName,
@RequestParam(value = "symbol")String symbol,
@RequestParam(value = "coinTotal")Long coinTotal)throws Exception{
ERC20 contract = ERC20.deploy(web3j,credentials, ERC20.GAS_PRICE,ERC20.GAS_LIMIT,coinName, BigInteger.valueOf(coinTotal),symbol).sendAsync().get();
logger.info("ERC20 Contract Address: {}",contract.getContractAddress());
return contract.getContractAddress();
}
/**
* @description 查詢總髮行量
* @author newonexd
* @date 2022/6/22 21:35
* @param contractAddress 部署的合約地址
* @return BigInteger 總髮行量
*/
@GetMapping("/coinTotal")
public BigInteger getTotal(@RequestParam(value = "contractAddress")String contractAddress) throws Exception {
ERC20 erc20 = loadContract(contractAddress);
BigInteger coinTotal = erc20.totalSupply().sendAsync().get();
logger.info("CoinTotal is: {}",coinTotal);
return coinTotal;
}
/**
* @description 獲取賬戶下Erc20Token總量
* @author newonexd
* @date 2022/6/22 21:36
* @param contractAddress 合約地址
* @param accountAddress 賬戶地址
* @return BigInteger Erc20Token總量
*/
@GetMapping("/balance")
public BigInteger getBalance(@RequestParam(value = "contractAddress")String contractAddress,
@RequestParam(value = "accountAddress")String accountAddress) throws Exception {
ERC20 erc20 = loadContract(contractAddress);
BigInteger balance = erc20.balanceOf(accountAddress).sendAsync().get();
logger.info("AccountAddress: {} hava Balance: {}",accountAddress,balance);
return balance;
}
/**
* @description 授權他人賬戶地址一定數量的Erc20Token 幣
* @author newonexd
* @date 2022/6/22 21:36
* @param contractAddress 合約地址
* @param approveAddress 被授權的賬戶地址
* @param tokenValue 授權Token總數
* @return String 該筆交易的雜湊值
*/
@PostMapping("/approver")
public String doApprover(@RequestParam(value = "contractAddress")String contractAddress,
@RequestParam(value = "approveAddress")String approveAddress,
@RequestParam(value = "tokenValue")int tokenValue)throws Exception {
ERC20 erc20 = loadContract(contractAddress);
TransactionReceipt transactionReceipt = erc20.approve(approveAddress,BigInteger.valueOf(tokenValue)).sendAsync().get();
boolean result = transactionReceipt.isStatusOK();
String transactionHash = transactionReceipt.getTransactionHash();
logger.info("Approve result: {},TxHash: {}",result,transactionHash);
return transactionHash;
}
/**
* @description 查詢指定地址下被允許消費的Erc20Token數量
* @author newonexd
* @date 2022/6/22 21:37
* @param contractAddress 合約地址
* @param tokenValue token數量
* @return BigInteger 被授權消費的Erc20數量
*/
@PostMapping("/transfer")
public int doPostTransfer(@RequestParam(value = "contractAddress")String contractAddress,
@RequestParam(value = "tokenValue")int tokenValue) throws Exception {
ERC20 erc20 = loadContract(contractAddress);
TransactionReceipt transactionReceipt = erc20.transfer(contractAddress,BigInteger.valueOf(tokenValue)).sendAsync().get();
if(transactionReceipt.isStatusOK()){
logger.info("Transfer token value : {}",tokenValue);
return tokenValue;
}else{
return 0;
}
}
/**
* @description 查詢指定地址下被允許消費的Erc20Token數量
* @author newonexd
* @date 2022/6/22 21:37
* @param contractAddress 合約地址
* @param approveAddress 被授權的賬戶地址
* @return BigInteger 被授權消費的Erc20數量
*/
@GetMapping("/allowrance")
public BigInteger doGetAllowrance(@RequestParam(value = "contractAddress")String contractAddress,
@RequestParam(value = "approveAddress")String approveAddress) throws Exception {
ERC20 erc20 = loadContract(contractAddress);
BigInteger allowrance = erc20.allowance(credentials.getAddress(),approveAddress).sendAsync().get();
logger.info("Allowrance : {}",allowrance);
return allowrance;
}
/**
* @description 根據合約地址載入合約資訊
* @author newonexd
* @date 2022/6/26 11:41
* @param contractAddress 合約地址
* @return ERC20
*/
private ERC20 loadContract(String contractAddress){
return ERC20.load(contractAddress,web3j,credentials,ERC20.GAS_PRICE,ERC20.GAS_LIMIT);
}
}