Solidity

使用 Truffle 訪問第三方合約的功能

  • November 13, 2017

我正在嘗試建構一個基本儀表板,讓我可以跟踪任何給定 ICO 的狀態(假設令牌是 ERC20)。

現在,我設法部署了一個基於 OpenZeppelin 和 Truffle 的簡單 Crowdsale + Coin 合約,並且我能夠訪問我建構的 Angular 2 前端上的狀態變數和函式。

接下來我做的事情也很好,使用 web3(沒有 Truffle)來訪問另一個部署的 Token,例如 BAT 並讀取它的公共狀態變數。這是通過以下程式碼實現的:

 var abi = [...] ;
 // Copied ABI from Etherscan https://etherscan.io/address/0x0d8775f648430679a709e98d2b0cb6250d2887ef#code 

 var MyContract = this.web3.eth.contract(abi);

 // initiate contract for an address
 var myContractInstance = MyContract.at('0x0D8775F648430679A709E98d2b0Cb6250d2887EF'); //Address to which BAT token is deployed.

 // call constant function (synchronous way)
 //var owner = myContractInstance .owner.call();

 console.log(myContractInstance);

 myContractInstance.totalSupply.call({from: this.account},
   function(error, result){
     console.log(result.toString(10))
 });

這有效地允許我從我自己的前端訪問 BAT 的 totalSupply。

現在,我很難弄清楚如何複製這段程式碼,但使用 Truffle 而不是 web3 呼叫。

我目前正在訪問我自己部署的契約,如下所示:

//Contracts have been built with Truffle here:
const crowdsaleArtifacts = require('../../build/contracts/PabloCoinCrowdsale.json');
const coinArtifacts = require('../../build/contracts/PabloCoin.json');

Crowdsale = contract(crowdsaleArtifacts);
Coin = contract(coinArtifacts);

//Bootstrap abstraction for use.
this.Crowdsale.setProvider(this.web3.currentProvider);
this.Coin.setProvider(this.web3.currentProvider);

//Once everything is loaded, for example, get totalSupply of Coin
this.getCoinInstance();

getCoinInstance(){
   this.Crowdsale
   .deployed()
   .then(instance =>{
     //Set the ref for the contract and look up it's associated token
     this.crowdsaleInstance = instance;
     this.crowdsaleInstance.token()
     .then(addr => {
       this.Coin.at(addr)
       .then(instance2 =>{
         // set the ref for the token and get totalSupply.
         this.coinInstance = instance2;
         this.totalSupply();
       })
     })
   })
   .catch(e => {
     console.log("ERR",e);
   });
 }

totalSupply(){
   this.coinInstance.totalSupply({
     from: this.account
   })
   .then(value =>{
     console.log("Total Supply:",this.web3.fromWei(value, "ether").toString(10));
   })
   .catch(e => {
     console.log(e);
   });
 }

弄清楚了。這是程式碼:

     var MyTruffleContract = contract({
       abi: abi //ABI obtained from Etherscan.
     })

     MyTruffleContract.setProvider(this.web3.currentProvider);
     console.log(MyTruffleContract);

     MyTruffleContract
     .at("0x0D8775F648430679A709E98d2b0Cb6250d2887EF") //Address of the contract, obtained from Etherscan
     .then(instance =>{
       instance.totalSupply({
         from: this.account
       })
       .then(value =>{
         console.log("Total Supply:",this.web3.fromWei(value, "ether").toString(10));
       })
       .catch(e => {
         console.log(e);
       });
     })

引用自:https://ethereum.stackexchange.com/questions/28425