前面我們介紹了以太坊私有鏈的搭建以及多節點私有鏈網絡,這次我們介紹如何使用truffle框架來部署編譯智能合約到我們之前搭建的私有鏈網絡中。
搭建環境及需使用的工具:ubuntu18.04 Truffle v5.0.18 geth 1.8.27 Node v10.16.0
solc 0.5.8+commit.23d335f2.Linux.g++
在我們部署一個簡單的合約之前,我們先介紹一些相關的知識。
一、geth 啟動節點參數介紹
geth 當中有許多指令,因為之后私有鏈節點啟動需要設置一些參數,我們重點介紹這些:
參數 | 參數詳解 |
datadir | 指明當前區塊鏈私鑰和網絡數據存放的位置 |
rpc | 開啟http-rpc服務,可以進行智能合約的部署和調試 |
rpcaddr | 指定http-rpc服務監聽地址,默認為"localhost" |
rpcport | 指定http-rpc服務監聽端口,默認為8545 |
rpccorsdomain | 表示任何鏈接都可以連接到此節點 |
rpcapi | 設置允許連接的rpc的客戶端,一般為db,eth,net,web3 |
nodiscover | 關閉自動連接節點,但是可以手動添加節點,在搭建私有鏈的時候,為避免其他節點連入私有鏈,可以使用該命令 |
maxpeers | 設置允許最大連節點數,默認25 |
networkid | 指定以太坊網絡id,共有鏈為1,測試鏈為3,默認啟動1 |
port | 指定以太坊網絡監聽端口,默認為30303 |
mine | 開啟挖礦,默認為cpu挖礦 |
minerthreads | 挖礦占用cpu線程數,默認為4,現命名為miner.threads |
etherbase | 指定礦工賬號 |
console | 啟動命令行模式,可以在geth中執行命令 |
我們可以在終端輸入geth -v來查看geth的全部指令
1 milo@milo-K46CB:~$ geth -v 2 Incorrect Usage. flag provided but not defined: -v 3 4 NAME: 5 geth - the go-ethereum command line interface 6 7 Copyright 2013-2018 The go-ethereum Authors 8 9 USAGE: 10 geth [options] command [command options] [arguments...] 11 12 VERSION: 13 1.8.27-stable-4bcc0a37 14 15 COMMANDS: 16 account Manage accounts 17 attach Start an interactive JavaScript environment (connect to node) 18 bug opens a window to report a bug on the geth repo 19 console Start an interactive JavaScript environment 20 copydb Create a local chain from a target chaindata folder 21 dump Dump a specific block from storage 22 dumpconfig Show configuration values 23 export Export blockchain into file 24 export-preimages Export the preimage database into an RLP stream 25 import Import a blockchain file 26 import-preimages Import the preimage database from an RLP stream 27 init Bootstrap and initialize a new genesis block 28 js Execute the specified JavaScript files 29 license Display license information 30 makecache Generate ethash verification cache (for testing) 31 makedag Generate ethash mining DAG (for testing) 32 monitor Monitor and visualize node metrics 33 removedb Remove blockchain and state databases 34 version Print version numbers 35 wallet Manage Ethereum presale wallets 36 help, h Shows a list of commands or help for one command 37 38 ETHEREUM OPTIONS: 39 --config value TOML configuration file 40 --datadir "/home/milo/.ethereum" Data directory for the databases and keystore 41 --keystore Directory for the keystore (default = inside the datadir) 42 --nousb Disables monitoring for and managing USB hardware wallets 43 --networkid value Network identifier (integer, 1=Frontier, 2=Morden (disused), 3=Ropsten, 4=Rinkeby) (default: 1) 44 --testnet Ropsten network: pre-configured proof-of-work test network 45 --rinkeby Rinkeby network: pre-configured proof-of-authority test network 46 --goerli Görli network: pre-configured proof-of-authority test network 47 --syncmode "fast" Blockchain sync mode ("fast", "full", or "light") 48 --gcmode value Blockchain garbage collection mode ("full", "archive") (default: "full") 49 --ethstats value Reporting URL of a ethstats service (nodename:secret@host:port) 50 --identity value Custom node name 51 --lightserv value Maximum percentage of time allowed for serving LES requests (0-90) (default: 0) 52 --lightpeers value Maximum number of LES client peers (default: 100) 53 --lightkdf Reduce key-derivation RAM & CPU usage at some expense of KDF strength 54 --whitelist value Comma separated block number-to-hash mappings to enforce (<number>=<hash>) 55 56 DEVELOPER CHAIN OPTIONS: 57 --dev Ephemeral proof-of-authority network with a pre-funded developer account, mining enabled 58 --dev.period value Block period to use in developer mode (0 = mine only if transaction pending) (default: 0) 59 60 ETHASH OPTIONS: 61 --ethash.cachedir Directory to store the ethash verification caches (default = inside the datadir) 62 --ethash.cachesinmem value Number of recent ethash caches to keep in memory (16MB each) (default: 2) 63 --ethash.cachesondisk value Number of recent ethash caches to keep on disk (16MB each) (default: 3) 64 --ethash.dagdir "/home/milo/.ethash" Directory to store the ethash mining DAGs (default = inside home folder) 65 --ethash.dagsinmem value Number of recent ethash mining DAGs to keep in memory (1+GB each) (default: 1) 66 --ethash.dagsondisk value Number of recent ethash mining DAGs to keep on disk (1+GB each) (default: 2) 67 68 TRANSACTION POOL OPTIONS: 69 --txpool.locals value Comma separated accounts to treat as locals (no flush, priority inclusion) 70 --txpool.nolocals Disables price exemptions for locally submitted transactions 71 --txpool.journal value Disk journal for local transaction to survive node restarts (default: "transactions.rlp") 72 --txpool.rejournal value Time interval to regenerate the local transaction journal (default: 1h0m0s) 73 --txpool.pricelimit value Minimum gas price limit to enforce for acceptance into the pool (default: 1) 74 --txpool.pricebump value Price bump percentage to replace an already existing transaction (default: 10) 75 --txpool.accountslots value Minimum number of executable transaction slots guaranteed per account (default: 16) 76 --txpool.globalslots value Maximum number of executable transaction slots for all accounts (default: 4096) 77 --txpool.accountqueue value Maximum number of non-executable transaction slots permitted per account (default: 64) 78 --txpool.globalqueue value Maximum number of non-executable transaction slots for all accounts (default: 1024) 79 --txpool.lifetime value Maximum amount of time non-executable transaction are queued (default: 3h0m0s) 80 81 PERFORMANCE TUNING OPTIONS: 82 --cache value Megabytes of memory allocated to internal caching (default: 1024) 83 --cache.database value Percentage of cache memory allowance to use for database io (default: 50) 84 --cache.trie value Percentage of cache memory allowance to use for trie caching (default: 25) 85 --cache.gc value Percentage of cache memory allowance to use for trie pruning (default: 25) 86 --trie-cache-gens value Number of trie node generations to keep in memory (default: 120) 87 88 ACCOUNT OPTIONS: 89 --unlock value Comma separated list of accounts to unlock 90 --password value Password file to use for non-interactive password input 91 92 API AND CONSOLE OPTIONS: 93 --rpc Enable the HTTP-RPC server 94 --rpcaddr value HTTP-RPC server listening interface (default: "localhost") 95 --rpcport value HTTP-RPC server listening port (default: 8545) 96 --rpcapi value API's offered over the HTTP-RPC interface 97 --rpc.gascap value Sets a cap on gas that can be used in eth_call/estimateGas (default: 0) 98 --ws Enable the WS-RPC server 99 --wsaddr value WS-RPC server listening interface (default: "localhost") 100 --wsport value WS-RPC server listening port (default: 8546) 101 --wsapi value API's offered over the WS-RPC interface 102 --wsorigins value Origins from which to accept websockets requests 103 --ipcdisable Disable the IPC-RPC server 104 --ipcpath Filename for IPC socket/pipe within the datadir (explicit paths escape it) 105 --rpccorsdomain value Comma separated list of domains from which to accept cross origin requests (browser enforced) 106 --rpcvhosts value Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (default: "localhost") 107 --jspath loadScript JavaScript root path for loadScript (default: ".") 108 --exec value Execute JavaScript statement 109 --preload value Comma separated list of JavaScript files to preload into the console 110 111 NETWORKING OPTIONS: 112 --bootnodes value Comma separated enode URLs for P2P discovery bootstrap (set v4+v5 instead for light servers) 113 --bootnodesv4 value Comma separated enode URLs for P2P v4 discovery bootstrap (light server, full nodes) 114 --bootnodesv5 value Comma separated enode URLs for P2P v5 discovery bootstrap (light server, light nodes) 115 --port value Network listening port (default: 30303) 116 --maxpeers value Maximum number of network peers (network disabled if set to 0) (default: 25) 117 --maxpendpeers value Maximum number of pending connection attempts (defaults used if set to 0) (default: 0) 118 --nat value NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>) (default: "any") 119 --nodiscover Disables the peer discovery mechanism (manual peer addition) 120 --v5disc Enables the experimental RLPx V5 (Topic Discovery) mechanism 121 --netrestrict value Restricts network communication to the given IP networks (CIDR masks) 122 --nodekey value P2P node key file 123 --nodekeyhex value P2P node key as hex (for testing) 124 125 MINER OPTIONS: 126 --mine Enable mining 127 --miner.threads value Number of CPU threads to use for mining (default: 0) 128 --miner.notify value Comma separated HTTP URL list to notify of new work packages 129 --miner.gasprice "1000000000" Minimum gas price for mining a transaction 130 --miner.gastarget value Target gas floor for mined blocks (default: 8000000) 131 --miner.gaslimit value Target gas ceiling for mined blocks (default: 8000000) 132 --miner.etherbase value Public address for block mining rewards (default = first account) (default: "0") 133 --miner.extradata value Block extra data set by the miner (default = client version) 134 --miner.recommit value Time interval to recreate the block being mined (default: 3s) 135 --miner.noverify Disable remote sealing verification 136 137 GAS PRICE ORACLE OPTIONS: 138 --gpoblocks value Number of recent blocks to check for gas prices (default: 20) 139 --gpopercentile value Suggested gas price is the given percentile of a set of recent transaction gas prices (default: 60) 140 141 VIRTUAL MACHINE OPTIONS: 142 --vmdebug Record information useful for VM and contract debugging 143 --vm.evm value External EVM configuration (default = built-in interpreter) 144 --vm.ewasm value External ewasm configuration (default = built-in interpreter) 145 146 LOGGING AND DEBUGGING OPTIONS: 147 --fakepow Disables proof-of-work verification 148 --nocompaction Disables db compaction after import 149 --verbosity value Logging verbosity: 0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=detail (default: 3) 150 --vmodule value Per-module verbosity: comma-separated list of <pattern>=<level> (e.g. eth/*=5,p2p=4) 151 --backtrace value Request a stack trace at a specific logging statement (e.g. "block.go:271") 152 --debug Prepends log messages with call-site location (file and line number) 153 --pprof Enable the pprof HTTP server 154 --pprofaddr value pprof HTTP server listening interface (default: "127.0.0.1") 155 --pprofport value pprof HTTP server listening port (default: 6060) 156 --memprofilerate value Turn on memory profiling with the given rate (default: 524288) 157 --blockprofilerate value Turn on block profiling with the given rate (default: 0) 158 --cpuprofile value Write CPU profile to the given file 159 --trace value Write execution trace to the given file 160 161 METRICS AND STATS OPTIONS: 162 --metrics Enable metrics collection and reporting 163 --metrics.influxdb Enable metrics export/push to an external InfluxDB database 164 --metrics.influxdb.endpoint value InfluxDB API endpoint to report metrics to (default: "http://localhost:8086") 165 --metrics.influxdb.database value InfluxDB database name to push reported metrics to (default: "geth") 166 --metrics.influxdb.username value Username to authorize access to the database (default: "test") 167 --metrics.influxdb.password value Password to authorize access to the database (default: "test") 168 --metrics.influxdb.tags value Comma-separated InfluxDB tags (key/values) attached to all measurements (default: "host=localhost") 169 170 WHISPER (EXPERIMENTAL) OPTIONS: 171 --shh Enable Whisper 172 --shh.maxmessagesize value Max message size accepted (default: 1048576) 173 --shh.pow value Minimum POW accepted (default: 0.2) 174 --shh.restrict-light Restrict connection between two whisper light clients 175 176 DEPRECATED OPTIONS: 177 --minerthreads value Number of CPU threads to use for mining (deprecated, use --miner.threads) (default: 0) 178 --targetgaslimit value Target gas floor for mined blocks (deprecated, use --miner.gastarget) (default: 8000000) 179 --gasprice "1000000000" Minimum gas price for mining a transaction (deprecated, use --miner.gasprice) 180 --etherbase value Public address for block mining rewards (default = first account, deprecated, use --miner.etherbase) (default: "0") 181 --extradata value Block extra data set by the miner (default = client version, deprecated, use --miner.extradata) 182 183 MISC OPTIONS: 184 --override.constantinople value Manually specify constantinople fork-block, overriding the bundled setting (default: 0) 185 --help, -h show help 186 187 188 COPYRIGHT: 189 Copyright 2013-2018 The go-ethereum Authors
二、truffle框架介紹
終端輸入truffle -v
1 milo@milo-K46CB:~$ truffle -v 2 Truffle v5.0.18 - a development framework for Ethereum 3 4 Usage: truffle <command> [options] 5 6 Commands: 7 build Execute build pipeline (if configuration present) 8 compile Compile contract source files 9 config Set user-level configuration options 10 console Run a console with contract abstractions and commands available 11 create Helper to create new contracts, migrations and tests 12 debug Interactively debug any transaction on the blockchain (experimental) 13 deploy (alias for migrate) 14 develop Open a console with a local development blockchain 15 exec Execute a JS module within this Truffle environment 16 help List all commands or provide information about a specific command 17 init Initialize new and empty Ethereum project 18 install Install a package from the Ethereum Package Registry 19 migrate Run migrations to deploy contracts 20 networks Show addresses for deployed contracts on each network 21 obtain Fetch and cache a specified compiler 22 opcode Print the compiled opcodes for a given contract 23 publish Publish a package to the Ethereum Package Registry 24 run Run a third-party command 25 test Run JavaScript and Solidity tests 26 unbox Download a Truffle Box, a pre-built Truffle project 27 version Show version number and exit 28 watch Watch filesystem for changes and rebuild the project automatically
truffle是一套以太坊的開發測試框架,使用solidity開發語言,類似於javascript
這里我們就不將truffle的安裝了
下面進入主要內容
三、啟動私有鏈節點
進入私有鏈文件夾打開一個終端,后面我們以終端1代指它,在終端1輸入以下命令
1 milo@milo-K46CB:~/private-geth$ geth --rpc --rpccorsdomain "*" --datadir ./data/00 --port 61910 --rpcport 8545 --rpcapi "db,eth,net,web3" --networkid 100 console
需要注意的是我們這里的啟動節點命令與之前我們搭建的節點啟動命令略有不同,其中:
--rpc是開啟http-rpc服務,可以進行智能合約的部署和調試
--rpccorsdomain "*"表示任何鏈接都可以連接到此節點
--port 指定以太坊網絡監聽端口,默認為30303,這里隨意選一個就好
--rpcport是指定http-rpc服務監聽端口,默認為8545,但也可以自己更改,這里我們就用8545
(敲黑板,這里有個重點,我們這里設置的rpcport要與之后truffle-config.js文件中的port相對應)
--rpcapi是設置允許連接的rpc的客戶端,一般為db,eth,net,web3,貌似這里也可以不用加
四、truffle合約編譯部署
1、首先我們創建一個項目文件夾truffle_Project,然后打開一個新的終端,之后我們我們用終端2代之它,在終端2輸入以下命令創建文件夾並初始化truffle環境
1 milo@milo-K46CB:~$ mkdir truffleProject 2 milo@milo-K46CB:~$ cd truffleProject/ 3 milo@milo-K46CB:~/truffleProject$ truffle init
輸出以下結果:
1 ✔ Preparing to download 2 ✔ Downloading 3 ✔ Cleaning up temporary files 4 ✔ Setting up box 5 6 Unbox successful. Sweet! 7 8 Commands: 9 10 Compile: truffle compile 11 Migrate: truffle migrate 12 Test contracts: truffle test
經過初始化后,我們創建的truffle_Project文件夾下會多出contracts,migrations,test三個文件夾和treffle_config.js文件
2、編寫合約
進入到contracts文件夾中,我們建立一個簡單的智能合約Test.sol,在端口2輸入以下命令
1 milo@milo-K46CB:~/truffleProject$ cd contracts/ 2 milo@milo-K46CB:~/truffleProject/contracts$ vim Test.sol
輸入以上命令出現以下結果:
輸入以下內容到文件內,wq保存退出
pragma solidity ^0.5.0; contract Test { function multiply(uint a) pure public returns(uint d) { return a * 7; } }
3、修改配置
終端輸入指令進入migrateions文件中,創建2_deploy_contracys.js文件,具體操作如下:
1 milo@milo-K46CB:~/truffleProgect$ cd migrations/ 2 milo@milo-K46CB:~/truffleProgect/migrations$ vim 2_deploy_contracys.js
輸入以下內容:
1 var Test = artifacts.require("./Test.sol"); 2 3 module.exports = function(deployer) { 4 deployer.deploy(Test); 5 };
之后我們在回到trifflr_Project文件夾,修改truffle-config.js文件,如下
1 milo@milo-K46CB:~/truffleProgect$ vim truffle-config.js
1 networks: { 2 live: { 3 host: "localhost", //本地地址,因為是在本機上建立的節點 4 port: 8545, //Ethereum的rpc監聽的端口號,默認是8545 5 network_id: 100 // 自定義網絡號 6 }
此處的port要與啟動節點參數rpcport相同
4、編譯
輸入以下指令進行合約編譯
milo@milo-K46CB:~/truffleProject$ truffle compile
編譯成功輸出以下結果:
1 Compiling your contracts... 2 =========================== 3 > Compiling ./contracts/Test.sol 4 > Artifacts written to /home/milo/truffleProgect/build/contracts 5 > Compiled successfully using: 6 - solc: 0.5.0+commit.1d4f565a.Emscripten.clang
這個時候我們就准備將合約部署到區塊鏈中了,之前我們已經在終端1開啟了私有鏈節點,在部署前,我們最好先開始挖礦,因為有有可能挖出礦的時間太長超過部署時間導致部署失敗,在終端1輸入:
1 > miner.start(3) 2 INFO [06-30|14:41:52.571] Updated mining threads threads=3 3 INFO [06-30|14:41:52.571] Transaction pool price threshold updated price=1000000000 4 INFO [06-30|14:56:17.263] Commit new mining work number=57 sealhash=8af97d…82bbb5 uncles=0 txs=1 gas=284908 fees=0.00569816 elapsed=29.717ms
然后我們在到終端2輸入以下命令開始部署:
1 milo@milo-K46CB:~/truffleProject$ truffle migrate --network live
此時終端1會出現:
1 INFO [06-30|14:56:15.134] Submitted contract creation
fullhash=0xf429d7cb5f31287af7328ad699c883ddabc346c03d778dbd3adc100de4d53967 contract=0x66C64c5dcacE473aD26497781df1E63d6Dd95688
輸入部署命令后,當挖到一個礦時,成功時會出現以下結果:
1 Compiling your contracts... 2 =========================== 3 > Everything is up to date, there is nothing to compile. 4 5 6 Starting migrations... 7 ====================== 8 > Network name: 'live' 9 > Network id: 100 10 > Block gas limit: 0xf25e94c2 11 12 13 1_initial_migration.js 14 ====================== 15 16 Deploying 'Migrations' 17 ---------------------- 18 > transaction hash: 0xf429d7cb5f31287af7328ad699c883ddabc346c03d778dbd3adc100de4d53967 19 > Blocks: 1 Seconds: 554 20 > contract address: 0x66C64c5dcacE473aD26497781df1E63d6Dd95688 21 > block number: 57 22 > block timestamp: 1561877762 23 > account: 0x8830397771710ADE101f0080f0da076181Bad374 24 > balance: 284 25 > gas used: 284908 26 > gas price: 20 gwei 27 > value sent: 0 ETH 28 > total cost: 0.00569816 ETH 29 30 31 ⠦ Saving migration to chain.
需要注意的是這個時候我們需要繼續挖礦才能往下進行,只有挖到新的區塊才能將合約部署到區塊中
終端1:
1 INFO [06-30|14:56:17.263] Commit new mining work number=57 sealhash=8af97d…82bbb5 uncles=0 txs=1 gas=284908 fees=0.00569816 elapsed=29.717ms 2 INFO [06-30|15:05:26.447] Successfully sealed new block number=57 sealhash=8af97d…82bbb5 hash=f75699…3cd3f8 elapsed=9m9.184s 3 INFO [06-30|15:05:26.645] 🔗 block reached canonical chain number=50 hash=e1bd78…66cb22 4 INFO [06-30|15:05:26.659] 🔨 mined potential block number=57 hash=f75699…3cd3f8 5 6 INFO [06-30|15:35:36.018] Commit new mining work number=60 sealhash=2c8cb8…6beaab uncles=0 txs=1 gas=106241 fees=0.00212482 elapsed=24.778ms 7 INFO [06-30|15:35:36.198] Successfully sealed new block number=60 sealhash=2c8cb8…6beaab hash=fc8f2e…c7e0ad elapsed=180.515ms 8 INFO [06-30|15:35:36.198] 🔗 block reached canonical chain number=53 hash=88967f…8f12f8 9 INFO [06-30|15:35:36.198] 🔨 mined potential block number=60 hash=fc8f2e…c7e0ad 10 INFO [06-30|15:35:36.199] Commit new mining work number=61 sealhash=4ab3e8…675cc8 uncles=0 txs=0 gas=0 fees=0 elapsed=267.307µs 11 INFO [06-30|15:35:36.487] Successfully sealed new block number=61 sealhash=4ab3e8…675cc8 hash=fe871e…560170 elapsed=288.572ms 12 INFO [06-30|15:35:36.487] 🔗 block reached canonical chain number=54 hash=c19457…22223c 13 INFO [06-30|15:35:36.487] 🔨 mined potential block number=61 hash=fe871e…560170 14 INFO [06-30|15:35:36.488] Commit new mining work number=62 sealhash=314d24…1b4ece uncles=0 txs=0 gas=0 fees=0 elapsed=165.646µs 15 INFO [06-30|15:35:36.772] Successfully sealed new block number=62 sealhash=314d24…1b4ece hash=052003…b1004c elapsed=284.138ms
終端2:
1 ====================== 2 3 Deploying 'Migrations' 4 ---------------------- 5 > transaction hash: 0x39a329ee6f0afa49a9a2ebe20c3c8546ac51d081e869ccca1ad34e3e1bc43457 6 > Blocks: 1 Seconds: 386 7 > contract address: 0xff6cbFDEEDBA3E0f3714bBA7267658357C351D28 8 > block number: 58 9 > block timestamp: 1561879271 10 > account: 0x8830397771710ADE101f0080f0da076181Bad374 11 > balance: 289 12 > gas used: 284908 13 > gas price: 20 gwei 14 > value sent: 0 ETH 15 > total cost: 0.00569816 ETH 16 17 18 > Saving migration to chain. 19 > Saving artifacts 20 ------------------------------------- 21 > Total cost: 0.00569816 ETH 22 23 24 2_deploy_contracys.js 25 ===================== 26 27 Deploying 'Test' 28 ---------------- 29 > transaction hash: 0x803270c2ee1625c05fd55902b437d567a56618856f665ee4260dcad59b3526cd 30 > Blocks: 0 Seconds: 0 31 > contract address: 0xa12E7a68Cd8F79a0978DdD5764B943Ef9d685493 32 > block number: 60 33 > block timestamp: 1561880132 34 > account: 0x8830397771710ADE101f0080f0da076181Bad374 35 > balance: 309 36 > gas used: 106241 37 > gas price: 20 gwei 38 > value sent: 0 ETH 39 > total cost: 0.00212482 ETH 40 41 42 > Saving migration to chain. 43 > Saving artifacts 44 ------------------------------------- 45 > Total cost: 0.00212482 ETH 46 47 48 Summary 49 ======= 50 > Total deployments: 2 51 > Final cost: 0.00782298 ETH
五、調用合約
以上操作后,我們的簡單智能合約就部署完成了
下面我們進行合約的調用
打開truffle_Project/bulid/contracts/Test.json文件,可以看到以下內容
{ abi: [{ constant: false, inputs: [{...}], name: "multiply", outputs: [{...}], payable: false, type: "function" }], address: "0xa12E7a68Cd8F79a0978DdD5764B943Ef9d685493", transactionHash: null, allEvents: function(), multiply: function() } "compiler": { "name": "solc", "version": "0.5.0+commit.1d4f565a.Emscripten.clang" }, "networks": { "100": { "events": {}, "links": {}, "address": "0xa12E7a68Cd8F79a0978DdD5764B943Ef9d685493", "transactionHash": "0x803270c2ee1625c05fd55902b437d567a56618856f665ee4260dcad59b3526cd" } }, "schemaVersion": "3.0.9", "updatedAt": "2019-06-30T07:35:39.931Z",
將abi中的內容的內容拿出來先在線壓縮,在終端1輸入如下:
1 > abi=[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"payable":false,"type":"function"}]
輸出:
1 [{ 2 constant: false, 3 inputs: [{ 4 name: "a", 5 type: "uint256" 6 }], 7 name: "multiply", 8 outputs: [{ 9 name: "d", 10 type: "uint256" 11 }], 12 payable: false, 13 type: "function" 14 }]
接着在終端1輸入:
1 > test=eth.contract(abi).at("0xa12E7a68Cd8F79a0978DdD5764B943Ef9d685493")
其中這個地址可以在上面的Test.json中看到
之后我們就可以調用啦,在終端1中輸入:
1 > test.multiply.call(100) 2 700
可以看出成功調用了我們寫的合約,到這里所有的工作就完成了