MetaCoin——Truffle 控制台操作:truffle-develop 部署合约并用truffle develop 内置EVM 挖矿

Truffle develop 控制台与智能合约交互:

  • truffle develop 与ganache一样默认提供10个账户
PS F:\Github\fuzzy-spoon\fuzzy-spoon\metacoin> truffle develop
Truffle Develop started at http://127.0.0.1:9545/

Accounts:
(0) 0x627306090abab3a6e1400e9345bc60c78a8bef57
(1) 0xf17f52151ebef6c7334fad080c5704d77216b732
(2) 0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef
(3) 0x821aea9a577a9b44299b9c15c88cf3087f3b5544
(4) 0x0d1d4e623d10f9fba5db95830f7d3839406c6af2
(5) 0x2932b7a2355d6fecc4b5c0b6bd44cc31df247a2e
(6) 0x2191ef87e392377ec08e7c08eb105ef5448eced5
(7) 0x0f4f2ac550a1b4e2280d04c21cea7ebd822934b5
(8) 0x6330a553fc93768f612722bb8c2ec78ac90b3bbc
(9) 0x5aeda56215b167893e80b4fe645ba6d5bab767de

Private Keys:
(0) c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3
(1) ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f
(2) 0dbbe8e4ae425a6d2687f1a7e3ba17bc98c673636790f1b8ad91193c05875ef1
(3) c88b703fb08cbea894b6aeff5a544fb92e78a18e19814cd85da83b71f772aa6c
(4) 388c684f0ba1ef5017716adb5d21a053ea8e90277d0868337519f97bede61418
(5) 659cbb0e2411a44db63778987b1e22153c086a95eb6b18bdf89de078917abc63
(6) 82d052c865f5763aad42add438569276c00d3d88a2d062d36b2bae914d58b8c8
(7) aa3680d5d48a8283413f7a108367c7299ca73f553735860a87b08f39395618b7
(8) 0f62d96d6675f32685bbdb8ac13cda7c23436f63efbb9d07700d8669ff12b7c4
(9) 8d5366123cb560bb606379f90a0bfd4769eecc0557f1b362dcae9012b548b1e5

Mnemonic: candy maple cake sugar pudding cream honey rich smooth crumble sweet treat

⚠️  Important ⚠️  : This mnemonic was created for you by Truffle. It is not secure.
Ensure you do not use it on production blockchains, or else you risk losing funds.
  • web3查询账户余额
truffle(develop)>  web3.eth.getBalance("0x627306090abab3a6e1400e9345bc60c78a8bef57")
BigNumber { s: 1, e: 20, c: [ 1000000 ] }truffle(develop)>
  • 查询 metacoin 发布后智能合约中的账户余额:

MetaCoin.deployed().then(function(instance){return instance.getBalance(web3.eth.accounts[0]);}).then(function(value){return value.toNumber()});
  • 查询账户余额值多少ETH
MetaCoin.deployed().then(function(instance){return instance.getBalanceInEth(web3.eth.accounts[0]);}).then(function(value){return value.toNumber()});
  • 转 metacoin 从一个账户转账到另外一个账户
MetaCoin.deployed().then(function(instance){return instance.sendCoin(web3.eth.accounts[1], 500);});
  • 查询接收 metacoin 的账户的余额:
MetaCoin.deployed().then(function(instance){return instance.getBalance(web3.eth.accounts[1]);}).then(function(value){return value.toNumber()});
  • 查询转出 metacoin 账户的余额:
MetaCoin.deployed().then(function(instance){return instance.getBalance(web3.eth.accounts[0]);}).then(function(value){return value.toNumber()});
  • call方法查看账户余额 ,通过call方法调用不会修改数据,文档“not intending to persist any changes”,但是查看余额时不用call暂时也没有发现有其他影响。
truffle(development)> MetaCoin.deployed().then(function(instance){meta = instance; return meta.getBalance.call(account_one,{from:account_one});}).then(function(balance){console.log(balance.toNumber());}).catch(function(e){})
9380
undefined
  • 查看合约详细内容
