Using Harmony Chrome Extension Wallet with Smart Contracts
Add the following lines to your src/init.js
1
import initializeContract from './contract';
2
import userWallet from './userWallet';
3
4
let but = document.getElementById("inputtButton");
5
6
but.addEventListener("click",initWallet);
7
8
async function initWallet(){
9
const wallet = new userWallet();
10
await wallet.signin();
11
const contract = await initializeContract();
12
console.log(contract)
13
const result = await contract.methods.getCount().call()
14
console.log(result.toString())
15
}
Copied!
In you src/hmy.js file, add the following lines of code
1
const { Harmony } = require('@harmony-js/core');
2
const { ChainType } = require('@harmony-js/utils');
3
4
export default new Harmony(
5
// let's assume we deploy smart contract to this end-point URL
6
'https://api.s0.b.hmny.io',
7
{
8
chainType: ChainType.Harmony,
9
chainId: 2,
10
},
11
);
Copied!
Now add the following lines of code to src/contract.js
1
import hmy from './hmy';
2
import fs from 'fs';
3
4
const initializeContract = async (wallet)=>{
5
let contract = fs.readFileSync("../build/contracts/Counter.json" , { encoding: "UTF-8" });
6
contract = JSON.parse(contract)
7
const abi = contract.abi;
8
const contractAddress = contract.networks['2'].address;
9
const contractInstance = hmy.contracts.createContract(abi,contractAddress);
10
return contractInstance
11
}
12
13
export default initializeContract;
Copied!
To sign the transactions when calling send method on a smart contract, add the following lines to wallet class in src/userWallet.js
1
signTransaction(txn) {
2
if (this.isOneWallet) {
3
return this.onewallet.signTransaction(txn);
4
}
5
}
6
7
attachToContract(contract) {
8
if(this.onewallet){
9
contract.wallet.signTransaction = async (tx)=>{
10
tx.from = this.address;
11
const signTx = await this.signTransaction(tx);
12
console.log(signTx);
13
return signTx;
14
}
15
}
16
return contract
17
}
Copied!
We assume that you are using the same setup structure throughout the documentation. If not, change the path of Counter.json to your desired location.

That's It !!

Now call "view" methods on smart contracts like this:
1
const value = await contract.methods.getMoneyStored().call();
Copied!
Call "payable" methods like this.
1
const one = new BN('1')
2
let options = {
3
gasPrice: 1000000000,
4
gasLimit: 210000,
5
value: toWei(one, hmy.utils.Units.one),
6
};
7
8
const increment = await contract.methods.addMoney().send(options)
Copied!
Congratulations you have now connected your Harmony Chrome Extension Wallet, and completed writing code for it to interact with the Harmony blockchain.
Last modified 2mo ago
Export as PDF
Copy link
Contents
That's It !!