iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 24
2
Blockchain

區塊練起來-智能合約與DApp開發系列 第 24

[區塊練起來-智能合約與DApp開發] DAY 24 - web3.js 呼叫合約

貼心小語

上一篇我們使用 Truffle 進行合約部署及函式庫連結,那麼在部署完之後當然要與合約進行互動,我們將使用 web3.js 來調用合約。


取得合約實例

先使用 Truffle 將合約部署到 Ganache 中:

truffle migrate

我們要取得合約的 實例(Instance) 來與該合約做互動,必須使用 ABI合約位址 來建構對應的實例。在 ProviderService 中設計呼叫 Resume 合約的方法:

public getResume(address: string): any {
    return new this.web3.eth.Contract(ResumeContract.abi, address);
}

然後在 app.component.ts 中取得 Resume 實例:

constructor(private provider: ProviderService) {
const resume = this.provider.getResume('0x1Ff192E4bA1b23bdb586A290C525b6037f8859a8');
}

呼叫合約的函式

有了合約的實例之後,要針對合約做操作就簡單許多。合約的函式位於實例的 methods 裡,從 methods 中找到並呼叫 profile() 來取得個人資料。由於取得個人資料不會改變狀態變數,所以不需要附帳戶就可以呼叫,使用 call() 即可:

resume.methods.profile().call().then(res => console.log(res));

會看到部署合約時所輸入的資訊:
https://ithelp.ithome.com.tw/upload/images/20190910/20119338JQWYPbbXJS.png
如果是會改變狀態變數的函式,則需要附上付款帳戶,並使用 send({ from: account }) 。除了用 then() 接收回傳資料以外,還可以使用 on() 來針對不同時機點做不同事情,如:取得交易 hash 的時機點就用 transactionHash 、取得收據的時間點就用 receipt 、發生錯誤用 error 等。

constructor(private provider: ProviderService) {
    this.provider.getAccount().pipe(
        take(1)
    ).subscribe(accounts => {
        this.provider.defaultAccount = accounts[0];
        const resume = this.provider.getResume('0x1Ff192E4bA1b23bdb586A290C525b6037f8859a8');
        resume.methods.setPermission('0x68CC696C9510ba6f2dC764BaE42bcE0aC08c3783', 'HAOSchool', 1, true)
        .send({ from: this.provider.defaultAccount })
        .on('transactionHash', hash => console.log(hash))
        .on('receipt', receipt => console.log(receipt))
        .on('error', console.error);
    });
}

付款後就打開開發人員工具來看印出了哪些資訊:
https://ithelp.ithome.com.tw/upload/images/20190910/20119338wCnnCdpj6Y.png
可以看到我們把交易的 hash 以及收據的資訊都印出來了,表示成功囉!


今日小結

透過 web3.js 取得合約的實例,並使用實例來操作對應的智能合約,這部分也是 DApp 的核心功能之一,務必熟悉!


上一篇
[區塊練起來-智能合約與DApp開發] DAY 23 - web3.js 結合 Truffle 部署合約
下一篇
[區塊練起來-智能合約與DApp開發] DAY 25 - web3.js 訂閱Event
系列文
區塊練起來-智能合約與DApp開發31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言