MetaCoin.deployed().then(function(instance){console.log(instance)});
TruffleContract {
  constructor:
   { [Function: TruffleContract]
     _static_methods:
      { setProvider: [Function: setProvider],
        new: [Function: new],
        at: [Function: at],
        deployed: [Function: deployed],
        defaults: [Function: defaults],
        hasNetwork: [Function: hasNetwork],
        isDeployed: [Function: isDeployed],
        detectNetwork: [Function: detectNetwork],
        setNetwork: [Function: setNetwork],
        resetAddress: [Function: resetAddress],
        link: [Function: link],
        clone: [Function: clone],
        addProp: [Function: addProp],
        toJSON: [Function: toJSON] },
     _properties:
      { contract_name: [Object],
        contractName: [Object],
        abi: [Object],
        network: [Function: network],
        networks: [Function: networks],
        address: [Object],
        transactionHash: [Object],
        links: [Function: links],
        events: [Function: events],
        binary: [Function: binary],
        deployedBinary: [Function: deployedBinary],
        unlinked_binary: [Object],
        bytecode: [Object],
        deployedBytecode: [Object],
        sourceMap: [Object],
        deployedSourceMap: [Object],
        source: [Object],
        sourcePath: [Object],
        legacyAST: [Object],
        ast: [Object],
        compiler: [Object],
        schema_version: [Function: schema_version],
        schemaVersion: [Function: schemaVersion],
        updated_at: [Function: updated_at],
        updatedAt: [Function: updatedAt] },
     _property_values: {},
     _json:
      { contractName: 'MetaCoin',
        abi: [Array],
        bytecode:
         '0x608060405234801561001057600080fd5b506127106000803273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506103fc806100656000396000f300608060405260043610610057576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680637bd703e81461005c57806390b98a11146100b3578063f8b2cb4f14610118575b600080fd5b34801561006857600080fd5b5061009d600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061016f565b6040518082815260200191505060405180910390f35b3480156100bf57600080fd5b506100fe600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061022f565b604051808215151515815260200191505060405180910390f35b34801561012457600080fd5b50610159600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610388565b6040518082815260200191505060405180910390f35b600073__ConvertLib____________________________6396e4ee3d61019484610388565b60026040518363ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808381526020018281526020019250505060206040518083038186803b1580156101ed57600080fd5b505af4158015610201573d6000803e3d6000fd5b505050506040513d602081101561021757600080fd5b81019080805190602001909291905050509050919050565b6000816000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410156102805760009050610382565b816000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282540392505081905550816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b92915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490509190505600a165627a7a723058201e6f722164933905ec5113302fb1bb308b04762932dd700061f555f758733de00029',
        deployedBytecode:
         '0x608060405260043610610057576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680637bd703e81461005c57806390b98a11146100b3578063f8b2cb4f14610118575b600080fd5b34801561006857600080fd5b5061009d600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061016f565b6040518082815260200191505060405180910390f35b3480156100bf57600080fd5b506100fe600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061022f565b604051808215151515815260200191505060405180910390f35b34801561012457600080fd5b50610159600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610388565b6040518082815260200191505060405180910390f35b600073__ConvertLib____________________________6396e4ee3d61019484610388565b60026040518363ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808381526020018281526020019250505060206040518083038186803b1580156101ed57600080fd5b505af4158015610201573d6000803e3d6000fd5b505050506040513d602081101561021757600080fd5b81019080805190602001909291905050509050919050565b6000816000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410156102805760009050610382565b816000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282540392505081905550816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b92915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490509190505600a165627a7a723058201e6f722164933905ec5113302fb1bb308b04762932dd700061f555f758733de00029',
        sourceMap:
         '316:675:1:-;;;453:57;8:9:-1;5:2;;;30:1;27;20:12;5:2;453:57:1;501:5;479:8;:19;488:9;479:19;;;;;;;;;;;;;;;:27;;;;316:675;;;;;;',
        deployedSourceMap:
         '316:675:1:-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;780:117;;8:9:-1;5:2;;;30:1;27;20:12;5:2;780:117:1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;513:264;;8:9:-1;5:2;;;30:1;27;20:12;5:2;513:264:1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;900:89;;8:9:-1;5:2;;;30:1;27;20:12;5:2;900:89:1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;780:117;839:4;855:10;:18;874:16;885:4;874:10;:16::i;:::-;891:1;855:38;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8:9:-1;5:2;;;30:1;27;20:12;5:2;855:38:1;;;;8:9:-1;5:2;;;45:16;42:1;39;24:38;77:16;74:1;67:27;5:2;855:38:1;;;;;;;13:2:-1;8:3;5:11;2:2;;;29:1;26;19:12;2:2;855:38:1;;;;;;;;;;;;;;;;848:45;;780:117;;;:::o;513:264::-;577:15;625:6;602:8;:20;611:10;602:20;;;;;;;;;;;;;;;;:29;598:47;;;640:5;633:12;;;;598:47;673:6;649:8;:20;658:10;649:20;;;;;;;;;;;;;;;;:30;;;;;;;;;;;705:6;683:8;:18;692:8;683:18;;;;;;;;;;;;;;;;:28;;;;;;;;;;;741:8;720:38;;729:10;720:38;;;751:6;720:38;;;;;;;;;;;;;;;;;;769:4;762:11;;513:264;;;;;:::o;900:89::-;954:4;971:8;:14;980:4;971:14;;;;;;;;;;;;;;;;964:21;;900:89;;;:::o',
        source:
         'pragma solidity ^0.4.17;\n\nimport "./ConvertLib.sol";\n\n// This is just a simple example of a coin-like contract.\n// It is not standards compatible and cannot be expected to talk to other\n// coin/token contracts. If you want to create a standards-compliant\n// token, see: https://github.com/ConsenSys/Tokens. Cheers!\n\ncontract MetaCoin {\n\tmapping (address => uint) balances;\n\n\tevent Transfer(address indexed _from, address indexed _to, uint256 _value);\n\n\tconstructor () public {\n\t\tbalances[tx.origin] = 10000;\n\t}\n\n\tfunction sendCoin(address receiver, uint amount) public returns(bool sufficient) {\n\t\tif (balances[msg.sender] < amount) return false;\n\t\tbalances[msg.sender] -= amount;\n\t\tbalances[receiver] += amount;\n\t\temit Transfer(msg.sender, receiver, amount);\n\t\treturn true;\n\t}\n\n\tfunction getBalanceInEth(address addr) public view returns(uint){\n\t\treturn ConvertLib.convert(getBalance(addr),2);\n\t}\n\n\tfunction getBalance(address addr) public view returns(uint) {\n\t\treturn balances[addr];\n\t}\n}\n',
        sourcePath:
         'F:\\Github\\fuzzy-spoon\\fuzzy-spoon\\web-pack\\contracts\\MetaCoin.sol',
        ast: [Object],
        legacyAST: [Object],
        compiler: [Object],
        networks: [Object],
        schemaVersion: '2.0.1',
        updatedAt: '2018-07-21T02:15:29.660Z' },
     setProvider: [Function: bound setProvider],
     new: [Function: bound new],
     at: [Function: bound at],
     deployed: [Function: bound deployed],
     defaults: [Function: bound defaults],
     hasNetwork: [Function: bound hasNetwork],
     isDeployed: [Function: bound isDeployed],
     detectNetwork: [Function: bound detectNetwork],
     setNetwork: [Function: bound setNetwork],
     resetAddress: [Function: bound resetAddress],
     link: [Function: bound link],
     clone: [Function: bound clone],
     addProp: [Function: bound addProp],
     toJSON: [Function: bound toJSON],
     web3:
      Web3 {
        _requestManager: [RequestManager],
        currentProvider: [Provider],
        eth: [Eth],
        db: [DB],
        shh: [Shh],
        net: [Net],
        personal: [Personal],
        bzz: [Swarm],
        settings: [Settings],
        version: [Object],
        providers: [Object],
        _extend: [Function] },
     class_defaults:
      { from: '0x8e0d8466ef0cc4b0a1301aa7da1a030063efa3e2',
        gas: 6721975,
        gasPrice: 100000000000 },
     currentProvider:
      HttpProvider {
        host: 'http://127.0.0.1:8545',
        timeout: 0,
        user: undefined,
        password: undefined,
        headers: undefined,
        send: [Function],
        sendAsync: [Function],
        _alreadyWrapped: true },
     network_id: '5778' },
  abi:
   [ { inputs: [],
       payable: false,
       stateMutability: 'nonpayable',
       type: 'constructor' },
     { anonymous: false,
       inputs: [Array],
       name: 'Transfer',
       type: 'event' },
     { constant: false,
       inputs: [Array],
       name: 'sendCoin',
       outputs: [Array],
       payable: false,
       stateMutability: 'nonpayable',
       type: 'function' },
     { constant: true,
       inputs: [Array],
       name: 'getBalanceInEth',
       outputs: [Array],
       payable: false,
       stateMutability: 'view',
       type: 'function' },
     { constant: true,
       inputs: [Array],
       name: 'getBalance',
       outputs: [Array],
       payable: false,
       stateMutability: 'view',
       type: 'function' } ],
  contract:
   Contract {
     _eth:
      Eth {
        _requestManager: [RequestManager],
        getBalance: [Function],
        getStorageAt: [Function],
        getCode: [Function],
        getBlock: [Function],
        getUncle: [Function],
        getCompilers: [Function],
        getBlockTransactionCount: [Function],
        getBlockUncleCount: [Function],
        getTransaction: [Function],
        getTransactionFromBlock: [Function],
        getTransactionReceipt: [Function],
        getTransactionCount: [Function],
        call: [Function],
        estimateGas: [Function],
        sendRawTransaction: [Function],
        signTransaction: [Function],
        sendTransaction: [Function],
        sign: [Function],
        compile: [Object],
        submitWork: [Function],
        getWork: [Function],
        coinbase: [Getter],
        getCoinbase: [Function],
        mining: [Getter],
        getMining: [Function],
        hashrate: [Getter],
        getHashrate: [Function],
        syncing: [Getter],
        getSyncing: [Function],
        gasPrice: [Getter],
        getGasPrice: [Function],
        accounts: [Getter],
        getAccounts: [Function],
        blockNumber: [Getter],
        getBlockNumber: [Function],
        protocolVersion: [Getter],
        getProtocolVersion: [Function],
        iban: [Function],
        sendIBANTransaction: [Function: bound transfer] },
     transactionHash: null,
     address: '0xa7225c8b65f113150eeeb83cd70b0d276c1d8e95',
     abi: [ [Object], [Object], [Object], [Object], [Object] ],
     sendCoin:
      { [Function: bound ]
        request: [Function: bound ],
        call: [Function: bound ],
        sendTransaction: [Function: bound ],
        estimateGas: [Function: bound ],
        getData: [Function: bound ],
        'address,uint256': [Circular] },
     getBalanceInEth:
      { [Function: bound ]
        request: [Function: bound ],
        call: [Function: bound ],
        sendTransaction: [Function: bound ],
        estimateGas: [Function: bound ],
        getData: [Function: bound ],
        address: [Circular] },
     getBalance:
      { [Function: bound ]
        request: [Function: bound ],
        call: [Function: bound ],
        sendTransaction: [Function: bound ],
        estimateGas: [Function: bound ],
        getData: [Function: bound ],
        address: [Circular] },
     allEvents: [Function: bound ],
     Transfer:
      { [Function: bound ] 'address,address,uint256': [Function: bound ] } },
  Transfer:
   { [Function: bound ] 'address,address,uint256': [Function: bound ] },
  sendCoin:
   { [Function]
     call: [Function],
     sendTransaction: [Function],
     request: [Function: bound ],
     estimateGas: [Function] },
  getBalanceInEth:
   { [Function]
     call: [Function],
     sendTransaction: [Function],
     request: [Function: bound ],
     estimateGas: [Function] },
  getBalance:
   { [Function]
     call: [Function],
     sendTransaction: [Function],
     request: [Function: bound ],
     estimateGas: [Function] },
  sendTransaction: [Function],
  send: [Function],
  allEvents: [Function: bound ],
  address: '0xa7225c8b65f113150eeeb83cd70b0d276c1d8e95',
  transactionHash: null }

 

  ContractName.deployed()或ContractName.at(contractAddress)获取已经部署的合约对象

