Java智能合约代码分享

public class HelloWorldContract extends Contract implements HelloWorldInterface {

    // https://remix.ethereum.org/ Compile - Details - WEB3DEPLOY - data
    private static final String BINARY = "0x6060604052341561000f57600080fd5b60d38061001d6000396000f3006060604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806360fe47b114604e5780636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c60048080359060200190919050506094565b005b3415607857600080fd5b607e609e565b6040518082815260200191505060405180910390f35b8060008190555050565b600080549050905600a165627a7a72305820b287ea3878f6f6cc6e7e3885be10bd9172b2074fbdc32fbfc8f7edd3f683e8d90029";

    /**
     * HelloWorld合约
     *
     * @param contractAddress 合约地址
     * @param web3j           RPC请求
     * @param credentials     钱包凭证
     * @param gasPrice        GAS价格
     * @param gasLimit        GAS上限
     */
    private HelloWorldContract(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice,
                               BigInteger gasLimit) {
        super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);
    }

    /**
     * 部署合约
     *
     * @param web3j       RPC请求
     * @param credentials 钱包凭证
     * @param gasPrice    GAS价格
     * @param gasLimit    GAS上限
     * @return
     */
    public static RemoteCall<HelloWorldContract> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
        // 构造函数参数 NULL
        String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.<Type>asList());
        return deployRemoteCall(HelloWorldContract.class, web3j, credentials, gasPrice, gasLimit, BINARY, encodedConstructor);
    }

    /**
     * 加载合约
     *
     * @param contractAddress 合约地址
     * @param web3j           RPC请求
     * @param credentials     钱包凭证
     * @param gasPrice        GAS价格
     * @param gasLimit        GAS上限
     * @return
     */
    public static HelloWorldContract load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
        return new HelloWorldContract(contractAddress, web3j, credentials, gasPrice, gasLimit);
    }

    /**
     * get
     */
    public RemoteCall<Uint256> get() {
        Function function = new Function("get", Arrays.<Type>asList(),
                Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {
                }));
        return executeRemoteCallSingleValueReturn(function);
    }

    /**
     * set
     */
    public RemoteCall<TransactionReceipt> set(int x) {
        Function function = new Function("set", Arrays.<Type>asList(new Uint256(x)),
                Arrays.<TypeReference<?>>asList());
        return executeRemoteCallTransaction(function);
    }
}
package com.redhat.helloworld.contract;

import com.redhat.helloworld.util.Consts;
import org.web3j.abi.datatypes.generated.Uint256;
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.protocol.http.HttpService;

/**
 * @author littleredhat
 * <p>
 * 部署合约方式:
 * 一、wallet 部署
 * 二、geth 部署
 * 三、web3j 部署
 */
public class HelloWorldMain {

    public static void main(String[] args) throws Exception {
        // 获取凭证
        Credentials credentials = WalletUtils.loadCredentials(Consts.PASSWORD, Consts.PATH);
        System.out.println("getCredentialsAddress : " + credentials.getAddress());

        // defaults to http://localhost:8545/
        Web3j web3j = Web3j.build(new HttpService());

        // 部署合约
        // HelloWorldContract contract = HelloWorldContract.deploy(web3j, credentials,
        //         Consts.GAS_PRICE, Consts.GAS_LIMIT).send();
        // System.out.println("getContractAddress : " + contract.getContractAddress());

        // 加载合约
        HelloWorldContract contract = HelloWorldContract.load(Consts.HELLOWORLD_ADDR, web3j, credentials,
                Consts.GAS_PRICE, Consts.GAS_LIMIT);
        System.out.println("getContractAddress : " + contract.getContractAddress());

        // 同步请求方式 //
        // set
        TransactionReceipt transactionReceipt = contract.set(10000).send();
        System.out.println("waiting..."); // 进入阻塞
        System.out.println("set : " + transactionReceipt.getTransactionHash());
        // get
        Uint256 result = contract.get().send();
        System.out.println("waiting..."); // 进入阻塞
        System.out.println("get : " + result.getValue().intValue());

        // 异步请求方式 //
        // set
        /*
        CompletableFuture<TransactionReceipt> transactionReceiptAsync = contract.set(10000).sendAsync();
        System.out.println("waiting..."); // 马上返回
        System.out.println("set : " + transactionReceiptAsync.get().getTransactionHash());
        */
        // get
        /*
        CompletableFuture<Uint256> resultAsync = contract.get().sendAsync();
        System.out.println("waiting..."); // 马上返回
        System.out.println("get : " + resultAsync.get().getValue().intValue());
        */
    }
}
  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然可以!以下是一个示例代码,演示如何使用Java调用智能合约进行买卖交易: 首先,您需要通过Web3j库与以太坊网络进行交互。确保已在项目中导入Web3j库的依赖。 ```java import org.web3j.crypto.Credentials; import org.web3j.crypto.WalletUtils; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.RemoteCall; import org.web3j.protocol.core.methods.response.TransactionReceipt; import org.web3j.protocol.http.HttpService; import org.web3j.tx.Contract; import org.web3j.tx.ManagedTransaction; import java.math.BigInteger; public class SmartContractExample { // 合约地址 private static final String CONTRACT_ADDRESS = "0x1234567890abcdef..."; // 发送者地址 private static final String SENDER_ADDRESS = "0xabcdef1234567890..."; // 发送者私钥 private static final String SENDER_PRIVATE_KEY = "abcdef1234567890..."; public static void main(String[] args) { // 连接以太坊节点 Web3j web3j = Web3j.build(new HttpService("http://localhost:8545")); try { // 加载发送者的凭据 Credentials credentials = WalletUtils.loadCredentials("", SENDER_PRIVATE_KEY); // 加载智能合约 MyContract contract = MyContract.load(CONTRACT_ADDRESS, web3j, credentials, ManagedTransaction.GAS_PRICE, Contract.GAS_LIMIT); // 调用合约方法进行买卖交易 BigInteger quantityToBuy = BigInteger.valueOf(10); // 要购买的数量 BigInteger priceToBuy = BigInteger.valueOf(100); // 购买价格 RemoteCall<TransactionReceipt> buyTransaction = contract.buy(quantityToBuy, priceToBuy); TransactionReceipt buyReceipt = buyTransaction.send(); // 检查交易是否成功 if (buyReceipt.isStatusOK()) { System.out.println("交易成功!交易哈希: " + buyReceipt.getTransactionHash()); } else { System.out.println("交易失败!"); } } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码示例使用Web3j库连接到以太坊网络,并使用发送者的地址和私钥加载凭据。然后,它加载智能合约并调用合约的`buy`方法,传递要购买的数量和价格。最后,它检查交易是否成功,并打印相应的结果。 请确保将`CONTRACT_ADDRESS`、`SENDER_ADDRESS`和`SENDER_PRIVATE_KEY`替换为相应的值,以及调整Web3j连接的URL和智能合约的方法和参数。 这只是一个简单的示例,实际的智能合约调用可能会更复杂,需要根据您的智能合约的具体情况做出调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值