区块链学习(四)truffle部署编译智能合约以太坊私有链

前面我们介绍了以太坊私有链的搭建以及多节点私有链网络,这次我们介绍如何使用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

可以看出成功调用了我们写的合约,到这里所有的工作就完成了

 

posted @ 2019-06-30 22:03 Milo196 阅读(...) 评论(...) 编辑 收藏