truffle(development)> var metacoin = MetaCoin.deployed()
undefined

truffle(development)> metacoin.getBalance.call(web3.eth.accounts[0])
TypeError: Cannot read property 'call' of undefined
truffle(development)> metacoin.sendCoin.sendTransaction(web3.eth.accounts[1],30,{from:web3.eth.accounts[0]})
TypeError: Cannot read property 'sendTransaction' of undefined

但是命令却没有作用,提示“undefined”,但是在http://dophin459.coding.me/posts/6dfb7cf8/文档中命令正常执行,原因没有暂时,没有找到需要看一下truffle 的命令操作和web3.js的命令文档;如下执行命令是可以成功的。

truffle(development)> web3.eth.getBalance(web3.eth.accounts[0])
BigNumber { s: 1, e: 19, c: [ 496736, 52700000000000 ] }

上面所使用的web3.eth.accounts[0],并没有初始化web3对象,但是控制台输入web3会弹出,表示已经初始化了web3对象,truffle 控制台执行migrate --reset重新部署后(如果之前有部署过合约,用--reset 表示重新部署),会根据truffle.js配置网络重新部署合约,并初始化了web3对象:

truffle(development)> web3
Web3 {
  _requestManager:
   RequestManager {
     provider:
      HttpProvider {                                                                                                                           Number()});        host: 'http://127.0.0.1:7545',
        timeout: 0,
        user: undefined,
        password: undefined,
        headers: undefined,
        send: [Function],
        sendAsync: [Function],
        _alreadyWrapped: true },
     polls: {},
     timeout: null },
  currentProvider:
   HttpProvider {
     host: 'http://127.0.0.1:7545',
     timeout: 0,
     user: undefined,
     password: undefined,
     headers: undefined,
     send: [Function],
     sendAsync: [Function],
     _alreadyWrapped: true },

