1
0
mirror of https://github.com/oceanprotocol-archive/squid-js.git synced 2024-02-02 15:31:51 +01:00
squid-js/src/keeper/ContractHandler.ts

45 lines
1.7 KiB
TypeScript
Raw Normal View History

2019-03-01 13:24:04 +01:00
import { Contract } from "web3-eth-contract"
2018-10-02 10:06:26 +02:00
import Logger from "../utils/Logger"
2018-10-16 14:56:18 +02:00
import Keeper from "./Keeper"
2018-10-16 15:02:44 +02:00
import Web3Provider from "./Web3Provider"
export default class ContractHandler {
2019-03-01 13:24:04 +01:00
public static async get(what: string): Promise<Contract> {
2018-10-17 18:24:01 +02:00
const where = (await (await Keeper.getInstance()).getNetworkName()).toLowerCase()
try {
return ContractHandler.contracts.get(what) || await ContractHandler.load(what, where)
2018-10-17 18:24:01 +02:00
} catch (err) {
Logger.error("Failed to load", what, "from", where, err)
throw err
}
}
2018-11-08 08:23:00 +01:00
protected static set(name: string, contractInstance: Contract) {
ContractHandler.contracts.set(name, contractInstance)
}
2018-11-08 08:23:00 +01:00
protected static has(name: string): boolean {
return ContractHandler.contracts.has(name)
}
private static contracts: Map<string, Contract> = new Map<string, Contract>()
2018-10-17 18:24:01 +02:00
private static async load(what: string, where: string): Promise<Contract> {
2018-10-16 14:56:18 +02:00
const web3 = Web3Provider.getWeb3()
Logger.debug("Loading", what, "from", where)
2018-11-26 15:55:09 +01:00
const artifact = require(`@oceanprotocol/keeper-contracts/artifacts/${what}.${where}.json`)
2018-10-17 18:24:01 +02:00
// Logger.log('Loaded artifact', artifact)
const code = await web3.eth.getCode(artifact.address)
if (code === "0x0") {
// no code in the blockchain dude
throw new Error(`No code deployed at address ${artifact.address}, sorry.`)
}
2018-10-17 18:24:01 +02:00
const contract = new web3.eth.Contract(artifact.abi, artifact.address)
Logger.debug("Getting instance of", what, "from", where, "at address", artifact.address)
ContractHandler.contracts.set(what, contract)
return ContractHandler.contracts.get(what)
}
}