區塊鏈學習(四)truffle部署編譯智能合約以太坊私有鏈

前面咱們介紹了以太坊私有鏈的搭建以及多節點私有鏈網絡,此次咱們介紹如何使用truffle框架來部署編譯智能合約到咱們以前搭建的私有鏈網絡中。javascript

搭建環境及需使用的工具:ubuntu18.04  Truffle v5.0.18  geth 1.8.27  Node v10.16.0java

solc  0.5.8+commit.23d335f2.Linux.g++node

在咱們部署一個簡單的合約以前,咱們先介紹一些相關的知識。web

1、geth 啓動節點參數介紹json

geth 當中有許多指令,由於以後私有鏈節點啓動須要設置一些參數,咱們重點介紹這些:bootstrap

參數 參數詳解
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的所有指令ubuntu

  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

2、truffle框架介紹vim

終端輸入truffle -vapi

 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開發語言,相似於javascriptwebsocket

這裏咱們就不將truffle的安裝了

下面進入主要內容

3、啓動私有鏈節點

進入私有鏈文件夾打開一個終端,後面咱們以終端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,貌似這裏也能夠不用加

4、truffle合約編譯部署

一、首先咱們建立一個項目文件夾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文件

二、編寫合約

進入到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;
    }
}

三、修改配置

終端輸入指令進入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相同

四、編譯

輸入如下指令進行合約編譯 

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

5、調用合約

以上操做後,咱們的簡單智能合約就部署完成了

下面咱們進行合約的調用

打開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

能夠看出成功調用了咱們寫的合約,到這裏全部的工做就完成了

相關文章
相關標籤/搜索