...

}

 修改网络的端口号后,会在新IP+port上部署合约,并初始化web3对象

truffle(development)> web3
Web3 {
  _requestManager:
   RequestManager {
     provider:
      HttpProvider {
        host: 'http://127.0.0.1:8545',
        timeout: 0,
        user: undefined,
        password: undefined,
        headers: undefined,
        send: [Function],
        sendAsync: [Function],
        _alreadyWrapped: true },
     polls: {},
     timeout: null },
  currentProvider:
   HttpProvider {
     host: 'http://127.0.0.1:8545',
     timeout: 0,
     user: undefined,
     password: undefined,
     headers: undefined,
     send: [Function],
     sendAsync: [Function],
     _alreadyWrapped: true },

 总之呢,上面执行的各种命令也是用到web3对象命令,truffle 根据truffle.js自动创建了web3对象供控制台使用。

  • 也可以这样实现truffle.js:
var Web3 = require("web3");
// 创建web3对象
var web3 = new Web3();
// 连接到以太坊节点
web3.setProvider(new Web3.providers.HttpProvider("http://localhost:8545"));
  • truffle compile --all ,truffle test 命令都正常执行,但是truffle console 打开控制台时出错,说明这样不行。
PS F:\Github\fuzzy-spoon\fuzzy-spoon\web-pack> truffle console
No network available. Use `truffle develop` or add network to truffle.js config.
PS F:\Github\fuzzy-spoon\fuzzy-spoon\web-pack>
  •  还是这样编写truffle.js才可以用truffle develop控制台
module.exports = {
  networks: {
    development: {
      host: '127.0.0.1',
      port: 8545,
      network_id: '*' // Match any network id
    }
  }
}
  •  重新编译并打开控制台后,migrate --reset 重新部署后会获得
PS F:\Github\fuzzy-spoon\fuzzy-spoon\web-pack> truffle console
truffle(development)> migrate --reset
Using network 'development'.

Running migration: 1_initial_migration.js
  Replacing Migrations...
  ... 0x9c6e503858ac6977673a8b8adc00931a8d8efbf73ba224dbf9ace81afa5f9d64
  Migrations: 0x139783d06ef96f51cb7d50782ac8e624ab553875
Saving successful migration to network...
  ... 0xa44226d2ba63424755579599da7773dbdd717cfd81ea7ebf76ca55079097632f
Saving artifacts...
Running migration: 2_deploy_contracts.js
  Replacing ConvertLib...
  ... 0xac555c337b2884f4048501f9a34d144b73d20be04d8e392cc75c009135e86d39
  ConvertLib: 0xb4cdd736bfc63ca0261bea92032bb5de43ff58cd
  Linking ConvertLib to MetaCoin
  Replacing MetaCoin...
  ... 0x85e30cece1f6d6d1f71081071a19fa5d5570cec20e112b5269a485092a03824a
  MetaCoin: 0xa7225c8b65f113150eeeb83cd70b0d276c1d8e95
Saving successful migration to network...
  ... 0x2729679eb9bc9e05d3c0886b63d8de87bfa4976cf4b6a0773048ca77958d6b7f
Saving artifacts...
  • 找到哪里是合约地址? 
  Replacing MetaCoin...
  ... 0x85e30cece1f6d6d1f71081071a19fa5d5570cec20e112b5269a485092a03824a //部署hash值
  MetaCoin: 0xa7225c8b65f113150eeeb83cd70b0d276c1d8e95 //部署地址
  • 在MetaCoin.json中也有地址
// 合约ABI
var abi = [{"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"amount","type":"uint256"}],"name":"sendCoin","outputs":[{"name":"sufficient","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"addr","type":"address"}],"name":"getBalance","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"}];
// 合约地址
var address = "0xa7225c8b65f113150eeeb83cd70b0d276c1d8e95";
// 通过ABI和地址获取已部署的合约对象
var metacoin = web3.eth.contract(abi).at(address);
  • 查看账户余额
