Truffle-contract Call Contract __geth

Source: Internet
Author: User
Truffle-contract and contract interaction

Truffle-contract is also a JavaScript library for interacting with the ether-square intelligent contract, which is more convenient than web3.js.
Article Turn from:
http://dophin459.coding.me/posts/79b3ba3d/
https://blog.csdn.net/DDFFR/article/details/73772690 Truffle-contract has the following characteristics: Synchronized transactions: To ensure that the transaction takes effect before continuing with other operations returns promise: Each encapsulated contract function returns promise and can be performed on it. Then operation avoids callback Hell (callback Hell) problem Default parameters are provided for the transaction: for example, from or gas returns logs for each transaction, transaction receipt and transaction hash use truffle-contract need to install web3 truffle-contract Truffle-contract Call Contract

1, before calling the contract, the first deployment of a simple contract, you can refer to the following simple demo.

pragma solidity ^0.4.16;
Contract Metacoin {
    mapping (address => uint) balances;
    Event Transfer (address indexed _from, address indexed _to, uint256 _value);
    function Metacoin () {
        Balances[tx.origin] = 10000;
    }
    function Sendcoin (address receiver, uint amount) returns (bool sufficient) {
        if (Balances[msg.sender] < amount) ret Urn false;
        Balances[msg.sender]-= amount;
        Balances[receiver] + = amount;
        Transfer (Msg.sender, receiver, amount);
        return true;
    }
    function getbalance (address addr) returns (UINT) {return
        balances[addr];
    }
}

2, the contract to deploy to the Ethernet network to obtain the contract address and trading address (temporarily not used), can refer to

Contract mined! 
Address:0x75c35c980c0d37ef46df04d31a140b65503c0eed 
Transactionhash: 0x66a19b078e5b4b80ba082e0e1d17ceff42a597e4e4e8e60d2ada9f7b5cd09143
Initializing contract Objects

Like Web3.js, to use truffle-contract, you need to initialize the contract object and connect to an Ethernet square node. In your own project to create a new JS file, enter the following code

Reference Web3
var Web3 = require ("web3");
Reference Truffle-contract
var contract = require ("Truffle-contract");
The contract ABI contract ABI has
var contract_abi = [{"Constant '] in your compiled JSON file: false, Inputs: [{' Name ': ' A ', ' type ': ' uint256 '},{'] Name ":" B "," Type ":" uint256 "}]," name ":" Addmath "," outputs ": [{" Name ":" C "," type ":" uint256 "}]," payable ": false," Statemutability ":" Nonpayable "," type ":" function "};
The Contract object
var metacoin = contract ({
    Abi:contract_abi
}) is
initialized by the ABI; Connect to the Ether square node
var provider = new Web3.providers.HttpProvider ("http://localhost:8545");
Metacoin.setprovider (provider);

Next, you can use the following three functions of Metacoin: at (contract_address): Obtaining a Metacoin contract instance through a specified contract address deployed () : Get Metacoin Contract Instance new () By default contract address: Deploy a new contract and obtain a new deployed contract instance

Since our contract has already been deployed, we will use the ' at ' method to get an example of the contract, to invoke the contract, and the other two to be studied. Reference Code
Call contract function

Account Address
var account_one = "0x68b73956d704007514e9257813bdc58cdf3c969a";
The contract address
var contract_address = "0xb2cdd356e58280906ce53e1665697b50f88aac56";
Metacoin.at (contract_address). Then (function (instance) {return
    instance.getBalance.call (account_one);
}). Then (function (balance) {
    Console.log (Balance.tonumber ());
}). catch (function (err) {
    console.log (err);
});

First, get the contract instance through metacoin.at (), In a. Then chained call, the callback function obtains the contract instance instance in the parameter, and then the GetBalance function is invoked using the contract instance in the callback function, and then continues through. Then chained call, the return value getbalance is obtained by the callback function.

Let's take a look at the call to the Sendcoin function:

