以太坊客户端安装
我们选择其中一个主流的客户端go-ethereum(Geth)进行安装。以Windows为例:
执行:pkg install go-ethereum
链搭建
以搭建私链为例:
新建目录(eth-pri)
执行启动命令
1
geth --datadir ether-pri --rpcapi="db,eth,net,web3,miner,personal,web3" --http --dev --dev.period 10 --http.corsdomain "https://remix.ethereum.org,http://remix.ethereum.org"
连接客户端
1
geth attach http://localhost:8545
命令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21账号
创建:personal.newAccount()
获取账号:eth.accounts
获取余额:eth.getBalance("sssss")
解锁账号:personal.unlockAccount(user1,password)
挖矿
开始:miner.start()
结束:miner.stop()
设置挖矿奖励用户:miner.setEtherbase(user3)
转账
u1 = eth.accounts[0]
u2 = eth.accounts[1]
eth.sendTransaction({from:u1, to:u2, value:web3.toWei(10, "ether")})
交易前解锁账号
personal.unlockAcount(u1, password)
交易完需要挖矿来确认其他命令操作 可以参考Web3js
合约
合约开发
(合约调用的四种方式](https://blog.csdn.net/TurkeyCock/article/details/83826531)
library:公共代码复用,不允许定义任何storage类型的变量,不能修改合约的状态。
合约编译、部署
Remix
remix访问本地:
- uninstall the old one:
npm uninstall -g remixd - install the new:
npm install -g @remix-project/remixd - share folder:
remixd -s <absolute-path> --remix-ide https://remix.ethereum.org
Truffle
- 初始化truffle项目:
1
2npm init -y
truffle init - solidity安装外部依赖:
1
2// ERC20依赖
npm install @openzeppelin/contracts
合约调试
Buidler内置了Buidler EVM ,这是一个专为开发而设计的以太坊网络。它允许你部署合约,运行测试和调试代码。可以将合约部署到buidler-evm上,调试完再部署到实际使用的链上。
使用步骤:
- 启动(每次启动貌似起个新链,之前部署的合约都不存在了)
npx buidler node - 合约项目下载Buidler依赖
npm install @nomiclabs/buidler - 合约引入console依赖
import "@nomiclabs/buidler/console.sol"; - 使用日志打印
console.log("value:", 11);
注:
支持的solidity版本 < 0.8.0,如果solidity版本>=0.8.0,可以修改console源码,把byte类型相关去除
其他资料:
https://cloud.tencent.com/developer/article/1679411
https://www.blockvalue.com/news/2019100619910.html
前端开发
Demo地址
Vue + Element-Ui + Web3js
- 创建Vue项目
1
2
3
4安装vue:npm install -g vue-cli
初始化vue项目:vue init webpack my-project
安装web3:npm install web3@1.3.1
启动项目:npm run dev
Java调用合约
pom.xml引用
1
2
3
4
5
6
7
8
9
10
11<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>4.8.4</version>
</dependency>
<dependency>
<groupId>org.web3j</groupId>
<artifactId>codegen</artifactId>
<version>4.8.4</version>
</dependency>通过abi文件生成java类
1
2
3
4private static void transformABI() throws Exception {
//org.web3j.codegen.TruffleJsonFunctionWrapperGenerator /path/to/<truffle-smart-contract-output>.json -o /path/to/src/main/java -p com.your.organisation.name
TruffleJsonFunctionWrapperGenerator.main(new String[]{"D:\\developtools\\truffle\\workspace\\truffleTest\\build\\contracts\\GuessVote.json","-o","D:/git/netease-leihuo/ethereum-test/src/main/java","-p","com.cjf.web3j.abi"});
}合约中方法调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31// 默认链接到,或者自己指定 http://localhost:8545/
Web3j web3 = Web3j.build(new HttpService());
//获取链接到的client的版本
Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send();
String clientVersion = web3ClientVersion.getWeb3ClientVersion();
System.out.println(clientVersion);
//获取当前gasprice
EthGasPrice gasPrice = web3.ethGasPrice().send();
BigInteger priceResult = gasPrice.getGasPrice();
System.out.println("current gas price:" + priceResult);
//获取块的gasLimit
EthBlock.Block block = web3.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, false).send().getBlock();
System.out.println("BLOCK GAS LIMIT:" + block.getGasLimit());
StaticGasProvider gasProvider = new StaticGasProvider(priceResult, block.getGasLimit());
//使用私钥创建Credentials
Credentials owner = Credentials.create("****");
//需要指定chainId来创建TransactionManager ,否则交易会因为防重放攻击而无法被执行
TransactionManager transactionManager = new RawTransactionManager(web3, owner, 1337);
//获取一个链上已经存在的合约
GuessVote guessVote = GuessVote.load(GuessVote.getPreviouslyDeployedAddress("1337"), web3, transactionManager, gasProvider);
// 调用合约中的方法
TransactionReceipt s = guessVote.generateVoteResult().send();
System.out.println(s);
MetaMask钱包
MetaMask文档
安装:npm install metamask
1 | // 获取最新区块 |
部署到测试链
币安测试链
注:ip限制,充值不上换代理。
部署测试链步骤:
- 修改truffle-config.jsnetworks增加配置
1
2
3
4const HDWalletProvider = require('@truffle/hdwallet-provider');
const fs = require('fs');
const mnemonic = fs.readFileSync(".secret").toString().trim();1
2
3
4
5
6
7testnet: {
provider: () => new HDWalletProvider(mnemonic, `https://data-seed-prebsc-2-s1.binance.org:8545`),
network_id: 97,
confirmations: 10,
timeoutBlocks: 200,
skipDryRun: true
} - 部署命令
truffle migrate --network testnet
火币测试链
1 | 测试网地址: |
FAQ
- Exception in thread “main” java.lang.UnsupportedOperationException: Unsupported type encountered: tuple
1
https://stackoverflow.com/questions/48877910/how-can-i-return-an-array-of-struct-in-solidity
- 合约多字段返回
java:元组
js:struct[],调用call方法需要传account
参考文档