Ethers.js "Error: unknown account #0 (operation="getAddress", code=UNSUPPORTED_OPERATION)"

Ethers.js "Error: unknown account #0 (operation="getAddress", code=UNSUPPORTED_OPERATION)"

我正在尝试使用 Ethers.js 从 KyberSwap 获取 ETH 的价格,但我收到以下错误:

Error: unknown account #0 (operation="getAddress", code=UNSUPPORTED_OPERATION, version=providers/5.5.3)

我已连接到 Infura 网络套接字以获取数据。这是我的脚本:

const { ethers } = require("hardhat");
const kyberABI = require('./kyberABI.json')

const provider = new ethers.providers.WebSocketProvider("wss://mainnet.infura.io/ws/v3/<project_id>")

const kyberNetworkProxyAddress = "0x818E6FECD516Ecc3849DAf6845e3EC868087B755"
const daiAddress = "0x6b175474e89094c44da98b954eedeac495271d0f"

const kyber = new ethers.Contract(
    kyberNetworkProxyAddress,
    kyberABI.kyberNetworkProxy,
    provider.getSigner(),
);

async function main() {
    // Update eth price from Kyber to reflect current market value
    let curEthPriceUSD
    const updateEthPrice = async () => {
        const results = await kyber.getExpectedRate(
            '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
            daiAddress,
            1
        )
        curEthPriceUSD = results.expectedRate
    }
    await updateEthPrice()
    console.log('Current Ethereum price in USD is: ',
        ethers.utils.formatEther(curEthPriceUSD))
}

main()

如何修复此错误?

related issue on Github.

中找到了解决此问题的方法

我没有使用 provider.getSigner() 来初始化 kyber 合约,而是使用 Wallet 对象并从那里获取签名者:

const wallet = new ethers.Wallet(ethPrivkey, provider);
const signer = wallet.provider.getSigner(wallet.address);

const kyber = new ethers.Contract(
    kyberNetworkProxyAddress,
    kyberABI.kyberNetworkProxy,
    signer
);

有完全相同的错误消息,在我的例子中,这是由于 Metamask 帐户未连接。第二行修复了它:

const provider = new ethers.providers.Web3Provider(window.ethereum);
await provider.send('eth_requestAccounts', []); // <- this promps user to connect metamask
const signer = provider.getSigner();