Account Address
var account_one = "0x68b73956d704007514e9257813bdc58cdf3c969a";
var account_two = "0x9c3c1a2f5ef913fac44f0348a78f68d835f3f26e";
The contract address
var contract_address = "0xb2cdd356e58280906ce53e1665697b50f88aac56";
Metacoin.at (contract_address). Then (function (instance) {
    //Call Sendcoin sends a transaction return to the block chain
    Instance.sendcoin (Account_two, {from:account_one});
Then (function (Result) {
    //The callback function is executed only after the transaction takes effect
    //The result object contains the following three fields:
    //RESULT.TX      => transaction hash, is a string
    //Result.receipt => Transaction Execution result, is an object
    //result.logs    => transaction generates an event collection that is an object array
    Console.log (result);
}). catch (function (err) {
    console.log (err);
});

Here, the call Sendcoin sends a transaction to the block chain, and the callback function is executed after the transaction takes effect, and the parameter of the callback function contains the hash of the transaction, the execution result of the transaction, and the event generated by the transaction.
Capturing events
You can get a transaction-triggered event by Result.logs:

Account address var account_one = "0x68b73956d704007514e9257813bdc58cdf3c969a";
var account_two = "0x9c3c1a2f5ef913fac44f0348a78f68d835f3f26e";
The contract address var contract_address = "0xb2cdd356e58280906ce53e1665697b50f88aac56"; Metacoin.at (contract_address). Then (function (instance) {//Call Sendcoin sends a transaction to the block chain return Instance.sendcoin (account_t
Wo, M, {from:account_one}); The. Then (function (Result) {//This callback function is executed only after the transaction takes effect//Result.logs is an array in which each element of the array is an event object//The query result.logs can get interested
        for (var i = 0; i < result.logs.length i++) {var log = result.logs[i];
            if (log.event = = "Transfer") {Console.log ("from:", Log.args._from);
            Console.log ("To:", log.args._to);
            Console.log ("Amount:", Log.args._value.tonumber ());
        Break
). catch (function (err) {Console.log (err);}); Output: from:0x68b73956d704007514e9257813bdc58cdf3c969a to:0x9c3c1a2f5ef913fac44f0348a78f68d835f3f26e amount:100

Sendcoin execution triggers a transfer event, which, in a callback function, can be obtained by querying Result.logs, which in turn can get the event's parameter values. a complete example

The following is a complete example:

var Web3 = require ("WEB3");
var contract = require ("Truffle-contract"); Contract ABI var contract_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 ': ' Co  Nstructor "}, {" 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 "}];
The Contract object var metacoin = contract ({Abi:contract_abi}) is initialized by the ABI;
Connect to the ether square node var provider = new Web3.providers.HttpProvider ("http://localhost:8545"); Metacoin.setprovider (ProvideR);
Account address var account_one = "0x68b73956d704007514e9257813bdc58cdf3c969a";
var account_two = "0x9c3c1a2f5ef913fac44f0348a78f68d835f3f26e";
The contract address var contract_address = "0xb2cdd356e58280906ce53e1665697b50f88aac56";
var coin;
    Metacoin.at (contract_address). Then (function (instance) {coin = instance;
First look at account two balance return Coin.getBalance.call (account_two); }). Then (function (balance_of_account_two) {Console.log ("Balance of account Two is", Balance_of_account_two.tonumber ()
    );
From account always account two turn 100 currency return Coin.sendcoin (Account_two, {from:account_one});
    }). Then (function (Result) {Console.log ("Sent coin from account one to account two.");
Check the balance of account two again return Coin.getBalance.call (Account_two); }). Then (function (balance_of_account_two) {Console.log ("Balance of account Two is", Balance_of_account_two.tonumber ()
); ). catch (function (err) {Console.log ("Error:", Err.message);});
//output Balance of account two is 3400 Sent-coin from account one to account two. Balance of two is 3500 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.