Как я могу вызвать функцию контракта из Java?

Есть контракт BizzleTokenSale.

pragma solidity ^0.4.2;

import "./BizzleToken.sol";

contract BizzleTokenSale {

address admin;

BizzleToken public tokenContract;
uint256 public tokenPrice;
uint256 public tokensSold;


event Sell(address _buyer, uint256 _amount);

function BizzleTokenSale(BizzleToken _tokenContract, uint256 _tokenPrice) public {
    admin = msg.sender;
    tokenContract = _tokenContract;
    tokenPrice = _tokenPrice;


}

function multiply(uint x, uint y) internal pure returns (uint z) {

    require(y == 0 || (z = x * y) / y == x);

}

function buyTokens(uint256 _numberOfTokens) public payable {

    // Require that value is equal
    require(msg.value == multiply(_numberOfTokens, tokenPrice));

    // Require token contract has enough tokens
    require(tokenContract.balanceOf(this) >= _numberOfTokens);

    // Require transfer is successfull
    require(tokenContract.transfer(msg.sender, _numberOfTokens));

    // Keep track tokensSold
    tokensSold += _numberOfTokens;

    // track Sell event
    Sell(msg.sender, _numberOfTokens);
}

 function endSale() public {
    require(msg.sender == admin);
    require(tokenContract.transfer(admin, tokenContract.balanceOf(this)));
    admin.transfer(address(this).balance);
}
}

И есть BizzleToken.sol

pragma solidity ^0.4.2;


contract BizzleToken {

string public name = "Bizzle Token";
string public symbol = "BIZ";
string public standart = "Bizzle Token v1.0";
uint256 public totalSupply;

mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;


event Transfer(
    address indexed _from,
    address indexed _to,
    uint256 _value
);

event Approval(
    address indexed _owner,
    address indexed _spender,
    uint256 _value
);

function BizzleToken(uint256 _initialSupply) public {
    balanceOf[msg.sender] = _initialSupply;
    totalSupply = _initialSupply;

}

function transfer(address _to , uint256 _value) public returns (bool success){

    // Exception does not have enough tokens
    require(balanceOf[msg.sender] >= _value);

    balanceOf[msg.sender] -= _value;

    balanceOf[_to] += _value;

    Transfer(msg.sender, _to, _value);


    return true;

}


function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {

     // check _from token balance
    require(_value <= balanceOf[_from]);
     // check allowance is big enough
    require(_value <= allowance[_from][msg.sender]);

    balanceOf[_from] -= _value;
    balanceOf[_to] += _value;

    allowance[_from][msg.sender] -= _value;

    Transfer(_from,_to,_value);

    return true;

}


function approve(address _spender, uint256 _value) public returns (bool success) {

    allowance[msg.sender][_spender] = _value;

    Approval(msg.sender,_spender, _value);

    return true;


}

function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
    return allowance[_owner][_spender];
}

}

Я проверил с помощью JavaScript, он работает.

App = {
web3Provider: null,
contracts: {},
account: '0x0',
loading: false,
tokenPrice: 1000000000000000,
tokensSold: 0,
tokensAvailable: 750000,

init: function() {
console.log("App initialized...")
return App.initWeb3();
},

**/// Buy tokens Function**

buyTokens: function() {
$('#content').hide();
$('#loader').show();
var numberOfTokens = $('#numberOfTokens').val();
App.contracts.BizzleTokenSale.deployed().then(function(instance) {
  return instance.buyTokens(numberOfTokens, {
    from: App.account,
    value: numberOfTokens * App.tokenPrice,
    gas: 500000 // Gas limit
  });
}).then(function(result) {
  console.log("Tokens bought...")
  $('form').trigger('reset') // reset number of tokens in form
  // Wait for Sell event
});

}

Мой вопрос: как я могу подключиться к смарт-контракту с Java?

Вот мой класс Java.

    public TransactionReceipt buyTokens(Uint256 _amount) throws IOException, TransactionException {
    Function function = new Function("buyTokens", Arrays.<Type>asList(_amount), Collections.<TypeReference<?>>emptyList());
    return executeTransaction(function);
    }

Когда я вызываю эту ошибку функции Java, ошибка была в Etherscan.

Эфир не отправляется на смарт-контракт.

Как я могу сделать этот шаг в Java? return instance.buyTokens(numberOfTokens, { from: App.account, value: numberOfTokens * App.tokenPrice, gas: 500000 // Лимит газа });

Ответы (1)

Так как функция payable; вы также можете передать значение.

Без значения функция, кажется, возвращается в этой строке:

function buyTokens(uint256 _numberOfTokens) public payable {

    // Require that value is equal
    require(msg.value == multiply(_numberOfTokens, tokenPrice));

(значение будет равно 0 или нулю)

Попробуйте это в Java:

//Calculate "value" like it is done in JS code that you mentioned. And provide that as parameter.
public TransactionReceipt buyTokens(Uint256 _amount, BigInteger value) throws IOException, TransactionException {
    Function function = new Function("buyTokens", Arrays.<Type>asList(_amount), Collections.<TypeReference<?>>emptyList());
    return executeTransaction(function, value);
    }