步骤1: 安装brew
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
步骤2: 安装solc
brew install solidity
步骤3: 下载web3j并下载依赖包
可以从 web3j Releases 下载 web3j 的依赖包。
步骤4: 转换ntf文件成abi和bin
solc --bin GylsYnNFT.sol -o ./output
solc --abi GylsYnNFT.sol -o ./output
步骤5: 使用web3j将abi和bin转换成Java文件
在下载好的web3j的bin下面进行调用
web3j solidity generate /path/to/yourContract.bin /path/to/yourContract.abi -o /path/to/outputDirectory -p com.example.contract
步骤6: 调用代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.tx.Transfer;
import org.web3j.utils.Convert;
import java.math.BigDecimal;
/**
* @author : vanadic@me.com
*/
@Service
public class NFTContractService {
@Autowired
private Web3j web3j;
// 智能合约地址
private static final String CONTRACT_ADDRESS = "";
// 钱包文件路径和密码
private static final String WALLET_FILE = "";
private static final String WALLET_PASSWORD = "";
// 用于与智能合约交互的示例方法
public String interactWithSmartContract() {
try {
// 从钱包文件加载凭证
Credentials credentials = WalletUtils.loadCredentials(WALLET_PASSWORD, WALLET_FILE);
// 构造智能合约对象
YourSmartContract contract = YourSmartContract.load(CONTRACT_ADDRESS, web3j, credentials, ManagedTransaction.GAS_PRICE, Contract.GAS_LIMIT);
// 调用智能合约的某个方法
TransactionReceipt transactionReceipt = contract.someMethod().send();
// 获取交易的哈希值
String transactionHash = transactionReceipt.getTransactionHash();
return "Transaction Hash: " + transactionHash;
} catch (Exception e) {
e.printStackTrace();
return "Error interacting with smart contract";
}
}
// 用于向指定地址发送以太币的示例方法
public String sendEther(String toAddress, BigDecimal amount) {
try {
// 从钱包文件加载凭证
Credentials credentials = WalletUtils.loadCredentials(WALLET_PASSWORD, WALLET_FILE);
// 发送以太币
TransactionReceipt transactionReceipt = Transfer.sendFunds(
web3j, credentials, toAddress, amount, Convert.Unit.ETHER).send();
// 获取交易的哈希值
String transactionHash = transactionReceipt.getTransactionHash();
return "Transaction Hash: " + transactionHash;
} catch (Exception e) {
e.printStackTrace();
return "Error sending ether";
}
}
}