编程语言
首页 > 编程语言> > 使用Java+Web3j和Ethereum网络交互(二):部署ERC20并调用合约功能

使用Java+Web3j和Ethereum网络交互(二):部署ERC20并调用合约功能

作者:互联网

添加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);
    }
}

标签:contractAddress,BigInteger,Java,uint256,Web3j,Ethereum,address,return,ERC20
来源: https://www.cnblogs.com/cbkj-xd/p/16413245.html