truffle(development)> var account_one = web3.eth.accounts[0];
undefined
truffle(development)> var account_one_balance = metacoin.getBalance.call(account_one);
undefined
truffle(development)> console.log("account one balance:",account_one_balance.toNumber());
account one balance: 10000
undefined
  •  sendCoin函数,由于sendCoin要修改合约内部的数据,所以要使sendCoin生效,必须要向区块链发送交易,可以在sendCoin后面加上.sendTransaction()来指明这是一笔交易:
truffle(development)> var account_one = web3.eth.accounts[0];
undefined
truffle(development)> var account_two = web3.eth.accounts[1];
undefined
truffle(development)> var txhash = metacoin.sendCoin.sendTransaction(account_two, 100, {from:account_one});
undefined
truffle(development)> console.log(txhash);
0xcbd82c0131871bf159dd5c6c8e8f3b5d309711984d3e384ff861806e9ca2f512undefined
truffle(development)>
  • 在ganache客户端 也监控到了这笔交易:

 

MetaCoin——Truffle 控制台操作:truffle-develop 部署合约并用truffle develop 内置EVM 挖矿_第1张图片

  • 查看账户account_one的余额
truffle(development)> metacoin.getBalance.call(account_one)
BigNumber { s: 1, e: 3, c: [ 9900 ] }
truffle(development)> metacoin.getBalance.call(account_two)
BigNumber { s: 1, e: 2, c: [ 100 ] }
truffle(development)>

 在sendCoin函数后加上.sendTransaction() 指明要向区块链发送交易,合约函数sendCoin只有两个参数,而在web3中通过.sendTransaction() 调用合约函数的时候可以指定from/value/gas等属性。

  • 监听合约事件

