UNPKG

@kaiachain/ethers-ext

Version:
84 lines (83 loc) 3.49 kB
import { JsonRpcProvider as EthersJsonRpcProvider, Web3Provider as EthersWeb3Provider } from "@ethersproject/providers"; import { asyncOpenApi } from "@kaiachain/js-ext-core"; // @ts-ignore: package @kaiachain/web3rpc has no .d.ts file. import * as web3rpc from "@kaiachain/web3rpc"; import { JsonRpcSigner } from "./signer.js"; /* eslint-disable no-multi-spaces */ export class JsonRpcProvider extends EthersJsonRpcProvider { constructor(url, network) { super(url, network); const send = (method, params) => { return this.send(method, params); }; const { AdminApi, DebugApi, GovernanceApi, KlayApi, NetApi, PersonalApi, TxpoolApi } = web3rpc; this.admin = asyncOpenApi(send, AdminApi); this.debug = asyncOpenApi(send, DebugApi); this.governance = asyncOpenApi(send, GovernanceApi); this.klay = asyncOpenApi(send, KlayApi); this.kaia = asyncOpenApi(send, KlayApi); this.net = asyncOpenApi(send, NetApi); this.personal = asyncOpenApi(send, PersonalApi); this.txpool = asyncOpenApi(send, TxpoolApi); } } export class Web3Provider extends EthersWeb3Provider { constructor(provider, network) { super(provider, network); const send = async (method, params = []) => { if (method === "wallet_switchEthereumChain") { method = "wallet_switchKlaytnChain"; } if (method === "wallet_addEthereumChain") { method = "wallet_addKlaytnChain"; } if (provider?.request) { return provider.request({ method, params }); } else if (provider?.send) { return provider.send(method, params); } else if (provider?.sendAsync && provider?.isMobile) { if (method === "eth_requestAccounts" || method == "eth_accounts" || method == "kaia_accounts") { return provider?.enable(); } else { return new Promise((resolve, reject) => { provider.sendAsync({ method, params }, (err, result) => { if (err) { reject(err); } else { resolve(result?.result || ""); } }); }); } } else { throw new Error("Provider does not support sendAsync or send methods"); } }; this.send = send; const { AdminApi, DebugApi, GovernanceApi, KlayApi, NetApi, PersonalApi, TxpoolApi } = web3rpc; this.admin = asyncOpenApi(send, AdminApi); this.debug = asyncOpenApi(send, DebugApi); this.governance = asyncOpenApi(send, GovernanceApi); this.klay = asyncOpenApi(send, KlayApi); this.kaia = asyncOpenApi(send, KlayApi); this.net = asyncOpenApi(send, NetApi); this.personal = asyncOpenApi(send, PersonalApi); this.txpool = asyncOpenApi(send, TxpoolApi); } getSigner(addressOrIndex) { return new JsonRpcSigner(this, addressOrIndex); } send(method, params) { return this.send(method, params); } listAccounts() { return this.send("eth_accounts", []).then((accounts) => { return accounts; }); } }