NFT + JAVA + 可更新合约

1 篇文章 0 订阅
1 篇文章 0 订阅

前言

合约部署参考:hardhat

合约开发参考:openzeppelin

钱包:metamask

部署链使用的是:sepolia

合约生成Java:solc

合约部署和测试自行处理

1. 合约

合约代码:ZhuZiNFTU.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";


contract ZhuZiNFTU is ERC721URIStorageUpgradeable {
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIds;

	function initialize() initializer public {
        __ERC721_init("ZhuZiUNFT", "ZZU");
		
	}

    function awardItem(address player, string memory tokenURI)
        public
        returns (uint256)
    {
        uint256 newItemId = _tokenIds.current();
        _mint(player, newItemId);
        _setTokenURI(newItemId, tokenURI);

        _tokenIds.increment();
        return newItemId;
    }
	
	
	function turl(uint256 tokenId) public view returns (string memory) {
        return tokenURI(tokenId);
    }
}

2. 合约生成Java文件

## 安装
npm install solc@0.4.26

## 生成 bin abi文件
cd node_modules/
./solc/solcjs ../contracts/ZhuZiNFTU.sol --bin --abi --optimize -o ../java/

## 转为java文件
cd ../
web3j generate solidity -b java/___contracts_ZhuZiNFTU_sol_ZhuZiNFTU.bin  -a java/___contracts_ZhuZiNFTU_sol_ZhuZiNFTU.abi -o java/  -p com.test

3. 调用Java操作Nft

package com.demo.web3.test;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.RawTransactionManager;
import org.web3j.tx.TransactionManager;
import org.web3j.tx.gas.ContractGasProvider;
import org.web3j.tx.gas.StaticGasProvider;
import org.web3j.utils.Convert;

import com.demo.web3.test3.Web3Util;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class DemoZZU {
	static Credentials credentials = null;
    // sepolia 服务地址
	static Web3j web3j = Web3j.build(new HttpService("https://sepolia.infura.io/v3/"));
	// 私钥
	static String privateKey = "";

	private static void init() {
		try {
			credentials = Web3Util.getCredentials(privateKey);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
		init();
		// 合约地址
		String contractAddress = "0xBC43ACbDf62eeC2915035680d34c5B1Ac6D2B151";
		// 钱包地址
		String address1 = "0x5B42212e35702d336d63E20c30B9084919be5078";
		balanceOf(contractAddress, address1);
		
		String url = "https://storage.googleapis.com/opensea-prod.appspot.com/puffs/1.png";
		createNftByUrl(contractAddress, address1, url);
		url = "https://storage.googleapis.com/opensea-prod.appspot.com/puffs/2.png";
		createNftByUrl(contractAddress, address1, url);
		url = "https://storage.googleapis.com/opensea-prod.appspot.com/puffs/3.png";
		createNftByUrl(contractAddress, address1, url);
		
		balanceOf(contractAddress, address1);
	}
	
	public static void createNftByUrl(String contractAddress, String player, String url) throws Exception {
		JsonObject json = new JsonObject();
		json.addProperty("image", url);
		json.addProperty("name", "Opensea zhuzi Creatures");
		json.addProperty("description", "zhuzi Counters");
		JsonArray attributes = new JsonArray();
		JsonObject n = new JsonObject();
		n.addProperty("n", "yyyd");
		attributes.add(n);
//		json.add("attributes", attributes);
		
		String t = json.toString();

		t = "data:application/json;utf8," + t;
		System.out.println(t);
		createNft(contractAddress, player, t);
	}
	
	public static void createNft(String contractAddress, String player, String tokenURI) throws Exception {
		___contracts_ZhuZiNFTU_sol_ZhuZiNFTU zz = getZz(contractAddress);
		TransactionReceipt t = zz.awardItem(player, tokenURI).send();
		System.out.println("nft: " + t);
		System.out.println("tokenid: " + getTokenId(t));
	}
	
	
	
	private static BigInteger getTokenId(TransactionReceipt t) {
		try {
			List<String> ts = t.getLogs().get(0).getTopics();
			return toBigInteger(ts.get(ts.size()-1));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static BigInteger toBigInteger(String str) {
		try {
			if(str.startsWith("0x")) {
				return new BigInteger(""+Integer.parseInt(str.replace("0x", ""), 16));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static ___contracts_ZhuZiNFTU_sol_ZhuZiNFTU getZz(String contractAddress) throws Exception {
		TransactionManager transactionManager = getRawTransactionManager();
		ContractGasProvider contractGasProvider = getContractGasProvider();
		___contracts_ZhuZiNFTU_sol_ZhuZiNFTU zz = ___contracts_ZhuZiNFTU_sol_ZhuZiNFTU.load(contractAddress, web3j,
				transactionManager, contractGasProvider);
		return zz;
	}
	
	private static void balanceOf(String contractAddress, String account) throws Exception {
		___contracts_ZhuZiNFTU_sol_ZhuZiNFTU zz = getZz(contractAddress);
		EthGetBalance balance = web3j.ethGetBalance(account, DefaultBlockParameterName.LATEST).send();
		BigDecimal balanceVaue = Convert.fromWei(balance.getBalance().toString(), Convert.Unit.ETHER);
		System.out.println("balance: " + balanceVaue.toString());
		
		BigInteger b = zz.balanceOf(account).send();
		System.out.println("nft balanceOf: " + b.longValue());
	}


	private static TransactionManager getRawTransactionManager() throws IOException {
		return getRawTransactionManager(credentials);
	}
	
	private static TransactionManager getRawTransactionManager(Credentials credentials) throws IOException {
		BigInteger chainId = web3j.ethChainId().send().getChainId();
		return new RawTransactionManager(web3j, credentials, chainId.longValue());
	}

	private static ContractGasProvider getContractGasProvider() {
		return new StaticGasProvider(BigInteger.valueOf(22_000_000_000l), BigInteger.valueOf(6_700_000l));
	}
}

4. 效果

查看链信息:https://sepolia.etherscan.io/address/0xBC43ACbDf62eeC2915035680d34c5B1Ac6D2B151

添加并查看钱包:

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值