精华内容
下载资源
问答
  • 前面我们介绍了以太坊私有链的搭建以及多节点私有链网络,这次我们介绍如何使用truffle框架来部署编译智能合约到我们之前搭建的私有链网络中。 搭建环境及需使用的工具:ubuntu18.04Truffle v5.0.18 geth1.8.27...

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

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

     

    转载于:https://www.cnblogs.com/Falix/p/11111445.html

    展开全文
  • 使用truffle编译和部署智能合约

    千次阅读 2018-03-26 22:52:15
    1、首先下载并且安装truffle客户端 npm install -g truffle truffle是一个以太坊智能合约开发框架2、创建一个truffle项目的根目录,以D:\truffle\truffle_java为例。打开cmd命令行工具,导航到truffle_java目录下。...
    1、首先下载并且安装truffle客户端 npm install -g truffle truffle是一个以太坊智能合约开发框架
    2、创建一个truffle项目的根目录,以D:\truffle\truffle_java为例。打开cmd命令行工具,导航到truffle_java目录下。执行truffle init命令。会在该目录下出现下面目录结构的文件:
    -comtracts
    --Migrations.sol
    -migrations
    --1_initial_migration.js
    -test
    -truffle.js
    -truffle-config.js
    3、编译智能合约
    我们在contracts文件夹下创建一个智能合约文件Test.sol,文件内容如下:
    pragma solidity ^0.4.17;
    contract Test {
    function multiply(uint a) public returns(uint) {
    return a * 7;
    }
    }
    保存之后,执行truffle compile命令,truffle会把contracts文件夹下的智能合约文件编译成json的格式保存在build\contracts文件夹下,这个文件夹是新生成的文件夹。
    truffle仅默认编译自上次编译后被修改过的文件,来减少不必要的编译,如果你想编译全部文件,可以使用--compile-all选项:truffle compile --compile-all
    4、配置truffle-config.js文件,由于truffle.js和truffle-config.js文件有冲突,所以我们需要把truffle.js文件删除,只使用truffle-config.js文件。(如果你在windows上操作,那就删除truffle.js,如果你在另一个系统上操作,删除其中一个或者同时保留他们,都不要紧。这样做的原因是,在windows上有一个命名问题,当我们想要执行truffle命令时,它会打开truffle.js配置文件而不是读取里面的数据)
    truffle-config.js内容如下:
    module.exports = {
    // See <http://truffleframework.com/docs/advanced/configuration>
    // to customize your Truffle configuration!
    rpc: {
    host: "localhost",
    port: 8545
    },
    networks: {
    development: {
    network_id: "*",
    host: "localhost",
    port: 8545
    }
    }
    };
    4、部署智能合约
    编写部署智能合约的js文件,在migrations文件夹下,该文件夹下有个默认的文件1_initial_migration.js,这是部署Migration.sol智能合约的,内容如下:
    var Migrations = artifacts.require("./Migrations.sol");
    module.exports = function(deployer) {
    deployer.deploy(Migrations);
    };
    如果我们有多个智能合约,只需要把对应的智能合约文件名加上去即可
    然后在命令行执行truffle migrate,就可以把智能合约部署到以太坊网络上去了。
    注意:truffle部署智能合约的默认账户是geth客户端的主账户,所以在部署之前要把主账户解锁之后才可以部署,并且部署的时候需要挖矿。
    展开全文
  • Truffle 部署 编译 测试 智能合约 的 完整实践操作目标 搭建开发环境 创建一个Truffle项目 编写智能合约 编译转移智能合约 测试智能合约 创建用户界面连接智能合约 在浏览器中访问Dapp 搭建开发环境 Node.js v6+ LTS...

    Truffle 部署 编译 测试 智能合约 的 完整实践操作

    目标

    • 搭建开发环境
    • 创建一个Truffle项目
    • 编写智能合约
    • 编译转移智能合约
    • 测试智能合约
    • 创建用户界面连接智能合约
    • 在浏览器中访问Dapp

    搭建开发环境

    • Node.js v6+ LTS and npm (comes with Node)
    • Git

    这里配置脚本略过。。。。

    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ node -v
    v8.5.0
    
    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ npm -v
    5.4.2
    
    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ git --version
    git version 2.13.5 (Apple Git-94)
    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ npm install -g ethereumjs-testrpc
    /usr/local/bin/testrpc -> /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js
    
    > fsevents@1.1.2 install /usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/fsevents
    > node install
    
    events.js:182
          throw er; // Unhandled 'error' event
          ^
    
    Error: spawn node-pre-gyp ENOENT
        at _errnoException (util.js:1026:11)
        at Process.ChildProcess._handle.onexit (internal/child_process.js:192:19)
        at onErrorNT (internal/child_process.js:374:16)
        at _combinedTickCallback (internal/process/next_tick.js:138:11)
        at process._tickCallback (internal/process/next_tick.js:180:9)
        at Function.Module.runMain (module.js:667:11)
        at startup (bootstrap_node.js:201:16)
        at bootstrap_node.js:626:3
    
    > uglifyjs-webpack-plugin@0.4.6 postinstall /usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/uglifyjs-webpack-plugin
    > node lib/post_install.js
    
    npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.2 (node_modules/ethereumjs-testrpc/node_modules/fsevents):
    npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.2 install: `node install`
    npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
    
    + ethereumjs-testrpc@4.1.3
    added 2 packages, removed 475 packages, updated 238 packages and moved 1 package in 293.194s
    
    
       ╭─────────────────────────────────────╮
       │                                     │
       │   Update available 5.4.25.5.1    │
       │     Run npm i -g npm to update      │
       │                                     │
       ╰─────────────────────────────────────╯
    
    
    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ npm i -g npm to update  
    /usr/local/bin/npm -> /usr/local/lib/node_modules/npm/bin/npm-cli.js
    /usr/local/bin/npx -> /usr/local/lib/node_modules/npm/bin/npx-cli.js
    /usr/local/bin/update -> /usr/local/lib/node_modules/update/bin/update.js
    + update@0.7.4
    + npm@5.5.1
    + to@0.2.9
    added 708 packages, removed 2 packages and updated 29 packages in 434.067s
    
    
    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ sudo  npm install -g ethereumjs-testrpc                        
    npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/_yargs@3.10.0@yargs/node_modules/cliui
    npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/_yargs@3.10.0@yargs/node_modules/decamelize
    npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/_strip-ansi@3.0.1@strip-ansi/node_modules/ansi-regex
    npm ERR! path /usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/_yargs@3.10.0@yargs/node_modules/cliui
    npm ERR! code ENOENT
    npm ERR! errno -2
    npm ERR! syscall access
    npm ERR! enoent ENOENT: no such file or directory, access '/usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/_yargs@3.10.0@yargs/node_modules/cliui'
    npm ERR! enoent This is related to npm not being able to find a file.
    npm ERR! enoent 
    
    npm ERR! A complete log of this run can be found in:
    npm ERR!     /Users/xiaoyu/.npm/_logs/2017-10-26T08_09_48_018Z-debug.log
    
    
    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ npm install -g truffle
    /usr/local/bin/truffle -> /usr/local/lib/node_modules/truffle/build/cli.bundled.js
    + truffle@3.4.11
    removed 105 packages and updated 91 packages in 89.658s

    用Truffle Box创建一个Truffle项目

    ❖  ~/solidity [16:15:01]
    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ mkdir pet-shop-tutorial
    ❖  ~/solidity [16:15:06]
    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ cd pet-shop-tutorial
    
    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ truffle unbox pet-shop
    Downloading...
    Unpacking...
    Setting up...

    目录结构

    /contracts 智能合约
    /migrations 迁移系统来处理智能合约部署
    /test 测试
    truffle.js 配置文件

    其他部分是nodejs的配置文件以及文件夹

    编写智能合约

    contracts中创建Adoption.sol文件

    pragma solidity ^0.4.4;
    
    contract Adoption {
    
        address[16] public adopters; //存储地址
    
        //采用一个宠物
        function adopt(uint petId) public returns (uint) {
            require(petId >= 0 && petId <= 15);
    
            adopters[petId] = msg.sender;
    
            return petId;
        }
    
        //返回采用者
        function getAdopters() public returns (address[16]) {
            return adopters;
        }
    }
    

    编译转移智能合约

    EVM的测试环境

    打开另一个窗口

    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ testrpc -p 8588
    EthereumJS TestRPC v4.1.3 (ganache-core: 1.1.3)
    
    Available Accounts
    ==================
    (0) 0xd2a54e8087d88889e1857698ceb228493b67bab6
    (1) 0x44d32639c3803b9daa7392ff2ea50644153d7721
    (2) 0x32d951e2f319edb079764b1c75864497a3132446
    (3) 0x82244a630d6031be85ca298376cfa2bd6c7389a6
    (4) 0xd3b556b69eb670a250bbc3f15ebefb081d4c7108
    (5) 0x9f50cf1b425c6ca97de0128e46a21abd7bda3258
    (6) 0x8e0545a4fe9eac1bb2f4683f0c6b36cd4a364a40
    (7) 0x200b052f6eaeaa1dc11abcc3101b7a8aca293e70
    (8) 0xcbd4c8b9d264367d385d4938c3b390a2eb0f2a62
    (9) 0xa769a296f0bbab07e48ca62da5ad5aea4c920580
    
    Private Keys
    ==================
    (0) a4f66a0654bbd1338a0cc9264624ad9f710f5cd65bbd4aed6f0b20706335e573
    (1) cab64a11662597c79a9e866865efbec4b2e1701ed21783f68a61162937baaf8a
    (2) 9f52f1c63923b390b438212bdd4594d3b479b22024bd193b8a3a600572f697af
    (3) 452b11e8ea19803b44b474d86c13d7325a387459abe634ad1c64b13eb26d0745
    (4) a663ff82b20002942c491e393951e5e366d8cceeff89732690f974f709243260
    (5) 7410aba40135ee4fea322a13403b081939d245e7ed534e016090657cbdb6183c
    (6) 269e44a7c17d591d23a694539a8d6feee3d9894182d4bc663a2f51fc33a3f540
    (7) 4f70e8c8f25a1ef2e9057a1b25053d6bceca46b68dfc0548e0c96b16fa9af5eb
    (8) 6114321e07ba8248509c17f4f0318aaf0edd972986f43ec652a2030b6cfe18bd
    (9) 37cacf13d9833bb3c63c657b42fed5f87f3806cca4d1cd400cbc5f7c8c2a3cc1
    
    HD Wallet
    ==================
    Mnemonic:      better become piano october library quarter festival ability arrow patch fringe practice
    Base HD Path:  m/44'/60'/0'/0/{account_index}
    
    Listening on localhost:8588

    这里注意,我的测试demo指定了端口,那么也要修改对应的配置文件。

    truffle.js
    
    module.exports = {
      networks: {
        development: {
          host: "localhost",
          port: 8588,
          network_id: "*" // Match any network id
        }
      }
    };

    编译智能合约

    ❖  ~/solidity/pet-shop-tutorial [16:27:59]
    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ truffle compile
    Compiling ./contracts/Adoption.sol...
    Compiling ./contracts/Migrations.sol...
    Writing artifacts to ./build/contracts
    

    迁移智能合约

    查看项目目录,会发现migrations目录中已经存在了一个文件1_initial_migration.js

    我们开始创建第二个文件2_deploy_contracts.js

    var Adoption = artifacts.require("./Adoption.sol");
    
    module.exports = function(deployer) {
      deployer.deploy(Adoption);
    };

    执行迁移

    ❖  ~/solidity/pet-shop-tutorial [16:53:30]
    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ truffle migrate
    Using network 'development'.
    
    Running migration: 1_initial_migration.js
      Deploying Migrations...
      ... 0x09db8962f99c5e5bdb316882c9f3aff69244df68664c6d90dda7e8c9f5249809
      Migrations: 0xf7345735ec00a0b797e5469a49b5deaf9131659f
    Saving successful migration to network...
      ... 0xb6f330b833176db1e94d24c84bab618b6c9205585e9803f7c6fe21f14fec179a
    Saving artifacts...
    Running migration: 2_deploy_contracts.js
      Deploying Adoption...
      ... 0xb93b24287ebba0dfd091e62fb9d55e188a76412097fdae4a7caf1520b9aaabb9
      Adoption: 0x424bc3aeeeb6d0a0e0ed8271ce7764b6ad336c7a
    Saving successful migration to network...
      ... 0x26f08c9da8a6ec12f4edece8a6344a9030bb7fbd97f3b1a4592b93f4aec2dc39
    Saving artifacts...
    

    同时,你在testrpc上还能看到下面的输出

    Listening on localhost:8588
    net_version
    eth_accounts
    eth_accounts
    net_version
    net_version
    eth_sendTransaction
    
      Transaction: 0x09db8962f99c5e5bdb316882c9f3aff69244df68664c6d90dda7e8c9f5249809
      Contract created: 0xf7345735ec00a0b797e5469a49b5deaf9131659f
      Gas usage: 201556
      Block Number: 1
      Block Time: Thu Oct 26 2017 16:58:31 GMT+0800 (CST)
    
    eth_newBlockFilter
    eth_getFilterChanges
    eth_getTransactionReceipt
    eth_getCode
    eth_uninstallFilter
    eth_sendTransaction
    
      Transaction: 0xb6f330b833176db1e94d24c84bab618b6c9205585e9803f7c6fe21f14fec179a
      Gas usage: 41965
      Block Number: 2
      Block Time: Thu Oct 26 2017 16:58:31 GMT+0800 (CST)
    
    eth_getTransactionReceipt
    eth_accounts
    net_version
    net_version
    eth_sendTransaction
    
      Transaction: 0xb93b24287ebba0dfd091e62fb9d55e188a76412097fdae4a7caf1520b9aaabb9
      Contract created: 0x424bc3aeeeb6d0a0e0ed8271ce7764b6ad336c7a
      Gas usage: 213057
      Block Number: 3
      Block Time: Thu Oct 26 2017 16:58:31 GMT+0800 (CST)
    
    eth_newBlockFilter
    eth_getFilterChanges
    eth_getTransactionReceipt
    eth_getCode
    eth_uninstallFilter
    eth_sendTransaction
    
      Transaction: 0x26f08c9da8a6ec12f4edece8a6344a9030bb7fbd97f3b1a4592b93f4aec2dc39
      Gas usage: 26965
      Block Number: 4
      Block Time: Thu Oct 26 2017 16:58:31 GMT+0800 (CST)
    
    eth_getTransactionReceipt
    

    测试智能合约

    test文件夹中创建文件TestAdoption.sol

    pragma solidity ^0.4.11;
    
    import "truffle/Assert.sol"; //truffle公共的库
    import "truffle/DeployedAddresses.sol"; //truffle公共的库
    import "../contracts/Adoption.sol";
    
    contract TestAdoption {
        Adoption adoption = Adoption(DeployedAddresses.Adoption());
    
        // 测试 adopt()
        function testUserCanAdoptPet() {
            uint returnedId = adoption.adopt(8); //调用输入参数
    
            uint expected = 8; //期望的结果
    
            Assert.equal(returnedId, expected, "Adoption of pet ID 8 should be recorded."); //判断如果没有就抛出异常
        }
    
        // 单个测试
        function testGetAdopterAddressByPetId() {
    
            address expected = this;
    
            address adopter = adoption.adopters(8);
    
            Assert.equal(adopter, expected, "Owner of pet ID 8 should be recorded.");
        }
    
        // 所有的测试
        function testGetAdopterAddressByPetIdInArray() {
    
            address expected = this;
    
            address[16] memory adopters = adoption.getAdopters();
    
            Assert.equal(adopters[8], expected, "Owner of pet ID 8 should be recorded.");
        }
    
    
    }

    运行测试命令

    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ truffle test
    Using network 'development'.
    
    Compiling ./contracts/Adoption.sol...
    Compiling ./test/TestAdoption.sol...
    Compiling truffle/Assert.sol...
    Compiling truffle/DeployedAddresses.sol...
    
    Compilation warnings encountered:
    
    truffle/Assert.sol:114:20: Warning: This declaration shadows an existing declaration.
        function equal(string A, string B, string message) constant returns (bool result) {
                       ^------^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:137:23: Warning: This declaration shadows an existing declaration.
        function notEqual(string A, string B, string message) constant returns (bool result) {
                          ^------^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:206:20: Warning: This declaration shadows an existing declaration.
        function equal(bytes32 A, bytes32 B, string message) constant returns (bool result) {
                       ^-------^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:226:23: Warning: This declaration shadows an existing declaration.
        function notEqual(bytes32 A, bytes32 B, string message) constant returns (bool result) {
                          ^-------^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:286:20: Warning: This declaration shadows an existing declaration.
        function equal(address A, address B, string message) constant returns (bool result) {
                       ^-------^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:305:23: Warning: This declaration shadows an existing declaration.
        function notEqual(address A, address B, string message) constant returns (bool result) {
                          ^-------^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:403:20: Warning: This declaration shadows an existing declaration.
        function equal(bool A, bool B, string message) constant returns (bool result) {
                       ^----^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:426:23: Warning: This declaration shadows an existing declaration.
        function notEqual(bool A, bool B, string message) constant returns (bool result) {
                          ^----^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:451:20: Warning: This declaration shadows an existing declaration.
        function equal(uint A, uint B, string message) constant returns (bool result) {
                       ^----^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:474:23: Warning: This declaration shadows an existing declaration.
        function notEqual(uint A, uint B, string message) constant returns (bool result) {
                          ^----^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:497:22: Warning: This declaration shadows an existing declaration.
        function isAbove(uint A, uint B, string message) constant returns (bool result) {
                         ^----^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:520:24: Warning: This declaration shadows an existing declaration.
        function isAtLeast(uint A, uint B, string message) constant returns (bool result) {
                           ^----^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:543:22: Warning: This declaration shadows an existing declaration.
        function isBelow(uint A, uint B, string message) constant returns (bool result) {
                         ^----^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:566:23: Warning: This declaration shadows an existing declaration.
        function isAtMost(uint A, uint B, string message) constant returns (bool result) {
                          ^----^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:635:20: Warning: This declaration shadows an existing declaration.
        function equal(int A, int B, string message) constant returns (bool result) {
                       ^---^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:658:23: Warning: This declaration shadows an existing declaration.
        function notEqual(int A, int B, string message) constant returns (bool result) {
                          ^---^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:681:22: Warning: This declaration shadows an existing declaration.
        function isAbove(int A, int B, string message) constant returns (bool result) {
                         ^---^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:704:24: Warning: This declaration shadows an existing declaration.
        function isAtLeast(int A, int B, string message) constant returns (bool result) {
                           ^---^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:727:22: Warning: This declaration shadows an existing declaration.
        function isBelow(int A, int B, string message) constant returns (bool result) {
                         ^---^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:750:23: Warning: This declaration shadows an existing declaration.
        function isAtMost(int A, int B, string message) constant returns (bool result) {
                          ^---^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:1267:27: Warning: This declaration shadows an existing declaration.
        function balanceEqual(address A, uint b, string message) constant returns (bool result) {
                              ^-------^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:1287:30: Warning: This declaration shadows an existing declaration.
        function balanceNotEqual(address A, uint b, string message) constant returns (bool result) {
                                 ^-------^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:1306:28: Warning: This declaration shadows an existing declaration.
        function balanceIsZero(address A, string message) constant returns (bool result) {
                               ^-------^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    ,truffle/Assert.sol:1325:31: Warning: This declaration shadows an existing declaration.
        function balanceIsNotZero(address A, string message) constant returns (bool result) {
                                  ^-------^
    truffle/Assert.sol:64:5: The shadowed declaration is here:
        uint8 constant A = uint8(byte('a'));
        ^---------------------------------^
    
    
    
    
      TestAdoption
        ✓ testUserCanAdoptPet (100ms)
        ✓ testGetAdopterAddressByPetId (106ms)
        ✓ testGetAdopterAddressByPetIdInArray (119ms)
    
    
      3 passing (912ms)
    
    

    同时,在testrpc窗口中,输出如下内容

    net_version
    eth_accounts
    eth_accounts
    eth_accounts
    eth_sendTransaction
    
      Transaction: 0x0248e4f5b8ed0130b6c04fb0628747948c4430b2db32ae4b4aecc5837c95a7a9
      Contract created: 0x44d5b51c7a790edf595f36f647d8782ab95d2043
      Gas usage: 201556
      Block Number: 5
      Block Time: Thu Oct 26 2017 17:29:40 GMT+0800 (CST)
    
    eth_newBlockFilter
    eth_getFilterChanges
    eth_getTransactionReceipt
    eth_getCode
    eth_uninstallFilter
    eth_sendTransaction
    
      Transaction: 0xf25d861fa237ca89ece917d3bfcae990b00253a213e3dfe977c808727bb41621
      Gas usage: 41965
      Block Number: 6
      Block Time: Thu Oct 26 2017 17:29:40 GMT+0800 (CST)
    
    eth_getTransactionReceipt
    eth_accounts
    eth_sendTransaction
    
      Transaction: 0x3bc4a4f9a6a29e336135a0617b9dcda72af62f8ed6ba8cdcb52e2c13b9c0b9c1
      Contract created: 0x7e434775cefce86de3c944aeb840b80ffa397e6f
      Gas usage: 213057
      Block Number: 7
      Block Time: Thu Oct 26 2017 17:29:40 GMT+0800 (CST)
    
    eth_newBlockFilter
    eth_getFilterChanges
    eth_getTransactionReceipt
    eth_getCode
    eth_uninstallFilter
    eth_sendTransaction
    
      Transaction: 0x8e9a560c91b97f4fe1020f9e4154b063391d4e1b6da522a80e78d572e18e3864
      Gas usage: 26965
      Block Number: 8
      Block Time: Thu Oct 26 2017 17:29:40 GMT+0800 (CST)
    
    eth_getTransactionReceipt
    evm_snapshot
    Saved snapshot #1
    net_version
    eth_sendTransaction
    net_version
    eth_sendTransaction
    
      Transaction: 0xbcca837fc7693ae43eef2210f88f5b59ada90c2c56250558bdee776417c6ce8d
      Contract created: 0x16e910a876a0ef1ad4fceb7b15b0ed1e34212a3f
      Gas usage: 141661
      Block Number: 9
      Block Time: Thu Oct 26 2017 17:29:40 GMT+0800 (CST)
    
    eth_newBlockFilter
    
      Transaction: 0x8ad5172333283066102aada539d0b17f14a3a13b5bc996b8baca49296d625045
      Contract created: 0x7d49d66afb1fa72446cbbeb2dc7f43237a2895d9
      Gas usage: 4630196
      Block Number: 10
      Block Time: Thu Oct 26 2017 17:29:40 GMT+0800 (CST)
    
    eth_newBlockFilter
    eth_getFilterChanges
    eth_getFilterChanges
    eth_getTransactionReceipt
    eth_getTransactionReceipt
    eth_getCode
    eth_getCode
    eth_uninstallFilter
    eth_uninstallFilter
    eth_sendTransaction
    
      Transaction: 0x4a9374f9c1da7266c44b9c3f191572a79938bf446e9261a910904fbd86b019ef
      Contract created: 0x2411f93ad68e7a071ad6b116614d4a45049a2e36
      Gas usage: 425816
      Block Number: 11
      Block Time: Thu Oct 26 2017 17:29:41 GMT+0800 (CST)
    
    eth_newBlockFilter
    eth_getFilterChanges
    eth_getTransactionReceipt
    eth_getCode
    eth_uninstallFilter
    eth_blockNumber
    eth_sendTransaction
    
      Transaction: 0xc77b4f897c7ebcd27022c0b677589b6a3611384f5734660ec422cde74f0bec24
      Gas usage: 48908
      Block Number: 12
      Block Time: Thu Oct 26 2017 17:29:41 GMT+0800 (CST)
    
    eth_getTransactionReceipt
    eth_blockNumber
    eth_sendTransaction
    
      Transaction: 0xbc11d4af9475b481271d824c3ba492d7eb23a204608c3da790b77cd8509d518e
      Gas usage: 29062
      Block Number: 13
      Block Time: Thu Oct 26 2017 17:29:41 GMT+0800 (CST)
    
    eth_getTransactionReceipt
    eth_blockNumber
    eth_sendTransaction
    
      Transaction: 0x64e35489fcad832bfce85d305726922c2c2a97dcb897ffbfc4a69b0649fc7244
      Gas usage: 36064
      Block Number: 14
      Block Time: Thu Oct 26 2017 17:29:41 GMT+0800 (CST)
    
    eth_getTransactionReceipt
    

    创建用户界面连接智能合约

    安装web3

    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ npm install -g web3
    npm WARN deprecated fs-promise@2.0.3: Use mz or fs-extra^3.0 with Promise Support
    npm WARN deprecated tar.gz@1.0.7: ⚠️  WARNING ⚠️ tar.gz module has been deprecated and your application is vulnerable. Please use tar module instead: https://npmjs.com/tar
    npm WARN deprecated minimatch@0.3.0: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
    
    > scrypt@6.0.3 preinstall /usr/local/lib/node_modules/web3/node_modules/scrypt
    > node node-scrypt-preinstall.js
    
    
    > scrypt@6.0.3 install /usr/local/lib/node_modules/web3/node_modules/scrypt
    > node-gyp rebuild
    
      SOLINK_MODULE(target) Release/copied_files.node
      CC(target) Release/obj.target/scrypt_wrapper/src/util/memlimit.o
      CC(target) Release/obj.target/scrypt_wrapper/src/scryptwrapper/keyderivation.o
      CC(target) Release/obj.target/scrypt_wrapper/src/scryptwrapper/pickparams.o
      CC(target) Release/obj.target/scrypt_wrapper/src/scryptwrapper/hash.o
      LIBTOOL-STATIC Release/scrypt_wrapper.a
      CC(target) Release/obj.target/scrypt_lib/scrypt/scrypt-1.2.0/lib/crypto/crypto_scrypt.o
      CC(target) Release/obj.target/scrypt_lib/scrypt/scrypt-1.2.0/lib/crypto/crypto_scrypt_smix.o
      CC(target) Release/obj.target/scrypt_lib/scrypt/scrypt-1.2.0/libcperciva/util/warnp.o
      CC(target) Release/obj.target/scrypt_lib/scrypt/scrypt-1.2.0/libcperciva/alg/sha256.o
      CC(target) Release/obj.target/scrypt_lib/scrypt/scrypt-1.2.0/libcperciva/util/insecure_memzero.o
      CC(target) Release/obj.target/scrypt_lib/scrypt/scrypt-1.2.0/lib/scryptenc/scryptenc_cpuperf.o
      LIBTOOL-STATIC Release/scrypt_lib.a
      CXX(target) Release/obj.target/scrypt/src/node-boilerplate/scrypt_common.o
      CXX(target) Release/obj.target/scrypt/src/node-boilerplate/scrypt_params_async.o
      CXX(target) Release/obj.target/scrypt/src/node-boilerplate/scrypt_params_sync.o
      CXX(target) Release/obj.target/scrypt/src/node-boilerplate/scrypt_kdf_async.o
      CXX(target) Release/obj.target/scrypt/src/node-boilerplate/scrypt_kdf_sync.o
      CXX(target) Release/obj.target/scrypt/src/node-boilerplate/scrypt_kdf-verify_sync.o
      CXX(target) Release/obj.target/scrypt/src/node-boilerplate/scrypt_kdf-verify_async.o
      CXX(target) Release/obj.target/scrypt/src/node-boilerplate/scrypt_hash_sync.o
      CXX(target) Release/obj.target/scrypt/src/node-boilerplate/scrypt_hash_async.o
      CXX(target) Release/obj.target/scrypt/scrypt_node.o
      SOLINK_MODULE(target) Release/scrypt.node
    
    > sha3@1.2.0 install /usr/local/lib/node_modules/web3/node_modules/sha3
    > node-gyp rebuild
    
      CXX(target) Release/obj.target/sha3/src/addon.o
    ../src/addon.cpp:59:36: warning: 'NewInstance' is deprecated [-Wdeprecated-declarations]
                            info.GetReturnValue().Set(cons->NewInstance(argc, argv));
                                                            ^
    /Users/xiaoyu/.node-gyp/8.5.0/include/node/v8.h:3787:3: note: 'NewInstance' has been explicitly marked deprecated here
      V8_DEPRECATED("Use maybe version",
      ^
    /Users/xiaoyu/.node-gyp/8.5.0/include/node/v8config.h:332:29: note: expanded from macro 'V8_DEPRECATED'
      declarator __attribute__((deprecated))
                                ^
    1 warning generated.
      CXX(target) Release/obj.target/sha3/src/displayIntermediateValues.o
      CXX(target) Release/obj.target/sha3/src/KeccakF-1600-reference.o
      CXX(target) Release/obj.target/sha3/src/KeccakNISTInterface.o
      CXX(target) Release/obj.target/sha3/src/KeccakSponge.o
      SOLINK_MODULE(target) Release/sha3.node
    
    > websocket@1.0.24 install /usr/local/lib/node_modules/web3/node_modules/websocket
    > (node-gyp rebuild 2> builderror.log) || (exit 0)
    
      CXX(target) Release/obj.target/bufferutil/src/bufferutil.o
      SOLINK_MODULE(target) Release/bufferutil.node
      CXX(target) Release/obj.target/validation/src/validation.o
      SOLINK_MODULE(target) Release/validation.node
    + web3@1.0.0-beta.24
    added 289 packages in 68.85s
    

    打开文件/src/js/app.js

    下面的代码展示了如何调用web3,调用合约的方法,以及绑定数据到UI

    App = {
      web3Provider: null,
      contracts: {},
    
      init: function() {
        // Load pets.
        $.getJSON('../pets.json', function(data) {
          var petsRow = $('#petsRow');
          var petTemplate = $('#petTemplate');
    
          for (i = 0; i < data.length; i ++) {
            petTemplate.find('.panel-title').text(data[i].name);
            petTemplate.find('img').attr('src', data[i].picture);
            petTemplate.find('.pet-breed').text(data[i].breed);
            petTemplate.find('.pet-age').text(data[i].age);
            petTemplate.find('.pet-location').text(data[i].location);
            petTemplate.find('.btn-adopt').attr('data-id', data[i].id);
    
            petsRow.append(petTemplate.html());
          }
        });
    
        return App.initWeb3();
      },
    
      initWeb3: function() {
    
          // web3入口
          if (typeof web3 !== 'undefined') {
              App.web3Provider = web3.currentProvider;
          } else {
              // 测试网络
              App.web3Provider = new Web3.providers.HttpProvider('http://localhost:8588'); //这里是我指定的端口88
          }
          web3 = new Web3(App.web3Provider);
    
        return App.initContract();
      },
    
      initContract: function() {
          //加载Adoption.json
          $.getJSON('Adoption.json', function(data) {
              // 智能合约实例化
              var AdoptionArtifact = data;
              App.contracts.Adoption = TruffleContract(AdoptionArtifact);
    
              // 设置合约提供者
              App.contracts.Adoption.setProvider(App.web3Provider);
    
              // 检索操作
              return App.markAdopted();
          });
    
        return App.bindEvents();
      },
    
      bindEvents: function() {
        $(document).on('click', '.btn-adopt', App.handleAdopt);
      },
    
      markAdopted: function(adopters, account) {
          //实例
          var adoptionInstance;
    
    
          App.contracts.Adoption.deployed().then(function(instance) {
              adoptionInstance = instance;
    
              return adoptionInstance.getAdopters.call();
          }).then(function(adopters) {
              for (i = 0; i < adopters.length; i++) {
                  if (adopters[i] !== '0x0000000000000000000000000000000000000000') {
                      $('.panel-pet').eq(i).find('button').text('Success').attr('disabled', true);
                  }
              }
          }).catch(function(err) {
              console.log(err.message);
          });
      },
    
      handleAdopt: function() {
        event.preventDefault();
    
        var petId = parseInt($(event.target).data('id'));
    
          var adoptionInstance;
    
          web3.eth.getAccounts(function(error, accounts) {
              if (error) {
                  console.log(error);
              }
    
              var account = accounts[0];
    
              App.contracts.Adoption.deployed().then(function(instance) {
                  adoptionInstance = instance;
    
                  // Execute adopt as a transaction by sending account
                  return adoptionInstance.adopt(petId, {from: account});
              }).then(function(result) {
                  return App.markAdopted();
              }).catch(function(err) {
                  console.log(err.message);
              });
          });
      }
    
    };
    
    $(function() {
      $(window).load(function() {
        App.init();
      });
    });
    

    在浏览器中运行dapp

    安装MetaMask到浏览器

    • 安装扩展程序
    • 创建测试网络账户
    • 从其他测试网络钱包转移eth

    创建一个账户并导入eth

    安装和配置lite-server

    打开bs-config.json文件

    {
      "server": {
        "baseDir": ["./src", "./build/contracts"]
      }
    }

    打开package.json文件,下面配置了lite-server的部分

    "scripts": {
      "dev": "lite-server",
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    

    当运行npm run dev的时候,就会启动lite-server

    运行Dapp

    ❖  ~/solidity/pet-shop-tutorial [17:35:33]
    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ npm run dev
    
    > pet-shop@1.0.0 dev /Users/xiaoyu/solidity/pet-shop-tutorial
    > lite-server
    
    sh: lite-server: command not found
    npm ERR! file sh
    npm ERR! code ELIFECYCLE
    npm ERR! errno ENOENT
    npm ERR! syscall spawn
    npm ERR! pet-shop@1.0.0 dev: `lite-server`
    npm ERR! spawn ENOENT
    npm ERR! 
    npm ERR! Failed at the pet-shop@1.0.0 dev script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
    
    npm ERR! A complete log of this run can be found in:
    npm ERR!     /Users/xiaoyu/.npm/_logs/2017-10-26T10_20_42_191Z-debug.log

    报错了。。。。

    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ npm install -g lite-server
    npm WARN deprecated express@2.5.11: express 2.x series is deprecated
    npm WARN deprecated connect@1.9.2: connect 1.x series is deprecated
    /usr/local/bin/lite-server -> /usr/local/lib/node_modules/lite-server/bin/lite-server
    
    > fsevents@1.1.2 install /usr/local/lib/node_modules/lite-server/node_modules/fsevents
    > node install
    
    [fsevents] Success: "/usr/local/lib/node_modules/lite-server/node_modules/fsevents/lib/binding/Release/node-v57-darwin-x64/fse.node" already installed
    Pass --update-binary to reinstall or --build-from-source to recompile
    + lite-server@2.3.0
    added 417 packages in 499.895s
    ❖  ~/solidity/pet-shop-tutorial [18:30:10]
    xiaoyu@LIXIAOYUdeMacBook-Pro.com➤ npm run dev               
    
    > pet-shop@1.0.0 dev /Users/xiaoyu/solidity/pet-shop-tutorial
    > lite-server
    
    ** browser-sync config **
    { injectChanges: false,
      files: [ './**/*.{html,htm,css,js}' ],
      watchOptions: { ignored: 'node_modules' },
      server: 
       { baseDir: [ './src', './build/contracts' ],
         middleware: [ [Function], [Function] ] } }
    [Browsersync] Access URLs:
     -------------------------------------
           Local: http://localhost:3000
        External: http://10.0.178.198:3000
     -------------------------------------
              UI: http://localhost:3001
     UI External: http://10.0.178.198:3001
     -------------------------------------
    [Browsersync] Serving files from: ./src
    [Browsersync] Serving files from: ./build/contracts
    [Browsersync] Watching files...
    17.10.26 18:31:20 200 GET /index.html
    17.10.26 18:31:20 200 GET /css/bootstrap.min.css
    17.10.26 18:31:21 200 GET /js/bootstrap.min.js
    17.10.26 18:31:21 200 GET /js/web3.min.js
    17.10.26 18:31:21 200 GET /js/app.js
    17.10.26 18:31:21 200 GET /js/truffle-contract.js
    17.10.26 18:31:24 200 GET /pets.json
    17.10.26 18:31:24 200 GET /Adoption.json
    17.10.26 18:31:24 200 GET /images/french-bulldog.jpeg
    17.10.26 18:31:24 200 GET /images/boxer.jpeg
    17.10.26 18:31:24 200 GET /images/scottish-terrier.jpeg
    17.10.26 18:31:24 200 GET /images/golden-retriever.jpeg
    17.10.26 18:31:24 404 GET /favicon.ico
    
    

    然后会自动打开浏览器,http://localhost:3000/

    示例网站

    点击adopt按钮,会跳出提示,支付合约费用,完成调用。

    总结

    Truffle能完成智能合约的整套流程。

    Truffle Box 提供了现成的项目,可以快速上手。

    Truffle官网文档够详细,点个赞。

    参考资料

    展开全文
  • 再重复truffle develop ---> compile.问题解决!!! Q2:compile时提示 Warning: No visibility specified. Defaulting to "public".   function test() pure returns (string) {  ^ (Relevant ...

    Q1:compile时遇到错误提示 

    contracts/Migrations.sol: ParsedContract.sol:7:14: ParserError: Expected identifier, got 'LParen'
      constructor() public {
                 ^
    Compilation failed. See above.
    ~/eth-hunt/

    初步判断为js的编译器版本不和,即solcjs@x.x.x.,与pragma solidity  ^x.x.y 不一样造成,

    尝试:

    npm uninstall -g truffle
    npm install -g truffle

     

    再重复truffle develop  --->  compile.问题解决!!!

    Q2:compile时提示

    Warning: No visibility specified. Defaulting to "public". 

      function test() pure returns (string) {

      ^ (Relevant source part starts here and spans across multiple lines).

    将contract里的function中的constant 改为 pure public,即可

    Q3:调用migrate时不成功遇到Using network 'develop'/n  Network up to date.可以试试重新部署 migrate --reset

    S1:truffle(develop)> contract = HelloWorld.deployed().then(instance => contract = instance) :instance是参数,()里为函数。

    migrate受阻,检查后仍通不过,重新truffle develop >compile > migrate

    contract里有pure public console里可以直接 contarct.test(); 调用函数。没有pure只能contarct.test.call(); 调用函数。

    展开全文
  • truffle是以太坊开发框架, 本地的用来编译、部署智能合约的工具。 1. Truffle安装 npm install truffle -g 2. Truffle项目开发 创建目录 mkdir MetaCoin cd MetaCoin 创建工程 truffle unbox metacoin ...
  • 编译智能合约

    2018-07-04 17:43:03
    编译智能合约 源文件位置 你的所有智能合约应该在你的工程目录下的 contracts 目录中。所有的合约都是由 solidity 编写,并且所有文件的后缀都是 .sol 。 在一个空的 truffle 项目中,只有一个 Migrations.sol ...
  • 内置的智能合约编译,链接,部署和二进制文件的管理。 快速开发下的自动合约测试。 脚本化的,可扩展的部署与发布框架。 部署到不管多少的公网或私网的网络环境管理功能 使用EthPM&NPM提供的包管理,...
  • 不能部署migrate通过Tunffle编译的以太坊智能合约。我是这么做的: truffle init truffle compile open other terminal and run testrpc truffle migrate 前三步都正常过了,当我运行truf...
  • 宠物店教程智能合约 带有松露的智能合约首个应用程序( ) 编译 truffle compile 迁移 truffle migrate 测试 truffle test 运行UI npm run dev
  • 创建工程目录mkdir truffle_project cd truffle_project truffle init创建工程目录并初始化后,文件夹目录结构如下:▾ truffle-project/ ... ▾ migrations/ 用来存放部署/迁移智能合约的脚本文件...

空空如也

空空如也

1 2 3 4 5 ... 12
收藏数 222
精华内容 88
关键字:

truffle编译智能合约