当通过.sendTransaction()调用合约的时候,交易会被提交到区块链处理,合约如何告知外部交易已经完成呢?通过触发监听合约事件告知外部交易已经完成。合约中定义事件,事件带有参数,在合约完成某些操作时触发事件,向外部传递信息。MetaCoin合约中在sendCoin函数中定义了事件Transfer,表示一个转账事件,转账成功后将会触发。在web3中使用事件,要首先获取事件对象,然后监听事件,如果事件发生,就会在回调函数中获取事件信息。

//监听到上次完成的交易触发的Transfer事件
myEvent.watch(function(err,result){ if(!err) {console.log(result);}else{console.log(err);} myEvent.stopWatching(); });
truffle(development)> var txhash = metacoin.sendCoin.sendTransaction(account_two, 100, {from:account_one});
undefined
truffle(development)> var myEvent = metacoin.Transfer();
undefined
truffle(development)> myEvent.watch(function(err,result){ if(!err) {console.log(result);}else{console.log(err);} myEvent.stopWatching(); });
Filter {
  requestManager:
   RequestManager {
     provider:
      HttpProvider {
        host: 'http://127.0.0.1:8545',
        timeout: 0,
        user: undefined,
        password: undefined,
        headers: undefined,
        send: [Function],
        sendAsync: [Function],
        _alreadyWrapped: true },
     polls: { '0x15': [Object], '0x16': [Object] },
     timeout:
      Timeout {
        _called: false,
        _idleTimeout: 500,
        _idlePrev: [TimersList],
        _idleNext: [TimersList],
        _idleStart: 1756433,
        _onTimeout: [Function: bound ],
        _timerArgs: undefined,
        _repeat: null,
        _destroyed: false,
        domain: [Domain],
        [Symbol(unrefed)]: false,
        [Symbol(asyncId)]: 43224,
        [Symbol(triggerId)]: 43208 } },
  options:
   { topics:
      [ '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',
        null,
        null ],
     from: undefined,
     to: undefined,
     address: '0xa7225c8b65f113150eeeb83cd70b0d276c1d8e95',
     fromBlock: undefined,
     toBlock: undefined },
  implementation:
   { newFilter:
      { [Function: send] request: [Function: bound ], call: [Function: newFilterCall] },
     uninstallFilter:
      { [Function: send] request: [Function: bound ], call: 'eth_uninstallFilter' },
     getLogs:
      { [Function: send] request: [Function: bound ], call: 'eth_getFilterLogs' },
     poll:
      { [Function: send] request: [Function: bound ], call: 'eth_getFilterChanges' } },
  filterId: '0x16',
  callbacks: [ [Function] ],
  getLogsCallbacks: [],
  pollFilters: [],
  formatter: [Function: bound ] }
