diff --git a/src/poolz/ThePoolz.ts b/src/poolz/ThePoolz.ts index c10390a..2b86f68 100644 --- a/src/poolz/ThePoolz.ts +++ b/src/poolz/ThePoolz.ts @@ -271,11 +271,24 @@ class ThePoolz implements EnforceInterface { const contract = new this.web3.eth.Contract(abi as AbiItem[], address) this.#contracts.set(collectionName, contract) return contract - } catch (e) {} + } catch (e) { + throw new Error(`Failed to create contract ${name} at ${address}: ${(e as Error).message}`) + } } + /** + * Fetches ABI by contract name version from Poolz database. + * Throws an error when the request fails or the ABI is missing. + */ private async fetchContractAbi(nameVersion: string) { const response = await fetch(`https://poolzfinancedata.com/contracts?_where[0][NameVersion]=${nameVersion}`) - return (await response.json())[0].ABI + if (!response.ok) { + throw new Error(`Unable to fetch ABI for ${nameVersion}: ${response.status} ${response.statusText}`) + } + const data = await response.json() + if (!Array.isArray(data) || !data[0]?.ABI) { + throw new Error(`ABI for ${nameVersion} not found`) + } + return data[0].ABI } } diff --git a/tests/ThePoolz.test.ts b/tests/ThePoolz.test.ts index 28a412f..9cc0d74 100644 --- a/tests/ThePoolz.test.ts +++ b/tests/ThePoolz.test.ts @@ -35,6 +35,9 @@ jest.mock("web3", () => { global.fetch = jest.fn(() => Promise.resolve({ + ok: true, + status: 200, + statusText: "OK", json: () => Promise.resolve([{ ABI: { rates: { CAD: 1.42 } } }]) }) ) as jest.Mock @@ -116,4 +119,22 @@ describe("ThePoolz", () => { await thePoolz.init() expect(thePoolz.CPoolx?.address).toEqual("0x000") }) + + test("Contract ABI fetch failure", async () => { + expect.assertions(1) + ;(fetch as jest.Mock).mockImplementationOnce(() => Promise.reject(new Error("network"))) + const thePoolz = new ThePoolz({ isTrustWallet: true }) + await thePoolz.init() + await expect(thePoolz.Contract("ERC20", "0x000")).rejects.toThrow("network") + }) + + test("Contract ABI invalid data", async () => { + expect.assertions(1) + ;(fetch as jest.Mock).mockImplementationOnce(() => + Promise.resolve({ ok: true, status: 200, statusText: "OK", json: () => Promise.resolve([]) }) + ) + const thePoolz = new ThePoolz({ isTrustWallet: true }) + await thePoolz.init() + await expect(thePoolz.Contract("ERC20", "0x000")).rejects.toThrow("ABI for ERC20 not found") + }) })