Create The Instance with Ether.js
Получаю ошибку каждый раз, когда пытаюсь создать сущность через библиотеку ether.js
Имею JSON файл, который я получил после компиляции .sol файла в Remix. Суть в чём? - Я пытаюсь соединиться с метамаском, получить данные с скомпилированого контракта(деплоить буду тоже через Remix) и обновить их, вот код:
import { Component, OnInit } from '@angular/core';
import { ethers } from "ethers";
declare let window: any;
const ethereum = window.ethereum;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
public account: string;
private balance: string;
public read: string;
private contractAddr: string;
private contract: any;
public message: string;
constructor() {
this.account = '';
this.balance = '';
this.read = '';
this.contractAddr = '0xd9145CCE52D386f254917e481eB44e9943F39138';
this.message = '';
}
ngOnInit() {
this.contract = require("../assets/contracts/HelloWorld.json");
//console.log(JSON.stringify(this.contract));
}
async getAccount() {
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
this.account = accounts[0]; //showAcc
this.balance = await ethereum.request({
method: 'eth_getBalance',
params: [this.account, 'latest']
})
//showBalance
this.read = (parseInt(this.balance) / 10 ** 18).toFixed(5);
}
createInstance() {
return new ethers.Contract(this.contract, this.contractAddr);
}
async getData() {
const helloWorldContract = this.createInstance();
this.message = await helloWorldContract.methods.message().call();
}
}
Вот ошибка: SyntaxError: Unexpected token x in JSON at position 1
Скриншот прилагается:

Вот файл JSON, то что внутри файла, это скопированый ABI с Remix'а.
[
{
"inputs": [
{
"internalType": "string",
"name": "initMessage",
"type": "string"
}
],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "string",
"name": "oldStr",
"type": "string"
},
{
"indexed": false,
"internalType": "string",
"name": "newStr",
"type": "string"
}
],
"name": "UpdatedMessages",
"type": "event"
},
{
"inputs": [],
"name": "message",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "string",
"name": "newMessage",
"type": "string"
}
],
"name": "update",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
]
Ответы (1 шт):
Ошибка была из-за того, что при создании сущности парсилась строка с адресом вместо ABI. Вот объяснение в документации. Таким образом нужно просто поменять местами аргументы в функции CreateInstance. Соответственно код должен выглядеть таким образом:
createInstance() {
return new ethers.Contract(this.contractAddr, this.contract.abi,
this.signer);
}
PS: signer - позволяет не только читать, но записывать, когда provider - только чтение. Это нужно для того, чтобы была возможность апдейтить данные в контракте.