truffle(development)> { logIndex: 0,
  transactionIndex: 0,
  transactionHash:
   '0xf191e4430353c38a990ed12897edb3ab2b4f1f075726581275fd0a23a5333a9e',//交易hash值
  blockHash:
   '0xd7f9b452ea4932f724860dd3dce58281e9c14f0816fa05c9fa834d8402b8513c',
  blockNumber: 27,
  address: '0xa7225c8b65f113150eeeb83cd70b0d276c1d8e95',
  type: 'mined',
  event: 'Transfer',
  args:
   { _from: '0x8e0d8466ef0cc4b0a1301aa7da1a030063efa3e2',
     _to: '0x24a5199dbc94f2f5e943d373785986e775d76eea',
     _value: BigNumber { s: 1, e: 2, c: [Array] } } }

undefined
// 交易hash值与监听事件得到的hash是同一hash
truffle(development)> console.log(txhash)
0xf191e4430353c38a990ed12897edb3ab2b4f1f075726581275fd0a23a5333a9e

 在ganache 客户端监也可以看到,它们的交易hash值是一致的。

MetaCoin——Truffle 控制台操作:truffle-develop 部署合约并用truffle develop 内置EVM 挖矿_第2张图片

注意到交易命令:

var txhash = metacoin.sendCoin.sendTransaction(account_two, 100, {from:account_one});
//根据官方文档:sendCoin钩子中没有第三个参数,第三个参数是特殊对象,始终作为最后一个参数传递给函数
var txhash = metacoin.sendCoin(account_two, 100, {from:account_one});
  •  官方文档中给出的监控事件的代码:
truffle(development)> MetaCoin.deployed().then(function(instance){meta = instance;return meta.sendCoin(account_two,10,{from:account_one});}).then(function(result){for (var i=0;i

 如果已经有合同的地址可以用抽象表示该地址的合同

var instance = MetaCoin.at("0x1234...");

添加新合同到网络

MetaCoin.new().then(function(instance) {
  // Print the new address
  console.log(instance.address);
}).catch(function(err) {
  // There was an error! Handle it.
});

 运行外部脚本

truffle exec 

 为了脚本能够正确运行,Truffle 将它们导出,将函数单个参数作为回调,(这怎么用呢?):

module.exports = function(callback) {
  // perform actions
}

定义了一个脚本在test/1.js


// 合约ABI
var abi = [{"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"amount","type":"uint256"}],"name":"sendCoin","outputs":[{"name":"sufficient","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"addr","type":"address"}],"name":"getBalance","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"}];
// 合约地址
var address = "0xa7225c8b65f113150eeeb83cd70b0d276c1d8e95";
// 通过ABI和地址获取已部署的合约对象
var metacoin = web3.eth.contract(abi).at(address);

var account_one = web3.eth.accounts[0];
var account_two = web3.eth.accounts[1];
console.log(account_one);
console.log(account_two);
// 提交交易到区块链,会立即返回交易hash,但是交易要等到被矿工收录到区块中后才生效
var txhash = metacoin.sendCoin.sendTransaction(account_two, 100, {from:account_one});
console.log(txhash);

var myEvent = metacoin.Transfer();
myEvent.watch(function(err, result) {
    if (!err) {
        console.log(result.transactionHash);
        if (result.transactionHash == txhash) { // txhash未定义?
            var account_one_balance = metacoin.getBalance.call(account_one);
            console.log("account one balance after sendCoin:", account_one_balance.toNumber());
        }
    } else {
        console.log(err);
    }
    myEvent.stopWatching();
});

在 truffle 控制台执行后出现txhash未定义错误 ,不知道为什么,alert声明全局变量也没用。

 

参考原文:

https://truffleframework.com/docs/getting_started/contracts

https://blog.csdn.net/tgbus18990140382/article/details/80916223

http://dophin459.coding.me/posts/9cc80f82/

http://dophin459.coding.me/posts/6dfb7cf8/

 

你可能感兴趣的:(区)