From 7578f5a1d4390c13158fb77881f78dab69fec5a6 Mon Sep 17 00:00:00 2001 From: robertlincecum Date: Fri, 15 Mar 2024 16:42:52 -0500 Subject: [PATCH] Add table for provider to manage connections to multiple shards on multiple machines --- lib.commonjs/_tests/test-provider-jsonrpc.js | 162 ++ .../_tests/test-provider-jsonrpc.js.map | 1 + lib.commonjs/_tests/test-providers-data.js | 329 ++++ .../_tests/test-providers-data.js.map | 1 + lib.commonjs/_tests/test-providers-errors.js | 235 +++ .../_tests/test-providers-errors.js.map | 1 + .../_tests/test-providers-fallback.js | 69 + .../_tests/test-providers-fallback.js.map | 1 + lib.commonjs/_tests/types.d.ts | 218 +++ lib.commonjs/_tests/types.d.ts.map | 1 + lib.commonjs/_tests/types.js.map | 1 + lib.commonjs/constants/shards.d.ts.map | 1 + lib.commonjs/constants/shards.js | 76 + lib.commonjs/constants/shards.js.map | 1 + lib.commonjs/contract/contract.d.ts | 168 ++ lib.commonjs/contract/contract.d.ts.map | 1 + lib.commonjs/contract/contract.js | 966 +++++++++++ lib.commonjs/contract/contract.js.map | 1 + lib.commonjs/contract/factory.d.ts.map | 1 + lib.commonjs/contract/factory.js | 198 +++ lib.commonjs/contract/factory.js.map | 1 + lib.commonjs/contract/types.d.ts | 193 +++ lib.commonjs/contract/types.d.ts.map | 1 + lib.commonjs/contract/types.js.map | 1 + lib.commonjs/contract/wrappers.d.ts | 143 ++ lib.commonjs/contract/wrappers.d.ts.map | 1 + lib.commonjs/contract/wrappers.js | 186 +++ lib.commonjs/contract/wrappers.js.map | 1 + lib.commonjs/providers/abstract-provider.d.ts | 499 ++++++ .../providers/abstract-provider.d.ts.map | 1 + lib.commonjs/providers/abstract-provider.js | 1478 +++++++++++++++++ .../providers/abstract-provider.js.map | 1 + lib.commonjs/providers/abstract-signer.d.ts | 77 + .../providers/abstract-signer.d.ts.map | 1 + lib.commonjs/providers/abstract-signer.js | 182 ++ lib.commonjs/providers/abstract-signer.js.map | 1 + lib.commonjs/providers/default-provider.d.ts | 48 + .../providers/default-provider.d.ts.map | 1 + lib.commonjs/providers/default-provider.js | 142 ++ .../providers/default-provider.js.map | 1 + lib.commonjs/providers/formatting.d.ts.map | 1 + lib.commonjs/providers/formatting.js.map | 1 + lib.commonjs/providers/provider-fallback.js | 615 +++++++ .../providers/provider-fallback.js.map | 1 + lib.commonjs/providers/provider-jsonrpc.d.ts | 336 ++++ .../providers/provider-jsonrpc.d.ts.map | 1 + lib.commonjs/providers/provider-jsonrpc.js | 965 +++++++++++ .../providers/provider-jsonrpc.js.map | 1 + lib.commonjs/providers/provider.d.ts | 1122 +++++++++++++ lib.commonjs/providers/provider.d.ts.map | 1 + lib.commonjs/providers/provider.js | 1330 +++++++++++++++ lib.commonjs/providers/provider.js.map | 1 + lib.commonjs/transaction/transaction.d.ts | 276 +++ lib.commonjs/transaction/transaction.d.ts.map | 1 + lib.commonjs/transaction/transaction.js | 549 ++++++ lib.commonjs/transaction/transaction.js.map | 1 + lib.commonjs/wallet/base-wallet.js | 108 ++ lib.commonjs/wallet/base-wallet.js.map | 1 + lib.esm/_tests/test-provider-jsonrpc.js | 159 ++ lib.esm/_tests/test-provider-jsonrpc.js.map | 1 + lib.esm/_tests/test-providers-data.js | 326 ++++ lib.esm/_tests/test-providers-data.js.map | 1 + lib.esm/_tests/test-providers-errors.js | 232 +++ lib.esm/_tests/test-providers-errors.js.map | 1 + lib.esm/_tests/test-providers-fallback.js | 64 + lib.esm/_tests/test-providers-fallback.js.map | 1 + lib.esm/_tests/types.d.ts | 218 +++ lib.esm/_tests/types.d.ts.map | 1 + lib.esm/_tests/types.js.map | 1 + lib.esm/constants/shards.d.ts.map | 1 + lib.esm/constants/shards.js | 73 + lib.esm/constants/shards.js.map | 1 + lib.esm/contract/contract.d.ts | 168 ++ lib.esm/contract/contract.d.ts.map | 1 + lib.esm/contract/contract.js | 959 +++++++++++ lib.esm/contract/contract.js.map | 1 + lib.esm/contract/factory.d.ts.map | 1 + lib.esm/contract/factory.js | 194 +++ lib.esm/contract/factory.js.map | 1 + lib.esm/contract/types.d.ts | 193 +++ lib.esm/contract/types.d.ts.map | 1 + lib.esm/contract/types.js.map | 1 + lib.esm/contract/wrappers.d.ts | 143 ++ lib.esm/contract/wrappers.d.ts.map | 1 + lib.esm/contract/wrappers.js | 177 ++ lib.esm/contract/wrappers.js.map | 1 + lib.esm/providers/abstract-provider.d.ts | 499 ++++++ lib.esm/providers/abstract-provider.d.ts.map | 1 + lib.esm/providers/abstract-provider.js | 1473 ++++++++++++++++ lib.esm/providers/abstract-provider.js.map | 1 + lib.esm/providers/abstract-signer.d.ts | 77 + lib.esm/providers/abstract-signer.d.ts.map | 1 + lib.esm/providers/abstract-signer.js | 177 ++ lib.esm/providers/abstract-signer.js.map | 1 + lib.esm/providers/default-provider.d.ts | 48 + lib.esm/providers/default-provider.d.ts.map | 1 + lib.esm/providers/default-provider.js | 138 ++ lib.esm/providers/default-provider.js.map | 1 + lib.esm/providers/formatting.d.ts.map | 1 + lib.esm/providers/formatting.js.map | 1 + lib.esm/providers/provider-fallback.js | 611 +++++++ lib.esm/providers/provider-fallback.js.map | 1 + lib.esm/providers/provider-jsonrpc.d.ts | 336 ++++ lib.esm/providers/provider-jsonrpc.d.ts.map | 1 + lib.esm/providers/provider-jsonrpc.js | 959 +++++++++++ lib.esm/providers/provider-jsonrpc.js.map | 1 + lib.esm/providers/provider.d.ts | 1122 +++++++++++++ lib.esm/providers/provider.d.ts.map | 1 + lib.esm/providers/provider.js | 1320 +++++++++++++++ lib.esm/providers/provider.js.map | 1 + lib.esm/transaction/transaction.d.ts | 276 +++ lib.esm/transaction/transaction.d.ts.map | 1 + lib.esm/transaction/transaction.js | 545 ++++++ lib.esm/transaction/transaction.js.map | 1 + lib.esm/wallet/base-wallet.js | 104 ++ lib.esm/wallet/base-wallet.js.map | 1 + src.ts/_tests/test-provider-jsonrpc.ts | 2 + src.ts/_tests/test-providers-data.ts | 4 +- src.ts/_tests/test-providers-errors.ts | 14 +- src.ts/_tests/test-providers-fallback.ts | 2 +- src.ts/_tests/types.ts | 1 + src.ts/constants/shards.ts | 7 + src.ts/contract/contract.ts | 24 +- src.ts/contract/factory.ts | 8 +- src.ts/contract/types.ts | 3 +- src.ts/contract/wrappers.ts | 4 +- src.ts/providers/abstract-provider.ts | 633 ++++--- src.ts/providers/abstract-signer.ts | 24 +- src.ts/providers/default-provider.ts | 16 +- src.ts/providers/formatting.ts | 1 + src.ts/providers/provider-fallback.ts | 4 +- src.ts/providers/provider-jsonrpc.ts | 75 +- src.ts/providers/provider.ts | 47 +- src.ts/transaction/transaction.ts | 38 +- src.ts/wallet/base-wallet.ts | 2 +- 135 files changed, 21861 insertions(+), 373 deletions(-) create mode 100644 lib.commonjs/_tests/test-provider-jsonrpc.js create mode 100644 lib.commonjs/_tests/test-provider-jsonrpc.js.map create mode 100644 lib.commonjs/_tests/test-providers-data.js create mode 100644 lib.commonjs/_tests/test-providers-data.js.map create mode 100644 lib.commonjs/_tests/test-providers-errors.js create mode 100644 lib.commonjs/_tests/test-providers-errors.js.map create mode 100644 lib.commonjs/_tests/test-providers-fallback.js create mode 100644 lib.commonjs/_tests/test-providers-fallback.js.map create mode 100644 lib.commonjs/_tests/types.d.ts create mode 100644 lib.commonjs/_tests/types.d.ts.map create mode 100644 lib.commonjs/_tests/types.js.map create mode 100644 lib.commonjs/constants/shards.d.ts.map create mode 100644 lib.commonjs/constants/shards.js create mode 100644 lib.commonjs/constants/shards.js.map create mode 100644 lib.commonjs/contract/contract.d.ts create mode 100644 lib.commonjs/contract/contract.d.ts.map create mode 100644 lib.commonjs/contract/contract.js create mode 100644 lib.commonjs/contract/contract.js.map create mode 100644 lib.commonjs/contract/factory.d.ts.map create mode 100644 lib.commonjs/contract/factory.js create mode 100644 lib.commonjs/contract/factory.js.map create mode 100644 lib.commonjs/contract/types.d.ts create mode 100644 lib.commonjs/contract/types.d.ts.map create mode 100644 lib.commonjs/contract/types.js.map create mode 100644 lib.commonjs/contract/wrappers.d.ts create mode 100644 lib.commonjs/contract/wrappers.d.ts.map create mode 100644 lib.commonjs/contract/wrappers.js create mode 100644 lib.commonjs/contract/wrappers.js.map create mode 100644 lib.commonjs/providers/abstract-provider.d.ts create mode 100644 lib.commonjs/providers/abstract-provider.d.ts.map create mode 100644 lib.commonjs/providers/abstract-provider.js create mode 100644 lib.commonjs/providers/abstract-provider.js.map create mode 100644 lib.commonjs/providers/abstract-signer.d.ts create mode 100644 lib.commonjs/providers/abstract-signer.d.ts.map create mode 100644 lib.commonjs/providers/abstract-signer.js create mode 100644 lib.commonjs/providers/abstract-signer.js.map create mode 100644 lib.commonjs/providers/default-provider.d.ts create mode 100644 lib.commonjs/providers/default-provider.d.ts.map create mode 100644 lib.commonjs/providers/default-provider.js create mode 100644 lib.commonjs/providers/default-provider.js.map create mode 100644 lib.commonjs/providers/formatting.d.ts.map create mode 100644 lib.commonjs/providers/formatting.js.map create mode 100644 lib.commonjs/providers/provider-fallback.js create mode 100644 lib.commonjs/providers/provider-fallback.js.map create mode 100644 lib.commonjs/providers/provider-jsonrpc.d.ts create mode 100644 lib.commonjs/providers/provider-jsonrpc.d.ts.map create mode 100644 lib.commonjs/providers/provider-jsonrpc.js create mode 100644 lib.commonjs/providers/provider-jsonrpc.js.map create mode 100644 lib.commonjs/providers/provider.d.ts create mode 100644 lib.commonjs/providers/provider.d.ts.map create mode 100644 lib.commonjs/providers/provider.js create mode 100644 lib.commonjs/providers/provider.js.map create mode 100644 lib.commonjs/transaction/transaction.d.ts create mode 100644 lib.commonjs/transaction/transaction.d.ts.map create mode 100644 lib.commonjs/transaction/transaction.js create mode 100644 lib.commonjs/transaction/transaction.js.map create mode 100644 lib.commonjs/wallet/base-wallet.js create mode 100644 lib.commonjs/wallet/base-wallet.js.map create mode 100644 lib.esm/_tests/test-provider-jsonrpc.js create mode 100644 lib.esm/_tests/test-provider-jsonrpc.js.map create mode 100644 lib.esm/_tests/test-providers-data.js create mode 100644 lib.esm/_tests/test-providers-data.js.map create mode 100644 lib.esm/_tests/test-providers-errors.js create mode 100644 lib.esm/_tests/test-providers-errors.js.map create mode 100644 lib.esm/_tests/test-providers-fallback.js create mode 100644 lib.esm/_tests/test-providers-fallback.js.map create mode 100644 lib.esm/_tests/types.d.ts create mode 100644 lib.esm/_tests/types.d.ts.map create mode 100644 lib.esm/_tests/types.js.map create mode 100644 lib.esm/constants/shards.d.ts.map create mode 100644 lib.esm/constants/shards.js create mode 100644 lib.esm/constants/shards.js.map create mode 100644 lib.esm/contract/contract.d.ts create mode 100644 lib.esm/contract/contract.d.ts.map create mode 100644 lib.esm/contract/contract.js create mode 100644 lib.esm/contract/contract.js.map create mode 100644 lib.esm/contract/factory.d.ts.map create mode 100644 lib.esm/contract/factory.js create mode 100644 lib.esm/contract/factory.js.map create mode 100644 lib.esm/contract/types.d.ts create mode 100644 lib.esm/contract/types.d.ts.map create mode 100644 lib.esm/contract/types.js.map create mode 100644 lib.esm/contract/wrappers.d.ts create mode 100644 lib.esm/contract/wrappers.d.ts.map create mode 100644 lib.esm/contract/wrappers.js create mode 100644 lib.esm/contract/wrappers.js.map create mode 100644 lib.esm/providers/abstract-provider.d.ts create mode 100644 lib.esm/providers/abstract-provider.d.ts.map create mode 100644 lib.esm/providers/abstract-provider.js create mode 100644 lib.esm/providers/abstract-provider.js.map create mode 100644 lib.esm/providers/abstract-signer.d.ts create mode 100644 lib.esm/providers/abstract-signer.d.ts.map create mode 100644 lib.esm/providers/abstract-signer.js create mode 100644 lib.esm/providers/abstract-signer.js.map create mode 100644 lib.esm/providers/default-provider.d.ts create mode 100644 lib.esm/providers/default-provider.d.ts.map create mode 100644 lib.esm/providers/default-provider.js create mode 100644 lib.esm/providers/default-provider.js.map create mode 100644 lib.esm/providers/formatting.d.ts.map create mode 100644 lib.esm/providers/formatting.js.map create mode 100644 lib.esm/providers/provider-fallback.js create mode 100644 lib.esm/providers/provider-fallback.js.map create mode 100644 lib.esm/providers/provider-jsonrpc.d.ts create mode 100644 lib.esm/providers/provider-jsonrpc.d.ts.map create mode 100644 lib.esm/providers/provider-jsonrpc.js create mode 100644 lib.esm/providers/provider-jsonrpc.js.map create mode 100644 lib.esm/providers/provider.d.ts create mode 100644 lib.esm/providers/provider.d.ts.map create mode 100644 lib.esm/providers/provider.js create mode 100644 lib.esm/providers/provider.js.map create mode 100644 lib.esm/transaction/transaction.d.ts create mode 100644 lib.esm/transaction/transaction.d.ts.map create mode 100644 lib.esm/transaction/transaction.js create mode 100644 lib.esm/transaction/transaction.js.map create mode 100644 lib.esm/wallet/base-wallet.js create mode 100644 lib.esm/wallet/base-wallet.js.map diff --git a/lib.commonjs/_tests/test-provider-jsonrpc.js b/lib.commonjs/_tests/test-provider-jsonrpc.js new file mode 100644 index 00000000..1e1cc33b --- /dev/null +++ b/lib.commonjs/_tests/test-provider-jsonrpc.js @@ -0,0 +1,162 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +const assert_1 = tslib_1.__importDefault(require("assert")); +const index_js_1 = require("../index.js"); +const StatusMessages = { + 200: "OK", + 400: "BAD REQUEST", + 500: "SERVER ERROR", +}; +const wallet = new index_js_1.Wallet((0, index_js_1.id)("test")); +function createProvider(testFunc) { + let blockNumber = 1; + const ticker = setInterval(() => { blockNumber++; }, 100); + if (ticker.unref) { + ticker.unref(); + } + const processReq = (req) => { + let result = testFunc(req.method, req.params, blockNumber); + if (result === undefined) { + switch (req.method) { + case "quai_blockNumber": + result = blockNumber; + break; + case "quai_chainId": + result = "0x1337"; + break; + case "quai_accounts": + result = [wallet.address]; + break; + default: + console.log("****", req); + return { id: index_js_1.id, error: "unsupported", jsonrpc: "2.0" }; + } + } + return { id: req.id, result, jsonrpc: "2.0" }; + }; + const req = new index_js_1.FetchRequest("http:/\/localhost:8082/"); + req.getUrlFunc = async (_req, signal) => { + const req = JSON.parse(_req.hasBody() ? (0, index_js_1.toUtf8String)(_req.body) : ""); + let statusCode = 200; + const headers = {}; + let resp; + try { + if (Array.isArray(req)) { + resp = req.map((r) => processReq(r)); + } + else { + resp = processReq(req); + } + } + catch (error) { + statusCode = 500; + resp = error.message; + } + const body = (0, index_js_1.toUtf8Bytes)(JSON.stringify(resp)); + return { + statusCode, + statusMessage: StatusMessages[statusCode], + headers, body + }; + }; + return new index_js_1.JsonRpcProvider(req, undefined, { cacheTimeout: -1 }); +} +describe("Ensure Catchable Errors", function () { + it("Can catch bad broadcast replies", async function () { + this.timeout(15000); + const txInfo = { + chainId: 1337, + gasLimit: 100000, + maxFeePerGas: 2000000000, + maxPriorityFeePerGas: 1000000000, + to: wallet.address, + from: wallet.address, + value: 1, + }; + const txSign = await wallet.signTransaction(txInfo); + const txObj = index_js_1.Transaction.from(txSign); + let count = 0; + const provider = createProvider((method, params, blockNumber) => { + switch (method) { + case "quai_sendTransaction": + return txObj.hash; + case "quai_getTransactionByHash": { + count++; + // First time; fail! + if (count === 1) { + throw (0, index_js_1.makeError)("Faux Error", "SERVER_ERROR", { + request: ({}) + }); + } + // Second time; return null + if (count === 2) { + return null; + } + // Return a valid tx... + const result = Object.assign({}, txObj.toJSON(), txObj.signature.toJSON(), { hash: txObj.hash, from: wallet.address }); + // ...eventually mined + if (count > 4) { + result.blockNumber = blockNumber; + result.blockHash = (0, index_js_1.id)("test"); + } + return result; + } + } + return undefined; + }); + const signer = await provider.getSigner(); + const tx = await signer.sendTransaction(txInfo); + (0, assert_1.default)(tx); + }); + it("Missing v is recovered", async function () { + this.timeout(15000); + const txInfo = { + chainId: 1337, + gasLimit: 100000, + maxFeePerGas: 2000000000, + maxPriorityFeePerGas: 1000000000, + to: wallet.address, + from: wallet.address, + value: 1, + }; + const txSign = await wallet.signTransaction(txInfo); + const txObj = index_js_1.Transaction.from(txSign); + let count = 0; + // A provider which is mocked to return a "missing v" + // in getTransaction + const provider = createProvider((method, params, blockNumber) => { + switch (method) { + case "quai_sendTransaction": + return txObj.hash; + case "quai_getTransactionByHash": { + count++; + // The fully valid tx response + const result = Object.assign({}, txObj.toJSON(), txObj.signature.toJSON(), { hash: txObj.hash, from: wallet.address, sig: null }); + // First time; fail with a missing v! + if (count < 2) { + delete result.v; + } + // Debug + result._count = count; + return result; + } + } + return undefined; + }); + // Track any "missing v" error + let missingV = null; + provider.on("error", (e) => { + if ((0, index_js_1.isError)(e, "UNKNOWN_ERROR") && (0, index_js_1.isError)(e.error, "INVALID_ARGUMENT")) { + if (e.error.argument === "signature" && e.error.shortMessage === "missing v") { + missingV = e.error; + } + } + }); + const signer = await provider.getSigner(); + const tx = await signer.sendTransaction(txInfo); + assert_1.default.ok(!!tx, "we got a transaction"); + assert_1.default.ok(!!missingV, "missing v error present"); + }); +}); +//# sourceMappingURL=test-provider-jsonrpc.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-provider-jsonrpc.js.map b/lib.commonjs/_tests/test-provider-jsonrpc.js.map new file mode 100644 index 00000000..1a5e1032 --- /dev/null +++ b/lib.commonjs/_tests/test-provider-jsonrpc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-provider-jsonrpc.js","sourceRoot":"","sources":["../../src.ts/_tests/test-provider-jsonrpc.ts"],"names":[],"mappings":";;;AAAA,4DAA4B;AAE5B,0CAIqB;AAErB,MAAM,cAAc,GAA2B;IAC7C,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,aAAa;IAClB,GAAG,EAAE,cAAc;CACpB,CAAC;AAMF,MAAM,MAAM,GAAG,IAAI,iBAAM,CAAC,IAAA,aAAE,EAAC,MAAM,CAAC,CAAC,CAAC;AAEtC,SAAS,cAAc,CAAC,QAAwB;IAE5C,IAAI,WAAW,GAAG,CAAC,CAAC;IACpB,MAAM,MAAM,GAAG,WAAW,CAAC,GAAG,EAAE,GAAG,WAAW,EAAE,CAAA,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACzD,IAAI,MAAM,CAAC,KAAK,EAAE;QAAE,MAAM,CAAC,KAAK,EAAE,CAAC;KAAE;IAErC,MAAM,UAAU,GAAG,CAAC,GAAuD,EAAE,EAAE;QAE3E,IAAI,MAA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AAC,KAAK,EAAE,kBAAkB,CAAC,EAAE;gBACrE,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,KAAK,WAAW,IAAI,CAAC,CAAC,KAAK,CAAC,YAAY,KAAK,WAAW,EAAE;oBAC1E,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC;iBACtB;aACJ;QACL,CAAC,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,SAAS,EAAE,CAAC;QAE1C,MAAM,EAAE,GAAG,MAAM,MAAM,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;QAChD,gBAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,sBAAsB,CAAC,CAAC;QACxC,gBAAM,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,EAAE,yBAAyB,CAAC,CAAC;IACrD,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/_tests/test-providers-data.js b/lib.commonjs/_tests/test-providers-data.js new file mode 100644 index 00000000..9fe647d5 --- /dev/null +++ b/lib.commonjs/_tests/test-providers-data.js @@ -0,0 +1,329 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +const assert_1 = tslib_1.__importDefault(require("assert")); +// import { +// checkProvider, getProvider, providerNames +// } from "./create-provider.js"; +// import { retryIt } from "./utils.js"; +//import type { Provider } from "../index.js"; +const index_js_1 = require("../index.js"); +const axios_1 = tslib_1.__importDefault(require("axios")); +const utils_js_1 = require("./utils.js"); +// import { +// networkFeatureAtBlock, networkNames, +// testAddress, testBlock, testReceipt, testTransaction +// } from "./blockchain-data.js"; +// import type { TestBlockchainNetwork } from "./blockchain-data.js"; +//setupProviders(); +const providerC1 = new index_js_1.quais.JsonRpcProvider(process.env.RPC_URL); +const wallet = new index_js_1.quais.Wallet(process.env.FAUCET_PRIVATEKEY || '', providerC1); +const destinationC1 = '0x0047f9CEa7662C567188D58640ffC48901cde02a'; +const destinationC2 = '0x011ae0a1Bd5B71b4F16F8FdD3AEF278C3D042449'; +function equals(name, actual, expected) { + if (expected && expected.eq) { + if (actual == null) { + assert_1.default.ok(false, name + " - actual big number null"); + } + expected = BigInt(expected); + actual = BigInt(actual); + assert_1.default.ok(expected.eq(actual), name + " matches"); + } + else if (Array.isArray(expected)) { + if (actual == null) { + assert_1.default.ok(false, name + " - actual array null"); + } + assert_1.default.equal(actual.length, expected.length, name + " array lengths match"); + for (let i = 0; i < expected.length; i++) { + equals("(" + name + " - item " + i + ")", actual[i], expected[i]); + } + } + else if (typeof (expected) === "object") { + if (actual == null) { + if (expected === actual) { + return; + } + assert_1.default.ok(false, name + " - actual object null"); + } + let keys = {}; + Object.keys(expected).forEach((key) => { keys[key] = true; }); + Object.keys(actual).forEach((key) => { keys[key] = true; }); + Object.keys(keys).forEach((key) => { + if (typeof actual[key] === "string" && actual[key].toLowerCase && key === "type") { + actual[key] = actual[key].toLowerCase(); + } + equals("(" + name + " - key + " + key + ")", actual[key], expected[key]); + }); + } + else { + if (actual == null) { + assert_1.default.ok(false, name + " - actual null"); + } + // Modify this part for case-insensitive comparison for string values + if (typeof actual === 'string' && typeof expected === 'string') { + assert_1.default.equal(actual.toLowerCase(), expected.toLowerCase(), name + " matches (case-insensitive)"); + } + else { + assert_1.default.equal(actual, expected, name + " matches"); + } + } +} +async function getRPCGasPrice(url) { + try { + let response; + do { + response = await axios_1.default.post(url || "http://localhost:8610", { + jsonrpc: "2.0", + method: "quai_gasPrice", + params: [], + id: 1 + }); + } while (response.data.result == null); + return response.data.result; + } + catch (error) { + throw new Error(`Error fetching block: ${error.message}`); + } +} +async function sendTransaction(to) { + let txResponse; + let typeValue; + try { + console.log("Nonce: ", await providerC1.getTransactionCount(wallet.address, 'latest')); + do { + typeValue = (0, index_js_1.getTxType)(wallet.address, to); + const gas = await getRPCGasPrice(process.env.RPC_URL); + let tx = { + from: wallet.address, + to, + value: index_js_1.quais.parseEther("0.1"), + gasPrice: gas * 2, + maxFeePerGas: index_js_1.quais.parseUnits('20', 'gwei'), + maxPriorityFeePerGas: index_js_1.quais.parseUnits('20', 'gwei'), + nonce: await providerC1.getTransactionCount(wallet.address, 'latest'), + data: '', + type: typeValue, + gasLimit: typeValue == 0 ? 21000 : 42000, + chainId: Number(process.env.CHAIN_ID || 1337), + }; + txResponse = await wallet.sendTransaction(tx); + console.log(txResponse); + await (0, utils_js_1.stall)(15000); + } while (txResponse.hash == null); + console.log(`Transaction hash for type ${typeValue}: `, txResponse.hash); + return txResponse; + } + catch (error) { + console.error('Failed to send Transaction: ', error); + return null; + } +} +async function fetchRPCBlock(blockNumber) { + try { + let response; + do { + response = await axios_1.default.post(process.env.RPC_URL || "http://localhost:8610", { + jsonrpc: "2.0", + method: "quai_getBlockByNumber", + params: [ + blockNumber || '0xA', + false + ], + id: 1 + }); + } while (response.data.result.hash == null); + return response.data.result; + } + catch (error) { + throw error; + } +} +async function fetchRPCBalance(address, url) { + try { + let response; + do { + response = await axios_1.default.post(url, { + jsonrpc: "2.0", + method: "quai_getBalance", + params: [ + address, + 'latest' + ], + id: 1 + }); + } while (response.data.result == null); + return response.data.result; + } + catch (error) { + throw new Error(`Error fetching block: ${error.message}`); + } +} +async function fetchRPCTxReceipt(hash, url) { + try { + let response; + do { + response = await axios_1.default.post(url, { + jsonrpc: "2.0", + method: "quai_getTransactionReceipt", + params: [ + hash + ], + id: 1 + }); + await (0, utils_js_1.stall)(5000); + } while (response.data.result.blockHash == null); + return response.data.result; + } + catch (error) { + throw new Error(`Error fetching block: ${error.message}`); + } +} +describe("Test Provider Block operations", function () { + let block; + before(async () => { + const rpcBlock = await fetchRPCBlock('0xA'); + block = { + hash: rpcBlock.hash, + number: rpcBlock.number.map((stringNumber) => Number(stringNumber)), + transactions: rpcBlock.transactions, + parentHash: rpcBlock.parentHash, + parentEntropy: rpcBlock.parentEntropy.map((entropy) => BigInt(entropy)), + extTransactions: rpcBlock.extTransactions, + timestamp: Number(rpcBlock.timestamp), + nonce: rpcBlock.nonce, + difficulty: BigInt(rpcBlock.difficulty), + gasLimit: BigInt(rpcBlock.gasLimit), + gasUsed: BigInt(rpcBlock.gasUsed), + miner: rpcBlock.miner, + extraData: rpcBlock.extraData, + transactionsRoot: rpcBlock.transactionsRoot, + evmRoot: rpcBlock.stateRoot, + utxoRoot: rpcBlock.utxoRoot, + receiptsRoot: rpcBlock.receiptsRoot, + baseFeePerGas: BigInt(rpcBlock.baseFeePerGas), + extRollupRoot: rpcBlock.extRollupRoot, + extTransactionsRoot: rpcBlock.extTransactionsRoot, + location: rpcBlock.location, + manifestHash: rpcBlock.manifestHash, + mixHash: rpcBlock.mixHash, + order: rpcBlock.order, + parentDeltaS: rpcBlock.parentDeltaS.map((delta) => BigInt(delta)), + sha3Uncles: rpcBlock.sha3Uncles, + size: BigInt(rpcBlock.size), + uncles: rpcBlock.uncles, + subManifest: rpcBlock.subManifest, + totalEntropy: BigInt(rpcBlock.totalEntropy), + }; + }); + it('should fetch block by number', async function () { + let responseBlock = await providerC1.getBlock('0,0', '0xA'); + assert_1.default.ok(responseBlock != null, "block != null"); + let { provider, ...formatBlock } = { + ...responseBlock, + transactions: responseBlock.transactions, + extTransactions: responseBlock.extTransactions + }; + equals("Block by Number", formatBlock, block); + }); + it('should fetch block by hash', async function () { + assert_1.default.ok(block.hash != null, 'block.hash != null'); + let responseBlock = await providerC1.getBlock('0,0', block.hash); + assert_1.default.ok(responseBlock != null, "block != null"); + let { provider, ...formatBlock } = { + ...responseBlock, + transactions: responseBlock.transactions, + extTransactions: responseBlock.extTransactions + }; + equals("Block by Hash", formatBlock, block); + }); +}); +describe("Test Transaction operations", function () { + let internalTx; + let internalToExternalTx; + it('should fetch balance after internal tx', async function () { + this.timeout(60000); + const oldBal = await fetchRPCBalance(destinationC1, process.env.RPC_URL || "http://localhost:8610"); + internalTx = await sendTransaction(destinationC1); + await (0, utils_js_1.stall)(30000); + const expectedBal = BigInt(internalTx.value); + const balance = await providerC1.getBalance(destinationC1); + const actualBal = Number(balance) - Number(oldBal); + assert_1.default.equal(actualBal, Number(expectedBal)); + }); + it('should get transaction receipt for internal tx', async function () { + this.timeout(60000); + const receipt = await fetchRPCTxReceipt(internalTx.hash, process.env.RPC_URL || "http://localhost:8610"); + const expectedReceipt = { + blockHash: receipt.blockHash, + contractAddress: receipt.contractAddress || null, + blockNumber: Number(receipt.blockNumber), + cumulativeGasUsed: BigInt(receipt.cumulativeGasUsed), + gasPrice: BigInt(receipt.effectiveGasPrice), + etxs: receipt.etxs, + gasUsed: BigInt(receipt.gasUsed), + logs: receipt.logs, + logsBloom: receipt.logsBloom, + status: Number(receipt.status), + to: receipt.to, + from: receipt.from, + hash: receipt.transactionHash, + index: Number(receipt.transactionIndex), + type: receipt.type, + }; + const receiptResponse = await providerC1.getTransactionReceipt(internalTx.hash); + let { provider, ...receiptResult } = { + ...receiptResponse, + logs: receiptResponse?.logs + }; + equals("Internal Tx Receipt", receiptResult, expectedReceipt); + }); + it("should fetch transaction receipt for internal to external tx", async function () { + this.timeout(120000); + internalToExternalTx = await sendTransaction(destinationC2); + await (0, utils_js_1.stall)(60000); + const receipt = await fetchRPCTxReceipt(internalToExternalTx.hash, process.env.RPC_URL || "http://localhost:8610"); + await (0, utils_js_1.stall)(30000); + const etx = receipt.etxs[0]; + const expectedReceipt = { + blockHash: receipt.blockHash, + blockNumber: Number(receipt.blockNumber), + contractAddress: receipt.contractAddress || null, + cumulativeGasUsed: BigInt(receipt.cumulativeGasUsed), + gasPrice: BigInt(receipt.effectiveGasPrice), + etxs: [ + { + type: Number(etx.type), + nonce: Number(etx.nonce), + maxPriorityFeePerGas: BigInt(etx.maxPriorityFeePerGas), + maxFeePerGas: BigInt(etx.maxFeePerGas), + gas: BigInt(etx.gas), + value: BigInt(etx.value), + input: etx.input, + to: etx.to, + from: etx.sender, + hash: etx.hash, + chainId: Number(etx.chainId), + accessList: etx.accessList, + } + ], + gasUsed: BigInt(receipt.gasUsed), + logs: receipt.logs, + logsBloom: receipt.logsBloom, + status: Number(receipt.status), + to: receipt.to, + from: receipt.from, + hash: receipt.transactionHash, + index: Number(receipt.transactionIndex), + type: Number(receipt.type), + }; + const receiptResponse = await providerC1.getTransactionReceipt(internalToExternalTx.hash); + let { provider, ...receiptResult } = { + ...receiptResponse, + logs: receiptResponse?.logs + }; + console.log(receiptResult); + console.log(expectedReceipt); + equals("Internal to External Tx Receipt", receiptResult, expectedReceipt); + }); +}); +//# sourceMappingURL=test-providers-data.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-providers-data.js.map b/lib.commonjs/_tests/test-providers-data.js.map new file mode 100644 index 00000000..c0a50cd3 --- /dev/null +++ b/lib.commonjs/_tests/test-providers-data.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-providers-data.js","sourceRoot":"","sources":["../../src.ts/_tests/test-providers-data.ts"],"names":[],"mappings":";;;AAAA,4DAA4B;AAE5B,WAAW;AACX,gDAAgD;AAChD,iCAAiC;AACjC,wCAAwC;AAExC,8CAA8C;AAC9C,0CAA+C;AAC/C,0DAA0B;AAC1B,yCAAmC;AACnC,WAAW;AACX,2CAA2C;AAC3C,2DAA2D;AAC3D,iCAAiC;AAEjC,qEAAqE;AAGrE,mBAAmB;AAGnB,MAAM,UAAU,GAAG,IAAI,gBAAK,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAClE,MAAM,MAAM,GAAG,IAAI,gBAAK,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,IAAI,EAAE,EAAE,UAAU,CAAC,CAAC;AACjF,MAAM,aAAa,GAAG,4CAA4C,CAAA;AAClE,MAAM,aAAa,GAAG,4CAA4C,CAAA;AAElE,SAAS,MAAM,CAAC,IAAY,EAAE,MAAW,EAAE,QAAa;IACpD,IAAI,QAAQ,IAAI,QAAQ,CAAC,EAAE,EAAE;QACzB,IAAI,MAAM,IAAI,IAAI,EAAE;YAAE,gBAAM,CAAC,EAAE,CAAC,KA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AAE,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC;SAC7B,CAAA;QACD,MAAM,eAAe,GAAG,MAAM,UAAU,CAAC,qBAAqB,CAAC,oBAAoB,CAAC,IAAI,CAAC,CAAC;QAC1F,IAAI,EAAE,QAAQ,EAAE,GAAG,aAAa,EAAE,GAAG;YACjC,GAAG,eAAe;YAClB,IAAI,EAAE,eAAe,EAAE,IAAI;SAC9B,CAAC;QACF,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;QAC3B,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAA;QAC5B,MAAM,CAAC,iCAAiC,EAAE,aAAa,EAAE,eAAe,CAAC,CAAC;IAC9E,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAA"} \ No newline at end of file diff --git a/lib.commonjs/_tests/test-providers-errors.js b/lib.commonjs/_tests/test-providers-errors.js new file mode 100644 index 00000000..93a2f58d --- /dev/null +++ b/lib.commonjs/_tests/test-providers-errors.js @@ -0,0 +1,235 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +const assert_1 = tslib_1.__importDefault(require("assert")); +const index_js_1 = require("../index.js"); +const create_provider_js_1 = require("./create-provider.js"); +const utils_js_1 = require("./utils.js"); +//require('dotenv').config(); +const dotenv_1 = tslib_1.__importDefault(require("dotenv")); +dotenv_1.default.config(); +(0, create_provider_js_1.setupProviders)(); +describe("Tests Provider Call Exception", function () { + const panics = [ + //{ code: 0x00, reason: "GENERIC_PANIC" }, + { code: 0x01, reason: "ASSERT_FALSE" }, + { code: 0x11, reason: "OVERFLOW" }, + { code: 0x12, reason: "DIVIDE_BY_ZERO" }, + //{ code: 0x21, reason: "ENUM_RANGE_ERROR" }, + //{ code: 0x22, reason: "BAD_STORAGE_DATA" }, + { code: 0x31, reason: "STACK_UNDERFLOW" }, + { code: 0x32, reason: "ARRAY_RANGE_ERROR" }, + //{ code: 0x41, reason: "OUT_OF_MEMORY" }, + //{ code: 0x51, reason: "UNINITIALIZED_FUNCTION_CALL" }, + ]; + const testAddr = "0x0aff86a125b29b25a9e418c2fb64f1753532c0ca"; //Cyprus1 + const testAddr2 = "0x0aff86a125b29b25a9e418c2fb64f1753532c0ca"; //Cyprus1 + const networkName = "colosseum"; + for (const { code, reason } of panics) { + for (const method of ["call", "estimateGas"]) { + for (const providerName of create_provider_js_1.providerNames) { + const provider = (0, create_provider_js_1.getProvider)(providerName, networkName); + if (provider == null) { + continue; + } + it(`tests panic code: ${providerName}.${method}.${reason}`, async function () { + this.timeout(10000); + const data = (0, index_js_1.concat)([ + (0, index_js_1.dataSlice)((0, index_js_1.id)("testPanic(uint256)"), 0, 4), + (0, index_js_1.zeroPadValue)((0, index_js_1.toBeArray)(code), 32) + ]); + await (0, utils_js_1.stall)(1000); + const tx = { to: testAddr, from: testAddr2, data }; + try { + const result = await (method === "call" ? provider.call(tx) : provider.estimateGas(tx)); + console.log(result); + assert_1.default.ok(false, "panic call did not throw"); + } + catch (error) { + assert_1.default.ok((0, index_js_1.isCallException)(error), "isCallException"); + // Check some basics + assert_1.default.equal(error.action, method, `error.action == ${method}`); + assert_1.default.equal(error.reason, `Panic due to ${reason}(${code})`, "error.reason"); + // Check the transaciton + assert_1.default.equal(error.transaction.to, tx.to, `error.transaction.to`); + assert_1.default.equal(error.transaction.data, tx.data, `error.transaction.data`); + // We have no invocation data + assert_1.default.equal(error.invocation, null, `error.invocation != null`); + // Check the revert + assert_1.default.ok(error.revert != null, "error.revert == null"); + assert_1.default.equal(error.revert.name, "Panic", `error.revert.name`); + assert_1.default.equal(error.revert.signature, "Panic(uint256)", `error.revert.signature`); + assert_1.default.equal(error.revert.args.length, 1, `error.revert.args.length`); + assert_1.default.equal(error.revert.args[0], code, `error.revert.args[0]`); + } + }); + } + } + } + const customErrors = [ + { + name: "CustomError1", + signature: "testCustomError1(bool,uint256,string)", + data: "0xdb7342480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000b68656c6c6f20776f726c64000000000000000000000000000000000000000000", + //data: "0x852d0c740000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000", + message: `execution reverted (unknown custom error)`, + reason: null, + revert: null, + }, + { + name: "Error", + signature: "testErrorString(bool,string)", + data: "0xb206699b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000b68656c6c6f20776f726c64000000000000000000000000000000000000000000", + //data: "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000" + message: `execution reverted: "hello world"`, + reason: "hello world", + revert: { + signature: "Error(string)", + name: "Error", + args: ['hello world'] + } + }, + ]; + for (const { data, message, name, reason, revert } of customErrors) { + for (const method of ["call", "estimateGas"]) { + const tx = { to: testAddr, from: testAddr2, data }; + for (const providerName of create_provider_js_1.providerNames) { + const provider = (0, create_provider_js_1.getProvider)(providerName, networkName); + if (provider == null) { + continue; + } + it(`tests custom errors: ${providerName}.${method}.${name}`, async function () { + this.timeout(10000); + try { + const result = await (method === "call" ? provider.call(tx) : provider.estimateGas(tx)); + console.log(result); + assert_1.default.ok(false, "panic call did not throw"); + } + catch (error) { + assert_1.default.ok((0, index_js_1.isCallException)(error), "isCallException"); + // Check some basics + assert_1.default.equal(error.action, method, `error.action == ${method}`); + assert_1.default.ok(error.message.startsWith(message), "error.message == message"); + if (reason) { + assert_1.default.equal(error.reason, reason, "error.reason"); + } + else { + assert_1.default.ok(error.reason == null, "error.reason != null"); + } + if (revert) { + assert_1.default.ok(error.revert != null, "error.revert == null"); + assert_1.default.equal(error.revert.name, revert.name, "error.revert.name"); + assert_1.default.equal(error.revert.signature, revert.signature, "error.revert.signature"); + assert_1.default.equal(error.revert.args.length, revert.args.length, "error.revert.args.length"); + for (let i = 0; i < revert.args.length; i++) { + assert_1.default.equal(error.revert.args[i], revert.args[i], `error.revert.args[${i}]`); + } + } + else { + assert_1.default.ok(error.revert == null, "error.revert != null"); + } + } + }); + } + } + } +}); +describe("Test Provider Blockchain Errors", function () { + const wallet = new index_js_1.Wallet((process.env.FAUCET_PRIVATEKEY)); + const wallet2 = new index_js_1.Wallet((process.env.FAUCET_PRIVATEKEY)); + const networkName = "colosseum"; + for (const providerName of create_provider_js_1.providerNames) { + const provider = (0, create_provider_js_1.getProvider)(providerName, networkName); + if (provider == null) { + continue; + } + // The CI runs multiple tests at once; minimize colliding with + // the initial tx by using a random value, so we can detect + // replacements we didn't do. + const value = Math.trunc(Math.random() * 2048) + 2; + it(`tests underpriced replacement transaction: ${providerName}`, async function () { + this.timeout(60000); + const w = wallet.connect(provider); + let tx1 = null; + let nonce = null; + ; + for (let i = 0; i < 10; i++) { + nonce = await w.getNonce("pending"); + try { + tx1 = await w.sendTransaction({ + nonce, to: wallet, from: wallet2, value + }); + } + catch (error) { + // Another CI host beat us to this nonce + if ((0, index_js_1.isError)(error, "REPLACEMENT_UNDERPRICED") || (0, index_js_1.isError)(error, "NONCE_EXPIRED")) { + await (0, utils_js_1.stall)(1000); + continue; + } + console.log("EE-tx1", nonce, value, error); + throw error; + } + break; + } + if (tx1 == null || nonce == null) { + throw new Error("could not send initial tx"); + } + const rejection = assert_1.default.rejects(async function () { + // Send another tx with the same nonce + const tx2 = await w.sendTransaction({ + nonce, to: wallet, from: wallet2, value: 1 + }); + console.log({ tx1, tx2 }); + }, (error) => { + return (0, index_js_1.isError)(error, "REPLACEMENT_UNDERPRICED"); + }); + // Wait for the first tx to get mined so we start with a + // clean slate on the next provider + await tx1.wait(); + // This should have already happened + await rejection; + }); + } + for (const providerName of create_provider_js_1.providerNames) { + const provider = (0, create_provider_js_1.getProvider)(providerName, networkName); + if (provider == null) { + continue; + } + it(`tests insufficient funds: ${providerName}`, async function () { + this.timeout(60000); + const w = index_js_1.Wallet.createRandom("m/44'/60'/0'/0/0").connect(provider); + await assert_1.default.rejects(async function () { + const tx = await w.sendTransaction({ + to: wallet, from: wallet2, value: 1 + }); + console.log(tx); + }, (error) => { + return ((0, index_js_1.isError)(error, "INSUFFICIENT_FUNDS") && + typeof (error.transaction.from) === "string" && + error.transaction.from.toLowerCase() === w.address.toLowerCase()); + }); + }); + } + for (const providerName of create_provider_js_1.providerNames) { + const provider = (0, create_provider_js_1.getProvider)(providerName, networkName); + if (provider == null) { + continue; + } + it(`tests nonce expired: ${providerName}`, async function () { + this.timeout(60000); + const w = wallet.connect(provider); + await assert_1.default.rejects(async function () { + const tx = await w.sendTransaction({ + to: wallet, from: wallet2, value: 1 + }); + console.log(tx); + }, (error) => { + if (!(0, index_js_1.isError)(error, "NONCE_EXPIRED")) { + console.log(error); + } + return (0, index_js_1.isError)(error, "NONCE_EXPIRED"); + }); + }); + } +}); +//# sourceMappingURL=test-providers-errors.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-providers-errors.js.map b/lib.commonjs/_tests/test-providers-errors.js.map new file mode 100644 index 00000000..85645cc2 --- /dev/null +++ b/lib.commonjs/_tests/test-providers-errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-providers-errors.js","sourceRoot":"","sources":["../../src.ts/_tests/test-providers-errors.ts"],"names":[],"mappings":";;;AACA,4DAA4B;AAE5B,0CAIqB;AAErB,6DAAkF;AAClF,yCAAmC;AAGnC,6BAA6B;AAC7B,4DAA4B;AAC5B,gBAAM,CAAC,MAAM,EAAE,CAAC;AAehB,IAAA,mCAAc,GAAE,CAAC;AAEjB,QAAQ,CAAC,+BAA+B,EAAE;IAEtC,MAAM,MAAM,GAA4C;QACpD,0CAA0C;QAC1C,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,cAAc,EAAE;QACtC,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,UAAU,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AAoB,CAAC;oBACxC,OAAM,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,QAAQ;oBAC3C,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;YAC1E,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;KACN;IAED,KAAK,MAAM,YAAY,IAAI,kCAAa,EAAE;QAEtC,MAAM,QAAQ,GAAG,IAAA,gCAAW,EAAC,YAAY,EAAE,WAAW,CAAC,CAAC;QACxD,IAAI,QAAQ,IAAI,IAAI,EAAE;YAAE,SAAS;SAAE;QAEnC,EAAE,CAAC,wBAAyB,YAAa,EAAE,EAAE,KAAK;YAC9C,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAEpB,MAAM,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;YAEnC,MAAM,gBAAM,CAAC,OAAO,CAAC,KAAK;gBACtB,MAAM,EAAE,GAAG,MAAM,CAAC,CAAC,eAAe,CAAC;oBAC/B,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;iBACtC,CAAC,CAAC;gBACH,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YACpB,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE;gBACT,IAAI,CAAC,IAAA,kBAAO,EAAC,KAAK,EAAE,eAAe,CAAC,EAAE;oBAClC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;iBACtB;gBACD,OAAO,IAAA,kBAAO,EAAC,KAAK,EAAE,eAAe,CAAC,CAAC;YAC3C,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;KACN;AAEL,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/_tests/test-providers-fallback.js b/lib.commonjs/_tests/test-providers-fallback.js new file mode 100644 index 00000000..1c015df1 --- /dev/null +++ b/lib.commonjs/_tests/test-providers-fallback.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MockProvider = void 0; +const tslib_1 = require("tslib"); +const assert_1 = tslib_1.__importDefault(require("assert")); +const index_js_1 = require("../index.js"); +const network = index_js_1.Network.from("mainnet"); +function stall(duration) { + return new Promise((resolve) => { setTimeout(resolve, duration); }); +} +class MockProvider extends index_js_1.AbstractProvider { + _perform; + constructor(perform) { + super(network, { cacheTimeout: -1 }); + this._perform = perform; + } + async _detectNetwork() { return network; } + async perform(req) { + return await this._perform(req); + } +} +exports.MockProvider = MockProvider; +describe("Test Fallback broadcast", function () { + const txHash = "0xe9fb92945282cf04f7bb3027d690fdaab6d601c99a7cdd0a5eb41d1a5c0893d5"; + async function test(actions) { + const tx = "0x00f8788223288202898504a817c8008504a817c800825208940aff86a125b29b25a9e418c2fb64f1753532c0ca88016345785d8a000080c001a0711d47f0f6828721f336430ca87277534d0134de5f04ce3629085f8d5371c129a061c4838dec40c296cfad6fe771d502c26e209089124e6f702c64353b3ca195c1"; + const providers = actions.map(({ timeout, error }) => { + return new MockProvider(async (r) => { + if (r.method === "getBlockNumber") { + return 1; + } + if (r.method === "broadcastTransaction") { + await stall(timeout); + if (error) { + throw error; + } + return txHash; + } + throw new Error(`unhandled method: ${r.method}`); + }); + }); + ; + const provider = new index_js_1.FallbackProvider(providers); + return await provider.broadcastTransaction('0,1', tx); + } + it("picks late non-failed broadcasts", async function () { + const result = await test([ + { timeout: 200, error: (0, index_js_1.makeError)("already seen", "UNKNOWN_ERROR") }, + { timeout: 4000, error: (0, index_js_1.makeError)("already seen", "UNKNOWN_ERROR") }, + { timeout: 400 }, + ]); + (0, assert_1.default)(result.hash === txHash, "result.hash === txHash"); + }); + it("insufficient funds short-circuit broadcast", async function () { + await assert_1.default.rejects(async function () { + const result = await test([ + { timeout: 200, error: (0, index_js_1.makeError)("is broke", "INSUFFICIENT_FUNDS") }, + { timeout: 400, error: (0, index_js_1.makeError)("is broke", "INSUFFICIENT_FUNDS") }, + { timeout: 800 }, + { timeout: 1000 }, + ]); + console.log(result); + }, function (error) { + (0, assert_1.default)((0, index_js_1.isError)(error, "INSUFFICIENT_FUNDS")); + return true; + }); + }); +}); +//# sourceMappingURL=test-providers-fallback.js.map \ No newline at end of file diff --git a/lib.commonjs/_tests/test-providers-fallback.js.map b/lib.commonjs/_tests/test-providers-fallback.js.map new file mode 100644 index 00000000..a3ebc1a8 --- /dev/null +++ b/lib.commonjs/_tests/test-providers-fallback.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-providers-fallback.js","sourceRoot":"","sources":["../../src.ts/_tests/test-providers-fallback.ts"],"names":[],"mappings":";;;;AAAA,4DAA4B;AAE5B,0CAIqB;AAQrB,MAAM,OAAO,GAAG,kBAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;AAExC,SAAS,KAAK,CAAC,QAAgB;IAC3B,OAAQ,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,GAAG,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACzE,CAAC;AAKD,MAAa,YAAa,SAAQ,2BAAgB;IACrC,QAAQ,CAAY;IAE7B,YAAY,OAAkB;QAC1B,KAAK,CAAC,OAAO,EAAE,EAAE,YAAY,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;QACrC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC5B,CAAC;IAED,KAAK,CAAC,cAAc,KAAuB,OAAO,OAAO,CAAC,CAAC,CAAC;IAE5D,KAAK,CAAC,OAAO,CAAC,GAAyB;QACnC,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IACpC,CAAC;CACJ;AAbD,oCAaC;AAED,QAAQ,CAAC,yBAAyB,EAAE;IAEhC,MAAM,MAAM,GAAG,oEAAoE,CAAC;IAEpF,KAAK,UAAU,IAAI,CAAC,OAAk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QAClD,MAAM,gBAAM,CAAC,OAAO,CAAC,KAAK;YACtB,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC;gBACtB,EAAE,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,IAAA,oBAAS,EAAC,UAAU,EAAE,oBAAoB,CAAC,EAAE;gBACpE,EAAE,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,IAAA,oBAAS,EAAC,UAAU,EAAE,oBAAoB,CAAC,EAAE;gBACpE,EAAE,OAAO,EAAE,GAAG,EAAE;gBAChB,EAAE,OAAO,EAAE,IAAI,EAAE;aACpB,CAAC,CAAC;YACH,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACxB,CAAC,EAAE,UAAS,KAAc;YACtB,IAAA,gBAAM,EAAC,IAAA,kBAAO,EAAC,KAAK,EAAE,oBAAoB,CAAC,CAAC,CAAC;YAC7C,OAAO,IAAI,CAAC;QAChB,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/_tests/types.d.ts b/lib.commonjs/_tests/types.d.ts new file mode 100644 index 00000000..fcd151ca --- /dev/null +++ b/lib.commonjs/_tests/types.d.ts @@ -0,0 +1,218 @@ +export type TestCaseAbiVerbose = { + type: "address" | "hexstring" | "number" | "string"; + value: string; +} | { + type: "boolean"; + value: boolean; +} | { + type: "array"; + value: Array; +} | { + type: "object"; + value: Array; +}; +export interface TestCaseAbi { + name: string; + type: string; + value: any; + verbose: TestCaseAbiVerbose; + bytecode: string; + encoded: string; +} +export interface TestCaseAccount { + name: string; + privateKey: string; + address: string; + icap: string; +} +export type TestCaseCreate = { + sender: string; + creates: Array<{ + name: string; + nonce: number; + address: string; + }>; +}; +export type TestCaseCreate2 = { + sender: string; + creates: Array<{ + name: string; + salt: string; + initCode: string; + initCodeHash: string; + address: string; + }>; +}; +export interface TestCaseHash { + name: string; + data: string; + sha256: string; + sha512: string; + ripemd160: string; + keccak256: string; +} +export interface TestCasePbkdf { + name: string; + password: string; + salt: string; + dkLen: number; + pbkdf2: { + iterations: number; + algorithm: "sha256" | "sha512"; + key: string; + }; + scrypt: { + N: number; + r: number; + p: number; + key: string; + }; +} +export interface TestCaseHmac { + name: string; + data: string; + key: string; + algorithm: "sha256" | "sha512"; + hmac: string; +} +export interface TestCaseHash { + name: string; + data: string; + sha256: string; + sha512: string; + ripemd160: string; + keccak256: string; +} +export interface TestCaseNamehash { + name: string; + ensName: string; + error?: string; + namehash?: string; +} +export interface TestCaseTypedDataDomain { + name?: string; + version?: string; + chainId?: number; + verifyingContract?: string; + salt?: string; +} +export interface TestCaseTypedDataType { + name: string; + type: string; +} +export interface TestCaseTypedData { + name: string; + domain: TestCaseTypedDataDomain; + primaryType: string; + types: Record>; + data: any; + encoded: string; + digest: string; + privateKey?: string; + signature?: string; +} +export interface TestCaseSolidityHash { + name: string; + types: Array; + keccak256: string; + ripemd160: string; + sha256: string; + values: Array; +} +export interface TestCaseUnit { + name: string; + wei: string; + quais: string; + ether_format: string; + kwei?: string; + mwei?: string; + gwei?: string; + szabo?: string; + finney?: string; + finney_format?: string; + szabo_format?: string; + gwei_format?: string; + mwei_format?: string; + kwei_format?: string; +} +export type NestedHexString = string | Array; +export interface TestCaseRlp { + name: string; + encoded: string; + decoded: NestedHexString; +} +export interface TestCaseTransactionTx { + to?: string; + from: string; + nonce?: number; + gasLimit?: string; + gasPrice?: string; + maxFeePerGas?: string; + maxPriorityFeePerGas?: string; + data?: string; + value?: string; + accessList?: Array<{ + address: string; + storageKeys: Array; + }>; + chainId?: string; +} +export interface TestCaseTransactionSig { + r: string; + s: string; + v: string; +} +export interface TestCaseTransaction { + name: string; + transaction: TestCaseTransactionTx; + privateKey: string; + unsignedLegacy: string; + signedLegacy: string; + unsignedEip155: string; + signedEip155: string; + unsignedBerlin: string; + signedBerlin: string; + unsignedLondon: string; + signedLondon: string; + signatureLegacy: TestCaseTransactionSig; + signatureEip155: TestCaseTransactionSig; + signatureBerlin: TestCaseTransactionSig; + signatureLondon: TestCaseTransactionSig; +} +export interface TestCaseMnemonicNode { + path: string; + chainCode: string; + depth: number; + index: number; + parentFingerprint: string; + fingerprint: string; + publicKey: string; + privateKey: string; + xpriv: string; + xpub: string; +} +export interface TestCaseMnemonic { + name: string; + phrase: string; + phraseHash: string; + password: string; + locale: string; + entropy: string; + seed: string; + nodes: Array; +} +export interface TestCaseWallet { + name: string; + filename: string; + type: string; + address: string; + password: string; + content: string; +} +export interface TestCaseWordlist { + name: string; + filename: string; + locale: string; + content: string; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/lib.commonjs/_tests/types.d.ts.map b/lib.commonjs/_tests/types.d.ts.map new file mode 100644 index 00000000..53aa7770 --- /dev/null +++ b/lib.commonjs/_tests/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src.ts/_tests/types.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,kBAAkB,GAAG;IAC7B,IAAI,EAAE,SAAS,GAAG,WAAW,GAAG,QAAQ,GAAG,QAAQ,CAAC;IACpD,KAAK,EAAE,MAAM,CAAA;CAChB,GAAG;IACA,IAAI,EAAE,SAAS,CAAC;IAChB,KAAK,EAAE,OAAO,CAAA;CACjB,GAAG;IACA,IAAI,EAAE,OAAO,CAAC;IACd,KAAK,EAAE,KAAK,CAAC,kBAAkB,CAAC,CAAA;CACnC,GAAG;IACA,IAAI,EAAE,QAAQ,CAAC;IACf,KAAK,EAAE,KAAK,CAAC,kBAAkB,CAAC,CAAA;CACnC,CAAA;AAED,MAAM,WAAW,WAAW;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,GAAG,CAAC;IACX,OAAO,EAAE,kBAAkB,CAAC;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CACnB;AAKD,MAAM,WAAW,eAAe;IAC5B,IA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CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,KAAK,CAAC,oBAAoB,CAAC,CAAC;CACtC;AAED,MAAM,WAAW,cAAc;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CACnB;AAKD,MAAM,WAAW,gBAAgB;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CACnB"} \ No newline at end of file diff --git a/lib.commonjs/_tests/types.js.map b/lib.commonjs/_tests/types.js.map new file mode 100644 index 00000000..e5fe2d97 --- /dev/null +++ b/lib.commonjs/_tests/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src.ts/_tests/types.ts"],"names":[],"mappings":";;AA6PC,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/constants/shards.d.ts.map b/lib.commonjs/constants/shards.d.ts.map new file mode 100644 index 00000000..09ab3283 --- /dev/null +++ b/lib.commonjs/constants/shards.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"shards.d.ts","sourceRoot":"","sources":["../../src.ts/constants/shards.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,SAAS;;;;;;GAuErB,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/constants/shards.js b/lib.commonjs/constants/shards.js new file mode 100644 index 00000000..76b41f4d --- /dev/null +++ b/lib.commonjs/constants/shards.js @@ -0,0 +1,76 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ShardData = void 0; +exports.ShardData = [ + { + name: "Cyprus One", + nickname: 'cyprus1', + shard: "zone-0-0", + context: 2, + byte: "0x00" //0000 0000 region-0 zone-0 + }, + { + name: "Cyprus Two", + nickname: 'cyprus2', + shard: "zone-0-1", + context: 2, + byte: "0x01" // 0000 0001 region-0 zone-1 + }, + { + name: "Cyprus Three", + nickname: 'cyprus3', + shard: "zone-0-2", + context: 2, + byte: "0x02" // 0000 0010 region-0 zone-2 + }, + { + name: "Paxos One", + nickname: 'paxos1', + shard: "zone-1-0", + context: 2, + byte: "0x10" // 0001 0000 region-1 zone-0 + }, + { + name: "Paxos Two", + nickname: 'paxos2', + shard: "zone-1-1", + context: 2, + byte: "0x11" // 0001 0001 region-1 zone-1 + }, + { + name: "Paxos Three", + nickname: 'paxos3', + shard: "zone-1-2", + context: 2, + byte: "0x12" // 0001 0010 region-1 zone-2 + }, + { + name: "Hydra One", + nickname: 'hydra1', + shard: "zone-2-0", + context: 2, + byte: "0x20" // 0010 0000 region-2 zone-0 + }, + { + name: "Hydra Two", + nickname: 'hydra2', + shard: "zone-2-1", + context: 2, + byte: "0x21" // 0010 0001 region-2 zone-1 + }, + { + name: "Hydra Three", + nickname: 'hydra3', + shard: "zone-2-2", + context: 2, + byte: "0x22" // 0010 0010 region-2 zone-2 + }, + { + name: "Prime", + nickname: 'prime', + shard: "prime", + context: 2, + byte: "0x" + } +]; +//# sourceMappingURL=shards.js.map \ No newline at end of file diff --git a/lib.commonjs/constants/shards.js.map b/lib.commonjs/constants/shards.js.map new file mode 100644 index 00000000..1442e994 --- /dev/null +++ b/lib.commonjs/constants/shards.js.map @@ -0,0 +1 @@ +{"version":3,"file":"shards.js","sourceRoot":"","sources":["../../src.ts/constants/shards.ts"],"names":[],"mappings":";;;AAAa,QAAA,SAAS,GAAG;IACvB;QACI,IAAI,EAAE,YAAY;QAClB,QAAQ,EAAE,SAAS;QACnB,KAAK,EAAE,UAAU;QACj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C5C;IACD;QACI,IAAI,EAAE,OAAO;QACb,QAAQ,EAAE,OAAO;QACjB,KAAK,EAAE,OAAO;QACd,OAAO,EAAE,CAAC;QACV,IAAI,EAAE,IAAI;KACb;CACF,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/contract/contract.d.ts b/lib.commonjs/contract/contract.d.ts new file mode 100644 index 00000000..2a0a7be8 --- /dev/null +++ b/lib.commonjs/contract/contract.d.ts @@ -0,0 +1,168 @@ +import { Interface } from "../abi/index.js"; +import { Log, TransactionResponse } from "../providers/provider.js"; +import { ContractTransactionResponse, EventLog } from "./wrappers.js"; +import type { EventFragment, FunctionFragment, InterfaceAbi, ParamType } from "../abi/index.js"; +import type { Addressable } from "../address/index.js"; +import type { EventEmitterable, Listener } from "../utils/index.js"; +import type { BlockTag, ContractRunner } from "../providers/index.js"; +import type { ContractEventName, ContractInterface, ContractMethod, ContractEvent, ContractTransaction, WrappedFallback } from "./types.js"; +/** + * @_ignore: + */ +export declare function copyOverrides(arg: any, allowed?: Array): Promise>; +/** + * @_ignore: + */ +export declare function resolveArgs(_runner: null | ContractRunner, inputs: ReadonlyArray, args: Array): Promise>; +declare const internal: unique symbol; +export declare class BaseContract implements Addressable, EventEmitterable { + /** + * The target to connect to. + * + * This can be an address, ENS name or any [[Addressable]], such as + * another contract. To get the resovled address, use the ``getAddress`` + * method. + */ + readonly target: string | Addressable; + /** + * The contract Interface. + */ + readonly interface: Interface; + /** + * The connected runner. This is generally a [[Provider]] or a + * [[Signer]], which dictates what operations are supported. + * + * For example, a **Contract** connected to a [[Provider]] may + * only execute read-only operations. + */ + readonly runner: null | ContractRunner; + /** + * All the Events available on this contract. + */ + readonly filters: Record; + /** + * @_ignore: + */ + readonly [internal]: any; + /** + * The fallback or receive function if any. + */ + readonly fallback: null | WrappedFallback; + /** + * Creates a new contract connected to %%target%% with the %%abi%% and + * optionally connected to a %%runner%% to perform operations on behalf + * of. + */ + constructor(target: string | Addressable, abi: Interface | InterfaceAbi, runner?: null | ContractRunner, _deployTx?: null | TransactionResponse); + /** + * Return a new Contract instance with the same target and ABI, but + * a different %%runner%%. + */ + connect(runner: null | ContractRunner): BaseContract; + /** + * Return a new Contract instance with the same ABI and runner, but + * a different %%target%%. + */ + attach(target: string | Addressable): BaseContract; + /** + * Return the resolved address of this Contract. + */ + getAddress(): Promise; + /** + * Return the deployed bytecode or null if no bytecode is found. + */ + getDeployedCode(): Promise; + /** + * Resolve to this Contract once the bytecode has been deployed, or + * resolve immediately if already deployed. + */ + waitForDeployment(): Promise; + /** + * Return the transaction used to deploy this contract. + * + * This is only available if this instance was returned from a + * [[ContractFactory]]. + */ + deploymentTransaction(): null | ContractTransactionResponse; + /** + * Return the function for a given name. This is useful when a contract + * method name conflicts with a JavaScript name such as ``prototype`` or + * when using a Contract programatically. + */ + getFunction(key: string | FunctionFragment): T; + /** + * Return the event for a given name. This is useful when a contract + * event name conflicts with a JavaScript name such as ``prototype`` or + * when using a Contract programatically. + */ + getEvent(key: string | EventFragment): ContractEvent; + /** + * @_ignore: + */ + queryTransaction(hash: string): Promise>; + /** + * Provide historic access to event data for %%event%% in the range + * %%fromBlock%% (default: ``0``) to %%toBlock%% (default: ``"latest"``) + * inclusive. + */ + queryFilter(shard: string, event: ContractEventName, fromBlock?: BlockTag, toBlock?: BlockTag): Promise>; + /** + * Add an event %%listener%% for the %%event%%. + */ + on(event: ContractEventName, listener: Listener): Promise; + /** + * Add an event %%listener%% for the %%event%%, but remove the listener + * after it is fired once. + */ + once(event: ContractEventName, listener: Listener): Promise; + /** + * Emit an %%event%% calling all listeners with %%args%%. + * + * Resolves to ``true`` if any listeners were called. + */ + emit(event: ContractEventName, ...args: Array): Promise; + /** + * Resolves to the number of listeners of %%event%% or the total number + * of listeners if unspecified. + */ + listenerCount(event?: ContractEventName): Promise; + /** + * Resolves to the listeners subscribed to %%event%% or all listeners + * if unspecified. + */ + listeners(event?: ContractEventName): Promise>; + /** + * Remove the %%listener%% from the listeners for %%event%% or remove + * all listeners if unspecified. + */ + off(event: ContractEventName, listener?: Listener): Promise; + /** + * Remove all the listeners for %%event%% or remove all listeners if + * unspecified. + */ + removeAllListeners(event?: ContractEventName): Promise; + /** + * Alias for [on]. + */ + addListener(event: ContractEventName, listener: Listener): Promise; + /** + * Alias for [off]. + */ + removeListener(event: ContractEventName, listener: Listener): Promise; + /** + * Create a new Class for the %%abi%%. + */ + static buildClass(abi: Interface | InterfaceAbi): new (target: string, runner?: null | ContractRunner) => BaseContract & Omit; + /** + * Create a new BaseContract with a specified Interface. + */ + static from(target: string, abi: Interface | InterfaceAbi, runner?: null | ContractRunner): BaseContract & Omit; +} +declare const Contract_base: new (target: string, abi: Interface | InterfaceAbi, runner?: ContractRunner | null | undefined) => BaseContract & Omit; +/** + * A [[BaseContract]] with no type guards on its methods or events. + */ +export declare class Contract extends Contract_base { +} +export {}; +//# sourceMappingURL=contract.d.ts.map \ No newline at end of file diff --git a/lib.commonjs/contract/contract.d.ts.map b/lib.commonjs/contract/contract.d.ts.map new file mode 100644 index 00000000..bd14a80e --- /dev/null +++ b/lib.commonjs/contract/contract.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../../src.ts/contract/contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAS,MAAM,iBAAiB,CAAC;AAInD,OAAO,EAAe,GAAG,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAMjF,OAAO,EAEH,2BAA2B,EAC3B,QAAQ,EACX,MAAM,eAAe,CAAC;AAEvB,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,YAAY,EAAE,SAAS,EAAU,MAAM,iBAAiB,CAAC;AACxG,OAAO,KAAK,EAAE,WAAW,EAAgB,MAAM,qBAAqB,CAAC;AACrE,OAAO,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EACR,QAAQ,EAAE,cAAc,EAC3B,MAAM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contract.js b/lib.commonjs/contract/contract.js new file mode 100644 index 00000000..ecbf273d --- /dev/null +++ b/lib.commonjs/contract/contract.js @@ -0,0 +1,966 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Contract = exports.BaseContract = exports.resolveArgs = exports.copyOverrides = void 0; +const index_js_1 = require("../abi/index.js"); +const index_js_2 = require("../address/index.js"); +// import from provider.ts instead of index.ts to prevent circular dep +// from quaiscanProvider +const provider_js_1 = require("../providers/provider.js"); +const index_js_3 = require("../utils/index.js"); +const wrappers_js_1 = require("./wrappers.js"); +const BN_0 = BigInt(0); +function canCall(value) { + return (value && typeof (value.call) === "function"); +} +function canEstimate(value) { + return (value && typeof (value.estimateGas) === "function"); +} +function canResolve(value) { + return (value && typeof (value.resolveName) === "function"); +} +function canSend(value) { + return (value && typeof (value.sendTransaction) === "function"); +} +function getResolver(value) { + if (value != null) { + if (canResolve(value)) { + return value; + } + if (value.provider) { + return value.provider; + } + } + return undefined; +} +class PreparedTopicFilter { + #filter; + fragment; + constructor(contract, fragment, args) { + (0, index_js_3.defineProperties)(this, { fragment }); + if (fragment.inputs.length < args.length) { + throw new Error("too many arguments"); + } + // Recursively descend into args and resolve any addresses + const runner = getRunner(contract.runner, "resolveName"); + const resolver = canResolve(runner) ? runner : null; + this.#filter = (async function () { + const resolvedArgs = await Promise.all(fragment.inputs.map((param, index) => { + const arg = args[index]; + if (arg == null) { + return null; + } + return param.walkAsync(args[index], (type, value) => { + if (type === "address") { + if (Array.isArray(value)) { + return Promise.all(value.map((v) => (0, index_js_2.resolveAddress)(v, resolver))); + } + return (0, index_js_2.resolveAddress)(value, resolver); + } + return value; + }); + })); + return contract.interface.encodeFilterTopics(fragment, resolvedArgs); + })(); + } + getTopicFilter() { + return this.#filter; + } +} +// A = Arguments passed in as a tuple +// R = The result type of the call (i.e. if only one return type, +// the qualified type, otherwise Result) +// D = The type the default call will return (i.e. R for view/pure, +// TransactionResponse otherwise) +//export interface ContractMethod = Array, R = any, D extends R | ContractTransactionResponse = ContractTransactionResponse> { +function getRunner(value, feature) { + if (value == null) { + return null; + } + if (typeof (value[feature]) === "function") { + return value; + } + if (value.provider && typeof (value.provider[feature]) === "function") { + return value.provider; + } + return null; +} +function getProvider(value) { + if (value == null) { + return null; + } + return value.provider || null; +} +/** + * @_ignore: + */ +async function copyOverrides(arg, allowed) { + // Make sure the overrides passed in are a valid overrides object + const _overrides = index_js_1.Typed.dereference(arg, "overrides"); + (0, index_js_3.assertArgument)(typeof (_overrides) === "object", "invalid overrides parameter", "overrides", arg); + // Create a shallow copy (we'll deep-ify anything needed during normalizing) + const overrides = (0, provider_js_1.copyRequest)(_overrides); + (0, index_js_3.assertArgument)(overrides.to == null || (allowed || []).indexOf("to") >= 0, "cannot override to", "overrides.to", overrides.to); + (0, index_js_3.assertArgument)(overrides.data == null || (allowed || []).indexOf("data") >= 0, "cannot override data", "overrides.data", overrides.data); + // Resolve any from + if (overrides.from) { + overrides.from = overrides.from; + } + return overrides; +} +exports.copyOverrides = copyOverrides; +/** + * @_ignore: + */ +async function resolveArgs(_runner, inputs, args) { + // Recursively descend into args and resolve any addresses + const runner = getRunner(_runner, "resolveName"); + const resolver = canResolve(runner) ? runner : null; + return await Promise.all(inputs.map((param, index) => { + return param.walkAsync(args[index], (type, value) => { + value = index_js_1.Typed.dereference(value, type); + if (type === "address") { + return (0, index_js_2.resolveAddress)(value, resolver); + } + return value; + }); + })); +} +exports.resolveArgs = resolveArgs; +function buildWrappedFallback(contract) { + const populateTransaction = async function (overrides) { + // If an overrides was passed in, copy it and normalize the values + const tx = (await copyOverrides(overrides, ["data"])); + tx.to = await contract.getAddress(); + if (tx.from) { + tx.from = await (0, index_js_2.resolveAddress)(tx.from, getResolver(contract.runner)); + } + const iface = contract.interface; + const noValue = ((0, index_js_3.getBigInt)((tx.value || BN_0), "overrides.value") === BN_0); + const noData = ((tx.data || "0x") === "0x"); + if (iface.fallback && !iface.fallback.payable && iface.receive && !noData && !noValue) { + (0, index_js_3.assertArgument)(false, "cannot send data to receive or send value to non-payable fallback", "overrides", overrides); + } + (0, index_js_3.assertArgument)(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data); + // Only allow payable contracts to set non-zero value + const payable = iface.receive || (iface.fallback && iface.fallback.payable); + (0, index_js_3.assertArgument)(payable || noValue, "cannot send value to non-payable fallback", "overrides.value", tx.value); + // Only allow fallback contracts to set non-empty data + (0, index_js_3.assertArgument)(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data); + return tx; + }; + const staticCall = async function (overrides) { + const runner = getRunner(contract.runner, "call"); + (0, index_js_3.assert)(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" }); + const tx = await populateTransaction(overrides); + try { + return await runner.call(tx); + } + catch (error) { + if ((0, index_js_3.isCallException)(error) && error.data) { + throw contract.interface.makeError(error.data, tx); + } + throw error; + } + }; + const send = async function (overrides) { + const runner = contract.runner; + (0, index_js_3.assert)(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" }); + const tx = await runner.sendTransaction(await populateTransaction(overrides)); + const provider = getProvider(contract.runner); + // @TODO: the provider can be null; make a custom dummy provider that will throw a + // meaningful error + return new wrappers_js_1.ContractTransactionResponse(contract.interface, provider, tx); + }; + const estimateGas = async function (overrides) { + const runner = getRunner(contract.runner, "estimateGas"); + (0, index_js_3.assert)(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }); + return await runner.estimateGas(await populateTransaction(overrides)); + }; + const method = async (overrides) => { + return await send(overrides); + }; + (0, index_js_3.defineProperties)(method, { + _contract: contract, + estimateGas, + populateTransaction, + send, staticCall + }); + return method; +} +function buildWrappedMethod(contract, key) { + const getFragment = function (...args) { + const fragment = contract.interface.getFunction(key, args); + (0, index_js_3.assert)(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key, args } + }); + return fragment; + }; + const populateTransaction = async function (...args) { + const fragment = getFragment(...args); + // If an overrides was passed in, copy it and normalize the values + let overrides; + if (fragment.inputs.length + 1 === args.length) { + overrides = await copyOverrides(args.pop()); + const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args); + return Object.assign({}, overrides, await (0, index_js_3.resolveProperties)({ + to: contract.getAddress(), + data: contract.interface.encodeFunctionData(fragment, resolvedArgs) + })); + // if (overrides.from) { + // overrides.from = await resolveAddress(overrides.from, getResolver(contract.runner)); + // } + } + if (fragment.inputs.length !== args.length) { + throw new Error("internal error: fragment inputs doesn't match arguments; should not happen"); + } + const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args); + return await (0, index_js_3.resolveProperties)({ + to: contract.getAddress(), + from: args.pop().from, + data: contract.interface.encodeFunctionData(fragment, resolvedArgs) + }); + }; + const staticCall = async function (...args) { + const result = await staticCallResult(...args); + if (result.length === 1) { + return result[0]; + } + return result; + }; + const send = async function (...args) { + const runner = contract.runner; + (0, index_js_3.assert)(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" }); + const tx = await runner.sendTransaction(await populateTransaction(...args)); + const provider = getProvider(contract.runner); + // @TODO: the provider can be null; make a custom dummy provider that will throw a + // meaningful error + return new wrappers_js_1.ContractTransactionResponse(contract.interface, provider, tx); + }; + const estimateGas = async function (...args) { + const runner = getRunner(contract.runner, "estimateGas"); + (0, index_js_3.assert)(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }); + return await runner.estimateGas(await populateTransaction(...args)); + }; + const staticCallResult = async function (...args) { + const runner = getRunner(contract.runner, "call"); + (0, index_js_3.assert)(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" }); + const tx = await populateTransaction(...args); + let result = "0x"; + try { + result = await runner.call(tx); + } + catch (error) { + if ((0, index_js_3.isCallException)(error) && error.data) { + throw contract.interface.makeError(error.data, tx); + } + throw error; + } + const fragment = getFragment(...args); + return contract.interface.decodeFunctionResult(fragment, result); + }; + const method = async (...args) => { + const fragment = getFragment(...args); + if (fragment.constant) { + return await staticCall(...args); + } + return await send(...args); + }; + (0, index_js_3.defineProperties)(method, { + name: contract.interface.getFunctionName(key), + _contract: contract, _key: key, + getFragment, + estimateGas, + populateTransaction, + send, staticCall, staticCallResult, + }); + // Only works on non-ambiguous keys (refined fragment is always non-ambiguous) + Object.defineProperty(method, "fragment", { + configurable: false, + enumerable: true, + get: () => { + const fragment = contract.interface.getFunction(key); + (0, index_js_3.assert)(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key } + }); + return fragment; + } + }); + return method; +} +function buildWrappedEvent(contract, key) { + const getFragment = function (...args) { + const fragment = contract.interface.getEvent(key, args); + (0, index_js_3.assert)(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key, args } + }); + return fragment; + }; + const method = function (...args) { + return new PreparedTopicFilter(contract, getFragment(...args), args); + }; + (0, index_js_3.defineProperties)(method, { + name: contract.interface.getEventName(key), + _contract: contract, _key: key, + getFragment + }); + // Only works on non-ambiguous keys (refined fragment is always non-ambiguous) + Object.defineProperty(method, "fragment", { + configurable: false, + enumerable: true, + get: () => { + const fragment = contract.interface.getEvent(key); + (0, index_js_3.assert)(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key } + }); + return fragment; + } + }); + return method; +} +// The combination of TypeScrype, Private Fields and Proxies makes +// the world go boom; so we hide variables with some trickery keeping +// a symbol attached to each BaseContract which its sub-class (even +// via a Proxy) can reach and use to look up its internal values. +const internal = Symbol.for("_quaisInternal_contract"); +const internalValues = new WeakMap(); +function setInternal(contract, values) { + internalValues.set(contract[internal], values); +} +function getInternal(contract) { + return internalValues.get(contract[internal]); +} +function isDeferred(value) { + return (value && typeof (value) === "object" && ("getTopicFilter" in value) && + (typeof (value.getTopicFilter) === "function") && value.fragment); +} +async function getSubInfo(contract, event) { + let topics; + let fragment = null; + // Convert named events to topicHash and get the fragment for + // events which need deconstructing. + if (Array.isArray(event)) { + const topicHashify = function (name) { + if ((0, index_js_3.isHexString)(name, 32)) { + return name; + } + const fragment = contract.interface.getEvent(name); + (0, index_js_3.assertArgument)(fragment, "unknown fragment", "name", name); + return fragment.topicHash; + }; + // Array of Topics and Names; e.g. `[ "0x1234...89ab", "Transfer(address)" ]` + topics = event.map((e) => { + if (e == null) { + return null; + } + if (Array.isArray(e)) { + return e.map(topicHashify); + } + return topicHashify(e); + }); + } + else if (event === "*") { + topics = [null]; + } + else if (typeof (event) === "string") { + if ((0, index_js_3.isHexString)(event, 32)) { + // Topic Hash + topics = [event]; + } + else { + // Name or Signature; e.g. `"Transfer", `"Transfer(address)"` + fragment = contract.interface.getEvent(event); + (0, index_js_3.assertArgument)(fragment, "unknown fragment", "event", event); + topics = [fragment.topicHash]; + } + } + else if (isDeferred(event)) { + // Deferred Topic Filter; e.g. `contract.filter.Transfer(from)` + topics = await event.getTopicFilter(); + } + else if ("fragment" in event) { + // ContractEvent; e.g. `contract.filter.Transfer` + fragment = event.fragment; + topics = [fragment.topicHash]; + } + else { + (0, index_js_3.assertArgument)(false, "unknown event name", "event", event); + } + // Normalize topics and sort TopicSets + topics = topics.map((t) => { + if (t == null) { + return null; + } + if (Array.isArray(t)) { + const items = Array.from(new Set(t.map((t) => t.toLowerCase())).values()); + if (items.length === 1) { + return items[0]; + } + items.sort(); + return items; + } + return t.toLowerCase(); + }); + const tag = topics.map((t) => { + if (t == null) { + return "null"; + } + if (Array.isArray(t)) { + return t.join("|"); + } + return t; + }).join("&"); + return { fragment, tag, topics }; +} +async function hasSub(contract, event) { + const { subs } = getInternal(contract); + return subs.get((await getSubInfo(contract, event)).tag) || null; +} +async function getSub(contract, operation, event) { + // Make sure our runner can actually subscribe to events + const provider = getProvider(contract.runner); + (0, index_js_3.assert)(provider, "contract runner does not support subscribing", "UNSUPPORTED_OPERATION", { operation }); + const { fragment, tag, topics } = await getSubInfo(contract, event); + const { addr, subs } = getInternal(contract); + let sub = subs.get(tag); + if (!sub) { + const address = (addr ? addr : contract); + const filter = { address, topics }; + const listener = (log) => { + let foundFragment = fragment; + if (foundFragment == null) { + try { + foundFragment = contract.interface.getEvent(log.topics[0]); + } + catch (error) { } + } + // If fragment is null, we do not deconstruct the args to emit + if (foundFragment) { + const _foundFragment = foundFragment; + const args = fragment ? contract.interface.decodeEventLog(fragment, log.data, log.topics) : []; + emit(contract, event, args, (listener) => { + return new wrappers_js_1.ContractEventPayload(contract, listener, event, _foundFragment, log); + }); + } + else { + emit(contract, event, [], (listener) => { + return new wrappers_js_1.ContractUnknownEventPayload(contract, listener, event, log); + }); + } + }; + let starting = []; + const start = () => { + if (starting.length) { + return; + } + starting.push(provider.on(filter, listener)); + }; + const stop = async () => { + if (starting.length == 0) { + return; + } + let started = starting; + starting = []; + await Promise.all(started); + provider.off(filter, listener); + }; + sub = { tag, listeners: [], start, stop }; + subs.set(tag, sub); + } + return sub; +} +// We use this to ensure one emit resolves before firing the next to +// ensure correct ordering (note this cannot throw and just adds the +// notice to the event queu using setTimeout). +let lastEmit = Promise.resolve(); +async function _emit(contract, event, args, payloadFunc) { + await lastEmit; + const sub = await hasSub(contract, event); + if (!sub) { + return false; + } + const count = sub.listeners.length; + sub.listeners = sub.listeners.filter(({ listener, once }) => { + const passArgs = Array.from(args); + if (payloadFunc) { + passArgs.push(payloadFunc(once ? null : listener)); + } + try { + listener.call(contract, ...passArgs); + } + catch (error) { } + return !once; + }); + if (sub.listeners.length === 0) { + sub.stop(); + getInternal(contract).subs.delete(sub.tag); + } + return (count > 0); +} +async function emit(contract, event, args, payloadFunc) { + try { + await lastEmit; + } + catch (error) { } + const resultPromise = _emit(contract, event, args, payloadFunc); + lastEmit = resultPromise; + return await resultPromise; +} +const passProperties = ["then"]; +class BaseContract { + /** + * The target to connect to. + * + * This can be an address, ENS name or any [[Addressable]], such as + * another contract. To get the resovled address, use the ``getAddress`` + * method. + */ + target; + /** + * The contract Interface. + */ + interface; + /** + * The connected runner. This is generally a [[Provider]] or a + * [[Signer]], which dictates what operations are supported. + * + * For example, a **Contract** connected to a [[Provider]] may + * only execute read-only operations. + */ + runner; + /** + * All the Events available on this contract. + */ + filters; + /** + * @_ignore: + */ + [internal]; + /** + * The fallback or receive function if any. + */ + fallback; + /** + * Creates a new contract connected to %%target%% with the %%abi%% and + * optionally connected to a %%runner%% to perform operations on behalf + * of. + */ + constructor(target, abi, runner, _deployTx) { + (0, index_js_3.assertArgument)(typeof (target) === "string" || (0, index_js_2.isAddressable)(target), "invalid value for Contract target", "target", target); + if (runner == null) { + runner = null; + } + const iface = index_js_1.Interface.from(abi); + (0, index_js_3.defineProperties)(this, { target, runner, interface: iface }); + Object.defineProperty(this, internal, { value: {} }); + let addrPromise; + let addr = null; + let deployTx = null; + if (_deployTx) { + const provider = getProvider(runner); + // @TODO: the provider can be null; make a custom dummy provider that will throw a + // meaningful error + deployTx = new wrappers_js_1.ContractTransactionResponse(this.interface, provider, _deployTx); + } + let subs = new Map(); + // Resolve the target as the address + if (typeof (target) === "string") { + if ((0, index_js_3.isHexString)(target)) { + addr = target; + addrPromise = Promise.resolve(target); + } + else { + const resolver = getRunner(runner, "resolveName"); + if (!canResolve(resolver)) { + throw (0, index_js_3.makeError)("contract runner does not support name resolution", "UNSUPPORTED_OPERATION", { + operation: "resolveName" + }); + } + addrPromise = resolver.resolveName(target).then((addr) => { + if (addr == null) { + throw (0, index_js_3.makeError)("an ENS name used for a contract target must be correctly configured", "UNCONFIGURED_NAME", { + value: target + }); + } + getInternal(this).addr = addr; + return addr; + }); + } + } + else { + addrPromise = target.getAddress().then((addr) => { + if (addr == null) { + throw new Error("TODO"); + } + getInternal(this).addr = addr; + return addr; + }); + } + // Set our private values + setInternal(this, { addrPromise, addr, deployTx, subs }); + // Add the event filters + const filters = new Proxy({}, { + get: (target, prop, receiver) => { + // Pass important checks (like `then` for Promise) through + if (typeof (prop) === "symbol" || passProperties.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); + } + try { + return this.getEvent(prop); + } + catch (error) { + if (!(0, index_js_3.isError)(error, "INVALID_ARGUMENT") || error.argument !== "key") { + throw error; + } + } + return undefined; + }, + has: (target, prop) => { + // Pass important checks (like `then` for Promise) through + if (passProperties.indexOf(prop) >= 0) { + return Reflect.has(target, prop); + } + return Reflect.has(target, prop) || this.interface.hasEvent(String(prop)); + } + }); + (0, index_js_3.defineProperties)(this, { filters }); + (0, index_js_3.defineProperties)(this, { + fallback: ((iface.receive || iface.fallback) ? (buildWrappedFallback(this)) : null) + }); + // Return a Proxy that will respond to functions + return new Proxy(this, { + get: (target, prop, receiver) => { + if (typeof (prop) === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); + } + // Undefined properties should return undefined + try { + return target.getFunction(prop); + } + catch (error) { + if (!(0, index_js_3.isError)(error, "INVALID_ARGUMENT") || error.argument !== "key") { + throw error; + } + } + return undefined; + }, + has: (target, prop) => { + if (typeof (prop) === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) { + return Reflect.has(target, prop); + } + return target.interface.hasFunction(prop); + } + }); + } + /** + * Return a new Contract instance with the same target and ABI, but + * a different %%runner%%. + */ + connect(runner) { + return new BaseContract(this.target, this.interface, runner); + } + /** + * Return a new Contract instance with the same ABI and runner, but + * a different %%target%%. + */ + attach(target) { + return new BaseContract(target, this.interface, this.runner); + } + /** + * Return the resolved address of this Contract. + */ + async getAddress() { return await getInternal(this).addrPromise; } + /** + * Return the deployed bytecode or null if no bytecode is found. + */ + async getDeployedCode() { + const provider = getProvider(this.runner); + (0, index_js_3.assert)(provider, "runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "getDeployedCode" }); + const code = await provider.getCode(await this.getAddress()); + if (code === "0x") { + return null; + } + return code; + } + /** + * Resolve to this Contract once the bytecode has been deployed, or + * resolve immediately if already deployed. + */ + async waitForDeployment() { + // We have the deployement transaction; just use that (throws if deployement fails) + const deployTx = this.deploymentTransaction(); + if (deployTx) { + await deployTx.wait(); + return this; + } + // Check for code + const code = await this.getDeployedCode(); + if (code != null) { + return this; + } + // Make sure we can subscribe to a provider event + const provider = getProvider(this.runner); + (0, index_js_3.assert)(provider != null, "contract runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "waitForDeployment" }); + return new Promise((resolve, reject) => { + const checkCode = async () => { + try { + const code = await this.getDeployedCode(); + if (code != null) { + return resolve(this); + } + provider.once("block", checkCode); + } + catch (error) { + reject(error); + } + }; + checkCode(); + }); + } + /** + * Return the transaction used to deploy this contract. + * + * This is only available if this instance was returned from a + * [[ContractFactory]]. + */ + deploymentTransaction() { + return getInternal(this).deployTx; + } + /** + * Return the function for a given name. This is useful when a contract + * method name conflicts with a JavaScript name such as ``prototype`` or + * when using a Contract programatically. + */ + getFunction(key) { + if (typeof (key) !== "string") { + key = key.format(); + } + const func = buildWrappedMethod(this, key); + return func; + } + /** + * Return the event for a given name. This is useful when a contract + * event name conflicts with a JavaScript name such as ``prototype`` or + * when using a Contract programatically. + */ + getEvent(key) { + if (typeof (key) !== "string") { + key = key.format(); + } + return buildWrappedEvent(this, key); + } + /** + * @_ignore: + */ + async queryTransaction(hash) { + throw new Error("@TODO"); + } + /* + // @TODO: this is a non-backwards compatible change, but will be added + // in v7 and in a potential SmartContract class in an upcoming + // v6 release + async getTransactionReceipt(hash: string): Promise { + const provider = getProvider(this.runner); + assert(provider, "contract runner does not have a provider", + "UNSUPPORTED_OPERATION", { operation: "queryTransaction" }); + + const receipt = await provider.getTransactionReceipt(hash); + if (receipt == null) { return null; } + + return new ContractTransactionReceipt(this.interface, provider, receipt); + } + */ + /** + * Provide historic access to event data for %%event%% in the range + * %%fromBlock%% (default: ``0``) to %%toBlock%% (default: ``"latest"``) + * inclusive. + */ + async queryFilter(shard, event, fromBlock, toBlock) { + if (fromBlock == null) { + fromBlock = 0; + } + if (toBlock == null) { + toBlock = "latest"; + } + const { addr, addrPromise } = getInternal(this); + const address = (addr ? addr : (await addrPromise)); + const { fragment, topics } = await getSubInfo(this, event); + const filter = { address, topics, fromBlock, toBlock, shard: shard }; + const provider = getProvider(this.runner); + (0, index_js_3.assert)(provider, "contract runner does not have a provider", "UNSUPPORTED_OPERATION", { operation: "queryFilter" }); + return (await provider.getLogs(filter)).map((log) => { + let foundFragment = fragment; + if (foundFragment == null) { + try { + foundFragment = this.interface.getEvent(log.topics[0]); + } + catch (error) { } + } + if (foundFragment) { + try { + return new wrappers_js_1.EventLog(log, this.interface, foundFragment); + } + catch (error) { + return new wrappers_js_1.UndecodedEventLog(log, error); + } + } + return new provider_js_1.Log(log, provider); + }); + } + /** + * Add an event %%listener%% for the %%event%%. + */ + async on(event, listener) { + const sub = await getSub(this, "on", event); + sub.listeners.push({ listener, once: false }); + sub.start(); + return this; + } + /** + * Add an event %%listener%% for the %%event%%, but remove the listener + * after it is fired once. + */ + async once(event, listener) { + const sub = await getSub(this, "once", event); + sub.listeners.push({ listener, once: true }); + sub.start(); + return this; + } + /** + * Emit an %%event%% calling all listeners with %%args%%. + * + * Resolves to ``true`` if any listeners were called. + */ + async emit(event, ...args) { + return await emit(this, event, args, null); + } + /** + * Resolves to the number of listeners of %%event%% or the total number + * of listeners if unspecified. + */ + async listenerCount(event) { + if (event) { + const sub = await hasSub(this, event); + if (!sub) { + return 0; + } + return sub.listeners.length; + } + const { subs } = getInternal(this); + let total = 0; + for (const { listeners } of subs.values()) { + total += listeners.length; + } + return total; + } + /** + * Resolves to the listeners subscribed to %%event%% or all listeners + * if unspecified. + */ + async listeners(event) { + if (event) { + const sub = await hasSub(this, event); + if (!sub) { + return []; + } + return sub.listeners.map(({ listener }) => listener); + } + const { subs } = getInternal(this); + let result = []; + for (const { listeners } of subs.values()) { + result = result.concat(listeners.map(({ listener }) => listener)); + } + return result; + } + /** + * Remove the %%listener%% from the listeners for %%event%% or remove + * all listeners if unspecified. + */ + async off(event, listener) { + const sub = await hasSub(this, event); + if (!sub) { + return this; + } + if (listener) { + const index = sub.listeners.map(({ listener }) => listener).indexOf(listener); + if (index >= 0) { + sub.listeners.splice(index, 1); + } + } + if (listener == null || sub.listeners.length === 0) { + sub.stop(); + getInternal(this).subs.delete(sub.tag); + } + return this; + } + /** + * Remove all the listeners for %%event%% or remove all listeners if + * unspecified. + */ + async removeAllListeners(event) { + if (event) { + const sub = await hasSub(this, event); + if (!sub) { + return this; + } + sub.stop(); + getInternal(this).subs.delete(sub.tag); + } + else { + const { subs } = getInternal(this); + for (const { tag, stop } of subs.values()) { + stop(); + subs.delete(tag); + } + } + return this; + } + /** + * Alias for [on]. + */ + async addListener(event, listener) { + return await this.on(event, listener); + } + /** + * Alias for [off]. + */ + async removeListener(event, listener) { + return await this.off(event, listener); + } + /** + * Create a new Class for the %%abi%%. + */ + static buildClass(abi) { + class CustomContract extends BaseContract { + constructor(address, runner = null) { + super(address, abi, runner); + } + } + return CustomContract; + } + ; + /** + * Create a new BaseContract with a specified Interface. + */ + static from(target, abi, runner) { + if (runner == null) { + runner = null; + } + const contract = new this(target, abi, runner); + return contract; + } +} +exports.BaseContract = BaseContract; +function _ContractBase() { + return BaseContract; +} +/** + * A [[BaseContract]] with no type guards on its methods or events. + */ +class Contract extends _ContractBase() { +} +exports.Contract = Contract; +//# sourceMappingURL=contract.js.map \ No newline at end of file diff --git a/lib.commonjs/contract/contract.js.map b/lib.commonjs/contract/contract.js.map new file mode 100644 index 00000000..c0ac465a --- /dev/null +++ b/lib.commonjs/contract/contract.js.map @@ -0,0 +1 @@ +{"version":3,"file":"contract.js","sourceRoot":"","sources":["../../src.ts/contract/contract.ts"],"names":[],"mappings":";;;AAAA,8CAAmD;AACnD,kDAAoE;AACpE,sEAAsE;AACtE,wBAAwB;AACxB,0DAAiF;AACjF,gDAG2B;AAE3B,+CAIuB;AAsBvB,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAkBvB,SAAS,OAAO,CAAC,KAAU;IACvB,OAAO,CAAC,KAAK,IAAI,OAAM,CAAC,KAAK,CAAC,IAAI,C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file mode 100644 index 00000000..6cba74a2 --- /dev/null +++ b/lib.commonjs/contract/factory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../../src.ts/contract/factory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAM5C,OAAO,EAAE,YAAY,EAA8B,MAAM,eAAe,CAAC;AAEzE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAChF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEnD,OAAO,KAAK,EACR,iBAAiB,EAAE,kBAAkB,EAAE,yBAAyB,EACnE,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AASjE;;GAEG;AACH,qBAAa,eAAe,CAAC,CAAC,SAAS,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY;IAE5E;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAG,SAAS,CAAC;IAE/B;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAG,MAAM,CAAC;IAE3B;;OAEG;IACH,QAAQ,CAAC,MAAM,EAAG,IAAI,GAAG,cAAc,CAAC;IAExC;;;;;;OAMG;gBACS,GAAG,EAAE,SAAS,GAAG,YAAY,EAAE,QAAQ,EAAE,SAAS,GAAG;QAAE,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,MAAM,CAAC,EAAE,IAAI,GAAG,cAAc;IAkBnH,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,GAAG,YAAY,GAAG,IAAI,CAAC,CAAC,EAAE,MAAM,YAAY,CAAC;IAIhF;;;OAGG;IACG,oBAAoB,CAAC,GAAG,IAAI,EAAE,kBAAkB,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,yBAAyB,CAAC;IA2E9F;;;;;;;OAOG;IACG,MAAM,CAAC,GAAG,IAAI,EAAE,kBAAkB,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,YAAY,GAAG;QAAE,qBAAqB,IAAI,2BAA2B,CAAA;KAAE,GAAG,IAAI,CAAC,CAAC,EAAE,MAAM,YAAY,CAAC,CAAC;IAsBhK,MAAM,CAAC,kBAAkB,CAAC,WAAW,EAAE;QACnC,IAAI,EAAE,MAAM,CAAC;QACb,KAAK,EAAE,MAAM,CAAC;QACd,IAAI,EAAE,SAAS,CAAC;KACnB,GAAG,MAAM;IAQA,oBAAoB,CACtB,EAAE,EAAE,kBAAkB,GACrB,OAAO,CAAC,kBAAkB,CAAC;IAwBhC;;;OAGG;IACH,OAAO,CAAC,MAAM,EAAE,IAAI,GAAG,cAAc,GAAG,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC;IAI7D;;OAEG;IACH,MAAM,CAAC,YAAY,CAAC,CAAC,SAAS,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,iBAAiB,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,EAAE,cAAc,GAAG,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC;CAgB7I"} \ No newline at end of file diff --git a/lib.commonjs/contract/factory.js b/lib.commonjs/contract/factory.js new file mode 100644 index 00000000..858294aa --- /dev/null +++ b/lib.commonjs/contract/factory.js @@ -0,0 +1,198 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ContractFactory = void 0; +const index_js_1 = require("../abi/index.js"); +const index_js_2 = require("../utils/index.js"); +const contract_js_1 = require("./contract.js"); +const index_js_3 = require("../utils/index.js"); +const quais_js_1 = require("../quais.js"); +const address_js_1 = require("../address/address.js"); +const properties_js_1 = require("../utils/properties.js"); +// A = Arguments to the constructor +// I = Interface of deployed contracts +/** + * A **ContractFactory** is used to deploy a Contract to the blockchain. + */ +class ContractFactory { + /** + * The Contract Interface. + */ + interface; + /** + * The Contract deployment bytecode. Often called the initcode. + */ + bytecode; + /** + * The ContractRunner to deploy the Contract as. + */ + runner; + /** + * Create a new **ContractFactory** with %%abi%% and %%bytecode%%, + * optionally connected to %%runner%%. + * + * The %%bytecode%% may be the ``bytecode`` property within the + * standard Solidity JSON output. + */ + constructor(abi, bytecode, runner) { + const iface = index_js_1.Interface.from(abi); + // Dereference Solidity bytecode objects and allow a missing `0x`-prefix + if (bytecode instanceof Uint8Array) { + bytecode = (0, index_js_2.hexlify)((0, index_js_2.getBytes)(bytecode)); + } + else { + if (typeof (bytecode) === "object") { + bytecode = bytecode.object; + } + if (!bytecode.startsWith("0x")) { + bytecode = "0x" + bytecode; + } + bytecode = (0, index_js_2.hexlify)((0, index_js_2.getBytes)(bytecode)); + } + (0, index_js_2.defineProperties)(this, { + bytecode, interface: iface, runner: (runner || null) + }); + } + attach(target) { + return new contract_js_1.BaseContract(target, this.interface, this.runner); + } + /** + * Resolves to the transaction to deploy the contract, passing %%args%% + * into the constructor. + */ + async getDeployTransaction(...args) { + let overrides; + const fragment = this.interface.deploy; + if (fragment.inputs.length + 1 === args.length) { + overrides = await (0, contract_js_1.copyOverrides)(args.pop()); + const resolvedArgs = await (0, contract_js_1.resolveArgs)(this.runner, fragment.inputs, args); + const data = (0, index_js_2.concat)([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]); + return Object.assign({}, overrides, { data }); + } + if (fragment.inputs.length !== args.length) { + throw new Error("incorrect number of arguments to constructor"); + } + const resolvedArgs = await (0, contract_js_1.resolveArgs)(this.runner, fragment.inputs, args); + const data = (0, index_js_2.concat)([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]); + return Object.assign({}, args.pop().from, { data }); + } + // getDeployTransaction3(...args: Array): TransactionRequest { + // let tx: TransactionRequest = {}; + // // If we have 1 additional argument, we allow transaction overrides + // if ( + // args.length === this.interface.deploy.inputs.length + 1 && + // typeof args[args.length - 1] === "object" + // ) { + // //tx = shallowCopy(args.pop()); + // tx = copyOverrides(args.pop()); + // for (const key in tx) { + // if (!allowedTransactionKeys[key]) { + // throw new Error("unknown transaction override " + key); + // } + // } + // } + // // Do not allow these to be overridden in a deployment transaction + // ["data", "from", "to"].forEach((key) => { + // if ((tx)[key] == null) { + // return; + // } + // assertArgument(false, "cannot override " + key, key, (tx)[key]); + // }); + // if (tx.value) { + // const value = Number(tx.value) + // if ( value != 0 && !this.interface.deploy.payable) { + // assertArgument( + // false, + // "non-zero value provided to non-payable (or constructor) function", + // "value", value + // ); + // } + // } + // // // Make sure the call matches the constructor signature + // // logger.checkArgumentCount( + // // args.length, + // // this.interface.deploy.inputs.length, + // // " in Contract constructor" + // // ); + // // Set the data to the bytecode + the encoded constructor arguments + // tx.data = hexlify( + // concat([this.bytecode, this.interface.encodeDeploy(args)]) + // ); + // return tx; + // } + /** + * Resolves to the Contract deployed by passing %%args%% into the + * constructor. + * + * This will resovle to the Contract before it has been deployed to the + * network, so the [[BaseContract-waitForDeployment]] should be used before + * sending any transactions to it. + */ + async deploy(...args) { + const tx = await this.getDeployTransaction(...args); + (0, index_js_2.assert)(this.runner && typeof (this.runner.sendTransaction) === "function", "factory runner does not support sending transactions", "UNSUPPORTED_OPERATION", { + operation: "sendTransaction" + }); + if (this.runner instanceof quais_js_1.Wallet) { + tx.from = this.runner.address; + } + const grindedTx = await this.grindContractAddress(tx); + console.log("grindedTx", grindedTx); + const sentTx = await this.runner.sendTransaction(grindedTx); + const address = (0, properties_js_1.getStatic)(this.constructor, "getContractAddress")?.(tx); + //const address = getCreateAddress(sentTx); + return new contract_js_1.BaseContract(address, this.interface, this.runner, sentTx); + } + static getContractAddress(transaction) { + return (0, address_js_1.getContractAddress)(transaction.from, BigInt(transaction.nonce), // Fix: Convert BigInt to bigint + transaction.data); + } + async grindContractAddress(tx) { + if (tx.nonce == null && tx.from) { + tx.nonce = await this.runner?.provider?.getTransactionCount(tx.from); + } + const sender = String(tx.from); + const toShard = (0, index_js_3.getShardForAddress)(sender); + var i = 0; + var startingData = tx.data; + while (i < 10000) { + var contractAddress = (0, address_js_1.getContractAddress)(sender, BigInt(tx.nonce || 0), tx.data || ''); + var contractShard = (0, index_js_3.getShardForAddress)(contractAddress); + console.log("contractAddress ", contractAddress); + var utxo = (0, index_js_3.isUTXOAddress)(contractAddress); + if (contractShard === toShard && !utxo) { + return tx; + } + var salt = (0, quais_js_1.randomBytes)(32); + tx.data = (0, index_js_2.hexlify)((0, index_js_2.concat)([String(startingData), salt])); + i++; + } + return tx; + } + /** + * Return a new **ContractFactory** with the same ABI and bytecode, + * but connected to %%runner%%. + */ + connect(runner) { + return new ContractFactory(this.interface, this.bytecode, runner); + } + /** + * Create a new **ContractFactory** from the standard Solidity JSON output. + */ + static fromSolidity(output, runner) { + (0, index_js_2.assertArgument)(output != null, "bad compiler output", "output", output); + if (typeof (output) === "string") { + output = JSON.parse(output); + } + const abi = output.abi; + let bytecode = ""; + if (output.bytecode) { + bytecode = output.bytecode; + } + else if (output.evm && output.evm.bytecode) { + bytecode = output.evm.bytecode; + } + return new this(abi, bytecode, runner); + } +} +exports.ContractFactory = ContractFactory; +//# sourceMappingURL=factory.js.map \ No newline at end of file diff --git a/lib.commonjs/contract/factory.js.map b/lib.commonjs/contract/factory.js.map new file mode 100644 index 00000000..06b5bfc5 --- /dev/null +++ b/lib.commonjs/contract/factory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"factory.js","sourceRoot":"","sources":["../../src.ts/contract/factory.ts"],"names":[],"mappings":";;;AACA,8CAA4C;AAC5C,gDAG2B;AAE3B,+CAAyE;AAMzE,gDAAsE;AAKtE,0CAAkD;AAClD,sDAA2D;AAC3D,0DAAmD;AAGnD,mCAAmC;AACnC,sCAAsC;AAEtC;;GAEG;AACH,MAAa,eAAe;IAExB;;OAEG;IACM,SAAS,CAAa;IAE/B;;OAEG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AI,CAAC,CAAC,CAAC,CAAC;YACxD,CAAC,EAAE,CAAC;SACP;QACD,OAAO,EAAE,CAAC;IACZ,CAAC;IAEH;;;OAGG;IACH,OAAO,CAAC,MAA6B;QACjC,OAAO,IAAI,eAAe,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IACtE,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,YAAY,CAA2D,MAAW,EAAE,MAAuB;QAC9G,IAAA,yBAAc,EAAC,MAAM,IAAI,IAAI,EAAE,qBAAqB,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;QAExE,IAAI,OAAM,CAAC,MAAM,CAAC,KAAK,QAAQ,EAAE;YAAE,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;SAAE;QAEjE,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC;QAEvB,IAAI,QAAQ,GAAG,EAAE,CAAC;QAClB,IAAI,MAAM,CAAC,QAAQ,EAAE;YACjB,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;SAC9B;aAAM,IAAI,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE;YAC1C,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;SAClC;QAED,OAAO,IAAI,IAAI,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;IAC3C,CAAC;CACJ;AA5ND,0CA4NC"} \ No newline at end of file diff --git a/lib.commonjs/contract/types.d.ts b/lib.commonjs/contract/types.d.ts new file mode 100644 index 00000000..be2d954d --- /dev/null +++ b/lib.commonjs/contract/types.d.ts @@ -0,0 +1,193 @@ +import type { EventFragment, FunctionFragment, Result, Typed } from "../abi/index.js"; +import type { TransactionRequest, PreparedTransactionRequest, TopicFilter } from "../providers/index.js"; +import type { ContractTransactionResponse } from "./wrappers.js"; +/** + * The name for an event used for subscribing to Contract events. + * + * **``string``** - An event by name. The event must be non-ambiguous. + * The parameters will be dereferenced when passed into the listener. + * + * [[ContractEvent]] - A filter from the ``contract.filters``, which will + * pass only the EventPayload as a single parameter, which includes a + * ``.signature`` property that can be used to further filter the event. + * + * [[TopicFilter]] - A filter defined using the standard Ethereum API + * which provides the specific topic hash or topic hashes to watch for along + * with any additional values to filter by. This will only pass a single + * parameter to the listener, the EventPayload which will include additional + * details to refine by, such as the event name and signature. + * + * [[DeferredTopicFilter]] - A filter created by calling a [[ContractEvent]] + * with parameters, which will create a filter for a specific event + * signautre and dereference each parameter when calling the listener. + */ +export type ContractEventName = string | ContractEvent | TopicFilter | DeferredTopicFilter; +/** + * A Contract with no method constraints. + */ +export interface ContractInterface { + [name: string]: BaseContractMethod; +} +/** + * When creating a filter using the ``contract.filters``, this is returned. + */ +export interface DeferredTopicFilter { + getTopicFilter(): Promise; + fragment: EventFragment; +} +/** + * When populating a transaction this type is returned. + */ +export interface ContractTransaction extends PreparedTransactionRequest { + /** + * The target address. + */ + to: string; + /** + * The transaction data. + */ + data: string; + /** + * The from address, if any. + */ + from: string; +} +/** + * A deployment transaction for a contract. + */ +export interface ContractDeployTransaction extends Omit { +} +/** + * The overrides for a contract transaction. + */ +export interface Overrides extends Omit { +} +/** + * Arguments to a Contract method can always include an additional and + * optional overrides parameter. + * + * @_ignore: + */ +export type PostfixOverrides> = A | [...A, Overrides]; +/** + * Arguments to a Contract method can always include an additional and + * optional overrides parameter, and each parameter can optionally be + * [[Typed]]. + * + * @_ignore: + */ +export type ContractMethodArgs> = PostfixOverrides<{ + [I in keyof A]-?: A[I] | Typed; +}>; +/** + * A Contract method can be called directly, or used in various ways. + */ +export interface BaseContractMethod = Array, R = any, D extends R | ContractTransactionResponse = R | ContractTransactionResponse> { + (...args: ContractMethodArgs): Promise; + /** + * The name of the Contract method. + */ + name: string; + /** + * The fragment of the Contract method. This will throw on ambiguous + * method names. + */ + fragment: FunctionFragment; + /** + * Returns the fragment constrained by %%args%%. This can be used to + * resolve ambiguous method names. + */ + getFragment(...args: ContractMethodArgs): FunctionFragment; + /** + * Returns a populated transaction that can be used to perform the + * contract method with %%args%%. + */ + populateTransaction(...args: ContractMethodArgs): Promise; + /** + * Call the contract method with %%args%% and return the value. + * + * If the return value is a single type, it will be dereferenced and + * returned directly, otherwise the full Result will be returned. + */ + staticCall(...args: ContractMethodArgs): Promise; + /** + * Send a transaction for the contract method with %%args%%. + */ + send(...args: ContractMethodArgs): Promise; + /** + * Estimate the gas to send the contract method with %%args%%. + */ + estimateGas(...args: ContractMethodArgs): Promise; + /** + * Call the contract method with %%args%% and return the Result + * without any dereferencing. + */ + staticCallResult(...args: ContractMethodArgs): Promise; +} +/** + * A contract method on a Contract. + */ +export interface ContractMethod = Array, R = any, D extends R | ContractTransactionResponse = R | ContractTransactionResponse> extends BaseContractMethod { +} +/** + * A pure of view method on a Contract. + */ +export interface ConstantContractMethod, R = any> extends ContractMethod { +} +/** + * Each argument of an event is nullable (to indicate matching //any//. + * + * @_ignore: + */ +export type ContractEventArgs> = { + [I in keyof A]?: A[I] | Typed | null; +}; +export interface ContractEvent = Array> { + (...args: ContractEventArgs): DeferredTopicFilter; + /** + * The name of the Contract event. + */ + name: string; + /** + * The fragment of the Contract event. This will throw on ambiguous + * method names. + */ + fragment: EventFragment; + /** + * Returns the fragment constrained by %%args%%. This can be used to + * resolve ambiguous event names. + */ + getFragment(...args: ContractEventArgs): EventFragment; +} +/** + * A Fallback or Receive function on a Contract. + */ +export interface WrappedFallback { + (overrides?: Omit): Promise; + /** + * Returns a populated transaction that can be used to perform the + * fallback method. + * + * For non-receive fallback, ``data`` may be overridden. + */ + populateTransaction(overrides?: Omit): Promise; + /** + * Call the contract fallback and return the result. + * + * For non-receive fallback, ``data`` may be overridden. + */ + staticCall(overrides?: Omit): Promise; + /** + * Send a transaction to the contract fallback. + * + * For non-receive fallback, ``data`` may be overridden. + */ + send(overrides?: Omit): Promise; + /** + * Estimate the gas to send a transaction to the contract fallback. + * + * For non-receive fallback, ``data`` may be overridden. + */ + estimateGas(overrides?: Omit): Promise; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/lib.commonjs/contract/types.d.ts.map b/lib.commonjs/contract/types.d.ts.map new file mode 100644 index 00000000..8c805861 --- /dev/null +++ b/lib.commonjs/contract/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src.ts/contract/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACR,aAAa,EAAE,gBAAgB,EAAE,MAAM,EAAE,KAAK,EACjD,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EACR,kBAAkB,EAAE,0BAA0B,EAAE,WAAW,EAC9D,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAGjE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,aAAa,GAAG,WAAW,GAAG,mBAAmB,CAAC;AAE3F;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAC9B,CAAE,IAAI,EAAE,MAAM,GAAI,kBAAkB,CAAC;CACxC;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAChC,cAAc,IAAI,OAAO,CAAC,WAAW,CAAC,CAAC;IACvC,QAAQ,EAAE,aAAa,CAAC;CAC3B;AAED;;GAEG;AACH,MAAM,WAAW,mBAAoB,SAAQ,0BAA0B;IACnE;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;CAEhB;AAED;;GAEG;AACH,MAAM,WAAW,yBAA0B,SAAQ,IAAI,CAAC,mBAAmB,EAAE,IAAI,CAAC;CAAI;AAEtF;;GAEG;AACH,MAAM,WAAW,SAAU,SAAQ,IAAI,CAAC,kBAAkB,EAAE,IAAI,GAAG,MAAM,C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;IAC5B,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,kBAAkB,EAAE,IAAI,CAAC,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;IAEnF;;;;;OAKG;IACH,mBAAmB,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,kBAAkB,EAAE,IAAI,CAAC,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;IAE9F;;;;OAIG;IACH,UAAU,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,kBAAkB,EAAE,IAAI,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAExE;;;;OAIG;IACH,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,kBAAkB,EAAE,IAAI,CAAC,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;IAEvF;;;;OAIG;IACH,WAAW,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,kBAAkB,EAAE,IAAI,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAC5E"} \ No newline at end of file diff --git a/lib.commonjs/contract/types.js.map b/lib.commonjs/contract/types.js.map new file mode 100644 index 00000000..d98dbb60 --- /dev/null +++ b/lib.commonjs/contract/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src.ts/contract/types.ts"],"names":[],"mappings":";;AAqCC,CAAC;AAuC4E,CAAC;AA4H9E,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/contract/wrappers.d.ts b/lib.commonjs/contract/wrappers.d.ts new file mode 100644 index 00000000..e5af484f --- /dev/null +++ b/lib.commonjs/contract/wrappers.d.ts @@ -0,0 +1,143 @@ +import { Block, Log, TransactionReceipt, TransactionResponse } from "../providers/provider.js"; +import { EventPayload } from "../utils/index.js"; +import type { EventFragment, Interface, Result } from "../abi/index.js"; +import type { Listener } from "../utils/index.js"; +import type { Provider } from "../providers/index.js"; +import type { BaseContract } from "./contract.js"; +import type { ContractEventName } from "./types.js"; +/** + * An **EventLog** contains additional properties parsed from the [[Log]]. + */ +export declare class EventLog extends Log { + /** + * The Contract Interface. + */ + readonly interface: Interface; + /** + * The matching event. + */ + readonly fragment: EventFragment; + /** + * The parsed arguments passed to the event by ``emit``. + */ + readonly args: Result; + /** + * @_ignore: + */ + constructor(log: Log, iface: Interface, fragment: EventFragment); + /** + * The name of the event. + */ + get eventName(): string; + /** + * The signature of the event. + */ + get eventSignature(): string; +} +/** + * An **EventLog** contains additional properties parsed from the [[Log]]. + */ +export declare class UndecodedEventLog extends Log { + /** + * The error encounted when trying to decode the log. + */ + readonly error: Error; + /** + * @_ignore: + */ + constructor(log: Log, error: Error); +} +/** + * A **ContractTransactionReceipt** includes the parsed logs from a + * [[TransactionReceipt]]. + */ +export declare class ContractTransactionReceipt extends TransactionReceipt { + #private; + /** + * @_ignore: + */ + constructor(iface: Interface, provider: Provider, tx: TransactionReceipt); + /** + * The parsed logs for any [[Log]] which has a matching event in the + * Contract ABI. + */ + get logs(): Array; +} +/** + * A **ContractTransactionResponse** will return a + * [[ContractTransactionReceipt]] when waited on. + */ +export declare class ContractTransactionResponse extends TransactionResponse { + #private; + /** + * @_ignore: + */ + constructor(iface: Interface, provider: Provider, tx: TransactionResponse); + /** + * Resolves once this transaction has been mined and has + * %%confirms%% blocks including it (default: ``1``) with an + * optional %%timeout%%. + * + * This can resolve to ``null`` only if %%confirms%% is ``0`` + * and the transaction has not been mined, otherwise this will + * wait until enough confirmations have completed. + */ + wait(confirms?: number): Promise; +} +/** + * A **ContractUnknownEventPayload** is included as the last parameter to + * Contract Events when the event does not match any events in the ABI. + */ +export declare class ContractUnknownEventPayload extends EventPayload { + /** + * The log with no matching events. + */ + readonly log: Log; + /** + * @_event: + */ + constructor(contract: BaseContract, listener: null | Listener, filter: ContractEventName, log: Log); + /** + * Resolves to the block the event occured in. + */ + getBlock(shard: string): Promise; + /** + * Resolves to the transaction the event occured in. + */ + getTransaction(): Promise; + /** + * Resolves to the transaction receipt the event occured in. + */ + getTransactionReceipt(): Promise; +} +/** + * A **ContractEventPayload** is included as the last parameter to + * Contract Events when the event is known. + */ +export declare class ContractEventPayload extends ContractUnknownEventPayload { + /** + * The matching event. + */ + readonly fragment: EventFragment; + /** + * The log, with parsed properties. + */ + readonly log: EventLog; + /** + * The parsed arguments passed to the event by ``emit``. + */ + readonly args: Result; + /** + * @_ignore: + */ + constructor(contract: BaseContract, listener: null | Listener, filter: ContractEventName, fragment: EventFragment, _log: Log); + /** + * The event name. + */ + get eventName(): string; + /** + * The event signature. + */ + get eventSignature(): string; +} +//# sourceMappingURL=wrappers.d.ts.map \ No newline at end of file diff --git a/lib.commonjs/contract/wrappers.d.ts.map b/lib.commonjs/contract/wrappers.d.ts.map new file mode 100644 index 00000000..cd3ccc0d --- /dev/null +++ b/lib.commonjs/contract/wrappers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wrappers.d.ts","sourceRoot":"","sources":["../../src.ts/contract/wrappers.ts"],"names":[],"mappings":"AAEA,OAAO,EACH,KAAK,EAAE,GAAG,EAAE,kBAAkB,EAAE,mBAAmB,EACtD,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAoB,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEnE,OAAO,KAAK,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACxE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,EACR,QAAQ,EACX,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEpD;;GAEG;AACH,qBAAa,QAAS,SAAQ,GAAG;IAC7B;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAG,SAAS,CAAC;IAE/B;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAG,aAAa,CAAC;IAElC;;OAEG;IACH,QAAQ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G;IACG,cAAc,IAAI,OAAO,CAAC,mBAAmB,CAAC;IAIpD;;OAEG;IACG,qBAAqB,IAAI,OAAO,CAAC,kBAAkB,CAAC;CAG7D;AAED;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,2BAA2B;IAEjE;;OAEG;IACH,SAAiB,QAAQ,EAAE,aAAa,CAAC;IAEzC;;OAEG;IACH,SAAiB,GAAG,EAAE,QAAQ,CAAC;IAE/B;;OAEG;IACH,SAAiB,IAAI,EAAE,MAAM,CAAC;IAE9B;;OAEG;gBACS,QAAQ,EAAE,YAAY,EAAE,QAAQ,EAAE,IAAI,GAAG,QAAQ,EAAE,MAAM,EAAE,iBAAiB,EAAE,QAAQ,EAAE,aAAa,EAAE,IAAI,EAAE,GAAG;IAM5H;;OAEG;IACH,IAAI,SAAS,IAAI,MAAM,CAEtB;IAED;;OAEG;IACH,IAAI,cAAc,IAAI,MAAM,CAE3B;CACJ"} \ No newline at end of file diff --git a/lib.commonjs/contract/wrappers.js b/lib.commonjs/contract/wrappers.js new file mode 100644 index 00000000..36dc5e0e --- /dev/null +++ b/lib.commonjs/contract/wrappers.js @@ -0,0 +1,186 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ContractEventPayload = exports.ContractUnknownEventPayload = exports.ContractTransactionResponse = exports.ContractTransactionReceipt = exports.UndecodedEventLog = exports.EventLog = void 0; +// import from provider.ts instead of index.ts to prevent circular dep +// from quaiscanProvider +const provider_js_1 = require("../providers/provider.js"); +const index_js_1 = require("../utils/index.js"); +/** + * An **EventLog** contains additional properties parsed from the [[Log]]. + */ +class EventLog extends provider_js_1.Log { + /** + * The Contract Interface. + */ + interface; + /** + * The matching event. + */ + fragment; + /** + * The parsed arguments passed to the event by ``emit``. + */ + args; + /** + * @_ignore: + */ + constructor(log, iface, fragment) { + super(log, log.provider); + const args = iface.decodeEventLog(fragment, log.data, log.topics); + (0, index_js_1.defineProperties)(this, { args, fragment, interface: iface }); + } + /** + * The name of the event. + */ + get eventName() { return this.fragment.name; } + /** + * The signature of the event. + */ + get eventSignature() { return this.fragment.format(); } +} +exports.EventLog = EventLog; +/** + * An **EventLog** contains additional properties parsed from the [[Log]]. + */ +class UndecodedEventLog extends provider_js_1.Log { + /** + * The error encounted when trying to decode the log. + */ + error; + /** + * @_ignore: + */ + constructor(log, error) { + super(log, log.provider); + (0, index_js_1.defineProperties)(this, { error }); + } +} +exports.UndecodedEventLog = UndecodedEventLog; +/** + * A **ContractTransactionReceipt** includes the parsed logs from a + * [[TransactionReceipt]]. + */ +class ContractTransactionReceipt extends provider_js_1.TransactionReceipt { + #iface; + /** + * @_ignore: + */ + constructor(iface, provider, tx) { + super(tx, provider); + this.#iface = iface; + } + /** + * The parsed logs for any [[Log]] which has a matching event in the + * Contract ABI. + */ + get logs() { + return super.logs.map((log) => { + const fragment = log.topics.length ? this.#iface.getEvent(log.topics[0]) : null; + if (fragment) { + try { + return new EventLog(log, this.#iface, fragment); + } + catch (error) { + return new UndecodedEventLog(log, error); + } + } + return log; + }); + } +} +exports.ContractTransactionReceipt = ContractTransactionReceipt; +/** + * A **ContractTransactionResponse** will return a + * [[ContractTransactionReceipt]] when waited on. + */ +class ContractTransactionResponse extends provider_js_1.TransactionResponse { + #iface; + /** + * @_ignore: + */ + constructor(iface, provider, tx) { + super(tx, provider); + this.#iface = iface; + } + /** + * Resolves once this transaction has been mined and has + * %%confirms%% blocks including it (default: ``1``) with an + * optional %%timeout%%. + * + * This can resolve to ``null`` only if %%confirms%% is ``0`` + * and the transaction has not been mined, otherwise this will + * wait until enough confirmations have completed. + */ + async wait(confirms) { + const receipt = await super.wait(confirms); + if (receipt == null) { + return null; + } + return new ContractTransactionReceipt(this.#iface, this.provider, receipt); + } +} +exports.ContractTransactionResponse = ContractTransactionResponse; +/** + * A **ContractUnknownEventPayload** is included as the last parameter to + * Contract Events when the event does not match any events in the ABI. + */ +class ContractUnknownEventPayload extends index_js_1.EventPayload { + /** + * The log with no matching events. + */ + log; + /** + * @_event: + */ + constructor(contract, listener, filter, log) { + super(contract, listener, filter); + (0, index_js_1.defineProperties)(this, { log }); + } + /** + * Resolves to the block the event occured in. + */ + async getBlock(shard) { + return await this.log.getBlock(shard); + } + /** + * Resolves to the transaction the event occured in. + */ + async getTransaction() { + return await this.log.getTransaction(); + } + /** + * Resolves to the transaction receipt the event occured in. + */ + async getTransactionReceipt() { + return await this.log.getTransactionReceipt(); + } +} +exports.ContractUnknownEventPayload = ContractUnknownEventPayload; +/** + * A **ContractEventPayload** is included as the last parameter to + * Contract Events when the event is known. + */ +class ContractEventPayload extends ContractUnknownEventPayload { + /** + * @_ignore: + */ + constructor(contract, listener, filter, fragment, _log) { + super(contract, listener, filter, new EventLog(_log, contract.interface, fragment)); + const args = contract.interface.decodeEventLog(fragment, this.log.data, this.log.topics); + (0, index_js_1.defineProperties)(this, { args, fragment }); + } + /** + * The event name. + */ + get eventName() { + return this.fragment.name; + } + /** + * The event signature. + */ + get eventSignature() { + return this.fragment.format(); + } +} +exports.ContractEventPayload = ContractEventPayload; +//# sourceMappingURL=wrappers.js.map \ No newline at end of file diff --git a/lib.commonjs/contract/wrappers.js.map b/lib.commonjs/contract/wrappers.js.map new file mode 100644 index 00000000..37bee2ab --- /dev/null +++ b/lib.commonjs/contract/wrappers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wrappers.js","sourceRoot":"","sources":["../../src.ts/contract/wrappers.ts"],"names":[],"mappings":";;;AAAA,sEAAsE;AACtE,wBAAwB;AACxB,0DAEkC;AAClC,gDAAmE;AAWnE;;GAEG;AACH,MAAa,QAAS,SAAQ,iBAAG;IAC7B;;OAEG;IACM,SAAS,CAAa;IAE/B;;OAEG;IACM,QAAQ,CAAiB;IAElC;;OAEG;IACM,IAAI,CAAU;IAEvB;;OAEG;IACH,YAAY,GAAQ,EAAE,KAAgB,EAAE,QAAuB;QAC3D,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC;QACzB,MAAM,IAAI,GAAG,KA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AAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,cAAc;QAChB,OAAO,MAAM,IAAI,CAAC,GAAG,CAAC,cAAc,EAAE,CAAC;IAC3C,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,qBAAqB;QACvB,OAAO,MAAM,IAAI,CAAC,GAAG,CAAC,qBAAqB,EAAE,CAAC;IAClD,CAAC;CACJ;AAlCD,kEAkCC;AAED;;;GAGG;AACH,MAAa,oBAAqB,SAAQ,2BAA2B;IAiBjE;;OAEG;IACH,YAAY,QAAsB,EAAE,QAAyB,EAAE,MAAyB,EAAE,QAAuB,EAAE,IAAS;QACxH,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC,CAAC;QACpF,MAAM,IAAI,GAAG,QAAQ,CAAC,SAAS,CAAC,cAAc,CAAC,QAAQ,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACzF,IAAA,2BAAgB,EAAuB,IAAI,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC;IACrE,CAAC;IAED;;OAEG;IACH,IAAI,SAAS;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;IAC9B,CAAC;IAED;;OAEG;IACH,IAAI,cAAc;QACd,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;IAClC,CAAC;CACJ;AAvCD,oDAuCC"} \ No newline at end of file diff --git a/lib.commonjs/providers/abstract-provider.d.ts b/lib.commonjs/providers/abstract-provider.d.ts new file mode 100644 index 00000000..7d006601 --- /dev/null +++ b/lib.commonjs/providers/abstract-provider.d.ts @@ -0,0 +1,499 @@ +/** + * The available providers should suffice for most developers purposes, + * but the [[AbstractProvider]] class has many features which enable + * sub-classing it for specific purposes. + * + * @_section: api/providers/abstract-provider: Subclassing Provider [abstract-provider] + */ +import { FetchRequest } from "../utils/index.js"; +import { EnsResolver } from "./ens-resolver.js"; +import { Network } from "./network.js"; +import { Block, FeeData, Log, TransactionReceipt, TransactionResponse } from "./provider.js"; +import type { AddressLike } from "../address/index.js"; +import type { BigNumberish } from "../utils/index.js"; +import type { Listener } from "../utils/index.js"; +import type { Networkish } from "./network.js"; +import type { BlockParams, LogParams, TransactionReceiptParams, TransactionResponseParams } from "./formatting.js"; +import type { BlockTag, EventFilter, Filter, FilterByBlockHash, OrphanFilter, PreparedTransactionRequest, Provider, ProviderEvent, TransactionRequest } from "./provider.js"; +/** + * The types of additional event values that can be emitted for the + * ``"debug"`` event. + */ +export type DebugEventAbstractProvider = { + action: "sendCcipReadFetchRequest"; + request: FetchRequest; + index: number; + urls: Array; +} | { + action: "receiveCcipReadFetchResult"; + request: FetchRequest; + result: any; +} | { + action: "receiveCcipReadFetchError"; + request: FetchRequest; + result: any; +} | { + action: "sendCcipReadCall"; + transaction: { + to: string; + data: string; + }; +} | { + action: "receiveCcipReadCallResult"; + transaction: { + to: string; + data: string; + }; + result: string; +} | { + action: "receiveCcipReadCallError"; + transaction: { + to: string; + data: string; + }; + error: Error; +}; +/** + * The value passed to the [[AbstractProvider-_getSubscriber]] method. + * + * Only developers sub-classing [[AbstractProvider[[ will care about this, + * if they are modifying a low-level feature of how subscriptions operate. + */ +export type Subscription = { + type: "block" | "close" | "debug" | "error" | "finalized" | "network" | "pending" | "safe"; + tag: string; +} | { + type: "transaction"; + tag: string; + hash: string; +} | { + type: "event"; + tag: string; + filter: EventFilter; +} | { + type: "orphan"; + tag: string; + filter: OrphanFilter; +}; +/** + * A **Subscriber** manages a subscription. + * + * Only developers sub-classing [[AbstractProvider[[ will care about this, + * if they are modifying a low-level feature of how subscriptions operate. + */ +export interface Subscriber { + /** + * Called initially when a subscriber is added the first time. + */ + start(): void; + /** + * Called when there are no more subscribers to the event. + */ + stop(): void; + /** + * Called when the subscription should pause. + * + * If %%dropWhilePaused%%, events that occur while paused should not + * be emitted [[resume]]. + */ + pause(dropWhilePaused?: boolean): void; + /** + * Resume a paused subscriber. + */ + resume(): void; + /** + * The frequency (in ms) to poll for events, if polling is used by + * the subscriber. + * + * For non-polling subscribers, this must return ``undefined``. + */ + pollingInterval?: number; +} +/** + * An **UnmanagedSubscriber** is useful for events which do not require + * any additional management, such as ``"debug"`` which only requires + * emit in synchronous event loop triggered calls. + */ +export declare class UnmanagedSubscriber implements Subscriber { + /** + * The name fof the event. + */ + name: string; + /** + * Create a new UnmanagedSubscriber with %%name%%. + */ + constructor(name: string); + start(): void; + stop(): void; + pause(dropWhilePaused?: boolean): void; + resume(): void; +} +/** + * An **AbstractPlugin** is used to provide additional internal services + * to an [[AbstractProvider]] without adding backwards-incompatible changes + * to method signatures or other internal and complex logic. + */ +export interface AbstractProviderPlugin { + /** + * The reverse domain notation of the plugin. + */ + readonly name: string; + /** + * Creates a new instance of the plugin, connected to %%provider%%. + */ + connect(provider: AbstractProvider): AbstractProviderPlugin; +} +/** + * A normalized filter used for [[PerformActionRequest]] objects. + */ +export type PerformActionFilter = { + address?: string | Array; + topics?: Array>; + fromBlock?: BlockTag; + toBlock?: BlockTag; + shard: string; +} | { + address?: string | Array; + topics?: Array>; + blockHash?: string; + shard: string; +}; +/** + * A normalized transactions used for [[PerformActionRequest]] objects. + */ +export interface PerformActionTransaction extends PreparedTransactionRequest { + /** + * The ``to`` address of the transaction. + */ + to?: string; + /** + * The sender of the transaction. + */ + from: string; +} +/** + * The [[AbstractProvider]] methods will normalize all values and pass this + * type to [[AbstractProvider-_perform]]. + */ +export type PerformActionRequest = { + method: "broadcastTransaction"; + signedTransaction: string; + shard: string; +} | { + method: "call"; + transaction: PerformActionTransaction; + blockTag: BlockTag; + shard?: string; +} | { + method: "chainId"; + shard?: string; +} | { + method: "estimateGas"; + transaction: PerformActionTransaction; + shard?: string; +} | { + method: "getBalance"; + address: string; + blockTag: BlockTag; + shard: string; +} | { + method: "getBlock"; + blockTag: BlockTag; + includeTransactions: boolean; + shard: string; +} | { + method: "getBlock"; + blockHash: string; + includeTransactions: boolean; + shard: string; +} | { + method: "getBlockNumber"; + shard?: string; +} | { + method: "getCode"; + address: string; + blockTag: BlockTag; + shard: string; +} | { + method: "getGasPrice"; + txType: boolean; + shard?: string; +} | { + method: "getLogs"; + filter: PerformActionFilter; + shard: string; +} | { + method: "getMaxPriorityFeePerGas"; + shard?: string; +} | { + method: "getStorage"; + address: string; + position: bigint; + blockTag: BlockTag; + shard: string; +} | { + method: "getTransaction"; + hash: string; + shard: string; +} | { + method: "getTransactionCount"; + address: string; + blockTag: BlockTag; + shard: string; +} | { + method: "getTransactionReceipt"; + hash: string; + shard: string; +} | { + method: "getTransactionResult"; + hash: string; + shard: string; +} | { + method: "getRunningLocations"; + shard?: string; +} | { + method: "getProtocolTrieExpansionCount"; + shard: string; +} | { + method: "getQiRateAtBlock"; + blockTag: BlockTag; + amt: number; + shard: string; +} | { + method: "getQuaiRateAtBlock"; + blockTag: BlockTag; + amt: number; + shard: string; +}; +/** + * Options for configuring some internal aspects of an [[AbstractProvider]]. + * + * **``cacheTimeout``** - how long to cache a low-level ``_perform`` + * for, based on input parameters. This reduces the number of calls + * to getChainId and getBlockNumber, but may break test chains which + * can perform operations (internally) synchronously. Use ``-1`` to + * disable, ``0`` will only buffer within the same event loop and + * any other value is in ms. (default: ``250``) + */ +export type AbstractProviderOptions = { + cacheTimeout?: number; + pollingInterval?: number; +}; +/** + * An **AbstractProvider** provides a base class for other sub-classes to + * implement the [[Provider]] API by normalizing input arguments and + * formatting output results as well as tracking events for consistent + * behaviour on an eventually-consistent network. + */ +export declare class AbstractProvider implements Provider { + #private; + _urlMap: Map; + /** + * Create a new **AbstractProvider** connected to %%network%%, or + * use the various network detection capabilities to discover the + * [[Network]] if necessary. + */ + constructor(_network?: "any" | Networkish, options?: AbstractProviderOptions); + initUrlMap(urls: string[] | FetchRequest): Promise; + shardBytes(shard: string): string; + get connect(): FetchRequest[]; + shardFromAddress(_address: AddressLike): Promise; + shardFromHash(hash: string): string; + getLatestQuaiRate(shard: string, amt?: number): Promise; + getQuaiRateAtBlock(shard: string, blockTag: BlockTag, amt?: number): Promise; + getLatestQiRate(shard: string, amt?: number): Promise; + getQiRateAtBlock(shard: string, blockTag: BlockTag, amt?: number): Promise; + get pollingInterval(): number; + /** + * Returns ``this``, to allow an **AbstractProvider** to implement + * the [[ContractRunner]] interface. + */ + get provider(): this; + /** + * Returns all the registered plug-ins. + */ + get plugins(): Array; + /** + * Attach a new plug-in. + */ + attachPlugin(plugin: AbstractProviderPlugin): this; + /** + * Get a plugin by name. + */ + getPlugin(name: string): null | T; + /** + * Prevent any CCIP-read operation, regardless of whether requested + * in a [[call]] using ``enableCcipRead``. + */ + get disableCcipRead(): boolean; + set disableCcipRead(value: boolean); + /** + * Resolves to the data for executing the CCIP-read operations. + */ + ccipReadFetch(tx: PerformActionTransaction, calldata: string, urls: Array): Promise; + /** + * Provides the opportunity for a sub-class to wrap a block before + * returning it, to add additional properties or an alternate + * sub-class of [[Block]]. + */ + _wrapBlock(value: BlockParams, network: Network): Block; + /** + * Provides the opportunity for a sub-class to wrap a log before + * returning it, to add additional properties or an alternate + * sub-class of [[Log]]. + */ + _wrapLog(value: LogParams, network: Network): Log; + /** + * Provides the opportunity for a sub-class to wrap a transaction + * receipt before returning it, to add additional properties or an + * alternate sub-class of [[TransactionReceipt]]. + */ + _wrapTransactionReceipt(value: TransactionReceiptParams, network: Network): TransactionReceipt; + /** + * Provides the opportunity for a sub-class to wrap a transaction + * response before returning it, to add additional properties or an + * alternate sub-class of [[TransactionResponse]]. + */ + _wrapTransactionResponse(tx: TransactionResponseParams, network: Network): TransactionResponse; + /** + * Resolves to the Network, forcing a network detection using whatever + * technique the sub-class requires. + * + * Sub-classes **must** override this. + */ + _detectNetwork(shard?: string): Promise; + /** + * Sub-classes should use this to perform all built-in operations. All + * methods sanitizes and normalizes the values passed into this. + * + * Sub-classes **must** override this. + */ + _perform(req: PerformActionRequest): Promise; + getBlockNumber(shard?: string): Promise; + /** + * Returns or resolves to the address for %%address%%, resolving ENS + * names and [[Addressable]] objects and returning if already an + * address. + */ + _getAddress(address: AddressLike): string | Promise; + /** + * Returns or resolves to a valid block tag for %%blockTag%%, resolving + * negative values and returning if already a valid block tag. + */ + _getBlockTag(shard?: string, blockTag?: BlockTag): string | Promise; + /** + * Returns or resolves to a filter for %%filter%%, resolving any ENS + * names or [[Addressable]] object and returning if already a valid + * filter. + */ + _getFilter(filter: Filter | FilterByBlockHash): PerformActionFilter | Promise; + /** + * Returns or resovles to a transaction for %%request%%, resolving + * any ENS names or [[Addressable]] and returning if already a valid + * transaction. + */ + _getTransactionRequest(_request: TransactionRequest): PerformActionTransaction | Promise; + getNetwork(shard?: string): Promise; + getRunningLocations(shard?: string): Promise; + getProtocolTrieExpansionCount(shard: string): Promise; + getFeeData(shard?: string, txType?: boolean): Promise; + estimateGas(_tx: TransactionRequest): Promise; + call(_tx: TransactionRequest): Promise; + getBalance(address: AddressLike, blockTag?: BlockTag): Promise; + getTransactionCount(address: AddressLike, blockTag?: BlockTag): Promise; + getCode(address: AddressLike, blockTag?: BlockTag): Promise; + getStorage(address: AddressLike, _position: BigNumberish, blockTag?: BlockTag): Promise; + broadcastTransaction(shard: string, signedTx: string): Promise; + getBlock(shard: string, block: BlockTag | string, prefetchTxs?: boolean): Promise; + getTransaction(hash: string): Promise; + getTransactionReceipt(hash: string): Promise; + getTransactionResult(hash: string): Promise; + getLogs(_filter: Filter | FilterByBlockHash): Promise>; + _getProvider(chainId: number): AbstractProvider; + getResolver(name: string): Promise; + getAvatar(name: string): Promise; + resolveName(name: string): Promise; + lookupAddress(address: string): Promise; + waitForTransaction(hash: string, _confirms?: null | number, timeout?: null | number): Promise; + waitForBlock(shard: string, blockTag?: BlockTag): Promise; + /** + * Clear a timer created using the [[_setTimeout]] method. + */ + _clearTimeout(timerId: number): void; + /** + * Create a timer that will execute %%func%% after at least %%timeout%% + * (in ms). If %%timeout%% is unspecified, then %%func%% will execute + * in the next event loop. + * + * [Pausing](AbstractProvider-paused) the provider will pause any + * associated timers. + */ + _setTimeout(_func: () => void, timeout?: number): number; + /** + * Perform %%func%% on each subscriber. + */ + _forEachSubscriber(func: (s: Subscriber) => void): void; + /** + * Sub-classes may override this to customize subscription + * implementations. + */ + _getSubscriber(sub: Subscription): Subscriber; + /** + * If a [[Subscriber]] fails and needs to replace itself, this + * method may be used. + * + * For example, this is used for providers when using the + * ``eth_getFilterChanges`` method, which can return null if state + * filters are not supported by the backend, allowing the Subscriber + * to swap in a [[PollingEventSubscriber]]. + */ + _recoverSubscriber(oldSub: Subscriber, newSub: Subscriber): void; + on(event: ProviderEvent, listener: Listener): Promise; + once(event: ProviderEvent, listener: Listener): Promise; + emit(event: ProviderEvent, ...args: Array): Promise; + listenerCount(event?: ProviderEvent): Promise; + listeners(event?: ProviderEvent): Promise>; + off(event: ProviderEvent, listener?: Listener): Promise; + removeAllListeners(event?: ProviderEvent): Promise; + addListener(event: ProviderEvent, listener: Listener): Promise; + removeListener(event: ProviderEvent, listener: Listener): Promise; + /** + * If this provider has been destroyed using the [[destroy]] method. + * + * Once destroyed, all resources are reclaimed, internal event loops + * and timers are cleaned up and no further requests may be sent to + * the provider. + */ + get destroyed(): boolean; + /** + * Sub-classes may use this to shutdown any sockets or release their + * resources and reject any pending requests. + * + * Sub-classes **must** call ``super.destroy()``. + */ + destroy(): void; + /** + * Whether the provider is currently paused. + * + * A paused provider will not emit any events, and generally should + * not make any requests to the network, but that is up to sub-classes + * to manage. + * + * Setting ``paused = true`` is identical to calling ``.pause(false)``, + * which will buffer any events that occur while paused until the + * provider is unpaused. + */ + get paused(): boolean; + set paused(pause: boolean); + /** + * Pause the provider. If %%dropWhilePaused%%, any events that occur + * while paused are dropped, otherwise all events will be emitted once + * the provider is unpaused. + */ + pause(dropWhilePaused?: boolean): void; + /** + * Resume the provider. + */ + resume(): void; +} +//# sourceMappingURL=abstract-provider.d.ts.map \ No newline at end of file diff --git a/lib.commonjs/providers/abstract-provider.d.ts.map b/lib.commonjs/providers/abstract-provider.d.ts.map new file mode 100644 index 00000000..dae3efc8 --- /dev/null +++ b/lib.commonjs/providers/abstract-provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"abstract-provider.d.ts","sourceRoot":"","sources":["../../src.ts/providers/abstract-provider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAeH,OAAO,EAIH,YAAY,EAGf,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAIhD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAe,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAE1G,OAAO,KAAK,EAAe,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAElD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAG/C,OAAO,KAAK,EACR,WAAW,EAAE,SAAS,EAAE,wBAAwB,EAChD,yBAAyB,EAC5B,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EACR,QAAQ,EAAE,WAAW,EAAE,MAAM,EAAE,iBAAiB,EAAE,YAAY,EAC9D,0BAA0B,EAAE,QAAQ,EAAE,aAAa,EACnD,kBAAkB,EACrB,MAAM,eAAe,CAAC;AAkCvB;;;GAGG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACrC,MAAM,EAAE,0BAA0B,CAAC;IACnC,OAAO,EAAE,YAAY,CAAA;IACrB,KAAK,EAAE,MAAM,CAAA;IACb,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,CAAA;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,CAAC,IAAI,CAAC;IAKpE,cAAc,CAAC,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAI7E;;;;;;OAMG;IACH,IAAI,SAAS,IAAI,OAAO,CAEvB;IAED;;;;;OAKG;IACH,OAAO,IAAI,IAAI;IAYf;;;;;;;;;;OAUG;IACH,IAAI,MAAM,IAAI,OAAO,CAAwC;IAC7D,IAAI,MAAM,CAAC,KAAK,EAAE,OAAO,EAQxB;IAED;;;;OAIG;IACH,KAAK,CAAC,eAAe,CAAC,EAAE,OAAO,GAAG,IAAI;IAsBtC;;OAEG;IACH,MAAM,IAAI,IAAI;CAiBjB"} \ No newline at end of file diff --git a/lib.commonjs/providers/abstract-provider.js b/lib.commonjs/providers/abstract-provider.js new file mode 100644 index 00000000..1208bc7d --- /dev/null +++ b/lib.commonjs/providers/abstract-provider.js @@ -0,0 +1,1478 @@ +"use strict"; +/** + * The available providers should suffice for most developers purposes, + * but the [[AbstractProvider]] class has many features which enable + * sub-classing it for specific purposes. + * + * @_section: api/providers/abstract-provider: Subclassing Provider [abstract-provider] + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AbstractProvider = exports.UnmanagedSubscriber = void 0; +// @TODO +// Event coalescence +// When we register an event with an async value (e.g. address is a Signer +// or ENS name), we need to add it immeidately for the Event API, but also +// need time to resolve the address. Upon resolving the address, we need to +// migrate the listener to the static event. We also need to maintain a map +// of Signer/ENS name to address so we can sync respond to listenerCount. +const index_js_1 = require("../address/index.js"); +const index_js_2 = require("../constants/index.js"); +const index_js_3 = require("../contract/index.js"); +const index_js_4 = require("../hash/index.js"); +const index_js_5 = require("../transaction/index.js"); +const index_js_6 = require("../utils/index.js"); +const ens_resolver_js_1 = require("./ens-resolver.js"); +const format_js_1 = require("./format.js"); +const network_js_1 = require("./network.js"); +const provider_js_1 = require("./provider.js"); +// Constants +const BN_2 = BigInt(2); +const MAX_CCIP_REDIRECTS = 10; +function isPromise(value) { + return (value && typeof (value.then) === "function"); +} +function getTag(prefix, value) { + return prefix + ":" + JSON.stringify(value, (k, v) => { + if (v == null) { + return "null"; + } + if (typeof (v) === "bigint") { + return `bigint:${v.toString()}`; + } + if (typeof (v) === "string") { + return v.toLowerCase(); + } + // Sort object keys + if (typeof (v) === "object" && !Array.isArray(v)) { + const keys = Object.keys(v); + keys.sort(); + return keys.reduce((accum, key) => { + accum[key] = v[key]; + return accum; + }, {}); + } + return v; + }); +} +/** + * An **UnmanagedSubscriber** is useful for events which do not require + * any additional management, such as ``"debug"`` which only requires + * emit in synchronous event loop triggered calls. + */ +class UnmanagedSubscriber { + /** + * The name fof the event. + */ + name; + /** + * Create a new UnmanagedSubscriber with %%name%%. + */ + constructor(name) { (0, index_js_6.defineProperties)(this, { name }); } + start() { } + stop() { } + pause(dropWhilePaused) { } + resume() { } +} +exports.UnmanagedSubscriber = UnmanagedSubscriber; +function copy(value) { + return JSON.parse(JSON.stringify(value)); +} +function concisify(items) { + items = Array.from((new Set(items)).values()); + items.sort(); + return items; +} +async function getSubscription(_event, provider) { + if (_event == null) { + throw new Error("invalid event"); + } + // Normalize topic array info an EventFilter + if (Array.isArray(_event)) { + _event = { topics: _event }; + } + if (typeof (_event) === "string") { + switch (_event) { + case "block": + case "debug": + case "error": + case "finalized": + case "network": + case "pending": + case "safe": { + return { type: _event, tag: _event }; + } + } + } + if ((0, index_js_6.isHexString)(_event, 32)) { + const hash = _event.toLowerCase(); + return { type: "transaction", tag: getTag("tx", { hash }), hash }; + } + if (_event.orphan) { + const event = _event; + // @TODO: Should lowercase and whatnot things here instead of copy... + return { type: "orphan", tag: getTag("orphan", event), filter: copy(event) }; + } + if ((_event.address || _event.topics)) { + const event = _event; + const filter = { + topics: ((event.topics || []).map((t) => { + if (t == null) { + return null; + } + if (Array.isArray(t)) { + return concisify(t.map((t) => t.toLowerCase())); + } + return t.toLowerCase(); + })) + }; + if (event.address) { + const addresses = []; + const promises = []; + const addAddress = (addr) => { + if ((0, index_js_6.isHexString)(addr)) { + addresses.push(addr); + } + else { + promises.push((async () => { + addresses.push(await (0, index_js_1.resolveAddress)(addr, provider)); + })()); + } + }; + if (Array.isArray(event.address)) { + event.address.forEach(addAddress); + } + else { + addAddress(event.address); + } + if (promises.length) { + await Promise.all(promises); + } + filter.address = concisify(addresses.map((a) => a.toLowerCase())); + } + return { filter, tag: getTag("event", filter), type: "event" }; + } + (0, index_js_6.assertArgument)(false, "unknown ProviderEvent", "event", _event); +} +function getTime() { return (new Date()).getTime(); } +const defaultOptions = { + cacheTimeout: 250, + pollingInterval: 4000 +}; +// type CcipArgs = { +// sender: string; +// urls: Array; +// calldata: string; +// selector: string; +// extraData: string; +// errorArgs: Array +// }; +/** + * An **AbstractProvider** provides a base class for other sub-classes to + * implement the [[Provider]] API by normalizing input arguments and + * formatting output results as well as tracking events for consistent + * behaviour on an eventually-consistent network. + */ +class AbstractProvider { + _urlMap; + #connect; + #subs; + #plugins; + // null=unpaused, true=paused+dropWhilePaused, false=paused + #pausedState; + #destroyed; + #networkPromise; + #anyNetwork; + #performCache; + // The most recent block number if running an event or -1 if no "block" event + #lastBlockNumber; + #nextTimer; + #timers; + #disableCcipRead; + #options; + /** + * Create a new **AbstractProvider** connected to %%network%%, or + * use the various network detection capabilities to discover the + * [[Network]] if necessary. + */ + constructor(_network, options) { + this.#options = Object.assign({}, defaultOptions, options || {}); + if (_network === "any") { + this.#anyNetwork = true; + this.#networkPromise = null; + } + else if (_network) { + const network = network_js_1.Network.from(_network); + this.#anyNetwork = false; + this.#networkPromise = Promise.resolve(network); + setTimeout(() => { this.emit("network", network, null); }, 0); + } + else { + this.#anyNetwork = false; + this.#networkPromise = null; + } + this.#lastBlockNumber = -1; + this.#performCache = new Map(); + this.#subs = new Map(); + this.#plugins = new Map(); + this.#pausedState = null; + this.#destroyed = false; + this.#nextTimer = 1; + this.#timers = new Map(); + this.#disableCcipRead = false; + this.#connect = []; + this._urlMap = new Map(); + } + async initUrlMap(urls) { + if (urls instanceof index_js_6.FetchRequest) { + const primeUrl = urls.url.split(":")[0] + ":" + urls.url.split(":")[1] + ":9001"; + this._urlMap.set('0x', primeUrl); + urls.url = primeUrl; + this.#connect.push(urls); + const shards = await this.getRunningLocations(); + shards.forEach((shard) => { + const port = 9100 + 20 * shard[0] + shard[1]; + this._urlMap.set(`0x${shard[0].toString(16)}${shard[1].toString(16)}`, urls.url.split(":")[0] + ":" + urls.url.split(":")[1] + ":" + port); + }); + return; + } + for (const url of urls) { + const primeUrl = url.split(":")[0] + ":" + url.split(":")[1] + ":9001"; + this._urlMap.set('0x', primeUrl); + this.#connect.push(new index_js_6.FetchRequest(primeUrl)); + const shards = await this.getRunningLocations(); // Now waits for the previous to complete + shards.forEach((shard) => { + const port = 9100 + 20 * shard[0] + shard[1]; + this._urlMap.set(`0x${shard[0].toString(16)}${shard[1].toString(16)}`, url.split(":")[0] + ":" + url.split(":")[1] + ":" + port); + }); + } + } + shardBytes(shard) { + return index_js_2.ShardData.find(it => it.name == shard || + it.byte == shard || + it.nickname == shard || + it.shard == shard)?.byte || ''; + } + get connect() { return this.#connect; } + async shardFromAddress(_address) { + let address = this._getAddress(_address); + return (await address).slice(0, 4); + } + shardFromHash(hash) { + return hash.slice(0, 4); + } + async getLatestQuaiRate(shard, amt = 1) { + const blockNumber = await this.getBlockNumber(shard); + return this.getQuaiRateAtBlock(shard, blockNumber, amt); + } + async getQuaiRateAtBlock(shard, blockTag, amt = 1) { + let resolvedBlockTag = this._getBlockTag(shard, blockTag); + if (typeof resolvedBlockTag !== "string") { + resolvedBlockTag = await resolvedBlockTag; + } + return await this.#perform({ + method: "getQuaiRateAtBlock", + blockTag: resolvedBlockTag, + amt, + shard: shard + }); + } + async getLatestQiRate(shard, amt = 1) { + const blockNumber = await this.getBlockNumber(shard); + return this.getQiRateAtBlock(shard, blockNumber, amt); + } + async getQiRateAtBlock(shard, blockTag, amt = 1) { + let resolvedBlockTag = this._getBlockTag(shard, blockTag); + if (typeof resolvedBlockTag !== "string") { + resolvedBlockTag = await resolvedBlockTag; + } + return await this.#perform({ + method: "getQiRateAtBlock", + blockTag: resolvedBlockTag, + amt, + shard: shard + }); + } + get pollingInterval() { return this.#options.pollingInterval; } + /** + * Returns ``this``, to allow an **AbstractProvider** to implement + * the [[ContractRunner]] interface. + */ + get provider() { return this; } + /** + * Returns all the registered plug-ins. + */ + get plugins() { + return Array.from(this.#plugins.values()); + } + /** + * Attach a new plug-in. + */ + attachPlugin(plugin) { + if (this.#plugins.get(plugin.name)) { + throw new Error(`cannot replace existing plugin: ${plugin.name} `); + } + this.#plugins.set(plugin.name, plugin.connect(this)); + return this; + } + /** + * Get a plugin by name. + */ + getPlugin(name) { + return (this.#plugins.get(name)) || null; + } + /** + * Prevent any CCIP-read operation, regardless of whether requested + * in a [[call]] using ``enableCcipRead``. + */ + get disableCcipRead() { return this.#disableCcipRead; } + set disableCcipRead(value) { this.#disableCcipRead = !!value; } + // Shares multiple identical requests made during the same 250ms + async #perform(req) { + const timeout = this.#options.cacheTimeout; + // Caching disabled + if (timeout < 0) { + return await this._perform(req); + } + // Create a tag + const tag = getTag(req.method, req); + let perform = this.#performCache.get(tag); + if (!perform) { + perform = this._perform(req); + this.#performCache.set(tag, perform); + setTimeout(() => { + if (this.#performCache.get(tag) === perform) { + this.#performCache.delete(tag); + } + }, timeout); + } + return await perform; + } + /** + * Resolves to the data for executing the CCIP-read operations. + */ + async ccipReadFetch(tx, calldata, urls) { + if (this.disableCcipRead || urls.length === 0 || tx.to == null) { + return null; + } + const sender = tx.to.toLowerCase(); + const data = calldata.toLowerCase(); + const errorMessages = []; + for (let i = 0; i < urls.length; i++) { + const url = urls[i]; + // URL expansion + const href = url.replace("{sender}", sender).replace("{data}", data); + // If no {data} is present, use POST; otherwise GET + //const json: string | null = (url.indexOf("{data}") >= 0) ? null: JSON.stringify({ data, sender }); + //const result = await fetchJson({ url: href, errorPassThrough: true }, json, (value, response) => { + // value.status = response.statusCode; + // return value; + //}); + const request = new index_js_6.FetchRequest(href); + if (url.indexOf("{data}") === -1) { + request.body = { data, sender }; + } + this.emit("debug", { action: "sendCcipReadFetchRequest", request, index: i, urls }); + let errorMessage = "unknown error"; + const resp = await request.send(); + try { + const result = resp.bodyJson; + if (result.data) { + this.emit("debug", { action: "receiveCcipReadFetchResult", request, result }); + return result.data; + } + if (result.message) { + errorMessage = result.message; + } + this.emit("debug", { action: "receiveCcipReadFetchError", request, result }); + } + catch (error) { } + // 4xx indicates the result is not present; stop + (0, index_js_6.assert)(resp.statusCode < 400 || resp.statusCode >= 500, `response not found during CCIP fetch: ${errorMessage}`, "OFFCHAIN_FAULT", { reason: "404_MISSING_RESOURCE", transaction: tx, info: { url, errorMessage } }); + // 5xx indicates server issue; try the next url + errorMessages.push(errorMessage); + } + (0, index_js_6.assert)(false, `error encountered during CCIP fetch: ${errorMessages.map((m) => JSON.stringify(m)).join(", ")}`, "OFFCHAIN_FAULT", { + reason: "500_SERVER_ERROR", + transaction: tx, info: { urls, errorMessages } + }); + } + /** + * Provides the opportunity for a sub-class to wrap a block before + * returning it, to add additional properties or an alternate + * sub-class of [[Block]]. + */ + _wrapBlock(value, network) { + return new provider_js_1.Block((0, format_js_1.formatBlock)(value), this); + } + /** + * Provides the opportunity for a sub-class to wrap a log before + * returning it, to add additional properties or an alternate + * sub-class of [[Log]]. + */ + _wrapLog(value, network) { + return new provider_js_1.Log((0, format_js_1.formatLog)(value), this); + } + /** + * Provides the opportunity for a sub-class to wrap a transaction + * receipt before returning it, to add additional properties or an + * alternate sub-class of [[TransactionReceipt]]. + */ + _wrapTransactionReceipt(value, network) { + return new provider_js_1.TransactionReceipt((0, format_js_1.formatTransactionReceipt)(value), this); + } + /** + * Provides the opportunity for a sub-class to wrap a transaction + * response before returning it, to add additional properties or an + * alternate sub-class of [[TransactionResponse]]. + */ + _wrapTransactionResponse(tx, network) { + return new provider_js_1.TransactionResponse((0, format_js_1.formatTransactionResponse)(tx), this); + } + /** + * Resolves to the Network, forcing a network detection using whatever + * technique the sub-class requires. + * + * Sub-classes **must** override this. + */ + _detectNetwork(shard) { + (0, index_js_6.assert)(false, "sub-classes must implement this", "UNSUPPORTED_OPERATION", { + operation: "_detectNetwork" + }); + } + /** + * Sub-classes should use this to perform all built-in operations. All + * methods sanitizes and normalizes the values passed into this. + * + * Sub-classes **must** override this. + */ + async _perform(req) { + (0, index_js_6.assert)(false, `unsupported method: ${req.method}`, "UNSUPPORTED_OPERATION", { + operation: req.method, + info: req + }); + } + // State + async getBlockNumber(shard) { + const blockNumber = (0, index_js_6.getNumber)(await this.#perform({ method: "getBlockNumber", shard: shard }), "%response"); + if (this.#lastBlockNumber >= 0) { + this.#lastBlockNumber = blockNumber; + } + return blockNumber; + } + /** + * Returns or resolves to the address for %%address%%, resolving ENS + * names and [[Addressable]] objects and returning if already an + * address. + */ + _getAddress(address) { + return (0, index_js_1.resolveAddress)(address, this); + } + /** + * Returns or resolves to a valid block tag for %%blockTag%%, resolving + * negative values and returning if already a valid block tag. + */ + _getBlockTag(shard, blockTag) { + if (blockTag == null) { + return "latest"; + } + switch (blockTag) { + case "earliest": + return "0x0"; + case "finalized": + case "latest": + case "pending": + case "safe": + return blockTag; + } + if ((0, index_js_6.isHexString)(blockTag)) { + if ((0, index_js_6.isHexString)(blockTag, 32)) { + return blockTag; + } + return (0, index_js_6.toQuantity)(blockTag); + } + if (typeof (blockTag) === "bigint") { + blockTag = (0, index_js_6.getNumber)(blockTag, "blockTag"); + } + if (typeof (blockTag) === "number") { + if (blockTag >= 0) { + return (0, index_js_6.toQuantity)(blockTag); + } + if (this.#lastBlockNumber >= 0) { + return (0, index_js_6.toQuantity)(this.#lastBlockNumber + blockTag); + } + return this.getBlockNumber(shard).then((b) => (0, index_js_6.toQuantity)(b + blockTag)); + } + (0, index_js_6.assertArgument)(false, "invalid blockTag", "blockTag", blockTag); + } + /** + * Returns or resolves to a filter for %%filter%%, resolving any ENS + * names or [[Addressable]] object and returning if already a valid + * filter. + */ + _getFilter(filter) { + // Create a canonical representation of the topics + const topics = (filter.topics || []).map((t) => { + if (t == null) { + return null; + } + if (Array.isArray(t)) { + return concisify(t.map((t) => t.toLowerCase())); + } + return t.toLowerCase(); + }); + const blockHash = ("blockHash" in filter) ? filter.blockHash : undefined; + const resolve = (_address, fromBlock, toBlock, shard) => { + let address = undefined; + switch (_address.length) { + case 0: break; + case 1: + address = _address[0]; + break; + default: + _address.sort(); + address = _address; + } + if (blockHash) { + if (fromBlock != null || toBlock != null) { + throw new Error("invalid filter"); + } + } + const filter = {}; + if (address) { + filter.address = address; + } + if (topics.length) { + filter.topics = topics; + } + if (fromBlock) { + filter.fromBlock = fromBlock; + } + if (toBlock) { + filter.toBlock = toBlock; + } + if (blockHash) { + filter.blockHash = blockHash; + } + if (shard) { + filter.shard = shard; + } + return filter; + }; + // Addresses could be async (ENS names or Addressables) + let address = []; + if (filter.address) { + if (Array.isArray(filter.address)) { + for (const addr of filter.address) { + address.push(this._getAddress(addr)); + } + } + else { + address.push(this._getAddress(filter.address)); + } + } + let fromBlock = undefined; + if ("fromBlock" in filter) { + fromBlock = this._getBlockTag(filter.shard, filter.fromBlock); + } + let toBlock = undefined; + if ("toBlock" in filter) { + toBlock = this._getBlockTag(filter.shard, filter.toBlock); + } + const shard = filter.shard; + if (address.filter((a) => (typeof (a) !== "string")).length || + (fromBlock != null && typeof (fromBlock) !== "string") || + (toBlock != null && typeof (toBlock) !== "string")) { + return Promise.all([Promise.all(address), fromBlock, toBlock, shard]).then((result) => { + return resolve(result[0], result[1], result[2]); + }); + } + return resolve(address, fromBlock, toBlock, shard); + } + /** + * Returns or resovles to a transaction for %%request%%, resolving + * any ENS names or [[Addressable]] and returning if already a valid + * transaction. + */ + _getTransactionRequest(_request) { + const request = (0, provider_js_1.copyRequest)(_request); + const promises = []; + ["to", "from"].forEach((key) => { + if (request[key] == null) { + return; + } + const addr = (0, index_js_1.resolveAddress)(request[key], this); + if (isPromise(addr)) { + promises.push((async function () { request[key] = await addr; })()); + } + else { + request[key] = addr; + } + }); + if (request.blockTag != null) { + const blockTag = this._getBlockTag(request.chainId?.toString(), request.blockTag); + if (isPromise(blockTag)) { + promises.push((async function () { request.blockTag = await blockTag; })()); + } + else { + request.blockTag = blockTag; + } + } + if (promises.length) { + return (async function () { + await Promise.all(promises); + return request; + })(); + } + return request; + } + async getNetwork(shard = 'prime') { + // No explicit network was set and this is our first time + if (this.#networkPromise == null) { + // Detect the current network (shared with all calls) + const detectNetwork = (async () => { + try { + const network = await this._detectNetwork(shard); + this.emit("network", network, null); + return network; + } + catch (error) { + if (this.#networkPromise === detectNetwork) { + this.#networkPromise = null; + } + throw error; + } + })(); + this.#networkPromise = detectNetwork; + return (await detectNetwork).clone(); + } + const networkPromise = this.#networkPromise; + const [expected, actual] = await Promise.all([ + networkPromise, + this._detectNetwork(shard) // The actual connected network + ]); + if (expected.chainId !== actual.chainId) { + if (this.#anyNetwork) { + // The "any" network can change, so notify listeners + this.emit("network", actual, expected); + // Update the network if something else hasn't already changed it + if (this.#networkPromise === networkPromise) { + this.#networkPromise = Promise.resolve(actual); + } + } + else { + // Otherwise, we do not allow changes to the underlying network + (0, index_js_6.assert)(false, `network changed: ${expected.chainId} => ${actual.chainId} `, "NETWORK_ERROR", { + event: "changed" + }); + } + } + return expected.clone(); + } + async getRunningLocations(shard) { + return await this.#perform(shard ? { method: "getRunningLocations", shard: shard } : { method: "getRunningLocations" }); + } + async getProtocolTrieExpansionCount(shard) { + return await this.#perform({ method: "getProtocolTrieExpansionCount", shard: shard }); + } + async getFeeData(shard, txType = true) { + const network = await this.getNetwork(); + const getFeeDataFunc = async () => { + const { gasPrice, priorityFee } = await (0, index_js_6.resolveProperties)({ + gasPrice: ((async () => { + try { + const value = await this.#perform({ method: "getGasPrice", txType, shard: shard }); + return (0, index_js_6.getBigInt)(value, "%response"); + } + catch (error) { } + return null; + })()), + priorityFee: ((async () => { + try { + const value = txType ? await this.#perform({ method: "getMaxPriorityFeePerGas", shard: shard }) : 0; + return (0, index_js_6.getBigInt)(value, "%response"); + } + catch (error) { } + return null; + })()) + }); + if (gasPrice == null) { + throw new Error("could not determine gasPrice"); + } + let maxFeePerGas = null; + let maxPriorityFeePerGas = null; + // These are the recommended EIP-1559 heuristics for fee data + maxPriorityFeePerGas = (priorityFee != null) ? priorityFee : BigInt("1000000000"); + maxFeePerGas = (gasPrice * BN_2) + maxPriorityFeePerGas; + return new provider_js_1.FeeData(gasPrice, maxFeePerGas, maxPriorityFeePerGas); + }; + // Check for a FeeDataNetWorkPlugin + const plugin = network.getPlugin("org.quais.plugins.network.FetchUrlFeeDataPlugin"); + if (plugin) { + const req = new index_js_6.FetchRequest(plugin.url); + const feeData = await plugin.processFunc(getFeeDataFunc, this, req); + return new provider_js_1.FeeData(feeData.gasPrice, feeData.maxFeePerGas, feeData.maxPriorityFeePerGas); + } + return await getFeeDataFunc(); + } + async estimateGas(_tx) { + let tx = this._getTransactionRequest(_tx); + if (isPromise(tx)) { + tx = await tx; + } + const shard = await this.shardFromAddress(tx.from); + return (0, index_js_6.getBigInt)(await this.#perform({ + method: "estimateGas", transaction: tx, shard: shard + }), "%response"); + } + async #call(tx, blockTag, attempt) { + (0, index_js_6.assert)(attempt < MAX_CCIP_REDIRECTS, "CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", { + reason: "TOO_MANY_REDIRECTS", + transaction: Object.assign({}, tx, { blockTag, enableCcipRead: true }) + }); + // This came in as a PerformActionTransaction, so to/from are safe; we can cast + const transaction = (0, provider_js_1.copyRequest)(tx); + try { + return (0, index_js_6.hexlify)(await this._perform({ method: "call", transaction, blockTag })); + } + catch (error) { + // CCIP Read OffchainLookup + // if (!this.disableCcipRead && isCallException(error) && error.data && attempt >= 0 && blockTag === "latest" && transaction.to != null && dataSlice(error.data, 0, 4) === "0x556f1830") { + // const data = error.data; + // const txSender = await resolveAddress(transaction.to, this); + // // Parse the CCIP Read Arguments + // let ccipArgs: CcipArgs; + // try { + // ccipArgs = parseOffchainLookup(dataSlice(error.data, 4)); + // } catch (error: any) { + // assert(false, error.message, "OFFCHAIN_FAULT", { + // reason: "BAD_DATA", transaction, info: { data } }); + // } + // // Check the sender of the OffchainLookup matches the transaction + // assert(ccipArgs.sender.toLowerCase() === txSender.toLowerCase(), + // "CCIP Read sender mismatch", "CALL_EXCEPTION", { + // action: "call", + // data, + // reason: "OffchainLookup", + // transaction: transaction, // @TODO: populate data? + // invocation: null, + // revert: { + // signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", + // name: "OffchainLookup", + // args: ccipArgs.errorArgs + // } + // }); + // const ccipResult = await this.ccipReadFetch(transaction, ccipArgs.calldata, ccipArgs.urls); + // assert(ccipResult != null, "CCIP Read failed to fetch data", "OFFCHAIN_FAULT", { + // reason: "FETCH_FAILED", transaction, info: { data: error.data, errorArgs: ccipArgs.errorArgs } }); + // const tx = { + // to: txSender, + // data: concat([ ccipArgs.selector, encodeBytes([ ccipResult, ccipArgs.extraData ]) ]) + // }; + // this.emit("debug", { action: "sendCcipReadCall", transaction: tx }); + // try { + // const result = await this.#call(tx, blockTag, attempt + 1); + // this.emit("debug", { action: "receiveCcipReadCallResult", transaction: Object.assign({ }, tx), result }); + // return result; + // } catch (error) { + // this.emit("debug", { action: "receiveCcipReadCallError", transaction: Object.assign({ }, tx), error }); + // throw error; + // } + // } + throw error; + } + } + async #checkNetwork(promise, shard) { + const { value } = await (0, index_js_6.resolveProperties)({ + network: this.getNetwork(), + value: promise + }); + return value; + } + async call(_tx) { + const shard = await this.shardFromAddress(_tx.from); + const { tx, blockTag } = await (0, index_js_6.resolveProperties)({ + tx: this._getTransactionRequest(_tx), + blockTag: this._getBlockTag(shard, _tx.blockTag) + }); + return await this.#checkNetwork(this.#call(tx, blockTag, _tx.enableCcipRead ? 0 : -1), shard); + } + // Account + async #getAccountValue(request, _address, _blockTag) { + let address = this._getAddress(_address); + const shard = await this.shardFromAddress(_address); + let blockTag = this._getBlockTag(shard, _blockTag); + if (typeof (address) !== "string" || typeof (blockTag) !== "string") { + [address, blockTag] = await Promise.all([address, blockTag]); + } + return await this.#checkNetwork(this.#perform(Object.assign(request, { address, blockTag, shard: shard })), shard); + } + async getBalance(address, blockTag) { + return (0, index_js_6.getBigInt)(await this.#getAccountValue({ method: "getBalance" }, address, blockTag), "%response"); + } + async getTransactionCount(address, blockTag) { + return (0, index_js_6.getNumber)(await this.#getAccountValue({ method: "getTransactionCount" }, address, blockTag), "%response"); + } + async getCode(address, blockTag) { + return (0, index_js_6.hexlify)(await this.#getAccountValue({ method: "getCode" }, address, blockTag)); + } + async getStorage(address, _position, blockTag) { + const position = (0, index_js_6.getBigInt)(_position, "position"); + return (0, index_js_6.hexlify)(await this.#getAccountValue({ method: "getStorage", position }, address, blockTag)); + } + // Write + async broadcastTransaction(shard, signedTx) { + const { blockNumber, hash, network } = await (0, index_js_6.resolveProperties)({ + blockNumber: this.getBlockNumber(shard), + hash: this._perform({ + method: "broadcastTransaction", + signedTransaction: signedTx, + shard: shard + }), + network: this.getNetwork() + }); + const tx = index_js_5.Transaction.from(signedTx); + if (tx.hash !== hash) { + throw new Error("@TODO: the returned hash did not match"); + } + return this._wrapTransactionResponse(tx, network).replaceableTransaction(blockNumber); + } + async #getBlock(shard, block, includeTransactions) { + // @TODO: Add CustomBlockPlugin check + if ((0, index_js_6.isHexString)(block, 32)) { + return await this.#perform({ + method: "getBlock", blockHash: block, includeTransactions, shard: shard + }); + } + let blockTag = this._getBlockTag(shard, block); + if (typeof (blockTag) !== "string") { + blockTag = await blockTag; + } + return await this.#perform({ + method: "getBlock", blockTag, includeTransactions, shard: shard + }); + } + // Queries + async getBlock(shard, block, prefetchTxs) { + const { network, params } = await (0, index_js_6.resolveProperties)({ + network: this.getNetwork(), + params: this.#getBlock(shard, block, !!prefetchTxs) + }); + if (params == null) { + return null; + } + return this._wrapBlock(params, network); + } + async getTransaction(hash) { + const shard = this.shardFromHash(hash); + const { network, params } = await (0, index_js_6.resolveProperties)({ + network: this.getNetwork(), + params: this.#perform({ method: "getTransaction", hash, shard: shard }) + }); + if (params == null) { + return null; + } + return this._wrapTransactionResponse(params, network); + } + async getTransactionReceipt(hash) { + const shard = this.shardFromHash(hash); + const { network, params } = await (0, index_js_6.resolveProperties)({ + network: this.getNetwork(), + params: this.#perform({ method: "getTransactionReceipt", hash, shard: shard }) + }); + if (params == null) { + return null; + } + // Some backends did not backfill the effectiveGasPrice in to old transactions + // in the receipt, so we look it up manually and inject it. + if (params.gasPrice == null && params.effectiveGasPrice == null) { + const tx = await this.#perform({ method: "getTransaction", hash, shard: shard }); + if (tx == null) { + throw new Error("report this; could not find tx or effectiveGasPrice"); + } + params.effectiveGasPrice = tx.gasPrice; + } + return this._wrapTransactionReceipt(params, network); + } + async getTransactionResult(hash) { + const shard = this.shardFromHash(hash); + const { result } = await (0, index_js_6.resolveProperties)({ + network: this.getNetwork(), + result: this.#perform({ method: "getTransactionResult", hash, shard: shard }) + }); + if (result == null) { + return null; + } + return (0, index_js_6.hexlify)(result); + } + // Bloom-filter Queries + async getLogs(_filter) { + let filter = this._getFilter(_filter); + if (isPromise(filter)) { + filter = await filter; + } + const shard = filter.shard; + const { network, params } = await (0, index_js_6.resolveProperties)({ + network: this.getNetwork(), + params: this.#perform({ method: "getLogs", filter, shard: shard }) + }); + return params.map((p) => this._wrapLog(p, network)); + } + // ENS + _getProvider(chainId) { + (0, index_js_6.assert)(false, "provider cannot connect to target network", "UNSUPPORTED_OPERATION", { + operation: "_getProvider()" + }); + } + async getResolver(name) { + return await ens_resolver_js_1.EnsResolver.fromName(this, name); + } + async getAvatar(name) { + const resolver = await this.getResolver(name); + if (resolver) { + return await resolver.getAvatar(); + } + return null; + } + async resolveName(name) { + const resolver = await this.getResolver(name); + if (resolver) { + return await resolver.getAddress(); + } + return null; + } + async lookupAddress(address) { + address = (0, index_js_1.getAddress)(address); + const node = (0, index_js_4.namehash)(address.substring(2).toLowerCase() + ".addr.reverse"); + try { + const ensAddr = await ens_resolver_js_1.EnsResolver.getEnsAddress(this); + const ensContract = new index_js_3.Contract(ensAddr, [ + "function resolver(bytes32) view returns (address)" + ], this); + const resolver = await ensContract.resolver(node); + if (resolver == null || resolver === index_js_2.ZeroAddress) { + return null; + } + const resolverContract = new index_js_3.Contract(resolver, [ + "function name(bytes32) view returns (string)" + ], this); + const name = await resolverContract.name(node); + // Failed forward resolution + const check = await this.resolveName(name); + if (check !== address) { + return null; + } + return name; + } + catch (error) { + // No data was returned from the resolver + if ((0, index_js_6.isError)(error, "BAD_DATA") && error.value === "0x") { + return null; + } + // Something reerted + if ((0, index_js_6.isError)(error, "CALL_EXCEPTION")) { + return null; + } + throw error; + } + return null; + } + async waitForTransaction(hash, _confirms, timeout) { + const shard = this.shardFromHash(hash); + const confirms = (_confirms != null) ? _confirms : 1; + if (confirms === 0) { + return this.getTransactionReceipt(hash); + } + return new Promise(async (resolve, reject) => { + let timer = null; + const listener = (async (blockNumber) => { + try { + const receipt = await this.getTransactionReceipt(hash); + if (receipt != null) { + if (blockNumber - receipt.blockNumber + 1 >= confirms) { + resolve(receipt); + //this.off("block", listener); + if (timer) { + clearTimeout(timer); + timer = null; + } + return; + } + } + } + catch (error) { + console.log("EEE", error); + } + this.once("block", listener); + }); + if (timeout != null) { + timer = setTimeout(() => { + if (timer == null) { + return; + } + timer = null; + this.off("block", listener); + reject((0, index_js_6.makeError)("timeout", "TIMEOUT", { reason: "timeout" })); + }, timeout); + } + listener(await this.getBlockNumber(shard)); + }); + } + async waitForBlock(shard, blockTag) { + (0, index_js_6.assert)(false, "not implemented yet", "NOT_IMPLEMENTED", { + operation: "waitForBlock" + }); + } + /** + * Clear a timer created using the [[_setTimeout]] method. + */ + _clearTimeout(timerId) { + const timer = this.#timers.get(timerId); + if (!timer) { + return; + } + if (timer.timer) { + clearTimeout(timer.timer); + } + this.#timers.delete(timerId); + } + /** + * Create a timer that will execute %%func%% after at least %%timeout%% + * (in ms). If %%timeout%% is unspecified, then %%func%% will execute + * in the next event loop. + * + * [Pausing](AbstractProvider-paused) the provider will pause any + * associated timers. + */ + _setTimeout(_func, timeout) { + if (timeout == null) { + timeout = 0; + } + const timerId = this.#nextTimer++; + const func = () => { + this.#timers.delete(timerId); + _func(); + }; + if (this.paused) { + this.#timers.set(timerId, { timer: null, func, time: timeout }); + } + else { + const timer = setTimeout(func, timeout); + this.#timers.set(timerId, { timer, func, time: getTime() }); + } + return timerId; + } + /** + * Perform %%func%% on each subscriber. + */ + _forEachSubscriber(func) { + for (const sub of this.#subs.values()) { + func(sub.subscriber); + } + } + /** + * Sub-classes may override this to customize subscription + * implementations. + */ + _getSubscriber(sub) { + switch (sub.type) { + case "debug": + case "error": + case "network": + return new UnmanagedSubscriber(sub.type); + } + throw new Error("HTTP polling not supported. This method should be implemented by subclasses."); + } + /** + * If a [[Subscriber]] fails and needs to replace itself, this + * method may be used. + * + * For example, this is used for providers when using the + * ``eth_getFilterChanges`` method, which can return null if state + * filters are not supported by the backend, allowing the Subscriber + * to swap in a [[PollingEventSubscriber]]. + */ + _recoverSubscriber(oldSub, newSub) { + for (const sub of this.#subs.values()) { + if (sub.subscriber === oldSub) { + if (sub.started) { + sub.subscriber.stop(); + } + sub.subscriber = newSub; + if (sub.started) { + newSub.start(); + } + if (this.#pausedState != null) { + newSub.pause(this.#pausedState); + } + break; + } + } + } + async #hasSub(event, emitArgs) { + let sub = await getSubscription(event, this); + // This is a log that is removing an existing log; we actually want + // to emit an orphan event for the removed log + if (sub.type === "event" && emitArgs && emitArgs.length > 0 && emitArgs[0].removed === true) { + sub = await getSubscription({ orphan: "drop-log", log: emitArgs[0] }, this); + } + return this.#subs.get(sub.tag) || null; + } + async #getSub(event) { + const subscription = await getSubscription(event, this); + // Prevent tampering with our tag in any subclass' _getSubscriber + const tag = subscription.tag; + let sub = this.#subs.get(tag); + if (!sub) { + const subscriber = this._getSubscriber(subscription); + const addressableMap = new WeakMap(); + const nameMap = new Map(); + sub = { subscriber, tag, addressableMap, nameMap, started: false, listeners: [] }; + this.#subs.set(tag, sub); + } + return sub; + } + async on(event, listener) { + const sub = await this.#getSub(event); + sub.listeners.push({ listener, once: false }); + if (!sub.started) { + sub.subscriber.start(); + sub.started = true; + if (this.#pausedState != null) { + sub.subscriber.pause(this.#pausedState); + } + } + return this; + } + async once(event, listener) { + const sub = await this.#getSub(event); + sub.listeners.push({ listener, once: true }); + if (!sub.started) { + sub.subscriber.start(); + sub.started = true; + if (this.#pausedState != null) { + sub.subscriber.pause(this.#pausedState); + } + } + return this; + } + async emit(event, ...args) { + const sub = await this.#hasSub(event, args); + // If there is not subscription or if a recent emit removed + // the last of them (which also deleted the sub) do nothing + if (!sub || sub.listeners.length === 0) { + return false; + } + ; + const count = sub.listeners.length; + sub.listeners = sub.listeners.filter(({ listener, once }) => { + const payload = new index_js_6.EventPayload(this, (once ? null : listener), event); + try { + listener.call(this, ...args, payload); + } + catch (error) { } + return !once; + }); + if (sub.listeners.length === 0) { + if (sub.started) { + sub.subscriber.stop(); + } + this.#subs.delete(sub.tag); + } + return (count > 0); + } + async listenerCount(event) { + if (event) { + const sub = await this.#hasSub(event); + if (!sub) { + return 0; + } + return sub.listeners.length; + } + let total = 0; + for (const { listeners } of this.#subs.values()) { + total += listeners.length; + } + return total; + } + async listeners(event) { + if (event) { + const sub = await this.#hasSub(event); + if (!sub) { + return []; + } + return sub.listeners.map(({ listener }) => listener); + } + let result = []; + for (const { listeners } of this.#subs.values()) { + result = result.concat(listeners.map(({ listener }) => listener)); + } + return result; + } + async off(event, listener) { + const sub = await this.#hasSub(event); + if (!sub) { + return this; + } + if (listener) { + const index = sub.listeners.map(({ listener }) => listener).indexOf(listener); + if (index >= 0) { + sub.listeners.splice(index, 1); + } + } + if (!listener || sub.listeners.length === 0) { + if (sub.started) { + sub.subscriber.stop(); + } + this.#subs.delete(sub.tag); + } + return this; + } + async removeAllListeners(event) { + if (event) { + const { tag, started, subscriber } = await this.#getSub(event); + if (started) { + subscriber.stop(); + } + this.#subs.delete(tag); + } + else { + for (const [tag, { started, subscriber }] of this.#subs) { + if (started) { + subscriber.stop(); + } + this.#subs.delete(tag); + } + } + return this; + } + // Alias for "on" + async addListener(event, listener) { + return await this.on(event, listener); + } + // Alias for "off" + async removeListener(event, listener) { + return this.off(event, listener); + } + /** + * If this provider has been destroyed using the [[destroy]] method. + * + * Once destroyed, all resources are reclaimed, internal event loops + * and timers are cleaned up and no further requests may be sent to + * the provider. + */ + get destroyed() { + return this.#destroyed; + } + /** + * Sub-classes may use this to shutdown any sockets or release their + * resources and reject any pending requests. + * + * Sub-classes **must** call ``super.destroy()``. + */ + destroy() { + // Stop all listeners + this.removeAllListeners(); + // Shut down all tiemrs + for (const timerId of this.#timers.keys()) { + this._clearTimeout(timerId); + } + this.#destroyed = true; + } + /** + * Whether the provider is currently paused. + * + * A paused provider will not emit any events, and generally should + * not make any requests to the network, but that is up to sub-classes + * to manage. + * + * Setting ``paused = true`` is identical to calling ``.pause(false)``, + * which will buffer any events that occur while paused until the + * provider is unpaused. + */ + get paused() { return (this.#pausedState != null); } + set paused(pause) { + if (!!pause === this.paused) { + return; + } + if (this.paused) { + this.resume(); + } + else { + this.pause(false); + } + } + /** + * Pause the provider. If %%dropWhilePaused%%, any events that occur + * while paused are dropped, otherwise all events will be emitted once + * the provider is unpaused. + */ + pause(dropWhilePaused) { + this.#lastBlockNumber = -1; + if (this.#pausedState != null) { + if (this.#pausedState == !!dropWhilePaused) { + return; + } + (0, index_js_6.assert)(false, "cannot change pause type; resume first", "UNSUPPORTED_OPERATION", { + operation: "pause" + }); + } + this._forEachSubscriber((s) => s.pause(dropWhilePaused)); + this.#pausedState = !!dropWhilePaused; + for (const timer of this.#timers.values()) { + // Clear the timer + if (timer.timer) { + clearTimeout(timer.timer); + } + // Remaining time needed for when we become unpaused + timer.time = getTime() - timer.time; + } + } + /** + * Resume the provider. + */ + resume() { + if (this.#pausedState == null) { + return; + } + this._forEachSubscriber((s) => s.resume()); + this.#pausedState = null; + for (const timer of this.#timers.values()) { + // Remaining time when we were paused + let timeout = timer.time; + if (timeout < 0) { + timeout = 0; + } + // Start time (in cause paused, so we con compute remaininf time) + timer.time = getTime(); + // Start the timer + setTimeout(timer.func, timeout); + } + } +} +exports.AbstractProvider = AbstractProvider; +// function _parseString(result: string, start: number): null | string { +// try { +// const bytes = _parseBytes(result, start); +// if (bytes) { return toUtf8String(bytes); } +// } catch(error) { } +// return null; +// } +// function _parseBytes(result: string, start: number): null | string { +// if (result === "0x") { return null; } +// try { +// const offset = getNumber(dataSlice(result, start, start + 32)); +// const length = getNumber(dataSlice(result, offset, offset + 32)); +// +// return dataSlice(result, offset + 32, offset + 32 + length); +// } catch (error) { } +// return null; +// } +// function numPad(value: number): Uint8Array { +// const result = toBeArray(value); +// if (result.length > 32) { throw new Error("internal; should not happen"); } +// +// const padded = new Uint8Array(32); +// padded.set(result, 32 - result.length); +// return padded; +// } +// function bytesPad(value: Uint8Array): Uint8Array { +// if ((value.length % 32) === 0) { return value; } +// +// const result = new Uint8Array(Math.ceil(value.length / 32) * 32); +// result.set(value); +// return result; +// } +// const empty: Uint8Array = new Uint8Array([ ]); +// ABI Encodes a series of (bytes, bytes, ...) +// function encodeBytes(datas: Array): string { +// const result: Array = [ ]; +// +// let byteCount = 0; +// +// // Add place-holders for pointers as we add items +// for (let i = 0; i < datas.length; i++) { +// result.push(empty); +// byteCount += 32; +// } +// +// for (let i = 0; i < datas.length; i++) { +// const data = getBytes(datas[i]); +// +// // Update the bytes offset +// result[i] = numPad(byteCount); +// +// // The length and padded value of data +// result.push(numPad(data.length)); +// result.push(bytesPad(data)); +// byteCount += 32 + Math.ceil(data.length / 32) * 32; +// } +// +// return concat(result); +// } +// const zeros = "0x0000000000000000000000000000000000000000000000000000000000000000" +// function parseOffchainLookup(data: string): CcipArgs { +// const result: CcipArgs = { +// sender: "", urls: [ ], calldata: "", selector: "", extraData: "", errorArgs: [ ] +// }; +// +// assert(dataLength(data) >= 5 * 32, "insufficient OffchainLookup data", "OFFCHAIN_FAULT", { +// reason: "insufficient OffchainLookup data" +// }); +// +// const sender = dataSlice(data, 0, 32); +// assert(dataSlice(sender, 0, 12) === dataSlice(zeros, 0, 12), "corrupt OffchainLookup sender", "OFFCHAIN_FAULT", { +// reason: "corrupt OffchainLookup sender" +// }); +// result.sender = dataSlice(sender, 12); +// +// // Read the URLs from the response +// try { +// const urls: Array = []; +// const urlsOffset = getNumber(dataSlice(data, 32, 64)); +// const urlsLength = getNumber(dataSlice(data, urlsOffset, urlsOffset + 32)); +// const urlsData = dataSlice(data, urlsOffset + 32); +// for (let u = 0; u < urlsLength; u++) { +// const url = _parseString(urlsData, u * 32); +// if (url == null) { throw new Error("abort"); } +// urls.push(url); +// } +// result.urls = urls; +// } catch (error) { +// assert(false, "corrupt OffchainLookup urls", "OFFCHAIN_FAULT", { +// reason: "corrupt OffchainLookup urls" +// }); +// } +// +// // Get the CCIP calldata to forward +// try { +// const calldata = _parseBytes(data, 64); +// if (calldata == null) { throw new Error("abort"); } +// result.calldata = calldata; +// } catch (error) { +// assert(false, "corrupt OffchainLookup calldata", "OFFCHAIN_FAULT", { +// reason: "corrupt OffchainLookup calldata" +// }); +// } +// +// // Get the callbackSelector (bytes4) +// assert(dataSlice(data, 100, 128) === dataSlice(zeros, 0, 28), "corrupt OffchainLookup callbaackSelector", "OFFCHAIN_FAULT", { +// reason: "corrupt OffchainLookup callbaackSelector" +// }); +// result.selector = dataSlice(data, 96, 100); +// +// // Get the extra data to send back to the contract as context +// try { +// const extraData = _parseBytes(data, 128); +// if (extraData == null) { throw new Error("abort"); } +// result.extraData = extraData; +// } catch (error) { +// assert(false, "corrupt OffchainLookup extraData", "OFFCHAIN_FAULT", { +// reason: "corrupt OffchainLookup extraData" +// }); +// } +// +// result.errorArgs = "sender,urls,calldata,selector,extraData".split(/,/).map((k) => (result)[k]) +// +// return result; +// } +//# sourceMappingURL=abstract-provider.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/abstract-provider.js.map b/lib.commonjs/providers/abstract-provider.js.map new file mode 100644 index 00000000..827b59c3 --- /dev/null +++ b/lib.commonjs/providers/abst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;AACzD,iCAAiC;AACjC,2FAA2F;AAC3F,SAAS;AACT,EAAE;AACF,iGAAiG;AACjG,qDAAqD;AACrD,UAAU;AACV,EAAE;AACF,6CAA6C;AAC7C,wHAAwH;AACxH,kDAAkD;AAClD,UAAU;AACV,6CAA6C;AAC7C,EAAE;AACF,yCAAyC;AACzC,YAAY;AACZ,0CAA0C;AAC1C,iEAAiE;AACjE,sFAAsF;AACtF,6DAA6D;AAC7D,iDAAiD;AACjD,0DAA0D;AAC1D,6DAA6D;AAC7D,8BAA8B;AAC9B,YAAY;AACZ,8BAA8B;AAC9B,wBAAwB;AACxB,2EAA2E;AAC3E,oDAAoD;AACpD,cAAc;AACd,QAAQ;AACR,EAAE;AACF,0CAA0C;AAC1C,YAAY;AACZ,kDAAkD;AAClD,8DAA8D;AAC9D,sCAAsC;AACtC,wBAAwB;AACxB,+EAA+E;AAC/E,wDAAwD;AACxD,cAAc;AACd,QAAQ;AACR,EAAE;AACF,2CAA2C;AAC3C,oIAAoI;AACpI,6DAA6D;AAC7D,UAAU;AACV,kDAAkD;AAClD,EAAE;AACF,oEAAoE;AACpE,YAAY;AACZ,oDAAoD;AACpD,+DAA+D;AAC/D,wCAAwC;AACxC,wBAAwB;AACxB,gFAAgF;AAChF,yDAAyD;AACzD,cAAc;AACd,QAAQ;AACR,EAAE;AACF,2GAA2G;AAC3G,EAAE;AACF,qBAAqB;AACrB,IAAI"} \ No newline at end of file diff --git a/lib.commonjs/providers/abstract-signer.d.ts b/lib.commonjs/providers/abstract-signer.d.ts new file mode 100644 index 00000000..62147c3a --- /dev/null +++ b/lib.commonjs/providers/abstract-signer.d.ts @@ -0,0 +1,77 @@ +/** + * Generally the [[Wallet]] and [[JsonRpcSigner]] and their sub-classes + * are sufficent for most developers, but this is provided to + * fascilitate more complex Signers. + * + * @_section: api/providers/abstract-signer: Subclassing Signer [abstract-signer] + */ +import { AddressLike } from "../address/index.js"; +import type { TypedDataDomain, TypedDataField } from "../hash/index.js"; +import type { TransactionLike } from "../transaction/index.js"; +import type { BlockTag, Provider, TransactionRequest, TransactionResponse } from "./provider.js"; +import type { Signer } from "./signer.js"; +/** + * An **AbstractSigner** includes most of teh functionality required + * to get a [[Signer]] working as expected, but requires a few + * Signer-specific methods be overridden. + * + */ +export declare abstract class AbstractSigner

implements Signer { + /** + * The provider this signer is connected to. + */ + readonly provider: P; + /** + * Creates a new Signer connected to %%provider%%. + */ + constructor(provider?: P); + /** + * Resolves to the Signer address. + */ + abstract getAddress(): Promise; + _getAddress(address: AddressLike): string | Promise; + shardFromAddress(_address: AddressLike): Promise; + /** + * Returns the signer connected to %%provider%%. + * + * This may throw, for example, a Signer connected over a Socket or + * to a specific instance of a node may not be transferrable. + */ + abstract connect(provider: null | Provider): Signer; + getNonce(blockTag?: BlockTag): Promise; + populateCall(tx: TransactionRequest): Promise>; + populateTransaction(tx: TransactionRequest): Promise>; + estimateGas(tx: TransactionRequest): Promise; + call(tx: TransactionRequest): Promise; + resolveName(name: string): Promise; + sendTransaction(tx: TransactionRequest): Promise; + abstract signTransaction(tx: TransactionRequest): Promise; + abstract signMessage(message: string | Uint8Array): Promise; + abstract signTypedData(domain: TypedDataDomain, types: Record>, value: Record): Promise; +} +/** + * A **VoidSigner** is a class deisgned to allow an address to be used + * in any API which accepts a Signer, but for which there are no + * credentials available to perform any actual signing. + * + * This for example allow impersonating an account for the purpose of + * static calls or estimating gas, but does not allow sending transactions. + */ +export declare class VoidSigner extends AbstractSigner { + #private; + /** + * The signer address. + */ + readonly address: string; + /** + * Creates a new **VoidSigner** with %%address%% attached to + * %%provider%%. + */ + constructor(address: string, provider?: null | Provider); + getAddress(): Promise; + connect(provider: null | Provider): VoidSigner; + signTransaction(tx: TransactionRequest): Promise; + signMessage(message: string | Uint8Array): Promise; + signTypedData(domain: TypedDataDomain, types: Record>, value: Record): Promise; +} +//# sourceMappingURL=abstract-signer.d.ts.map \ No newline at end of file diff --git a/lib.commonjs/providers/abstract-signer.d.ts.map b/lib.commonjs/providers/abstract-signer.d.ts.map new file mode 100644 index 00000000..27f43736 --- /dev/null +++ b/lib.commonjs/providers/abstract-signer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"abstract-signer.d.ts","sourceRoot":"","sources":["../../src.ts/providers/abstract-signer.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAC,WAAW,EAAiB,MAAM,qBAAqB,CAAC;AAQhE,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAE/D,OAAO,KAAK,EACR,QAAQ,EAAE,QAAQ,EAAE,kBAAkB,EAAE,mBAAmB,EAC9D,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AA+B1C;;;;;GAKG;AACH,8BAAsB,cAAc,CAAC,CAAC,SAAS,IAAI,GAAG,QAAQ,GAAG,IAAI,GAAG,QAAQ,CAAE,YAAW,MAAM;IAC/F;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAG,CAAC,CAAC;IAEtB;;OAEG;gBACS,QAAQ,CAAC,EAAE,CAAC;IAIxB;;OAEG;IACH,QAAQ,CAAC,UAAU,IAAI,OAAO,CAAC,MAAM,CAAC;IAGtC,WAAW,CAAC,OAAO,EAAE,WAAW,GAAG,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAIrD,gBAAgB,CAAC,QAAQ,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC;IAI9D;;;;;OAKG;IACH,QAAQ,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,GAAG,QAAQ,GAAG,MAAM;IAE7C,QAAQ,CAAC,QAAQ,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC;IAI9C,YAAY,CAAC,EAAE,EAAE,kBAAkB,GAAG,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;IAKtE,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AM,EAAE,eAAe,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC;CAG1I"} \ No newline at end of file diff --git a/lib.commonjs/providers/abstract-signer.js b/lib.commonjs/providers/abstract-signer.js new file mode 100644 index 00000000..89aff5b3 --- /dev/null +++ b/lib.commonjs/providers/abstract-signer.js @@ -0,0 +1,182 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VoidSigner = exports.AbstractSigner = void 0; +/** + * Generally the [[Wallet]] and [[JsonRpcSigner]] and their sub-classes + * are sufficent for most developers, but this is provided to + * fascilitate more complex Signers. + * + * @_section: api/providers/abstract-signer: Subclassing Signer [abstract-signer] + */ +const index_js_1 = require("../address/index.js"); +const index_js_2 = require("../transaction/index.js"); +const index_js_3 = require("../utils/index.js"); +const provider_js_1 = require("./provider.js"); +const index_js_4 = require("../utils/index.js"); +function checkProvider(signer, operation) { + if (signer.provider) { + return signer.provider; + } + (0, index_js_3.assert)(false, "missing provider", "UNSUPPORTED_OPERATION", { operation }); +} +async function populate(signer, tx) { + let pop = (0, provider_js_1.copyRequest)(tx); + if (pop.to != null) { + pop.to = (0, index_js_1.resolveAddress)(pop.to, signer); + } + if (pop.from != null) { + const from = pop.from; + pop.from = Promise.all([ + signer.getAddress(), + (0, index_js_1.resolveAddress)(from, signer) + ]).then(([address, from]) => { + (0, index_js_3.assertArgument)(address.toLowerCase() === from.toLowerCase(), "transaction from mismatch", "tx.from", from); + return address; + }); + } + else { + pop.from = signer.getAddress(); + } + return await (0, index_js_3.resolveProperties)(pop); +} +/** + * An **AbstractSigner** includes most of teh functionality required + * to get a [[Signer]] working as expected, but requires a few + * Signer-specific methods be overridden. + * + */ +class AbstractSigner { + /** + * The provider this signer is connected to. + */ + provider; + /** + * Creates a new Signer connected to %%provider%%. + */ + constructor(provider) { + (0, index_js_3.defineProperties)(this, { provider: (provider || null) }); + } + _getAddress(address) { + return (0, index_js_1.resolveAddress)(address, this); + } + async shardFromAddress(_address) { + let address = this._getAddress(_address); + return (await address).slice(0, 4); + } + async getNonce(blockTag) { + return checkProvider(this, "getTransactionCount").getTransactionCount(await this.getAddress(), blockTag); + } + async populateCall(tx) { + const pop = await populate(this, tx); + return pop; + } + async populateTransaction(tx) { + const provider = checkProvider(this, "populateTransaction"); + const shard = await this.shardFromAddress(tx.from); + const pop = await populate(this, tx); + if (pop.nonce == null) { + pop.nonce = await this.getNonce("pending"); + } + if (pop.type == null) { + pop.type = await (0, index_js_4.getTxType)(pop.from ?? null, pop.to ?? null); + } + if (pop.gasLimit == null) { + if (tx.type == 0) + pop.gasLimit = await this.estimateGas(pop); + else { + //Special cases for type 2 tx to bypass address out of scope in the node + let temp = pop.to; + pop.to = "0x0000000000000000000000000000000000000000"; + pop.gasLimit = (0, index_js_3.getBigInt)(2 * Number(await this.estimateGas(pop))); + pop.to = temp; + } + } + // Populate the chain ID + const network = await (this.provider).getNetwork(); + if (pop.chainId != null) { + const chainId = (0, index_js_3.getBigInt)(pop.chainId); + (0, index_js_3.assertArgument)(chainId === network.chainId, "transaction chainId mismatch", "tx.chainId", shard); + } + else { + pop.chainId = network.chainId; + } + if (pop.maxFeePerGas == null || pop.maxPriorityFeePerGas == null) { + const feeData = await provider.getFeeData(shard); + if (pop.maxFeePerGas == null) { + pop.maxFeePerGas = feeData.maxFeePerGas; + } + if (pop.maxPriorityFeePerGas == null) { + pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; + } + } + if (pop.type == 2) { + pop.externalGasLimit = (0, index_js_3.getBigInt)(Number(pop.gasLimit) * 9); + pop.externalGasTip = (0, index_js_3.getBigInt)(Number(pop.maxPriorityFeePerGas) * 9); + pop.externalGasPrice = (0, index_js_3.getBigInt)(Number(pop.maxFeePerGas) * 9); + } + //@TOOD: Don't await all over the place; save them up for + // the end for better batching + return await (0, index_js_3.resolveProperties)(pop); + } + async estimateGas(tx) { + return checkProvider(this, "estimateGas").estimateGas(await this.populateCall(tx)); + } + async call(tx) { + return checkProvider(this, "call").call(await this.populateCall(tx)); + } + async resolveName(name) { + const provider = checkProvider(this, "resolveName"); + return await provider.resolveName(name); + } + async sendTransaction(tx) { + const provider = checkProvider(this, "sendTransaction"); + const shard = await this.shardFromAddress(tx.from); + const pop = await this.populateTransaction(tx); + // delete pop.from; + const txObj = index_js_2.Transaction.from(pop); + const signedTx = await this.signTransaction(txObj); + console.log("signedTX: ", JSON.stringify(txObj)); + return await provider.broadcastTransaction(shard, signedTx); + } +} +exports.AbstractSigner = AbstractSigner; +/** + * A **VoidSigner** is a class deisgned to allow an address to be used + * in any API which accepts a Signer, but for which there are no + * credentials available to perform any actual signing. + * + * This for example allow impersonating an account for the purpose of + * static calls or estimating gas, but does not allow sending transactions. + */ +class VoidSigner extends AbstractSigner { + /** + * The signer address. + */ + address; + /** + * Creates a new **VoidSigner** with %%address%% attached to + * %%provider%%. + */ + constructor(address, provider) { + super(provider); + (0, index_js_3.defineProperties)(this, { address }); + } + async getAddress() { return this.address; } + connect(provider) { + return new VoidSigner(this.address, provider); + } + #throwUnsupported(suffix, operation) { + (0, index_js_3.assert)(false, `VoidSigner cannot sign ${suffix}`, "UNSUPPORTED_OPERATION", { operation }); + } + async signTransaction(tx) { + this.#throwUnsupported("transactions", "signTransaction"); + } + async signMessage(message) { + this.#throwUnsupported("messages", "signMessage"); + } + async signTypedData(domain, types, value) { + this.#throwUnsupported("typed-data", "signTypedData"); + } +} +exports.VoidSigner = VoidSigner; +//# sourceMappingURL=abstract-signer.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/abstract-signer.js.map b/lib.commonjs/providers/abstract-signer.js.map new file mode 100644 index 00000000..06cb6eaf --- /dev/null +++ b/lib.commonjs/providers/abstract-signer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abstract-signer.js","sourceRoot":"","sources":["../../src.ts/providers/abstract-signer.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ChG,CAAC;IAED,KAAK,CAAC,eAAe,CAAC,EAAsB;QACxC,IAAI,CAAC,iBAAiB,CAAC,cAAc,EAAE,iBAAiB,CAAC,CAAC;IAC9D,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,OAA4B;QAC1C,IAAI,CAAC,iBAAiB,CAAC,UAAU,EAAE,aAAa,CAAC,CAAC;IACtD,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,MAAuB,EAAE,KAA4C,EAAE,KAA0B;QACjH,IAAI,CAAC,iBAAiB,CAAC,YAAY,EAAE,eAAe,CAAC,CAAC;IAC1D,CAAC;CACJ;AApCD,gCAoCC"} \ No newline at end of file diff --git a/lib.commonjs/providers/default-provider.d.ts b/lib.commonjs/providers/default-provider.d.ts new file mode 100644 index 00000000..a869dc5c --- /dev/null +++ b/lib.commonjs/providers/default-provider.d.ts @@ -0,0 +1,48 @@ +import type { AbstractProvider } from "./abstract-provider.js"; +import type { Networkish } from "./network.js"; +import { WebSocketLike } from "./provider-websocket.js"; +/** + * Returns a default provider for %%network%%. + * + * If %%network%% is a [[WebSocketLike]] or string that begins with + * ``"ws:"`` or ``"wss:"``, a [[WebSocketProvider]] is returned backed + * by that WebSocket or URL. + * + * If %%network%% is a string that begins with ``"HTTP:"`` or ``"HTTPS:"``, + * a [[JsonRpcProvider]] is returned connected to that URL. + * + * Otherwise, a default provider is created backed by well-known public + * Web3 backends (such as [[link-infura]]) using community-provided API + * keys. + * + * The %%options%% allows specifying custom API keys per backend (setting + * an API key to ``"-"`` will omit that provider) and ``options.exclusive`` + * can be set to either a backend name or and array of backend names, which + * will whitelist **only** those backends. + * + * Current backend strings supported are: + * - ``"alchemy"`` + * - ``"ankr"`` + * - ``"cloudflare"`` + * - ``"quaiscan"`` + * - ``"infura"`` + * - ``"publicPolygon"`` + * - ``"quicknode"`` + * + * @example: + * // Connect to a local Geth node + * provider = getDefaultProvider("http://localhost:8545/"); + * + * // Connect to Ethereum mainnet with any current and future + * // third-party services available + * provider = getDefaultProvider("mainnet"); + * + * // Connect to Polygon, but only allow quaiscan and + * // INFURA and use "MY_API_KEY" in calls to quaiscan. + * provider = getDefaultProvider("matic", { + * quaiscan: "MY_API_KEY", + * exclusive: [ "quaiscan", "infura" ] + * }); + */ +export declare function getDefaultProvider(network: string | string[] | Networkish | WebSocketLike, options?: any): AbstractProvider; +//# sourceMappingURL=default-provider.d.ts.map \ No newline at end of file diff --git a/lib.commonjs/providers/default-provider.d.ts.map b/lib.commonjs/providers/default-provider.d.ts.map new file mode 100644 index 00000000..a4680d53 --- /dev/null +++ b/lib.commonjs/providers/default-provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"default-provider.d.ts","sourceRoot":"","sources":["../../src.ts/providers/default-provider.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AASxD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,UAAU,GAAG,aAAa,EAAE,OAAO,CAAC,EAAE,GAAG,GAAG,gBAAgB,CAsF3H"} \ No newline at end of file diff --git a/lib.commonjs/providers/default-provider.js b/lib.commonjs/providers/default-provider.js new file mode 100644 index 00000000..38f78d9a --- /dev/null +++ b/lib.commonjs/providers/default-provider.js @@ -0,0 +1,142 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getDefaultProvider = void 0; +const index_js_1 = require("../utils/index.js"); +const provider_fallback_js_1 = require("./provider-fallback.js"); +const provider_jsonrpc_js_1 = require("./provider-jsonrpc.js"); +const network_js_1 = require("./network.js"); +const provider_websocket_js_1 = require("./provider-websocket.js"); +function isWebSocketLike(value) { + return (value && typeof (value.send) === "function" && + typeof (value.close) === "function"); +} +const Testnets = "goerli kovan sepolia classicKotti optimism-goerli arbitrum-goerli matic-mumbai bnbt".split(" "); +/** + * Returns a default provider for %%network%%. + * + * If %%network%% is a [[WebSocketLike]] or string that begins with + * ``"ws:"`` or ``"wss:"``, a [[WebSocketProvider]] is returned backed + * by that WebSocket or URL. + * + * If %%network%% is a string that begins with ``"HTTP:"`` or ``"HTTPS:"``, + * a [[JsonRpcProvider]] is returned connected to that URL. + * + * Otherwise, a default provider is created backed by well-known public + * Web3 backends (such as [[link-infura]]) using community-provided API + * keys. + * + * The %%options%% allows specifying custom API keys per backend (setting + * an API key to ``"-"`` will omit that provider) and ``options.exclusive`` + * can be set to either a backend name or and array of backend names, which + * will whitelist **only** those backends. + * + * Current backend strings supported are: + * - ``"alchemy"`` + * - ``"ankr"`` + * - ``"cloudflare"`` + * - ``"quaiscan"`` + * - ``"infura"`` + * - ``"publicPolygon"`` + * - ``"quicknode"`` + * + * @example: + * // Connect to a local Geth node + * provider = getDefaultProvider("http://localhost:8545/"); + * + * // Connect to Ethereum mainnet with any current and future + * // third-party services available + * provider = getDefaultProvider("mainnet"); + * + * // Connect to Polygon, but only allow quaiscan and + * // INFURA and use "MY_API_KEY" in calls to quaiscan. + * provider = getDefaultProvider("matic", { + * quaiscan: "MY_API_KEY", + * exclusive: [ "quaiscan", "infura" ] + * }); + */ +function getDefaultProvider(network, options) { + if (options == null) { + options = {}; + } + const allowService = (name) => { + if (options[name] === "-") { + return false; + } + if (typeof (options.exclusive) === "string") { + return (name === options.exclusive); + } + if (Array.isArray(options.exclusive)) { + return (options.exclusive.indexOf(name) !== -1); + } + return true; + }; + if (typeof (network) === "string" && network.match(/^https?:/)) { + return new provider_jsonrpc_js_1.JsonRpcProvider(network); + } + if (Array.isArray(network) && network[0].match(/^https?:/)) { + return new provider_jsonrpc_js_1.JsonRpcProvider(network); + } + if (typeof (network) === "string" && network.match(/^wss?:/) || isWebSocketLike(network)) { + return new provider_websocket_js_1.WebSocketProvider(network); + } + if (Array.isArray(network) && (network[0].match(/^wss?:/) || isWebSocketLike(network[0]))) { + return new provider_websocket_js_1.WebSocketProvider(network[0]); + } + if (Array.isArray(network)) { + (0, index_js_1.assert)(false, "unsupported default network", "UNSUPPORTED_OPERATION", { + operation: "getDefaultProvider" + }); + } + // Get the network and name, if possible + let staticNetwork = null; + try { + staticNetwork = network_js_1.Network.from(network); + } + catch (error) { } + const providers = []; + if (allowService("publicPolygon") && staticNetwork) { + if (staticNetwork.name === "matic") { + providers.push(new provider_jsonrpc_js_1.JsonRpcProvider("https:/\/polygon-rpc.com/", staticNetwork, { staticNetwork })); + } + } + /* + if (options.pocket !== "-") { + try { + let appId = options.pocket; + let secretKey: undefined | string = undefined; + let loadBalancer: undefined | boolean = undefined; + if (typeof(appId) === "object") { + loadBalancer = !!appId.loadBalancer; + secretKey = appId.secretKey; + appId = appId.appId; + } + providers.push(new PocketProvider(network, appId, secretKey, loadBalancer)); + } catch (error) { console.log(error); } + } + */ + (0, index_js_1.assert)(providers.length, "unsupported default network", "UNSUPPORTED_OPERATION", { + operation: "getDefaultProvider" + }); + // No need for a FallbackProvider + if (providers.length === 1) { + return providers[0]; + } + // We use the floor because public third-party providers can be unreliable, + // so a low number of providers with a large quorum will fail too often + let quorum = Math.floor(providers.length / 2); + if (quorum > 2) { + quorum = 2; + } + // Testnets don't need as strong a security gaurantee and speed is + // more useful during testing + if (staticNetwork && Testnets.indexOf(staticNetwork.name) !== -1) { + quorum = 1; + } + // Provided override qorum takes priority + if (options && options.quorum) { + quorum = options.quorum; + } + return new provider_fallback_js_1.FallbackProvider(providers, undefined, { quorum }); +} +exports.getDefaultProvider = getDefaultProvider; +//# sourceMappingURL=default-provider.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/default-provider.js.map b/lib.commonjs/providers/default-provider.js.map new file mode 100644 index 00000000..1df4b175 --- /dev/null +++ b/lib.commonjs/providers/default-provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"default-provider.js","sourceRoot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BAA6B,EAAE,uBAAuB,EAAE;QAC7E,SAAS,EAAE,oBAAoB;KAClC,CAAC,CAAC;IAEH,iCAAiC;IACjC,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE;QAAE,OAAO,SAAS,CAAC,CAAC,CAAC,CAAC;KAAE;IAEpD,2EAA2E;IAC3E,uEAAuE;IACvE,IAAI,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC9C,IAAI,MAAM,GAAG,CAAC,EAAE;QAAE,MAAM,GAAG,CAAC,CAAC;KAAE;IAE/B,kEAAkE;IAClE,6BAA6B;IAC7B,IAAI,aAAa,IAAI,QAAQ,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE;QAAE,MAAM,GAAG,CAAC,CAAC;KAAE;IAEjF,yCAAyC;IACzC,IAAI,OAAO,IAAI,OAAO,CAAC,MAAM,EAAE;QAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;KAAE;IAE3D,OAAO,IAAI,uCAAgB,CAAC,SAAS,EAAE,SAAS,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;AAClE,CAAC;AAtFD,gDAsFC"} \ No newline at end of file diff --git a/lib.commonjs/providers/formatting.d.ts.map b/lib.commonjs/providers/formatting.d.ts.map new file mode 100644 index 00000000..dbea997a --- /dev/null +++ b/lib.commonjs/providers/formatting.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"formatting.d.ts","sourceRoot":"","sources":["../../src.ts/providers/formatting.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAM1D;;;GAGG;AACH,MAAM,WAAW,WAAW;IACxB;;OAEG;IACH,IAAI,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC;IAErB;;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AK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,SAAS,EAAE,SAAS,CAAC;IAErB;;OAEG;IACH,UAAU,EAAE,IAAI,GAAG,UAAU,CAAC;IAI9B,WAAY,CAAC,EAAE,MAAM,CAAE;IAEvB,WAAY,CAAC,EAAE,MAAM,CAAE;IAEvB,SAAY,CAAC,EAAE,MAAM,CAAE;IAEvB,OAAY,CAAC,EAAE,MAAM,CAAE;IAEvB,aAAc,CAAC,EAAE,UAAU,CAAE;CAChC"} \ No newline at end of file diff --git a/lib.commonjs/providers/formatting.js.map b/lib.commonjs/providers/formatting.js.map new file mode 100644 index 00000000..c59f1ce5 --- /dev/null +++ b/lib.commonjs/providers/formatting.js.map @@ -0,0 +1 @@ +{"version":3,"file":"formatting.js","sourceRoot":"","sources":["../../src.ts/providers/formatting.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAkHF,CAAC;AAqRD,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/providers/provider-fallback.js b/lib.commonjs/providers/provider-fallback.js new file mode 100644 index 00000000..7047f9b7 --- /dev/null +++ b/lib.commonjs/providers/provider-fallback.js @@ -0,0 +1,615 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FallbackProvider = void 0; +/** + * A **FallbackProvider** providers resiliance, security and performatnce + * in a way that is customizable and configurable. + * + * @_section: api/providers/fallback-provider:Fallback Provider [about-fallback-provider] + */ +const index_js_1 = require("../utils/index.js"); +const abstract_provider_js_1 = require("./abstract-provider.js"); +const network_js_1 = require("./network.js"); +const BN_1 = BigInt("1"); +const BN_2 = BigInt("2"); +function shuffle(array) { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + const tmp = array[i]; + array[i] = array[j]; + array[j] = tmp; + } +} +function stall(duration) { + return new Promise((resolve) => { setTimeout(resolve, duration); }); +} +function getTime() { return (new Date()).getTime(); } +function stringify(value) { + return JSON.stringify(value, (key, value) => { + if (typeof (value) === "bigint") { + return { type: "bigint", value: value.toString() }; + } + return value; + }); +} +; +const defaultConfig = { stallTimeout: 400, priority: 1, weight: 1 }; +const defaultState = { + blockNumber: -2, requests: 0, lateResponses: 0, errorResponses: 0, + outOfSync: -1, unsupportedEvents: 0, rollingDuration: 0, score: 0, + _network: null, _updateNumber: null, _totalTime: 0, + _lastFatalError: null, _lastFatalErrorTimestamp: 0 +}; +async function waitForSync(config, blockNumber) { + while (config.blockNumber < 0 || config.blockNumber < blockNumber) { + if (!config._updateNumber) { + config._updateNumber = (async () => { + try { + const blockNumber = await config.provider.getBlockNumber(); + if (blockNumber > config.blockNumber) { + config.blockNumber = blockNumber; + } + } + catch (error) { + config.blockNumber = -2; + config._lastFatalError = error; + config._lastFatalErrorTimestamp = getTime(); + } + config._updateNumber = null; + })(); + } + await config._updateNumber; + config.outOfSync++; + if (config._lastFatalError) { + break; + } + } +} +function _normalize(value) { + if (value == null) { + return "null"; + } + if (Array.isArray(value)) { + return "[" + (value.map(_normalize)).join(",") + "]"; + } + if (typeof (value) === "object" && typeof (value.toJSON) === "function") { + return _normalize(value.toJSON()); + } + switch (typeof (value)) { + case "boolean": + case "symbol": + return value.toString(); + case "bigint": + case "number": + return BigInt(value).toString(); + case "string": + return JSON.stringify(value); + case "object": { + const keys = Object.keys(value); + keys.sort(); + return "{" + keys.map((k) => `${JSON.stringify(k)}:${_normalize(value[k])}`).join(",") + "}"; + } + } + console.log("Could not serialize", value); + throw new Error("Hmm..."); +} +function normalizeResult(value) { + if ("error" in value) { + const error = value.error; + return { tag: _normalize(error), value: error }; + } + const result = value.result; + return { tag: _normalize(result), value: result }; +} +// This strategy picks the highest weight result, as long as the weight is +// equal to or greater than quorum +function checkQuorum(quorum, results) { + const tally = new Map(); + for (const { value, tag, weight } of results) { + const t = tally.get(tag) || { value, weight: 0 }; + t.weight += weight; + tally.set(tag, t); + } + let best = null; + for (const r of tally.values()) { + if (r.weight >= quorum && (!best || r.weight > best.weight)) { + best = r; + } + } + if (best) { + return best.value; + } + return undefined; +} +function getMedian(quorum, results) { + let resultWeight = 0; + const errorMap = new Map(); + let bestError = null; + const values = []; + for (const { value, tag, weight } of results) { + if (value instanceof Error) { + const e = errorMap.get(tag) || { value, weight: 0 }; + e.weight += weight; + errorMap.set(tag, e); + if (bestError == null || e.weight > bestError.weight) { + bestError = e; + } + } + else { + values.push(BigInt(value)); + resultWeight += weight; + } + } + if (resultWeight < quorum) { + // We have quorum for an error + if (bestError && bestError.weight >= quorum) { + return bestError.value; + } + // We do not have quorum for a result + return undefined; + } + // Get the sorted values + values.sort((a, b) => ((a < b) ? -1 : (b > a) ? 1 : 0)); + const mid = Math.floor(values.length / 2); + // Odd-length; take the middle value + if (values.length % 2) { + return values[mid]; + } + // Even length; take the ceiling of the mean of the center two values + return (values[mid - 1] + values[mid] + BN_1) / BN_2; +} +function getAnyResult(quorum, results) { + // If any value or error meets quorum, that is our preferred result + const result = checkQuorum(quorum, results); + if (result !== undefined) { + return result; + } + // Otherwise, do we have any result? + for (const r of results) { + if (r.value) { + return r.value; + } + } + // Nope! + return undefined; +} +function getFuzzyMode(quorum, results) { + if (quorum === 1) { + return (0, index_js_1.getNumber)(getMedian(quorum, results), "%internal"); + } + const tally = new Map(); + const add = (result, weight) => { + const t = tally.get(result) || { result, weight: 0 }; + t.weight += weight; + tally.set(result, t); + }; + for (const { weight, value } of results) { + const r = (0, index_js_1.getNumber)(value); + add(r - 1, weight); + add(r, weight); + add(r + 1, weight); + } + let bestWeight = 0; + let bestResult = undefined; + for (const { weight, result } of tally.values()) { + // Use this result, if this result meets quorum and has either: + // - a better weight + // - or equal weight, but the result is larger + if (weight >= quorum && (weight > bestWeight || (bestResult != null && weight === bestWeight && result > bestResult))) { + bestWeight = weight; + bestResult = result; + } + } + return bestResult; +} +/** + * A **FallbackProvider** manages several [[Providers]] providing + * resiliance by switching between slow or misbehaving nodes, security + * by requiring multiple backends to aggree and performance by allowing + * faster backends to respond earlier. + * + */ +class FallbackProvider extends abstract_provider_js_1.AbstractProvider { + /** + * The number of backends that must agree on a value before it is + * accpeted. + */ + quorum; + /** + * @_ignore: + */ + eventQuorum; + /** + * @_ignore: + */ + eventWorkers; + #configs; + #height; + #initialSyncPromise; + /** + * Creates a new **FallbackProvider** with %%providers%% connected to + * %%network%%. + * + * If a [[Provider]] is included in %%providers%%, defaults are used + * for the configuration. + */ + constructor(providers, network, options) { + super(network, options); + this.#configs = providers.map((p) => { + if (p instanceof abstract_provider_js_1.AbstractProvider) { + return Object.assign({ provider: p }, defaultConfig, defaultState); + } + else { + return Object.assign({}, defaultConfig, p, defaultState); + } + }); + this.#height = -2; + this.#initialSyncPromise = null; + if (options && options.quorum != null) { + this.quorum = options.quorum; + } + else { + this.quorum = Math.ceil(this.#configs.reduce((accum, config) => { + accum += config.weight; + return accum; + }, 0) / 2); + } + this.eventQuorum = 1; + this.eventWorkers = 1; + (0, index_js_1.assertArgument)(this.quorum <= this.#configs.reduce((a, c) => (a + c.weight), 0), "quorum exceed provider wieght", "quorum", this.quorum); + } + get providerConfigs() { + return this.#configs.map((c) => { + const result = Object.assign({}, c); + for (const key in result) { + if (key[0] === "_") { + delete result[key]; + } + } + return result; + }); + } + async _detectNetwork() { + return network_js_1.Network.from((0, index_js_1.getBigInt)(await this._perform({ method: "chainId" }))); + } + // @TODO: Add support to select providers to be the event subscriber + //_getSubscriber(sub: Subscription): Subscriber { + // throw new Error("@TODO"); + //} + /** + * Transforms a %%req%% into the correct method call on %%provider%%. + */ + async _translatePerform(provider, req) { + switch (req.method) { + case "broadcastTransaction": + return await provider.broadcastTransaction(req.shard, req.signedTransaction); + case "call": + return await provider.call(Object.assign({}, req.transaction, { blockTag: req.blockTag })); + case "chainId": + return (await provider.getNetwork()).chainId; + case "estimateGas": + return await provider.estimateGas(req.transaction); + case "getBalance": + return await provider.getBalance(req.address, req.blockTag); + case "getBlock": { + const block = ("blockHash" in req) ? req.blockHash : req.blockTag; + return await provider.getBlock(req.shard, block, req.includeTransactions); + } + case "getBlockNumber": + return await provider.getBlockNumber(); + case "getCode": + return await provider.getCode(req.address, req.blockTag); + case "getGasPrice": + return (await provider.getFeeData()).gasPrice; + case "getMaxPriorityFeePerGas": + return (await provider.getFeeData()).maxPriorityFeePerGas; + case "getLogs": + return await provider.getLogs(req.filter); + case "getStorage": + return await provider.getStorage(req.address, req.position, req.blockTag); + case "getTransaction": + return await provider.getTransaction(req.hash); + case "getTransactionCount": + return await provider.getTransactionCount(req.address, req.blockTag); + case "getTransactionReceipt": + return await provider.getTransactionReceipt(req.hash); + case "getTransactionResult": + return await provider.getTransactionResult(req.hash); + } + } + // Grab the next (random) config that is not already part of + // the running set + #getNextConfig(running) { + // @TODO: Maybe do a check here to favour (heavily) providers that + // do not require waitForSync and disfavour providers that + // seem down-ish or are behaving slowly + const configs = Array.from(running).map((r) => r.config); + // Shuffle the states, sorted by priority + const allConfigs = this.#configs.slice(); + shuffle(allConfigs); + allConfigs.sort((a, b) => (a.priority - b.priority)); + for (const config of allConfigs) { + if (config._lastFatalError) { + continue; + } + if (configs.indexOf(config) === -1) { + return config; + } + } + return null; + } + // Adds a new runner (if available) to running. + #addRunner(running, req) { + const config = this.#getNextConfig(running); + // No runners available + if (config == null) { + return null; + } + // Create a new runner + const runner = { + config, result: null, didBump: false, + perform: null, staller: null + }; + const now = getTime(); + // Start performing this operation + runner.perform = (async () => { + try { + config.requests++; + const result = await this._translatePerform(config.provider, req); + runner.result = { result }; + } + catch (error) { + config.errorResponses++; + runner.result = { error }; + } + const dt = (getTime() - now); + config._totalTime += dt; + config.rollingDuration = 0.95 * config.rollingDuration + 0.05 * dt; + runner.perform = null; + })(); + // Start a staller; when this times out, it's time to force + // kicking off another runner because we are taking too long + runner.staller = (async () => { + await stall(config.stallTimeout); + runner.staller = null; + })(); + running.add(runner); + return runner; + } + // Initializes the blockNumber and network for each runner and + // blocks until initialized + async #initialSync() { + let initialSync = this.#initialSyncPromise; + if (!initialSync) { + const promises = []; + this.#configs.forEach((config) => { + promises.push((async () => { + await waitForSync(config, 0); + if (!config._lastFatalError) { + config._network = await config.provider.getNetwork(); + } + })()); + }); + this.#initialSyncPromise = initialSync = (async () => { + // Wait for all providers to have a block number and network + await Promise.all(promises); + // Check all the networks match + let chainId = null; + for (const config of this.#configs) { + if (config._lastFatalError) { + continue; + } + const network = (config._network); + if (chainId == null) { + chainId = network.chainId; + } + else if (network.chainId !== chainId) { + (0, index_js_1.assert)(false, "cannot mix providers on different networks", "UNSUPPORTED_OPERATION", { + operation: "new FallbackProvider" + }); + } + } + })(); + } + await initialSync; + } + async #checkQuorum(running, req) { + // Get all the result objects + const results = []; + for (const runner of running) { + if (runner.result != null) { + const { tag, value } = normalizeResult(runner.result); + results.push({ tag, value, weight: runner.config.weight }); + } + } + // Are there enough results to event meet quorum? + if (results.reduce((a, r) => (a + r.weight), 0) < this.quorum) { + return undefined; + } + switch (req.method) { + case "getBlockNumber": { + // We need to get the bootstrap block height + if (this.#height === -2) { + this.#height = Math.ceil((0, index_js_1.getNumber)(getMedian(this.quorum, this.#configs.filter((c) => (!c._lastFatalError)).map((c) => ({ + value: c.blockNumber, + tag: (0, index_js_1.getNumber)(c.blockNumber).toString(), + weight: c.weight + }))))); + } + // Find the mode across all the providers, allowing for + // a little drift between block heights + const mode = getFuzzyMode(this.quorum, results); + if (mode === undefined) { + return undefined; + } + if (mode > this.#height) { + this.#height = mode; + } + return this.#height; + } + case "getGasPrice": + case "getMaxPriorityFeePerGas": + case "estimateGas": + return getMedian(this.quorum, results); + case "getBlock": + // Pending blocks are in the mempool and already + // quite untrustworthy; just grab anything + if ("blockTag" in req && req.blockTag === "pending") { + return getAnyResult(this.quorum, results); + } + return checkQuorum(this.quorum, results); + case "call": + case "chainId": + case "getBalance": + case "getTransactionCount": + case "getCode": + case "getStorage": + case "getTransaction": + case "getTransactionReceipt": + case "getLogs": + return checkQuorum(this.quorum, results); + case "broadcastTransaction": + return getAnyResult(this.quorum, results); + } + (0, index_js_1.assert)(false, "unsupported method", "UNSUPPORTED_OPERATION", { + operation: `_perform(${stringify(req.method)})` + }); + } + async #waitForQuorum(running, req) { + if (running.size === 0) { + throw new Error("no runners?!"); + } + // Any promises that are interesting to watch for; an expired stall + // or a successful perform + const interesting = []; + let newRunners = 0; + for (const runner of running) { + // No responses, yet; keep an eye on it + if (runner.perform) { + interesting.push(runner.perform); + } + // Still stalling... + if (runner.staller) { + interesting.push(runner.staller); + continue; + } + // This runner has already triggered another runner + if (runner.didBump) { + continue; + } + // Got a response (result or error) or stalled; kick off another runner + runner.didBump = true; + newRunners++; + } + // Check if we have reached quorum on a result (or error) + const value = await this.#checkQuorum(running, req); + if (value !== undefined) { + if (value instanceof Error) { + throw value; + } + return value; + } + // Add any new runners, because a staller timed out or a result + // or error response came in. + for (let i = 0; i < newRunners; i++) { + this.#addRunner(running, req); + } + // All providers have returned, and we have no result + (0, index_js_1.assert)(interesting.length > 0, "quorum not met", "SERVER_ERROR", { + request: "%sub-requests", + info: { request: req, results: Array.from(running).map((r) => stringify(r.result)) } + }); + // Wait for someone to either complete its perform or stall out + await Promise.race(interesting); + // This is recursive, but at worst case the depth is 2x the + // number of providers (each has a perform and a staller) + return await this.#waitForQuorum(running, req); + } + async _perform(req) { + // Broadcasting a transaction is rare (ish) and already incurs + // a cost on the user, so spamming is safe-ish. Just send it to + // every backend. + if (req.method === "broadcastTransaction") { + // Once any broadcast provides a positive result, use it. No + // need to wait for anyone else + const results = this.#configs.map((c) => null); + const broadcasts = this.#configs.map(async ({ provider, weight }, index) => { + try { + const result = await provider._perform(req); + results[index] = Object.assign(normalizeResult({ result }), { weight }); + } + catch (error) { + results[index] = Object.assign(normalizeResult({ error }), { weight }); + } + }); + // As each promise finishes... + while (true) { + // Check for a valid broadcast result + const done = results.filter((r) => (r != null)); + for (const { value } of done) { + if (!(value instanceof Error)) { + return value; + } + } + // Check for a legit broadcast error (one which we cannot + // recover from; some nodes may return the following red + // herring events: + // - alredy seend (UNKNOWN_ERROR) + // - NONCE_EXPIRED + // - REPLACEMENT_UNDERPRICED + const result = checkQuorum(this.quorum, results.filter((r) => (r != null))); + if ((0, index_js_1.isError)(result, "INSUFFICIENT_FUNDS")) { + throw result; + } + // Kick off the next provider (if any) + const waiting = broadcasts.filter((b, i) => (results[i] == null)); + if (waiting.length === 0) { + break; + } + await Promise.race(waiting); + } + // Use standard quorum results; any result was returned above, + // so this will find any error that met quorum if any + const result = getAnyResult(this.quorum, results); + (0, index_js_1.assert)(result !== undefined, "problem multi-broadcasting", "SERVER_ERROR", { + request: "%sub-requests", + info: { request: req, results: results.map(stringify) } + }); + if (result instanceof Error) { + throw result; + } + return result; + } + await this.#initialSync(); + // Bootstrap enough runners to meet quorum + const running = new Set(); + let inflightQuorum = 0; + while (true) { + const runner = this.#addRunner(running, req); + if (runner == null) { + break; + } + inflightQuorum += runner.config.weight; + if (inflightQuorum >= this.quorum) { + break; + } + } + const result = await this.#waitForQuorum(running, req); + // Track requests sent to a provider that are still + // outstanding after quorum has been otherwise found + for (const runner of running) { + if (runner.perform && runner.result == null) { + runner.config.lateResponses++; + } + } + return result; + } + async destroy() { + for (const { provider } of this.#configs) { + provider.destroy(); + } + super.destroy(); + } +} +exports.FallbackProvider = FallbackProvider; +//# sourceMappingURL=provider-fallback.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/provider-fallback.js.map b/lib.commonjs/providers/provider-fallback.js.map new file mode 100644 index 00000000..0e1050c6 --- /dev/null +++ b/lib.commonjs/providers/provider-fallback.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-fallback.js","sourceRoot":"","sources":["../../src.ts/providers/provider-fallback.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACH,gDAE2B;AAE3B,iEAA0D;AAC1D,6CAAsC;AAKtC,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;AACzB,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;AAEzB,SAAS,OAAO,CAAU,KAAe;IACrC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AAO,EAAE,GAAG,CAAC,CAAC;YAC7C,IAAI,MAAM,IAAI,IAAI,EAAE;gBAAE,MAAM;aAAE;YAC9B,cAAc,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;YACvC,IAAI,cAAc,IAAI,IAAI,CAAC,MAAM,EAAE;gBAAE,MAAM;aAAE;SAChD;QAED,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;QAEvD,mDAAmD;QACnD,oDAAoD;QACpD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE;YAC1B,IAAI,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,MAAM,IAAI,IAAI,EAAE;gBACzC,MAAM,CAAC,MAAM,CAAC,aAAa,EAAE,CAAC;aACjC;SACJ;QAED,OAAO,MAAM,CAAC;IAClB,CAAC;IAED,KAAK,CAAC,OAAO;QACT,KAAK,MAAM,EAAE,QAAQ,EAAE,IAAI,IAAI,CAAC,QAAQ,EAAE;YACtC,QAAQ,CAAC,OAAO,EAAE,CAAC;SACtB;QACD,KAAK,CAAC,OAAO,EAAE,CAAC;IACpB,CAAC;CACJ;AAnbD,4CAmbC"} \ No newline at end of file diff --git a/lib.commonjs/providers/provider-jsonrpc.d.ts b/lib.commonjs/providers/provider-jsonrpc.d.ts new file mode 100644 index 00000000..4db114aa --- /dev/null +++ b/lib.commonjs/providers/provider-jsonrpc.d.ts @@ -0,0 +1,336 @@ +/** + * One of the most common ways to interact with the blockchain is + * by a node running a JSON-RPC interface which can be connected to, + * based on the transport, using: + * + * - HTTP or HTTPS - [[JsonRpcProvider]] + * - WebSocket - [[WebSocketProvider]] + * - IPC - [[IpcSocketProvider]] + * + * @_section: api/providers/jsonrpc:JSON-RPC Provider [about-jsonrpcProvider] + */ +import { FetchRequest } from "../utils/index.js"; +import { AbstractProvider } from "./abstract-provider.js"; +import { AbstractSigner } from "./abstract-signer.js"; +import { Network } from "./network.js"; +import type { TypedDataDomain, TypedDataField } from "../hash/index.js"; +import type { TransactionLike } from "../transaction/index.js"; +import type { PerformActionRequest, Subscriber, Subscription } from "./abstract-provider.js"; +import type { Networkish } from "./network.js"; +import type { Provider, TransactionRequest, TransactionResponse } from "./provider.js"; +import type { Signer } from "./signer.js"; +/** + * A JSON-RPC payload, which are sent to a JSON-RPC server. + */ +export type JsonRpcPayload = { + /** + * The JSON-RPC request ID. + */ + id: number; + /** + * The JSON-RPC request method. + */ + method: string; + /** + * The JSON-RPC request parameters. + */ + params: Array | Record; + /** + * A required constant in the JSON-RPC specification. + */ + jsonrpc: "2.0"; +}; +/** + * A JSON-RPC result, which are returned on success from a JSON-RPC server. + */ +export type JsonRpcResult = { + /** + * The response ID to match it to the relevant request. + */ + id: number; + /** + * The response result. + */ + result: any; +}; +/** + * A JSON-RPC error, which are returned on failure from a JSON-RPC server. + */ +export type JsonRpcError = { + /** + * The response ID to match it to the relevant request. + */ + id: number; + /** + * The response error. + */ + error: { + code: number; + message?: string; + data?: any; + }; +}; +/** + * When subscribing to the ``"debug"`` event, the [[Listener]] will + * receive this object as the first parameter. + */ +export type DebugEventJsonRpcApiProvider = { + action: "sendRpcPayload"; + payload: JsonRpcPayload | Array; +} | { + action: "receiveRpcResult"; + result: Array; +} | { + action: "receiveRpcError"; + error: Error; +}; +/** + * Options for configuring a [[JsonRpcApiProvider]]. Much of this + * is targetted towards sub-classes, which often will not expose + * any of these options to their consumers. + * + * **``polling``** - use the polling strategy is used immediately + * for events; otherwise, attempt to use filters and fall back onto + * polling (default: ``false``) + * + * **``staticNetwork``** - do not request chain ID on requests to + * validate the underlying chain has not changed (default: ``null``) + * + * This should **ONLY** be used if it is **certain** that the network + * cannot change, such as when using INFURA (since the URL dictates the + * network). If the network is assumed static and it does change, this + * can have tragic consequences. For example, this **CANNOT** be used + * with MetaMask, since the used can select a new network from the + * drop-down at any time. + * + * **``batchStallTime``** - how long (ms) to aggregate requests into a + * single batch. ``0`` indicates batching will only encompass the current + * event loop. If ``batchMaxCount = 1``, this is ignored. (default: ``10``) + * + * **``batchMaxSize``** - target maximum size (bytes) to allow per batch + * request (default: 1Mb) + * + * **``batchMaxCount``** - maximum number of requests to allow in a batch. + * If ``batchMaxCount = 1``, then batching is disabled. (default: ``100``) + * + * **``cacheTimeout``** - passed as [[AbstractProviderOptions]]. + */ +export type JsonRpcApiProviderOptions = { + staticNetwork?: null | Network | boolean; + batchStallTime?: number; + batchMaxSize?: number; + batchMaxCount?: number; + cacheTimeout?: number; +}; +/** + * A **JsonRpcTransactionRequest** is formatted as needed by the JSON-RPC + * Ethereum API specification. + */ +export interface JsonRpcTransactionRequest { + /** + * The sender address to use when signing. + */ + from?: string; + /** + * The target address. + */ + to?: string; + /** + * The transaction data. + */ + data?: string; + /** + * The chain ID the transaction is valid on. + */ + chainId?: string; + /** + * The [[link-eip-2718]] transaction type. + */ + type?: string; + /** + * The maximum amount of gas to allow a transaction to consume. + * + * In most other places in quais, this is called ``gasLimit`` which + * differs from the JSON-RPC Ethereum API specification. + */ + gas?: string; + /** + * The gas price per wei for transactions prior to [[link-eip-1559]]. + */ + gasPrice?: string; + /** + * The maximum fee per gas for [[link-eip-1559]] transactions. + */ + maxFeePerGas?: string; + /** + * The maximum priority fee per gas for [[link-eip-1559]] transactions. + */ + maxPriorityFeePerGas?: string; + /** + * The nonce for the transaction. + */ + nonce?: string; + /** + * The transaction value (in wei). + */ + value?: string; + /** + * The transaction access list. + */ + accessList?: Array<{ + address: string; + storageKeys: Array; + }>; +} +export declare class JsonRpcSigner extends AbstractSigner { + address: string; + constructor(provider: JsonRpcApiProvider, address: string); + connect(provider: null | Provider): Signer; + getAddress(): Promise; + populateTransaction(tx: TransactionRequest): Promise>; + sendUncheckedTransaction(_tx: TransactionRequest): Promise; + sendTransaction(tx: TransactionRequest): Promise; + signTransaction(_tx: TransactionRequest): Promise; + signMessage(_message: string | Uint8Array): Promise; + signTypedData(domain: TypedDataDomain, types: Record>, _value: Record): Promise; + unlock(password: string): Promise; + _legacySignMessage(_message: string | Uint8Array): Promise; +} +/** + * The JsonRpcApiProvider is an abstract class and **MUST** be + * sub-classed. + * + * It provides the base for all JSON-RPC-based Provider interaction. + * + * Sub-classing Notes: + * - a sub-class MUST override _send + * - a sub-class MUST call the `_start()` method once connected + */ +export declare abstract class JsonRpcApiProvider extends AbstractProvider { + #private; + initPromise?: Promise; + constructor(network?: Networkish, options?: JsonRpcApiProviderOptions); + /** + * Returns the value associated with the option %%key%%. + * + * Sub-classes can use this to inquire about configuration options. + */ + _getOption(key: K): JsonRpcApiProviderOptions[K]; + /** + * Gets the [[Network]] this provider has committed to. On each call, the network + * is detected, and if it has changed, the call will reject. + */ + get _network(): Network; + /** + * Sends a JSON-RPC %%payload%% (or a batch) to the underlying channel. + * + * Sub-classes **MUST** override this. + */ + abstract _send(payload: JsonRpcPayload | Array, shard?: string): Promise>; + /** + * Resolves to the non-normalized value by performing %%req%%. + * + * Sub-classes may override this to modify behavior of actions, + * and should generally call ``super._perform`` as a fallback. + */ + _perform(req: PerformActionRequest): Promise; + /** + * Sub-classes may override this; it detects the *actual* network that + * we are **currently** connected to. + * + * Keep in mind that [[send]] may only be used once [[ready]], otherwise the + * _send primitive must be used instead. + */ + _detectNetwork(): Promise; + /** + * Sub-classes **MUST** call this. Until [[_start]] has been called, no calls + * will be passed to [[_send]] from [[send]]. If it is overridden, then + * ``super._start()`` **MUST** be called. + * + * Calling it multiple times is safe and has no effect. + */ + _start(): void; + /** + * Resolves once the [[_start]] has been called. This can be used in + * sub-classes to defer sending data until the connection has been + * established. + */ + _waitUntilReady(): Promise; + /** + * Return a Subscriber that will manage the %%sub%%. + * + * Sub-classes may override this to modify the behavior of + * subscription management. + */ + _getSubscriber(sub: Subscription): Subscriber; + /** + * Returns true only if the [[_start]] has been called. + */ + get ready(): boolean; + /** + * Returns %%tx%% as a normalized JSON-RPC transaction request, + * which has all values hexlified and any numeric values converted + * to Quantity values. + */ + getRpcTransaction(tx: TransactionRequest): JsonRpcTransactionRequest; + /** + * Returns the request method and arguments required to perform + * %%req%%. + */ + getRpcRequest(req: PerformActionRequest): null | { + method: string; + args: Array; + }; + /** + * Returns an quais-style Error for the given JSON-RPC error + * %%payload%%, coalescing the various strings and error shapes + * that different nodes return, coercing them into a machine-readable + * standardized error. + */ + getRpcError(payload: JsonRpcPayload, _error: JsonRpcError): Error; + /** + * Requests the %%method%% with %%params%% via the JSON-RPC protocol + * over the underlying channel. This can be used to call methods + * on the backend that do not have a high-level API within the Provider + * API. + * + * This method queues requests according to the batch constraints + * in the options, assigns the request a unique ID. + * + * **Do NOT override** this method in sub-classes; instead + * override [[_send]] or force the options values in the + * call to the constructor to modify this method's behavior. + */ + send(method: string, params: Array | Record, shard?: string): Promise; + /** + * Resolves to the [[Signer]] account for %%address%% managed by + * the client. + * + * If the %%address%% is a number, it is used as an index in the + * the accounts from [[listAccounts]]. + * + * This can only be used on clients which manage accounts (such as + * Geth with imported account or MetaMask). + * + * Throws if the account doesn't exist. + */ + getSigner(address?: number | string): Promise; + listAccounts(): Promise>; + destroy(): void; +} +/** + * The JsonRpcProvider is one of the most common Providers, + * which performs all operations over HTTP (or HTTPS) requests. + * + * Events are processed by polling the backend for the current block + * number; when it advances, all block-base events are then checked + * for updates. + */ +export declare class JsonRpcProvider extends JsonRpcApiProvider { + constructor(urls?: string | string[] | FetchRequest, network?: Networkish, options?: JsonRpcApiProviderOptions); + _getSubscriber(sub: Subscription): Subscriber; + _getConnection(shard?: string): FetchRequest; + send(method: string, params: Array | Record, shard?: string): Promise; + _send(payload: JsonRpcPayload | Array, shard?: string): Promise>; +} +//# sourceMappingURL=provider-jsonrpc.d.ts.map \ No newline at end of file diff --git a/lib.commonjs/providers/provider-jsonrpc.d.ts.map b/lib.commonjs/providers/provider-jsonrpc.d.ts.map new file mode 100644 index 00000000..2af20c84 --- /dev/null +++ b/lib.commonjs/providers/provider-jsonrpc.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-jsonrpc.d.ts","sourceRoot":"","sources":["../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AAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC;IAsB5F;;;;;;;;;;;OAWG;IAIG,SAAS,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC;IA4B5D,YAAY,IAAI,OAAO,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;IAKnD,OAAO,IAAI,IAAI;CAmBlB;AAED;;;;;;;GAOG;AACH,qBAAa,eAAgB,SAAQ,kBAAkB;gBAEvC,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,YAAY,EAAE,OAAO,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE,yBAAyB;IAa9G,cAAc,CAAC,GAAG,EAAE,YAAY,GAAG,UAAU;IAK7C,cAAc,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,YAAY;IAStC,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC;IAU5F,KAAK,CAAC,OAAO,EAAE,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;CAa9G"} \ No newline at end of file diff --git a/lib.commonjs/providers/provider-jsonrpc.js b/lib.commonjs/providers/provider-jsonrpc.js new file mode 100644 index 00000000..f71a1f19 --- /dev/null +++ b/lib.commonjs/providers/provider-jsonrpc.js @@ -0,0 +1,965 @@ +"use strict"; +/** + * One of the most common ways to interact with the blockchain is + * by a node running a JSON-RPC interface which can be connected to, + * based on the transport, using: + * + * - HTTP or HTTPS - [[JsonRpcProvider]] + * - WebSocket - [[WebSocketProvider]] + * - IPC - [[IpcSocketProvider]] + * + * @_section: api/providers/jsonrpc:JSON-RPC Provider [about-jsonrpcProvider] + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JsonRpcProvider = exports.JsonRpcApiProvider = exports.JsonRpcSigner = void 0; +// @TODO: +// - Add the batching API +// https://playground.open-rpc.org/?schemaUrl=https://raw.githubusercontent.com/ethereum/eth1.0-apis/assembled-spec/openrpc.json&uiSchema%5BappBar%5D%5Bui:splitView%5D=true&uiSchema%5BappBar%5D%5Bui:input%5D=false&uiSchema%5BappBar%5D%5Bui:examplesDropdown%5D=false +const index_js_1 = require("../abi/index.js"); +const index_js_2 = require("../address/index.js"); +const index_js_3 = require("../hash/index.js"); +const index_js_4 = require("../transaction/index.js"); +const index_js_5 = require("../utils/index.js"); +const abstract_provider_js_1 = require("./abstract-provider.js"); +const abstract_signer_js_1 = require("./abstract-signer.js"); +const network_js_1 = require("./network.js"); +const subscriber_filterid_js_1 = require("./subscriber-filterid.js"); +const Primitive = "bigint,boolean,function,number,string,symbol".split(/,/g); +//const Methods = "getAddress,then".split(/,/g); +function deepCopy(value) { + if (value == null || Primitive.indexOf(typeof (value)) >= 0) { + return value; + } + // Keep any Addressable + if (typeof (value.getAddress) === "function") { + return value; + } + if (Array.isArray(value)) { + return (value.map(deepCopy)); + } + if (typeof (value) === "object") { + return Object.keys(value).reduce((accum, key) => { + accum[key] = value[key]; + return accum; + }, {}); + } + throw new Error(`should not happen: ${value} (${typeof (value)})`); +} +function stall(duration) { + return new Promise((resolve) => { setTimeout(resolve, duration); }); +} +function getLowerCase(value) { + if (value) { + return value.toLowerCase(); + } + return value; +} +const defaultOptions = { + staticNetwork: null, + batchStallTime: 10, + batchMaxSize: (1 << 20), + batchMaxCount: 100, + cacheTimeout: 250 +}; +// @TODO: Unchecked Signers +class JsonRpcSigner extends abstract_signer_js_1.AbstractSigner { + address; + constructor(provider, address) { + super(provider); + address = (0, index_js_2.getAddress)(address); + (0, index_js_5.defineProperties)(this, { address }); + } + connect(provider) { + (0, index_js_5.assert)(false, "cannot reconnect JsonRpcSigner", "UNSUPPORTED_OPERATION", { + operation: "signer.connect" + }); + } + async getAddress() { + return this.address; + } + // JSON-RPC will automatially fill in nonce, etc. so we just check from + async populateTransaction(tx) { + return await this.populateCall(tx); + } + // Returns just the hash of the transaction after sent, which is what + // the bare JSON-RPC API does; + async sendUncheckedTransaction(_tx) { + const tx = deepCopy(_tx); + const promises = []; + // Make sure the from matches the sender + if (tx.from) { + const _from = tx.from; + promises.push((async () => { + const from = await (0, index_js_2.resolveAddress)(_from, this.provider); + (0, index_js_5.assertArgument)(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx); + tx.from = from; + })()); + } + else { + tx.from = this.address; + } + // The JSON-RPC for quai_sendTransaction uses 90000 gas; if the user + // wishes to use this, it is easy to specify explicitly, otherwise + // we look it up for them. + if (tx.gasLimit == null) { + promises.push((async () => { + tx.gasLimit = await this.provider.estimateGas({ ...tx, from: this.address }); + })()); + } + // The address may be an ENS name or Addressable + if (tx.to != null) { + const _to = tx.to; + promises.push((async () => { + tx.to = await (0, index_js_2.resolveAddress)(_to, this.provider); + })()); + } + // Wait until all of our properties are filled in + if (promises.length) { + await Promise.all(promises); + } + const hexTx = this.provider.getRpcTransaction(tx); + return this.provider.send("quai_sendTransaction", [hexTx]); + } + async sendTransaction(tx) { + // This cannot be mined any earlier than any recent block + const shard = await this.shardFromAddress(tx.from); + const blockNumber = await this.provider.getBlockNumber(shard); + // Send the transaction + const hash = await this.sendUncheckedTransaction(tx); + // Unfortunately, JSON-RPC only provides and opaque transaction hash + // for a response, and we need the actual transaction, so we poll + // for it; it should show up very quickly + return await (new Promise((resolve, reject) => { + const timeouts = [1000, 100]; + let invalids = 0; + const checkTx = async () => { + try { + // Try getting the transaction + const tx = await this.provider.getTransaction(hash); + if (tx != null) { + resolve(tx.replaceableTransaction(blockNumber)); + return; + } + } + catch (error) { + // If we were cancelled: stop polling. + // If the data is bad: the node returns bad transactions + // If the network changed: calling again will also fail + // If unsupported: likely destroyed + if ((0, index_js_5.isError)(error, "CANCELLED") || (0, index_js_5.isError)(error, "BAD_DATA") || + (0, index_js_5.isError)(error, "NETWORK_ERROR" || (0, index_js_5.isError)(error, "UNSUPPORTED_OPERATION"))) { + if (error.info == null) { + error.info = {}; + } + error.info.sendTransactionHash = hash; + reject(error); + return; + } + // Stop-gap for misbehaving backends; see #4513 + if ((0, index_js_5.isError)(error, "INVALID_ARGUMENT")) { + invalids++; + if (error.info == null) { + error.info = {}; + } + error.info.sendTransactionHash = hash; + if (invalids > 10) { + reject(error); + return; + } + } + // Notify anyone that cares; but we will try again, since + // it is likely an intermittent service error + this.provider.emit("error", (0, index_js_5.makeError)("failed to fetch transation after sending (will try again)", "UNKNOWN_ERROR", { error })); + } + // Wait another 4 seconds + this.provider._setTimeout(() => { checkTx(); }, timeouts.pop() || 4000); + }; + checkTx(); + })); + } + async signTransaction(_tx) { + const tx = deepCopy(_tx); + // Make sure the from matches the sender + if (tx.from) { + const from = await (0, index_js_2.resolveAddress)(tx.from, this.provider); + (0, index_js_5.assertArgument)(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx); + tx.from = from; + } + else { + tx.from = this.address; + } + const hexTx = this.provider.getRpcTransaction(tx); + return await this.provider.send("quai_signTransaction", [hexTx]); + } + async signMessage(_message) { + const message = ((typeof (_message) === "string") ? (0, index_js_5.toUtf8Bytes)(_message) : _message); + return await this.provider.send("personal_sign", [ + (0, index_js_5.hexlify)(message), this.address.toLowerCase() + ]); + } + async signTypedData(domain, types, _value) { + const value = deepCopy(_value); + // Populate any ENS names (in-place) + const populated = await index_js_3.TypedDataEncoder.resolveNames(domain, types, value, async (value) => { + const address = await (0, index_js_2.resolveAddress)(value); + (0, index_js_5.assertArgument)(address != null, "TypedData does not support null address", "value", value); + return address; + }); + return await this.provider.send("quai_signTypedData_v4", [ + this.address.toLowerCase(), + JSON.stringify(index_js_3.TypedDataEncoder.getPayload(populated.domain, types, populated.value)) + ]); + } + async unlock(password) { + return this.provider.send("personal_unlockAccount", [ + this.address.toLowerCase(), password, null + ]); + } + // https://github.com/ethereum/wiki/wiki/JSON-RPC#quai_sign + async _legacySignMessage(_message) { + const message = ((typeof (_message) === "string") ? (0, index_js_5.toUtf8Bytes)(_message) : _message); + return await this.provider.send("quai_sign", [ + this.address.toLowerCase(), (0, index_js_5.hexlify)(message) + ]); + } +} +exports.JsonRpcSigner = JsonRpcSigner; +/** + * The JsonRpcApiProvider is an abstract class and **MUST** be + * sub-classed. + * + * It provides the base for all JSON-RPC-based Provider interaction. + * + * Sub-classing Notes: + * - a sub-class MUST override _send + * - a sub-class MUST call the `_start()` method once connected + */ +class JsonRpcApiProvider extends abstract_provider_js_1.AbstractProvider { + #options; + // The next ID to use for the JSON-RPC ID field + #nextId; + // Payloads are queued and triggered in batches using the drainTimer + #payloads; + #drainTimer; + #notReady; + #network; + #pendingDetectNetwork; + initPromise; + #scheduleDrain() { + if (this.#drainTimer) { + return; + } + // If we aren't using batching, no harm in sending it immediately + const stallTime = (this._getOption("batchMaxCount") === 1) ? 0 : this._getOption("batchStallTime"); + this.#drainTimer = setTimeout(() => { + this.#drainTimer = null; + const payloads = this.#payloads; + this.#payloads = []; + while (payloads.length) { + // Create payload batches that satisfy our batch constraints + const batch = [(payloads.shift())]; + while (payloads.length) { + if (batch.length === this.#options.batchMaxCount) { + break; + } + batch.push((payloads.shift())); + const bytes = JSON.stringify(batch.map((p) => p.payload)); + if (bytes.length > this.#options.batchMaxSize) { + payloads.unshift((batch.pop())); + break; + } + } + // Process the result to each payload + (async () => { + const payloadMap = new Map(); + for (let i = 0; i < batch.length; i++) { + if (!payloadMap.has(batch[i].shard)) { + if (batch[i].payload != null) { + payloadMap.set(batch[i].shard, [batch[i].payload]); + } + ; + } + else { + payloadMap.get(batch[i].shard)?.push(batch[i].payload); + } + } + let rawResult = []; + await Promise.all(Array.from(payloadMap).map(async ([key, value]) => { + const payload = value.length === 1 ? value[0] : value; + const shard = key; + this.emit("debug", { action: "sendRpcPayload", payload }); + rawResult.push(await this._send(payload, shard)); + this.emit("debug", { action: "receiveRpcResult", payload }); + })); + const result = rawResult.flat(); + try { + // Process results in batch order + for (const { resolve, reject, payload } of batch) { + if (this.destroyed) { + reject((0, index_js_5.makeError)("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: payload.method })); + continue; + } + // Find the matching result + const resp = result.filter((r) => (r.id === payload.id))[0]; + // No result; the node failed us in unexpected ways + if (resp == null) { + const error = (0, index_js_5.makeError)("missing response for request", "BAD_DATA", { + value: result, info: { payload } + }); + this.emit("error", error); + reject(error); + continue; + } + // The response is an error + if ("error" in resp) { + reject(this.getRpcError(payload, resp)); + continue; + } + // All good; send the result + resolve(resp.result); + } + } + catch (error) { + this.emit("debug", { action: "receiveRpcError", error }); + for (const { reject } of batch) { + // @TODO: augment the error with the payload + reject(error); + } + } + })(); + } + }, stallTime); + } + constructor(network, options) { + super(network, options); + this.#nextId = 1; + this.#options = Object.assign({}, defaultOptions, options || {}); + this.#payloads = []; + this.#drainTimer = null; + this.#network = null; + this.#pendingDetectNetwork = null; + { + let resolve = null; + const promise = new Promise((_resolve) => { + resolve = _resolve; + }); + this.#notReady = { promise, resolve }; + } + const staticNetwork = this._getOption("staticNetwork"); + if (typeof (staticNetwork) === "boolean") { + (0, index_js_5.assertArgument)(!staticNetwork || network !== "any", "staticNetwork cannot be used on special network 'any'", "options", options); + if (staticNetwork && network != null) { + this.#network = network_js_1.Network.from(network); + } + } + else if (staticNetwork) { + // Make sure any static network is compatbile with the provided netwrok + (0, index_js_5.assertArgument)(network == null || staticNetwork.matches(network), "staticNetwork MUST match network object", "options", options); + this.#network = staticNetwork; + } + } + /** + * Returns the value associated with the option %%key%%. + * + * Sub-classes can use this to inquire about configuration options. + */ + _getOption(key) { + return this.#options[key]; + } + /** + * Gets the [[Network]] this provider has committed to. On each call, the network + * is detected, and if it has changed, the call will reject. + */ + get _network() { + (0, index_js_5.assert)(this.#network, "network is not available yet", "NETWORK_ERROR"); + return this.#network; + } + /** + * Resolves to the non-normalized value by performing %%req%%. + * + * Sub-classes may override this to modify behavior of actions, + * and should generally call ``super._perform`` as a fallback. + */ + async _perform(req) { + // Legacy networks do not like the type field being passed along (which + // is fair), so we delete type if it is 0 and a non-EIP-1559 network + await this.initPromise; + if (req.method === "call" || req.method === "estimateGas") { + let tx = req.transaction; + if (tx && tx.type != null && (0, index_js_5.getBigInt)(tx.type)) { + // If there are no EIP-1559 properties, it might be non-EIP-a559 + if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) { + const feeData = await this.getFeeData(req.shard); + if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) { + // Network doesn't know about EIP-1559 (and hence type) + req = Object.assign({}, req, { + transaction: Object.assign({}, tx, { type: undefined }) + }); + } + } + } + } + const request = this.getRpcRequest(req); + if (request != null) { + return await this.send(request.method, request.args, req.shard); + } + return super._perform(req); + } + /** + * Sub-classes may override this; it detects the *actual* network that + * we are **currently** connected to. + * + * Keep in mind that [[send]] may only be used once [[ready]], otherwise the + * _send primitive must be used instead. + */ + async _detectNetwork() { + const network = this._getOption("staticNetwork"); + if (network) { + if (network === true) { + if (this.#network) { + return this.#network; + } + } + else { + return network; + } + } + if (this.#pendingDetectNetwork) { + return await this.#pendingDetectNetwork; + } + // If we are ready, use ``send``, which enabled requests to be batched + if (this.ready) { + this.#pendingDetectNetwork = (async () => { + try { + const result = network_js_1.Network.from((0, index_js_5.getBigInt)(await this.send("quai_chainId", []))); + this.#pendingDetectNetwork = null; + return result; + } + catch (error) { + this.#pendingDetectNetwork = null; + throw error; + } + })(); + return await this.#pendingDetectNetwork; + } + // We are not ready yet; use the primitive _send + this.#pendingDetectNetwork = (async () => { + const payload = { + id: this.#nextId++, method: "quai_chainId", params: [], jsonrpc: "2.0" + }; + this.emit("debug", { action: "sendRpcPayload", payload }); + let result; + try { + result = (await this._send(payload))[0]; + this.#pendingDetectNetwork = null; + } + catch (error) { + this.#pendingDetectNetwork = null; + this.emit("debug", { action: "receiveRpcError", error }); + throw error; + } + this.emit("debug", { action: "receiveRpcResult", result }); + if ("result" in result) { + return network_js_1.Network.from((0, index_js_5.getBigInt)(result.result)); + } + throw this.getRpcError(payload, result); + })(); + return await this.#pendingDetectNetwork; + } + /** + * Sub-classes **MUST** call this. Until [[_start]] has been called, no calls + * will be passed to [[_send]] from [[send]]. If it is overridden, then + * ``super._start()`` **MUST** be called. + * + * Calling it multiple times is safe and has no effect. + */ + _start() { + if (this.#notReady == null || this.#notReady.resolve == null) { + return; + } + this.#notReady.resolve(); + this.#notReady = null; + (async () => { + // Bootstrap the network + while (this.#network == null && !this.destroyed) { + try { + this.#network = await this._detectNetwork(); + } + catch (error) { + if (this.destroyed) { + break; + } + console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"); + this.emit("error", (0, index_js_5.makeError)("failed to bootstrap network detection", "NETWORK_ERROR", { event: "initial-network-discovery", info: { error } })); + await stall(1000); + } + } + // Start dispatching requests + this.#scheduleDrain(); + })(); + } + /** + * Resolves once the [[_start]] has been called. This can be used in + * sub-classes to defer sending data until the connection has been + * established. + */ + async _waitUntilReady() { + if (this.#notReady == null) { + return; + } + return await this.#notReady.promise; + } + /** + * Return a Subscriber that will manage the %%sub%%. + * + * Sub-classes may override this to modify the behavior of + * subscription management. + */ + _getSubscriber(sub) { + // Pending Filters aren't availble via polling + if (sub.type === "pending") { + return new subscriber_filterid_js_1.FilterIdPendingSubscriber(this); + } + if (sub.type === "event") { + return new subscriber_filterid_js_1.FilterIdEventSubscriber(this, sub.filter); + } + // Orphaned Logs are handled automatically, by the filter, since + // logs with removed are emitted by it + if (sub.type === "orphan" && sub.filter.orphan === "drop-log") { + return new abstract_provider_js_1.UnmanagedSubscriber("orphan"); + } + return super._getSubscriber(sub); + } + /** + * Returns true only if the [[_start]] has been called. + */ + get ready() { return this.#notReady == null; } + /** + * Returns %%tx%% as a normalized JSON-RPC transaction request, + * which has all values hexlified and any numeric values converted + * to Quantity values. + */ + getRpcTransaction(tx) { + const result = {}; + // JSON-RPC now requires numeric values to be "quantity" values + ["chainId", "gasLimit", "gasPrice", "type", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "value"].forEach((key) => { + if (tx[key] == null) { + return; + } + let dstKey = key; + if (key === "gasLimit") { + dstKey = "gas"; + } + result[dstKey] = (0, index_js_5.toQuantity)((0, index_js_5.getBigInt)(tx[key], `tx.${key}`)); + }); + // Make sure addresses and data are lowercase + ["from", "to", "data"].forEach((key) => { + if (tx[key] == null) { + return; + } + result[key] = (0, index_js_5.hexlify)(tx[key]); + }); + // Normalize the access list object + if (tx.accessList) { + result["accessList"] = (0, index_js_4.accessListify)(tx.accessList); + } + return result; + } + /** + * Returns the request method and arguments required to perform + * %%req%%. + */ + getRpcRequest(req) { + switch (req.method) { + case "chainId": + return { method: "quai_chainId", args: [] }; + case "getBlockNumber": + return { method: "quai_blockNumber", args: [] }; + case "getGasPrice": + return { + method: "quai_baseFee", + args: [req.txType] + }; + case "getMaxPriorityFeePerGas": + return { method: "quai_maxPriorityFeePerGas", args: [] }; + case "getBalance": + return { + method: "quai_getBalance", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getTransactionCount": + return { + method: "quai_getTransactionCount", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getCode": + return { + method: "quai_getCode", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getStorage": + return { + method: "quai_getStorageAt", + args: [ + getLowerCase(req.address), + ("0x" + req.position.toString(16)), + req.blockTag + ] + }; + case "broadcastTransaction": + return { + method: "quai_sendRawTransaction", + args: [req.signedTransaction] + }; + case "getBlock": + if ("blockTag" in req) { + return { + method: "quai_getBlockByNumber", + args: [req.blockTag, !!req.includeTransactions] + }; + } + else if ("blockHash" in req) { + return { + method: "quai_getBlockByHash", + args: [req.blockHash, !!req.includeTransactions] + }; + } + break; + case "getTransaction": + return { + method: "quai_getTransactionByHash", + args: [req.hash] + }; + case "getTransactionReceipt": + return { + method: "quai_getTransactionReceipt", + args: [req.hash] + }; + case "call": + return { + method: "quai_call", + args: [this.getRpcTransaction(req.transaction), req.blockTag] + }; + case "estimateGas": { + return { + method: "quai_estimateGas", + args: [this.getRpcTransaction(req.transaction)] + }; + } + case "getRunningLocations": { + return { + method: "quai_listRunningChains", + args: [] + }; + } + case "getProtocolTrieExpansionCount": { + return { + method: "quai_getProtocolExpansionNumber", + args: [] + }; + } + case "getQiRateAtBlock": { + return { + method: "quai_qiRateAtBlock", + args: [req.blockTag, req.amt] + }; + } + case "getQuaiRateAtBlock": { + return { + method: "quai_quaiRateAtBlock", + args: [req.blockTag, req.amt] + }; + } + case "getLogs": + if (req.filter && req.filter.address != null) { + if (Array.isArray(req.filter.address)) { + req.filter.address = req.filter.address.map(getLowerCase); + } + else { + req.filter.address = getLowerCase(req.filter.address); + } + } + return { method: "quai_getLogs", args: [req.filter] }; + } + return null; + } + /** + * Returns an quais-style Error for the given JSON-RPC error + * %%payload%%, coalescing the various strings and error shapes + * that different nodes return, coercing them into a machine-readable + * standardized error. + */ + getRpcError(payload, _error) { + const { method } = payload; + const { error } = _error; + if (method === "quai_estimateGas" && error.message) { + const msg = error.message; + if (!msg.match(/revert/i) && msg.match(/insufficient funds/i)) { + return (0, index_js_5.makeError)("insufficient funds", "INSUFFICIENT_FUNDS", { + transaction: (payload.params[0]), + info: { payload, error } + }); + } + } + if (method === "quai_call" || method === "quai_estimateGas") { + const result = spelunkData(error); + const e = index_js_1.AbiCoder.getBuiltinCallException((method === "quai_call") ? "call" : "estimateGas", (payload.params[0]), (result ? result.data : null)); + e.info = { error, payload }; + return e; + } + // Only estimateGas and call can return arbitrary contract-defined text, so now we + // we can process text safely. + const message = JSON.stringify(spelunkMessage(error)); + if (typeof (error.message) === "string" && error.message.match(/user denied|quais-user-denied/i)) { + const actionMap = { + quai_sign: "signMessage", + personal_sign: "signMessage", + quai_signTypedData_v4: "signTypedData", + quai_signTransaction: "signTransaction", + quai_sendTransaction: "sendTransaction", + quai_requestAccounts: "requestAccess", + wallet_requestAccounts: "requestAccess", + }; + return (0, index_js_5.makeError)(`user rejected action`, "ACTION_REJECTED", { + action: (actionMap[method] || "unknown"), + reason: "rejected", + info: { payload, error } + }); + } + if (method === "quai_sendRawTransaction" || method === "quai_sendTransaction") { + const transaction = (payload.params[0]); + if (message.match(/insufficient funds|base fee exceeds gas limit/i)) { + return (0, index_js_5.makeError)("insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", { + transaction, info: { error } + }); + } + if (message.match(/nonce/i) && message.match(/too low/i)) { + return (0, index_js_5.makeError)("nonce has already been used", "NONCE_EXPIRED", { transaction, info: { error } }); + } + // "replacement transaction underpriced" + if (message.match(/replacement transaction/i) && message.match(/underpriced/i)) { + return (0, index_js_5.makeError)("replacement fee too low", "REPLACEMENT_UNDERPRICED", { transaction, info: { error } }); + } + if (message.match(/only replay-protected/i)) { + return (0, index_js_5.makeError)("legacy pre-eip-155 transactions not supported", "UNSUPPORTED_OPERATION", { + operation: method, info: { transaction, info: { error } } + }); + } + } + let unsupported = !!message.match(/the method .* does not exist/i); + if (!unsupported) { + if (error && error.details && error.details.startsWith("Unauthorized method:")) { + unsupported = true; + } + } + if (unsupported) { + return (0, index_js_5.makeError)("unsupported operation", "UNSUPPORTED_OPERATION", { + operation: payload.method, info: { error, payload } + }); + } + return (0, index_js_5.makeError)("could not coalesce error", "UNKNOWN_ERROR", { error, payload }); + } + /** + * Requests the %%method%% with %%params%% via the JSON-RPC protocol + * over the underlying channel. This can be used to call methods + * on the backend that do not have a high-level API within the Provider + * API. + * + * This method queues requests according to the batch constraints + * in the options, assigns the request a unique ID. + * + * **Do NOT override** this method in sub-classes; instead + * override [[_send]] or force the options values in the + * call to the constructor to modify this method's behavior. + */ + send(method, params, shard) { + // @TODO: cache chainId?? purge on switch_networks + // We have been destroyed; no operations are supported anymore + if (this.destroyed) { + return Promise.reject((0, index_js_5.makeError)("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: method })); + } + const id = this.#nextId++; + const promise = new Promise((resolve, reject) => { + this.#payloads.push({ + resolve, reject, + payload: { method, params, id, jsonrpc: "2.0" }, + shard: shard + }); + }); + // If there is not a pending drainTimer, set one + this.#scheduleDrain(); + return promise; + } + /** + * Resolves to the [[Signer]] account for %%address%% managed by + * the client. + * + * If the %%address%% is a number, it is used as an index in the + * the accounts from [[listAccounts]]. + * + * This can only be used on clients which manage accounts (such as + * Geth with imported account or MetaMask). + * + * Throws if the account doesn't exist. + */ + // Works only if using a local node or browser wallet for this, otherwise cannot get accounts + async getSigner(address) { + if (address == null) { + address = 0; + } + const accountsPromise = this.send("quai_accounts", []); + // Account index + if (typeof (address) === "number") { + const accounts = (await accountsPromise); + if (address >= accounts.length) { + throw new Error("no such account"); + } + return new JsonRpcSigner(this, accounts[address]); + } + const { accounts } = await (0, index_js_5.resolveProperties)({ + network: this.getNetwork(), + accounts: accountsPromise + }); + // Account address + address = (0, index_js_2.getAddress)(address); + for (const account of accounts) { + if ((0, index_js_2.getAddress)(account) === address) { + return new JsonRpcSigner(this, address); + } + } + throw new Error("invalid account"); + } + async listAccounts() { + const accounts = await this.send("quai_accounts", []); + return accounts.map((a) => new JsonRpcSigner(this, a)); + } + destroy() { + // Stop processing requests + if (this.#drainTimer) { + clearTimeout(this.#drainTimer); + this.#drainTimer = null; + } + // Cancel all pending requests + for (const { payload, reject } of this.#payloads) { + reject((0, index_js_5.makeError)("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: payload.method })); + } + this.#payloads = []; + // Parent clean-up + super.destroy(); + } +} +exports.JsonRpcApiProvider = JsonRpcApiProvider; +/** + * The JsonRpcProvider is one of the most common Providers, + * which performs all operations over HTTP (or HTTPS) requests. + * + * Events are processed by polling the backend for the current block + * number; when it advances, all block-base events are then checked + * for updates. + */ +class JsonRpcProvider extends JsonRpcApiProvider { + constructor(urls, network, options) { + if (urls == null) { + urls = ["http:/\/localhost:8545"]; + } + super(network, options); + if (Array.isArray(urls)) { + this.initPromise = this.initUrlMap(urls); + } + else if (typeof urls === "string") { + this.initPromise = this.initUrlMap([urls]); + } + else { + this.initPromise = this.initUrlMap(urls.clone()); + } + } + _getSubscriber(sub) { + const subscriber = super._getSubscriber(sub); + return subscriber; + } + _getConnection(shard) { + const connection = this.connect[this.connect.length - 1].clone(); + if (typeof shard === "string") { + const shardBytes = this.shardBytes(shard); + connection.url = this._urlMap.get(shardBytes) ?? connection.url; + } + return connection; + } + async send(method, params, shard) { + // All requests are over HTTP, so we can just start handling requests + // We do this here rather than the constructor so that we don't send any + // requests to the network (i.e. quai_chainId) until we absolutely have to. + // await this.initPromise; + await this._start(); + return await super.send(method, params, shard); + } + async _send(payload, shard) { + // Configure a POST connection for the requested method + const request = this._getConnection(shard); + request.body = JSON.stringify(payload); + request.setHeader("content-type", "application/json"); + const response = await request.send(); + response.assertOk(); + let resp = response.bodyJson; + if (!Array.isArray(resp)) { + resp = [resp]; + } + return resp; + } +} +exports.JsonRpcProvider = JsonRpcProvider; +function spelunkData(value) { + if (value == null) { + return null; + } + // These *are* the droids we're looking for. + if (typeof (value.message) === "string" && value.message.match(/revert/i) && (0, index_js_5.isHexString)(value.data)) { + return { message: value.message, data: value.data }; + } + // Spelunk further... + if (typeof (value) === "object") { + for (const key in value) { + const result = spelunkData(value[key]); + if (result) { + return result; + } + } + return null; + } + // Might be a JSON string we can further descend... + if (typeof (value) === "string") { + try { + return spelunkData(JSON.parse(value)); + } + catch (error) { } + } + return null; +} +function _spelunkMessage(value, result) { + if (value == null) { + return; + } + // These *are* the droids we're looking for. + if (typeof (value.message) === "string") { + result.push(value.message); + } + // Spelunk further... + if (typeof (value) === "object") { + for (const key in value) { + _spelunkMessage(value[key], result); + } + } + // Might be a JSON string we can further descend... + if (typeof (value) === "string") { + try { + return _spelunkMessage(JSON.parse(value), result); + } + catch (error) { } + } +} +function spelunkMessage(value) { + const result = []; + _spelunkMessage(value, result); + return result; +} +//# sourceMappingURL=provider-jsonrpc.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/provider-jsonrpc.js.map b/lib.commonjs/providers/provider-jsonrpc.js.map new file mode 100644 index 00000000..51cf8bc2 --- /dev/null +++ b/lib.commonjs/providers/provider-jsonrpc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-jsonrpc.js","sourceRoot":"","sources":["../../src.ts/providers/provider-jsonrpc.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;AAEH,SAAS;AACT,yBAAyB;AAEzB,yQAAyQ;AAEzQ,8CAA2C;AAC3C,kDAAiE;AACjE,+CAAoD;AACpD,sDAAwD;AACxD,gDAI2B;AAE3B,iEAA+E;AAC/E,6DAAsD;AACtD,6CAAuC;AACvC,qEAA8F;AAa9F,MAAM,SAAS,GAAG,8CAA8C,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAC7E,gDAAgD;AAChD,SAAS,QAAQ,CAAU,KAAQ;IAC/B,IAAI,KAAK,IAAI,IAAI,IAAI,SAAS,CAAC,OAAO,CAAC,OAAM,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,EAAE;QACxD,OAAO,KAAK,CAAC;KAChB;IAED,uBAAuB;IACvB,IAAI,OAAM,CAAO,KAAM,CAAC,UAAU,CAAC,KAAK,UAAU,EAAE;QAChD,OAAO,KAAK,CAAC;KAChB;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;QAAE,OAAY,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC;KAAE;IAEhE,IAAI,OAAM,CAAC,KAAK,CAAC,KAAK,QAAQ,EAAE;QAC5B,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;YAC5C,KAAK,CAAC,GAAG,CAAC,GA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KAAK,EAAE,GAAG;KACtB;AACL,CAAC;AAED,SAAS,cAAc,CAAC,KAAU;IAC9B,MAAM,MAAM,GAAkB,EAAG,CAAC;IAClC,eAAe,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC/B,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/providers/provider.d.ts b/lib.commonjs/providers/provider.d.ts new file mode 100644 index 00000000..fc553c0e --- /dev/null +++ b/lib.commonjs/providers/provider.d.ts @@ -0,0 +1,1122 @@ +import type { AddressLike, NameResolver } from "../address/index.js"; +import type { BigNumberish, EventEmitterable } from "../utils/index.js"; +import type { Signature } from "../crypto/index.js"; +import type { AccessList, AccessListish, TransactionLike } from "../transaction/index.js"; +import type { ContractRunner } from "./contracts.js"; +import type { Network } from "./network.js"; +/** + * A **BlockTag** specifies a specific block. + * + * **numeric value** - specifies the block height, where + * the genesis block is block 0; many operations accept a negative + * value which indicates the block number should be deducted from + * the most recent block. A numeric value may be a ``number``, ``bigint``, + * or a decimal of hex string. + * + * **blockhash** - specifies a specific block by its blockhash; this allows + * potentially orphaned blocks to be specifed, without ambiguity, but many + * backends do not support this for some operations. + */ +export type BlockTag = BigNumberish | string; +import { BlockParams, LogParams, TransactionReceiptParams, TransactionResponseParams } from "./formatting.js"; +/** + * A **FeeData** wraps all the fee-related values associated with + * the network. + */ +export declare class FeeData { + /** + * The gas price for legacy networks. + */ + readonly gasPrice: null | bigint; + /** + * The maximum fee to pay per gas. + * + * The base fee per gas is defined by the network and based on + * congestion, increasing the cost during times of heavy load + * and lowering when less busy. + * + * The actual fee per gas will be the base fee for the block + * and the priority fee, up to the max fee per gas. + * + * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559)) + */ + readonly maxFeePerGas: null | bigint; + /** + * The additional amout to pay per gas to encourage a validator + * to include the transaction. + * + * The purpose of this is to compensate the validator for the + * adjusted risk for including a given transaction. + * + * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559)) + */ + readonly maxPriorityFeePerGas: null | bigint; + /** + * Creates a new FeeData for %%gasPrice%%, %%maxFeePerGas%% and + * %%maxPriorityFeePerGas%%. + */ + constructor(gasPrice?: null | bigint, maxFeePerGas?: null | bigint, maxPriorityFeePerGas?: null | bigint); + /** + * Returns a JSON-friendly value. + */ + toJSON(): any; +} +/** + * A **TransactionRequest** is a transactions with potentially various + * properties not defined, or with less strict types for its values. + * + * This is used to pass to various operations, which will internally + * coerce any types and populate any necessary values. + */ +export interface TransactionRequest { + /** + * The transaction type. + */ + type?: null | number; + /** + * The target of the transaction. + */ + to?: null | AddressLike; + /** + * The sender of the transaction. + */ + from: AddressLike; + /** + * The nonce of the transaction, used to prevent replay attacks. + */ + nonce?: null | number; + /** + * The maximum amount of gas to allow this transaction to consime. + */ + gasLimit?: null | BigNumberish; + /** + * The gas price to use for legacy transactions or transactions on + * legacy networks. + * + * Most of the time the ``max*FeePerGas`` is preferred. + */ + gasPrice?: null | BigNumberish; + /** + * The [[link-eip-1559]] maximum priority fee to pay per gas. + */ + maxPriorityFeePerGas?: null | BigNumberish; + /** + * The [[link-eip-1559]] maximum total fee to pay per gas. The actual + * value used is protocol enforced to be the block's base fee. + */ + maxFeePerGas?: null | BigNumberish; + /** + * The transaction data. + */ + data?: null | string; + /** + * The transaction value (in wei). + */ + value?: null | BigNumberish; + /** + * The chain ID for the network this transaction is valid on. + */ + chainId?: null | BigNumberish; + /** + * The [[link-eip-2930]] access list. Storage slots included in the access + * list are //warmed// by pre-loading them, so their initial cost to + * fetch is guaranteed, but then each additional access is cheaper. + */ + accessList?: null | AccessListish; + /** + * A custom object, which can be passed along for network-specific + * values. + */ + customData?: any; + /** + * When using ``call`` or ``estimateGas``, this allows a specific + * block to be queried. Many backends do not support this and when + * unsupported errors are silently squelched and ``"latest"`` is used. + */ + blockTag?: BlockTag; + /** + * When using ``call``, this enables CCIP-read, which permits the + * provider to be redirected to web-based content during execution, + * which is then further validated by the contract. + * + * There are potential security implications allowing CCIP-read, as + * it could be used to expose the IP address or user activity during + * the fetch to unexpected parties. + */ + enableCcipRead?: boolean; + /** +* The external gas price. +*/ + externalGasPrice?: null | BigNumberish; + /** + * The external gas tip. + */ + externalGasTip?: null | BigNumberish; + /** + * The external gas limit. + */ + externalGasLimit?: null | BigNumberish; + /** + * The external data. + */ + externalData?: null | string; + /** + * The access list for berlin and london transactions. + */ + externalAccessList?: null | AccessListish; +} +/** + * A **PreparedTransactionRequest** is identical to a [[TransactionRequest]] + * except all the property types are strictly enforced. + */ +export interface PreparedTransactionRequest { + /** + * The transaction type. + */ + type?: number; + /** + * The target of the transaction. + */ + to?: AddressLike; + /** + * The sender of the transaction. + */ + from: AddressLike; + /** + * The nonce of the transaction, used to prevent replay attacks. + */ + nonce?: number; + /** + * The maximum amount of gas to allow this transaction to consime. + */ + gasLimit?: bigint; + /** + * The gas price to use for legacy transactions or transactions on + * legacy networks. + * + * Most of the time the ``max*FeePerGas`` is preferred. + */ + gasPrice?: bigint; + /** + * The [[link-eip-1559]] maximum priority fee to pay per gas. + */ + maxPriorityFeePerGas?: bigint; + /** + * The [[link-eip-1559]] maximum total fee to pay per gas. The actual + * value used is protocol enforced to be the block's base fee. + */ + maxFeePerGas?: bigint; + /** + * The transaction data. + */ + data?: string; + /** + * The transaction value (in wei). + */ + value?: bigint; + /** + * The chain ID for the network this transaction is valid on. + */ + chainId?: bigint; + /** + * The [[link-eip-2930]] access list. Storage slots included in the access + * list are //warmed// by pre-loading them, so their initial cost to + * fetch is guaranteed, but then each additional access is cheaper. + */ + accessList?: AccessList; + /** + * A custom object, which can be passed along for network-specific + * values. + */ + customData?: any; + /** + * When using ``call`` or ``estimateGas``, this allows a specific + * block to be queried. Many backends do not support this and when + * unsupported errors are silently squelched and ``"latest"`` is used. + */ + blockTag?: BlockTag; + /** + * When using ``call``, this enables CCIP-read, which permits the + * provider to be redirected to web-based content during execution, + * which is then further validated by the contract. + * + * There are potential security implications allowing CCIP-read, as + * it could be used to expose the IP address or user activity during + * the fetch to unexpected parties. + */ + enableCcipRead?: boolean; +} +/** + * Returns a copy of %%req%% with all properties coerced to their strict + * types. + */ +export declare function copyRequest(req: TransactionRequest): PreparedTransactionRequest; +/** + * An Interface to indicate a [[Block]] has been included in the + * blockchain. This asserts a Type Guard that necessary properties + * are non-null. + * + * Before a block is included, it is a //pending// block. + */ +export interface MinedBlock extends Block { + /** + * The block number also known as the block height. + */ + readonly number: number; + /** + * The block hash. + */ + readonly hash: string; + /** + * The block timestamp, in seconds from epoch. + */ + readonly timestamp: number; + /** + * The block date, created from the [[timestamp]]. + */ + readonly date: Date; + /** + * The miner of the block, also known as the ``author`` or + * block ``producer``. + */ + readonly miner: string; +} +/** + * A **Block** represents the data associated with a full block on + * Ethereum. + */ +export declare class Block implements BlockParams, Iterable { + #private; + /** + * The provider connected to the block used to fetch additional details + * if necessary. + */ + readonly provider: Provider; + /** + * The block number, sometimes called the block height. This is a + * sequential number that is one higher than the parent block. + */ + readonly number: Array | number; + /** + * The block hash. + * + * This hash includes all properties, so can be safely used to identify + * an exact set of block properties. + */ + readonly hash: null | string; + /** + * The timestamp for this block, which is the number of seconds since + * epoch that this block was included. + */ + readonly timestamp: number; + /** + * The block hash of the parent block. + */ + readonly parentHash: Array | string; + /** + * The nonce. + * + * On legacy networks, this is the random number inserted which + * permitted the difficulty target to be reached. + */ + readonly nonce: string; + /** + * The difficulty target. + * + * On legacy networks, this is the proof-of-work target required + * for a block to meet the protocol rules to be included. + * + * On modern networks, this is a random number arrived at using + * randao. @TODO: Find links? + */ + readonly difficulty: bigint; + /** + * The total gas limit for this block. + */ + readonly gasLimit: bigint; + /** + * The total gas used in this block. + */ + readonly gasUsed: bigint; + /** + * The miner coinbase address, wihch receives any subsidies for + * including this block. + */ + readonly miner: string; + /** + * Any extra data the validator wished to include. + */ + readonly extraData: string; + /** + * The base fee per gas that all transactions in this block were + * charged. + * + * This adjusts after each block, depending on how congested the network + * is. + */ + readonly baseFeePerGas: null | bigint; + readonly manifestHash: Array; + readonly location: bigint; + readonly parentDeltaS: Array; + readonly parentEntropy: Array; + readonly order: number; + readonly subManifest: Array | null; + readonly totalEntropy: bigint; + readonly mixHash: string; + readonly receiptsRoot: string; + readonly sha3Uncles: string; + readonly size: bigint; + readonly evmRoot: string; + readonly utxoRoot: string; + readonly uncles: Array | null; + readonly transactionsRoot: string; + readonly extRollupRoot: string; + readonly extTransactionsRoot: string; + /** + * Create a new **Block** object. + * + * This should generally not be necessary as the unless implementing a + * low-level library. + */ + constructor(block: BlockParams, provider: Provider); + /** + * Returns the list of transaction hashes, in the order + * they were executed within the block. + */ + get transactions(): ReadonlyArray; + get extTransactions(): ReadonlyArray; + /** + * Returns the complete transactions, in the order they + * were executed within the block. + * + * This is only available for blocks which prefetched + * transactions, by passing ``true`` to %%prefetchTxs%% + * into [[Provider-getBlock]]. + */ + get prefetchedTransactions(): Array; + get prefetchedExtTransactions(): Array; + /** + * Returns a JSON-friendly value. + */ + toJSON(): any; + [Symbol.iterator](): Iterator; + /** + * The number of transactions in this block. + */ + get length(): number; + /** + * The [[link-js-date]] this block was included at. + */ + get date(): null | Date; + /** + * Get the transaction at %%indexe%% within this block. + */ + getTransaction(indexOrHash: number | string): Promise; + getExtTransaction(indexOrHash: number | string): Promise; + /** + * If a **Block** was fetched with a request to include the transactions + * this will allow synchronous access to those transactions. + * + * If the transactions were not prefetched, this will throw. + */ + getPrefetchedTransaction(indexOrHash: number | string): TransactionResponse; + /** + * Returns true if this block been mined. This provides a type guard + * for all properties on a [[MinedBlock]]. + */ + isMined(): this is MinedBlock; + /** + * @_ignore: + */ + orphanedEvent(): OrphanFilter; +} +/** + * A **Log** in Ethereum represents an event that has been included in a + * transaction using the ``LOG*`` opcodes, which are most commonly used by + * Solidity's emit for announcing events. + */ +export declare class Log implements LogParams { + /** + * The provider connected to the log used to fetch additional details + * if necessary. + */ + readonly provider: Provider; + /** + * The transaction hash of the transaction this log occurred in. Use the + * [[Log-getTransaction]] to get the [[TransactionResponse]]. + */ + readonly transactionHash: string; + /** + * The block hash of the block this log occurred in. Use the + * [[Log-getBlock]] to get the [[Block]]. + */ + readonly blockHash: string; + /** + * The block number of the block this log occurred in. It is preferred + * to use the [[Block-hash]] when fetching the related [[Block]], + * since in the case of an orphaned block, the block at that height may + * have changed. + */ + readonly blockNumber: number; + /** + * If the **Log** represents a block that was removed due to an orphaned + * block, this will be true. + * + * This can only happen within an orphan event listener. + */ + readonly removed: boolean; + /** + * The address of the contract that emitted this log. + */ + readonly address: string; + /** + * The data included in this log when it was emitted. + */ + readonly data: string; + /** + * The indexed topics included in this log when it was emitted. + * + * All topics are included in the bloom filters, so they can be + * efficiently filtered using the [[Provider-getLogs]] method. + */ + readonly topics: ReadonlyArray; + /** + * The index within the block this log occurred at. This is generally + * not useful to developers, but can be used with the various roots + * to proof inclusion within a block. + */ + readonly index: number; + /** + * The index within the transaction of this log. + */ + readonly transactionIndex: number; + /** + * @_ignore: + */ + constructor(log: LogParams, provider: Provider); + /** + * Returns a JSON-compatible object. + */ + toJSON(): any; + /** + * Returns the block that this log occurred in. + */ + getBlock(shard: string): Promise; + /** + * Returns the transaction that this log occurred in. + */ + getTransaction(): Promise; + /** + * Returns the transaction receipt fot the transaction that this + * log occurred in. + */ + getTransactionReceipt(): Promise; + /** + * @_ignore: + */ + removedEvent(): OrphanFilter; +} +export declare function shardFromHash(hash: string): string; +/** + * A **TransactionReceipt** includes additional information about a + * transaction that is only available after it has been mined. + */ +export declare class TransactionReceipt implements TransactionReceiptParams, Iterable { + #private; + /** + * The provider connected to the log used to fetch additional details + * if necessary. + */ + readonly provider: Provider; + /** + * The address the transaction was sent to. + */ + readonly to: null | string; + /** + * The sender of the transaction. + */ + readonly from: string; + /** + * The address of the contract if the transaction was directly + * responsible for deploying one. + * + * This is non-null **only** if the ``to`` is empty and the ``data`` + * was successfully executed as initcode. + */ + readonly contractAddress: null | string; + /** + * The transaction hash. + */ + readonly hash: string; + /** + * The index of this transaction within the block transactions. + */ + readonly index: number; + /** + * The block hash of the [[Block]] this transaction was included in. + */ + readonly blockHash: string; + /** + * The block number of the [[Block]] this transaction was included in. + */ + readonly blockNumber: number; + /** + * The bloom filter bytes that represent all logs that occurred within + * this transaction. This is generally not useful for most developers, + * but can be used to validate the included logs. + */ + readonly logsBloom: string; + /** + * The actual amount of gas used by this transaction. + * + * When creating a transaction, the amount of gas that will be used can + * only be approximated, but the sender must pay the gas fee for the + * entire gas limit. After the transaction, the difference is refunded. + */ + readonly gasUsed: bigint; + /** + * The amount of gas used by all transactions within the block for this + * and all transactions with a lower ``index``. + * + * This is generally not useful for developers but can be used to + * validate certain aspects of execution. + */ + readonly cumulativeGasUsed: bigint; + /** + * The actual gas price used during execution. + * + * Due to the complexity of [[link-eip-1559]] this value can only + * be caluclated after the transaction has been mined, snce the base + * fee is protocol-enforced. + */ + readonly gasPrice: bigint; + /** + * The [[link-eip-2718]] transaction type. + */ + readonly type: number; + /** + * The status of this transaction, indicating success (i.e. ``1``) or + * a revert (i.e. ``0``). + * + * This is available in post-byzantium blocks, but some backends may + * backfill this value. + */ + readonly status: null | number; + readonly etxs: ReadonlyArray; + /** + * @_ignore: + */ + constructor(tx: TransactionReceiptParams, provider: Provider); + /** + * The logs for this transaction. + */ + get logs(): ReadonlyArray; + /** + * Returns a JSON-compatible representation. + */ + toJSON(): any; + /** + * @_ignore: + */ + get length(): number; + [Symbol.iterator](): Iterator; + /** + * The total fee for this transaction, in wei. + */ + get fee(): bigint; + /** + * Resolves to the block this transaction occurred in. + */ + getBlock(shard: string): Promise; + /** + * Resolves to the transaction this transaction occurred in. + */ + getTransaction(): Promise; + /** + * Resolves to the return value of the execution of this transaction. + * + * Support for this feature is limited, as it requires an archive node + * with the ``debug_`` or ``trace_`` API enabled. + */ + getResult(): Promise; + /** + * Resolves to the number of confirmations this transaction has. + */ + confirmations(): Promise; + /** + * @_ignore: + */ + removedEvent(): OrphanFilter; + /** + * @_ignore: + */ + reorderedEvent(other?: TransactionResponse): OrphanFilter; +} +/** + * A **MinedTransactionResponse** is an interface representing a + * transaction which has been mined and allows for a type guard for its + * property values being defined. + */ +export interface MinedTransactionResponse extends TransactionResponse { + /** + * The block number this transaction occurred in. + */ + blockNumber: number; + /** + * The block hash this transaction occurred in. + */ + blockHash: string; + /** + * The date this transaction occurred on. + */ + date: Date; +} +/** + * A **TransactionResponse** includes all properties about a transaction + * that was sent to the network, which may or may not be included in a + * block. + * + * The [[TransactionResponse-isMined]] can be used to check if the + * transaction has been mined as well as type guard that the otherwise + * possibly ``null`` properties are defined. + */ +export declare class TransactionResponse implements TransactionLike, TransactionResponseParams { + #private; + /** + * The provider this is connected to, which will influence how its + * methods will resolve its async inspection methods. + */ + readonly provider: Provider; + /** + * The block number of the block that this transaction was included in. + * + * This is ``null`` for pending transactions. + */ + readonly blockNumber: null | number; + /** + * The blockHash of the block that this transaction was included in. + * + * This is ``null`` for pending transactions. + */ + readonly blockHash: null | string; + /** + * The index within the block that this transaction resides at. + */ + readonly index: bigint; + /** + * The transaction hash. + */ + readonly hash: string; + /** + * The [[link-eip-2718]] transaction envelope type. This is + * ``0`` for legacy transactions types. + */ + readonly type: number; + /** + * The receiver of this transaction. + * + * If ``null``, then the transaction is an initcode transaction. + * This means the result of executing the [[data]] will be deployed + * as a new contract on chain (assuming it does not revert) and the + * address may be computed using [[getCreateAddress]]. + */ + readonly to: null | string; + /** + * The sender of this transaction. It is implicitly computed + * from the transaction pre-image hash (as the digest) and the + * [[signature]] using ecrecover. + */ + readonly from: string; + /** + * The nonce, which is used to prevent replay attacks and offer + * a method to ensure transactions from a given sender are explicitly + * ordered. + * + * When sending a transaction, this must be equal to the number of + * transactions ever sent by [[from]]. + */ + readonly nonce: number; + /** + * The maximum units of gas this transaction can consume. If execution + * exceeds this, the entries transaction is reverted and the sender + * is charged for the full amount, despite not state changes being made. + */ + readonly gasLimit: bigint; + /** + * The maximum priority fee (per unit of gas) to allow a + * validator to charge the sender. This is inclusive of the + * [[maxFeeFeePerGas]]. + */ + readonly maxPriorityFeePerGas: null | bigint; + /** + * The maximum fee (per unit of gas) to allow this transaction + * to charge the sender. + */ + readonly maxFeePerGas: null | bigint; + /** + * The data. + */ + readonly data: string; + /** + * The value, in wei. Use [[formatEther]] to format this value + * as ether. + */ + readonly value: bigint; + /** + * The chain ID. + */ + readonly chainId: bigint; + /** + * The signature. + */ + readonly signature: Signature; + /** + * The [[link-eip-2930]] access list for transaction types that + * support it, otherwise ``null``. + */ + readonly accessList: null | AccessList; + readonly etxGasLimit?: bigint; + readonly etxGasPrice?: bigint; + readonly etxGasTip?: bigint; + readonly etxData?: string; + readonly etxAccessList?: AccessList; + /** + * @_ignore: + */ + constructor(tx: TransactionResponseParams, provider: Provider); + /** + * Returns a JSON-compatible representation of this transaction. + */ + toJSON(): any; + /** + * Resolves to the Block that this transaction was included in. + * + * This will return null if the transaction has not been included yet. + */ + getBlock(shard: string): Promise; + /** + * Resolves to this transaction being re-requested from the + * provider. This can be used if you have an unmined transaction + * and wish to get an up-to-date populated instance. + */ + getTransaction(): Promise; + /** + * Resolve to the number of confirmations this transaction has. + */ + confirmations(): Promise; + /** + * Resolves once this transaction has been mined and has + * %%confirms%% blocks including it (default: ``1``) with an + * optional %%timeout%%. + * + * This can resolve to ``null`` only if %%confirms%% is ``0`` + * and the transaction has not been mined, otherwise this will + * wait until enough confirmations have completed. + */ + wait(_confirms?: number, _timeout?: number): Promise; + /** + * Returns ``true`` if this transaction has been included. + * + * This is effective only as of the time the TransactionResponse + * was instantiated. To get up-to-date information, use + * [[getTransaction]]. + * + * This provides a Type Guard that this transaction will have + * non-null property values for properties that are null for + * unmined transactions. + */ + isMined(): this is MinedTransactionResponse; + /** + * Returns a filter which can be used to listen for orphan events + * that evict this transaction. + */ + removedEvent(): OrphanFilter; + /** + * Returns a filter which can be used to listen for orphan events + * that re-order this event against %%other%%. + */ + reorderedEvent(other?: TransactionResponse): OrphanFilter; + /** + * Returns a new TransactionResponse instance which has the ability to + * detect (and throw an error) if the transaction is replaced, which + * will begin scanning at %%startBlock%%. + * + * This should generally not be used by developers and is intended + * primarily for internal use. Setting an incorrect %%startBlock%% can + * have devastating performance consequences if used incorrectly. + */ + replaceableTransaction(startBlock: number): TransactionResponse; +} +/** + * An Orphan Filter allows detecting when an orphan block has + * resulted in dropping a block or transaction or has resulted + * in transactions changing order. + * + * Not currently fully supported. + */ +export type OrphanFilter = { + orphan: "drop-block"; + hash: string; + number: number; +} | { + orphan: "drop-transaction"; + tx: { + hash: string; + blockHash: string; + blockNumber: number; + }; + other?: { + hash: string; + blockHash: string; + blockNumber: number; + }; +} | { + orphan: "reorder-transaction"; + tx: { + hash: string; + blockHash: string; + blockNumber: number; + }; + other?: { + hash: string; + blockHash: string; + blockNumber: number; + }; +} | { + orphan: "drop-log"; + log: { + transactionHash: string; + blockHash: string; + blockNumber: number; + address: string; + data: string; + topics: ReadonlyArray; + index: number; + }; +}; +/** + * A **TopicFilter** provides a struture to define bloom-filter + * queries. + * + * Each field that is ``null`` matches **any** value, a field that is + * a ``string`` must match exactly that value and and ``array`` is + * effectively an ``OR``-ed set, where any one of those values must + * match. + */ +export type TopicFilter = Array>; +/** + * An **EventFilter** allows efficiently filtering logs (also known as + * events) using bloom filters included within blocks. + */ +export interface EventFilter { + address?: AddressLike | Array; + topics?: TopicFilter; +} +/** + * A **Filter** allows searching a specific range of blocks for mathcing + * logs. + */ +export interface Filter extends EventFilter { + /** + * The start block for the filter (inclusive). + */ + fromBlock?: BlockTag; + /** + * The end block for the filter (inclusive). + */ + toBlock?: BlockTag; + shard: string; +} +/** + * A **FilterByBlockHash** allows searching a specific block for mathcing + * logs. + */ +export interface FilterByBlockHash extends EventFilter { + /** + * The blockhash of the specific block for the filter. + */ + blockHash?: string; + shard: string; +} +/** + * A **ProviderEvent** provides the types of events that can be subscribed + * to on a [[Provider]]. + * + * Each provider may include additional possible events it supports, but + * the most commonly supported are: + * + * **``"block"``** - calls the listener with the current block number on each + * new block. + * + * **``"error"``** - calls the listener on each async error that occurs during + * the event loop, with the error. + * + * **``"debug"``** - calls the listener on debug events, which can be used to + * troubleshoot network errors, provider problems, etc. + * + * **``transaction hash``** - calls the listener on each block after the + * transaction has been mined; generally ``.once`` is more appropriate for + * this event. + * + * **``Array``** - calls the listener on each log that matches the filter. + * + * [[EventFilter]] - calls the listener with each matching log + */ +export type ProviderEvent = string | Array> | EventFilter | OrphanFilter; +/** + * A **Provider** is the primary method to interact with the read-only + * content on Ethereum. + * + * It allows access to details about accounts, blocks and transactions + * and the ability to query event logs and simulate contract execution. + * + * Account data includes the [balance](getBalance), + * [transaction count](getTransactionCount), [code](getCode) and + * [state trie storage](getStorage). + * + * Simulating execution can be used to [call](call), + * [estimate gas](estimateGas) and + * [get transaction results](getTransactionResult). + * + * The [[broadcastTransaction]] is the only method which allows updating + * the blockchain, but it is usually accessed by a [[Signer]], since a + * private key must be used to sign the transaction before it can be + * broadcast. + */ +export interface Provider extends ContractRunner, EventEmitterable, NameResolver { + /** + * The provider iteself. + * + * This is part of the necessary API for executing a contract, as + * it provides a common property on any [[ContractRunner]] that + * can be used to access the read-only portion of the runner. + */ + provider: this; + /** + * Shutdown any resources this provider is using. No additional + * calls should be made to this provider after calling this. + */ + destroy(): void; + /** + * Get the current block number. + */ + getBlockNumber(shard: string): Promise; + /** + * Get the connected [[Network]]. + */ + getNetwork(shard?: string): Promise; + /** + * Get the best guess at the recommended [[FeeData]]. + */ + getFeeData(shard: string): Promise; + /** + * Get the account balance (in wei) of %%address%%. If %%blockTag%% + * is specified and the node supports archive access for that + * %%blockTag%%, the balance is as of that [[BlockTag]]. + * + * @note On nodes without archive access enabled, the %%blockTag%% may be + * **silently ignored** by the node, which may cause issues if relied on. + */ + getBalance(address: AddressLike, blockTag?: BlockTag): Promise; + /** + * Get the number of transactions ever sent for %%address%%, which + * is used as the ``nonce`` when sending a transaction. If + * %%blockTag%% is specified and the node supports archive access + * for that %%blockTag%%, the transaction count is as of that + * [[BlockTag]]. + * + * @note On nodes without archive access enabled, the %%blockTag%% may be + * **silently ignored** by the node, which may cause issues if relied on. + */ + getTransactionCount(address: AddressLike, blockTag?: BlockTag): Promise; + /** + * Get the bytecode for %%address%%. + * + * @note On nodes without archive access enabled, the %%blockTag%% may be + * **silently ignored** by the node, which may cause issues if relied on. + */ + getCode(address: AddressLike, blockTag?: BlockTag): Promise; + /** + * Get the storage slot value for %%address%% at slot %%position%%. + * + * @note On nodes without archive access enabled, the %%blockTag%% may be + * **silently ignored** by the node, which may cause issues if relied on. + */ + getStorage(address: AddressLike, position: BigNumberish, blockTag?: BlockTag): Promise; + /** + * Estimates the amount of gas required to executre %%tx%%. + */ + estimateGas(tx: TransactionRequest): Promise; + /** + * Simulate the execution of %%tx%%. If the call reverts, it will + * throw a [[CallExceptionError]] which includes the revert data. + */ + call(tx: TransactionRequest): Promise; + /** + * Broadcasts the %%signedTx%% to the network, adding it to the + * memory pool of any node for which the transaction meets the + * rebroadcast requirements. + */ + broadcastTransaction(shard: string, signedTx: string): Promise; + /** + * Resolves to the block for %%blockHashOrBlockTag%%. + * + * If %%prefetchTxs%%, and the backend supports including transactions + * with block requests, all transactions will be included and the + * [[Block]] object will not need to make remote calls for getting + * transactions. + */ + getBlock(shard: string, blockHashOrBlockTag: BlockTag | string, prefetchTxs?: boolean): Promise; + /** + * Resolves to the transaction for %%hash%%. + * + * If the transaction is unknown or on pruning nodes which + * discard old transactions this resolves to ``null``. + */ + getTransaction(hash: string): Promise; + /** + * Resolves to the transaction receipt for %%hash%%, if mined. + * + * If the transaction has not been mined, is unknown or on + * pruning nodes which discard old transactions this resolves to + * ``null``. + */ + getTransactionReceipt(hash: string): Promise; + /** + * Resolves to the result returned by the executions of %%hash%%. + * + * This is only supported on nodes with archive access and with + * the necessary debug APIs enabled. + */ + getTransactionResult(hash: string): Promise; + /** + * Resolves to the list of Logs that match %%filter%% + */ + getLogs(filter: Filter | FilterByBlockHash): Promise>; + /** + * Resolves to the address configured for the %%ensName%% or + * ``null`` if unconfigured. + */ + resolveName(ensName: string): Promise; + /** + * Resolves to the ENS name associated for the %%address%% or + * ``null`` if the //primary name// is not configured. + * + * Users must perform additional steps to configure a //primary name//, + * which is not currently common. + */ + lookupAddress(address: string): Promise; + /** + * Waits until the transaction %%hash%% is mined and has %%confirms%% + * confirmations. + */ + waitForTransaction(hash: string, confirms?: number, timeout?: number): Promise; + /** + * Resolves to the block at %%blockTag%% once it has been mined. + * + * This can be useful for waiting some number of blocks by using + * the ``currentBlockNumber + N``. + */ + waitForBlock(shard: string, blockTag?: BlockTag): Promise; +} +//# sourceMappingURL=provider.d.ts.map \ No newline at end of file diff --git a/lib.commonjs/providers/provider.d.ts.map b/lib.commonjs/providers/provider.d.ts.map new file mode 100644 index 00000000..2c32d120 --- /dev/null +++ b/lib.commonjs/providers/provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src.ts/providers/provider.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACxE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAE1F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAK5C;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,QAAQ,GAAG,YAAY,GAAG,MAAM,CAAC;AAE7C,OAAO,EACH,WAAW,EAAE,SAAS,EAAE,wBAAwB,EAChD,yBAAyB,EAC5B,MAAM,iBAAiB,CAAC;AAgBzB;;;GAGG;AACH,qBAAa,OAAO;IAChB;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAG,IAAI,GAAG,MAAM,CAAC;I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--- /dev/null +++ b/lib.commonjs/providers/provider.js @@ -0,0 +1,1330 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TransactionResponse = exports.TransactionReceipt = exports.shardFromHash = exports.Log = exports.Block = exports.copyRequest = exports.FeeData = void 0; +//import { resolveAddress } from "@quaisproject/address"; +const index_js_1 = require("../utils/index.js"); +const index_js_2 = require("../transaction/index.js"); +const BN_0 = BigInt(0); +// ----------------------- +function getValue(value) { + if (value == null) { + return null; + } + return value; +} +function toJson(value) { + if (value == null) { + return null; + } + return value.toString(); +} +// @TODO? implements Required +/** + * A **FeeData** wraps all the fee-related values associated with + * the network. + */ +class FeeData { + /** + * The gas price for legacy networks. + */ + gasPrice; + /** + * The maximum fee to pay per gas. + * + * The base fee per gas is defined by the network and based on + * congestion, increasing the cost during times of heavy load + * and lowering when less busy. + * + * The actual fee per gas will be the base fee for the block + * and the priority fee, up to the max fee per gas. + * + * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559)) + */ + maxFeePerGas; + /** + * The additional amout to pay per gas to encourage a validator + * to include the transaction. + * + * The purpose of this is to compensate the validator for the + * adjusted risk for including a given transaction. + * + * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559)) + */ + maxPriorityFeePerGas; + /** + * Creates a new FeeData for %%gasPrice%%, %%maxFeePerGas%% and + * %%maxPriorityFeePerGas%%. + */ + constructor(gasPrice, maxFeePerGas, maxPriorityFeePerGas) { + (0, index_js_1.defineProperties)(this, { + gasPrice: getValue(gasPrice), + maxFeePerGas: getValue(maxFeePerGas), + maxPriorityFeePerGas: getValue(maxPriorityFeePerGas) + }); + } + /** + * Returns a JSON-friendly value. + */ + toJSON() { + const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = this; + return { + _type: "FeeData", + gasPrice: toJson(gasPrice), + maxFeePerGas: toJson(maxFeePerGas), + maxPriorityFeePerGas: toJson(maxPriorityFeePerGas), + }; + } +} +exports.FeeData = FeeData; +; +/** + * Returns a copy of %%req%% with all properties coerced to their strict + * types. + */ +function copyRequest(req) { + const result = {}; + // These could be addresses, ENS names or Addressables + if (req.to) { + result.to = req.to; + } + if (req.from) { + result.from = req.from; + } + if (req.data) { + result.data = (0, index_js_1.hexlify)(req.data); + } + const bigIntKeys = "chainId,gasLimit,gasPrice,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/); + for (const key of bigIntKeys) { + if (!(key in req) || req[key] == null) { + continue; + } + result[key] = (0, index_js_1.getBigInt)(req[key], `request.${key}`); + } + const numberKeys = "type,nonce".split(/,/); + for (const key of numberKeys) { + if (!(key in req) || req[key] == null) { + continue; + } + result[key] = (0, index_js_1.getNumber)(req[key], `request.${key}`); + } + if (req.accessList) { + result.accessList = (0, index_js_2.accessListify)(req.accessList); + } + if ("blockTag" in req) { + result.blockTag = req.blockTag; + } + if ("enableCcipRead" in req) { + result.enableCcipRead = !!req.enableCcipRead; + } + if ("customData" in req) { + result.customData = req.customData; + } + return result; +} +exports.copyRequest = copyRequest; +/** + * A **Block** represents the data associated with a full block on + * Ethereum. + */ +class Block { + /** + * The provider connected to the block used to fetch additional details + * if necessary. + */ + provider; + /** + * The block number, sometimes called the block height. This is a + * sequential number that is one higher than the parent block. + */ + number; + /** + * The block hash. + * + * This hash includes all properties, so can be safely used to identify + * an exact set of block properties. + */ + hash; + /** + * The timestamp for this block, which is the number of seconds since + * epoch that this block was included. + */ + timestamp; + /** + * The block hash of the parent block. + */ + parentHash; + /** + * The nonce. + * + * On legacy networks, this is the random number inserted which + * permitted the difficulty target to be reached. + */ + nonce; + /** + * The difficulty target. + * + * On legacy networks, this is the proof-of-work target required + * for a block to meet the protocol rules to be included. + * + * On modern networks, this is a random number arrived at using + * randao. @TODO: Find links? + */ + difficulty; + /** + * The total gas limit for this block. + */ + gasLimit; + /** + * The total gas used in this block. + */ + gasUsed; + /** + * The miner coinbase address, wihch receives any subsidies for + * including this block. + */ + miner; + /** + * Any extra data the validator wished to include. + */ + extraData; + /** + * The base fee per gas that all transactions in this block were + * charged. + * + * This adjusts after each block, depending on how congested the network + * is. + */ + baseFeePerGas; + manifestHash; + location; + parentDeltaS; + parentEntropy; + order; + subManifest; + totalEntropy; + mixHash; + receiptsRoot; + sha3Uncles; + size; + evmRoot; + utxoRoot; + uncles; + #transactions; + transactionsRoot; + extRollupRoot; + #extTransactions; + extTransactionsRoot; + /** + * Create a new **Block** object. + * + * This should generally not be necessary as the unless implementing a + * low-level library. + */ + constructor(block, provider) { + this.#transactions = block.transactions.map((tx) => { + if (typeof (tx) !== "string") { + return new TransactionResponse(tx, provider); + } + return tx; + }); + this.#extTransactions = block.extTransactions.map((tx) => { + if (typeof (tx) !== "string") { + return new TransactionResponse(tx, provider); + } + return tx; + }); + this.transactionsRoot = block.transactionsRoot; + this.extRollupRoot = block.extRollupRoot; + this.extTransactionsRoot = block.extTransactionsRoot; + (0, index_js_1.defineProperties)(this, { + provider, + hash: getValue(block.hash), + number: block.number, + timestamp: block.timestamp, + parentHash: block.parentHash, + nonce: block.nonce, + difficulty: block.difficulty, + gasLimit: block.gasLimit, + gasUsed: block.gasUsed, + miner: block.miner, + extraData: block.extraData, + baseFeePerGas: getValue(block.baseFeePerGas), + manifestHash: block.manifestHash, + location: block.location, + parentDeltaS: block.parentDeltaS, + parentEntropy: block.parentEntropy, + order: block.order, + subManifest: block.subManifest, + totalEntropy: block.totalEntropy, + mixHash: block.mixHash, + receiptsRoot: block.receiptsRoot, + sha3Uncles: block.sha3Uncles, + size: block.size, + evmRoot: block.evmRoot, + utxoRoot: block.utxoRoot, + uncles: block.uncles, + transactionsRoot: block.transactionsRoot, + extRollupRoot: block.extRollupRoot, + extTransactionsRoot: block.extTransactionsRoot, + }); + } + /** + * Returns the list of transaction hashes, in the order + * they were executed within the block. + */ + get transactions() { + return this.#transactions.map((tx) => { + if (typeof (tx) === "string") { + return tx; + } + return tx.hash; + }); + } + get extTransactions() { + return this.#extTransactions.map((tx) => { + if (typeof (tx) === "string") { + return tx; + } + return tx.hash; + }); + } + /** + * Returns the complete transactions, in the order they + * were executed within the block. + * + * This is only available for blocks which prefetched + * transactions, by passing ``true`` to %%prefetchTxs%% + * into [[Provider-getBlock]]. + */ + get prefetchedTransactions() { + const txs = this.#transactions.slice(); + // Doesn't matter... + if (txs.length === 0) { + return []; + } + // Make sure we prefetched the transactions + (0, index_js_1.assert)(typeof (txs[0]) === "object", "transactions were not prefetched with block request", "UNSUPPORTED_OPERATION", { + operation: "transactionResponses()" + }); + return txs; + } + get prefetchedExtTransactions() { + const txs = this.#extTransactions.slice(); + // Doesn't matter... + if (txs.length === 0) { + return []; + } + // Make sure we prefetched the transactions + (0, index_js_1.assert)(typeof (txs[0]) === "object", "transactions were not prefetched with block request", "UNSUPPORTED_OPERATION", { + operation: "transactionResponses()" + }); + return txs; + } + /** + * Returns a JSON-friendly value. + */ + toJSON() { + const { baseFeePerGas, difficulty, extraData, gasLimit, gasUsed, hash, miner, nonce, number, parentHash, timestamp, manifestHash, location, parentDeltaS, parentEntropy, order, subManifest, totalEntropy, mixHash, receiptsRoot, sha3Uncles, size, evmRoot, utxoRoot, uncles, transactionsRoot, extRollupRoot, extTransactionsRoot } = this; + // Using getters to retrieve the transactions and extTransactions + const transactions = this.transactions; + const extTransactions = this.extTransactions; + return { + _type: "Block", + baseFeePerGas: toJson(baseFeePerGas), + difficulty: toJson(difficulty), + extraData, + gasLimit: toJson(gasLimit), + gasUsed: toJson(gasUsed), + hash, + miner, + nonce, + number, + parentHash, + timestamp, + manifestHash, + location, + parentDeltaS, + parentEntropy, + order, + subManifest, + totalEntropy, + mixHash, + receiptsRoot, + sha3Uncles, + size, + evmRoot, + utxoRoot, + uncles, + transactionsRoot, + extRollupRoot, + extTransactionsRoot, + transactions, + extTransactions // Includes the extended transaction hashes or full transactions based on the prefetched data + }; + } + [Symbol.iterator]() { + let index = 0; + const txs = this.transactions; + return { + next: () => { + if (index < this.length) { + return { + value: txs[index++], done: false + }; + } + return { value: undefined, done: true }; + } + }; + } + /** + * The number of transactions in this block. + */ + get length() { return this.#transactions.length; } + /** + * The [[link-js-date]] this block was included at. + */ + get date() { + if (this.timestamp == null) { + return null; + } + return new Date(this.timestamp * 1000); + } + /** + * Get the transaction at %%indexe%% within this block. + */ + async getTransaction(indexOrHash) { + // Find the internal value by its index or hash + let tx = undefined; + if (typeof (indexOrHash) === "number") { + tx = this.#transactions[indexOrHash]; + } + else { + const hash = indexOrHash.toLowerCase(); + for (const v of this.#transactions) { + if (typeof (v) === "string") { + if (v !== hash) { + continue; + } + tx = v; + break; + } + else { + if (v.hash === hash) { + continue; + } + tx = v; + break; + } + } + } + if (tx == null) { + throw new Error("no such tx"); + } + if (typeof (tx) === "string") { + return (await this.provider.getTransaction(tx)); + } + else { + return tx; + } + } + async getExtTransaction(indexOrHash) { + // Find the internal value by its index or hash + let tx = undefined; + if (typeof (indexOrHash) === "number") { + tx = this.#extTransactions[indexOrHash]; + } + else { + const hash = indexOrHash.toLowerCase(); + for (const v of this.#extTransactions) { + if (typeof (v) === "string") { + if (v !== hash) { + continue; + } + tx = v; + break; + } + else { + if (v.hash === hash) { + continue; + } + tx = v; + break; + } + } + } + if (tx == null) { + throw new Error("no such tx"); + } + if (typeof (tx) === "string") { + return (await this.provider.getTransaction(tx)); + } + else { + return tx; + } + } + /** + * If a **Block** was fetched with a request to include the transactions + * this will allow synchronous access to those transactions. + * + * If the transactions were not prefetched, this will throw. + */ + getPrefetchedTransaction(indexOrHash) { + const txs = this.prefetchedTransactions; + if (typeof (indexOrHash) === "number") { + return txs[indexOrHash]; + } + indexOrHash = indexOrHash.toLowerCase(); + for (const tx of txs) { + if (tx.hash === indexOrHash) { + return tx; + } + } + (0, index_js_1.assertArgument)(false, "no matching transaction", "indexOrHash", indexOrHash); + } + /** + * Returns true if this block been mined. This provides a type guard + * for all properties on a [[MinedBlock]]. + */ + isMined() { return !!this.hash; } + /** + * @_ignore: + */ + orphanedEvent() { + if (!this.isMined()) { + throw new Error(""); + } + return createOrphanedBlockFilter(this); + } +} +exports.Block = Block; +////////////////////// +// Log +/** + * A **Log** in Ethereum represents an event that has been included in a + * transaction using the ``LOG*`` opcodes, which are most commonly used by + * Solidity's emit for announcing events. + */ +class Log { + /** + * The provider connected to the log used to fetch additional details + * if necessary. + */ + provider; + /** + * The transaction hash of the transaction this log occurred in. Use the + * [[Log-getTransaction]] to get the [[TransactionResponse]]. + */ + transactionHash; + /** + * The block hash of the block this log occurred in. Use the + * [[Log-getBlock]] to get the [[Block]]. + */ + blockHash; + /** + * The block number of the block this log occurred in. It is preferred + * to use the [[Block-hash]] when fetching the related [[Block]], + * since in the case of an orphaned block, the block at that height may + * have changed. + */ + blockNumber; + /** + * If the **Log** represents a block that was removed due to an orphaned + * block, this will be true. + * + * This can only happen within an orphan event listener. + */ + removed; + /** + * The address of the contract that emitted this log. + */ + address; + /** + * The data included in this log when it was emitted. + */ + data; + /** + * The indexed topics included in this log when it was emitted. + * + * All topics are included in the bloom filters, so they can be + * efficiently filtered using the [[Provider-getLogs]] method. + */ + topics; + /** + * The index within the block this log occurred at. This is generally + * not useful to developers, but can be used with the various roots + * to proof inclusion within a block. + */ + index; + /** + * The index within the transaction of this log. + */ + transactionIndex; + /** + * @_ignore: + */ + constructor(log, provider) { + this.provider = provider; + const topics = Object.freeze(log.topics.slice()); + (0, index_js_1.defineProperties)(this, { + transactionHash: log.transactionHash, + blockHash: log.blockHash, + blockNumber: log.blockNumber, + removed: log.removed, + address: log.address, + data: log.data, + topics, + index: log.index, + transactionIndex: log.transactionIndex, + }); + } + /** + * Returns a JSON-compatible object. + */ + toJSON() { + const { address, blockHash, blockNumber, data, index, removed, topics, transactionHash, transactionIndex } = this; + return { + _type: "log", + address, blockHash, blockNumber, data, index, + removed, topics, transactionHash, transactionIndex + }; + } + /** + * Returns the block that this log occurred in. + */ + async getBlock(shard) { + const block = await this.provider.getBlock(shard, this.blockHash); + (0, index_js_1.assert)(!!block, "failed to find transaction", "UNKNOWN_ERROR", {}); + return block; + } + /** + * Returns the transaction that this log occurred in. + */ + async getTransaction() { + const tx = await this.provider.getTransaction(this.transactionHash); + (0, index_js_1.assert)(!!tx, "failed to find transaction", "UNKNOWN_ERROR", {}); + return tx; + } + /** + * Returns the transaction receipt fot the transaction that this + * log occurred in. + */ + async getTransactionReceipt() { + const receipt = await this.provider.getTransactionReceipt(this.transactionHash); + (0, index_js_1.assert)(!!receipt, "failed to find transaction receipt", "UNKNOWN_ERROR", {}); + return receipt; + } + /** + * @_ignore: + */ + removedEvent() { + return createRemovedLogFilter(this); + } +} +exports.Log = Log; +////////////////////// +// Transaction Receipt +function shardFromHash(hash) { + return hash.slice(0, 4); +} +exports.shardFromHash = shardFromHash; +/** + * A **TransactionReceipt** includes additional information about a + * transaction that is only available after it has been mined. + */ +class TransactionReceipt { + /** + * The provider connected to the log used to fetch additional details + * if necessary. + */ + provider; + /** + * The address the transaction was sent to. + */ + to; + /** + * The sender of the transaction. + */ + from; + /** + * The address of the contract if the transaction was directly + * responsible for deploying one. + * + * This is non-null **only** if the ``to`` is empty and the ``data`` + * was successfully executed as initcode. + */ + contractAddress; + /** + * The transaction hash. + */ + hash; + /** + * The index of this transaction within the block transactions. + */ + index; + /** + * The block hash of the [[Block]] this transaction was included in. + */ + blockHash; + /** + * The block number of the [[Block]] this transaction was included in. + */ + blockNumber; + /** + * The bloom filter bytes that represent all logs that occurred within + * this transaction. This is generally not useful for most developers, + * but can be used to validate the included logs. + */ + logsBloom; + /** + * The actual amount of gas used by this transaction. + * + * When creating a transaction, the amount of gas that will be used can + * only be approximated, but the sender must pay the gas fee for the + * entire gas limit. After the transaction, the difference is refunded. + */ + gasUsed; + /** + * The amount of gas used by all transactions within the block for this + * and all transactions with a lower ``index``. + * + * This is generally not useful for developers but can be used to + * validate certain aspects of execution. + */ + cumulativeGasUsed; + /** + * The actual gas price used during execution. + * + * Due to the complexity of [[link-eip-1559]] this value can only + * be caluclated after the transaction has been mined, snce the base + * fee is protocol-enforced. + */ + gasPrice; + /** + * The [[link-eip-2718]] transaction type. + */ + type; + //readonly byzantium!: boolean; + /** + * The status of this transaction, indicating success (i.e. ``1``) or + * a revert (i.e. ``0``). + * + * This is available in post-byzantium blocks, but some backends may + * backfill this value. + */ + status; + /** + * The root hash of this transaction. + * + * This is no present and was only included in pre-byzantium blocks, but + * could be used to validate certain parts of the receipt. + */ + #logs; + etxs; + /** + * @_ignore: + */ + constructor(tx, provider) { + this.#logs = Object.freeze(tx.logs.map((log) => { + return new Log(log, provider); + })); + let gasPrice = BN_0; + if (tx.effectiveGasPrice != null) { + gasPrice = tx.effectiveGasPrice; + } + else if (tx.gasPrice != null) { + gasPrice = tx.gasPrice; + } + (0, index_js_1.defineProperties)(this, { + provider, + to: tx.to, + from: tx.from, + contractAddress: tx.contractAddress, + hash: tx.hash, + index: tx.index, + blockHash: tx.blockHash, + blockNumber: tx.blockNumber, + logsBloom: tx.logsBloom, + gasUsed: tx.gasUsed, + cumulativeGasUsed: tx.cumulativeGasUsed, + gasPrice, + etxs: tx.etxs, + type: tx.type, + //byzantium: tx.byzantium, + status: tx.status, + }); + } + /** + * The logs for this transaction. + */ + get logs() { return this.#logs; } + /** + * Returns a JSON-compatible representation. + */ + toJSON() { + const { to, from, contractAddress, hash, index, blockHash, blockNumber, logsBloom, logs, //byzantium, + status } = this; + return { + _type: "TransactionReceipt", + blockHash, blockNumber, + //byzantium, + contractAddress, + cumulativeGasUsed: toJson(this.cumulativeGasUsed), + from, + gasPrice: toJson(this.gasPrice), + gasUsed: toJson(this.gasUsed), + hash, index, logs, logsBloom, status, to + }; + } + /** + * @_ignore: + */ + get length() { return this.logs.length; } + [Symbol.iterator]() { + let index = 0; + return { + next: () => { + if (index < this.length) { + return { value: this.logs[index++], done: false }; + } + return { value: undefined, done: true }; + } + }; + } + /** + * The total fee for this transaction, in wei. + */ + get fee() { + return this.gasUsed * this.gasPrice; + } + /** + * Resolves to the block this transaction occurred in. + */ + async getBlock(shard) { + const block = await this.provider.getBlock(shard, this.blockHash); + if (block == null) { + throw new Error("TODO"); + } + return block; + } + /** + * Resolves to the transaction this transaction occurred in. + */ + async getTransaction() { + const tx = await this.provider.getTransaction(this.hash); + if (tx == null) { + throw new Error("TODO"); + } + return tx; + } + /** + * Resolves to the return value of the execution of this transaction. + * + * Support for this feature is limited, as it requires an archive node + * with the ``debug_`` or ``trace_`` API enabled. + */ + async getResult() { + return (await this.provider.getTransactionResult(this.hash)); + } + /** + * Resolves to the number of confirmations this transaction has. + */ + async confirmations() { + const shard = shardFromHash(this.hash); + return (await this.provider.getBlockNumber(shard)) - this.blockNumber + 1; + } + /** + * @_ignore: + */ + removedEvent() { + return createRemovedTransactionFilter(this); + } + /** + * @_ignore: + */ + reorderedEvent(other) { + (0, index_js_1.assert)(!other || other.isMined(), "unmined 'other' transction cannot be orphaned", "UNSUPPORTED_OPERATION", { operation: "reorderedEvent(other)" }); + return createReorderedTransactionFilter(this, other); + } +} +exports.TransactionReceipt = TransactionReceipt; +/** + * A **TransactionResponse** includes all properties about a transaction + * that was sent to the network, which may or may not be included in a + * block. + * + * The [[TransactionResponse-isMined]] can be used to check if the + * transaction has been mined as well as type guard that the otherwise + * possibly ``null`` properties are defined. + */ +class TransactionResponse { + /** + * The provider this is connected to, which will influence how its + * methods will resolve its async inspection methods. + */ + provider; + /** + * The block number of the block that this transaction was included in. + * + * This is ``null`` for pending transactions. + */ + blockNumber; + /** + * The blockHash of the block that this transaction was included in. + * + * This is ``null`` for pending transactions. + */ + blockHash; + /** + * The index within the block that this transaction resides at. + */ + index; + /** + * The transaction hash. + */ + hash; + /** + * The [[link-eip-2718]] transaction envelope type. This is + * ``0`` for legacy transactions types. + */ + type; + /** + * The receiver of this transaction. + * + * If ``null``, then the transaction is an initcode transaction. + * This means the result of executing the [[data]] will be deployed + * as a new contract on chain (assuming it does not revert) and the + * address may be computed using [[getCreateAddress]]. + */ + to; + /** + * The sender of this transaction. It is implicitly computed + * from the transaction pre-image hash (as the digest) and the + * [[signature]] using ecrecover. + */ + from; + /** + * The nonce, which is used to prevent replay attacks and offer + * a method to ensure transactions from a given sender are explicitly + * ordered. + * + * When sending a transaction, this must be equal to the number of + * transactions ever sent by [[from]]. + */ + nonce; + /** + * The maximum units of gas this transaction can consume. If execution + * exceeds this, the entries transaction is reverted and the sender + * is charged for the full amount, despite not state changes being made. + */ + gasLimit; + /** + * The maximum priority fee (per unit of gas) to allow a + * validator to charge the sender. This is inclusive of the + * [[maxFeeFeePerGas]]. + */ + maxPriorityFeePerGas; + /** + * The maximum fee (per unit of gas) to allow this transaction + * to charge the sender. + */ + maxFeePerGas; + /** + * The data. + */ + data; + /** + * The value, in wei. Use [[formatEther]] to format this value + * as ether. + */ + value; + /** + * The chain ID. + */ + chainId; + /** + * The signature. + */ + signature; + /** + * The [[link-eip-2930]] access list for transaction types that + * support it, otherwise ``null``. + */ + accessList; + // Extrernal transaction specific fields + etxGasLimit; + etxGasPrice; + etxGasTip; + etxData; + etxAccessList; + #startBlock; + /** + * @_ignore: + */ + constructor(tx, provider) { + this.provider = provider; + this.blockNumber = (tx.blockNumber != null) ? tx.blockNumber : null; + this.blockHash = (tx.blockHash != null) ? tx.blockHash : null; + this.hash = tx.hash; + this.index = tx.index; + this.type = tx.type; + this.from = tx.from; + this.to = tx.to || null; + this.gasLimit = tx.gasLimit; + this.nonce = tx.nonce; + this.data = tx.data; + this.value = tx.value; + this.maxPriorityFeePerGas = (tx.maxPriorityFeePerGas != null) ? tx.maxPriorityFeePerGas : null; + this.maxFeePerGas = (tx.maxFeePerGas != null) ? tx.maxFeePerGas : null; + this.chainId = tx.chainId; + this.signature = tx.signature; + this.accessList = (tx.accessList != null) ? tx.accessList : null; + if (tx.type != 2) { + delete tx.etxGasLimit; + delete tx.etxGasPrice; + delete tx.etxGasTip; + delete tx.etxData; + delete tx.etxAccessList; + } + if (tx.etxGasLimit) + this.etxGasLimit = tx.etxGasLimit; + if (tx.etxGasPrice) + this.etxGasPrice = tx.etxGasPrice; + if (tx.etxGasTip) + this.etxGasTip = tx.etxGasTip; + if (tx.etxData) + this.etxData = tx.etxData; + if (tx.etxAccessList) + this.etxAccessList = tx.etxAccessList; + this.#startBlock = -1; + } + /** + * Returns a JSON-compatible representation of this transaction. + */ + toJSON() { + const { blockNumber, blockHash, index, hash, type, to, from, nonce, data, signature, accessList, + //etxGasLimit, etxGasPrice, etxGasTip, etxData, etxAccessList // Include new fields + } = this; + let result = { + _type: "TransactionReceipt", + accessList, blockNumber, blockHash, + chainId: toJson(this.chainId), + data, from, + gasLimit: toJson(this.gasLimit), + hash, + maxFeePerGas: toJson(this.maxFeePerGas), + maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas), + nonce, signature, to, index, type, + value: toJson(this.value), + // Include new fields in the output + // etxGasLimit: etxGasLimit ? toJson(etxGasLimit) : null, + // etxGasPrice: etxGasPrice ? toJson(etxGasPrice) : null, + // etxGasTip: etxGasTip ? toJson(etxGasTip) : null, + // etxData: etxData ? etxData : null, + // etxAccessList: etxAccessList ? etxAccessList : null + }; + return result; + } + /** + * Resolves to the Block that this transaction was included in. + * + * This will return null if the transaction has not been included yet. + */ + async getBlock(shard) { + let blockNumber = this.blockNumber; + if (blockNumber == null) { + const tx = await this.getTransaction(); + if (tx) { + blockNumber = tx.blockNumber; + } + } + if (blockNumber == null) { + return null; + } + const block = this.provider.getBlock(shard, blockNumber); + if (block == null) { + throw new Error("TODO"); + } + return block; + } + /** + * Resolves to this transaction being re-requested from the + * provider. This can be used if you have an unmined transaction + * and wish to get an up-to-date populated instance. + */ + async getTransaction() { + return this.provider.getTransaction(this.hash); + } + /** + * Resolve to the number of confirmations this transaction has. + */ + async confirmations() { + const shard = shardFromHash(this.hash); + if (this.blockNumber == null) { + const { tx, blockNumber } = await (0, index_js_1.resolveProperties)({ + tx: this.getTransaction(), + blockNumber: this.provider.getBlockNumber(shard) + }); + // Not mined yet... + if (tx == null || tx.blockNumber == null) { + return 0; + } + return blockNumber - tx.blockNumber + 1; + } + const blockNumber = await this.provider.getBlockNumber(shard); + return blockNumber - this.blockNumber + 1; + } + /** + * Resolves once this transaction has been mined and has + * %%confirms%% blocks including it (default: ``1``) with an + * optional %%timeout%%. + * + * This can resolve to ``null`` only if %%confirms%% is ``0`` + * and the transaction has not been mined, otherwise this will + * wait until enough confirmations have completed. + */ + async wait(_confirms, _timeout) { + const confirms = (_confirms == null) ? 1 : _confirms; + const timeout = (_timeout == null) ? 0 : _timeout; + let startBlock = this.#startBlock; + let nextScan = -1; + let stopScanning = (startBlock === -1) ? true : false; + const shard = shardFromHash(this.hash); + const checkReplacement = async () => { + // Get the current transaction count for this sender + if (stopScanning) { + return null; + } + const { blockNumber, nonce } = await (0, index_js_1.resolveProperties)({ + blockNumber: this.provider.getBlockNumber(shard), + nonce: this.provider.getTransactionCount(this.from) + }); + // No transaction or our nonce has not been mined yet; but we + // can start scanning later when we do start + if (nonce < this.nonce) { + startBlock = blockNumber; + return; + } + // We were mined; no replacement + if (stopScanning) { + return null; + } + const mined = await this.getTransaction(); + if (mined && mined.blockNumber != null) { + return; + } + // We were replaced; start scanning for that transaction + // Starting to scan; look back a few extra blocks for safety + if (nextScan === -1) { + nextScan = startBlock - 3; + if (nextScan < this.#startBlock) { + nextScan = this.#startBlock; + } + } + while (nextScan <= blockNumber) { + // Get the next block to scan + if (stopScanning) { + return null; + } + const block = await this.provider.getBlock(shard, nextScan, true); + // This should not happen; but we'll try again shortly + if (block == null) { + return; + } + // We were mined; no replacement + for (const hash of block) { + if (hash === this.hash) { + return; + } + } + // Search for the transaction that replaced us + for (let i = 0; i < block.length; i++) { + const tx = await block.getTransaction(i); + if (tx.from === this.from && tx.nonce === this.nonce) { + // Get the receipt + if (stopScanning) { + return null; + } + const receipt = await this.provider.getTransactionReceipt(tx.hash); + // This should not happen; but we'll try again shortly + if (receipt == null) { + return; + } + // We will retry this on the next block (this case could be optimized) + if ((blockNumber - receipt.blockNumber + 1) < confirms) { + return; + } + // The reason we were replaced + let reason = "replaced"; + if (tx.data === this.data && tx.to === this.to && tx.value === this.value) { + reason = "repriced"; + } + else if (tx.data === "0x" && tx.from === tx.to && tx.value === BN_0) { + reason = "cancelled"; + } + (0, index_js_1.assert)(false, "transaction was replaced", "TRANSACTION_REPLACED", { + cancelled: (reason === "replaced" || reason === "cancelled"), + reason, + replacement: tx.replaceableTransaction(startBlock), + hash: tx.hash, + receipt + }); + } + } + nextScan++; + } + return; + }; + const checkReceipt = (receipt) => { + if (receipt == null || receipt.status !== 0) { + return receipt; + } + (0, index_js_1.assert)(false, "transaction execution reverted", "CALL_EXCEPTION", { + action: "sendTransaction", + data: null, reason: null, invocation: null, revert: null, + transaction: { + to: receipt.to, + from: receipt.from, + data: "" // @TODO: in v7, split out sendTransaction properties + }, receipt + }); + }; + const receipt = await this.provider.getTransactionReceipt(this.hash); + if (confirms === 0) { + return checkReceipt(receipt); + } + if (receipt) { + if ((await receipt.confirmations()) >= confirms) { + return checkReceipt(receipt); + } + } + else { + // Check for a replacement; throws if a replacement was found + await checkReplacement(); + // Allow null only when the confirms is 0 + if (confirms === 0) { + return null; + } + } + const waiter = new Promise((resolve, reject) => { + // List of things to cancel when we have a result (one way or the other) + const cancellers = []; + const cancel = () => { cancellers.forEach((c) => c()); }; + // On cancel, stop scanning for replacements + cancellers.push(() => { stopScanning = true; }); + // Set up any timeout requested + if (timeout > 0) { + const timer = setTimeout(() => { + cancel(); + reject((0, index_js_1.makeError)("wait for transaction timeout", "TIMEOUT")); + }, timeout); + cancellers.push(() => { clearTimeout(timer); }); + } + const txListener = async (receipt) => { + // Done; return it! + if ((await receipt.confirmations()) >= confirms) { + cancel(); + try { + resolve(checkReceipt(receipt)); + } + catch (error) { + reject(error); + } + } + }; + cancellers.push(() => { this.provider.off(this.hash, txListener); }); + this.provider.on(this.hash, txListener); + // We support replacement detection; start checking + if (startBlock >= 0) { + const replaceListener = async () => { + try { + // Check for a replacement; this throws only if one is found + await checkReplacement(); + } + catch (error) { + // We were replaced (with enough confirms); re-throw the error + if ((0, index_js_1.isError)(error, "TRANSACTION_REPLACED")) { + cancel(); + reject(error); + return; + } + } + // Rescheudle a check on the next block + if (!stopScanning) { + this.provider.once("block", replaceListener); + } + }; + cancellers.push(() => { this.provider.off("block", replaceListener); }); + this.provider.once("block", replaceListener); + } + }); + return await waiter; + } + /** + * Returns ``true`` if this transaction has been included. + * + * This is effective only as of the time the TransactionResponse + * was instantiated. To get up-to-date information, use + * [[getTransaction]]. + * + * This provides a Type Guard that this transaction will have + * non-null property values for properties that are null for + * unmined transactions. + */ + isMined() { + return (this.blockHash != null); + } + /** + * Returns a filter which can be used to listen for orphan events + * that evict this transaction. + */ + removedEvent() { + (0, index_js_1.assert)(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }); + return createRemovedTransactionFilter(this); + } + /** + * Returns a filter which can be used to listen for orphan events + * that re-order this event against %%other%%. + */ + reorderedEvent(other) { + (0, index_js_1.assert)(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }); + (0, index_js_1.assert)(!other || other.isMined(), "unmined 'other' transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }); + return createReorderedTransactionFilter(this, other); + } + /** + * Returns a new TransactionResponse instance which has the ability to + * detect (and throw an error) if the transaction is replaced, which + * will begin scanning at %%startBlock%%. + * + * This should generally not be used by developers and is intended + * primarily for internal use. Setting an incorrect %%startBlock%% can + * have devastating performance consequences if used incorrectly. + */ + replaceableTransaction(startBlock) { + (0, index_js_1.assertArgument)(Number.isInteger(startBlock) && startBlock >= 0, "invalid startBlock", "startBlock", startBlock); + const tx = new TransactionResponse(this, this.provider); + tx.#startBlock = startBlock; + return tx; + } +} +exports.TransactionResponse = TransactionResponse; +function createOrphanedBlockFilter(block) { + return { orphan: "drop-block", hash: block.hash, number: block.number }; +} +function createReorderedTransactionFilter(tx, other) { + return { orphan: "reorder-transaction", tx, other }; +} +function createRemovedTransactionFilter(tx) { + return { orphan: "drop-transaction", tx }; +} +function createRemovedLogFilter(log) { + return { orphan: "drop-log", log: { + transactionHash: log.transactionHash, + blockHash: log.blockHash, + blockNumber: log.blockNumber, + address: log.address, + data: log.data, + topics: Object.freeze(log.topics.slice()), + index: log.index + } }; +} +//# sourceMappingURL=provider.js.map \ No newline at end of file diff --git a/lib.commonjs/providers/provider.js.map b/lib.commonjs/providers/provider.js.map new file mode 100644 index 00000000..5eeddabb --- /dev/null +++ b/lib.commonjs/providers/provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src.ts/providers/provider.ts"],"names":[],"mappings":";;;AAAA,yDAAyD;AACzD,gDAG2B;AAC3B,sDAAwD;AAWxD,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAsBvB,0BAA0B;AAE1B,SAAS,QAAQ,CAAI,KAA2B;IAC5C,IAAI,KAAK,IAAI,IAAI,EAAE;QAAE,OAAO,IAAI,CAAC;KAAE;IACnC,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,SAAS,MAAM,CAAC,KAAoB;IAChC,IAAI,KAAK,IAAI,IAAI,EAAE;QAAE,OAAO,IAAI,CAAC;KAAE;IACnC,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC;AAC5B,CAAC;AAED,0DAA0D;AAE1D;;;GAGG;AACH,MAAa,OAAO;IAChB;;OAEG;IACM,QAAQ,CAAiB;IAElC;;;;;;;;;;;OAWG;IACM,YAAY,CAAiB;IAEtC;;;;;;;;OAQG;IACM,oBAAoB,CAAiB;IAE9C;;;OAGG;IACH,YAAY,QAAwB,EAAE,YAA4B,EAAE,oBAAoC;QACpG,IAAA,2BAAgB,EAAU,IAAI,EAAE;YAC5B,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC;YAC5B,YAAY,EAAE,QAAQ,CAAC,YAAY,CAAC;YACpC,oBAAoB,EAAE,QAAQ,CAAC,oBAAoB,CAAC;SACvD,CAAC,CAAC;IACP,CAAC;IAED;;OAEG;IACH,MAAM;QACF,MAAM,EACF,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AE,KAAgE;IACpK,OAAO,EAAE,MAAM,EAAE,qBAAqB,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;AACxD,CAAC;AAED,SAAS,8BAA8B,CAAC,EAA4D;IAChG,OAAO,EAAE,MAAM,EAAE,kBAAkB,EAAE,EAAE,EAAE,CAAC;AAC9C,CAAC;AAED,SAAS,sBAAsB,CAAC,GAAqJ;IACjL,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,EAAE;YAC9B,eAAe,EAAE,GAAG,CAAC,eAAe;YACpC,SAAS,EAAE,GAAG,CAAC,SAAS;YACxB,WAAW,EAAE,GAAG,CAAC,WAAW;YAC5B,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,IAAI,EAAE,GAAG,CAAC,IAAI;YACd,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;YACzC,KAAK,EAAE,GAAG,CAAC,KAAK;SACnB,EAAE,CAAC;AACR,CAAC"} \ No newline at end of file diff --git a/lib.commonjs/transaction/transaction.d.ts b/lib.commonjs/transaction/transaction.d.ts new file mode 100644 index 00000000..00742ee8 --- /dev/null +++ b/lib.commonjs/transaction/transaction.d.ts @@ -0,0 +1,276 @@ +import { Signature } from "../crypto/index.js"; +import type { BigNumberish, BytesLike } from "../utils/index.js"; +import type { SignatureLike } from "../crypto/index.js"; +import type { AccessList, AccessListish } from "./index.js"; +export interface TransactionLike { + /** + * The type. + */ + type?: null | number; + /** + * The recipient address or ``null`` for an ``init`` transaction. + */ + to?: null | A; + /** + * The sender. + */ + from: A; + /** + * The nonce. + */ + nonce?: null | number; + /** + * The maximum amount of gas that can be used. + */ + gasLimit?: null | BigNumberish; + /** + * The gas price for legacy and berlin transactions. + */ + gasPrice?: null | BigNumberish; + /** + * The maximum priority fee per gas for london transactions. + */ + maxPriorityFeePerGas?: null | BigNumberish; + /** + * The maximum total fee per gas for london transactions. + */ + maxFeePerGas?: null | BigNumberish; + /** + * The data. + */ + data?: null | string; + /** + * The value (in wei) to send. + */ + value?: null | BigNumberish; + /** + * The chain ID the transaction is valid on. + */ + chainId?: null | BigNumberish; + /** + * The transaction hash. + */ + hash?: null | string; + /** + * The signature provided by the sender. + */ + signature?: null | SignatureLike; + /** + * The access list for berlin and london transactions. + */ + accessList?: null | AccessListish; + /** + * The external gas price. + */ + externalGasPrice?: null | BigNumberish; + /** + * The external gas tip. + */ + externalGasTip?: null | BigNumberish; + /** + * The external gas limit. + */ + externalGasLimit?: null | BigNumberish; + /** + * The external data. + */ + externalData?: null | string; + /** + * The access list for berlin and london transactions. + */ + externalAccessList?: null | AccessListish; +} +/** + * A **Transaction** describes an operation to be executed on + * Ethereum by an Externally Owned Account (EOA). It includes + * who (the [[to]] address), what (the [[data]]) and how much (the + * [[value]] in ether) the operation should entail. + * + * @example: + * tx = new Transaction() + * //_result: + * + * tx.data = "0x1234"; + * //_result: + */ +export declare class Transaction implements TransactionLike { + #private; + from: string; + /** + * The transaction type. + * + * If null, the type will be automatically inferred based on + * explicit properties. + */ + get type(): null | number; + set type(value: null | number | string); + /** + * The name of the transaction type. + */ + get typeName(): null | string; + /** + * The ``to`` address for the transaction or ``null`` if the + * transaction is an ``init`` transaction. + */ + get to(): null | string; + set to(value: null | string); + /** + * The transaction nonce. + */ + get nonce(): number; + set nonce(value: BigNumberish); + /** + * The gas limit. + */ + get gasLimit(): bigint; + set gasLimit(value: BigNumberish); + /** + * The gas price. + * + * On legacy networks this defines the fee that will be paid. On + * EIP-1559 networks, this should be ``null``. + */ + get gasPrice(): null | bigint; + set gasPrice(value: null | BigNumberish); + /** + * The maximum priority fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get maxPriorityFeePerGas(): null | bigint; + set maxPriorityFeePerGas(value: null | BigNumberish); + /** + * The maximum total fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get maxFeePerGas(): null | bigint; + set maxFeePerGas(value: null | BigNumberish); + /** + * The transaction data. For ``init`` transactions this is the + * deployment code. + */ + get data(): string; + set data(value: BytesLike); + /** + * The amount of ether to send in this transactions. + */ + get value(): bigint; + set value(value: BigNumberish); + /** + * The chain ID this transaction is valid on. + */ + get chainId(): bigint; + set chainId(value: BigNumberish); + /** + * If signed, the signature for this transaction. + */ + get signature(): null | Signature; + set signature(value: null | SignatureLike); + /** + * The access list. + * + * An access list permits discounted (but pre-paid) access to + * bytecode and state variable access within contract execution. + */ + get accessList(): null | AccessList; + set accessList(value: null | AccessListish); + /** + * The gas limit. + */ + get externalGasLimit(): bigint; + set externalGasLimit(value: BigNumberish); + /** + * The maximum priority fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get externalGasTip(): null | bigint; + set externalGasTip(value: null | BigNumberish); + /** + * The maximum total fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get externalGasPrice(): null | bigint; + set externalGasPrice(value: null | BigNumberish); + /** + * The transaction externalData. For ``init`` transactions this is the + * deployment code. + */ + get externalData(): string; + set externalData(value: BytesLike); + /** + * The external access list. + * + * An access list permits discounted (but pre-paid) access to + * bytecode and state variable access within contract execution. + */ + get externalAccessList(): null | AccessList; + set externalAccessList(value: null | AccessListish); + /** + * Creates a new Transaction with default values. + */ + constructor(from: string); + /** + * The transaction hash, if signed. Otherwise, ``null``. + */ + get hash(): null | string; + /** + * The pre-image hash of this transaction. + * + * This is the digest that a [[Signer]] must sign to authorize + * this transaction. + */ + get unsignedHash(): string; + /** + * The public key of the sender, if signed. Otherwise, ``null``. + */ + get fromPublicKey(): null | string; + /** + * Returns true if signed. + * + * This provides a Type Guard that properties requiring a signed + * transaction are non-null. + */ + isSigned(): this is (Transaction & { + type: number; + typeName: string; + from: string; + signature: Signature; + }); + /** + * The serialized transaction. + * + * This throws if the transaction is unsigned. For the pre-image, + * use [[unsignedSerialized]]. + */ + get serialized(): string; + /** + * The transaction pre-image. + * + * The hash of this is the digest which needs to be signed to + * authorize this transaction. + */ + get unsignedSerialized(): string; + /** + * Return the most "likely" type; currently the highest + * supported transaction type. + */ + inferType(): number; + /** + * Validates the explicit properties and returns a list of compatible + * transaction types. + */ + inferTypes(): Array; + /** + * Create a copy of this transaciton. + */ + clone(): Transaction; + /** + * Return a JSON-friendly object. + */ + toJSON(): any; + /** + * Create a **Transaction** from a serialized transaction or a + * Transaction-like object. + */ + static from(tx: string | TransactionLike): Transaction; +} +//# sourceMappingURL=transaction.d.ts.map \ No newline at end of file diff --git a/lib.commonjs/transaction/transaction.d.ts.map b/lib.commonjs/transaction/transaction.d.ts.map new file mode 100644 index 00000000..fdd69770 --- /dev/null +++ b/lib.commonjs/transaction/transaction.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transaction.d.ts","sourceRoot":"","sources":["../../src.ts/transaction/transaction.ts"],"names":[],"mappings":"AAEA,OAAO,EAAa,SAAS,EAAc,MAAM,oBAAoB,CAAC;AAQtE,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAG5D,MAAM,WAAW,eAAe,CAAC,CAAC,GAAG,MAAM;IACvC;;OAEG;IACH,IAAI,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC;IAErB;;OAEG;IACH,EAAE,CAAC,EAAE,IAAI,GAAG,CAAC,CAAC;IAEd;;OAEG;IACH,IAAI,EAAE,CAAC,CAAC;IACR;;OAEG;IACH,KAAK,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC;IAEtB;;OAEG;IACH,QAAQ,CAAC,EAAE,IAAI,GAAG,YAAY,CAAC;IAE/B;;OAEG;IACH,QAAQ,CAAC,EAAE,IAAI,GAAG,YAAY,CAAC;IAE/B;;OAEG;IACH,oBAAoB,CAAC,EAAE,IAAI,GAAG,YAAY,CAAC;IAE3C;;OAEG;IACH,YAAY,CAAC,EAAE,IAAI,GAAG,YAAY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,EAE5C;IAED;;;OAGG;IACH,IAAI,gBAAgB,IAAI,IAAI,GAAG,MAAM,CAMpC;IACD,IAAI,gBAAgB,CAAC,KAAK,EAAE,IAAI,GAAG,YAAY,EAE9C;IAED;;;OAGG;IACH,IAAI,YAAY,IAAI,MAAM,CAA+B;IACzD,IAAI,YAAY,CAAC,KAAK,EAAE,SAAS,EAA0C;IAE3E;;;;;OAKG;IACH,IAAI,kBAAkB,IAAI,IAAI,GAAG,UAAU,CAM1C;IACD,IAAI,kBAAkB,CAAC,KAAK,EAAE,IAAI,GAAG,aAAa,EAEjD;IAID;;OAEG;gBACS,IAAI,EAAE,MAAM;IAqBxB;;OAEG;IACH,IAAI,IAAI,IAAI,IAAI,GAAG,MAAM,CAGxB;IAED;;;;;OAKG;IACH,IAAI,YAAY,IAAI,MAAM,CAEzB;IAED;;OAEG;IACH,IAAI,aAAa,IAAI,IAAI,GAAG,MAAM,CAGjC;IAED;;;;;OAKG;IACH,QAAQ,IAAI,IAAI,IAAI,CAAC,WAAW,GAAG;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,SAAS,CAAA;KAAE,CAAC;IAK1G;;;;;OAKG;IACH,IAAI,UAAU,IAAI,MAAM,CAIvB;IAED;;;;;OAKG;IACH,IAAI,kBAAkB,IAAI,MAAM,CAE/B;IAED;;;OAGG;IACH,SAAS,IAAI,MAAM;IAInB;;;OAGG;IACH,UAAU,IAAI,KAAK,CAAC,MAAM,CAAC;IAyC3B;;OAEG;IACH,KAAK,IAAI,WAAW;IAIpB;;OAEG;IACH,MAAM,IAAI,GAAG;IA4Bb;;;OAGG;IACH,MAAM,CAAC,IAAI,CAAC,EAAE,EAAE,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC,GAAG,WAAW;CAsCjE"} \ No newline at end of file diff --git a/lib.commonjs/transaction/transaction.js b/lib.commonjs/transaction/transaction.js new file mode 100644 index 00000000..89c7e957 --- /dev/null +++ b/lib.commonjs/transaction/transaction.js @@ -0,0 +1,549 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Transaction = void 0; +const index_js_1 = require("../address/index.js"); +const index_js_2 = require("../crypto/index.js"); +const index_js_3 = require("../utils/index.js"); +const accesslist_js_1 = require("./accesslist.js"); +function handleNumber(_value, param) { + if (_value === "0x") { + return 0; + } + return (0, index_js_3.getNumber)(_value, param); +} +function formatNumber(_value, name) { + const value = (0, index_js_3.getBigInt)(_value, "value"); + const result = (0, index_js_3.toBeArray)(value); + (0, index_js_3.assertArgument)(result.length <= 32, `value too large`, `tx.${name}`, value); + return result; +} +function _parseSignature(tx, fields, serialize) { + let yParity; + try { + yParity = handleNumber(fields[0], "yParity"); + if (yParity !== 0 && yParity !== 1) { + throw new Error("bad yParity"); + } + } + catch (error) { + (0, index_js_3.assertArgument)(false, "invalid yParity", "yParity", fields[0]); + } + const r = (0, index_js_3.zeroPadValue)(fields[1], 32); + const s = (0, index_js_3.zeroPadValue)(fields[2], 32); + const signature = index_js_2.Signature.from({ r, s, yParity }); + tx.signature = signature; +} +function _parse(data) { + const decodedTx = (0, index_js_3.decodeProto)((0, index_js_3.getBytes)(data)); + const tx = { + type: decodedTx.type, + from: decodedTx.from, + chainId: (0, index_js_3.toBigInt)(decodedTx.chain_id), + nonce: decodedTx.nonce, + maxPriorityFeePerGas: (0, index_js_3.toBigInt)(decodedTx.gas_tip_cap), + maxFeePerGas: (0, index_js_3.toBigInt)(decodedTx.gas_fee_cap), + gasLimit: (0, index_js_3.toBigInt)(decodedTx.gas), + to: (0, index_js_3.hexlify)(decodedTx.to), + value: (0, index_js_3.toBigInt)(decodedTx.value), + data: (0, index_js_3.hexlify)(decodedTx.data), + accessList: decodedTx.access_list.access_tuples, + }; + if (decodedTx.type == 2) { + tx.externalGasLimit = (0, index_js_3.toBigInt)(decodedTx.etx_gas_limit); + tx.externalGasPrice = (0, index_js_3.toBigInt)(decodedTx.etx_gas_price); + tx.externalGasTip = (0, index_js_3.toBigInt)(decodedTx.etx_gas_tip); + tx.externalData = (0, index_js_3.hexlify)(decodedTx.etx_data); + tx.externalAccessList = decodedTx.etx_access_list.access_tuples; + } + tx.hash = (0, index_js_2.keccak256)(data); + const signatureFields = [ + (0, index_js_3.hexlify)(decodedTx.v), + (0, index_js_3.hexlify)(decodedTx.r), + (0, index_js_3.hexlify)(decodedTx.s), + ]; + _parseSignature(tx, signatureFields, _serialize); + return tx; +} +function _serialize(tx, sig) { + const formattedTx = { + chain_id: formatNumber(tx.chainId || 0, "chainId"), + nonce: (tx.nonce || 0), + gas_tip_cap: formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"), + gas_fee_cap: formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"), + gas: Number(tx.gasLimit || 0), + to: tx.to != null ? (0, index_js_3.getBytes)(tx.to) : "0x", + value: formatNumber(tx.value || 0, "value"), + data: (0, index_js_3.getBytes)(tx.data || "0x"), + access_list: { access_tuples: tx.accessList || [] }, + type: (tx.type || 0), + }; + if (tx.type == 2) { + formattedTx.etx_gas_limit = Number(tx.externalGasLimit || 0); + formattedTx.etx_gas_price = formatNumber(tx.externalGasPrice || 0, "externalGasPrice"); + formattedTx.etx_gas_tip = formatNumber(tx.externalGasTip || 0, "externalGasTip"); + formattedTx.etx_data = (0, index_js_3.getBytes)(tx.externalData || "0x"); + formattedTx.etx_access_list = { access_tuples: tx.externalAccessList || [] }; + } + if (sig) { + formattedTx.v = formatNumber(sig.yParity, "yParity"), + formattedTx.r = (0, index_js_3.toBeArray)(sig.r), + formattedTx.s = (0, index_js_3.toBeArray)(sig.s); + } + return (0, index_js_3.encodeProto)(formattedTx); +} +/** + * A **Transaction** describes an operation to be executed on + * Ethereum by an Externally Owned Account (EOA). It includes + * who (the [[to]] address), what (the [[data]]) and how much (the + * [[value]] in ether) the operation should entail. + * + * @example: + * tx = new Transaction() + * //_result: + * + * tx.data = "0x1234"; + * //_result: + */ +class Transaction { + #type; + #to; + #data; + #nonce; + #gasLimit; + #gasPrice; + #maxPriorityFeePerGas; + #maxFeePerGas; + #value; + #chainId; + #sig; + #accessList; + #externalGasLimit; + #externalGasTip; + #externalGasPrice; + #externalAccessList; + #externalData; + from; + /** + * The transaction type. + * + * If null, the type will be automatically inferred based on + * explicit properties. + */ + get type() { return this.#type; } + set type(value) { + switch (value) { + case null: + this.#type = null; + break; + case 0: + case "standard": + this.#type = 0; + break; + // case 1: case "external": + // this.#type = 1; + // break; + case 2: + case "internalToExternal": + this.#type = 2; + break; + default: + (0, index_js_3.assertArgument)(false, "unsupported transaction type", "type", value); + } + } + /** + * The name of the transaction type. + */ + get typeName() { + switch (this.type) { + case 0: return "standard"; + case 1: return "external"; + case 2: return "internalToExternal"; + } + return null; + } + /** + * The ``to`` address for the transaction or ``null`` if the + * transaction is an ``init`` transaction. + */ + get to() { return this.#to; } + set to(value) { + this.#to = (value == null) ? null : (0, index_js_1.getAddress)(value); + } + /** + * The transaction nonce. + */ + get nonce() { return this.#nonce; } + set nonce(value) { this.#nonce = (0, index_js_3.getNumber)(value, "value"); } + /** + * The gas limit. + */ + get gasLimit() { return this.#gasLimit; } + set gasLimit(value) { this.#gasLimit = (0, index_js_3.getBigInt)(value); } + /** + * The gas price. + * + * On legacy networks this defines the fee that will be paid. On + * EIP-1559 networks, this should be ``null``. + */ + get gasPrice() { + const value = this.#gasPrice; + return value; + } + set gasPrice(value) { + this.#gasPrice = (value == null) ? null : (0, index_js_3.getBigInt)(value, "gasPrice"); + } + /** + * The maximum priority fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get maxPriorityFeePerGas() { + const value = this.#maxPriorityFeePerGas; + if (value == null) { + return null; + } + return value; + } + set maxPriorityFeePerGas(value) { + this.#maxPriorityFeePerGas = (value == null) ? null : (0, index_js_3.getBigInt)(value, "maxPriorityFeePerGas"); + } + /** + * The maximum total fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get maxFeePerGas() { + const value = this.#maxFeePerGas; + if (value == null) { + return null; + } + return value; + } + set maxFeePerGas(value) { + this.#maxFeePerGas = (value == null) ? null : (0, index_js_3.getBigInt)(value, "maxFeePerGas"); + } + /** + * The transaction data. For ``init`` transactions this is the + * deployment code. + */ + get data() { return this.#data; } + set data(value) { this.#data = (0, index_js_3.hexlify)(value); } + /** + * The amount of ether to send in this transactions. + */ + get value() { return this.#value; } + set value(value) { + this.#value = (0, index_js_3.getBigInt)(value, "value"); + } + /** + * The chain ID this transaction is valid on. + */ + get chainId() { return this.#chainId; } + set chainId(value) { this.#chainId = (0, index_js_3.getBigInt)(value); } + /** + * If signed, the signature for this transaction. + */ + get signature() { return this.#sig || null; } + set signature(value) { + this.#sig = (value == null) ? null : index_js_2.Signature.from(value); + } + /** + * The access list. + * + * An access list permits discounted (but pre-paid) access to + * bytecode and state variable access within contract execution. + */ + get accessList() { + const value = this.#accessList || null; + if (value == null) { + return null; + } + return value; + } + set accessList(value) { + this.#accessList = (value == null) ? null : (0, accesslist_js_1.accessListify)(value); + } + /** + * The gas limit. + */ + get externalGasLimit() { return this.#externalGasLimit; } + set externalGasLimit(value) { this.#externalGasLimit = (0, index_js_3.getBigInt)(value); } + /** + * The maximum priority fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get externalGasTip() { + const value = this.#externalGasTip; + if (value == null) { + return null; + } + return value; + } + set externalGasTip(value) { + this.#externalGasTip = (value == null) ? null : (0, index_js_3.getBigInt)(value, "externalGasTip"); + } + /** + * The maximum total fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get externalGasPrice() { + const value = this.#externalGasPrice; + if (value == null) { + return null; + } + return value; + } + set externalGasPrice(value) { + this.#externalGasPrice = (value == null) ? null : (0, index_js_3.getBigInt)(value, "externalGasPrice"); + } + /** + * The transaction externalData. For ``init`` transactions this is the + * deployment code. + */ + get externalData() { return this.#externalData; } + set externalData(value) { this.#externalData = (0, index_js_3.hexlify)(value); } + /** + * The external access list. + * + * An access list permits discounted (but pre-paid) access to + * bytecode and state variable access within contract execution. + */ + get externalAccessList() { + const value = this.#externalAccessList || null; + if (value == null) { + return null; + } + return value; + } + set externalAccessList(value) { + this.#externalAccessList = (value == null) ? null : (0, accesslist_js_1.accessListify)(value); + } + /** + * Creates a new Transaction with default values. + */ + constructor(from) { + this.#type = null; + this.#to = null; + this.#nonce = 0; + this.#gasLimit = BigInt(0); + this.#gasPrice = null; + this.#maxPriorityFeePerGas = null; + this.#maxFeePerGas = null; + this.#data = "0x"; + this.#value = BigInt(0); + this.#chainId = BigInt(0); + this.#sig = null; + this.#accessList = null; + this.#externalGasLimit = BigInt(0); + this.#externalGasTip = null; + this.#externalGasPrice = null; + this.#externalData = "0x"; + this.#externalAccessList = null; + this.from = from; + } + /** + * The transaction hash, if signed. Otherwise, ``null``. + */ + get hash() { + if (this.signature == null) { + return null; + } + return (0, index_js_2.keccak256)(this.serialized); + } + /** + * The pre-image hash of this transaction. + * + * This is the digest that a [[Signer]] must sign to authorize + * this transaction. + */ + get unsignedHash() { + return (0, index_js_2.keccak256)(this.unsignedSerialized); + } + /** + * The public key of the sender, if signed. Otherwise, ``null``. + */ + get fromPublicKey() { + if (this.signature == null) { + return null; + } + return index_js_2.SigningKey.recoverPublicKey(this.unsignedHash, this.signature); + } + /** + * Returns true if signed. + * + * This provides a Type Guard that properties requiring a signed + * transaction are non-null. + */ + isSigned() { + //isSigned(): this is SignedTransaction { + return this.signature != null; + } + /** + * The serialized transaction. + * + * This throws if the transaction is unsigned. For the pre-image, + * use [[unsignedSerialized]]. + */ + get serialized() { + (0, index_js_3.assert)(this.signature != null, "cannot serialize unsigned transaction; maybe you meant .unsignedSerialized", "UNSUPPORTED_OPERATION", { operation: ".serialized" }); + return _serialize(this, this.signature); + } + /** + * The transaction pre-image. + * + * The hash of this is the digest which needs to be signed to + * authorize this transaction. + */ + get unsignedSerialized() { + return _serialize(this); + } + /** + * Return the most "likely" type; currently the highest + * supported transaction type. + */ + inferType() { + return (this.inferTypes().pop()); + } + /** + * Validates the explicit properties and returns a list of compatible + * transaction types. + */ + inferTypes() { + // Checks that there are no conflicting properties set + // const hasGasPrice = this.gasPrice != null; + // const hasFee = (this.maxFeePerGas != null || this.maxPriorityFeePerGas != null); + const hasExternal = (this.externalGasLimit != null || this.externalGasTip != null || this.externalGasPrice != null || this.externalData != null || this.externalAccessList != null); + // const hasAccessList = (this.accessList != null); + //if (hasGasPrice && hasFee) { + // throw new Error("transaction cannot have gasPrice and maxFeePerGas"); + //} + if (this.maxFeePerGas != null && this.maxPriorityFeePerGas != null) { + (0, index_js_3.assert)(this.maxFeePerGas >= this.maxPriorityFeePerGas, "priorityFee cannot be more than maxFee", "BAD_DATA", { value: this }); + } + //if (this.type === 2 && hasGasPrice) { + // throw new Error("eip-1559 transaction cannot have gasPrice"); + //} + (0, index_js_3.assert)(hasExternal || (this.type !== 0 && this.type !== 1), "transaction type cannot have externalGasLimit, externalGasTip, externalGasPrice, externalData, or externalAccessList", "BAD_DATA", { value: this }); + const types = []; + // Explicit type + if (this.type != null) { + types.push(this.type); + } + else { + if (hasExternal) { + types.push(2); + } + else { + types.push(0); + } + } + types.sort(); + return types; + } + /** + * Create a copy of this transaciton. + */ + clone() { + return Transaction.from(this); + } + /** + * Return a JSON-friendly object. + */ + toJSON() { + const s = (v) => { + if (v == null) { + return null; + } + return v.toString(); + }; + return { + type: this.type, + to: this.to, + // from: this.from, + data: this.data, + nonce: this.nonce, + gasLimit: s(this.gasLimit), + gasPrice: s(this.gasPrice), + maxPriorityFeePerGas: s(this.maxPriorityFeePerGas), + maxFeePerGas: s(this.maxFeePerGas), + value: s(this.value), + chainId: s(this.chainId), + sig: this.signature ? this.signature.toJSON() : null, + accessList: this.accessList, + externalGasLimit: s(this.externalGasLimit), + externalGasTip: s(this.externalGasTip), + externalGasPrice: s(this.externalGasPrice), + externalData: this.externalData, + externalAccessList: this.externalAccessList, + }; + } + /** + * Create a **Transaction** from a serialized transaction or a + * Transaction-like object. + */ + static from(tx) { + // if (tx == null) { return new Transaction(); } + if (typeof (tx) === "string") { + const payload = (0, index_js_3.getBytes)(tx); + return Transaction.from(_parse(payload)); + } + const result = new Transaction(tx.from); + if (tx.type != null) { + result.type = tx.type; + } + if (tx.to != null) { + result.to = tx.to; + } + if (tx.nonce != null) { + result.nonce = tx.nonce; + } + if (tx.gasLimit != null) { + result.gasLimit = tx.gasLimit; + } + if (tx.maxPriorityFeePerGas != null) { + result.maxPriorityFeePerGas = tx.maxPriorityFeePerGas; + } + if (tx.maxFeePerGas != null) { + result.maxFeePerGas = tx.maxFeePerGas; + } + if (tx.data != null) { + result.data = tx.data; + } + if (tx.value != null) { + result.value = tx.value; + } + if (tx.chainId != null) { + result.chainId = tx.chainId; + } + if (tx.signature != null) { + result.signature = index_js_2.Signature.from(tx.signature); + } + if (tx.accessList != null) { + result.accessList = tx.accessList; + } + if (tx.externalGasLimit != null) { + result.externalGasLimit = tx.externalGasLimit; + } + if (tx.externalGasPrice != null) { + result.externalGasPrice = tx.externalGasPrice; + } + if (tx.externalGasTip != null) { + result.externalGasTip = tx.externalGasTip; + } + if (tx.externalData != null) { + result.externalData = tx.externalData; + } + if (tx.externalAccessList != null) { + result.externalAccessList = tx.externalAccessList; + } + if (tx.hash != null) { + (0, index_js_3.assertArgument)(result.isSigned(), "unsigned transaction cannot define hash", "tx", tx); + (0, index_js_3.assertArgument)(result.hash === tx.hash, "hash mismatch", "tx", tx); + } + if (tx.from != null) { + // assertArgument(result.isSigned(), "unsigned transaction cannot define from", "tx", tx); + (0, index_js_3.assertArgument)(result.from.toLowerCase() === (tx.from || "").toLowerCase(), "from mismatch", "tx", tx); + } + return result; + } +} +exports.Transaction = Transaction; +//# sourceMappingURL=transaction.js.map \ No newline at end of file diff --git a/lib.commonjs/transaction/transaction.js.map b/lib.commonjs/transaction/transaction.js.map new file mode 100644 index 00000000..4c963254 --- /dev/null +++ b/lib.commonjs/transaction/transaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transaction.js","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,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,CAAC,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,EAAE,eAAe,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;SAC1G;QAED,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ;AAhcD,kCAgcC"} \ No newline at end of file diff --git a/lib.commonjs/wallet/base-wallet.js b/lib.commonjs/wallet/base-wallet.js new file mode 100644 index 00000000..77b3e903 --- /dev/null +++ b/lib.commonjs/wallet/base-wallet.js @@ -0,0 +1,108 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BaseWallet = void 0; +const index_js_1 = require("../address/index.js"); +const index_js_2 = require("../hash/index.js"); +const index_js_3 = require("../providers/index.js"); +const index_js_4 = require("../transaction/index.js"); +const index_js_5 = require("../utils/index.js"); +/** + * The **BaseWallet** is a stream-lined implementation of a + * [[Signer]] that operates with a private key. + * + * It is preferred to use the [[Wallet]] class, as it offers + * additional functionality and simplifies loading a variety + * of JSON formats, Mnemonic Phrases, etc. + * + * This class may be of use for those attempting to implement + * a minimal Signer. + */ +class BaseWallet extends index_js_3.AbstractSigner { + /** + * The wallet address. + */ + #address; + #signingKey; + /** + * Creates a new BaseWallet for %%privateKey%%, optionally + * connected to %%provider%%. + * + * If %%provider%% is not specified, only offline methods can + * be used. + */ + constructor(privateKey, provider) { + super(provider); + (0, index_js_5.assertArgument)(privateKey && typeof (privateKey.sign) === "function", "invalid private key", "privateKey", "[ REDACTED ]"); + this.#signingKey = privateKey; + this.#address = (0, index_js_4.computeAddress)(this.signingKey.publicKey); + } + // Store private values behind getters to reduce visibility + // in console.log + /** + * The address of this wallet. + */ + get address() { return this.#address; } + /** + * The [[SigningKey]] used for signing payloads. + */ + get signingKey() { return this.#signingKey; } + /** + * The private key for this wallet. + */ + get privateKey() { return this.signingKey.privateKey; } + async getAddress() { return this.#address; } + connect(provider) { + return new BaseWallet(this.#signingKey, provider); + } + async signTransaction(tx) { + // Replace any Addressable or ENS name with an address + const { to, from } = await (0, index_js_5.resolveProperties)({ + to: (tx.to ? (0, index_js_1.resolveAddress)(tx.to, this.provider) : undefined), + from: (tx.from ? (0, index_js_1.resolveAddress)(tx.from, this.provider) : undefined) + }); + if (to != null) { + tx.to = to; + } + if (from != null) { + tx.from = from; + } + if (tx.from != null) { + (0, index_js_5.assertArgument)((0, index_js_1.getAddress)((tx.from)) === this.#address, "transaction from address mismatch", "tx.from", tx.from); + // delete tx.from; + } + // Build the transaction + const btx = index_js_4.Transaction.from(tx); + btx.signature = this.signingKey.sign(btx.unsignedHash); + return btx.serialized; + } + async signMessage(message) { + return this.signMessageSync(message); + } + // @TODO: Add a secialized signTx and signTyped sync that enforces + // all parameters are known? + /** + * Returns the signature for %%message%% signed with this wallet. + */ + signMessageSync(message) { + return this.signingKey.sign((0, index_js_2.hashMessage)(message)).serialized; + } + async signTypedData(domain, types, value) { + // Populate any ENS names + const populated = await index_js_2.TypedDataEncoder.resolveNames(domain, types, value, async (name) => { + // @TODO: this should use resolveName; addresses don't + // need a provider + (0, index_js_5.assert)(this.provider != null, "cannot resolve ENS names without a provider", "UNSUPPORTED_OPERATION", { + operation: "resolveName", + info: { name } + }); + const address = await this.provider.resolveName(name); + (0, index_js_5.assert)(address != null, "unconfigured ENS name", "UNCONFIGURED_NAME", { + value: name + }); + return address; + }); + return this.signingKey.sign(index_js_2.TypedDataEncoder.hash(populated.domain, types, populated.value)).serialized; + } +} +exports.BaseWallet = BaseWallet; +//# sourceMappingURL=base-wallet.js.map \ No newline at end of file diff --git a/lib.commonjs/wallet/base-wallet.js.map b/lib.commonjs/wallet/base-wallet.js.map new file mode 100644 index 00000000..30d36192 --- /dev/null +++ b/lib.commonjs/wallet/base-wallet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"base-wallet.js","sourceRoot":"","sources":["../../src.ts/wallet/base-wallet.ts"],"names":[],"mappings":";;;AAAA,kDAAiE;AACjE,+CAAiE;AACjE,o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,SAAS,GAAG,MAAM,2BAAgB,CAAC,YAAY,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,IAAY,EAAE,EAAE;YAC/F,sDAAsD;YACtD,yBAAyB;YAEzB,IAAA,iBAAM,EAAC,IAAI,CAAC,QAAQ,IAAI,IAAI,EAAE,6CAA6C,EAAE,uBAAuB,EAAE;gBAClG,SAAS,EAAE,aAAa;gBACxB,IAAI,EAAE,EAAE,IAAI,EAAE;aACjB,CAAC,CAAC;YAEH,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;YACtD,IAAA,iBAAM,EAAC,OAAO,IAAI,IAAI,EAAE,uBAAuB,EAAE,mBAAmB,EAAE;gBAClE,KAAK,EAAE,IAAI;aACd,CAAC,CAAC;YAEH,OAAO,OAAO,CAAC;QACnB,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,2BAAgB,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,UAAU,CAAC;IAC5G,CAAC;CACJ;AA5GD,gCA4GC"} \ No newline at end of file diff --git a/lib.esm/_tests/test-provider-jsonrpc.js b/lib.esm/_tests/test-provider-jsonrpc.js new file mode 100644 index 00000000..8dab0428 --- /dev/null +++ b/lib.esm/_tests/test-provider-jsonrpc.js @@ -0,0 +1,159 @@ +import assert from "assert"; +import { id, isError, makeError, toUtf8Bytes, toUtf8String, FetchRequest, JsonRpcProvider, Transaction, Wallet } from "../index.js"; +const StatusMessages = { + 200: "OK", + 400: "BAD REQUEST", + 500: "SERVER ERROR", +}; +const wallet = new Wallet(id("test")); +function createProvider(testFunc) { + let blockNumber = 1; + const ticker = setInterval(() => { blockNumber++; }, 100); + if (ticker.unref) { + ticker.unref(); + } + const processReq = (req) => { + let result = testFunc(req.method, req.params, blockNumber); + if (result === undefined) { + switch (req.method) { + case "quai_blockNumber": + result = blockNumber; + break; + case "quai_chainId": + result = "0x1337"; + break; + case "quai_accounts": + result = [wallet.address]; + break; + default: + console.log("****", req); + return { id, error: "unsupported", jsonrpc: "2.0" }; + } + } + return { id: req.id, result, jsonrpc: "2.0" }; + }; + const req = new FetchRequest("http:/\/localhost:8082/"); + req.getUrlFunc = async (_req, signal) => { + const req = JSON.parse(_req.hasBody() ? toUtf8String(_req.body) : ""); + let statusCode = 200; + const headers = {}; + let resp; + try { + if (Array.isArray(req)) { + resp = req.map((r) => processReq(r)); + } + else { + resp = processReq(req); + } + } + catch (error) { + statusCode = 500; + resp = error.message; + } + const body = toUtf8Bytes(JSON.stringify(resp)); + return { + statusCode, + statusMessage: StatusMessages[statusCode], + headers, body + }; + }; + return new JsonRpcProvider(req, undefined, { cacheTimeout: -1 }); +} +describe("Ensure Catchable Errors", function () { + it("Can catch bad broadcast replies", async function () { + this.timeout(15000); + const txInfo = { + chainId: 1337, + gasLimit: 100000, + maxFeePerGas: 2000000000, + maxPriorityFeePerGas: 1000000000, + to: wallet.address, + from: wallet.address, + value: 1, + }; + const txSign = await wallet.signTransaction(txInfo); + const txObj = Transaction.from(txSign); + let count = 0; + const provider = createProvider((method, params, blockNumber) => { + switch (method) { + case "quai_sendTransaction": + return txObj.hash; + case "quai_getTransactionByHash": { + count++; + // First time; fail! + if (count === 1) { + throw makeError("Faux Error", "SERVER_ERROR", { + request: ({}) + }); + } + // Second time; return null + if (count === 2) { + return null; + } + // Return a valid tx... + const result = Object.assign({}, txObj.toJSON(), txObj.signature.toJSON(), { hash: txObj.hash, from: wallet.address }); + // ...eventually mined + if (count > 4) { + result.blockNumber = blockNumber; + result.blockHash = id("test"); + } + return result; + } + } + return undefined; + }); + const signer = await provider.getSigner(); + const tx = await signer.sendTransaction(txInfo); + assert(tx); + }); + it("Missing v is recovered", async function () { + this.timeout(15000); + const txInfo = { + chainId: 1337, + gasLimit: 100000, + maxFeePerGas: 2000000000, + maxPriorityFeePerGas: 1000000000, + to: wallet.address, + from: wallet.address, + value: 1, + }; + const txSign = await wallet.signTransaction(txInfo); + const txObj = Transaction.from(txSign); + let count = 0; + // A provider which is mocked to return a "missing v" + // in getTransaction + const provider = createProvider((method, params, blockNumber) => { + switch (method) { + case "quai_sendTransaction": + return txObj.hash; + case "quai_getTransactionByHash": { + count++; + // The fully valid tx response + const result = Object.assign({}, txObj.toJSON(), txObj.signature.toJSON(), { hash: txObj.hash, from: wallet.address, sig: null }); + // First time; fail with a missing v! + if (count < 2) { + delete result.v; + } + // Debug + result._count = count; + return result; + } + } + return undefined; + }); + // Track any "missing v" error + let missingV = null; + provider.on("error", (e) => { + if (isError(e, "UNKNOWN_ERROR") && isError(e.error, "INVALID_ARGUMENT")) { + if (e.error.argument === "signature" && e.error.shortMessage === "missing v") { + missingV = e.error; + } + } + }); + const signer = await provider.getSigner(); + const tx = await signer.sendTransaction(txInfo); + assert.ok(!!tx, "we got a transaction"); + assert.ok(!!missingV, "missing v error present"); + }); +}); +//# sourceMappingURL=test-provider-jsonrpc.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-provider-jsonrpc.js.map b/lib.esm/_tests/test-provider-jsonrpc.js.map new file mode 100644 index 00000000..42887247 --- /dev/null +++ b/lib.esm/_tests/test-provider-jsonrpc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-provider-jsonrpc.js","sourceRoot":"","sources":["../../src.ts/_tests/test-provider-jsonrpc.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EACH,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EACjD,YAAY,EACZ,eAAe,EAAE,WAAW,EAAE,MAAM,EACvC,MAAM,aAAa,CAAC;AAErB,MAAM,cAAc,GAA2B;IAC7C,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,aAAa;IAClB,GAAG,EAAE,cAAc;CACpB,CAAC;AAMF,MAAM,MAAM,GAAG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CAAC,MAAM,GAAG,KAAK,CAAC;oBAEtB,OAAO,MAAM,CAAC;iBACjB;aACJ;YAED,OAAO,SAAS,CAAC;QACrB,CAAC,CAAC,CAAC;QAEH,8BAA8B;QAC9B,IAAI,QAAQ,GAAiB,IAAI,CAAC;QAClC,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE;YACvB,IAAI,OAAO,CAAC,CAAC,EAAE,eAAe,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,kBAAkB,CAAC,EAAE;gBACrE,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,KAAK,WAAW,IAAI,CAAC,CAAC,KAAK,CAAC,YAAY,KAAK,WAAW,EAAE;oBAC1E,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC;iBACtB;aACJ;QACL,CAAC,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,SAAS,EAAE,CAAC;QAE1C,MAAM,EAAE,GAAG,MAAM,MAAM,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;QAChD,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,sBAAsB,CAAC,CAAC;QACxC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,EAAE,yBAAyB,CAAC,CAAC;IACrD,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/_tests/test-providers-data.js b/lib.esm/_tests/test-providers-data.js new file mode 100644 index 00000000..3d74effd --- /dev/null +++ b/lib.esm/_tests/test-providers-data.js @@ -0,0 +1,326 @@ +import assert from "assert"; +// import { +// checkProvider, getProvider, providerNames +// } from "./create-provider.js"; +// import { retryIt } from "./utils.js"; +//import type { Provider } from "../index.js"; +import { getTxType, quais } from "../index.js"; +import axios from 'axios'; +import { stall } from "./utils.js"; +// import { +// networkFeatureAtBlock, networkNames, +// testAddress, testBlock, testReceipt, testTransaction +// } from "./blockchain-data.js"; +// import type { TestBlockchainNetwork } from "./blockchain-data.js"; +//setupProviders(); +const providerC1 = new quais.JsonRpcProvider(process.env.RPC_URL); +const wallet = new quais.Wallet(process.env.FAUCET_PRIVATEKEY || '', providerC1); +const destinationC1 = '0x0047f9CEa7662C567188D58640ffC48901cde02a'; +const destinationC2 = '0x011ae0a1Bd5B71b4F16F8FdD3AEF278C3D042449'; +function equals(name, actual, expected) { + if (expected && expected.eq) { + if (actual == null) { + assert.ok(false, name + " - actual big number null"); + } + expected = BigInt(expected); + actual = BigInt(actual); + assert.ok(expected.eq(actual), name + " matches"); + } + else if (Array.isArray(expected)) { + if (actual == null) { + assert.ok(false, name + " - actual array null"); + } + assert.equal(actual.length, expected.length, name + " array lengths match"); + for (let i = 0; i < expected.length; i++) { + equals("(" + name + " - item " + i + ")", actual[i], expected[i]); + } + } + else if (typeof (expected) === "object") { + if (actual == null) { + if (expected === actual) { + return; + } + assert.ok(false, name + " - actual object null"); + } + let keys = {}; + Object.keys(expected).forEach((key) => { keys[key] = true; }); + Object.keys(actual).forEach((key) => { keys[key] = true; }); + Object.keys(keys).forEach((key) => { + if (typeof actual[key] === "string" && actual[key].toLowerCase && key === "type") { + actual[key] = actual[key].toLowerCase(); + } + equals("(" + name + " - key + " + key + ")", actual[key], expected[key]); + }); + } + else { + if (actual == null) { + assert.ok(false, name + " - actual null"); + } + // Modify this part for case-insensitive comparison for string values + if (typeof actual === 'string' && typeof expected === 'string') { + assert.equal(actual.toLowerCase(), expected.toLowerCase(), name + " matches (case-insensitive)"); + } + else { + assert.equal(actual, expected, name + " matches"); + } + } +} +async function getRPCGasPrice(url) { + try { + let response; + do { + response = await axios.post(url || "http://localhost:8610", { + jsonrpc: "2.0", + method: "quai_gasPrice", + params: [], + id: 1 + }); + } while (response.data.result == null); + return response.data.result; + } + catch (error) { + throw new Error(`Error fetching block: ${error.message}`); + } +} +async function sendTransaction(to) { + let txResponse; + let typeValue; + try { + console.log("Nonce: ", await providerC1.getTransactionCount(wallet.address, 'latest')); + do { + typeValue = getTxType(wallet.address, to); + const gas = await getRPCGasPrice(process.env.RPC_URL); + let tx = { + from: wallet.address, + to, + value: quais.parseEther("0.1"), + gasPrice: gas * 2, + maxFeePerGas: quais.parseUnits('20', 'gwei'), + maxPriorityFeePerGas: quais.parseUnits('20', 'gwei'), + nonce: await providerC1.getTransactionCount(wallet.address, 'latest'), + data: '', + type: typeValue, + gasLimit: typeValue == 0 ? 21000 : 42000, + chainId: Number(process.env.CHAIN_ID || 1337), + }; + txResponse = await wallet.sendTransaction(tx); + console.log(txResponse); + await stall(15000); + } while (txResponse.hash == null); + console.log(`Transaction hash for type ${typeValue}: `, txResponse.hash); + return txResponse; + } + catch (error) { + console.error('Failed to send Transaction: ', error); + return null; + } +} +async function fetchRPCBlock(blockNumber) { + try { + let response; + do { + response = await axios.post(process.env.RPC_URL || "http://localhost:8610", { + jsonrpc: "2.0", + method: "quai_getBlockByNumber", + params: [ + blockNumber || '0xA', + false + ], + id: 1 + }); + } while (response.data.result.hash == null); + return response.data.result; + } + catch (error) { + throw error; + } +} +async function fetchRPCBalance(address, url) { + try { + let response; + do { + response = await axios.post(url, { + jsonrpc: "2.0", + method: "quai_getBalance", + params: [ + address, + 'latest' + ], + id: 1 + }); + } while (response.data.result == null); + return response.data.result; + } + catch (error) { + throw new Error(`Error fetching block: ${error.message}`); + } +} +async function fetchRPCTxReceipt(hash, url) { + try { + let response; + do { + response = await axios.post(url, { + jsonrpc: "2.0", + method: "quai_getTransactionReceipt", + params: [ + hash + ], + id: 1 + }); + await stall(5000); + } while (response.data.result.blockHash == null); + return response.data.result; + } + catch (error) { + throw new Error(`Error fetching block: ${error.message}`); + } +} +describe("Test Provider Block operations", function () { + let block; + before(async () => { + const rpcBlock = await fetchRPCBlock('0xA'); + block = { + hash: rpcBlock.hash, + number: rpcBlock.number.map((stringNumber) => Number(stringNumber)), + transactions: rpcBlock.transactions, + parentHash: rpcBlock.parentHash, + parentEntropy: rpcBlock.parentEntropy.map((entropy) => BigInt(entropy)), + extTransactions: rpcBlock.extTransactions, + timestamp: Number(rpcBlock.timestamp), + nonce: rpcBlock.nonce, + difficulty: BigInt(rpcBlock.difficulty), + gasLimit: BigInt(rpcBlock.gasLimit), + gasUsed: BigInt(rpcBlock.gasUsed), + miner: rpcBlock.miner, + extraData: rpcBlock.extraData, + transactionsRoot: rpcBlock.transactionsRoot, + evmRoot: rpcBlock.stateRoot, + utxoRoot: rpcBlock.utxoRoot, + receiptsRoot: rpcBlock.receiptsRoot, + baseFeePerGas: BigInt(rpcBlock.baseFeePerGas), + extRollupRoot: rpcBlock.extRollupRoot, + extTransactionsRoot: rpcBlock.extTransactionsRoot, + location: rpcBlock.location, + manifestHash: rpcBlock.manifestHash, + mixHash: rpcBlock.mixHash, + order: rpcBlock.order, + parentDeltaS: rpcBlock.parentDeltaS.map((delta) => BigInt(delta)), + sha3Uncles: rpcBlock.sha3Uncles, + size: BigInt(rpcBlock.size), + uncles: rpcBlock.uncles, + subManifest: rpcBlock.subManifest, + totalEntropy: BigInt(rpcBlock.totalEntropy), + }; + }); + it('should fetch block by number', async function () { + let responseBlock = await providerC1.getBlock('0,0', '0xA'); + assert.ok(responseBlock != null, "block != null"); + let { provider, ...formatBlock } = { + ...responseBlock, + transactions: responseBlock.transactions, + extTransactions: responseBlock.extTransactions + }; + equals("Block by Number", formatBlock, block); + }); + it('should fetch block by hash', async function () { + assert.ok(block.hash != null, 'block.hash != null'); + let responseBlock = await providerC1.getBlock('0,0', block.hash); + assert.ok(responseBlock != null, "block != null"); + let { provider, ...formatBlock } = { + ...responseBlock, + transactions: responseBlock.transactions, + extTransactions: responseBlock.extTransactions + }; + equals("Block by Hash", formatBlock, block); + }); +}); +describe("Test Transaction operations", function () { + let internalTx; + let internalToExternalTx; + it('should fetch balance after internal tx', async function () { + this.timeout(60000); + const oldBal = await fetchRPCBalance(destinationC1, process.env.RPC_URL || "http://localhost:8610"); + internalTx = await sendTransaction(destinationC1); + await stall(30000); + const expectedBal = BigInt(internalTx.value); + const balance = await providerC1.getBalance(destinationC1); + const actualBal = Number(balance) - Number(oldBal); + assert.equal(actualBal, Number(expectedBal)); + }); + it('should get transaction receipt for internal tx', async function () { + this.timeout(60000); + const receipt = await fetchRPCTxReceipt(internalTx.hash, process.env.RPC_URL || "http://localhost:8610"); + const expectedReceipt = { + blockHash: receipt.blockHash, + contractAddress: receipt.contractAddress || null, + blockNumber: Number(receipt.blockNumber), + cumulativeGasUsed: BigInt(receipt.cumulativeGasUsed), + gasPrice: BigInt(receipt.effectiveGasPrice), + etxs: receipt.etxs, + gasUsed: BigInt(receipt.gasUsed), + logs: receipt.logs, + logsBloom: receipt.logsBloom, + status: Number(receipt.status), + to: receipt.to, + from: receipt.from, + hash: receipt.transactionHash, + index: Number(receipt.transactionIndex), + type: receipt.type, + }; + const receiptResponse = await providerC1.getTransactionReceipt(internalTx.hash); + let { provider, ...receiptResult } = { + ...receiptResponse, + logs: receiptResponse?.logs + }; + equals("Internal Tx Receipt", receiptResult, expectedReceipt); + }); + it("should fetch transaction receipt for internal to external tx", async function () { + this.timeout(120000); + internalToExternalTx = await sendTransaction(destinationC2); + await stall(60000); + const receipt = await fetchRPCTxReceipt(internalToExternalTx.hash, process.env.RPC_URL || "http://localhost:8610"); + await stall(30000); + const etx = receipt.etxs[0]; + const expectedReceipt = { + blockHash: receipt.blockHash, + blockNumber: Number(receipt.blockNumber), + contractAddress: receipt.contractAddress || null, + cumulativeGasUsed: BigInt(receipt.cumulativeGasUsed), + gasPrice: BigInt(receipt.effectiveGasPrice), + etxs: [ + { + type: Number(etx.type), + nonce: Number(etx.nonce), + maxPriorityFeePerGas: BigInt(etx.maxPriorityFeePerGas), + maxFeePerGas: BigInt(etx.maxFeePerGas), + gas: BigInt(etx.gas), + value: BigInt(etx.value), + input: etx.input, + to: etx.to, + from: etx.sender, + hash: etx.hash, + chainId: Number(etx.chainId), + accessList: etx.accessList, + } + ], + gasUsed: BigInt(receipt.gasUsed), + logs: receipt.logs, + logsBloom: receipt.logsBloom, + status: Number(receipt.status), + to: receipt.to, + from: receipt.from, + hash: receipt.transactionHash, + index: Number(receipt.transactionIndex), + type: Number(receipt.type), + }; + const receiptResponse = await providerC1.getTransactionReceipt(internalToExternalTx.hash); + let { provider, ...receiptResult } = { + ...receiptResponse, + logs: receiptResponse?.logs + }; + console.log(receiptResult); + console.log(expectedReceipt); + equals("Internal to External Tx Receipt", receiptResult, expectedReceipt); + }); +}); +//# sourceMappingURL=test-providers-data.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-providers-data.js.map b/lib.esm/_tests/test-providers-data.js.map new file mode 100644 index 00000000..e046003c --- /dev/null +++ b/lib.esm/_tests/test-providers-data.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-providers-data.js","sourceRoot":"","sources":["../../src.ts/_tests/test-providers-data.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,WAAW;AACX,gDAAgD;AAChD,iCAAiC;AACjC,wCAAwC;AAExC,8CAA8C;AAC9C,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,WAAW;AACX,2CAA2C;AAC3C,2DAA2D;AAC3D,iCAAiC;AAEjC,qEAAqE;AAGrE,mBAAmB;AAGnB,MAAM,UAAU,GAAG,IAAI,KAAK,CAAC,eAAe,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAClE,MAAM,MAAM,GAAG,IAAI,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,IAAI,EAAE,EAAE,UAAU,CAAC,CAAC;AACjF,MAAM,aAAa,GAAG,4CAA4C,CAAA;AAClE,MAAM,aAAa,GAAG,4CAA4C,CAAA;AAElE,SAAS,MAAM,CAAC,IAAY,EAAE,MAAW,EAAE,QAAa;IAC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AAE,MAAM,CAAC,OAAO,CAAC,gBAAgB,CAAC;YACvC,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC;SAC7B,CAAA;QACD,MAAM,eAAe,GAAG,MAAM,UAAU,CAAC,qBAAqB,CAAC,oBAAoB,CAAC,IAAI,CAAC,CAAC;QAC1F,IAAI,EAAE,QAAQ,EAAE,GAAG,aAAa,EAAE,GAAG;YACjC,GAAG,eAAe;YAClB,IAAI,EAAE,eAAe,EAAE,IAAI;SAC9B,CAAC;QACF,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;QAC3B,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAA;QAC5B,MAAM,CAAC,iCAAiC,EAAE,aAAa,EAAE,eAAe,CAAC,CAAC;IAC9E,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAA"} \ No newline at end of file diff --git a/lib.esm/_tests/test-providers-errors.js b/lib.esm/_tests/test-providers-errors.js new file mode 100644 index 00000000..89270625 --- /dev/null +++ b/lib.esm/_tests/test-providers-errors.js @@ -0,0 +1,232 @@ +import assert from "assert"; +import { concat, dataSlice, id, toBeArray, zeroPadValue, isCallException, isError, Wallet } from "../index.js"; +import { getProvider, setupProviders, providerNames } from "./create-provider.js"; +import { stall } from "./utils.js"; +//require('dotenv').config(); +import dotenv from "dotenv"; +dotenv.config(); +setupProviders(); +describe("Tests Provider Call Exception", function () { + const panics = [ + //{ code: 0x00, reason: "GENERIC_PANIC" }, + { code: 0x01, reason: "ASSERT_FALSE" }, + { code: 0x11, reason: "OVERFLOW" }, + { code: 0x12, reason: "DIVIDE_BY_ZERO" }, + //{ code: 0x21, reason: "ENUM_RANGE_ERROR" }, + //{ code: 0x22, reason: "BAD_STORAGE_DATA" }, + { code: 0x31, reason: "STACK_UNDERFLOW" }, + { code: 0x32, reason: "ARRAY_RANGE_ERROR" }, + //{ code: 0x41, reason: "OUT_OF_MEMORY" }, + //{ code: 0x51, reason: "UNINITIALIZED_FUNCTION_CALL" }, + ]; + const testAddr = "0x0aff86a125b29b25a9e418c2fb64f1753532c0ca"; //Cyprus1 + const testAddr2 = "0x0aff86a125b29b25a9e418c2fb64f1753532c0ca"; //Cyprus1 + const networkName = "colosseum"; + for (const { code, reason } of panics) { + for (const method of ["call", "estimateGas"]) { + for (const providerName of providerNames) { + const provider = getProvider(providerName, networkName); + if (provider == null) { + continue; + } + it(`tests panic code: ${providerName}.${method}.${reason}`, async function () { + this.timeout(10000); + const data = concat([ + dataSlice(id("testPanic(uint256)"), 0, 4), + zeroPadValue(toBeArray(code), 32) + ]); + await stall(1000); + const tx = { to: testAddr, from: testAddr2, data }; + try { + const result = await (method === "call" ? provider.call(tx) : provider.estimateGas(tx)); + console.log(result); + assert.ok(false, "panic call did not throw"); + } + catch (error) { + assert.ok(isCallException(error), "isCallException"); + // Check some basics + assert.equal(error.action, method, `error.action == ${method}`); + assert.equal(error.reason, `Panic due to ${reason}(${code})`, "error.reason"); + // Check the transaciton + assert.equal(error.transaction.to, tx.to, `error.transaction.to`); + assert.equal(error.transaction.data, tx.data, `error.transaction.data`); + // We have no invocation data + assert.equal(error.invocation, null, `error.invocation != null`); + // Check the revert + assert.ok(error.revert != null, "error.revert == null"); + assert.equal(error.revert.name, "Panic", `error.revert.name`); + assert.equal(error.revert.signature, "Panic(uint256)", `error.revert.signature`); + assert.equal(error.revert.args.length, 1, `error.revert.args.length`); + assert.equal(error.revert.args[0], code, `error.revert.args[0]`); + } + }); + } + } + } + const customErrors = [ + { + name: "CustomError1", + signature: "testCustomError1(bool,uint256,string)", + data: "0xdb7342480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000b68656c6c6f20776f726c64000000000000000000000000000000000000000000", + //data: "0x852d0c740000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000", + message: `execution reverted (unknown custom error)`, + reason: null, + revert: null, + }, + { + name: "Error", + signature: "testErrorString(bool,string)", + data: "0xb206699b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000b68656c6c6f20776f726c64000000000000000000000000000000000000000000", + //data: "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000" + message: `execution reverted: "hello world"`, + reason: "hello world", + revert: { + signature: "Error(string)", + name: "Error", + args: ['hello world'] + } + }, + ]; + for (const { data, message, name, reason, revert } of customErrors) { + for (const method of ["call", "estimateGas"]) { + const tx = { to: testAddr, from: testAddr2, data }; + for (const providerName of providerNames) { + const provider = getProvider(providerName, networkName); + if (provider == null) { + continue; + } + it(`tests custom errors: ${providerName}.${method}.${name}`, async function () { + this.timeout(10000); + try { + const result = await (method === "call" ? provider.call(tx) : provider.estimateGas(tx)); + console.log(result); + assert.ok(false, "panic call did not throw"); + } + catch (error) { + assert.ok(isCallException(error), "isCallException"); + // Check some basics + assert.equal(error.action, method, `error.action == ${method}`); + assert.ok(error.message.startsWith(message), "error.message == message"); + if (reason) { + assert.equal(error.reason, reason, "error.reason"); + } + else { + assert.ok(error.reason == null, "error.reason != null"); + } + if (revert) { + assert.ok(error.revert != null, "error.revert == null"); + assert.equal(error.revert.name, revert.name, "error.revert.name"); + assert.equal(error.revert.signature, revert.signature, "error.revert.signature"); + assert.equal(error.revert.args.length, revert.args.length, "error.revert.args.length"); + for (let i = 0; i < revert.args.length; i++) { + assert.equal(error.revert.args[i], revert.args[i], `error.revert.args[${i}]`); + } + } + else { + assert.ok(error.revert == null, "error.revert != null"); + } + } + }); + } + } + } +}); +describe("Test Provider Blockchain Errors", function () { + const wallet = new Wallet((process.env.FAUCET_PRIVATEKEY)); + const wallet2 = new Wallet((process.env.FAUCET_PRIVATEKEY)); + const networkName = "colosseum"; + for (const providerName of providerNames) { + const provider = getProvider(providerName, networkName); + if (provider == null) { + continue; + } + // The CI runs multiple tests at once; minimize colliding with + // the initial tx by using a random value, so we can detect + // replacements we didn't do. + const value = Math.trunc(Math.random() * 2048) + 2; + it(`tests underpriced replacement transaction: ${providerName}`, async function () { + this.timeout(60000); + const w = wallet.connect(provider); + let tx1 = null; + let nonce = null; + ; + for (let i = 0; i < 10; i++) { + nonce = await w.getNonce("pending"); + try { + tx1 = await w.sendTransaction({ + nonce, to: wallet, from: wallet2, value + }); + } + catch (error) { + // Another CI host beat us to this nonce + if (isError(error, "REPLACEMENT_UNDERPRICED") || isError(error, "NONCE_EXPIRED")) { + await stall(1000); + continue; + } + console.log("EE-tx1", nonce, value, error); + throw error; + } + break; + } + if (tx1 == null || nonce == null) { + throw new Error("could not send initial tx"); + } + const rejection = assert.rejects(async function () { + // Send another tx with the same nonce + const tx2 = await w.sendTransaction({ + nonce, to: wallet, from: wallet2, value: 1 + }); + console.log({ tx1, tx2 }); + }, (error) => { + return isError(error, "REPLACEMENT_UNDERPRICED"); + }); + // Wait for the first tx to get mined so we start with a + // clean slate on the next provider + await tx1.wait(); + // This should have already happened + await rejection; + }); + } + for (const providerName of providerNames) { + const provider = getProvider(providerName, networkName); + if (provider == null) { + continue; + } + it(`tests insufficient funds: ${providerName}`, async function () { + this.timeout(60000); + const w = Wallet.createRandom("m/44'/60'/0'/0/0").connect(provider); + await assert.rejects(async function () { + const tx = await w.sendTransaction({ + to: wallet, from: wallet2, value: 1 + }); + console.log(tx); + }, (error) => { + return (isError(error, "INSUFFICIENT_FUNDS") && + typeof (error.transaction.from) === "string" && + error.transaction.from.toLowerCase() === w.address.toLowerCase()); + }); + }); + } + for (const providerName of providerNames) { + const provider = getProvider(providerName, networkName); + if (provider == null) { + continue; + } + it(`tests nonce expired: ${providerName}`, async function () { + this.timeout(60000); + const w = wallet.connect(provider); + await assert.rejects(async function () { + const tx = await w.sendTransaction({ + to: wallet, from: wallet2, value: 1 + }); + console.log(tx); + }, (error) => { + if (!isError(error, "NONCE_EXPIRED")) { + console.log(error); + } + return isError(error, "NONCE_EXPIRED"); + }); + }); + } +}); +//# sourceMappingURL=test-providers-errors.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-providers-errors.js.map b/lib.esm/_tests/test-providers-errors.js.map new file mode 100644 index 00000000..ef79323f --- /dev/null +++ b/lib.esm/_tests/test-providers-errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-providers-errors.js","sourceRoot":"","sources":["../../src.ts/_tests/test-providers-errors.ts"],"names":[],"mappings":"AACA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EACH,MAAM,EAAE,SAAS,EAAE,EAAE,EAAE,SAAS,EAAE,YAAY,EAC9C,eAAe,EAAE,OAAO,EACxB,MAAM,EACT,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAClF,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAGnC,6BAA6B;AAC7B,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,MAAM,CAAC,MAAM,EAAE,CAAC;AAehB,cAAc,EAAE,CAAC;AAEjB,QAAQ,CAAC,+BAA+B,EAAE;IAEtC,MAAM,MAAM,GAA4C;QACpD,0CAA0C;QAC1C,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,cAAc,EAAE;QACtC,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE;QAClC,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,gBAAgB,EAAE;QACxC,6CAA6C;QAC7C,6CAA6C;QAC7C,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,iBAAiB,EAAE;QACzC,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,mBAAmB,EAAE;QAC3C,0CAA0C;QAC1C,wDAA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C,EAAE,CAAC,wBAAyB,YAAa,EAAE,EAAE,KAAK;YAC9C,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAEpB,MAAM,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;YAEnC,MAAM,MAAM,CAAC,OAAO,CAAC,KAAK;gBACtB,MAAM,EAAE,GAAG,MAAM,CAAC,CAAC,eAAe,CAAC;oBAC/B,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;iBACtC,CAAC,CAAC;gBACH,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YACpB,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE;gBACT,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,eAAe,CAAC,EAAE;oBAClC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;iBACtB;gBACD,OAAO,OAAO,CAAC,KAAK,EAAE,eAAe,CAAC,CAAC;YAC3C,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;KACN;AAEL,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/_tests/test-providers-fallback.js b/lib.esm/_tests/test-providers-fallback.js new file mode 100644 index 00000000..0f1f5acc --- /dev/null +++ b/lib.esm/_tests/test-providers-fallback.js @@ -0,0 +1,64 @@ +import assert from "assert"; +import { isError, makeError, AbstractProvider, FallbackProvider, Network } from "../index.js"; +const network = Network.from("mainnet"); +function stall(duration) { + return new Promise((resolve) => { setTimeout(resolve, duration); }); +} +export class MockProvider extends AbstractProvider { + _perform; + constructor(perform) { + super(network, { cacheTimeout: -1 }); + this._perform = perform; + } + async _detectNetwork() { return network; } + async perform(req) { + return await this._perform(req); + } +} +describe("Test Fallback broadcast", function () { + const txHash = "0xe9fb92945282cf04f7bb3027d690fdaab6d601c99a7cdd0a5eb41d1a5c0893d5"; + async function test(actions) { + const tx = "0x00f8788223288202898504a817c8008504a817c800825208940aff86a125b29b25a9e418c2fb64f1753532c0ca88016345785d8a000080c001a0711d47f0f6828721f336430ca87277534d0134de5f04ce3629085f8d5371c129a061c4838dec40c296cfad6fe771d502c26e209089124e6f702c64353b3ca195c1"; + const providers = actions.map(({ timeout, error }) => { + return new MockProvider(async (r) => { + if (r.method === "getBlockNumber") { + return 1; + } + if (r.method === "broadcastTransaction") { + await stall(timeout); + if (error) { + throw error; + } + return txHash; + } + throw new Error(`unhandled method: ${r.method}`); + }); + }); + ; + const provider = new FallbackProvider(providers); + return await provider.broadcastTransaction('0,1', tx); + } + it("picks late non-failed broadcasts", async function () { + const result = await test([ + { timeout: 200, error: makeError("already seen", "UNKNOWN_ERROR") }, + { timeout: 4000, error: makeError("already seen", "UNKNOWN_ERROR") }, + { timeout: 400 }, + ]); + assert(result.hash === txHash, "result.hash === txHash"); + }); + it("insufficient funds short-circuit broadcast", async function () { + await assert.rejects(async function () { + const result = await test([ + { timeout: 200, error: makeError("is broke", "INSUFFICIENT_FUNDS") }, + { timeout: 400, error: makeError("is broke", "INSUFFICIENT_FUNDS") }, + { timeout: 800 }, + { timeout: 1000 }, + ]); + console.log(result); + }, function (error) { + assert(isError(error, "INSUFFICIENT_FUNDS")); + return true; + }); + }); +}); +//# sourceMappingURL=test-providers-fallback.js.map \ No newline at end of file diff --git a/lib.esm/_tests/test-providers-fallback.js.map b/lib.esm/_tests/test-providers-fallback.js.map new file mode 100644 index 00000000..980cc260 --- /dev/null +++ b/lib.esm/_tests/test-providers-fallback.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test-providers-fallback.js","sourceRoot":"","sources":["../../src.ts/_tests/test-providers-fallback.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EACH,OAAO,EAAE,SAAS,EAElB,gBAAgB,EAAE,gBAAgB,EAAE,OAAO,EAC9C,MAAM,aAAa,CAAC;AAQrB,MAAM,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,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AC,CAAC;AACP,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/lib.esm/_tests/types.d.ts b/lib.esm/_tests/types.d.ts new file mode 100644 index 00000000..fcd151ca --- /dev/null +++ b/lib.esm/_tests/types.d.ts @@ -0,0 +1,218 @@ +export type TestCaseAbiVerbose = { + type: "address" | "hexstring" | "number" | "string"; + value: string; +} | { + type: "boolean"; + value: boolean; +} | { + type: "array"; + value: Array; +} | { + type: "object"; + value: Array; +}; +export interface TestCaseAbi { + name: string; + type: string; + value: any; + verbose: TestCaseAbiVerbose; + bytecode: string; + encoded: string; +} +export interface TestCaseAccount { + name: string; + privateKey: string; + address: string; + icap: string; +} +export type TestCaseCreate = { + sender: string; + creates: Array<{ + name: string; + nonce: number; + address: string; + }>; +}; +export type TestCaseCreate2 = { + sender: string; + creates: Array<{ + name: string; + salt: string; + initCode: string; + initCodeHash: string; + address: string; + }>; +}; +export interface TestCaseHash { + name: string; + data: string; + sha256: string; + sha512: string; + ripemd160: string; + keccak256: string; +} +export interface TestCasePbkdf { + name: string; + password: string; + salt: string; + dkLen: number; + pbkdf2: { + iterations: number; + algorithm: "sha256" | "sha512"; + key: string; + }; + scrypt: { + N: number; + r: number; + p: number; + key: string; + }; +} +export interface TestCaseHmac { + name: string; + data: string; + key: string; + algorithm: "sha256" | "sha512"; + hmac: string; +} +export interface TestCaseHash { + name: string; + data: string; + sha256: string; + sha512: string; + ripemd160: string; + keccak256: string; +} +export interface TestCaseNamehash { + name: string; + ensName: string; + error?: string; + namehash?: string; +} +export interface TestCaseTypedDataDomain { + name?: string; + version?: string; + chainId?: number; + verifyingContract?: string; + salt?: string; +} +export interface TestCaseTypedDataType { + name: string; + type: string; +} +export interface TestCaseTypedData { + name: string; + domain: TestCaseTypedDataDomain; + primaryType: string; + types: Record>; + data: any; + encoded: string; + digest: string; + privateKey?: string; + signature?: string; +} +export interface TestCaseSolidityHash { + name: string; + types: Array; + keccak256: string; + ripemd160: string; + sha256: string; + values: Array; +} +export interface TestCaseUnit { + name: string; + wei: string; + quais: string; + ether_format: string; + kwei?: string; + mwei?: string; + gwei?: string; + szabo?: string; + finney?: string; + finney_format?: string; + szabo_format?: string; + gwei_format?: string; + mwei_format?: string; + kwei_format?: string; +} +export type NestedHexString = string | Array; +export interface TestCaseRlp { + name: string; + encoded: string; + decoded: NestedHexString; +} +export interface TestCaseTransactionTx { + to?: string; + from: string; + nonce?: number; + gasLimit?: string; + gasPrice?: string; + maxFeePerGas?: string; + maxPriorityFeePerGas?: string; + data?: string; + value?: string; + accessList?: Array<{ + address: string; + storageKeys: Array; + }>; + chainId?: string; +} +export interface TestCaseTransactionSig { + r: string; + s: string; + v: string; +} +export interface TestCaseTransaction { + name: string; + transaction: TestCaseTransactionTx; + privateKey: string; + unsignedLegacy: string; + signedLegacy: string; + unsignedEip155: string; + signedEip155: string; + unsignedBerlin: string; + signedBerlin: string; + unsignedLondon: string; + signedLondon: string; + signatureLegacy: TestCaseTransactionSig; + signatureEip155: TestCaseTransactionSig; + signatureBerlin: TestCaseTransactionSig; + signatureLondon: TestCaseTransactionSig; +} +export interface TestCaseMnemonicNode { + path: string; + chainCode: string; + depth: number; + index: number; + parentFingerprint: string; + fingerprint: string; + publicKey: string; + privateKey: string; + xpriv: string; + xpub: string; +} +export interface TestCaseMnemonic { + name: string; + phrase: string; + phraseHash: string; + password: string; + locale: string; + entropy: string; + seed: string; + nodes: Array; +} +export interface TestCaseWallet { + name: string; + filename: string; + type: string; + address: string; + password: string; + content: string; +} +export interface TestCaseWordlist { + name: string; + filename: string; + locale: string; + content: string; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/lib.esm/_tests/types.d.ts.map b/lib.esm/_tests/types.d.ts.map new file mode 100644 index 00000000..53aa7770 --- /dev/null +++ b/lib.esm/_tests/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src.ts/_tests/types.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,kBAAkB,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--git a/lib.esm/_tests/types.js.map b/lib.esm/_tests/types.js.map new file mode 100644 index 00000000..68216b0f --- /dev/null +++ b/lib.esm/_tests/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src.ts/_tests/types.ts"],"names":[],"mappings":"AA6PC,CAAC"} \ No newline at end of file diff --git a/lib.esm/constants/shards.d.ts.map b/lib.esm/constants/shards.d.ts.map new file mode 100644 index 00000000..09ab3283 --- /dev/null +++ b/lib.esm/constants/shards.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"shards.d.ts","sourceRoot":"","sources":["../../src.ts/constants/shards.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,SAAS;;;;;;GAuErB,CAAC"} \ No newline at end of file diff --git a/lib.esm/constants/shards.js b/lib.esm/constants/shards.js new file mode 100644 index 00000000..3fca26af --- /dev/null +++ b/lib.esm/constants/shards.js @@ -0,0 +1,73 @@ +export const ShardData = [ + { + name: "Cyprus One", + nickname: 'cyprus1', + shard: "zone-0-0", + context: 2, + byte: "0x00" //0000 0000 region-0 zone-0 + }, + { + name: "Cyprus Two", + nickname: 'cyprus2', + shard: "zone-0-1", + context: 2, + byte: "0x01" // 0000 0001 region-0 zone-1 + }, + { + name: "Cyprus Three", + nickname: 'cyprus3', + shard: "zone-0-2", + context: 2, + byte: "0x02" // 0000 0010 region-0 zone-2 + }, + { + name: "Paxos One", + nickname: 'paxos1', + shard: "zone-1-0", + context: 2, + byte: "0x10" // 0001 0000 region-1 zone-0 + }, + { + name: "Paxos Two", + nickname: 'paxos2', + shard: "zone-1-1", + context: 2, + byte: "0x11" // 0001 0001 region-1 zone-1 + }, + { + name: "Paxos Three", + nickname: 'paxos3', + shard: "zone-1-2", + context: 2, + byte: "0x12" // 0001 0010 region-1 zone-2 + }, + { + name: "Hydra One", + nickname: 'hydra1', + shard: "zone-2-0", + context: 2, + byte: "0x20" // 0010 0000 region-2 zone-0 + }, + { + name: "Hydra Two", + nickname: 'hydra2', + shard: "zone-2-1", + context: 2, + byte: "0x21" // 0010 0001 region-2 zone-1 + }, + { + name: "Hydra Three", + nickname: 'hydra3', + shard: "zone-2-2", + context: 2, + byte: "0x22" // 0010 0010 region-2 zone-2 + }, + { + name: "Prime", + nickname: 'prime', + shard: "prime", + context: 2, + byte: "0x" + } +]; +//# sourceMappingURL=shards.js.map \ No newline at end of file diff --git a/lib.esm/constants/shards.js.map b/lib.esm/constants/shards.js.map new file mode 100644 index 00000000..941d338e --- /dev/null +++ b/lib.esm/constants/shards.js.map @@ -0,0 +1 @@ +{"version":3,"file":"shards.js","sourceRoot":"","sources":["../../src.ts/constants/shards.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB;QACI,IAAI,EAAE,YAAY;QAClB,QAAQ,EAAE,SAAS;QACnB,KAAK,EAAE,UAAU;QACjB,OAAO,EAAE,CAAC;QACV,IAAI,EAAE,MAAM,CAAC,2BAA2B;KAC3C;IACD;QACI,IAAI,EAAE,YAAY;QAClB,QAAQ,EAAE,SAAS;QACnB,KAAK,EAAE,UAAU;QACjB,OAAO,EAAE,CAAC;QACV,IAAI,EAAE,MAAM,CAAC,4BAA4B;KAC5C;IACD;QACI,IAAI,EAAE,cAAc;QACpB,QAAQ,EAAE,SAAS;QACnB,KAAK,EAAE,UAAU;QACjB,OAAO,EAAE,CAAC;QACV,IAAI,EAAE,MAAM,CAAC,4BAA4B;KAC5C;IACD;QACI,IAAI,EAAE,WAAW;QACjB,QAAQ,EAAE,QAAQ;QAClB,KAAK,EAAE,UAAU;QACjB,OAAO,EAAE,CAAC;QACV,IAAI,EAAE,MAAM,CAAC,4BAA4B;KAC5C;IACD;QACI,IAAI,EAAE,WAAW;QACjB,QAAQ,EAAE,QAAQ;QAClB,KAAK,EAAE,UAAU;QACjB,OAAO,EAAE,CAAC;QACV,IAAI,EAAE,MAAM,CAAC,4BAA4B;KAC5C;IACD;QACI,IAAI,EAAE,aAAa;QACnB,QAAQ,EAAE,QAAQ;QAClB,KAAK,EAAE,UAAU;QACjB,OAAO,EAAE,CAAC;QACV,IAAI,EAAE,MAAM,CAAC,4BAA4B;KAC5C;IACD;QACI,IAAI,EAAE,WAAW;QACjB,QAAQ,EAAE,QAAQ;QAClB,KAAK,EAAE,UAAU;QACjB,OAAO,EAAE,CAAC;QACV,IAAI,EAAE,MAAM,CAAC,4BAA4B;KAC5C;IACD;QACI,IAAI,EAAE,WAAW;QACjB,QAAQ,EAAE,QAAQ;QAClB,KAAK,EAAE,UAAU;QACjB,OAAO,EAAE,CAAC;QACV,IAAI,EAAE,MAAM,CAAC,4BAA4B;KAC5C;IACD;QACI,IAAI,EAAE,aAAa;QACnB,QAAQ,EAAE,QAAQ;QAClB,KAAK,EAAE,UAAU;QACjB,OAAO,EAAE,CAAC;QACV,IAAI,EAAE,MAAM,CAAC,4BAA4B;KAC5C;IACD;QACI,IAAI,EAAE,OAAO;QACb,QAAQ,EAAE,OAAO;QACjB,KAAK,EAAE,OAAO;QACd,OAAO,EAAE,CAAC;QACV,IAAI,EAAE,IAAI;KACb;CACF,CAAC"} \ No newline at end of file diff --git a/lib.esm/contract/contract.d.ts b/lib.esm/contract/contract.d.ts new file mode 100644 index 00000000..2a0a7be8 --- /dev/null +++ b/lib.esm/contract/contract.d.ts @@ -0,0 +1,168 @@ +import { Interface } from "../abi/index.js"; +import { Log, TransactionResponse } from "../providers/provider.js"; +import { ContractTransactionResponse, EventLog } from "./wrappers.js"; +import type { EventFragment, FunctionFragment, InterfaceAbi, ParamType } from "../abi/index.js"; +import type { Addressable } from "../address/index.js"; +import type { EventEmitterable, Listener } from "../utils/index.js"; +import type { BlockTag, ContractRunner } from "../providers/index.js"; +import type { ContractEventName, ContractInterface, ContractMethod, ContractEvent, ContractTransaction, WrappedFallback } from "./types.js"; +/** + * @_ignore: + */ +export declare function copyOverrides(arg: any, allowed?: Array): Promise>; +/** + * @_ignore: + */ +export declare function resolveArgs(_runner: null | ContractRunner, inputs: ReadonlyArray, args: Array): Promise>; +declare const internal: unique symbol; +export declare class BaseContract implements Addressable, EventEmitterable { + /** + * The target to connect to. + * + * This can be an address, ENS name or any [[Addressable]], such as + * another contract. To get the resovled address, use the ``getAddress`` + * method. + */ + readonly target: string | Addressable; + /** + * The contract Interface. + */ + readonly interface: Interface; + /** + * The connected runner. This is generally a [[Provider]] or a + * [[Signer]], which dictates what operations are supported. + * + * For example, a **Contract** connected to a [[Provider]] may + * only execute read-only operations. + */ + readonly runner: null | ContractRunner; + /** + * All the Events available on this contract. + */ + readonly filters: Record; + /** + * @_ignore: + */ + readonly [internal]: any; + /** + * The fallback or receive function if any. + */ + readonly fallback: null | WrappedFallback; + /** + * Creates a new contract connected to %%target%% with the %%abi%% and + * optionally connected to a %%runner%% to perform operations on behalf + * of. + */ + constructor(target: string | Addressable, abi: Interface | InterfaceAbi, runner?: null | ContractRunner, _deployTx?: null | TransactionResponse); + /** + * Return a new Contract instance with the same target and ABI, but + * a different %%runner%%. + */ + connect(runner: null | ContractRunner): BaseContract; + /** + * Return a new Contract instance with the same ABI and runner, but + * a different %%target%%. + */ + attach(target: string | Addressable): BaseContract; + /** + * Return the resolved address of this Contract. + */ + getAddress(): Promise; + /** + * Return the deployed bytecode or null if no bytecode is found. + */ + getDeployedCode(): Promise; + /** + * Resolve to this Contract once the bytecode has been deployed, or + * resolve immediately if already deployed. + */ + waitForDeployment(): Promise; + /** + * Return the transaction used to deploy this contract. + * + * This is only available if this instance was returned from a + * [[ContractFactory]]. + */ + deploymentTransaction(): null | ContractTransactionResponse; + /** + * Return the function for a given name. This is useful when a contract + * method name conflicts with a JavaScript name such as ``prototype`` or + * when using a Contract programatically. + */ + getFunction(key: string | FunctionFragment): T; + /** + * Return the event for a given name. This is useful when a contract + * event name conflicts with a JavaScript name such as ``prototype`` or + * when using a Contract programatically. + */ + getEvent(key: string | EventFragment): ContractEvent; + /** + * @_ignore: + */ + queryTransaction(hash: string): Promise>; + /** + * Provide historic access to event data for %%event%% in the range + * %%fromBlock%% (default: ``0``) to %%toBlock%% (default: ``"latest"``) + * inclusive. + */ + queryFilter(shard: string, event: ContractEventName, fromBlock?: BlockTag, toBlock?: BlockTag): Promise>; + /** + * Add an event %%listener%% for the %%event%%. + */ + on(event: ContractEventName, listener: Listener): Promise; + /** + * Add an event %%listener%% for the %%event%%, but remove the listener + * after it is fired once. + */ + once(event: ContractEventName, listener: Listener): Promise; + /** + * Emit an %%event%% calling all listeners with %%args%%. + * + * Resolves to ``true`` if any listeners were called. + */ + emit(event: ContractEventName, ...args: Array): Promise; + /** + * Resolves to the number of listeners of %%event%% or the total number + * of listeners if unspecified. + */ + listenerCount(event?: ContractEventName): Promise; + /** + * Resolves to the listeners subscribed to %%event%% or all listeners + * if unspecified. + */ + listeners(event?: ContractEventName): Promise>; + /** + * Remove the %%listener%% from the listeners for %%event%% or remove + * all listeners if unspecified. + */ + off(event: ContractEventName, listener?: Listener): Promise; + /** + * Remove all the listeners for %%event%% or remove all listeners if + * unspecified. + */ + removeAllListeners(event?: ContractEventName): Promise; + /** + * Alias for [on]. + */ + addListener(event: ContractEventName, listener: Listener): Promise; + /** + * Alias for [off]. + */ + removeListener(event: ContractEventName, listener: Listener): Promise; + /** + * Create a new Class for the %%abi%%. + */ + static buildClass(abi: Interface | InterfaceAbi): new (target: string, runner?: null | ContractRunner) => BaseContract & Omit; + /** + * Create a new BaseContract with a specified Interface. + */ + static from(target: string, abi: Interface | InterfaceAbi, runner?: null | ContractRunner): BaseContract & Omit; +} +declare const Contract_base: new (target: string, abi: Interface | InterfaceAbi, runner?: ContractRunner | null | undefined) => BaseContract & Omit; +/** + * A [[BaseContract]] with no type guards on its methods or events. + */ +export declare class Contract extends Contract_base { +} +export {}; +//# sourceMappingURL=contract.d.ts.map \ No newline at end of file diff --git a/lib.esm/contract/contract.d.ts.map b/lib.esm/contract/contract.d.ts.map new file mode 100644 index 00000000..bd14a80e --- /dev/null +++ b/lib.esm/contract/contract.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cont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UAAU,CAAC,CAAC,GAAG,iBAAiB,EAAE,GAAG,EAAE,SAAS,GAAG,YAAY,GAAG,KAAK,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,IAAI,GAAG,cAAc,KAAK,YAAY,GAAG,IAAI,CAAC,CAAC,EAAE,MAAM,YAAY,CAAC;IAS3K;;OAEG;IACH,MAAM,CAAC,IAAI,CAAC,CAAC,GAAG,iBAAiB,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,SAAS,GAAG,YAAY,EAAE,MAAM,CAAC,EAAE,IAAI,GAAG,cAAc,GAAG,YAAY,GAAG,IAAI,CAAC,CAAC,EAAE,MAAM,YAAY,CAAC;CAKhK;;AAMD;;GAEG;AACH,qBAAa,QAAS,SAAQ,aAAe;CAAI"} \ No newline at end of file diff --git a/lib.esm/contract/contract.js b/lib.esm/contract/contract.js new file mode 100644 index 00000000..6144b413 --- /dev/null +++ b/lib.esm/contract/contract.js @@ -0,0 +1,959 @@ +import { Interface, Typed } from "../abi/index.js"; +import { isAddressable, resolveAddress } from "../address/index.js"; +// import from provider.ts instead of index.ts to prevent circular dep +// from quaiscanProvider +import { copyRequest, Log } from "../providers/provider.js"; +import { defineProperties, getBigInt, isCallException, isHexString, resolveProperties, isError, makeError, assert, assertArgument } from "../utils/index.js"; +import { ContractEventPayload, ContractUnknownEventPayload, ContractTransactionResponse, EventLog, UndecodedEventLog } from "./wrappers.js"; +const BN_0 = BigInt(0); +function canCall(value) { + return (value && typeof (value.call) === "function"); +} +function canEstimate(value) { + return (value && typeof (value.estimateGas) === "function"); +} +function canResolve(value) { + return (value && typeof (value.resolveName) === "function"); +} +function canSend(value) { + return (value && typeof (value.sendTransaction) === "function"); +} +function getResolver(value) { + if (value != null) { + if (canResolve(value)) { + return value; + } + if (value.provider) { + return value.provider; + } + } + return undefined; +} +class PreparedTopicFilter { + #filter; + fragment; + constructor(contract, fragment, args) { + defineProperties(this, { fragment }); + if (fragment.inputs.length < args.length) { + throw new Error("too many arguments"); + } + // Recursively descend into args and resolve any addresses + const runner = getRunner(contract.runner, "resolveName"); + const resolver = canResolve(runner) ? runner : null; + this.#filter = (async function () { + const resolvedArgs = await Promise.all(fragment.inputs.map((param, index) => { + const arg = args[index]; + if (arg == null) { + return null; + } + return param.walkAsync(args[index], (type, value) => { + if (type === "address") { + if (Array.isArray(value)) { + return Promise.all(value.map((v) => resolveAddress(v, resolver))); + } + return resolveAddress(value, resolver); + } + return value; + }); + })); + return contract.interface.encodeFilterTopics(fragment, resolvedArgs); + })(); + } + getTopicFilter() { + return this.#filter; + } +} +// A = Arguments passed in as a tuple +// R = The result type of the call (i.e. if only one return type, +// the qualified type, otherwise Result) +// D = The type the default call will return (i.e. R for view/pure, +// TransactionResponse otherwise) +//export interface ContractMethod = Array, R = any, D extends R | ContractTransactionResponse = ContractTransactionResponse> { +function getRunner(value, feature) { + if (value == null) { + return null; + } + if (typeof (value[feature]) === "function") { + return value; + } + if (value.provider && typeof (value.provider[feature]) === "function") { + return value.provider; + } + return null; +} +function getProvider(value) { + if (value == null) { + return null; + } + return value.provider || null; +} +/** + * @_ignore: + */ +export async function copyOverrides(arg, allowed) { + // Make sure the overrides passed in are a valid overrides object + const _overrides = Typed.dereference(arg, "overrides"); + assertArgument(typeof (_overrides) === "object", "invalid overrides parameter", "overrides", arg); + // Create a shallow copy (we'll deep-ify anything needed during normalizing) + const overrides = copyRequest(_overrides); + assertArgument(overrides.to == null || (allowed || []).indexOf("to") >= 0, "cannot override to", "overrides.to", overrides.to); + assertArgument(overrides.data == null || (allowed || []).indexOf("data") >= 0, "cannot override data", "overrides.data", overrides.data); + // Resolve any from + if (overrides.from) { + overrides.from = overrides.from; + } + return overrides; +} +/** + * @_ignore: + */ +export async function resolveArgs(_runner, inputs, args) { + // Recursively descend into args and resolve any addresses + const runner = getRunner(_runner, "resolveName"); + const resolver = canResolve(runner) ? runner : null; + return await Promise.all(inputs.map((param, index) => { + return param.walkAsync(args[index], (type, value) => { + value = Typed.dereference(value, type); + if (type === "address") { + return resolveAddress(value, resolver); + } + return value; + }); + })); +} +function buildWrappedFallback(contract) { + const populateTransaction = async function (overrides) { + // If an overrides was passed in, copy it and normalize the values + const tx = (await copyOverrides(overrides, ["data"])); + tx.to = await contract.getAddress(); + if (tx.from) { + tx.from = await resolveAddress(tx.from, getResolver(contract.runner)); + } + const iface = contract.interface; + const noValue = (getBigInt((tx.value || BN_0), "overrides.value") === BN_0); + const noData = ((tx.data || "0x") === "0x"); + if (iface.fallback && !iface.fallback.payable && iface.receive && !noData && !noValue) { + assertArgument(false, "cannot send data to receive or send value to non-payable fallback", "overrides", overrides); + } + assertArgument(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data); + // Only allow payable contracts to set non-zero value + const payable = iface.receive || (iface.fallback && iface.fallback.payable); + assertArgument(payable || noValue, "cannot send value to non-payable fallback", "overrides.value", tx.value); + // Only allow fallback contracts to set non-empty data + assertArgument(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data); + return tx; + }; + const staticCall = async function (overrides) { + const runner = getRunner(contract.runner, "call"); + assert(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" }); + const tx = await populateTransaction(overrides); + try { + return await runner.call(tx); + } + catch (error) { + if (isCallException(error) && error.data) { + throw contract.interface.makeError(error.data, tx); + } + throw error; + } + }; + const send = async function (overrides) { + const runner = contract.runner; + assert(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" }); + const tx = await runner.sendTransaction(await populateTransaction(overrides)); + const provider = getProvider(contract.runner); + // @TODO: the provider can be null; make a custom dummy provider that will throw a + // meaningful error + return new ContractTransactionResponse(contract.interface, provider, tx); + }; + const estimateGas = async function (overrides) { + const runner = getRunner(contract.runner, "estimateGas"); + assert(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }); + return await runner.estimateGas(await populateTransaction(overrides)); + }; + const method = async (overrides) => { + return await send(overrides); + }; + defineProperties(method, { + _contract: contract, + estimateGas, + populateTransaction, + send, staticCall + }); + return method; +} +function buildWrappedMethod(contract, key) { + const getFragment = function (...args) { + const fragment = contract.interface.getFunction(key, args); + assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key, args } + }); + return fragment; + }; + const populateTransaction = async function (...args) { + const fragment = getFragment(...args); + // If an overrides was passed in, copy it and normalize the values + let overrides; + if (fragment.inputs.length + 1 === args.length) { + overrides = await copyOverrides(args.pop()); + const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args); + return Object.assign({}, overrides, await resolveProperties({ + to: contract.getAddress(), + data: contract.interface.encodeFunctionData(fragment, resolvedArgs) + })); + // if (overrides.from) { + // overrides.from = await resolveAddress(overrides.from, getResolver(contract.runner)); + // } + } + if (fragment.inputs.length !== args.length) { + throw new Error("internal error: fragment inputs doesn't match arguments; should not happen"); + } + const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args); + return await resolveProperties({ + to: contract.getAddress(), + from: args.pop().from, + data: contract.interface.encodeFunctionData(fragment, resolvedArgs) + }); + }; + const staticCall = async function (...args) { + const result = await staticCallResult(...args); + if (result.length === 1) { + return result[0]; + } + return result; + }; + const send = async function (...args) { + const runner = contract.runner; + assert(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" }); + const tx = await runner.sendTransaction(await populateTransaction(...args)); + const provider = getProvider(contract.runner); + // @TODO: the provider can be null; make a custom dummy provider that will throw a + // meaningful error + return new ContractTransactionResponse(contract.interface, provider, tx); + }; + const estimateGas = async function (...args) { + const runner = getRunner(contract.runner, "estimateGas"); + assert(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }); + return await runner.estimateGas(await populateTransaction(...args)); + }; + const staticCallResult = async function (...args) { + const runner = getRunner(contract.runner, "call"); + assert(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" }); + const tx = await populateTransaction(...args); + let result = "0x"; + try { + result = await runner.call(tx); + } + catch (error) { + if (isCallException(error) && error.data) { + throw contract.interface.makeError(error.data, tx); + } + throw error; + } + const fragment = getFragment(...args); + return contract.interface.decodeFunctionResult(fragment, result); + }; + const method = async (...args) => { + const fragment = getFragment(...args); + if (fragment.constant) { + return await staticCall(...args); + } + return await send(...args); + }; + defineProperties(method, { + name: contract.interface.getFunctionName(key), + _contract: contract, _key: key, + getFragment, + estimateGas, + populateTransaction, + send, staticCall, staticCallResult, + }); + // Only works on non-ambiguous keys (refined fragment is always non-ambiguous) + Object.defineProperty(method, "fragment", { + configurable: false, + enumerable: true, + get: () => { + const fragment = contract.interface.getFunction(key); + assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key } + }); + return fragment; + } + }); + return method; +} +function buildWrappedEvent(contract, key) { + const getFragment = function (...args) { + const fragment = contract.interface.getEvent(key, args); + assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key, args } + }); + return fragment; + }; + const method = function (...args) { + return new PreparedTopicFilter(contract, getFragment(...args), args); + }; + defineProperties(method, { + name: contract.interface.getEventName(key), + _contract: contract, _key: key, + getFragment + }); + // Only works on non-ambiguous keys (refined fragment is always non-ambiguous) + Object.defineProperty(method, "fragment", { + configurable: false, + enumerable: true, + get: () => { + const fragment = contract.interface.getEvent(key); + assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { key } + }); + return fragment; + } + }); + return method; +} +// The combination of TypeScrype, Private Fields and Proxies makes +// the world go boom; so we hide variables with some trickery keeping +// a symbol attached to each BaseContract which its sub-class (even +// via a Proxy) can reach and use to look up its internal values. +const internal = Symbol.for("_quaisInternal_contract"); +const internalValues = new WeakMap(); +function setInternal(contract, values) { + internalValues.set(contract[internal], values); +} +function getInternal(contract) { + return internalValues.get(contract[internal]); +} +function isDeferred(value) { + return (value && typeof (value) === "object" && ("getTopicFilter" in value) && + (typeof (value.getTopicFilter) === "function") && value.fragment); +} +async function getSubInfo(contract, event) { + let topics; + let fragment = null; + // Convert named events to topicHash and get the fragment for + // events which need deconstructing. + if (Array.isArray(event)) { + const topicHashify = function (name) { + if (isHexString(name, 32)) { + return name; + } + const fragment = contract.interface.getEvent(name); + assertArgument(fragment, "unknown fragment", "name", name); + return fragment.topicHash; + }; + // Array of Topics and Names; e.g. `[ "0x1234...89ab", "Transfer(address)" ]` + topics = event.map((e) => { + if (e == null) { + return null; + } + if (Array.isArray(e)) { + return e.map(topicHashify); + } + return topicHashify(e); + }); + } + else if (event === "*") { + topics = [null]; + } + else if (typeof (event) === "string") { + if (isHexString(event, 32)) { + // Topic Hash + topics = [event]; + } + else { + // Name or Signature; e.g. `"Transfer", `"Transfer(address)"` + fragment = contract.interface.getEvent(event); + assertArgument(fragment, "unknown fragment", "event", event); + topics = [fragment.topicHash]; + } + } + else if (isDeferred(event)) { + // Deferred Topic Filter; e.g. `contract.filter.Transfer(from)` + topics = await event.getTopicFilter(); + } + else if ("fragment" in event) { + // ContractEvent; e.g. `contract.filter.Transfer` + fragment = event.fragment; + topics = [fragment.topicHash]; + } + else { + assertArgument(false, "unknown event name", "event", event); + } + // Normalize topics and sort TopicSets + topics = topics.map((t) => { + if (t == null) { + return null; + } + if (Array.isArray(t)) { + const items = Array.from(new Set(t.map((t) => t.toLowerCase())).values()); + if (items.length === 1) { + return items[0]; + } + items.sort(); + return items; + } + return t.toLowerCase(); + }); + const tag = topics.map((t) => { + if (t == null) { + return "null"; + } + if (Array.isArray(t)) { + return t.join("|"); + } + return t; + }).join("&"); + return { fragment, tag, topics }; +} +async function hasSub(contract, event) { + const { subs } = getInternal(contract); + return subs.get((await getSubInfo(contract, event)).tag) || null; +} +async function getSub(contract, operation, event) { + // Make sure our runner can actually subscribe to events + const provider = getProvider(contract.runner); + assert(provider, "contract runner does not support subscribing", "UNSUPPORTED_OPERATION", { operation }); + const { fragment, tag, topics } = await getSubInfo(contract, event); + const { addr, subs } = getInternal(contract); + let sub = subs.get(tag); + if (!sub) { + const address = (addr ? addr : contract); + const filter = { address, topics }; + const listener = (log) => { + let foundFragment = fragment; + if (foundFragment == null) { + try { + foundFragment = contract.interface.getEvent(log.topics[0]); + } + catch (error) { } + } + // If fragment is null, we do not deconstruct the args to emit + if (foundFragment) { + const _foundFragment = foundFragment; + const args = fragment ? contract.interface.decodeEventLog(fragment, log.data, log.topics) : []; + emit(contract, event, args, (listener) => { + return new ContractEventPayload(contract, listener, event, _foundFragment, log); + }); + } + else { + emit(contract, event, [], (listener) => { + return new ContractUnknownEventPayload(contract, listener, event, log); + }); + } + }; + let starting = []; + const start = () => { + if (starting.length) { + return; + } + starting.push(provider.on(filter, listener)); + }; + const stop = async () => { + if (starting.length == 0) { + return; + } + let started = starting; + starting = []; + await Promise.all(started); + provider.off(filter, listener); + }; + sub = { tag, listeners: [], start, stop }; + subs.set(tag, sub); + } + return sub; +} +// We use this to ensure one emit resolves before firing the next to +// ensure correct ordering (note this cannot throw and just adds the +// notice to the event queu using setTimeout). +let lastEmit = Promise.resolve(); +async function _emit(contract, event, args, payloadFunc) { + await lastEmit; + const sub = await hasSub(contract, event); + if (!sub) { + return false; + } + const count = sub.listeners.length; + sub.listeners = sub.listeners.filter(({ listener, once }) => { + const passArgs = Array.from(args); + if (payloadFunc) { + passArgs.push(payloadFunc(once ? null : listener)); + } + try { + listener.call(contract, ...passArgs); + } + catch (error) { } + return !once; + }); + if (sub.listeners.length === 0) { + sub.stop(); + getInternal(contract).subs.delete(sub.tag); + } + return (count > 0); +} +async function emit(contract, event, args, payloadFunc) { + try { + await lastEmit; + } + catch (error) { } + const resultPromise = _emit(contract, event, args, payloadFunc); + lastEmit = resultPromise; + return await resultPromise; +} +const passProperties = ["then"]; +export class BaseContract { + /** + * The target to connect to. + * + * This can be an address, ENS name or any [[Addressable]], such as + * another contract. To get the resovled address, use the ``getAddress`` + * method. + */ + target; + /** + * The contract Interface. + */ + interface; + /** + * The connected runner. This is generally a [[Provider]] or a + * [[Signer]], which dictates what operations are supported. + * + * For example, a **Contract** connected to a [[Provider]] may + * only execute read-only operations. + */ + runner; + /** + * All the Events available on this contract. + */ + filters; + /** + * @_ignore: + */ + [internal]; + /** + * The fallback or receive function if any. + */ + fallback; + /** + * Creates a new contract connected to %%target%% with the %%abi%% and + * optionally connected to a %%runner%% to perform operations on behalf + * of. + */ + constructor(target, abi, runner, _deployTx) { + assertArgument(typeof (target) === "string" || isAddressable(target), "invalid value for Contract target", "target", target); + if (runner == null) { + runner = null; + } + const iface = Interface.from(abi); + defineProperties(this, { target, runner, interface: iface }); + Object.defineProperty(this, internal, { value: {} }); + let addrPromise; + let addr = null; + let deployTx = null; + if (_deployTx) { + const provider = getProvider(runner); + // @TODO: the provider can be null; make a custom dummy provider that will throw a + // meaningful error + deployTx = new ContractTransactionResponse(this.interface, provider, _deployTx); + } + let subs = new Map(); + // Resolve the target as the address + if (typeof (target) === "string") { + if (isHexString(target)) { + addr = target; + addrPromise = Promise.resolve(target); + } + else { + const resolver = getRunner(runner, "resolveName"); + if (!canResolve(resolver)) { + throw makeError("contract runner does not support name resolution", "UNSUPPORTED_OPERATION", { + operation: "resolveName" + }); + } + addrPromise = resolver.resolveName(target).then((addr) => { + if (addr == null) { + throw makeError("an ENS name used for a contract target must be correctly configured", "UNCONFIGURED_NAME", { + value: target + }); + } + getInternal(this).addr = addr; + return addr; + }); + } + } + else { + addrPromise = target.getAddress().then((addr) => { + if (addr == null) { + throw new Error("TODO"); + } + getInternal(this).addr = addr; + return addr; + }); + } + // Set our private values + setInternal(this, { addrPromise, addr, deployTx, subs }); + // Add the event filters + const filters = new Proxy({}, { + get: (target, prop, receiver) => { + // Pass important checks (like `then` for Promise) through + if (typeof (prop) === "symbol" || passProperties.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); + } + try { + return this.getEvent(prop); + } + catch (error) { + if (!isError(error, "INVALID_ARGUMENT") || error.argument !== "key") { + throw error; + } + } + return undefined; + }, + has: (target, prop) => { + // Pass important checks (like `then` for Promise) through + if (passProperties.indexOf(prop) >= 0) { + return Reflect.has(target, prop); + } + return Reflect.has(target, prop) || this.interface.hasEvent(String(prop)); + } + }); + defineProperties(this, { filters }); + defineProperties(this, { + fallback: ((iface.receive || iface.fallback) ? (buildWrappedFallback(this)) : null) + }); + // Return a Proxy that will respond to functions + return new Proxy(this, { + get: (target, prop, receiver) => { + if (typeof (prop) === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); + } + // Undefined properties should return undefined + try { + return target.getFunction(prop); + } + catch (error) { + if (!isError(error, "INVALID_ARGUMENT") || error.argument !== "key") { + throw error; + } + } + return undefined; + }, + has: (target, prop) => { + if (typeof (prop) === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) { + return Reflect.has(target, prop); + } + return target.interface.hasFunction(prop); + } + }); + } + /** + * Return a new Contract instance with the same target and ABI, but + * a different %%runner%%. + */ + connect(runner) { + return new BaseContract(this.target, this.interface, runner); + } + /** + * Return a new Contract instance with the same ABI and runner, but + * a different %%target%%. + */ + attach(target) { + return new BaseContract(target, this.interface, this.runner); + } + /** + * Return the resolved address of this Contract. + */ + async getAddress() { return await getInternal(this).addrPromise; } + /** + * Return the deployed bytecode or null if no bytecode is found. + */ + async getDeployedCode() { + const provider = getProvider(this.runner); + assert(provider, "runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "getDeployedCode" }); + const code = await provider.getCode(await this.getAddress()); + if (code === "0x") { + return null; + } + return code; + } + /** + * Resolve to this Contract once the bytecode has been deployed, or + * resolve immediately if already deployed. + */ + async waitForDeployment() { + // We have the deployement transaction; just use that (throws if deployement fails) + const deployTx = this.deploymentTransaction(); + if (deployTx) { + await deployTx.wait(); + return this; + } + // Check for code + const code = await this.getDeployedCode(); + if (code != null) { + return this; + } + // Make sure we can subscribe to a provider event + const provider = getProvider(this.runner); + assert(provider != null, "contract runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "waitForDeployment" }); + return new Promise((resolve, reject) => { + const checkCode = async () => { + try { + const code = await this.getDeployedCode(); + if (code != null) { + return resolve(this); + } + provider.once("block", checkCode); + } + catch (error) { + reject(error); + } + }; + checkCode(); + }); + } + /** + * Return the transaction used to deploy this contract. + * + * This is only available if this instance was returned from a + * [[ContractFactory]]. + */ + deploymentTransaction() { + return getInternal(this).deployTx; + } + /** + * Return the function for a given name. This is useful when a contract + * method name conflicts with a JavaScript name such as ``prototype`` or + * when using a Contract programatically. + */ + getFunction(key) { + if (typeof (key) !== "string") { + key = key.format(); + } + const func = buildWrappedMethod(this, key); + return func; + } + /** + * Return the event for a given name. This is useful when a contract + * event name conflicts with a JavaScript name such as ``prototype`` or + * when using a Contract programatically. + */ + getEvent(key) { + if (typeof (key) !== "string") { + key = key.format(); + } + return buildWrappedEvent(this, key); + } + /** + * @_ignore: + */ + async queryTransaction(hash) { + throw new Error("@TODO"); + } + /* + // @TODO: this is a non-backwards compatible change, but will be added + // in v7 and in a potential SmartContract class in an upcoming + // v6 release + async getTransactionReceipt(hash: string): Promise { + const provider = getProvider(this.runner); + assert(provider, "contract runner does not have a provider", + "UNSUPPORTED_OPERATION", { operation: "queryTransaction" }); + + const receipt = await provider.getTransactionReceipt(hash); + if (receipt == null) { return null; } + + return new ContractTransactionReceipt(this.interface, provider, receipt); + } + */ + /** + * Provide historic access to event data for %%event%% in the range + * %%fromBlock%% (default: ``0``) to %%toBlock%% (default: ``"latest"``) + * inclusive. + */ + async queryFilter(shard, event, fromBlock, toBlock) { + if (fromBlock == null) { + fromBlock = 0; + } + if (toBlock == null) { + toBlock = "latest"; + } + const { addr, addrPromise } = getInternal(this); + const address = (addr ? addr : (await addrPromise)); + const { fragment, topics } = await getSubInfo(this, event); + const filter = { address, topics, fromBlock, toBlock, shard: shard }; + const provider = getProvider(this.runner); + assert(provider, "contract runner does not have a provider", "UNSUPPORTED_OPERATION", { operation: "queryFilter" }); + return (await provider.getLogs(filter)).map((log) => { + let foundFragment = fragment; + if (foundFragment == null) { + try { + foundFragment = this.interface.getEvent(log.topics[0]); + } + catch (error) { } + } + if (foundFragment) { + try { + return new EventLog(log, this.interface, foundFragment); + } + catch (error) { + return new UndecodedEventLog(log, error); + } + } + return new Log(log, provider); + }); + } + /** + * Add an event %%listener%% for the %%event%%. + */ + async on(event, listener) { + const sub = await getSub(this, "on", event); + sub.listeners.push({ listener, once: false }); + sub.start(); + return this; + } + /** + * Add an event %%listener%% for the %%event%%, but remove the listener + * after it is fired once. + */ + async once(event, listener) { + const sub = await getSub(this, "once", event); + sub.listeners.push({ listener, once: true }); + sub.start(); + return this; + } + /** + * Emit an %%event%% calling all listeners with %%args%%. + * + * Resolves to ``true`` if any listeners were called. + */ + async emit(event, ...args) { + return await emit(this, event, args, null); + } + /** + * Resolves to the number of listeners of %%event%% or the total number + * of listeners if unspecified. + */ + async listenerCount(event) { + if (event) { + const sub = await hasSub(this, event); + if (!sub) { + return 0; + } + return sub.listeners.length; + } + const { subs } = getInternal(this); + let total = 0; + for (const { listeners } of subs.values()) { + total += listeners.length; + } + return total; + } + /** + * Resolves to the listeners subscribed to %%event%% or all listeners + * if unspecified. + */ + async listeners(event) { + if (event) { + const sub = await hasSub(this, event); + if (!sub) { + return []; + } + return sub.listeners.map(({ listener }) => listener); + } + const { subs } = getInternal(this); + let result = []; + for (const { listeners } of subs.values()) { + result = result.concat(listeners.map(({ listener }) => listener)); + } + return result; + } + /** + * Remove the %%listener%% from the listeners for %%event%% or remove + * all listeners if unspecified. + */ + async off(event, listener) { + const sub = await hasSub(this, event); + if (!sub) { + return this; + } + if (listener) { + const index = sub.listeners.map(({ listener }) => listener).indexOf(listener); + if (index >= 0) { + sub.listeners.splice(index, 1); + } + } + if (listener == null || sub.listeners.length === 0) { + sub.stop(); + getInternal(this).subs.delete(sub.tag); + } + return this; + } + /** + * Remove all the listeners for %%event%% or remove all listeners if + * unspecified. + */ + async removeAllListeners(event) { + if (event) { + const sub = await hasSub(this, event); + if (!sub) { + return this; + } + sub.stop(); + getInternal(this).subs.delete(sub.tag); + } + else { + const { subs } = getInternal(this); + for (const { tag, stop } of subs.values()) { + stop(); + subs.delete(tag); + } + } + return this; + } + /** + * Alias for [on]. + */ + async addListener(event, listener) { + return await this.on(event, listener); + } + /** + * Alias for [off]. + */ + async removeListener(event, listener) { + return await this.off(event, listener); + } + /** + * Create a new Class for the %%abi%%. + */ + static buildClass(abi) { + class CustomContract extends BaseContract { + constructor(address, runner = null) { + super(address, abi, runner); + } + } + return CustomContract; + } + ; + /** + * Create a new BaseContract with a specified Interface. + */ + static from(target, abi, runner) { + if (runner == null) { + runner = null; + } + const contract = new this(target, abi, runner); + return contract; + } +} +function _ContractBase() { + return BaseContract; +} +/** + * A [[BaseContract]] with no type guards on its methods or events. + */ +export class Contract extends _ContractBase() { +} +//# sourceMappingURL=contract.js.map \ No newline at end of file diff --git a/lib.esm/contract/contract.js.map b/lib.esm/contract/contract.js.map new file mode 100644 index 00000000..3938135c --- /dev/null +++ b/lib.esm/contract/contract.js.map @@ -0,0 +1 @@ +{"version":3,"file":"contract.js","sourceRoot":"","sources":["../../src.ts/contract/contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACpE,sEAAsE;AACtE,wBAAwB;AACxB,OAAO,EAAE,WAAW,EAAE,GAAG,EAAuB,MAAM,0BAA0B,CAAC;AACjF,OAAO,EACH,gBAAgB,EAAE,SAAS,EAAE,eAAe,EAAE,WAAW,EAAE,iBAAiB,EAC5E,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,cAAc,EAC7C,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACH,oBAAoB,EAAE,2BAA2B,EACjD,2BAA2B,EAC3B,QAAQ,EAAE,iBAAiB,EAC9B,MAAM,eAAe,CAAC;AAsBvB,MAAM,IAAI,GAAG,MAAM,CAA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AwB,EAAE,QAAkB;QAC1D,OAAO,MAAM,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IAC1C,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,cAAc,CAAC,KAAwB,EAAE,QAAkB;QAC7D,OAAO,MAAM,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IAC3C,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,UAAU,CAAwB,GAA6B;QAClE,MAAM,cAAe,SAAQ,YAAY;YACrC,YAAY,OAAe,EAAE,SAAgC,IAAI;gBAC7D,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC;YAChC,CAAC;SACJ;QACD,OAAO,cAAqB,CAAC;IACjC,CAAC;IAAA,CAAC;IAEF;;OAEG;IACH,MAAM,CAAC,IAAI,CAAwB,MAAc,EAAE,GAA6B,EAAE,MAA8B;QAC5G,IAAI,MAAM,IAAI,IAAI,EAAE;YAAE,MAAM,GAAG,IAAI,CAAC;SAAE;QACtC,MAAM,QAAQ,GAAG,IAAI,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,MAAM,CAAE,CAAC;QAChD,OAAO,QAAe,CAAC;IAC3B,CAAC;CACJ;AAED,SAAS,aAAa;IAClB,OAAO,YAAmB,CAAC;AAC/B,CAAC;AAED;;GAEG;AACH,MAAM,OAAO,QAAS,SAAQ,aAAa,EAAE;CAAI"} \ No newline at end of file diff --git a/lib.esm/contract/factory.d.ts.map b/lib.esm/contract/factory.d.ts.map new file mode 100644 index 00000000..6cba74a2 --- /dev/null +++ b/lib.esm/contract/factory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../../src.ts/contract/factory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAM5C,OAAO,EAAE,YAAY,EAA8B,MAAM,eAAe,CAAC;AAEzE,OAAO,KAAK,EA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AAC,EAAE,MAAM,YAAY,CAAC,CAAC;IAsBhK,MAAM,CAAC,kBAAkB,CAAC,WAAW,EAAE;QACnC,IAAI,EAAE,MAAM,CAAC;QACb,KAAK,EAAE,MAAM,CAAC;QACd,IAAI,EAAE,SAAS,CAAC;KACnB,GAAG,MAAM;IAQA,oBAAoB,CACtB,EAAE,EAAE,kBAAkB,GACrB,OAAO,CAAC,kBAAkB,CAAC;IAwBhC;;;OAGG;IACH,OAAO,CAAC,MAAM,EAAE,IAAI,GAAG,cAAc,GAAG,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC;IAI7D;;OAEG;IACH,MAAM,CAAC,YAAY,CAAC,CAAC,SAAS,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,iBAAiB,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,EAAE,cAAc,GAAG,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC;CAgB7I"} \ No newline at end of file diff --git a/lib.esm/contract/factory.js b/lib.esm/contract/factory.js new file mode 100644 index 00000000..bf1b9233 --- /dev/null +++ b/lib.esm/contract/factory.js @@ -0,0 +1,194 @@ +import { Interface } from "../abi/index.js"; +import { concat, defineProperties, getBytes, hexlify, assert, assertArgument } from "../utils/index.js"; +import { BaseContract, copyOverrides, resolveArgs } from "./contract.js"; +import { getShardForAddress, isUTXOAddress } from "../utils/index.js"; +import { Wallet, randomBytes } from "../quais.js"; +import { getContractAddress } from "../address/address.js"; +import { getStatic } from "../utils/properties.js"; +// A = Arguments to the constructor +// I = Interface of deployed contracts +/** + * A **ContractFactory** is used to deploy a Contract to the blockchain. + */ +export class ContractFactory { + /** + * The Contract Interface. + */ + interface; + /** + * The Contract deployment bytecode. Often called the initcode. + */ + bytecode; + /** + * The ContractRunner to deploy the Contract as. + */ + runner; + /** + * Create a new **ContractFactory** with %%abi%% and %%bytecode%%, + * optionally connected to %%runner%%. + * + * The %%bytecode%% may be the ``bytecode`` property within the + * standard Solidity JSON output. + */ + constructor(abi, bytecode, runner) { + const iface = Interface.from(abi); + // Dereference Solidity bytecode objects and allow a missing `0x`-prefix + if (bytecode instanceof Uint8Array) { + bytecode = hexlify(getBytes(bytecode)); + } + else { + if (typeof (bytecode) === "object") { + bytecode = bytecode.object; + } + if (!bytecode.startsWith("0x")) { + bytecode = "0x" + bytecode; + } + bytecode = hexlify(getBytes(bytecode)); + } + defineProperties(this, { + bytecode, interface: iface, runner: (runner || null) + }); + } + attach(target) { + return new BaseContract(target, this.interface, this.runner); + } + /** + * Resolves to the transaction to deploy the contract, passing %%args%% + * into the constructor. + */ + async getDeployTransaction(...args) { + let overrides; + const fragment = this.interface.deploy; + if (fragment.inputs.length + 1 === args.length) { + overrides = await copyOverrides(args.pop()); + const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args); + const data = concat([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]); + return Object.assign({}, overrides, { data }); + } + if (fragment.inputs.length !== args.length) { + throw new Error("incorrect number of arguments to constructor"); + } + const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args); + const data = concat([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]); + return Object.assign({}, args.pop().from, { data }); + } + // getDeployTransaction3(...args: Array): TransactionRequest { + // let tx: TransactionRequest = {}; + // // If we have 1 additional argument, we allow transaction overrides + // if ( + // args.length === this.interface.deploy.inputs.length + 1 && + // typeof args[args.length - 1] === "object" + // ) { + // //tx = shallowCopy(args.pop()); + // tx = copyOverrides(args.pop()); + // for (const key in tx) { + // if (!allowedTransactionKeys[key]) { + // throw new Error("unknown transaction override " + key); + // } + // } + // } + // // Do not allow these to be overridden in a deployment transaction + // ["data", "from", "to"].forEach((key) => { + // if ((tx)[key] == null) { + // return; + // } + // assertArgument(false, "cannot override " + key, key, (tx)[key]); + // }); + // if (tx.value) { + // const value = Number(tx.value) + // if ( value != 0 && !this.interface.deploy.payable) { + // assertArgument( + // false, + // "non-zero value provided to non-payable (or constructor) function", + // "value", value + // ); + // } + // } + // // // Make sure the call matches the constructor signature + // // logger.checkArgumentCount( + // // args.length, + // // this.interface.deploy.inputs.length, + // // " in Contract constructor" + // // ); + // // Set the data to the bytecode + the encoded constructor arguments + // tx.data = hexlify( + // concat([this.bytecode, this.interface.encodeDeploy(args)]) + // ); + // return tx; + // } + /** + * Resolves to the Contract deployed by passing %%args%% into the + * constructor. + * + * This will resovle to the Contract before it has been deployed to the + * network, so the [[BaseContract-waitForDeployment]] should be used before + * sending any transactions to it. + */ + async deploy(...args) { + const tx = await this.getDeployTransaction(...args); + assert(this.runner && typeof (this.runner.sendTransaction) === "function", "factory runner does not support sending transactions", "UNSUPPORTED_OPERATION", { + operation: "sendTransaction" + }); + if (this.runner instanceof Wallet) { + tx.from = this.runner.address; + } + const grindedTx = await this.grindContractAddress(tx); + console.log("grindedTx", grindedTx); + const sentTx = await this.runner.sendTransaction(grindedTx); + const address = getStatic(this.constructor, "getContractAddress")?.(tx); + //const address = getCreateAddress(sentTx); + return new BaseContract(address, this.interface, this.runner, sentTx); + } + static getContractAddress(transaction) { + return getContractAddress(transaction.from, BigInt(transaction.nonce), // Fix: Convert BigInt to bigint + transaction.data); + } + async grindContractAddress(tx) { + if (tx.nonce == null && tx.from) { + tx.nonce = await this.runner?.provider?.getTransactionCount(tx.from); + } + const sender = String(tx.from); + const toShard = getShardForAddress(sender); + var i = 0; + var startingData = tx.data; + while (i < 10000) { + var contractAddress = getContractAddress(sender, BigInt(tx.nonce || 0), tx.data || ''); + var contractShard = getShardForAddress(contractAddress); + console.log("contractAddress ", contractAddress); + var utxo = isUTXOAddress(contractAddress); + if (contractShard === toShard && !utxo) { + return tx; + } + var salt = randomBytes(32); + tx.data = hexlify(concat([String(startingData), salt])); + i++; + } + return tx; + } + /** + * Return a new **ContractFactory** with the same ABI and bytecode, + * but connected to %%runner%%. + */ + connect(runner) { + return new ContractFactory(this.interface, this.bytecode, runner); + } + /** + * Create a new **ContractFactory** from the standard Solidity JSON output. + */ + static fromSolidity(output, runner) { + assertArgument(output != null, "bad compiler output", "output", output); + if (typeof (output) === "string") { + output = JSON.parse(output); + } + const abi = output.abi; + let bytecode = ""; + if (output.bytecode) { + bytecode = output.bytecode; + } + else if (output.evm && output.evm.bytecode) { + bytecode = output.evm.bytecode; + } + return new this(abi, bytecode, runner); + } +} +//# sourceMappingURL=factory.js.map \ No newline at end of file diff --git a/lib.esm/contract/factory.js.map b/lib.esm/contract/factory.js.map new file mode 100644 index 00000000..3d37fa88 --- /dev/null +++ b/lib.esm/contract/factory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"factory.js","sourceRoot":"","sources":["../../src.ts/contract/factory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EACH,MAAM,EAAE,gBAAgB,EAAE,QAAQ,EAAE,OAAO,EAC3C,MAAM,EAAE,cAAc,EACzB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAMzE,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAKtE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAGnD,mCAAmC;AACnC,sCAAsC;AAEtC;;GAEG;AACH,MAAM,OAAO,eAAe;IAExB;;OAEG;IACM,SAAS,CAAa;IAE/B;;OAEG;IACM,QAAQ,CAAU;IAE3B;;OAEG;IACM,MAAM,CAAyB;IAExC;;;;;;OAMG;IACH,YAAY,GAA6B,EAAE,QAAwC,EAAE,MAA8B;QAC/G,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAGlC,wEAAwE;QACxE,IAAI,QAAQ,YAAY,UA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AE,MAAM,CAAC,CAAC;QAExE,IAAI,OAAM,CAAC,MAAM,CAAC,KAAK,QAAQ,EAAE;YAAE,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;SAAE;QAEjE,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC;QAEvB,IAAI,QAAQ,GAAG,EAAE,CAAC;QAClB,IAAI,MAAM,CAAC,QAAQ,EAAE;YACjB,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;SAC9B;aAAM,IAAI,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE;YAC1C,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;SAClC;QAED,OAAO,IAAI,IAAI,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;IAC3C,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/contract/types.d.ts b/lib.esm/contract/types.d.ts new file mode 100644 index 00000000..be2d954d --- /dev/null +++ b/lib.esm/contract/types.d.ts @@ -0,0 +1,193 @@ +import type { EventFragment, FunctionFragment, Result, Typed } from "../abi/index.js"; +import type { TransactionRequest, PreparedTransactionRequest, TopicFilter } from "../providers/index.js"; +import type { ContractTransactionResponse } from "./wrappers.js"; +/** + * The name for an event used for subscribing to Contract events. + * + * **``string``** - An event by name. The event must be non-ambiguous. + * The parameters will be dereferenced when passed into the listener. + * + * [[ContractEvent]] - A filter from the ``contract.filters``, which will + * pass only the EventPayload as a single parameter, which includes a + * ``.signature`` property that can be used to further filter the event. + * + * [[TopicFilter]] - A filter defined using the standard Ethereum API + * which provides the specific topic hash or topic hashes to watch for along + * with any additional values to filter by. This will only pass a single + * parameter to the listener, the EventPayload which will include additional + * details to refine by, such as the event name and signature. + * + * [[DeferredTopicFilter]] - A filter created by calling a [[ContractEvent]] + * with parameters, which will create a filter for a specific event + * signautre and dereference each parameter when calling the listener. + */ +export type ContractEventName = string | ContractEvent | TopicFilter | DeferredTopicFilter; +/** + * A Contract with no method constraints. + */ +export interface ContractInterface { + [name: string]: BaseContractMethod; +} +/** + * When creating a filter using the ``contract.filters``, this is returned. + */ +export interface DeferredTopicFilter { + getTopicFilter(): Promise; + fragment: EventFragment; +} +/** + * When populating a transaction this type is returned. + */ +export interface ContractTransaction extends PreparedTransactionRequest { + /** + * The target address. + */ + to: string; + /** + * The transaction data. + */ + data: string; + /** + * The from address, if any. + */ + from: string; +} +/** + * A deployment transaction for a contract. + */ +export interface ContractDeployTransaction extends Omit { +} +/** + * The overrides for a contract transaction. + */ +export interface Overrides extends Omit { +} +/** + * Arguments to a Contract method can always include an additional and + * optional overrides parameter. + * + * @_ignore: + */ +export type PostfixOverrides> = A | [...A, Overrides]; +/** + * Arguments to a Contract method can always include an additional and + * optional overrides parameter, and each parameter can optionally be + * [[Typed]]. + * + * @_ignore: + */ +export type ContractMethodArgs> = PostfixOverrides<{ + [I in keyof A]-?: A[I] | Typed; +}>; +/** + * A Contract method can be called directly, or used in various ways. + */ +export interface BaseContractMethod = Array, R = any, D extends R | ContractTransactionResponse = R | ContractTransactionResponse> { + (...args: ContractMethodArgs): Promise; + /** + * The name of the Contract method. + */ + name: string; + /** + * The fragment of the Contract method. This will throw on ambiguous + * method names. + */ + fragment: FunctionFragment; + /** + * Returns the fragment constrained by %%args%%. This can be used to + * resolve ambiguous method names. + */ + getFragment(...args: ContractMethodArgs): FunctionFragment; + /** + * Returns a populated transaction that can be used to perform the + * contract method with %%args%%. + */ + populateTransaction(...args: ContractMethodArgs): Promise; + /** + * Call the contract method with %%args%% and return the value. + * + * If the return value is a single type, it will be dereferenced and + * returned directly, otherwise the full Result will be returned. + */ + staticCall(...args: ContractMethodArgs): Promise; + /** + * Send a transaction for the contract method with %%args%%. + */ + send(...args: ContractMethodArgs): Promise; + /** + * Estimate the gas to send the contract method with %%args%%. + */ + estimateGas(...args: ContractMethodArgs): Promise; + /** + * Call the contract method with %%args%% and return the Result + * without any dereferencing. + */ + staticCallResult(...args: ContractMethodArgs): Promise; +} +/** + * A contract method on a Contract. + */ +export interface ContractMethod = Array, R = any, D extends R | ContractTransactionResponse = R | ContractTransactionResponse> extends BaseContractMethod { +} +/** + * A pure of view method on a Contract. + */ +export interface ConstantContractMethod, R = any> extends ContractMethod { +} +/** + * Each argument of an event is nullable (to indicate matching //any//. + * + * @_ignore: + */ +export type ContractEventArgs> = { + [I in keyof A]?: A[I] | Typed | null; +}; +export interface ContractEvent = Array> { + (...args: ContractEventArgs): DeferredTopicFilter; + /** + * The name of the Contract event. + */ + name: string; + /** + * The fragment of the Contract event. This will throw on ambiguous + * method names. + */ + fragment: EventFragment; + /** + * Returns the fragment constrained by %%args%%. This can be used to + * resolve ambiguous event names. + */ + getFragment(...args: ContractEventArgs): EventFragment; +} +/** + * A Fallback or Receive function on a Contract. + */ +export interface WrappedFallback { + (overrides?: Omit): Promise; + /** + * Returns a populated transaction that can be used to perform the + * fallback method. + * + * For non-receive fallback, ``data`` may be overridden. + */ + populateTransaction(overrides?: Omit): Promise; + /** + * Call the contract fallback and return the result. + * + * For non-receive fallback, ``data`` may be overridden. + */ + staticCall(overrides?: Omit): Promise; + /** + * Send a transaction to the contract fallback. + * + * For non-receive fallback, ``data`` may be overridden. + */ + send(overrides?: Omit): Promise; + /** + * Estimate the gas to send a transaction to the contract fallback. + * + * For non-receive fallback, ``data`` may be overridden. + */ + estimateGas(overrides?: Omit): Promise; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/lib.esm/contract/types.d.ts.map b/lib.esm/contract/types.d.ts.map new file mode 100644 index 00000000..8c805861 --- /dev/null +++ b/lib.esm/contract/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src.ts/contract/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACR,aAAa,EAAE,gBAAgB,EAAE,MAAM,EAAE,KAAK,EACjD,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EACR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,CAAC,EAAE,IAAI,CAAC,kBAAkB,EAAE,IAAI,CAAC,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;IAEvF;;;;OAIG;IACH,WAAW,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,kBAAkB,EAAE,IAAI,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAC5E"} \ No newline at end of file diff --git a/lib.esm/contract/types.js.map b/lib.esm/contract/types.js.map new file mode 100644 index 00000000..d88f0d6d --- /dev/null +++ b/lib.esm/contract/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src.ts/contract/types.ts"],"names":[],"mappings":"AAqCC,CAAC;AAuC4E,CAAC;AA4H9E,CAAC"} \ No newline at end of file diff --git a/lib.esm/contract/wrappers.d.ts b/lib.esm/contract/wrappers.d.ts new file mode 100644 index 00000000..e5af484f --- /dev/null +++ b/lib.esm/contract/wrappers.d.ts @@ -0,0 +1,143 @@ +import { Block, Log, TransactionReceipt, TransactionResponse } from "../providers/provider.js"; +import { EventPayload } from "../utils/index.js"; +import type { EventFragment, Interface, Result } from "../abi/index.js"; +import type { Listener } from "../utils/index.js"; +import type { Provider } from "../providers/index.js"; +import type { BaseContract } from "./contract.js"; +import type { ContractEventName } from "./types.js"; +/** + * An **EventLog** contains additional properties parsed from the [[Log]]. + */ +export declare class EventLog extends Log { + /** + * The Contract Interface. + */ + readonly interface: Interface; + /** + * The matching event. + */ + readonly fragment: EventFragment; + /** + * The parsed arguments passed to the event by ``emit``. + */ + readonly args: Result; + /** + * @_ignore: + */ + constructor(log: Log, iface: Interface, fragment: EventFragment); + /** + * The name of the event. + */ + get eventName(): string; + /** + * The signature of the event. + */ + get eventSignature(): string; +} +/** + * An **EventLog** contains additional properties parsed from the [[Log]]. + */ +export declare class UndecodedEventLog extends Log { + /** + * The error encounted when trying to decode the log. + */ + readonly error: Error; + /** + * @_ignore: + */ + constructor(log: Log, error: Error); +} +/** + * A **ContractTransactionReceipt** includes the parsed logs from a + * [[TransactionReceipt]]. + */ +export declare class ContractTransactionReceipt extends TransactionReceipt { + #private; + /** + * @_ignore: + */ + constructor(iface: Interface, provider: Provider, tx: TransactionReceipt); + /** + * The parsed logs for any [[Log]] which has a matching event in the + * Contract ABI. + */ + get logs(): Array; +} +/** + * A **ContractTransactionResponse** will return a + * [[ContractTransactionReceipt]] when waited on. + */ +export declare class ContractTransactionResponse extends TransactionResponse { + #private; + /** + * @_ignore: + */ + constructor(iface: Interface, provider: Provider, tx: TransactionResponse); + /** + * Resolves once this transaction has been mined and has + * %%confirms%% blocks including it (default: ``1``) with an + * optional %%timeout%%. + * + * This can resolve to ``null`` only if %%confirms%% is ``0`` + * and the transaction has not been mined, otherwise this will + * wait until enough confirmations have completed. + */ + wait(confirms?: number): Promise; +} +/** + * A **ContractUnknownEventPayload** is included as the last parameter to + * Contract Events when the event does not match any events in the ABI. + */ +export declare class ContractUnknownEventPayload extends EventPayload { + /** + * The log with no matching events. + */ + readonly log: Log; + /** + * @_event: + */ + constructor(contract: BaseContract, listener: null | Listener, filter: ContractEventName, log: Log); + /** + * Resolves to the block the event occured in. + */ + getBlock(shard: string): Promise; + /** + * Resolves to the transaction the event occured in. + */ + getTransaction(): Promise; + /** + * Resolves to the transaction receipt the event occured in. + */ + getTransactionReceipt(): Promise; +} +/** + * A **ContractEventPayload** is included as the last parameter to + * Contract Events when the event is known. + */ +export declare class ContractEventPayload extends ContractUnknownEventPayload { + /** + * The matching event. + */ + readonly fragment: EventFragment; + /** + * The log, with parsed properties. + */ + readonly log: EventLog; + /** + * The parsed arguments passed to the event by ``emit``. + */ + readonly args: Result; + /** + * @_ignore: + */ + constructor(contract: BaseContract, listener: null | Listener, filter: ContractEventName, fragment: EventFragment, _log: Log); + /** + * The event name. + */ + get eventName(): string; + /** + * The event signature. + */ + get eventSignature(): string; +} +//# sourceMappingURL=wrappers.d.ts.map \ No newline at end of file diff --git a/lib.esm/contract/wrappers.d.ts.map b/lib.esm/contract/wrappers.d.ts.map new file mode 100644 index 00000000..cd3ccc0d --- /dev/null +++ b/lib.esm/contract/wrappers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wrappers.d.ts","sourceRoot":"","sources":["../../src.ts/contract/wrappers.ts"],"names":[],"mappings":"AAEA,OAAO,EACH,KAAK,EAAE,GAAG,EAAE,kBAAkB,EAAE,mBAAmB,EACtD,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAoB,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEnE,OAAO,KAAK,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACxE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,EACR,QAAQ,EACX,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEpD;;GAEG;AACH,qBAAa,QAAS,SAAQ,GAAG;IAC7B;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAG,SAAS,CAAC;IAE/B;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAG,aAAa,CAAC;IAElC;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAG,MAAM,CAAC;IAEvB;;OAEG;gBACS,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,aAAa;IAM/D;;OAEG;IACH,IAAI,SAAS,IAAI,MAAM,CAA+B;IAEtD;;OAEG;IACH,IAAI,cAAc,IAAI,MAAM,CAAmC;CAClE;AAED;;GAEG;AACH,qBAAa,iBAAkB,SAAQ,GAAG;IAEtC;;OAEG;IACH,QAAQ,CAAC,KAAK,EAAG,KAAK,CAAC;IAEvB;;OAEG;gBACS,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK;CAIrC;AAED;;;GAGG;AACH,qBAAa,0BAA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AAQ,EAAE,aAAa,EAAE,IAAI,EAAE,GAAG;IAM5H;;OAEG;IACH,IAAI,SAAS,IAAI,MAAM,CAEtB;IAED;;OAEG;IACH,IAAI,cAAc,IAAI,MAAM,CAE3B;CACJ"} \ No newline at end of file diff --git a/lib.esm/contract/wrappers.js b/lib.esm/contract/wrappers.js new file mode 100644 index 00000000..e3c705a0 --- /dev/null +++ b/lib.esm/contract/wrappers.js @@ -0,0 +1,177 @@ +// import from provider.ts instead of index.ts to prevent circular dep +// from quaiscanProvider +import { Log, TransactionReceipt, TransactionResponse } from "../providers/provider.js"; +import { defineProperties, EventPayload } from "../utils/index.js"; +/** + * An **EventLog** contains additional properties parsed from the [[Log]]. + */ +export class EventLog extends Log { + /** + * The Contract Interface. + */ + interface; + /** + * The matching event. + */ + fragment; + /** + * The parsed arguments passed to the event by ``emit``. + */ + args; + /** + * @_ignore: + */ + constructor(log, iface, fragment) { + super(log, log.provider); + const args = iface.decodeEventLog(fragment, log.data, log.topics); + defineProperties(this, { args, fragment, interface: iface }); + } + /** + * The name of the event. + */ + get eventName() { return this.fragment.name; } + /** + * The signature of the event. + */ + get eventSignature() { return this.fragment.format(); } +} +/** + * An **EventLog** contains additional properties parsed from the [[Log]]. + */ +export class UndecodedEventLog extends Log { + /** + * The error encounted when trying to decode the log. + */ + error; + /** + * @_ignore: + */ + constructor(log, error) { + super(log, log.provider); + defineProperties(this, { error }); + } +} +/** + * A **ContractTransactionReceipt** includes the parsed logs from a + * [[TransactionReceipt]]. + */ +export class ContractTransactionReceipt extends TransactionReceipt { + #iface; + /** + * @_ignore: + */ + constructor(iface, provider, tx) { + super(tx, provider); + this.#iface = iface; + } + /** + * The parsed logs for any [[Log]] which has a matching event in the + * Contract ABI. + */ + get logs() { + return super.logs.map((log) => { + const fragment = log.topics.length ? this.#iface.getEvent(log.topics[0]) : null; + if (fragment) { + try { + return new EventLog(log, this.#iface, fragment); + } + catch (error) { + return new UndecodedEventLog(log, error); + } + } + return log; + }); + } +} +/** + * A **ContractTransactionResponse** will return a + * [[ContractTransactionReceipt]] when waited on. + */ +export class ContractTransactionResponse extends TransactionResponse { + #iface; + /** + * @_ignore: + */ + constructor(iface, provider, tx) { + super(tx, provider); + this.#iface = iface; + } + /** + * Resolves once this transaction has been mined and has + * %%confirms%% blocks including it (default: ``1``) with an + * optional %%timeout%%. + * + * This can resolve to ``null`` only if %%confirms%% is ``0`` + * and the transaction has not been mined, otherwise this will + * wait until enough confirmations have completed. + */ + async wait(confirms) { + const receipt = await super.wait(confirms); + if (receipt == null) { + return null; + } + return new ContractTransactionReceipt(this.#iface, this.provider, receipt); + } +} +/** + * A **ContractUnknownEventPayload** is included as the last parameter to + * Contract Events when the event does not match any events in the ABI. + */ +export class ContractUnknownEventPayload extends EventPayload { + /** + * The log with no matching events. + */ + log; + /** + * @_event: + */ + constructor(contract, listener, filter, log) { + super(contract, listener, filter); + defineProperties(this, { log }); + } + /** + * Resolves to the block the event occured in. + */ + async getBlock(shard) { + return await this.log.getBlock(shard); + } + /** + * Resolves to the transaction the event occured in. + */ + async getTransaction() { + return await this.log.getTransaction(); + } + /** + * Resolves to the transaction receipt the event occured in. + */ + async getTransactionReceipt() { + return await this.log.getTransactionReceipt(); + } +} +/** + * A **ContractEventPayload** is included as the last parameter to + * Contract Events when the event is known. + */ +export class ContractEventPayload extends ContractUnknownEventPayload { + /** + * @_ignore: + */ + constructor(contract, listener, filter, fragment, _log) { + super(contract, listener, filter, new EventLog(_log, contract.interface, fragment)); + const args = contract.interface.decodeEventLog(fragment, this.log.data, this.log.topics); + defineProperties(this, { args, fragment }); + } + /** + * The event name. + */ + get eventName() { + return this.fragment.name; + } + /** + * The event signature. + */ + get eventSignature() { + return this.fragment.format(); + } +} +//# sourceMappingURL=wrappers.js.map \ No newline at end of file diff --git a/lib.esm/contract/wrappers.js.map b/lib.esm/contract/wrappers.js.map new file mode 100644 index 00000000..3b210e05 --- /dev/null +++ b/lib.esm/contract/wrappers.js.map @@ -0,0 +1 @@ +{"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EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC;IACrE,CAAC;IAED;;OAEG;IACH,IAAI,SAAS;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;IAC9B,CAAC;IAED;;OAEG;IACH,IAAI,cAAc;QACd,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;IAClC,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/providers/abstract-provider.d.ts b/lib.esm/providers/abstract-provider.d.ts new file mode 100644 index 00000000..7d006601 --- /dev/null +++ b/lib.esm/providers/abstract-provider.d.ts @@ -0,0 +1,499 @@ +/** + * The available providers should suffice for most developers purposes, + * but the [[AbstractProvider]] class has many features which enable + * sub-classing it for specific purposes. + * + * @_section: api/providers/abstract-provider: Subclassing Provider [abstract-provider] + */ +import { FetchRequest } from "../utils/index.js"; +import { EnsResolver } from "./ens-resolver.js"; +import { Network } from "./network.js"; +import { Block, FeeData, Log, TransactionReceipt, TransactionResponse } from "./provider.js"; +import type { AddressLike } from "../address/index.js"; +import type { BigNumberish } from "../utils/index.js"; +import type { Listener } from "../utils/index.js"; +import type { Networkish } from "./network.js"; +import type { BlockParams, LogParams, TransactionReceiptParams, TransactionResponseParams } from "./formatting.js"; +import type { BlockTag, EventFilter, Filter, FilterByBlockHash, OrphanFilter, PreparedTransactionRequest, Provider, ProviderEvent, TransactionRequest } from "./provider.js"; +/** + * The types of additional event values that can be emitted for the + * ``"debug"`` event. + */ +export type DebugEventAbstractProvider = { + action: "sendCcipReadFetchRequest"; + request: FetchRequest; + index: number; + urls: Array; +} | { + action: "receiveCcipReadFetchResult"; + request: FetchRequest; + result: any; +} | { + action: "receiveCcipReadFetchError"; + request: FetchRequest; + result: any; +} | { + action: "sendCcipReadCall"; + transaction: { + to: string; + data: string; + }; +} | { + action: "receiveCcipReadCallResult"; + transaction: { + to: string; + data: string; + }; + result: string; +} | { + action: "receiveCcipReadCallError"; + transaction: { + to: string; + data: string; + }; + error: Error; +}; +/** + * The value passed to the [[AbstractProvider-_getSubscriber]] method. + * + * Only developers sub-classing [[AbstractProvider[[ will care about this, + * if they are modifying a low-level feature of how subscriptions operate. + */ +export type Subscription = { + type: "block" | "close" | "debug" | "error" | "finalized" | "network" | "pending" | "safe"; + tag: string; +} | { + type: "transaction"; + tag: string; + hash: string; +} | { + type: "event"; + tag: string; + filter: EventFilter; +} | { + type: "orphan"; + tag: string; + filter: OrphanFilter; +}; +/** + * A **Subscriber** manages a subscription. + * + * Only developers sub-classing [[AbstractProvider[[ will care about this, + * if they are modifying a low-level feature of how subscriptions operate. + */ +export interface Subscriber { + /** + * Called initially when a subscriber is added the first time. + */ + start(): void; + /** + * Called when there are no more subscribers to the event. + */ + stop(): void; + /** + * Called when the subscription should pause. + * + * If %%dropWhilePaused%%, events that occur while paused should not + * be emitted [[resume]]. + */ + pause(dropWhilePaused?: boolean): void; + /** + * Resume a paused subscriber. + */ + resume(): void; + /** + * The frequency (in ms) to poll for events, if polling is used by + * the subscriber. + * + * For non-polling subscribers, this must return ``undefined``. + */ + pollingInterval?: number; +} +/** + * An **UnmanagedSubscriber** is useful for events which do not require + * any additional management, such as ``"debug"`` which only requires + * emit in synchronous event loop triggered calls. + */ +export declare class UnmanagedSubscriber implements Subscriber { + /** + * The name fof the event. + */ + name: string; + /** + * Create a new UnmanagedSubscriber with %%name%%. + */ + constructor(name: string); + start(): void; + stop(): void; + pause(dropWhilePaused?: boolean): void; + resume(): void; +} +/** + * An **AbstractPlugin** is used to provide additional internal services + * to an [[AbstractProvider]] without adding backwards-incompatible changes + * to method signatures or other internal and complex logic. + */ +export interface AbstractProviderPlugin { + /** + * The reverse domain notation of the plugin. + */ + readonly name: string; + /** + * Creates a new instance of the plugin, connected to %%provider%%. + */ + connect(provider: AbstractProvider): AbstractProviderPlugin; +} +/** + * A normalized filter used for [[PerformActionRequest]] objects. + */ +export type PerformActionFilter = { + address?: string | Array; + topics?: Array>; + fromBlock?: BlockTag; + toBlock?: BlockTag; + shard: string; +} | { + address?: string | Array; + topics?: Array>; + blockHash?: string; + shard: string; +}; +/** + * A normalized transactions used for [[PerformActionRequest]] objects. + */ +export interface PerformActionTransaction extends PreparedTransactionRequest { + /** + * The ``to`` address of the transaction. + */ + to?: string; + /** + * The sender of the transaction. + */ + from: string; +} +/** + * The [[AbstractProvider]] methods will normalize all values and pass this + * type to [[AbstractProvider-_perform]]. + */ +export type PerformActionRequest = { + method: "broadcastTransaction"; + signedTransaction: string; + shard: string; +} | { + method: "call"; + transaction: PerformActionTransaction; + blockTag: BlockTag; + shard?: string; +} | { + method: "chainId"; + shard?: string; +} | { + method: "estimateGas"; + transaction: PerformActionTransaction; + shard?: string; +} | { + method: "getBalance"; + address: string; + blockTag: BlockTag; + shard: string; +} | { + method: "getBlock"; + blockTag: BlockTag; + includeTransactions: boolean; + shard: string; +} | { + method: "getBlock"; + blockHash: string; + includeTransactions: boolean; + shard: string; +} | { + method: "getBlockNumber"; + shard?: string; +} | { + method: "getCode"; + address: string; + blockTag: BlockTag; + shard: string; +} | { + method: "getGasPrice"; + txType: boolean; + shard?: string; +} | { + method: "getLogs"; + filter: PerformActionFilter; + shard: string; +} | { + method: "getMaxPriorityFeePerGas"; + shard?: string; +} | { + method: "getStorage"; + address: string; + position: bigint; + blockTag: BlockTag; + shard: string; +} | { + method: "getTransaction"; + hash: string; + shard: string; +} | { + method: "getTransactionCount"; + address: string; + blockTag: BlockTag; + shard: string; +} | { + method: "getTransactionReceipt"; + hash: string; + shard: string; +} | { + method: "getTransactionResult"; + hash: string; + shard: string; +} | { + method: "getRunningLocations"; + shard?: string; +} | { + method: "getProtocolTrieExpansionCount"; + shard: string; +} | { + method: "getQiRateAtBlock"; + blockTag: BlockTag; + amt: number; + shard: string; +} | { + method: "getQuaiRateAtBlock"; + blockTag: BlockTag; + amt: number; + shard: string; +}; +/** + * Options for configuring some internal aspects of an [[AbstractProvider]]. + * + * **``cacheTimeout``** - how long to cache a low-level ``_perform`` + * for, based on input parameters. This reduces the number of calls + * to getChainId and getBlockNumber, but may break test chains which + * can perform operations (internally) synchronously. Use ``-1`` to + * disable, ``0`` will only buffer within the same event loop and + * any other value is in ms. (default: ``250``) + */ +export type AbstractProviderOptions = { + cacheTimeout?: number; + pollingInterval?: number; +}; +/** + * An **AbstractProvider** provides a base class for other sub-classes to + * implement the [[Provider]] API by normalizing input arguments and + * formatting output results as well as tracking events for consistent + * behaviour on an eventually-consistent network. + */ +export declare class AbstractProvider implements Provider { + #private; + _urlMap: Map; + /** + * Create a new **AbstractProvider** connected to %%network%%, or + * use the various network detection capabilities to discover the + * [[Network]] if necessary. + */ + constructor(_network?: "any" | Networkish, options?: AbstractProviderOptions); + initUrlMap(urls: string[] | FetchRequest): Promise; + shardBytes(shard: string): string; + get connect(): FetchRequest[]; + shardFromAddress(_address: AddressLike): Promise; + shardFromHash(hash: string): string; + getLatestQuaiRate(shard: string, amt?: number): Promise; + getQuaiRateAtBlock(shard: string, blockTag: BlockTag, amt?: number): Promise; + getLatestQiRate(shard: string, amt?: number): Promise; + getQiRateAtBlock(shard: string, blockTag: BlockTag, amt?: number): Promise; + get pollingInterval(): number; + /** + * Returns ``this``, to allow an **AbstractProvider** to implement + * the [[ContractRunner]] interface. + */ + get provider(): this; + /** + * Returns all the registered plug-ins. + */ + get plugins(): Array; + /** + * Attach a new plug-in. + */ + attachPlugin(plugin: AbstractProviderPlugin): this; + /** + * Get a plugin by name. + */ + getPlugin(name: string): null | T; + /** + * Prevent any CCIP-read operation, regardless of whether requested + * in a [[call]] using ``enableCcipRead``. + */ + get disableCcipRead(): boolean; + set disableCcipRead(value: boolean); + /** + * Resolves to the data for executing the CCIP-read operations. + */ + ccipReadFetch(tx: PerformActionTransaction, calldata: string, urls: Array): Promise; + /** + * Provides the opportunity for a sub-class to wrap a block before + * returning it, to add additional properties or an alternate + * sub-class of [[Block]]. + */ + _wrapBlock(value: BlockParams, network: Network): Block; + /** + * Provides the opportunity for a sub-class to wrap a log before + * returning it, to add additional properties or an alternate + * sub-class of [[Log]]. + */ + _wrapLog(value: LogParams, network: Network): Log; + /** + * Provides the opportunity for a sub-class to wrap a transaction + * receipt before returning it, to add additional properties or an + * alternate sub-class of [[TransactionReceipt]]. + */ + _wrapTransactionReceipt(value: TransactionReceiptParams, network: Network): TransactionReceipt; + /** + * Provides the opportunity for a sub-class to wrap a transaction + * response before returning it, to add additional properties or an + * alternate sub-class of [[TransactionResponse]]. + */ + _wrapTransactionResponse(tx: TransactionResponseParams, network: Network): TransactionResponse; + /** + * Resolves to the Network, forcing a network detection using whatever + * technique the sub-class requires. + * + * Sub-classes **must** override this. + */ + _detectNetwork(shard?: string): Promise; + /** + * Sub-classes should use this to perform all built-in operations. All + * methods sanitizes and normalizes the values passed into this. + * + * Sub-classes **must** override this. + */ + _perform(req: PerformActionRequest): Promise; + getBlockNumber(shard?: string): Promise; + /** + * Returns or resolves to the address for %%address%%, resolving ENS + * names and [[Addressable]] objects and returning if already an + * address. + */ + _getAddress(address: AddressLike): string | Promise; + /** + * Returns or resolves to a valid block tag for %%blockTag%%, resolving + * negative values and returning if already a valid block tag. + */ + _getBlockTag(shard?: string, blockTag?: BlockTag): string | Promise; + /** + * Returns or resolves to a filter for %%filter%%, resolving any ENS + * names or [[Addressable]] object and returning if already a valid + * filter. + */ + _getFilter(filter: Filter | FilterByBlockHash): PerformActionFilter | Promise; + /** + * Returns or resovles to a transaction for %%request%%, resolving + * any ENS names or [[Addressable]] and returning if already a valid + * transaction. + */ + _getTransactionRequest(_request: TransactionRequest): PerformActionTransaction | Promise; + getNetwork(shard?: string): Promise; + getRunningLocations(shard?: string): Promise; + getProtocolTrieExpansionCount(shard: string): Promise; + getFeeData(shard?: string, txType?: boolean): Promise; + estimateGas(_tx: TransactionRequest): Promise; + call(_tx: TransactionRequest): Promise; + getBalance(address: AddressLike, blockTag?: BlockTag): Promise; + getTransactionCount(address: AddressLike, blockTag?: BlockTag): Promise; + getCode(address: AddressLike, blockTag?: BlockTag): Promise; + getStorage(address: AddressLike, _position: BigNumberish, blockTag?: BlockTag): Promise; + broadcastTransaction(shard: string, signedTx: string): Promise; + getBlock(shard: string, block: BlockTag | string, prefetchTxs?: boolean): Promise; + getTransaction(hash: string): Promise; + getTransactionReceipt(hash: string): Promise; + getTransactionResult(hash: string): Promise; + getLogs(_filter: Filter | FilterByBlockHash): Promise>; + _getProvider(chainId: number): AbstractProvider; + getResolver(name: string): Promise; + getAvatar(name: string): Promise; + resolveName(name: string): Promise; + lookupAddress(address: string): Promise; + waitForTransaction(hash: string, _confirms?: null | number, timeout?: null | number): Promise; + waitForBlock(shard: string, blockTag?: BlockTag): Promise; + /** + * Clear a timer created using the [[_setTimeout]] method. + */ + _clearTimeout(timerId: number): void; + /** + * Create a timer that will execute %%func%% after at least %%timeout%% + * (in ms). If %%timeout%% is unspecified, then %%func%% will execute + * in the next event loop. + * + * [Pausing](AbstractProvider-paused) the provider will pause any + * associated timers. + */ + _setTimeout(_func: () => void, timeout?: number): number; + /** + * Perform %%func%% on each subscriber. + */ + _forEachSubscriber(func: (s: Subscriber) => void): void; + /** + * Sub-classes may override this to customize subscription + * implementations. + */ + _getSubscriber(sub: Subscription): Subscriber; + /** + * If a [[Subscriber]] fails and needs to replace itself, this + * method may be used. + * + * For example, this is used for providers when using the + * ``eth_getFilterChanges`` method, which can return null if state + * filters are not supported by the backend, allowing the Subscriber + * to swap in a [[PollingEventSubscriber]]. + */ + _recoverSubscriber(oldSub: Subscriber, newSub: Subscriber): void; + on(event: ProviderEvent, listener: Listener): Promise; + once(event: ProviderEvent, listener: Listener): Promise; + emit(event: ProviderEvent, ...args: Array): Promise; + listenerCount(event?: ProviderEvent): Promise; + listeners(event?: ProviderEvent): Promise>; + off(event: ProviderEvent, listener?: Listener): Promise; + removeAllListeners(event?: ProviderEvent): Promise; + addListener(event: ProviderEvent, listener: Listener): Promise; + removeListener(event: ProviderEvent, listener: Listener): Promise; + /** + * If this provider has been destroyed using the [[destroy]] method. + * + * Once destroyed, all resources are reclaimed, internal event loops + * and timers are cleaned up and no further requests may be sent to + * the provider. + */ + get destroyed(): boolean; + /** + * Sub-classes may use this to shutdown any sockets or release their + * resources and reject any pending requests. + * + * Sub-classes **must** call ``super.destroy()``. + */ + destroy(): void; + /** + * Whether the provider is currently paused. + * + * A paused provider will not emit any events, and generally should + * not make any requests to the network, but that is up to sub-classes + * to manage. + * + * Setting ``paused = true`` is identical to calling ``.pause(false)``, + * which will buffer any events that occur while paused until the + * provider is unpaused. + */ + get paused(): boolean; + set paused(pause: boolean); + /** + * Pause the provider. If %%dropWhilePaused%%, any events that occur + * while paused are dropped, otherwise all events will be emitted once + * the provider is unpaused. + */ + pause(dropWhilePaused?: boolean): void; + /** + * Resume the provider. + */ + resume(): void; +} +//# sourceMappingURL=abstract-provider.d.ts.map \ No newline at end of file diff --git a/lib.esm/providers/abstract-provider.d.ts.map b/lib.esm/providers/abstract-provider.d.ts.map new file mode 100644 index 00000000..dae3efc8 --- /dev/null +++ b/lib.esm/providers/abstract-provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"abstract-provider.d.ts","sourceRoot":"","sources":["../../src.ts/providers/abstract-provider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAeH,OAAO,EAIH,YAAY,EAGf,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAIhD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAe,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAE1G,OAAO,KAAK,EAAe,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAElD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAG/C,OAAO,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AAC,OAAO,CAAC;IAuBjE,aAAa,CAAC,KAAK,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC;IAcrD,SAAS,CAAC,KAAK,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAa1D,GAAG,CAAC,KAAK,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAiB7D,kBAAkB,CAAC,KAAK,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;IAexD,WAAW,CAAC,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAKpE,cAAc,CAAC,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAI7E;;;;;;OAMG;IACH,IAAI,SAAS,IAAI,OAAO,CAEvB;IAED;;;;;OAKG;IACH,OAAO,IAAI,IAAI;IAYf;;;;;;;;;;OAUG;IACH,IAAI,MAAM,IAAI,OAAO,CAAwC;IAC7D,IAAI,MAAM,CAAC,KAAK,EAAE,OAAO,EAQxB;IAED;;;;OAIG;IACH,KAAK,CAAC,eAAe,CAAC,EAAE,OAAO,GAAG,IAAI;IAsBtC;;OAEG;IACH,MAAM,IAAI,IAAI;CAiBjB"} \ No newline at end of file diff --git a/lib.esm/providers/abstract-provider.js b/lib.esm/providers/abstract-provider.js new file mode 100644 index 00000000..4bd1c2ea --- /dev/null +++ b/lib.esm/providers/abstract-provider.js @@ -0,0 +1,1473 @@ +/** + * The available providers should suffice for most developers purposes, + * but the [[AbstractProvider]] class has many features which enable + * sub-classing it for specific purposes. + * + * @_section: api/providers/abstract-provider: Subclassing Provider [abstract-provider] + */ +// @TODO +// Event coalescence +// When we register an event with an async value (e.g. address is a Signer +// or ENS name), we need to add it immeidately for the Event API, but also +// need time to resolve the address. Upon resolving the address, we need to +// migrate the listener to the static event. We also need to maintain a map +// of Signer/ENS name to address so we can sync respond to listenerCount. +import { getAddress, resolveAddress } from "../address/index.js"; +import { ShardData, ZeroAddress } from "../constants/index.js"; +import { Contract } from "../contract/index.js"; +import { namehash } from "../hash/index.js"; +import { Transaction } from "../transaction/index.js"; +import { hexlify, isHexString, getBigInt, getNumber, isError, makeError, assert, assertArgument, FetchRequest, toQuantity, defineProperties, EventPayload, resolveProperties, } from "../utils/index.js"; +import { EnsResolver } from "./ens-resolver.js"; +import { formatBlock, formatLog, formatTransactionReceipt, formatTransactionResponse } from "./format.js"; +import { Network } from "./network.js"; +import { copyRequest, Block, FeeData, Log, TransactionReceipt, TransactionResponse } from "./provider.js"; +// Constants +const BN_2 = BigInt(2); +const MAX_CCIP_REDIRECTS = 10; +function isPromise(value) { + return (value && typeof (value.then) === "function"); +} +function getTag(prefix, value) { + return prefix + ":" + JSON.stringify(value, (k, v) => { + if (v == null) { + return "null"; + } + if (typeof (v) === "bigint") { + return `bigint:${v.toString()}`; + } + if (typeof (v) === "string") { + return v.toLowerCase(); + } + // Sort object keys + if (typeof (v) === "object" && !Array.isArray(v)) { + const keys = Object.keys(v); + keys.sort(); + return keys.reduce((accum, key) => { + accum[key] = v[key]; + return accum; + }, {}); + } + return v; + }); +} +/** + * An **UnmanagedSubscriber** is useful for events which do not require + * any additional management, such as ``"debug"`` which only requires + * emit in synchronous event loop triggered calls. + */ +export class UnmanagedSubscriber { + /** + * The name fof the event. + */ + name; + /** + * Create a new UnmanagedSubscriber with %%name%%. + */ + constructor(name) { defineProperties(this, { name }); } + start() { } + stop() { } + pause(dropWhilePaused) { } + resume() { } +} +function copy(value) { + return JSON.parse(JSON.stringify(value)); +} +function concisify(items) { + items = Array.from((new Set(items)).values()); + items.sort(); + return items; +} +async function getSubscription(_event, provider) { + if (_event == null) { + throw new Error("invalid event"); + } + // Normalize topic array info an EventFilter + if (Array.isArray(_event)) { + _event = { topics: _event }; + } + if (typeof (_event) === "string") { + switch (_event) { + case "block": + case "debug": + case "error": + case "finalized": + case "network": + case "pending": + case "safe": { + return { type: _event, tag: _event }; + } + } + } + if (isHexString(_event, 32)) { + const hash = _event.toLowerCase(); + return { type: "transaction", tag: getTag("tx", { hash }), hash }; + } + if (_event.orphan) { + const event = _event; + // @TODO: Should lowercase and whatnot things here instead of copy... + return { type: "orphan", tag: getTag("orphan", event), filter: copy(event) }; + } + if ((_event.address || _event.topics)) { + const event = _event; + const filter = { + topics: ((event.topics || []).map((t) => { + if (t == null) { + return null; + } + if (Array.isArray(t)) { + return concisify(t.map((t) => t.toLowerCase())); + } + return t.toLowerCase(); + })) + }; + if (event.address) { + const addresses = []; + const promises = []; + const addAddress = (addr) => { + if (isHexString(addr)) { + addresses.push(addr); + } + else { + promises.push((async () => { + addresses.push(await resolveAddress(addr, provider)); + })()); + } + }; + if (Array.isArray(event.address)) { + event.address.forEach(addAddress); + } + else { + addAddress(event.address); + } + if (promises.length) { + await Promise.all(promises); + } + filter.address = concisify(addresses.map((a) => a.toLowerCase())); + } + return { filter, tag: getTag("event", filter), type: "event" }; + } + assertArgument(false, "unknown ProviderEvent", "event", _event); +} +function getTime() { return (new Date()).getTime(); } +const defaultOptions = { + cacheTimeout: 250, + pollingInterval: 4000 +}; +// type CcipArgs = { +// sender: string; +// urls: Array; +// calldata: string; +// selector: string; +// extraData: string; +// errorArgs: Array +// }; +/** + * An **AbstractProvider** provides a base class for other sub-classes to + * implement the [[Provider]] API by normalizing input arguments and + * formatting output results as well as tracking events for consistent + * behaviour on an eventually-consistent network. + */ +export class AbstractProvider { + _urlMap; + #connect; + #subs; + #plugins; + // null=unpaused, true=paused+dropWhilePaused, false=paused + #pausedState; + #destroyed; + #networkPromise; + #anyNetwork; + #performCache; + // The most recent block number if running an event or -1 if no "block" event + #lastBlockNumber; + #nextTimer; + #timers; + #disableCcipRead; + #options; + /** + * Create a new **AbstractProvider** connected to %%network%%, or + * use the various network detection capabilities to discover the + * [[Network]] if necessary. + */ + constructor(_network, options) { + this.#options = Object.assign({}, defaultOptions, options || {}); + if (_network === "any") { + this.#anyNetwork = true; + this.#networkPromise = null; + } + else if (_network) { + const network = Network.from(_network); + this.#anyNetwork = false; + this.#networkPromise = Promise.resolve(network); + setTimeout(() => { this.emit("network", network, null); }, 0); + } + else { + this.#anyNetwork = false; + this.#networkPromise = null; + } + this.#lastBlockNumber = -1; + this.#performCache = new Map(); + this.#subs = new Map(); + this.#plugins = new Map(); + this.#pausedState = null; + this.#destroyed = false; + this.#nextTimer = 1; + this.#timers = new Map(); + this.#disableCcipRead = false; + this.#connect = []; + this._urlMap = new Map(); + } + async initUrlMap(urls) { + if (urls instanceof FetchRequest) { + const primeUrl = urls.url.split(":")[0] + ":" + urls.url.split(":")[1] + ":9001"; + this._urlMap.set('0x', primeUrl); + urls.url = primeUrl; + this.#connect.push(urls); + const shards = await this.getRunningLocations(); + shards.forEach((shard) => { + const port = 9100 + 20 * shard[0] + shard[1]; + this._urlMap.set(`0x${shard[0].toString(16)}${shard[1].toString(16)}`, urls.url.split(":")[0] + ":" + urls.url.split(":")[1] + ":" + port); + }); + return; + } + for (const url of urls) { + const primeUrl = url.split(":")[0] + ":" + url.split(":")[1] + ":9001"; + this._urlMap.set('0x', primeUrl); + this.#connect.push(new FetchRequest(primeUrl)); + const shards = await this.getRunningLocations(); // Now waits for the previous to complete + shards.forEach((shard) => { + const port = 9100 + 20 * shard[0] + shard[1]; + this._urlMap.set(`0x${shard[0].toString(16)}${shard[1].toString(16)}`, url.split(":")[0] + ":" + url.split(":")[1] + ":" + port); + }); + } + } + shardBytes(shard) { + return ShardData.find(it => it.name == shard || + it.byte == shard || + it.nickname == shard || + it.shard == shard)?.byte || ''; + } + get connect() { return this.#connect; } + async shardFromAddress(_address) { + let address = this._getAddress(_address); + return (await address).slice(0, 4); + } + shardFromHash(hash) { + return hash.slice(0, 4); + } + async getLatestQuaiRate(shard, amt = 1) { + const blockNumber = await this.getBlockNumber(shard); + return this.getQuaiRateAtBlock(shard, blockNumber, amt); + } + async getQuaiRateAtBlock(shard, blockTag, amt = 1) { + let resolvedBlockTag = this._getBlockTag(shard, blockTag); + if (typeof resolvedBlockTag !== "string") { + resolvedBlockTag = await resolvedBlockTag; + } + return await this.#perform({ + method: "getQuaiRateAtBlock", + blockTag: resolvedBlockTag, + amt, + shard: shard + }); + } + async getLatestQiRate(shard, amt = 1) { + const blockNumber = await this.getBlockNumber(shard); + return this.getQiRateAtBlock(shard, blockNumber, amt); + } + async getQiRateAtBlock(shard, blockTag, amt = 1) { + let resolvedBlockTag = this._getBlockTag(shard, blockTag); + if (typeof resolvedBlockTag !== "string") { + resolvedBlockTag = await resolvedBlockTag; + } + return await this.#perform({ + method: "getQiRateAtBlock", + blockTag: resolvedBlockTag, + amt, + shard: shard + }); + } + get pollingInterval() { return this.#options.pollingInterval; } + /** + * Returns ``this``, to allow an **AbstractProvider** to implement + * the [[ContractRunner]] interface. + */ + get provider() { return this; } + /** + * Returns all the registered plug-ins. + */ + get plugins() { + return Array.from(this.#plugins.values()); + } + /** + * Attach a new plug-in. + */ + attachPlugin(plugin) { + if (this.#plugins.get(plugin.name)) { + throw new Error(`cannot replace existing plugin: ${plugin.name} `); + } + this.#plugins.set(plugin.name, plugin.connect(this)); + return this; + } + /** + * Get a plugin by name. + */ + getPlugin(name) { + return (this.#plugins.get(name)) || null; + } + /** + * Prevent any CCIP-read operation, regardless of whether requested + * in a [[call]] using ``enableCcipRead``. + */ + get disableCcipRead() { return this.#disableCcipRead; } + set disableCcipRead(value) { this.#disableCcipRead = !!value; } + // Shares multiple identical requests made during the same 250ms + async #perform(req) { + const timeout = this.#options.cacheTimeout; + // Caching disabled + if (timeout < 0) { + return await this._perform(req); + } + // Create a tag + const tag = getTag(req.method, req); + let perform = this.#performCache.get(tag); + if (!perform) { + perform = this._perform(req); + this.#performCache.set(tag, perform); + setTimeout(() => { + if (this.#performCache.get(tag) === perform) { + this.#performCache.delete(tag); + } + }, timeout); + } + return await perform; + } + /** + * Resolves to the data for executing the CCIP-read operations. + */ + async ccipReadFetch(tx, calldata, urls) { + if (this.disableCcipRead || urls.length === 0 || tx.to == null) { + return null; + } + const sender = tx.to.toLowerCase(); + const data = calldata.toLowerCase(); + const errorMessages = []; + for (let i = 0; i < urls.length; i++) { + const url = urls[i]; + // URL expansion + const href = url.replace("{sender}", sender).replace("{data}", data); + // If no {data} is present, use POST; otherwise GET + //const json: string | null = (url.indexOf("{data}") >= 0) ? null: JSON.stringify({ data, sender }); + //const result = await fetchJson({ url: href, errorPassThrough: true }, json, (value, response) => { + // value.status = response.statusCode; + // return value; + //}); + const request = new FetchRequest(href); + if (url.indexOf("{data}") === -1) { + request.body = { data, sender }; + } + this.emit("debug", { action: "sendCcipReadFetchRequest", request, index: i, urls }); + let errorMessage = "unknown error"; + const resp = await request.send(); + try { + const result = resp.bodyJson; + if (result.data) { + this.emit("debug", { action: "receiveCcipReadFetchResult", request, result }); + return result.data; + } + if (result.message) { + errorMessage = result.message; + } + this.emit("debug", { action: "receiveCcipReadFetchError", request, result }); + } + catch (error) { } + // 4xx indicates the result is not present; stop + assert(resp.statusCode < 400 || resp.statusCode >= 500, `response not found during CCIP fetch: ${errorMessage}`, "OFFCHAIN_FAULT", { reason: "404_MISSING_RESOURCE", transaction: tx, info: { url, errorMessage } }); + // 5xx indicates server issue; try the next url + errorMessages.push(errorMessage); + } + assert(false, `error encountered during CCIP fetch: ${errorMessages.map((m) => JSON.stringify(m)).join(", ")}`, "OFFCHAIN_FAULT", { + reason: "500_SERVER_ERROR", + transaction: tx, info: { urls, errorMessages } + }); + } + /** + * Provides the opportunity for a sub-class to wrap a block before + * returning it, to add additional properties or an alternate + * sub-class of [[Block]]. + */ + _wrapBlock(value, network) { + return new Block(formatBlock(value), this); + } + /** + * Provides the opportunity for a sub-class to wrap a log before + * returning it, to add additional properties or an alternate + * sub-class of [[Log]]. + */ + _wrapLog(value, network) { + return new Log(formatLog(value), this); + } + /** + * Provides the opportunity for a sub-class to wrap a transaction + * receipt before returning it, to add additional properties or an + * alternate sub-class of [[TransactionReceipt]]. + */ + _wrapTransactionReceipt(value, network) { + return new TransactionReceipt(formatTransactionReceipt(value), this); + } + /** + * Provides the opportunity for a sub-class to wrap a transaction + * response before returning it, to add additional properties or an + * alternate sub-class of [[TransactionResponse]]. + */ + _wrapTransactionResponse(tx, network) { + return new TransactionResponse(formatTransactionResponse(tx), this); + } + /** + * Resolves to the Network, forcing a network detection using whatever + * technique the sub-class requires. + * + * Sub-classes **must** override this. + */ + _detectNetwork(shard) { + assert(false, "sub-classes must implement this", "UNSUPPORTED_OPERATION", { + operation: "_detectNetwork" + }); + } + /** + * Sub-classes should use this to perform all built-in operations. All + * methods sanitizes and normalizes the values passed into this. + * + * Sub-classes **must** override this. + */ + async _perform(req) { + assert(false, `unsupported method: ${req.method}`, "UNSUPPORTED_OPERATION", { + operation: req.method, + info: req + }); + } + // State + async getBlockNumber(shard) { + const blockNumber = getNumber(await this.#perform({ method: "getBlockNumber", shard: shard }), "%response"); + if (this.#lastBlockNumber >= 0) { + this.#lastBlockNumber = blockNumber; + } + return blockNumber; + } + /** + * Returns or resolves to the address for %%address%%, resolving ENS + * names and [[Addressable]] objects and returning if already an + * address. + */ + _getAddress(address) { + return resolveAddress(address, this); + } + /** + * Returns or resolves to a valid block tag for %%blockTag%%, resolving + * negative values and returning if already a valid block tag. + */ + _getBlockTag(shard, blockTag) { + if (blockTag == null) { + return "latest"; + } + switch (blockTag) { + case "earliest": + return "0x0"; + case "finalized": + case "latest": + case "pending": + case "safe": + return blockTag; + } + if (isHexString(blockTag)) { + if (isHexString(blockTag, 32)) { + return blockTag; + } + return toQuantity(blockTag); + } + if (typeof (blockTag) === "bigint") { + blockTag = getNumber(blockTag, "blockTag"); + } + if (typeof (blockTag) === "number") { + if (blockTag >= 0) { + return toQuantity(blockTag); + } + if (this.#lastBlockNumber >= 0) { + return toQuantity(this.#lastBlockNumber + blockTag); + } + return this.getBlockNumber(shard).then((b) => toQuantity(b + blockTag)); + } + assertArgument(false, "invalid blockTag", "blockTag", blockTag); + } + /** + * Returns or resolves to a filter for %%filter%%, resolving any ENS + * names or [[Addressable]] object and returning if already a valid + * filter. + */ + _getFilter(filter) { + // Create a canonical representation of the topics + const topics = (filter.topics || []).map((t) => { + if (t == null) { + return null; + } + if (Array.isArray(t)) { + return concisify(t.map((t) => t.toLowerCase())); + } + return t.toLowerCase(); + }); + const blockHash = ("blockHash" in filter) ? filter.blockHash : undefined; + const resolve = (_address, fromBlock, toBlock, shard) => { + let address = undefined; + switch (_address.length) { + case 0: break; + case 1: + address = _address[0]; + break; + default: + _address.sort(); + address = _address; + } + if (blockHash) { + if (fromBlock != null || toBlock != null) { + throw new Error("invalid filter"); + } + } + const filter = {}; + if (address) { + filter.address = address; + } + if (topics.length) { + filter.topics = topics; + } + if (fromBlock) { + filter.fromBlock = fromBlock; + } + if (toBlock) { + filter.toBlock = toBlock; + } + if (blockHash) { + filter.blockHash = blockHash; + } + if (shard) { + filter.shard = shard; + } + return filter; + }; + // Addresses could be async (ENS names or Addressables) + let address = []; + if (filter.address) { + if (Array.isArray(filter.address)) { + for (const addr of filter.address) { + address.push(this._getAddress(addr)); + } + } + else { + address.push(this._getAddress(filter.address)); + } + } + let fromBlock = undefined; + if ("fromBlock" in filter) { + fromBlock = this._getBlockTag(filter.shard, filter.fromBlock); + } + let toBlock = undefined; + if ("toBlock" in filter) { + toBlock = this._getBlockTag(filter.shard, filter.toBlock); + } + const shard = filter.shard; + if (address.filter((a) => (typeof (a) !== "string")).length || + (fromBlock != null && typeof (fromBlock) !== "string") || + (toBlock != null && typeof (toBlock) !== "string")) { + return Promise.all([Promise.all(address), fromBlock, toBlock, shard]).then((result) => { + return resolve(result[0], result[1], result[2]); + }); + } + return resolve(address, fromBlock, toBlock, shard); + } + /** + * Returns or resovles to a transaction for %%request%%, resolving + * any ENS names or [[Addressable]] and returning if already a valid + * transaction. + */ + _getTransactionRequest(_request) { + const request = copyRequest(_request); + const promises = []; + ["to", "from"].forEach((key) => { + if (request[key] == null) { + return; + } + const addr = resolveAddress(request[key], this); + if (isPromise(addr)) { + promises.push((async function () { request[key] = await addr; })()); + } + else { + request[key] = addr; + } + }); + if (request.blockTag != null) { + const blockTag = this._getBlockTag(request.chainId?.toString(), request.blockTag); + if (isPromise(blockTag)) { + promises.push((async function () { request.blockTag = await blockTag; })()); + } + else { + request.blockTag = blockTag; + } + } + if (promises.length) { + return (async function () { + await Promise.all(promises); + return request; + })(); + } + return request; + } + async getNetwork(shard = 'prime') { + // No explicit network was set and this is our first time + if (this.#networkPromise == null) { + // Detect the current network (shared with all calls) + const detectNetwork = (async () => { + try { + const network = await this._detectNetwork(shard); + this.emit("network", network, null); + return network; + } + catch (error) { + if (this.#networkPromise === detectNetwork) { + this.#networkPromise = null; + } + throw error; + } + })(); + this.#networkPromise = detectNetwork; + return (await detectNetwork).clone(); + } + const networkPromise = this.#networkPromise; + const [expected, actual] = await Promise.all([ + networkPromise, + this._detectNetwork(shard) // The actual connected network + ]); + if (expected.chainId !== actual.chainId) { + if (this.#anyNetwork) { + // The "any" network can change, so notify listeners + this.emit("network", actual, expected); + // Update the network if something else hasn't already changed it + if (this.#networkPromise === networkPromise) { + this.#networkPromise = Promise.resolve(actual); + } + } + else { + // Otherwise, we do not allow changes to the underlying network + assert(false, `network changed: ${expected.chainId} => ${actual.chainId} `, "NETWORK_ERROR", { + event: "changed" + }); + } + } + return expected.clone(); + } + async getRunningLocations(shard) { + return await this.#perform(shard ? { method: "getRunningLocations", shard: shard } : { method: "getRunningLocations" }); + } + async getProtocolTrieExpansionCount(shard) { + return await this.#perform({ method: "getProtocolTrieExpansionCount", shard: shard }); + } + async getFeeData(shard, txType = true) { + const network = await this.getNetwork(); + const getFeeDataFunc = async () => { + const { gasPrice, priorityFee } = await resolveProperties({ + gasPrice: ((async () => { + try { + const value = await this.#perform({ method: "getGasPrice", txType, shard: shard }); + return getBigInt(value, "%response"); + } + catch (error) { } + return null; + })()), + priorityFee: ((async () => { + try { + const value = txType ? await this.#perform({ method: "getMaxPriorityFeePerGas", shard: shard }) : 0; + return getBigInt(value, "%response"); + } + catch (error) { } + return null; + })()) + }); + if (gasPrice == null) { + throw new Error("could not determine gasPrice"); + } + let maxFeePerGas = null; + let maxPriorityFeePerGas = null; + // These are the recommended EIP-1559 heuristics for fee data + maxPriorityFeePerGas = (priorityFee != null) ? priorityFee : BigInt("1000000000"); + maxFeePerGas = (gasPrice * BN_2) + maxPriorityFeePerGas; + return new FeeData(gasPrice, maxFeePerGas, maxPriorityFeePerGas); + }; + // Check for a FeeDataNetWorkPlugin + const plugin = network.getPlugin("org.quais.plugins.network.FetchUrlFeeDataPlugin"); + if (plugin) { + const req = new FetchRequest(plugin.url); + const feeData = await plugin.processFunc(getFeeDataFunc, this, req); + return new FeeData(feeData.gasPrice, feeData.maxFeePerGas, feeData.maxPriorityFeePerGas); + } + return await getFeeDataFunc(); + } + async estimateGas(_tx) { + let tx = this._getTransactionRequest(_tx); + if (isPromise(tx)) { + tx = await tx; + } + const shard = await this.shardFromAddress(tx.from); + return getBigInt(await this.#perform({ + method: "estimateGas", transaction: tx, shard: shard + }), "%response"); + } + async #call(tx, blockTag, attempt) { + assert(attempt < MAX_CCIP_REDIRECTS, "CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", { + reason: "TOO_MANY_REDIRECTS", + transaction: Object.assign({}, tx, { blockTag, enableCcipRead: true }) + }); + // This came in as a PerformActionTransaction, so to/from are safe; we can cast + const transaction = copyRequest(tx); + try { + return hexlify(await this._perform({ method: "call", transaction, blockTag })); + } + catch (error) { + // CCIP Read OffchainLookup + // if (!this.disableCcipRead && isCallException(error) && error.data && attempt >= 0 && blockTag === "latest" && transaction.to != null && dataSlice(error.data, 0, 4) === "0x556f1830") { + // const data = error.data; + // const txSender = await resolveAddress(transaction.to, this); + // // Parse the CCIP Read Arguments + // let ccipArgs: CcipArgs; + // try { + // ccipArgs = parseOffchainLookup(dataSlice(error.data, 4)); + // } catch (error: any) { + // assert(false, error.message, "OFFCHAIN_FAULT", { + // reason: "BAD_DATA", transaction, info: { data } }); + // } + // // Check the sender of the OffchainLookup matches the transaction + // assert(ccipArgs.sender.toLowerCase() === txSender.toLowerCase(), + // "CCIP Read sender mismatch", "CALL_EXCEPTION", { + // action: "call", + // data, + // reason: "OffchainLookup", + // transaction: transaction, // @TODO: populate data? + // invocation: null, + // revert: { + // signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", + // name: "OffchainLookup", + // args: ccipArgs.errorArgs + // } + // }); + // const ccipResult = await this.ccipReadFetch(transaction, ccipArgs.calldata, ccipArgs.urls); + // assert(ccipResult != null, "CCIP Read failed to fetch data", "OFFCHAIN_FAULT", { + // reason: "FETCH_FAILED", transaction, info: { data: error.data, errorArgs: ccipArgs.errorArgs } }); + // const tx = { + // to: txSender, + // data: concat([ ccipArgs.selector, encodeBytes([ ccipResult, ccipArgs.extraData ]) ]) + // }; + // this.emit("debug", { action: "sendCcipReadCall", transaction: tx }); + // try { + // const result = await this.#call(tx, blockTag, attempt + 1); + // this.emit("debug", { action: "receiveCcipReadCallResult", transaction: Object.assign({ }, tx), result }); + // return result; + // } catch (error) { + // this.emit("debug", { action: "receiveCcipReadCallError", transaction: Object.assign({ }, tx), error }); + // throw error; + // } + // } + throw error; + } + } + async #checkNetwork(promise, shard) { + const { value } = await resolveProperties({ + network: this.getNetwork(), + value: promise + }); + return value; + } + async call(_tx) { + const shard = await this.shardFromAddress(_tx.from); + const { tx, blockTag } = await resolveProperties({ + tx: this._getTransactionRequest(_tx), + blockTag: this._getBlockTag(shard, _tx.blockTag) + }); + return await this.#checkNetwork(this.#call(tx, blockTag, _tx.enableCcipRead ? 0 : -1), shard); + } + // Account + async #getAccountValue(request, _address, _blockTag) { + let address = this._getAddress(_address); + const shard = await this.shardFromAddress(_address); + let blockTag = this._getBlockTag(shard, _blockTag); + if (typeof (address) !== "string" || typeof (blockTag) !== "string") { + [address, blockTag] = await Promise.all([address, blockTag]); + } + return await this.#checkNetwork(this.#perform(Object.assign(request, { address, blockTag, shard: shard })), shard); + } + async getBalance(address, blockTag) { + return getBigInt(await this.#getAccountValue({ method: "getBalance" }, address, blockTag), "%response"); + } + async getTransactionCount(address, blockTag) { + return getNumber(await this.#getAccountValue({ method: "getTransactionCount" }, address, blockTag), "%response"); + } + async getCode(address, blockTag) { + return hexlify(await this.#getAccountValue({ method: "getCode" }, address, blockTag)); + } + async getStorage(address, _position, blockTag) { + const position = getBigInt(_position, "position"); + return hexlify(await this.#getAccountValue({ method: "getStorage", position }, address, blockTag)); + } + // Write + async broadcastTransaction(shard, signedTx) { + const { blockNumber, hash, network } = await resolveProperties({ + blockNumber: this.getBlockNumber(shard), + hash: this._perform({ + method: "broadcastTransaction", + signedTransaction: signedTx, + shard: shard + }), + network: this.getNetwork() + }); + const tx = Transaction.from(signedTx); + if (tx.hash !== hash) { + throw new Error("@TODO: the returned hash did not match"); + } + return this._wrapTransactionResponse(tx, network).replaceableTransaction(blockNumber); + } + async #getBlock(shard, block, includeTransactions) { + // @TODO: Add CustomBlockPlugin check + if (isHexString(block, 32)) { + return await this.#perform({ + method: "getBlock", blockHash: block, includeTransactions, shard: shard + }); + } + let blockTag = this._getBlockTag(shard, block); + if (typeof (blockTag) !== "string") { + blockTag = await blockTag; + } + return await this.#perform({ + method: "getBlock", blockTag, includeTransactions, shard: shard + }); + } + // Queries + async getBlock(shard, block, prefetchTxs) { + const { network, params } = await resolveProperties({ + network: this.getNetwork(), + params: this.#getBlock(shard, block, !!prefetchTxs) + }); + if (params == null) { + return null; + } + return this._wrapBlock(params, network); + } + async getTransaction(hash) { + const shard = this.shardFromHash(hash); + const { network, params } = await resolveProperties({ + network: this.getNetwork(), + params: this.#perform({ method: "getTransaction", hash, shard: shard }) + }); + if (params == null) { + return null; + } + return this._wrapTransactionResponse(params, network); + } + async getTransactionReceipt(hash) { + const shard = this.shardFromHash(hash); + const { network, params } = await resolveProperties({ + network: this.getNetwork(), + params: this.#perform({ method: "getTransactionReceipt", hash, shard: shard }) + }); + if (params == null) { + return null; + } + // Some backends did not backfill the effectiveGasPrice in to old transactions + // in the receipt, so we look it up manually and inject it. + if (params.gasPrice == null && params.effectiveGasPrice == null) { + const tx = await this.#perform({ method: "getTransaction", hash, shard: shard }); + if (tx == null) { + throw new Error("report this; could not find tx or effectiveGasPrice"); + } + params.effectiveGasPrice = tx.gasPrice; + } + return this._wrapTransactionReceipt(params, network); + } + async getTransactionResult(hash) { + const shard = this.shardFromHash(hash); + const { result } = await resolveProperties({ + network: this.getNetwork(), + result: this.#perform({ method: "getTransactionResult", hash, shard: shard }) + }); + if (result == null) { + return null; + } + return hexlify(result); + } + // Bloom-filter Queries + async getLogs(_filter) { + let filter = this._getFilter(_filter); + if (isPromise(filter)) { + filter = await filter; + } + const shard = filter.shard; + const { network, params } = await resolveProperties({ + network: this.getNetwork(), + params: this.#perform({ method: "getLogs", filter, shard: shard }) + }); + return params.map((p) => this._wrapLog(p, network)); + } + // ENS + _getProvider(chainId) { + assert(false, "provider cannot connect to target network", "UNSUPPORTED_OPERATION", { + operation: "_getProvider()" + }); + } + async getResolver(name) { + return await EnsResolver.fromName(this, name); + } + async getAvatar(name) { + const resolver = await this.getResolver(name); + if (resolver) { + return await resolver.getAvatar(); + } + return null; + } + async resolveName(name) { + const resolver = await this.getResolver(name); + if (resolver) { + return await resolver.getAddress(); + } + return null; + } + async lookupAddress(address) { + address = getAddress(address); + const node = namehash(address.substring(2).toLowerCase() + ".addr.reverse"); + try { + const ensAddr = await EnsResolver.getEnsAddress(this); + const ensContract = new Contract(ensAddr, [ + "function resolver(bytes32) view returns (address)" + ], this); + const resolver = await ensContract.resolver(node); + if (resolver == null || resolver === ZeroAddress) { + return null; + } + const resolverContract = new Contract(resolver, [ + "function name(bytes32) view returns (string)" + ], this); + const name = await resolverContract.name(node); + // Failed forward resolution + const check = await this.resolveName(name); + if (check !== address) { + return null; + } + return name; + } + catch (error) { + // No data was returned from the resolver + if (isError(error, "BAD_DATA") && error.value === "0x") { + return null; + } + // Something reerted + if (isError(error, "CALL_EXCEPTION")) { + return null; + } + throw error; + } + return null; + } + async waitForTransaction(hash, _confirms, timeout) { + const shard = this.shardFromHash(hash); + const confirms = (_confirms != null) ? _confirms : 1; + if (confirms === 0) { + return this.getTransactionReceipt(hash); + } + return new Promise(async (resolve, reject) => { + let timer = null; + const listener = (async (blockNumber) => { + try { + const receipt = await this.getTransactionReceipt(hash); + if (receipt != null) { + if (blockNumber - receipt.blockNumber + 1 >= confirms) { + resolve(receipt); + //this.off("block", listener); + if (timer) { + clearTimeout(timer); + timer = null; + } + return; + } + } + } + catch (error) { + console.log("EEE", error); + } + this.once("block", listener); + }); + if (timeout != null) { + timer = setTimeout(() => { + if (timer == null) { + return; + } + timer = null; + this.off("block", listener); + reject(makeError("timeout", "TIMEOUT", { reason: "timeout" })); + }, timeout); + } + listener(await this.getBlockNumber(shard)); + }); + } + async waitForBlock(shard, blockTag) { + assert(false, "not implemented yet", "NOT_IMPLEMENTED", { + operation: "waitForBlock" + }); + } + /** + * Clear a timer created using the [[_setTimeout]] method. + */ + _clearTimeout(timerId) { + const timer = this.#timers.get(timerId); + if (!timer) { + return; + } + if (timer.timer) { + clearTimeout(timer.timer); + } + this.#timers.delete(timerId); + } + /** + * Create a timer that will execute %%func%% after at least %%timeout%% + * (in ms). If %%timeout%% is unspecified, then %%func%% will execute + * in the next event loop. + * + * [Pausing](AbstractProvider-paused) the provider will pause any + * associated timers. + */ + _setTimeout(_func, timeout) { + if (timeout == null) { + timeout = 0; + } + const timerId = this.#nextTimer++; + const func = () => { + this.#timers.delete(timerId); + _func(); + }; + if (this.paused) { + this.#timers.set(timerId, { timer: null, func, time: timeout }); + } + else { + const timer = setTimeout(func, timeout); + this.#timers.set(timerId, { timer, func, time: getTime() }); + } + return timerId; + } + /** + * Perform %%func%% on each subscriber. + */ + _forEachSubscriber(func) { + for (const sub of this.#subs.values()) { + func(sub.subscriber); + } + } + /** + * Sub-classes may override this to customize subscription + * implementations. + */ + _getSubscriber(sub) { + switch (sub.type) { + case "debug": + case "error": + case "network": + return new UnmanagedSubscriber(sub.type); + } + throw new Error("HTTP polling not supported. This method should be implemented by subclasses."); + } + /** + * If a [[Subscriber]] fails and needs to replace itself, this + * method may be used. + * + * For example, this is used for providers when using the + * ``eth_getFilterChanges`` method, which can return null if state + * filters are not supported by the backend, allowing the Subscriber + * to swap in a [[PollingEventSubscriber]]. + */ + _recoverSubscriber(oldSub, newSub) { + for (const sub of this.#subs.values()) { + if (sub.subscriber === oldSub) { + if (sub.started) { + sub.subscriber.stop(); + } + sub.subscriber = newSub; + if (sub.started) { + newSub.start(); + } + if (this.#pausedState != null) { + newSub.pause(this.#pausedState); + } + break; + } + } + } + async #hasSub(event, emitArgs) { + let sub = await getSubscription(event, this); + // This is a log that is removing an existing log; we actually want + // to emit an orphan event for the removed log + if (sub.type === "event" && emitArgs && emitArgs.length > 0 && emitArgs[0].removed === true) { + sub = await getSubscription({ orphan: "drop-log", log: emitArgs[0] }, this); + } + return this.#subs.get(sub.tag) || null; + } + async #getSub(event) { + const subscription = await getSubscription(event, this); + // Prevent tampering with our tag in any subclass' _getSubscriber + const tag = subscription.tag; + let sub = this.#subs.get(tag); + if (!sub) { + const subscriber = this._getSubscriber(subscription); + const addressableMap = new WeakMap(); + const nameMap = new Map(); + sub = { subscriber, tag, addressableMap, nameMap, started: false, listeners: [] }; + this.#subs.set(tag, sub); + } + return sub; + } + async on(event, listener) { + const sub = await this.#getSub(event); + sub.listeners.push({ listener, once: false }); + if (!sub.started) { + sub.subscriber.start(); + sub.started = true; + if (this.#pausedState != null) { + sub.subscriber.pause(this.#pausedState); + } + } + return this; + } + async once(event, listener) { + const sub = await this.#getSub(event); + sub.listeners.push({ listener, once: true }); + if (!sub.started) { + sub.subscriber.start(); + sub.started = true; + if (this.#pausedState != null) { + sub.subscriber.pause(this.#pausedState); + } + } + return this; + } + async emit(event, ...args) { + const sub = await this.#hasSub(event, args); + // If there is not subscription or if a recent emit removed + // the last of them (which also deleted the sub) do nothing + if (!sub || sub.listeners.length === 0) { + return false; + } + ; + const count = sub.listeners.length; + sub.listeners = sub.listeners.filter(({ listener, once }) => { + const payload = new EventPayload(this, (once ? null : listener), event); + try { + listener.call(this, ...args, payload); + } + catch (error) { } + return !once; + }); + if (sub.listeners.length === 0) { + if (sub.started) { + sub.subscriber.stop(); + } + this.#subs.delete(sub.tag); + } + return (count > 0); + } + async listenerCount(event) { + if (event) { + const sub = await this.#hasSub(event); + if (!sub) { + return 0; + } + return sub.listeners.length; + } + let total = 0; + for (const { listeners } of this.#subs.values()) { + total += listeners.length; + } + return total; + } + async listeners(event) { + if (event) { + const sub = await this.#hasSub(event); + if (!sub) { + return []; + } + return sub.listeners.map(({ listener }) => listener); + } + let result = []; + for (const { listeners } of this.#subs.values()) { + result = result.concat(listeners.map(({ listener }) => listener)); + } + return result; + } + async off(event, listener) { + const sub = await this.#hasSub(event); + if (!sub) { + return this; + } + if (listener) { + const index = sub.listeners.map(({ listener }) => listener).indexOf(listener); + if (index >= 0) { + sub.listeners.splice(index, 1); + } + } + if (!listener || sub.listeners.length === 0) { + if (sub.started) { + sub.subscriber.stop(); + } + this.#subs.delete(sub.tag); + } + return this; + } + async removeAllListeners(event) { + if (event) { + const { tag, started, subscriber } = await this.#getSub(event); + if (started) { + subscriber.stop(); + } + this.#subs.delete(tag); + } + else { + for (const [tag, { started, subscriber }] of this.#subs) { + if (started) { + subscriber.stop(); + } + this.#subs.delete(tag); + } + } + return this; + } + // Alias for "on" + async addListener(event, listener) { + return await this.on(event, listener); + } + // Alias for "off" + async removeListener(event, listener) { + return this.off(event, listener); + } + /** + * If this provider has been destroyed using the [[destroy]] method. + * + * Once destroyed, all resources are reclaimed, internal event loops + * and timers are cleaned up and no further requests may be sent to + * the provider. + */ + get destroyed() { + return this.#destroyed; + } + /** + * Sub-classes may use this to shutdown any sockets or release their + * resources and reject any pending requests. + * + * Sub-classes **must** call ``super.destroy()``. + */ + destroy() { + // Stop all listeners + this.removeAllListeners(); + // Shut down all tiemrs + for (const timerId of this.#timers.keys()) { + this._clearTimeout(timerId); + } + this.#destroyed = true; + } + /** + * Whether the provider is currently paused. + * + * A paused provider will not emit any events, and generally should + * not make any requests to the network, but that is up to sub-classes + * to manage. + * + * Setting ``paused = true`` is identical to calling ``.pause(false)``, + * which will buffer any events that occur while paused until the + * provider is unpaused. + */ + get paused() { return (this.#pausedState != null); } + set paused(pause) { + if (!!pause === this.paused) { + return; + } + if (this.paused) { + this.resume(); + } + else { + this.pause(false); + } + } + /** + * Pause the provider. If %%dropWhilePaused%%, any events that occur + * while paused are dropped, otherwise all events will be emitted once + * the provider is unpaused. + */ + pause(dropWhilePaused) { + this.#lastBlockNumber = -1; + if (this.#pausedState != null) { + if (this.#pausedState == !!dropWhilePaused) { + return; + } + assert(false, "cannot change pause type; resume first", "UNSUPPORTED_OPERATION", { + operation: "pause" + }); + } + this._forEachSubscriber((s) => s.pause(dropWhilePaused)); + this.#pausedState = !!dropWhilePaused; + for (const timer of this.#timers.values()) { + // Clear the timer + if (timer.timer) { + clearTimeout(timer.timer); + } + // Remaining time needed for when we become unpaused + timer.time = getTime() - timer.time; + } + } + /** + * Resume the provider. + */ + resume() { + if (this.#pausedState == null) { + return; + } + this._forEachSubscriber((s) => s.resume()); + this.#pausedState = null; + for (const timer of this.#timers.values()) { + // Remaining time when we were paused + let timeout = timer.time; + if (timeout < 0) { + timeout = 0; + } + // Start time (in cause paused, so we con compute remaininf time) + timer.time = getTime(); + // Start the timer + setTimeout(timer.func, timeout); + } + } +} +// function _parseString(result: string, start: number): null | string { +// try { +// const bytes = _parseBytes(result, start); +// if (bytes) { return toUtf8String(bytes); } +// } catch(error) { } +// return null; +// } +// function _parseBytes(result: string, start: number): null | string { +// if (result === "0x") { return null; } +// try { +// const offset = getNumber(dataSlice(result, start, start + 32)); +// const length = getNumber(dataSlice(result, offset, offset + 32)); +// +// return dataSlice(result, offset + 32, offset + 32 + length); +// } catch (error) { } +// return null; +// } +// function numPad(value: number): Uint8Array { +// const result = toBeArray(value); +// if (result.length > 32) { throw new Error("internal; should not happen"); } +// +// const padded = new Uint8Array(32); +// padded.set(result, 32 - result.length); +// return padded; +// } +// function bytesPad(value: Uint8Array): Uint8Array { +// if ((value.length % 32) === 0) { return value; } +// +// const result = new Uint8Array(Math.ceil(value.length / 32) * 32); +// result.set(value); +// return result; +// } +// const empty: Uint8Array = new Uint8Array([ ]); +// ABI Encodes a series of (bytes, bytes, ...) +// function encodeBytes(datas: Array): string { +// const result: Array = [ ]; +// +// let byteCount = 0; +// +// // Add place-holders for pointers as we add items +// for (let i = 0; i < datas.length; i++) { +// result.push(empty); +// byteCount += 32; +// } +// +// for (let i = 0; i < datas.length; i++) { +// const data = getBytes(datas[i]); +// +// // Update the bytes offset +// result[i] = numPad(byteCount); +// +// // The length and padded value of data +// result.push(numPad(data.length)); +// result.push(bytesPad(data)); +// byteCount += 32 + Math.ceil(data.length / 32) * 32; +// } +// +// return concat(result); +// } +// const zeros = "0x0000000000000000000000000000000000000000000000000000000000000000" +// function parseOffchainLookup(data: string): CcipArgs { +// const result: CcipArgs = { +// sender: "", urls: [ ], calldata: "", selector: "", extraData: "", errorArgs: [ ] +// }; +// +// assert(dataLength(data) >= 5 * 32, "insufficient OffchainLookup data", "OFFCHAIN_FAULT", { +// reason: "insufficient OffchainLookup data" +// }); +// +// const sender = dataSlice(data, 0, 32); +// assert(dataSlice(sender, 0, 12) === dataSlice(zeros, 0, 12), "corrupt OffchainLookup sender", "OFFCHAIN_FAULT", { +// reason: "corrupt OffchainLookup sender" +// }); +// result.sender = dataSlice(sender, 12); +// +// // Read the URLs from the response +// try { +// const urls: Array = []; +// const urlsOffset = getNumber(dataSlice(data, 32, 64)); +// const urlsLength = getNumber(dataSlice(data, urlsOffset, urlsOffset + 32)); +// const urlsData = dataSlice(data, urlsOffset + 32); +// for (let u = 0; u < urlsLength; u++) { +// const url = _parseString(urlsData, u * 32); +// if (url == null) { throw new Error("abort"); } +// urls.push(url); +// } +// result.urls = urls; +// } catch (error) { +// assert(false, "corrupt OffchainLookup urls", "OFFCHAIN_FAULT", { +// reason: "corrupt OffchainLookup urls" +// }); +// } +// +// // Get the CCIP calldata to forward +// try { +// const calldata = _parseBytes(data, 64); +// if (calldata == null) { throw new Error("abort"); } +// result.calldata = calldata; +// } catch (error) { +// assert(false, "corrupt OffchainLookup calldata", "OFFCHAIN_FAULT", { +// reason: "corrupt OffchainLookup calldata" +// }); +// } +// +// // Get the callbackSelector (bytes4) +// assert(dataSlice(data, 100, 128) === dataSlice(zeros, 0, 28), "corrupt OffchainLookup callbaackSelector", "OFFCHAIN_FAULT", { +// reason: "corrupt OffchainLookup callbaackSelector" +// }); +// result.selector = dataSlice(data, 96, 100); +// +// // Get the extra data to send back to the contract as context +// try { +// const extraData = _parseBytes(data, 128); +// if (extraData == null) { throw new Error("abort"); } +// result.extraData = extraData; +// } catch (error) { +// assert(false, "corrupt OffchainLookup extraData", "OFFCHAIN_FAULT", { +// reason: "corrupt OffchainLookup extraData" +// }); +// } +// +// result.errorArgs = "sender,urls,calldata,selector,extraData".split(/,/).map((k) => (result)[k]) +// +// return result; +// } +//# sourceMappingURL=abstract-provider.js.map \ No newline at end of file diff --git a/lib.esm/providers/abstract-provider.js.map b/lib.esm/providers/abstract-provider.js.map new file mode 100644 index 00000000..b0867cb5 --- /dev/null +++ b/lib.esm/providers/abstract-provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abstract-provider.js","sourceRoot":"","sources":["../../src.ts/providers/abstract-provider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,QAAQ;AACR,oBAAoB;AACpB,4EAA4E;AAC5E,4EAA4E;AAC5E,6EAA6E;AAC7E,6EAA6E;AAC7E,2EAA2E;AAE3E,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,EAAE,QAAQ,EAAE,MAAM,s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CAAyC;AACzC,YAAY;AACZ,0CAA0C;AAC1C,iEAAiE;AACjE,sFAAsF;AACtF,6DAA6D;AAC7D,iDAAiD;AACjD,0DAA0D;AAC1D,6DAA6D;AAC7D,8BAA8B;AAC9B,YAAY;AACZ,8BAA8B;AAC9B,wBAAwB;AACxB,2EAA2E;AAC3E,oDAAoD;AACpD,cAAc;AACd,QAAQ;AACR,EAAE;AACF,0CAA0C;AAC1C,YAAY;AACZ,kDAAkD;AAClD,8DAA8D;AAC9D,sCAAsC;AACtC,wBAAwB;AACxB,+EAA+E;AAC/E,wDAAwD;AACxD,cAAc;AACd,QAAQ;AACR,EAAE;AACF,2CAA2C;AAC3C,oIAAoI;AACpI,6DAA6D;AAC7D,UAAU;AACV,kDAAkD;AAClD,EAAE;AACF,oEAAoE;AACpE,YAAY;AACZ,oDAAoD;AACpD,+DAA+D;AAC/D,wCAAwC;AACxC,wBAAwB;AACxB,gFAAgF;AAChF,yDAAyD;AACzD,cAAc;AACd,QAAQ;AACR,EAAE;AACF,2GAA2G;AAC3G,EAAE;AACF,qBAAqB;AACrB,IAAI"} \ No newline at end of file diff --git a/lib.esm/providers/abstract-signer.d.ts b/lib.esm/providers/abstract-signer.d.ts new file mode 100644 index 00000000..62147c3a --- /dev/null +++ b/lib.esm/providers/abstract-signer.d.ts @@ -0,0 +1,77 @@ +/** + * Generally the [[Wallet]] and [[JsonRpcSigner]] and their sub-classes + * are sufficent for most developers, but this is provided to + * fascilitate more complex Signers. + * + * @_section: api/providers/abstract-signer: Subclassing Signer [abstract-signer] + */ +import { AddressLike } from "../address/index.js"; +import type { TypedDataDomain, TypedDataField } from "../hash/index.js"; +import type { TransactionLike } from "../transaction/index.js"; +import type { BlockTag, Provider, TransactionRequest, TransactionResponse } from "./provider.js"; +import type { Signer } from "./signer.js"; +/** + * An **AbstractSigner** includes most of teh functionality required + * to get a [[Signer]] working as expected, but requires a few + * Signer-specific methods be overridden. + * + */ +export declare abstract class AbstractSigner

implements Signer { + /** + * The provider this signer is connected to. + */ + readonly provider: P; + /** + * Creates a new Signer connected to %%provider%%. + */ + constructor(provider?: P); + /** + * Resolves to the Signer address. + */ + abstract getAddress(): Promise; + _getAddress(address: AddressLike): string | Promise; + shardFromAddress(_address: AddressLike): Promise; + /** + * Returns the signer connected to %%provider%%. + * + * This may throw, for example, a Signer connected over a Socket or + * to a specific instance of a node may not be transferrable. + */ + abstract connect(provider: null | Provider): Signer; + getNonce(blockTag?: BlockTag): Promise; + populateCall(tx: TransactionRequest): Promise>; + populateTransaction(tx: TransactionRequest): Promise>; + estimateGas(tx: TransactionRequest): Promise; + call(tx: TransactionRequest): Promise; + resolveName(name: string): Promise; + sendTransaction(tx: TransactionRequest): Promise; + abstract signTransaction(tx: TransactionRequest): Promise; + abstract signMessage(message: string | Uint8Array): Promise; + abstract signTypedData(domain: TypedDataDomain, types: Record>, value: Record): Promise; +} +/** + * A **VoidSigner** is a class deisgned to allow an address to be used + * in any API which accepts a Signer, but for which there are no + * credentials available to perform any actual signing. + * + * This for example allow impersonating an account for the purpose of + * static calls or estimating gas, but does not allow sending transactions. + */ +export declare class VoidSigner extends AbstractSigner { + #private; + /** + * The signer address. + */ + readonly address: string; + /** + * Creates a new **VoidSigner** with %%address%% attached to + * %%provider%%. + */ + constructor(address: string, provider?: null | Provider); + getAddress(): Promise; + connect(provider: null | Provider): VoidSigner; + signTransaction(tx: TransactionRequest): Promise; + signMessage(message: string | Uint8Array): Promise; + signTypedData(domain: TypedDataDomain, types: Record>, value: Record): Promise; +} +//# sourceMappingURL=abstract-signer.d.ts.map \ No newline at end of file diff --git a/lib.esm/providers/abstract-signer.d.ts.map b/lib.esm/providers/abstract-signer.d.ts.map new file mode 100644 index 00000000..27f43736 --- /dev/null +++ b/lib.esm/providers/abstract-signer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"abstract-signer.d.ts","sourceRoot":"","sources":["../../src.ts/providers/abstract-signer.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,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ers/abstract-signer.js b/lib.esm/providers/abstract-signer.js new file mode 100644 index 00000000..7f9b5723 --- /dev/null +++ b/lib.esm/providers/abstract-signer.js @@ -0,0 +1,177 @@ +/** + * Generally the [[Wallet]] and [[JsonRpcSigner]] and their sub-classes + * are sufficent for most developers, but this is provided to + * fascilitate more complex Signers. + * + * @_section: api/providers/abstract-signer: Subclassing Signer [abstract-signer] + */ +import { resolveAddress } from "../address/index.js"; +import { Transaction } from "../transaction/index.js"; +import { defineProperties, getBigInt, resolveProperties, assert, assertArgument } from "../utils/index.js"; +import { copyRequest } from "./provider.js"; +import { getTxType } from "../utils/index.js"; +function checkProvider(signer, operation) { + if (signer.provider) { + return signer.provider; + } + assert(false, "missing provider", "UNSUPPORTED_OPERATION", { operation }); +} +async function populate(signer, tx) { + let pop = copyRequest(tx); + if (pop.to != null) { + pop.to = resolveAddress(pop.to, signer); + } + if (pop.from != null) { + const from = pop.from; + pop.from = Promise.all([ + signer.getAddress(), + resolveAddress(from, signer) + ]).then(([address, from]) => { + assertArgument(address.toLowerCase() === from.toLowerCase(), "transaction from mismatch", "tx.from", from); + return address; + }); + } + else { + pop.from = signer.getAddress(); + } + return await resolveProperties(pop); +} +/** + * An **AbstractSigner** includes most of teh functionality required + * to get a [[Signer]] working as expected, but requires a few + * Signer-specific methods be overridden. + * + */ +export class AbstractSigner { + /** + * The provider this signer is connected to. + */ + provider; + /** + * Creates a new Signer connected to %%provider%%. + */ + constructor(provider) { + defineProperties(this, { provider: (provider || null) }); + } + _getAddress(address) { + return resolveAddress(address, this); + } + async shardFromAddress(_address) { + let address = this._getAddress(_address); + return (await address).slice(0, 4); + } + async getNonce(blockTag) { + return checkProvider(this, "getTransactionCount").getTransactionCount(await this.getAddress(), blockTag); + } + async populateCall(tx) { + const pop = await populate(this, tx); + return pop; + } + async populateTransaction(tx) { + const provider = checkProvider(this, "populateTransaction"); + const shard = await this.shardFromAddress(tx.from); + const pop = await populate(this, tx); + if (pop.nonce == null) { + pop.nonce = await this.getNonce("pending"); + } + if (pop.type == null) { + pop.type = await getTxType(pop.from ?? null, pop.to ?? null); + } + if (pop.gasLimit == null) { + if (tx.type == 0) + pop.gasLimit = await this.estimateGas(pop); + else { + //Special cases for type 2 tx to bypass address out of scope in the node + let temp = pop.to; + pop.to = "0x0000000000000000000000000000000000000000"; + pop.gasLimit = getBigInt(2 * Number(await this.estimateGas(pop))); + pop.to = temp; + } + } + // Populate the chain ID + const network = await (this.provider).getNetwork(); + if (pop.chainId != null) { + const chainId = getBigInt(pop.chainId); + assertArgument(chainId === network.chainId, "transaction chainId mismatch", "tx.chainId", shard); + } + else { + pop.chainId = network.chainId; + } + if (pop.maxFeePerGas == null || pop.maxPriorityFeePerGas == null) { + const feeData = await provider.getFeeData(shard); + if (pop.maxFeePerGas == null) { + pop.maxFeePerGas = feeData.maxFeePerGas; + } + if (pop.maxPriorityFeePerGas == null) { + pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; + } + } + if (pop.type == 2) { + pop.externalGasLimit = getBigInt(Number(pop.gasLimit) * 9); + pop.externalGasTip = getBigInt(Number(pop.maxPriorityFeePerGas) * 9); + pop.externalGasPrice = getBigInt(Number(pop.maxFeePerGas) * 9); + } + //@TOOD: Don't await all over the place; save them up for + // the end for better batching + return await resolveProperties(pop); + } + async estimateGas(tx) { + return checkProvider(this, "estimateGas").estimateGas(await this.populateCall(tx)); + } + async call(tx) { + return checkProvider(this, "call").call(await this.populateCall(tx)); + } + async resolveName(name) { + const provider = checkProvider(this, "resolveName"); + return await provider.resolveName(name); + } + async sendTransaction(tx) { + const provider = checkProvider(this, "sendTransaction"); + const shard = await this.shardFromAddress(tx.from); + const pop = await this.populateTransaction(tx); + // delete pop.from; + const txObj = Transaction.from(pop); + const signedTx = await this.signTransaction(txObj); + console.log("signedTX: ", JSON.stringify(txObj)); + return await provider.broadcastTransaction(shard, signedTx); + } +} +/** + * A **VoidSigner** is a class deisgned to allow an address to be used + * in any API which accepts a Signer, but for which there are no + * credentials available to perform any actual signing. + * + * This for example allow impersonating an account for the purpose of + * static calls or estimating gas, but does not allow sending transactions. + */ +export class VoidSigner extends AbstractSigner { + /** + * The signer address. + */ + address; + /** + * Creates a new **VoidSigner** with %%address%% attached to + * %%provider%%. + */ + constructor(address, provider) { + super(provider); + defineProperties(this, { address }); + } + async getAddress() { return this.address; } + connect(provider) { + return new VoidSigner(this.address, provider); + } + #throwUnsupported(suffix, operation) { + assert(false, `VoidSigner cannot sign ${suffix}`, "UNSUPPORTED_OPERATION", { operation }); + } + async signTransaction(tx) { + this.#throwUnsupported("transactions", "signTransaction"); + } + async signMessage(message) { + this.#throwUnsupported("messages", "signMessage"); + } + async signTypedData(domain, types, value) { + this.#throwUnsupported("typed-data", "signTypedData"); + } +} +//# sourceMappingURL=abstract-signer.js.map \ No newline at end of file diff --git a/lib.esm/providers/abstract-signer.js.map b/lib.esm/providers/abstract-signer.js.map new file mode 100644 index 00000000..85cf6d25 --- /dev/null +++ b/lib.esm/providers/abstract-signer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abstract-signer.js","sourceRoot":"","sources":["../../src.ts/providers/abstract-signer.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAc,cAAc,EAAC,MAAM,qBAAqB,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EACH,gBAAgB,EAAE,SAAS,EAAE,iBAAiB,EAC9C,MAAM,EAAE,cAAc,EACzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAS5C,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAE9C,SAAS,aAAa,CAAC,MAAsB,EAAE,SAAiB;IAC5D,IAAI,MAAM,CAAC,QAAQ,EAAE;QAAE,OAAO,MAAM,CAAC,QAAQ,CAAC;KAAE;IAChD,MAAM,CAAC,KAAK,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,EAAE,SAA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provider.d.ts new file mode 100644 index 00000000..a869dc5c --- /dev/null +++ b/lib.esm/providers/default-provider.d.ts @@ -0,0 +1,48 @@ +import type { AbstractProvider } from "./abstract-provider.js"; +import type { Networkish } from "./network.js"; +import { WebSocketLike } from "./provider-websocket.js"; +/** + * Returns a default provider for %%network%%. + * + * If %%network%% is a [[WebSocketLike]] or string that begins with + * ``"ws:"`` or ``"wss:"``, a [[WebSocketProvider]] is returned backed + * by that WebSocket or URL. + * + * If %%network%% is a string that begins with ``"HTTP:"`` or ``"HTTPS:"``, + * a [[JsonRpcProvider]] is returned connected to that URL. + * + * Otherwise, a default provider is created backed by well-known public + * Web3 backends (such as [[link-infura]]) using community-provided API + * keys. + * + * The %%options%% allows specifying custom API keys per backend (setting + * an API key to ``"-"`` will omit that provider) and ``options.exclusive`` + * can be set to either a backend name or and array of backend names, which + * will whitelist **only** those backends. + * + * Current backend strings supported are: + * - ``"alchemy"`` + * - ``"ankr"`` + * - ``"cloudflare"`` + * - ``"quaiscan"`` + * - ``"infura"`` + * - ``"publicPolygon"`` + * - ``"quicknode"`` + * + * @example: + * // Connect to a local Geth node + * provider = getDefaultProvider("http://localhost:8545/"); + * + * // Connect to Ethereum mainnet with any current and future + * // third-party services available + * provider = getDefaultProvider("mainnet"); + * + * // Connect to Polygon, but only allow quaiscan and + * // INFURA and use "MY_API_KEY" in calls to quaiscan. + * provider = getDefaultProvider("matic", { + * quaiscan: "MY_API_KEY", + * exclusive: [ "quaiscan", "infura" ] + * }); + */ +export declare function getDefaultProvider(network: string | string[] | Networkish | WebSocketLike, options?: any): AbstractProvider; +//# sourceMappingURL=default-provider.d.ts.map \ No newline at end of file diff --git a/lib.esm/providers/default-provider.d.ts.map b/lib.esm/providers/default-provider.d.ts.map new file mode 100644 index 00000000..a4680d53 --- /dev/null +++ b/lib.esm/providers/default-provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"default-provider.d.ts","sourceRoot":"","sources":["../../src.ts/providers/default-provider.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AASxD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,UAAU,GAAG,aAAa,EAAE,OAAO,CAAC,EAAE,GAAG,GAAG,gBAAgB,CAsF3H"} \ No newline at end of file diff --git a/lib.esm/providers/default-provider.js b/lib.esm/providers/default-provider.js new file mode 100644 index 00000000..56260918 --- /dev/null +++ b/lib.esm/providers/default-provider.js @@ -0,0 +1,138 @@ +import { assert } from "../utils/index.js"; +import { FallbackProvider } from "./provider-fallback.js"; +import { JsonRpcProvider } from "./provider-jsonrpc.js"; +import { Network } from "./network.js"; +import { WebSocketProvider } from "./provider-websocket.js"; +function isWebSocketLike(value) { + return (value && typeof (value.send) === "function" && + typeof (value.close) === "function"); +} +const Testnets = "goerli kovan sepolia classicKotti optimism-goerli arbitrum-goerli matic-mumbai bnbt".split(" "); +/** + * Returns a default provider for %%network%%. + * + * If %%network%% is a [[WebSocketLike]] or string that begins with + * ``"ws:"`` or ``"wss:"``, a [[WebSocketProvider]] is returned backed + * by that WebSocket or URL. + * + * If %%network%% is a string that begins with ``"HTTP:"`` or ``"HTTPS:"``, + * a [[JsonRpcProvider]] is returned connected to that URL. + * + * Otherwise, a default provider is created backed by well-known public + * Web3 backends (such as [[link-infura]]) using community-provided API + * keys. + * + * The %%options%% allows specifying custom API keys per backend (setting + * an API key to ``"-"`` will omit that provider) and ``options.exclusive`` + * can be set to either a backend name or and array of backend names, which + * will whitelist **only** those backends. + * + * Current backend strings supported are: + * - ``"alchemy"`` + * - ``"ankr"`` + * - ``"cloudflare"`` + * - ``"quaiscan"`` + * - ``"infura"`` + * - ``"publicPolygon"`` + * - ``"quicknode"`` + * + * @example: + * // Connect to a local Geth node + * provider = getDefaultProvider("http://localhost:8545/"); + * + * // Connect to Ethereum mainnet with any current and future + * // third-party services available + * provider = getDefaultProvider("mainnet"); + * + * // Connect to Polygon, but only allow quaiscan and + * // INFURA and use "MY_API_KEY" in calls to quaiscan. + * provider = getDefaultProvider("matic", { + * quaiscan: "MY_API_KEY", + * exclusive: [ "quaiscan", "infura" ] + * }); + */ +export function getDefaultProvider(network, options) { + if (options == null) { + options = {}; + } + const allowService = (name) => { + if (options[name] === "-") { + return false; + } + if (typeof (options.exclusive) === "string") { + return (name === options.exclusive); + } + if (Array.isArray(options.exclusive)) { + return (options.exclusive.indexOf(name) !== -1); + } + return true; + }; + if (typeof (network) === "string" && network.match(/^https?:/)) { + return new JsonRpcProvider(network); + } + if (Array.isArray(network) && network[0].match(/^https?:/)) { + return new JsonRpcProvider(network); + } + if (typeof (network) === "string" && network.match(/^wss?:/) || isWebSocketLike(network)) { + return new WebSocketProvider(network); + } + if (Array.isArray(network) && (network[0].match(/^wss?:/) || isWebSocketLike(network[0]))) { + return new WebSocketProvider(network[0]); + } + if (Array.isArray(network)) { + assert(false, "unsupported default network", "UNSUPPORTED_OPERATION", { + operation: "getDefaultProvider" + }); + } + // Get the network and name, if possible + let staticNetwork = null; + try { + staticNetwork = Network.from(network); + } + catch (error) { } + const providers = []; + if (allowService("publicPolygon") && staticNetwork) { + if (staticNetwork.name === "matic") { + providers.push(new JsonRpcProvider("https:/\/polygon-rpc.com/", staticNetwork, { staticNetwork })); + } + } + /* + if (options.pocket !== "-") { + try { + let appId = options.pocket; + let secretKey: undefined | string = undefined; + let loadBalancer: undefined | boolean = undefined; + if (typeof(appId) === "object") { + loadBalancer = !!appId.loadBalancer; + secretKey = appId.secretKey; + appId = appId.appId; + } + providers.push(new PocketProvider(network, appId, secretKey, loadBalancer)); + } catch (error) { console.log(error); } + } + */ + assert(providers.length, "unsupported default network", "UNSUPPORTED_OPERATION", { + operation: "getDefaultProvider" + }); + // No need for a FallbackProvider + if (providers.length === 1) { + return providers[0]; + } + // We use the floor because public third-party providers can be unreliable, + // so a low number of providers with a large quorum will fail too often + let quorum = Math.floor(providers.length / 2); + if (quorum > 2) { + quorum = 2; + } + // Testnets don't need as strong a security gaurantee and speed is + // more useful during testing + if (staticNetwork && Testnets.indexOf(staticNetwork.name) !== -1) { + quorum = 1; + } + // Provided override qorum takes priority + if (options && options.quorum) { + quorum = options.quorum; + } + return new FallbackProvider(providers, undefined, { quorum }); +} +//# sourceMappingURL=default-provider.js.map \ No newline at end of file diff --git a/lib.esm/providers/default-provider.js.map b/lib.esm/providers/default-provider.js.map new file mode 100644 index 00000000..fdb2549f --- /dev/null +++ b/lib.esm/providers/default-provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"default-provider.js","sourceRoot":"","sources":["../../src.ts/providers/default-provider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAM5D,SAAS,eAAe,CAAC,KAAU;IAC/B,OAAO,CAAC,KAAK,IAAI,OAAM,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,UAAU;QAC9C,OAAM,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,UAAU,CAAC,CAAC;AAC5C,CAAC;AAED,MAAM,QAAQ,GAAG,qFAAqF,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAElH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAAuD,EAAE,OAAa;IACrG,IAAI,OAAO,IAAI,IAAI,EA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AE;IAEjF,yCAAyC;IACzC,IAAI,OAAO,IAAI,OAAO,CAAC,MAAM,EAAE;QAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;KAAE;IAE3D,OAAO,IAAI,gBAAgB,CAAC,SAAS,EAAE,SAAS,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;AAClE,CAAC"} \ No newline at end of file diff --git a/lib.esm/providers/formatting.d.ts.map b/lib.esm/providers/formatting.d.ts.map new file mode 100644 index 00000000..dbea997a --- /dev/null +++ b/lib.esm/providers/formatting.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"formatting.d.ts","sourceRoot":"","sources":["../../src.ts/providers/formatting.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAM1D;;;GAGG;AACH,MAAM,WAAW,WAAW;IACxB;;OAEG;IACH,IAAI,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC;IAErB;;OAEG;IACH,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;IAE/B;;;OAGG;IACH,SAAS,EAAE,MAAM,CAAC;IAElB;;;OAGG;IACH,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;IAEnC;;;OAGG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;IAElB;;;OAGG;IACH,aAAa,EAAE,IAAI,GAAG,MAAM,CAAC;IAE7B,YAAY,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAE5B,QAAQ,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AAE,aAAa,CAAC,MAAM,CAAC,CAAC;CAE/B;AAQD;;;GAGG;AACH,MAAM,WAAW,yBAAyB;IACtC;;OAEG;IACH,WAAW,EAAE,IAAI,GAAG,MAAM,CAAC;IAE3B;;OAEG;IACH,SAAS,EAAE,IAAI,GAAG,MAAM,CAAC;IAEzB;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAGd,IAAI,EAAE,MAAM,CAAC;IAEb;;;OAGG;IACH,EAAE,EAAE,IAAI,GAAG,MAAM,CAAC;IAElB;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;;OAGG;IACH,oBAAoB,EAAE,IAAI,GAAG,MAAM,CAAC;IAEpC;;;OAGG;IACH,YAAY,EAAE,IAAI,GAAG,MAAM,CAAC;IAE5B;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,SAAS,EAAE,SAAS,CAAC;IAErB;;OAEG;IACH,UAAU,EAAE,IAAI,GAAG,UAAU,CAAC;IAI9B,WAAY,CAAC,EAAE,MAAM,CAAE;IAEvB,WAAY,CAAC,EAAE,MAAM,CAAE;IAEvB,SAAY,CAAC,EAAE,MAAM,CAAE;IAEvB,OAAY,CAAC,EAAE,MAAM,CAAE;IAEvB,aAAc,CAAC,EAAE,UAAU,CAAE;CAChC"} \ No newline at end of file diff --git a/lib.esm/providers/formatting.js.map b/lib.esm/providers/formatting.js.map new file mode 100644 index 00000000..d14fcc57 --- /dev/null +++ b/lib.esm/providers/formatting.js.map @@ -0,0 +1 @@ +{"version":3,"file":"formatting.js","sourceRoot":"","sources":["../../src.ts/providers/formatting.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAkHF,CAAC;AAqRD,CAAC"} \ No newline at end of file diff --git a/lib.esm/providers/provider-fallback.js b/lib.esm/providers/provider-fallback.js new file mode 100644 index 00000000..a8e3c2a2 --- /dev/null +++ b/lib.esm/providers/provider-fallback.js @@ -0,0 +1,611 @@ +/** + * A **FallbackProvider** providers resiliance, security and performatnce + * in a way that is customizable and configurable. + * + * @_section: api/providers/fallback-provider:Fallback Provider [about-fallback-provider] + */ +import { assert, assertArgument, getBigInt, getNumber, isError } from "../utils/index.js"; +import { AbstractProvider } from "./abstract-provider.js"; +import { Network } from "./network.js"; +const BN_1 = BigInt("1"); +const BN_2 = BigInt("2"); +function shuffle(array) { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + const tmp = array[i]; + array[i] = array[j]; + array[j] = tmp; + } +} +function stall(duration) { + return new Promise((resolve) => { setTimeout(resolve, duration); }); +} +function getTime() { return (new Date()).getTime(); } +function stringify(value) { + return JSON.stringify(value, (key, value) => { + if (typeof (value) === "bigint") { + return { type: "bigint", value: value.toString() }; + } + return value; + }); +} +; +const defaultConfig = { stallTimeout: 400, priority: 1, weight: 1 }; +const defaultState = { + blockNumber: -2, requests: 0, lateResponses: 0, errorResponses: 0, + outOfSync: -1, unsupportedEvents: 0, rollingDuration: 0, score: 0, + _network: null, _updateNumber: null, _totalTime: 0, + _lastFatalError: null, _lastFatalErrorTimestamp: 0 +}; +async function waitForSync(config, blockNumber) { + while (config.blockNumber < 0 || config.blockNumber < blockNumber) { + if (!config._updateNumber) { + config._updateNumber = (async () => { + try { + const blockNumber = await config.provider.getBlockNumber(); + if (blockNumber > config.blockNumber) { + config.blockNumber = blockNumber; + } + } + catch (error) { + config.blockNumber = -2; + config._lastFatalError = error; + config._lastFatalErrorTimestamp = getTime(); + } + config._updateNumber = null; + })(); + } + await config._updateNumber; + config.outOfSync++; + if (config._lastFatalError) { + break; + } + } +} +function _normalize(value) { + if (value == null) { + return "null"; + } + if (Array.isArray(value)) { + return "[" + (value.map(_normalize)).join(",") + "]"; + } + if (typeof (value) === "object" && typeof (value.toJSON) === "function") { + return _normalize(value.toJSON()); + } + switch (typeof (value)) { + case "boolean": + case "symbol": + return value.toString(); + case "bigint": + case "number": + return BigInt(value).toString(); + case "string": + return JSON.stringify(value); + case "object": { + const keys = Object.keys(value); + keys.sort(); + return "{" + keys.map((k) => `${JSON.stringify(k)}:${_normalize(value[k])}`).join(",") + "}"; + } + } + console.log("Could not serialize", value); + throw new Error("Hmm..."); +} +function normalizeResult(value) { + if ("error" in value) { + const error = value.error; + return { tag: _normalize(error), value: error }; + } + const result = value.result; + return { tag: _normalize(result), value: result }; +} +// This strategy picks the highest weight result, as long as the weight is +// equal to or greater than quorum +function checkQuorum(quorum, results) { + const tally = new Map(); + for (const { value, tag, weight } of results) { + const t = tally.get(tag) || { value, weight: 0 }; + t.weight += weight; + tally.set(tag, t); + } + let best = null; + for (const r of tally.values()) { + if (r.weight >= quorum && (!best || r.weight > best.weight)) { + best = r; + } + } + if (best) { + return best.value; + } + return undefined; +} +function getMedian(quorum, results) { + let resultWeight = 0; + const errorMap = new Map(); + let bestError = null; + const values = []; + for (const { value, tag, weight } of results) { + if (value instanceof Error) { + const e = errorMap.get(tag) || { value, weight: 0 }; + e.weight += weight; + errorMap.set(tag, e); + if (bestError == null || e.weight > bestError.weight) { + bestError = e; + } + } + else { + values.push(BigInt(value)); + resultWeight += weight; + } + } + if (resultWeight < quorum) { + // We have quorum for an error + if (bestError && bestError.weight >= quorum) { + return bestError.value; + } + // We do not have quorum for a result + return undefined; + } + // Get the sorted values + values.sort((a, b) => ((a < b) ? -1 : (b > a) ? 1 : 0)); + const mid = Math.floor(values.length / 2); + // Odd-length; take the middle value + if (values.length % 2) { + return values[mid]; + } + // Even length; take the ceiling of the mean of the center two values + return (values[mid - 1] + values[mid] + BN_1) / BN_2; +} +function getAnyResult(quorum, results) { + // If any value or error meets quorum, that is our preferred result + const result = checkQuorum(quorum, results); + if (result !== undefined) { + return result; + } + // Otherwise, do we have any result? + for (const r of results) { + if (r.value) { + return r.value; + } + } + // Nope! + return undefined; +} +function getFuzzyMode(quorum, results) { + if (quorum === 1) { + return getNumber(getMedian(quorum, results), "%internal"); + } + const tally = new Map(); + const add = (result, weight) => { + const t = tally.get(result) || { result, weight: 0 }; + t.weight += weight; + tally.set(result, t); + }; + for (const { weight, value } of results) { + const r = getNumber(value); + add(r - 1, weight); + add(r, weight); + add(r + 1, weight); + } + let bestWeight = 0; + let bestResult = undefined; + for (const { weight, result } of tally.values()) { + // Use this result, if this result meets quorum and has either: + // - a better weight + // - or equal weight, but the result is larger + if (weight >= quorum && (weight > bestWeight || (bestResult != null && weight === bestWeight && result > bestResult))) { + bestWeight = weight; + bestResult = result; + } + } + return bestResult; +} +/** + * A **FallbackProvider** manages several [[Providers]] providing + * resiliance by switching between slow or misbehaving nodes, security + * by requiring multiple backends to aggree and performance by allowing + * faster backends to respond earlier. + * + */ +export class FallbackProvider extends AbstractProvider { + /** + * The number of backends that must agree on a value before it is + * accpeted. + */ + quorum; + /** + * @_ignore: + */ + eventQuorum; + /** + * @_ignore: + */ + eventWorkers; + #configs; + #height; + #initialSyncPromise; + /** + * Creates a new **FallbackProvider** with %%providers%% connected to + * %%network%%. + * + * If a [[Provider]] is included in %%providers%%, defaults are used + * for the configuration. + */ + constructor(providers, network, options) { + super(network, options); + this.#configs = providers.map((p) => { + if (p instanceof AbstractProvider) { + return Object.assign({ provider: p }, defaultConfig, defaultState); + } + else { + return Object.assign({}, defaultConfig, p, defaultState); + } + }); + this.#height = -2; + this.#initialSyncPromise = null; + if (options && options.quorum != null) { + this.quorum = options.quorum; + } + else { + this.quorum = Math.ceil(this.#configs.reduce((accum, config) => { + accum += config.weight; + return accum; + }, 0) / 2); + } + this.eventQuorum = 1; + this.eventWorkers = 1; + assertArgument(this.quorum <= this.#configs.reduce((a, c) => (a + c.weight), 0), "quorum exceed provider wieght", "quorum", this.quorum); + } + get providerConfigs() { + return this.#configs.map((c) => { + const result = Object.assign({}, c); + for (const key in result) { + if (key[0] === "_") { + delete result[key]; + } + } + return result; + }); + } + async _detectNetwork() { + return Network.from(getBigInt(await this._perform({ method: "chainId" }))); + } + // @TODO: Add support to select providers to be the event subscriber + //_getSubscriber(sub: Subscription): Subscriber { + // throw new Error("@TODO"); + //} + /** + * Transforms a %%req%% into the correct method call on %%provider%%. + */ + async _translatePerform(provider, req) { + switch (req.method) { + case "broadcastTransaction": + return await provider.broadcastTransaction(req.shard, req.signedTransaction); + case "call": + return await provider.call(Object.assign({}, req.transaction, { blockTag: req.blockTag })); + case "chainId": + return (await provider.getNetwork()).chainId; + case "estimateGas": + return await provider.estimateGas(req.transaction); + case "getBalance": + return await provider.getBalance(req.address, req.blockTag); + case "getBlock": { + const block = ("blockHash" in req) ? req.blockHash : req.blockTag; + return await provider.getBlock(req.shard, block, req.includeTransactions); + } + case "getBlockNumber": + return await provider.getBlockNumber(); + case "getCode": + return await provider.getCode(req.address, req.blockTag); + case "getGasPrice": + return (await provider.getFeeData()).gasPrice; + case "getMaxPriorityFeePerGas": + return (await provider.getFeeData()).maxPriorityFeePerGas; + case "getLogs": + return await provider.getLogs(req.filter); + case "getStorage": + return await provider.getStorage(req.address, req.position, req.blockTag); + case "getTransaction": + return await provider.getTransaction(req.hash); + case "getTransactionCount": + return await provider.getTransactionCount(req.address, req.blockTag); + case "getTransactionReceipt": + return await provider.getTransactionReceipt(req.hash); + case "getTransactionResult": + return await provider.getTransactionResult(req.hash); + } + } + // Grab the next (random) config that is not already part of + // the running set + #getNextConfig(running) { + // @TODO: Maybe do a check here to favour (heavily) providers that + // do not require waitForSync and disfavour providers that + // seem down-ish or are behaving slowly + const configs = Array.from(running).map((r) => r.config); + // Shuffle the states, sorted by priority + const allConfigs = this.#configs.slice(); + shuffle(allConfigs); + allConfigs.sort((a, b) => (a.priority - b.priority)); + for (const config of allConfigs) { + if (config._lastFatalError) { + continue; + } + if (configs.indexOf(config) === -1) { + return config; + } + } + return null; + } + // Adds a new runner (if available) to running. + #addRunner(running, req) { + const config = this.#getNextConfig(running); + // No runners available + if (config == null) { + return null; + } + // Create a new runner + const runner = { + config, result: null, didBump: false, + perform: null, staller: null + }; + const now = getTime(); + // Start performing this operation + runner.perform = (async () => { + try { + config.requests++; + const result = await this._translatePerform(config.provider, req); + runner.result = { result }; + } + catch (error) { + config.errorResponses++; + runner.result = { error }; + } + const dt = (getTime() - now); + config._totalTime += dt; + config.rollingDuration = 0.95 * config.rollingDuration + 0.05 * dt; + runner.perform = null; + })(); + // Start a staller; when this times out, it's time to force + // kicking off another runner because we are taking too long + runner.staller = (async () => { + await stall(config.stallTimeout); + runner.staller = null; + })(); + running.add(runner); + return runner; + } + // Initializes the blockNumber and network for each runner and + // blocks until initialized + async #initialSync() { + let initialSync = this.#initialSyncPromise; + if (!initialSync) { + const promises = []; + this.#configs.forEach((config) => { + promises.push((async () => { + await waitForSync(config, 0); + if (!config._lastFatalError) { + config._network = await config.provider.getNetwork(); + } + })()); + }); + this.#initialSyncPromise = initialSync = (async () => { + // Wait for all providers to have a block number and network + await Promise.all(promises); + // Check all the networks match + let chainId = null; + for (const config of this.#configs) { + if (config._lastFatalError) { + continue; + } + const network = (config._network); + if (chainId == null) { + chainId = network.chainId; + } + else if (network.chainId !== chainId) { + assert(false, "cannot mix providers on different networks", "UNSUPPORTED_OPERATION", { + operation: "new FallbackProvider" + }); + } + } + })(); + } + await initialSync; + } + async #checkQuorum(running, req) { + // Get all the result objects + const results = []; + for (const runner of running) { + if (runner.result != null) { + const { tag, value } = normalizeResult(runner.result); + results.push({ tag, value, weight: runner.config.weight }); + } + } + // Are there enough results to event meet quorum? + if (results.reduce((a, r) => (a + r.weight), 0) < this.quorum) { + return undefined; + } + switch (req.method) { + case "getBlockNumber": { + // We need to get the bootstrap block height + if (this.#height === -2) { + this.#height = Math.ceil(getNumber(getMedian(this.quorum, this.#configs.filter((c) => (!c._lastFatalError)).map((c) => ({ + value: c.blockNumber, + tag: getNumber(c.blockNumber).toString(), + weight: c.weight + }))))); + } + // Find the mode across all the providers, allowing for + // a little drift between block heights + const mode = getFuzzyMode(this.quorum, results); + if (mode === undefined) { + return undefined; + } + if (mode > this.#height) { + this.#height = mode; + } + return this.#height; + } + case "getGasPrice": + case "getMaxPriorityFeePerGas": + case "estimateGas": + return getMedian(this.quorum, results); + case "getBlock": + // Pending blocks are in the mempool and already + // quite untrustworthy; just grab anything + if ("blockTag" in req && req.blockTag === "pending") { + return getAnyResult(this.quorum, results); + } + return checkQuorum(this.quorum, results); + case "call": + case "chainId": + case "getBalance": + case "getTransactionCount": + case "getCode": + case "getStorage": + case "getTransaction": + case "getTransactionReceipt": + case "getLogs": + return checkQuorum(this.quorum, results); + case "broadcastTransaction": + return getAnyResult(this.quorum, results); + } + assert(false, "unsupported method", "UNSUPPORTED_OPERATION", { + operation: `_perform(${stringify(req.method)})` + }); + } + async #waitForQuorum(running, req) { + if (running.size === 0) { + throw new Error("no runners?!"); + } + // Any promises that are interesting to watch for; an expired stall + // or a successful perform + const interesting = []; + let newRunners = 0; + for (const runner of running) { + // No responses, yet; keep an eye on it + if (runner.perform) { + interesting.push(runner.perform); + } + // Still stalling... + if (runner.staller) { + interesting.push(runner.staller); + continue; + } + // This runner has already triggered another runner + if (runner.didBump) { + continue; + } + // Got a response (result or error) or stalled; kick off another runner + runner.didBump = true; + newRunners++; + } + // Check if we have reached quorum on a result (or error) + const value = await this.#checkQuorum(running, req); + if (value !== undefined) { + if (value instanceof Error) { + throw value; + } + return value; + } + // Add any new runners, because a staller timed out or a result + // or error response came in. + for (let i = 0; i < newRunners; i++) { + this.#addRunner(running, req); + } + // All providers have returned, and we have no result + assert(interesting.length > 0, "quorum not met", "SERVER_ERROR", { + request: "%sub-requests", + info: { request: req, results: Array.from(running).map((r) => stringify(r.result)) } + }); + // Wait for someone to either complete its perform or stall out + await Promise.race(interesting); + // This is recursive, but at worst case the depth is 2x the + // number of providers (each has a perform and a staller) + return await this.#waitForQuorum(running, req); + } + async _perform(req) { + // Broadcasting a transaction is rare (ish) and already incurs + // a cost on the user, so spamming is safe-ish. Just send it to + // every backend. + if (req.method === "broadcastTransaction") { + // Once any broadcast provides a positive result, use it. No + // need to wait for anyone else + const results = this.#configs.map((c) => null); + const broadcasts = this.#configs.map(async ({ provider, weight }, index) => { + try { + const result = await provider._perform(req); + results[index] = Object.assign(normalizeResult({ result }), { weight }); + } + catch (error) { + results[index] = Object.assign(normalizeResult({ error }), { weight }); + } + }); + // As each promise finishes... + while (true) { + // Check for a valid broadcast result + const done = results.filter((r) => (r != null)); + for (const { value } of done) { + if (!(value instanceof Error)) { + return value; + } + } + // Check for a legit broadcast error (one which we cannot + // recover from; some nodes may return the following red + // herring events: + // - alredy seend (UNKNOWN_ERROR) + // - NONCE_EXPIRED + // - REPLACEMENT_UNDERPRICED + const result = checkQuorum(this.quorum, results.filter((r) => (r != null))); + if (isError(result, "INSUFFICIENT_FUNDS")) { + throw result; + } + // Kick off the next provider (if any) + const waiting = broadcasts.filter((b, i) => (results[i] == null)); + if (waiting.length === 0) { + break; + } + await Promise.race(waiting); + } + // Use standard quorum results; any result was returned above, + // so this will find any error that met quorum if any + const result = getAnyResult(this.quorum, results); + assert(result !== undefined, "problem multi-broadcasting", "SERVER_ERROR", { + request: "%sub-requests", + info: { request: req, results: results.map(stringify) } + }); + if (result instanceof Error) { + throw result; + } + return result; + } + await this.#initialSync(); + // Bootstrap enough runners to meet quorum + const running = new Set(); + let inflightQuorum = 0; + while (true) { + const runner = this.#addRunner(running, req); + if (runner == null) { + break; + } + inflightQuorum += runner.config.weight; + if (inflightQuorum >= this.quorum) { + break; + } + } + const result = await this.#waitForQuorum(running, req); + // Track requests sent to a provider that are still + // outstanding after quorum has been otherwise found + for (const runner of running) { + if (runner.perform && runner.result == null) { + runner.config.lateResponses++; + } + } + return result; + } + async destroy() { + for (const { provider } of this.#configs) { + provider.destroy(); + } + super.destroy(); + } +} +//# sourceMappingURL=provider-fallback.js.map \ No newline at end of file diff --git a/lib.esm/providers/provider-fallback.js.map b/lib.esm/providers/provider-fallback.js.map new file mode 100644 index 00000000..a7a35098 --- /dev/null +++ b/lib.esm/providers/provider-fallback.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-fallback.js","sourceRoot":"","sources":["../../src.ts/providers/provider-fallback.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EACH,MAAM,EAAE,cAAc,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EACxD,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAKtC,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;AACzB,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;AAEzB,SAAS,OAAO,CAAU,KAAe;IACrC,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;QACvC,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QAC9C,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QACrB,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QACpB,KAAK,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC;KAClB;AACL,CAAC;AAED,SAAS,KAAK,CAAC,QAAgB;IAC3B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,GAAG,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACxE,CAAC;AAED,SAAS,OAAO,KAAa,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,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ff --git a/lib.esm/providers/provider-jsonrpc.d.ts b/lib.esm/providers/provider-jsonrpc.d.ts new file mode 100644 index 00000000..4db114aa --- /dev/null +++ b/lib.esm/providers/provider-jsonrpc.d.ts @@ -0,0 +1,336 @@ +/** + * One of the most common ways to interact with the blockchain is + * by a node running a JSON-RPC interface which can be connected to, + * based on the transport, using: + * + * - HTTP or HTTPS - [[JsonRpcProvider]] + * - WebSocket - [[WebSocketProvider]] + * - IPC - [[IpcSocketProvider]] + * + * @_section: api/providers/jsonrpc:JSON-RPC Provider [about-jsonrpcProvider] + */ +import { FetchRequest } from "../utils/index.js"; +import { AbstractProvider } from "./abstract-provider.js"; +import { AbstractSigner } from "./abstract-signer.js"; +import { Network } from "./network.js"; +import type { TypedDataDomain, TypedDataField } from "../hash/index.js"; +import type { TransactionLike } from "../transaction/index.js"; +import type { PerformActionRequest, Subscriber, Subscription } from "./abstract-provider.js"; +import type { Networkish } from "./network.js"; +import type { Provider, TransactionRequest, TransactionResponse } from "./provider.js"; +import type { Signer } from "./signer.js"; +/** + * A JSON-RPC payload, which are sent to a JSON-RPC server. + */ +export type JsonRpcPayload = { + /** + * The JSON-RPC request ID. + */ + id: number; + /** + * The JSON-RPC request method. + */ + method: string; + /** + * The JSON-RPC request parameters. + */ + params: Array | Record; + /** + * A required constant in the JSON-RPC specification. + */ + jsonrpc: "2.0"; +}; +/** + * A JSON-RPC result, which are returned on success from a JSON-RPC server. + */ +export type JsonRpcResult = { + /** + * The response ID to match it to the relevant request. + */ + id: number; + /** + * The response result. + */ + result: any; +}; +/** + * A JSON-RPC error, which are returned on failure from a JSON-RPC server. + */ +export type JsonRpcError = { + /** + * The response ID to match it to the relevant request. + */ + id: number; + /** + * The response error. + */ + error: { + code: number; + message?: string; + data?: any; + }; +}; +/** + * When subscribing to the ``"debug"`` event, the [[Listener]] will + * receive this object as the first parameter. + */ +export type DebugEventJsonRpcApiProvider = { + action: "sendRpcPayload"; + payload: JsonRpcPayload | Array; +} | { + action: "receiveRpcResult"; + result: Array; +} | { + action: "receiveRpcError"; + error: Error; +}; +/** + * Options for configuring a [[JsonRpcApiProvider]]. Much of this + * is targetted towards sub-classes, which often will not expose + * any of these options to their consumers. + * + * **``polling``** - use the polling strategy is used immediately + * for events; otherwise, attempt to use filters and fall back onto + * polling (default: ``false``) + * + * **``staticNetwork``** - do not request chain ID on requests to + * validate the underlying chain has not changed (default: ``null``) + * + * This should **ONLY** be used if it is **certain** that the network + * cannot change, such as when using INFURA (since the URL dictates the + * network). If the network is assumed static and it does change, this + * can have tragic consequences. For example, this **CANNOT** be used + * with MetaMask, since the used can select a new network from the + * drop-down at any time. + * + * **``batchStallTime``** - how long (ms) to aggregate requests into a + * single batch. ``0`` indicates batching will only encompass the current + * event loop. If ``batchMaxCount = 1``, this is ignored. (default: ``10``) + * + * **``batchMaxSize``** - target maximum size (bytes) to allow per batch + * request (default: 1Mb) + * + * **``batchMaxCount``** - maximum number of requests to allow in a batch. + * If ``batchMaxCount = 1``, then batching is disabled. (default: ``100``) + * + * **``cacheTimeout``** - passed as [[AbstractProviderOptions]]. + */ +export type JsonRpcApiProviderOptions = { + staticNetwork?: null | Network | boolean; + batchStallTime?: number; + batchMaxSize?: number; + batchMaxCount?: number; + cacheTimeout?: number; +}; +/** + * A **JsonRpcTransactionRequest** is formatted as needed by the JSON-RPC + * Ethereum API specification. + */ +export interface JsonRpcTransactionRequest { + /** + * The sender address to use when signing. + */ + from?: string; + /** + * The target address. + */ + to?: string; + /** + * The transaction data. + */ + data?: string; + /** + * The chain ID the transaction is valid on. + */ + chainId?: string; + /** + * The [[link-eip-2718]] transaction type. + */ + type?: string; + /** + * The maximum amount of gas to allow a transaction to consume. + * + * In most other places in quais, this is called ``gasLimit`` which + * differs from the JSON-RPC Ethereum API specification. + */ + gas?: string; + /** + * The gas price per wei for transactions prior to [[link-eip-1559]]. + */ + gasPrice?: string; + /** + * The maximum fee per gas for [[link-eip-1559]] transactions. + */ + maxFeePerGas?: string; + /** + * The maximum priority fee per gas for [[link-eip-1559]] transactions. + */ + maxPriorityFeePerGas?: string; + /** + * The nonce for the transaction. + */ + nonce?: string; + /** + * The transaction value (in wei). + */ + value?: string; + /** + * The transaction access list. + */ + accessList?: Array<{ + address: string; + storageKeys: Array; + }>; +} +export declare class JsonRpcSigner extends AbstractSigner { + address: string; + constructor(provider: JsonRpcApiProvider, address: string); + connect(provider: null | Provider): Signer; + getAddress(): Promise; + populateTransaction(tx: TransactionRequest): Promise>; + sendUncheckedTransaction(_tx: TransactionRequest): Promise; + sendTransaction(tx: TransactionRequest): Promise; + signTransaction(_tx: TransactionRequest): Promise; + signMessage(_message: string | Uint8Array): Promise; + signTypedData(domain: TypedDataDomain, types: Record>, _value: Record): Promise; + unlock(password: string): Promise; + _legacySignMessage(_message: string | Uint8Array): Promise; +} +/** + * The JsonRpcApiProvider is an abstract class and **MUST** be + * sub-classed. + * + * It provides the base for all JSON-RPC-based Provider interaction. + * + * Sub-classing Notes: + * - a sub-class MUST override _send + * - a sub-class MUST call the `_start()` method once connected + */ +export declare abstract class JsonRpcApiProvider extends AbstractProvider { + #private; + initPromise?: Promise; + constructor(network?: Networkish, options?: JsonRpcApiProviderOptions); + /** + * Returns the value associated with the option %%key%%. + * + * Sub-classes can use this to inquire about configuration options. + */ + _getOption(key: K): JsonRpcApiProviderOptions[K]; + /** + * Gets the [[Network]] this provider has committed to. On each call, the network + * is detected, and if it has changed, the call will reject. + */ + get _network(): Network; + /** + * Sends a JSON-RPC %%payload%% (or a batch) to the underlying channel. + * + * Sub-classes **MUST** override this. + */ + abstract _send(payload: JsonRpcPayload | Array, shard?: string): Promise>; + /** + * Resolves to the non-normalized value by performing %%req%%. + * + * Sub-classes may override this to modify behavior of actions, + * and should generally call ``super._perform`` as a fallback. + */ + _perform(req: PerformActionRequest): Promise; + /** + * Sub-classes may override this; it detects the *actual* network that + * we are **currently** connected to. + * + * Keep in mind that [[send]] may only be used once [[ready]], otherwise the + * _send primitive must be used instead. + */ + _detectNetwork(): Promise; + /** + * Sub-classes **MUST** call this. Until [[_start]] has been called, no calls + * will be passed to [[_send]] from [[send]]. If it is overridden, then + * ``super._start()`` **MUST** be called. + * + * Calling it multiple times is safe and has no effect. + */ + _start(): void; + /** + * Resolves once the [[_start]] has been called. This can be used in + * sub-classes to defer sending data until the connection has been + * established. + */ + _waitUntilReady(): Promise; + /** + * Return a Subscriber that will manage the %%sub%%. + * + * Sub-classes may override this to modify the behavior of + * subscription management. + */ + _getSubscriber(sub: Subscription): Subscriber; + /** + * Returns true only if the [[_start]] has been called. + */ + get ready(): boolean; + /** + * Returns %%tx%% as a normalized JSON-RPC transaction request, + * which has all values hexlified and any numeric values converted + * to Quantity values. + */ + getRpcTransaction(tx: TransactionRequest): JsonRpcTransactionRequest; + /** + * Returns the request method and arguments required to perform + * %%req%%. + */ + getRpcRequest(req: PerformActionRequest): null | { + method: string; + args: Array; + }; + /** + * Returns an quais-style Error for the given JSON-RPC error + * %%payload%%, coalescing the various strings and error shapes + * that different nodes return, coercing them into a machine-readable + * standardized error. + */ + getRpcError(payload: JsonRpcPayload, _error: JsonRpcError): Error; + /** + * Requests the %%method%% with %%params%% via the JSON-RPC protocol + * over the underlying channel. This can be used to call methods + * on the backend that do not have a high-level API within the Provider + * API. + * + * This method queues requests according to the batch constraints + * in the options, assigns the request a unique ID. + * + * **Do NOT override** this method in sub-classes; instead + * override [[_send]] or force the options values in the + * call to the constructor to modify this method's behavior. + */ + send(method: string, params: Array | Record, shard?: string): Promise; + /** + * Resolves to the [[Signer]] account for %%address%% managed by + * the client. + * + * If the %%address%% is a number, it is used as an index in the + * the accounts from [[listAccounts]]. + * + * This can only be used on clients which manage accounts (such as + * Geth with imported account or MetaMask). + * + * Throws if the account doesn't exist. + */ + getSigner(address?: number | string): Promise; + listAccounts(): Promise>; + destroy(): void; +} +/** + * The JsonRpcProvider is one of the most common Providers, + * which performs all operations over HTTP (or HTTPS) requests. + * + * Events are processed by polling the backend for the current block + * number; when it advances, all block-base events are then checked + * for updates. + */ +export declare class JsonRpcProvider extends JsonRpcApiProvider { + constructor(urls?: string | string[] | FetchRequest, network?: Networkish, options?: JsonRpcApiProviderOptions); + _getSubscriber(sub: Subscription): Subscriber; + _getConnection(shard?: string): FetchRequest; + send(method: string, params: Array | Record, shard?: string): Promise; + _send(payload: JsonRpcPayload | Array, shard?: string): Promise>; +} +//# sourceMappingURL=provider-jsonrpc.d.ts.map \ No newline at end of file diff --git a/lib.esm/providers/provider-jsonrpc.d.ts.map b/lib.esm/providers/provider-jsonrpc.d.ts.map new file mode 100644 index 00000000..2af20c84 --- /dev/null +++ b/lib.esm/providers/provider-jsonrpc.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-jsonrpc.d.ts","sourceRoot":"","sources":["../../src.ts/providers/provider-jsonrpc.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAWH,OAAO,EAGH,YAAY,EACf,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,gBAAgB,EAAuB,MAAM,wBAAwB,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAGvC,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAE/D,OAAO,KAAK,EAAE,oBAAoB,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAC7F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,KAAK,EAAE,QAAQ,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACvF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAsC1C;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IACzB;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;O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E,GAAG,CAAC,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC;IAU5F,KAAK,CAAC,OAAO,EAAE,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;CAa9G"} \ No newline at end of file diff --git a/lib.esm/providers/provider-jsonrpc.js b/lib.esm/providers/provider-jsonrpc.js new file mode 100644 index 00000000..206783cf --- /dev/null +++ b/lib.esm/providers/provider-jsonrpc.js @@ -0,0 +1,959 @@ +/** + * One of the most common ways to interact with the blockchain is + * by a node running a JSON-RPC interface which can be connected to, + * based on the transport, using: + * + * - HTTP or HTTPS - [[JsonRpcProvider]] + * - WebSocket - [[WebSocketProvider]] + * - IPC - [[IpcSocketProvider]] + * + * @_section: api/providers/jsonrpc:JSON-RPC Provider [about-jsonrpcProvider] + */ +// @TODO: +// - Add the batching API +// https://playground.open-rpc.org/?schemaUrl=https://raw.githubusercontent.com/ethereum/eth1.0-apis/assembled-spec/openrpc.json&uiSchema%5BappBar%5D%5Bui:splitView%5D=true&uiSchema%5BappBar%5D%5Bui:input%5D=false&uiSchema%5BappBar%5D%5Bui:examplesDropdown%5D=false +import { AbiCoder } from "../abi/index.js"; +import { getAddress, resolveAddress } from "../address/index.js"; +import { TypedDataEncoder } from "../hash/index.js"; +import { accessListify } from "../transaction/index.js"; +import { defineProperties, getBigInt, hexlify, isHexString, toQuantity, toUtf8Bytes, isError, makeError, assert, assertArgument, resolveProperties } from "../utils/index.js"; +import { AbstractProvider, UnmanagedSubscriber } from "./abstract-provider.js"; +import { AbstractSigner } from "./abstract-signer.js"; +import { Network } from "./network.js"; +import { FilterIdEventSubscriber, FilterIdPendingSubscriber } from "./subscriber-filterid.js"; +const Primitive = "bigint,boolean,function,number,string,symbol".split(/,/g); +//const Methods = "getAddress,then".split(/,/g); +function deepCopy(value) { + if (value == null || Primitive.indexOf(typeof (value)) >= 0) { + return value; + } + // Keep any Addressable + if (typeof (value.getAddress) === "function") { + return value; + } + if (Array.isArray(value)) { + return (value.map(deepCopy)); + } + if (typeof (value) === "object") { + return Object.keys(value).reduce((accum, key) => { + accum[key] = value[key]; + return accum; + }, {}); + } + throw new Error(`should not happen: ${value} (${typeof (value)})`); +} +function stall(duration) { + return new Promise((resolve) => { setTimeout(resolve, duration); }); +} +function getLowerCase(value) { + if (value) { + return value.toLowerCase(); + } + return value; +} +const defaultOptions = { + staticNetwork: null, + batchStallTime: 10, + batchMaxSize: (1 << 20), + batchMaxCount: 100, + cacheTimeout: 250 +}; +// @TODO: Unchecked Signers +export class JsonRpcSigner extends AbstractSigner { + address; + constructor(provider, address) { + super(provider); + address = getAddress(address); + defineProperties(this, { address }); + } + connect(provider) { + assert(false, "cannot reconnect JsonRpcSigner", "UNSUPPORTED_OPERATION", { + operation: "signer.connect" + }); + } + async getAddress() { + return this.address; + } + // JSON-RPC will automatially fill in nonce, etc. so we just check from + async populateTransaction(tx) { + return await this.populateCall(tx); + } + // Returns just the hash of the transaction after sent, which is what + // the bare JSON-RPC API does; + async sendUncheckedTransaction(_tx) { + const tx = deepCopy(_tx); + const promises = []; + // Make sure the from matches the sender + if (tx.from) { + const _from = tx.from; + promises.push((async () => { + const from = await resolveAddress(_from, this.provider); + assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx); + tx.from = from; + })()); + } + else { + tx.from = this.address; + } + // The JSON-RPC for quai_sendTransaction uses 90000 gas; if the user + // wishes to use this, it is easy to specify explicitly, otherwise + // we look it up for them. + if (tx.gasLimit == null) { + promises.push((async () => { + tx.gasLimit = await this.provider.estimateGas({ ...tx, from: this.address }); + })()); + } + // The address may be an ENS name or Addressable + if (tx.to != null) { + const _to = tx.to; + promises.push((async () => { + tx.to = await resolveAddress(_to, this.provider); + })()); + } + // Wait until all of our properties are filled in + if (promises.length) { + await Promise.all(promises); + } + const hexTx = this.provider.getRpcTransaction(tx); + return this.provider.send("quai_sendTransaction", [hexTx]); + } + async sendTransaction(tx) { + // This cannot be mined any earlier than any recent block + const shard = await this.shardFromAddress(tx.from); + const blockNumber = await this.provider.getBlockNumber(shard); + // Send the transaction + const hash = await this.sendUncheckedTransaction(tx); + // Unfortunately, JSON-RPC only provides and opaque transaction hash + // for a response, and we need the actual transaction, so we poll + // for it; it should show up very quickly + return await (new Promise((resolve, reject) => { + const timeouts = [1000, 100]; + let invalids = 0; + const checkTx = async () => { + try { + // Try getting the transaction + const tx = await this.provider.getTransaction(hash); + if (tx != null) { + resolve(tx.replaceableTransaction(blockNumber)); + return; + } + } + catch (error) { + // If we were cancelled: stop polling. + // If the data is bad: the node returns bad transactions + // If the network changed: calling again will also fail + // If unsupported: likely destroyed + if (isError(error, "CANCELLED") || isError(error, "BAD_DATA") || + isError(error, "NETWORK_ERROR" || isError(error, "UNSUPPORTED_OPERATION"))) { + if (error.info == null) { + error.info = {}; + } + error.info.sendTransactionHash = hash; + reject(error); + return; + } + // Stop-gap for misbehaving backends; see #4513 + if (isError(error, "INVALID_ARGUMENT")) { + invalids++; + if (error.info == null) { + error.info = {}; + } + error.info.sendTransactionHash = hash; + if (invalids > 10) { + reject(error); + return; + } + } + // Notify anyone that cares; but we will try again, since + // it is likely an intermittent service error + this.provider.emit("error", makeError("failed to fetch transation after sending (will try again)", "UNKNOWN_ERROR", { error })); + } + // Wait another 4 seconds + this.provider._setTimeout(() => { checkTx(); }, timeouts.pop() || 4000); + }; + checkTx(); + })); + } + async signTransaction(_tx) { + const tx = deepCopy(_tx); + // Make sure the from matches the sender + if (tx.from) { + const from = await resolveAddress(tx.from, this.provider); + assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx); + tx.from = from; + } + else { + tx.from = this.address; + } + const hexTx = this.provider.getRpcTransaction(tx); + return await this.provider.send("quai_signTransaction", [hexTx]); + } + async signMessage(_message) { + const message = ((typeof (_message) === "string") ? toUtf8Bytes(_message) : _message); + return await this.provider.send("personal_sign", [ + hexlify(message), this.address.toLowerCase() + ]); + } + async signTypedData(domain, types, _value) { + const value = deepCopy(_value); + // Populate any ENS names (in-place) + const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (value) => { + const address = await resolveAddress(value); + assertArgument(address != null, "TypedData does not support null address", "value", value); + return address; + }); + return await this.provider.send("quai_signTypedData_v4", [ + this.address.toLowerCase(), + JSON.stringify(TypedDataEncoder.getPayload(populated.domain, types, populated.value)) + ]); + } + async unlock(password) { + return this.provider.send("personal_unlockAccount", [ + this.address.toLowerCase(), password, null + ]); + } + // https://github.com/ethereum/wiki/wiki/JSON-RPC#quai_sign + async _legacySignMessage(_message) { + const message = ((typeof (_message) === "string") ? toUtf8Bytes(_message) : _message); + return await this.provider.send("quai_sign", [ + this.address.toLowerCase(), hexlify(message) + ]); + } +} +/** + * The JsonRpcApiProvider is an abstract class and **MUST** be + * sub-classed. + * + * It provides the base for all JSON-RPC-based Provider interaction. + * + * Sub-classing Notes: + * - a sub-class MUST override _send + * - a sub-class MUST call the `_start()` method once connected + */ +export class JsonRpcApiProvider extends AbstractProvider { + #options; + // The next ID to use for the JSON-RPC ID field + #nextId; + // Payloads are queued and triggered in batches using the drainTimer + #payloads; + #drainTimer; + #notReady; + #network; + #pendingDetectNetwork; + initPromise; + #scheduleDrain() { + if (this.#drainTimer) { + return; + } + // If we aren't using batching, no harm in sending it immediately + const stallTime = (this._getOption("batchMaxCount") === 1) ? 0 : this._getOption("batchStallTime"); + this.#drainTimer = setTimeout(() => { + this.#drainTimer = null; + const payloads = this.#payloads; + this.#payloads = []; + while (payloads.length) { + // Create payload batches that satisfy our batch constraints + const batch = [(payloads.shift())]; + while (payloads.length) { + if (batch.length === this.#options.batchMaxCount) { + break; + } + batch.push((payloads.shift())); + const bytes = JSON.stringify(batch.map((p) => p.payload)); + if (bytes.length > this.#options.batchMaxSize) { + payloads.unshift((batch.pop())); + break; + } + } + // Process the result to each payload + (async () => { + const payloadMap = new Map(); + for (let i = 0; i < batch.length; i++) { + if (!payloadMap.has(batch[i].shard)) { + if (batch[i].payload != null) { + payloadMap.set(batch[i].shard, [batch[i].payload]); + } + ; + } + else { + payloadMap.get(batch[i].shard)?.push(batch[i].payload); + } + } + let rawResult = []; + await Promise.all(Array.from(payloadMap).map(async ([key, value]) => { + const payload = value.length === 1 ? value[0] : value; + const shard = key; + this.emit("debug", { action: "sendRpcPayload", payload }); + rawResult.push(await this._send(payload, shard)); + this.emit("debug", { action: "receiveRpcResult", payload }); + })); + const result = rawResult.flat(); + try { + // Process results in batch order + for (const { resolve, reject, payload } of batch) { + if (this.destroyed) { + reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: payload.method })); + continue; + } + // Find the matching result + const resp = result.filter((r) => (r.id === payload.id))[0]; + // No result; the node failed us in unexpected ways + if (resp == null) { + const error = makeError("missing response for request", "BAD_DATA", { + value: result, info: { payload } + }); + this.emit("error", error); + reject(error); + continue; + } + // The response is an error + if ("error" in resp) { + reject(this.getRpcError(payload, resp)); + continue; + } + // All good; send the result + resolve(resp.result); + } + } + catch (error) { + this.emit("debug", { action: "receiveRpcError", error }); + for (const { reject } of batch) { + // @TODO: augment the error with the payload + reject(error); + } + } + })(); + } + }, stallTime); + } + constructor(network, options) { + super(network, options); + this.#nextId = 1; + this.#options = Object.assign({}, defaultOptions, options || {}); + this.#payloads = []; + this.#drainTimer = null; + this.#network = null; + this.#pendingDetectNetwork = null; + { + let resolve = null; + const promise = new Promise((_resolve) => { + resolve = _resolve; + }); + this.#notReady = { promise, resolve }; + } + const staticNetwork = this._getOption("staticNetwork"); + if (typeof (staticNetwork) === "boolean") { + assertArgument(!staticNetwork || network !== "any", "staticNetwork cannot be used on special network 'any'", "options", options); + if (staticNetwork && network != null) { + this.#network = Network.from(network); + } + } + else if (staticNetwork) { + // Make sure any static network is compatbile with the provided netwrok + assertArgument(network == null || staticNetwork.matches(network), "staticNetwork MUST match network object", "options", options); + this.#network = staticNetwork; + } + } + /** + * Returns the value associated with the option %%key%%. + * + * Sub-classes can use this to inquire about configuration options. + */ + _getOption(key) { + return this.#options[key]; + } + /** + * Gets the [[Network]] this provider has committed to. On each call, the network + * is detected, and if it has changed, the call will reject. + */ + get _network() { + assert(this.#network, "network is not available yet", "NETWORK_ERROR"); + return this.#network; + } + /** + * Resolves to the non-normalized value by performing %%req%%. + * + * Sub-classes may override this to modify behavior of actions, + * and should generally call ``super._perform`` as a fallback. + */ + async _perform(req) { + // Legacy networks do not like the type field being passed along (which + // is fair), so we delete type if it is 0 and a non-EIP-1559 network + await this.initPromise; + if (req.method === "call" || req.method === "estimateGas") { + let tx = req.transaction; + if (tx && tx.type != null && getBigInt(tx.type)) { + // If there are no EIP-1559 properties, it might be non-EIP-a559 + if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) { + const feeData = await this.getFeeData(req.shard); + if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) { + // Network doesn't know about EIP-1559 (and hence type) + req = Object.assign({}, req, { + transaction: Object.assign({}, tx, { type: undefined }) + }); + } + } + } + } + const request = this.getRpcRequest(req); + if (request != null) { + return await this.send(request.method, request.args, req.shard); + } + return super._perform(req); + } + /** + * Sub-classes may override this; it detects the *actual* network that + * we are **currently** connected to. + * + * Keep in mind that [[send]] may only be used once [[ready]], otherwise the + * _send primitive must be used instead. + */ + async _detectNetwork() { + const network = this._getOption("staticNetwork"); + if (network) { + if (network === true) { + if (this.#network) { + return this.#network; + } + } + else { + return network; + } + } + if (this.#pendingDetectNetwork) { + return await this.#pendingDetectNetwork; + } + // If we are ready, use ``send``, which enabled requests to be batched + if (this.ready) { + this.#pendingDetectNetwork = (async () => { + try { + const result = Network.from(getBigInt(await this.send("quai_chainId", []))); + this.#pendingDetectNetwork = null; + return result; + } + catch (error) { + this.#pendingDetectNetwork = null; + throw error; + } + })(); + return await this.#pendingDetectNetwork; + } + // We are not ready yet; use the primitive _send + this.#pendingDetectNetwork = (async () => { + const payload = { + id: this.#nextId++, method: "quai_chainId", params: [], jsonrpc: "2.0" + }; + this.emit("debug", { action: "sendRpcPayload", payload }); + let result; + try { + result = (await this._send(payload))[0]; + this.#pendingDetectNetwork = null; + } + catch (error) { + this.#pendingDetectNetwork = null; + this.emit("debug", { action: "receiveRpcError", error }); + throw error; + } + this.emit("debug", { action: "receiveRpcResult", result }); + if ("result" in result) { + return Network.from(getBigInt(result.result)); + } + throw this.getRpcError(payload, result); + })(); + return await this.#pendingDetectNetwork; + } + /** + * Sub-classes **MUST** call this. Until [[_start]] has been called, no calls + * will be passed to [[_send]] from [[send]]. If it is overridden, then + * ``super._start()`` **MUST** be called. + * + * Calling it multiple times is safe and has no effect. + */ + _start() { + if (this.#notReady == null || this.#notReady.resolve == null) { + return; + } + this.#notReady.resolve(); + this.#notReady = null; + (async () => { + // Bootstrap the network + while (this.#network == null && !this.destroyed) { + try { + this.#network = await this._detectNetwork(); + } + catch (error) { + if (this.destroyed) { + break; + } + console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"); + this.emit("error", makeError("failed to bootstrap network detection", "NETWORK_ERROR", { event: "initial-network-discovery", info: { error } })); + await stall(1000); + } + } + // Start dispatching requests + this.#scheduleDrain(); + })(); + } + /** + * Resolves once the [[_start]] has been called. This can be used in + * sub-classes to defer sending data until the connection has been + * established. + */ + async _waitUntilReady() { + if (this.#notReady == null) { + return; + } + return await this.#notReady.promise; + } + /** + * Return a Subscriber that will manage the %%sub%%. + * + * Sub-classes may override this to modify the behavior of + * subscription management. + */ + _getSubscriber(sub) { + // Pending Filters aren't availble via polling + if (sub.type === "pending") { + return new FilterIdPendingSubscriber(this); + } + if (sub.type === "event") { + return new FilterIdEventSubscriber(this, sub.filter); + } + // Orphaned Logs are handled automatically, by the filter, since + // logs with removed are emitted by it + if (sub.type === "orphan" && sub.filter.orphan === "drop-log") { + return new UnmanagedSubscriber("orphan"); + } + return super._getSubscriber(sub); + } + /** + * Returns true only if the [[_start]] has been called. + */ + get ready() { return this.#notReady == null; } + /** + * Returns %%tx%% as a normalized JSON-RPC transaction request, + * which has all values hexlified and any numeric values converted + * to Quantity values. + */ + getRpcTransaction(tx) { + const result = {}; + // JSON-RPC now requires numeric values to be "quantity" values + ["chainId", "gasLimit", "gasPrice", "type", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "value"].forEach((key) => { + if (tx[key] == null) { + return; + } + let dstKey = key; + if (key === "gasLimit") { + dstKey = "gas"; + } + result[dstKey] = toQuantity(getBigInt(tx[key], `tx.${key}`)); + }); + // Make sure addresses and data are lowercase + ["from", "to", "data"].forEach((key) => { + if (tx[key] == null) { + return; + } + result[key] = hexlify(tx[key]); + }); + // Normalize the access list object + if (tx.accessList) { + result["accessList"] = accessListify(tx.accessList); + } + return result; + } + /** + * Returns the request method and arguments required to perform + * %%req%%. + */ + getRpcRequest(req) { + switch (req.method) { + case "chainId": + return { method: "quai_chainId", args: [] }; + case "getBlockNumber": + return { method: "quai_blockNumber", args: [] }; + case "getGasPrice": + return { + method: "quai_baseFee", + args: [req.txType] + }; + case "getMaxPriorityFeePerGas": + return { method: "quai_maxPriorityFeePerGas", args: [] }; + case "getBalance": + return { + method: "quai_getBalance", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getTransactionCount": + return { + method: "quai_getTransactionCount", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getCode": + return { + method: "quai_getCode", + args: [getLowerCase(req.address), req.blockTag] + }; + case "getStorage": + return { + method: "quai_getStorageAt", + args: [ + getLowerCase(req.address), + ("0x" + req.position.toString(16)), + req.blockTag + ] + }; + case "broadcastTransaction": + return { + method: "quai_sendRawTransaction", + args: [req.signedTransaction] + }; + case "getBlock": + if ("blockTag" in req) { + return { + method: "quai_getBlockByNumber", + args: [req.blockTag, !!req.includeTransactions] + }; + } + else if ("blockHash" in req) { + return { + method: "quai_getBlockByHash", + args: [req.blockHash, !!req.includeTransactions] + }; + } + break; + case "getTransaction": + return { + method: "quai_getTransactionByHash", + args: [req.hash] + }; + case "getTransactionReceipt": + return { + method: "quai_getTransactionReceipt", + args: [req.hash] + }; + case "call": + return { + method: "quai_call", + args: [this.getRpcTransaction(req.transaction), req.blockTag] + }; + case "estimateGas": { + return { + method: "quai_estimateGas", + args: [this.getRpcTransaction(req.transaction)] + }; + } + case "getRunningLocations": { + return { + method: "quai_listRunningChains", + args: [] + }; + } + case "getProtocolTrieExpansionCount": { + return { + method: "quai_getProtocolExpansionNumber", + args: [] + }; + } + case "getQiRateAtBlock": { + return { + method: "quai_qiRateAtBlock", + args: [req.blockTag, req.amt] + }; + } + case "getQuaiRateAtBlock": { + return { + method: "quai_quaiRateAtBlock", + args: [req.blockTag, req.amt] + }; + } + case "getLogs": + if (req.filter && req.filter.address != null) { + if (Array.isArray(req.filter.address)) { + req.filter.address = req.filter.address.map(getLowerCase); + } + else { + req.filter.address = getLowerCase(req.filter.address); + } + } + return { method: "quai_getLogs", args: [req.filter] }; + } + return null; + } + /** + * Returns an quais-style Error for the given JSON-RPC error + * %%payload%%, coalescing the various strings and error shapes + * that different nodes return, coercing them into a machine-readable + * standardized error. + */ + getRpcError(payload, _error) { + const { method } = payload; + const { error } = _error; + if (method === "quai_estimateGas" && error.message) { + const msg = error.message; + if (!msg.match(/revert/i) && msg.match(/insufficient funds/i)) { + return makeError("insufficient funds", "INSUFFICIENT_FUNDS", { + transaction: (payload.params[0]), + info: { payload, error } + }); + } + } + if (method === "quai_call" || method === "quai_estimateGas") { + const result = spelunkData(error); + const e = AbiCoder.getBuiltinCallException((method === "quai_call") ? "call" : "estimateGas", (payload.params[0]), (result ? result.data : null)); + e.info = { error, payload }; + return e; + } + // Only estimateGas and call can return arbitrary contract-defined text, so now we + // we can process text safely. + const message = JSON.stringify(spelunkMessage(error)); + if (typeof (error.message) === "string" && error.message.match(/user denied|quais-user-denied/i)) { + const actionMap = { + quai_sign: "signMessage", + personal_sign: "signMessage", + quai_signTypedData_v4: "signTypedData", + quai_signTransaction: "signTransaction", + quai_sendTransaction: "sendTransaction", + quai_requestAccounts: "requestAccess", + wallet_requestAccounts: "requestAccess", + }; + return makeError(`user rejected action`, "ACTION_REJECTED", { + action: (actionMap[method] || "unknown"), + reason: "rejected", + info: { payload, error } + }); + } + if (method === "quai_sendRawTransaction" || method === "quai_sendTransaction") { + const transaction = (payload.params[0]); + if (message.match(/insufficient funds|base fee exceeds gas limit/i)) { + return makeError("insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", { + transaction, info: { error } + }); + } + if (message.match(/nonce/i) && message.match(/too low/i)) { + return makeError("nonce has already been used", "NONCE_EXPIRED", { transaction, info: { error } }); + } + // "replacement transaction underpriced" + if (message.match(/replacement transaction/i) && message.match(/underpriced/i)) { + return makeError("replacement fee too low", "REPLACEMENT_UNDERPRICED", { transaction, info: { error } }); + } + if (message.match(/only replay-protected/i)) { + return makeError("legacy pre-eip-155 transactions not supported", "UNSUPPORTED_OPERATION", { + operation: method, info: { transaction, info: { error } } + }); + } + } + let unsupported = !!message.match(/the method .* does not exist/i); + if (!unsupported) { + if (error && error.details && error.details.startsWith("Unauthorized method:")) { + unsupported = true; + } + } + if (unsupported) { + return makeError("unsupported operation", "UNSUPPORTED_OPERATION", { + operation: payload.method, info: { error, payload } + }); + } + return makeError("could not coalesce error", "UNKNOWN_ERROR", { error, payload }); + } + /** + * Requests the %%method%% with %%params%% via the JSON-RPC protocol + * over the underlying channel. This can be used to call methods + * on the backend that do not have a high-level API within the Provider + * API. + * + * This method queues requests according to the batch constraints + * in the options, assigns the request a unique ID. + * + * **Do NOT override** this method in sub-classes; instead + * override [[_send]] or force the options values in the + * call to the constructor to modify this method's behavior. + */ + send(method, params, shard) { + // @TODO: cache chainId?? purge on switch_networks + // We have been destroyed; no operations are supported anymore + if (this.destroyed) { + return Promise.reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: method })); + } + const id = this.#nextId++; + const promise = new Promise((resolve, reject) => { + this.#payloads.push({ + resolve, reject, + payload: { method, params, id, jsonrpc: "2.0" }, + shard: shard + }); + }); + // If there is not a pending drainTimer, set one + this.#scheduleDrain(); + return promise; + } + /** + * Resolves to the [[Signer]] account for %%address%% managed by + * the client. + * + * If the %%address%% is a number, it is used as an index in the + * the accounts from [[listAccounts]]. + * + * This can only be used on clients which manage accounts (such as + * Geth with imported account or MetaMask). + * + * Throws if the account doesn't exist. + */ + // Works only if using a local node or browser wallet for this, otherwise cannot get accounts + async getSigner(address) { + if (address == null) { + address = 0; + } + const accountsPromise = this.send("quai_accounts", []); + // Account index + if (typeof (address) === "number") { + const accounts = (await accountsPromise); + if (address >= accounts.length) { + throw new Error("no such account"); + } + return new JsonRpcSigner(this, accounts[address]); + } + const { accounts } = await resolveProperties({ + network: this.getNetwork(), + accounts: accountsPromise + }); + // Account address + address = getAddress(address); + for (const account of accounts) { + if (getAddress(account) === address) { + return new JsonRpcSigner(this, address); + } + } + throw new Error("invalid account"); + } + async listAccounts() { + const accounts = await this.send("quai_accounts", []); + return accounts.map((a) => new JsonRpcSigner(this, a)); + } + destroy() { + // Stop processing requests + if (this.#drainTimer) { + clearTimeout(this.#drainTimer); + this.#drainTimer = null; + } + // Cancel all pending requests + for (const { payload, reject } of this.#payloads) { + reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: payload.method })); + } + this.#payloads = []; + // Parent clean-up + super.destroy(); + } +} +/** + * The JsonRpcProvider is one of the most common Providers, + * which performs all operations over HTTP (or HTTPS) requests. + * + * Events are processed by polling the backend for the current block + * number; when it advances, all block-base events are then checked + * for updates. + */ +export class JsonRpcProvider extends JsonRpcApiProvider { + constructor(urls, network, options) { + if (urls == null) { + urls = ["http:/\/localhost:8545"]; + } + super(network, options); + if (Array.isArray(urls)) { + this.initPromise = this.initUrlMap(urls); + } + else if (typeof urls === "string") { + this.initPromise = this.initUrlMap([urls]); + } + else { + this.initPromise = this.initUrlMap(urls.clone()); + } + } + _getSubscriber(sub) { + const subscriber = super._getSubscriber(sub); + return subscriber; + } + _getConnection(shard) { + const connection = this.connect[this.connect.length - 1].clone(); + if (typeof shard === "string") { + const shardBytes = this.shardBytes(shard); + connection.url = this._urlMap.get(shardBytes) ?? connection.url; + } + return connection; + } + async send(method, params, shard) { + // All requests are over HTTP, so we can just start handling requests + // We do this here rather than the constructor so that we don't send any + // requests to the network (i.e. quai_chainId) until we absolutely have to. + // await this.initPromise; + await this._start(); + return await super.send(method, params, shard); + } + async _send(payload, shard) { + // Configure a POST connection for the requested method + const request = this._getConnection(shard); + request.body = JSON.stringify(payload); + request.setHeader("content-type", "application/json"); + const response = await request.send(); + response.assertOk(); + let resp = response.bodyJson; + if (!Array.isArray(resp)) { + resp = [resp]; + } + return resp; + } +} +function spelunkData(value) { + if (value == null) { + return null; + } + // These *are* the droids we're looking for. + if (typeof (value.message) === "string" && value.message.match(/revert/i) && isHexString(value.data)) { + return { message: value.message, data: value.data }; + } + // Spelunk further... + if (typeof (value) === "object") { + for (const key in value) { + const result = spelunkData(value[key]); + if (result) { + return result; + } + } + return null; + } + // Might be a JSON string we can further descend... + if (typeof (value) === "string") { + try { + return spelunkData(JSON.parse(value)); + } + catch (error) { } + } + return null; +} +function _spelunkMessage(value, result) { + if (value == null) { + return; + } + // These *are* the droids we're looking for. + if (typeof (value.message) === "string") { + result.push(value.message); + } + // Spelunk further... + if (typeof (value) === "object") { + for (const key in value) { + _spelunkMessage(value[key], result); + } + } + // Might be a JSON string we can further descend... + if (typeof (value) === "string") { + try { + return _spelunkMessage(JSON.parse(value), result); + } + catch (error) { } + } +} +function spelunkMessage(value) { + const result = []; + _spelunkMessage(value, result); + return result; +} +//# sourceMappingURL=provider-jsonrpc.js.map \ No newline at end of file diff --git a/lib.esm/providers/provider-jsonrpc.js.map b/lib.esm/providers/provider-jsonrpc.js.map new file mode 100644 index 00000000..37b81f65 --- /dev/null +++ b/lib.esm/providers/provider-jsonrpc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-jsonrpc.js","sourceRoot":"","sources":["../../src.ts/providers/prov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 No newline at end of file diff --git a/lib.esm/providers/provider.d.ts b/lib.esm/providers/provider.d.ts new file mode 100644 index 00000000..fc553c0e --- /dev/null +++ b/lib.esm/providers/provider.d.ts @@ -0,0 +1,1122 @@ +import type { AddressLike, NameResolver } from "../address/index.js"; +import type { BigNumberish, EventEmitterable } from "../utils/index.js"; +import type { Signature } from "../crypto/index.js"; +import type { AccessList, AccessListish, TransactionLike } from "../transaction/index.js"; +import type { ContractRunner } from "./contracts.js"; +import type { Network } from "./network.js"; +/** + * A **BlockTag** specifies a specific block. + * + * **numeric value** - specifies the block height, where + * the genesis block is block 0; many operations accept a negative + * value which indicates the block number should be deducted from + * the most recent block. A numeric value may be a ``number``, ``bigint``, + * or a decimal of hex string. + * + * **blockhash** - specifies a specific block by its blockhash; this allows + * potentially orphaned blocks to be specifed, without ambiguity, but many + * backends do not support this for some operations. + */ +export type BlockTag = BigNumberish | string; +import { BlockParams, LogParams, TransactionReceiptParams, TransactionResponseParams } from "./formatting.js"; +/** + * A **FeeData** wraps all the fee-related values associated with + * the network. + */ +export declare class FeeData { + /** + * The gas price for legacy networks. + */ + readonly gasPrice: null | bigint; + /** + * The maximum fee to pay per gas. + * + * The base fee per gas is defined by the network and based on + * congestion, increasing the cost during times of heavy load + * and lowering when less busy. + * + * The actual fee per gas will be the base fee for the block + * and the priority fee, up to the max fee per gas. + * + * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559)) + */ + readonly maxFeePerGas: null | bigint; + /** + * The additional amout to pay per gas to encourage a validator + * to include the transaction. + * + * The purpose of this is to compensate the validator for the + * adjusted risk for including a given transaction. + * + * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559)) + */ + readonly maxPriorityFeePerGas: null | bigint; + /** + * Creates a new FeeData for %%gasPrice%%, %%maxFeePerGas%% and + * %%maxPriorityFeePerGas%%. + */ + constructor(gasPrice?: null | bigint, maxFeePerGas?: null | bigint, maxPriorityFeePerGas?: null | bigint); + /** + * Returns a JSON-friendly value. + */ + toJSON(): any; +} +/** + * A **TransactionRequest** is a transactions with potentially various + * properties not defined, or with less strict types for its values. + * + * This is used to pass to various operations, which will internally + * coerce any types and populate any necessary values. + */ +export interface TransactionRequest { + /** + * The transaction type. + */ + type?: null | number; + /** + * The target of the transaction. + */ + to?: null | AddressLike; + /** + * The sender of the transaction. + */ + from: AddressLike; + /** + * The nonce of the transaction, used to prevent replay attacks. + */ + nonce?: null | number; + /** + * The maximum amount of gas to allow this transaction to consime. + */ + gasLimit?: null | BigNumberish; + /** + * The gas price to use for legacy transactions or transactions on + * legacy networks. + * + * Most of the time the ``max*FeePerGas`` is preferred. + */ + gasPrice?: null | BigNumberish; + /** + * The [[link-eip-1559]] maximum priority fee to pay per gas. + */ + maxPriorityFeePerGas?: null | BigNumberish; + /** + * The [[link-eip-1559]] maximum total fee to pay per gas. The actual + * value used is protocol enforced to be the block's base fee. + */ + maxFeePerGas?: null | BigNumberish; + /** + * The transaction data. + */ + data?: null | string; + /** + * The transaction value (in wei). + */ + value?: null | BigNumberish; + /** + * The chain ID for the network this transaction is valid on. + */ + chainId?: null | BigNumberish; + /** + * The [[link-eip-2930]] access list. Storage slots included in the access + * list are //warmed// by pre-loading them, so their initial cost to + * fetch is guaranteed, but then each additional access is cheaper. + */ + accessList?: null | AccessListish; + /** + * A custom object, which can be passed along for network-specific + * values. + */ + customData?: any; + /** + * When using ``call`` or ``estimateGas``, this allows a specific + * block to be queried. Many backends do not support this and when + * unsupported errors are silently squelched and ``"latest"`` is used. + */ + blockTag?: BlockTag; + /** + * When using ``call``, this enables CCIP-read, which permits the + * provider to be redirected to web-based content during execution, + * which is then further validated by the contract. + * + * There are potential security implications allowing CCIP-read, as + * it could be used to expose the IP address or user activity during + * the fetch to unexpected parties. + */ + enableCcipRead?: boolean; + /** +* The external gas price. +*/ + externalGasPrice?: null | BigNumberish; + /** + * The external gas tip. + */ + externalGasTip?: null | BigNumberish; + /** + * The external gas limit. + */ + externalGasLimit?: null | BigNumberish; + /** + * The external data. + */ + externalData?: null | string; + /** + * The access list for berlin and london transactions. + */ + externalAccessList?: null | AccessListish; +} +/** + * A **PreparedTransactionRequest** is identical to a [[TransactionRequest]] + * except all the property types are strictly enforced. + */ +export interface PreparedTransactionRequest { + /** + * The transaction type. + */ + type?: number; + /** + * The target of the transaction. + */ + to?: AddressLike; + /** + * The sender of the transaction. + */ + from: AddressLike; + /** + * The nonce of the transaction, used to prevent replay attacks. + */ + nonce?: number; + /** + * The maximum amount of gas to allow this transaction to consime. + */ + gasLimit?: bigint; + /** + * The gas price to use for legacy transactions or transactions on + * legacy networks. + * + * Most of the time the ``max*FeePerGas`` is preferred. + */ + gasPrice?: bigint; + /** + * The [[link-eip-1559]] maximum priority fee to pay per gas. + */ + maxPriorityFeePerGas?: bigint; + /** + * The [[link-eip-1559]] maximum total fee to pay per gas. The actual + * value used is protocol enforced to be the block's base fee. + */ + maxFeePerGas?: bigint; + /** + * The transaction data. + */ + data?: string; + /** + * The transaction value (in wei). + */ + value?: bigint; + /** + * The chain ID for the network this transaction is valid on. + */ + chainId?: bigint; + /** + * The [[link-eip-2930]] access list. Storage slots included in the access + * list are //warmed// by pre-loading them, so their initial cost to + * fetch is guaranteed, but then each additional access is cheaper. + */ + accessList?: AccessList; + /** + * A custom object, which can be passed along for network-specific + * values. + */ + customData?: any; + /** + * When using ``call`` or ``estimateGas``, this allows a specific + * block to be queried. Many backends do not support this and when + * unsupported errors are silently squelched and ``"latest"`` is used. + */ + blockTag?: BlockTag; + /** + * When using ``call``, this enables CCIP-read, which permits the + * provider to be redirected to web-based content during execution, + * which is then further validated by the contract. + * + * There are potential security implications allowing CCIP-read, as + * it could be used to expose the IP address or user activity during + * the fetch to unexpected parties. + */ + enableCcipRead?: boolean; +} +/** + * Returns a copy of %%req%% with all properties coerced to their strict + * types. + */ +export declare function copyRequest(req: TransactionRequest): PreparedTransactionRequest; +/** + * An Interface to indicate a [[Block]] has been included in the + * blockchain. This asserts a Type Guard that necessary properties + * are non-null. + * + * Before a block is included, it is a //pending// block. + */ +export interface MinedBlock extends Block { + /** + * The block number also known as the block height. + */ + readonly number: number; + /** + * The block hash. + */ + readonly hash: string; + /** + * The block timestamp, in seconds from epoch. + */ + readonly timestamp: number; + /** + * The block date, created from the [[timestamp]]. + */ + readonly date: Date; + /** + * The miner of the block, also known as the ``author`` or + * block ``producer``. + */ + readonly miner: string; +} +/** + * A **Block** represents the data associated with a full block on + * Ethereum. + */ +export declare class Block implements BlockParams, Iterable { + #private; + /** + * The provider connected to the block used to fetch additional details + * if necessary. + */ + readonly provider: Provider; + /** + * The block number, sometimes called the block height. This is a + * sequential number that is one higher than the parent block. + */ + readonly number: Array | number; + /** + * The block hash. + * + * This hash includes all properties, so can be safely used to identify + * an exact set of block properties. + */ + readonly hash: null | string; + /** + * The timestamp for this block, which is the number of seconds since + * epoch that this block was included. + */ + readonly timestamp: number; + /** + * The block hash of the parent block. + */ + readonly parentHash: Array | string; + /** + * The nonce. + * + * On legacy networks, this is the random number inserted which + * permitted the difficulty target to be reached. + */ + readonly nonce: string; + /** + * The difficulty target. + * + * On legacy networks, this is the proof-of-work target required + * for a block to meet the protocol rules to be included. + * + * On modern networks, this is a random number arrived at using + * randao. @TODO: Find links? + */ + readonly difficulty: bigint; + /** + * The total gas limit for this block. + */ + readonly gasLimit: bigint; + /** + * The total gas used in this block. + */ + readonly gasUsed: bigint; + /** + * The miner coinbase address, wihch receives any subsidies for + * including this block. + */ + readonly miner: string; + /** + * Any extra data the validator wished to include. + */ + readonly extraData: string; + /** + * The base fee per gas that all transactions in this block were + * charged. + * + * This adjusts after each block, depending on how congested the network + * is. + */ + readonly baseFeePerGas: null | bigint; + readonly manifestHash: Array; + readonly location: bigint; + readonly parentDeltaS: Array; + readonly parentEntropy: Array; + readonly order: number; + readonly subManifest: Array | null; + readonly totalEntropy: bigint; + readonly mixHash: string; + readonly receiptsRoot: string; + readonly sha3Uncles: string; + readonly size: bigint; + readonly evmRoot: string; + readonly utxoRoot: string; + readonly uncles: Array | null; + readonly transactionsRoot: string; + readonly extRollupRoot: string; + readonly extTransactionsRoot: string; + /** + * Create a new **Block** object. + * + * This should generally not be necessary as the unless implementing a + * low-level library. + */ + constructor(block: BlockParams, provider: Provider); + /** + * Returns the list of transaction hashes, in the order + * they were executed within the block. + */ + get transactions(): ReadonlyArray; + get extTransactions(): ReadonlyArray; + /** + * Returns the complete transactions, in the order they + * were executed within the block. + * + * This is only available for blocks which prefetched + * transactions, by passing ``true`` to %%prefetchTxs%% + * into [[Provider-getBlock]]. + */ + get prefetchedTransactions(): Array; + get prefetchedExtTransactions(): Array; + /** + * Returns a JSON-friendly value. + */ + toJSON(): any; + [Symbol.iterator](): Iterator; + /** + * The number of transactions in this block. + */ + get length(): number; + /** + * The [[link-js-date]] this block was included at. + */ + get date(): null | Date; + /** + * Get the transaction at %%indexe%% within this block. + */ + getTransaction(indexOrHash: number | string): Promise; + getExtTransaction(indexOrHash: number | string): Promise; + /** + * If a **Block** was fetched with a request to include the transactions + * this will allow synchronous access to those transactions. + * + * If the transactions were not prefetched, this will throw. + */ + getPrefetchedTransaction(indexOrHash: number | string): TransactionResponse; + /** + * Returns true if this block been mined. This provides a type guard + * for all properties on a [[MinedBlock]]. + */ + isMined(): this is MinedBlock; + /** + * @_ignore: + */ + orphanedEvent(): OrphanFilter; +} +/** + * A **Log** in Ethereum represents an event that has been included in a + * transaction using the ``LOG*`` opcodes, which are most commonly used by + * Solidity's emit for announcing events. + */ +export declare class Log implements LogParams { + /** + * The provider connected to the log used to fetch additional details + * if necessary. + */ + readonly provider: Provider; + /** + * The transaction hash of the transaction this log occurred in. Use the + * [[Log-getTransaction]] to get the [[TransactionResponse]]. + */ + readonly transactionHash: string; + /** + * The block hash of the block this log occurred in. Use the + * [[Log-getBlock]] to get the [[Block]]. + */ + readonly blockHash: string; + /** + * The block number of the block this log occurred in. It is preferred + * to use the [[Block-hash]] when fetching the related [[Block]], + * since in the case of an orphaned block, the block at that height may + * have changed. + */ + readonly blockNumber: number; + /** + * If the **Log** represents a block that was removed due to an orphaned + * block, this will be true. + * + * This can only happen within an orphan event listener. + */ + readonly removed: boolean; + /** + * The address of the contract that emitted this log. + */ + readonly address: string; + /** + * The data included in this log when it was emitted. + */ + readonly data: string; + /** + * The indexed topics included in this log when it was emitted. + * + * All topics are included in the bloom filters, so they can be + * efficiently filtered using the [[Provider-getLogs]] method. + */ + readonly topics: ReadonlyArray; + /** + * The index within the block this log occurred at. This is generally + * not useful to developers, but can be used with the various roots + * to proof inclusion within a block. + */ + readonly index: number; + /** + * The index within the transaction of this log. + */ + readonly transactionIndex: number; + /** + * @_ignore: + */ + constructor(log: LogParams, provider: Provider); + /** + * Returns a JSON-compatible object. + */ + toJSON(): any; + /** + * Returns the block that this log occurred in. + */ + getBlock(shard: string): Promise; + /** + * Returns the transaction that this log occurred in. + */ + getTransaction(): Promise; + /** + * Returns the transaction receipt fot the transaction that this + * log occurred in. + */ + getTransactionReceipt(): Promise; + /** + * @_ignore: + */ + removedEvent(): OrphanFilter; +} +export declare function shardFromHash(hash: string): string; +/** + * A **TransactionReceipt** includes additional information about a + * transaction that is only available after it has been mined. + */ +export declare class TransactionReceipt implements TransactionReceiptParams, Iterable { + #private; + /** + * The provider connected to the log used to fetch additional details + * if necessary. + */ + readonly provider: Provider; + /** + * The address the transaction was sent to. + */ + readonly to: null | string; + /** + * The sender of the transaction. + */ + readonly from: string; + /** + * The address of the contract if the transaction was directly + * responsible for deploying one. + * + * This is non-null **only** if the ``to`` is empty and the ``data`` + * was successfully executed as initcode. + */ + readonly contractAddress: null | string; + /** + * The transaction hash. + */ + readonly hash: string; + /** + * The index of this transaction within the block transactions. + */ + readonly index: number; + /** + * The block hash of the [[Block]] this transaction was included in. + */ + readonly blockHash: string; + /** + * The block number of the [[Block]] this transaction was included in. + */ + readonly blockNumber: number; + /** + * The bloom filter bytes that represent all logs that occurred within + * this transaction. This is generally not useful for most developers, + * but can be used to validate the included logs. + */ + readonly logsBloom: string; + /** + * The actual amount of gas used by this transaction. + * + * When creating a transaction, the amount of gas that will be used can + * only be approximated, but the sender must pay the gas fee for the + * entire gas limit. After the transaction, the difference is refunded. + */ + readonly gasUsed: bigint; + /** + * The amount of gas used by all transactions within the block for this + * and all transactions with a lower ``index``. + * + * This is generally not useful for developers but can be used to + * validate certain aspects of execution. + */ + readonly cumulativeGasUsed: bigint; + /** + * The actual gas price used during execution. + * + * Due to the complexity of [[link-eip-1559]] this value can only + * be caluclated after the transaction has been mined, snce the base + * fee is protocol-enforced. + */ + readonly gasPrice: bigint; + /** + * The [[link-eip-2718]] transaction type. + */ + readonly type: number; + /** + * The status of this transaction, indicating success (i.e. ``1``) or + * a revert (i.e. ``0``). + * + * This is available in post-byzantium blocks, but some backends may + * backfill this value. + */ + readonly status: null | number; + readonly etxs: ReadonlyArray; + /** + * @_ignore: + */ + constructor(tx: TransactionReceiptParams, provider: Provider); + /** + * The logs for this transaction. + */ + get logs(): ReadonlyArray; + /** + * Returns a JSON-compatible representation. + */ + toJSON(): any; + /** + * @_ignore: + */ + get length(): number; + [Symbol.iterator](): Iterator; + /** + * The total fee for this transaction, in wei. + */ + get fee(): bigint; + /** + * Resolves to the block this transaction occurred in. + */ + getBlock(shard: string): Promise; + /** + * Resolves to the transaction this transaction occurred in. + */ + getTransaction(): Promise; + /** + * Resolves to the return value of the execution of this transaction. + * + * Support for this feature is limited, as it requires an archive node + * with the ``debug_`` or ``trace_`` API enabled. + */ + getResult(): Promise; + /** + * Resolves to the number of confirmations this transaction has. + */ + confirmations(): Promise; + /** + * @_ignore: + */ + removedEvent(): OrphanFilter; + /** + * @_ignore: + */ + reorderedEvent(other?: TransactionResponse): OrphanFilter; +} +/** + * A **MinedTransactionResponse** is an interface representing a + * transaction which has been mined and allows for a type guard for its + * property values being defined. + */ +export interface MinedTransactionResponse extends TransactionResponse { + /** + * The block number this transaction occurred in. + */ + blockNumber: number; + /** + * The block hash this transaction occurred in. + */ + blockHash: string; + /** + * The date this transaction occurred on. + */ + date: Date; +} +/** + * A **TransactionResponse** includes all properties about a transaction + * that was sent to the network, which may or may not be included in a + * block. + * + * The [[TransactionResponse-isMined]] can be used to check if the + * transaction has been mined as well as type guard that the otherwise + * possibly ``null`` properties are defined. + */ +export declare class TransactionResponse implements TransactionLike, TransactionResponseParams { + #private; + /** + * The provider this is connected to, which will influence how its + * methods will resolve its async inspection methods. + */ + readonly provider: Provider; + /** + * The block number of the block that this transaction was included in. + * + * This is ``null`` for pending transactions. + */ + readonly blockNumber: null | number; + /** + * The blockHash of the block that this transaction was included in. + * + * This is ``null`` for pending transactions. + */ + readonly blockHash: null | string; + /** + * The index within the block that this transaction resides at. + */ + readonly index: bigint; + /** + * The transaction hash. + */ + readonly hash: string; + /** + * The [[link-eip-2718]] transaction envelope type. This is + * ``0`` for legacy transactions types. + */ + readonly type: number; + /** + * The receiver of this transaction. + * + * If ``null``, then the transaction is an initcode transaction. + * This means the result of executing the [[data]] will be deployed + * as a new contract on chain (assuming it does not revert) and the + * address may be computed using [[getCreateAddress]]. + */ + readonly to: null | string; + /** + * The sender of this transaction. It is implicitly computed + * from the transaction pre-image hash (as the digest) and the + * [[signature]] using ecrecover. + */ + readonly from: string; + /** + * The nonce, which is used to prevent replay attacks and offer + * a method to ensure transactions from a given sender are explicitly + * ordered. + * + * When sending a transaction, this must be equal to the number of + * transactions ever sent by [[from]]. + */ + readonly nonce: number; + /** + * The maximum units of gas this transaction can consume. If execution + * exceeds this, the entries transaction is reverted and the sender + * is charged for the full amount, despite not state changes being made. + */ + readonly gasLimit: bigint; + /** + * The maximum priority fee (per unit of gas) to allow a + * validator to charge the sender. This is inclusive of the + * [[maxFeeFeePerGas]]. + */ + readonly maxPriorityFeePerGas: null | bigint; + /** + * The maximum fee (per unit of gas) to allow this transaction + * to charge the sender. + */ + readonly maxFeePerGas: null | bigint; + /** + * The data. + */ + readonly data: string; + /** + * The value, in wei. Use [[formatEther]] to format this value + * as ether. + */ + readonly value: bigint; + /** + * The chain ID. + */ + readonly chainId: bigint; + /** + * The signature. + */ + readonly signature: Signature; + /** + * The [[link-eip-2930]] access list for transaction types that + * support it, otherwise ``null``. + */ + readonly accessList: null | AccessList; + readonly etxGasLimit?: bigint; + readonly etxGasPrice?: bigint; + readonly etxGasTip?: bigint; + readonly etxData?: string; + readonly etxAccessList?: AccessList; + /** + * @_ignore: + */ + constructor(tx: TransactionResponseParams, provider: Provider); + /** + * Returns a JSON-compatible representation of this transaction. + */ + toJSON(): any; + /** + * Resolves to the Block that this transaction was included in. + * + * This will return null if the transaction has not been included yet. + */ + getBlock(shard: string): Promise; + /** + * Resolves to this transaction being re-requested from the + * provider. This can be used if you have an unmined transaction + * and wish to get an up-to-date populated instance. + */ + getTransaction(): Promise; + /** + * Resolve to the number of confirmations this transaction has. + */ + confirmations(): Promise; + /** + * Resolves once this transaction has been mined and has + * %%confirms%% blocks including it (default: ``1``) with an + * optional %%timeout%%. + * + * This can resolve to ``null`` only if %%confirms%% is ``0`` + * and the transaction has not been mined, otherwise this will + * wait until enough confirmations have completed. + */ + wait(_confirms?: number, _timeout?: number): Promise; + /** + * Returns ``true`` if this transaction has been included. + * + * This is effective only as of the time the TransactionResponse + * was instantiated. To get up-to-date information, use + * [[getTransaction]]. + * + * This provides a Type Guard that this transaction will have + * non-null property values for properties that are null for + * unmined transactions. + */ + isMined(): this is MinedTransactionResponse; + /** + * Returns a filter which can be used to listen for orphan events + * that evict this transaction. + */ + removedEvent(): OrphanFilter; + /** + * Returns a filter which can be used to listen for orphan events + * that re-order this event against %%other%%. + */ + reorderedEvent(other?: TransactionResponse): OrphanFilter; + /** + * Returns a new TransactionResponse instance which has the ability to + * detect (and throw an error) if the transaction is replaced, which + * will begin scanning at %%startBlock%%. + * + * This should generally not be used by developers and is intended + * primarily for internal use. Setting an incorrect %%startBlock%% can + * have devastating performance consequences if used incorrectly. + */ + replaceableTransaction(startBlock: number): TransactionResponse; +} +/** + * An Orphan Filter allows detecting when an orphan block has + * resulted in dropping a block or transaction or has resulted + * in transactions changing order. + * + * Not currently fully supported. + */ +export type OrphanFilter = { + orphan: "drop-block"; + hash: string; + number: number; +} | { + orphan: "drop-transaction"; + tx: { + hash: string; + blockHash: string; + blockNumber: number; + }; + other?: { + hash: string; + blockHash: string; + blockNumber: number; + }; +} | { + orphan: "reorder-transaction"; + tx: { + hash: string; + blockHash: string; + blockNumber: number; + }; + other?: { + hash: string; + blockHash: string; + blockNumber: number; + }; +} | { + orphan: "drop-log"; + log: { + transactionHash: string; + blockHash: string; + blockNumber: number; + address: string; + data: string; + topics: ReadonlyArray; + index: number; + }; +}; +/** + * A **TopicFilter** provides a struture to define bloom-filter + * queries. + * + * Each field that is ``null`` matches **any** value, a field that is + * a ``string`` must match exactly that value and and ``array`` is + * effectively an ``OR``-ed set, where any one of those values must + * match. + */ +export type TopicFilter = Array>; +/** + * An **EventFilter** allows efficiently filtering logs (also known as + * events) using bloom filters included within blocks. + */ +export interface EventFilter { + address?: AddressLike | Array; + topics?: TopicFilter; +} +/** + * A **Filter** allows searching a specific range of blocks for mathcing + * logs. + */ +export interface Filter extends EventFilter { + /** + * The start block for the filter (inclusive). + */ + fromBlock?: BlockTag; + /** + * The end block for the filter (inclusive). + */ + toBlock?: BlockTag; + shard: string; +} +/** + * A **FilterByBlockHash** allows searching a specific block for mathcing + * logs. + */ +export interface FilterByBlockHash extends EventFilter { + /** + * The blockhash of the specific block for the filter. + */ + blockHash?: string; + shard: string; +} +/** + * A **ProviderEvent** provides the types of events that can be subscribed + * to on a [[Provider]]. + * + * Each provider may include additional possible events it supports, but + * the most commonly supported are: + * + * **``"block"``** - calls the listener with the current block number on each + * new block. + * + * **``"error"``** - calls the listener on each async error that occurs during + * the event loop, with the error. + * + * **``"debug"``** - calls the listener on debug events, which can be used to + * troubleshoot network errors, provider problems, etc. + * + * **``transaction hash``** - calls the listener on each block after the + * transaction has been mined; generally ``.once`` is more appropriate for + * this event. + * + * **``Array``** - calls the listener on each log that matches the filter. + * + * [[EventFilter]] - calls the listener with each matching log + */ +export type ProviderEvent = string | Array> | EventFilter | OrphanFilter; +/** + * A **Provider** is the primary method to interact with the read-only + * content on Ethereum. + * + * It allows access to details about accounts, blocks and transactions + * and the ability to query event logs and simulate contract execution. + * + * Account data includes the [balance](getBalance), + * [transaction count](getTransactionCount), [code](getCode) and + * [state trie storage](getStorage). + * + * Simulating execution can be used to [call](call), + * [estimate gas](estimateGas) and + * [get transaction results](getTransactionResult). + * + * The [[broadcastTransaction]] is the only method which allows updating + * the blockchain, but it is usually accessed by a [[Signer]], since a + * private key must be used to sign the transaction before it can be + * broadcast. + */ +export interface Provider extends ContractRunner, EventEmitterable, NameResolver { + /** + * The provider iteself. + * + * This is part of the necessary API for executing a contract, as + * it provides a common property on any [[ContractRunner]] that + * can be used to access the read-only portion of the runner. + */ + provider: this; + /** + * Shutdown any resources this provider is using. No additional + * calls should be made to this provider after calling this. + */ + destroy(): void; + /** + * Get the current block number. + */ + getBlockNumber(shard: string): Promise; + /** + * Get the connected [[Network]]. + */ + getNetwork(shard?: string): Promise; + /** + * Get the best guess at the recommended [[FeeData]]. + */ + getFeeData(shard: string): Promise; + /** + * Get the account balance (in wei) of %%address%%. If %%blockTag%% + * is specified and the node supports archive access for that + * %%blockTag%%, the balance is as of that [[BlockTag]]. + * + * @note On nodes without archive access enabled, the %%blockTag%% may be + * **silently ignored** by the node, which may cause issues if relied on. + */ + getBalance(address: AddressLike, blockTag?: BlockTag): Promise; + /** + * Get the number of transactions ever sent for %%address%%, which + * is used as the ``nonce`` when sending a transaction. If + * %%blockTag%% is specified and the node supports archive access + * for that %%blockTag%%, the transaction count is as of that + * [[BlockTag]]. + * + * @note On nodes without archive access enabled, the %%blockTag%% may be + * **silently ignored** by the node, which may cause issues if relied on. + */ + getTransactionCount(address: AddressLike, blockTag?: BlockTag): Promise; + /** + * Get the bytecode for %%address%%. + * + * @note On nodes without archive access enabled, the %%blockTag%% may be + * **silently ignored** by the node, which may cause issues if relied on. + */ + getCode(address: AddressLike, blockTag?: BlockTag): Promise; + /** + * Get the storage slot value for %%address%% at slot %%position%%. + * + * @note On nodes without archive access enabled, the %%blockTag%% may be + * **silently ignored** by the node, which may cause issues if relied on. + */ + getStorage(address: AddressLike, position: BigNumberish, blockTag?: BlockTag): Promise; + /** + * Estimates the amount of gas required to executre %%tx%%. + */ + estimateGas(tx: TransactionRequest): Promise; + /** + * Simulate the execution of %%tx%%. If the call reverts, it will + * throw a [[CallExceptionError]] which includes the revert data. + */ + call(tx: TransactionRequest): Promise; + /** + * Broadcasts the %%signedTx%% to the network, adding it to the + * memory pool of any node for which the transaction meets the + * rebroadcast requirements. + */ + broadcastTransaction(shard: string, signedTx: string): Promise; + /** + * Resolves to the block for %%blockHashOrBlockTag%%. + * + * If %%prefetchTxs%%, and the backend supports including transactions + * with block requests, all transactions will be included and the + * [[Block]] object will not need to make remote calls for getting + * transactions. + */ + getBlock(shard: string, blockHashOrBlockTag: BlockTag | string, prefetchTxs?: boolean): Promise; + /** + * Resolves to the transaction for %%hash%%. + * + * If the transaction is unknown or on pruning nodes which + * discard old transactions this resolves to ``null``. + */ + getTransaction(hash: string): Promise; + /** + * Resolves to the transaction receipt for %%hash%%, if mined. + * + * If the transaction has not been mined, is unknown or on + * pruning nodes which discard old transactions this resolves to + * ``null``. + */ + getTransactionReceipt(hash: string): Promise; + /** + * Resolves to the result returned by the executions of %%hash%%. + * + * This is only supported on nodes with archive access and with + * the necessary debug APIs enabled. + */ + getTransactionResult(hash: string): Promise; + /** + * Resolves to the list of Logs that match %%filter%% + */ + getLogs(filter: Filter | FilterByBlockHash): Promise>; + /** + * Resolves to the address configured for the %%ensName%% or + * ``null`` if unconfigured. + */ + resolveName(ensName: string): Promise; + /** + * Resolves to the ENS name associated for the %%address%% or + * ``null`` if the //primary name// is not configured. + * + * Users must perform additional steps to configure a //primary name//, + * which is not currently common. + */ + lookupAddress(address: string): Promise; + /** + * Waits until the transaction %%hash%% is mined and has %%confirms%% + * confirmations. + */ + waitForTransaction(hash: string, confirms?: number, timeout?: number): Promise; + /** + * Resolves to the block at %%blockTag%% once it has been mined. + * + * This can be useful for waiting some number of blocks by using + * the ``currentBlockNumber + N``. + */ + waitForBlock(shard: string, blockTag?: BlockTag): Promise; +} +//# sourceMappingURL=provider.d.ts.map \ No newline at end of file diff --git a/lib.esm/providers/provider.d.ts.map b/lib.esm/providers/provider.d.ts.map new file mode 100644 index 00000000..2c32d120 --- /dev/null +++ b/lib.esm/providers/provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src.ts/providers/provider.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACxE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAE1F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAK5C;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,QAAQ,GAAG,YAAY,GAAG,MAAM,CAAC;AAE7C,OAAO,EACH,WAAW,EAAE,SAAS,EAAE,wBAAwB,EAChD,yBAAyB,EAC5B,MAAM,iBAAiB,CAAC;AAgBzB;;;GAGG;AACH,qBAAa,OAAO;IAChB;;OAEG;IACH,QAAQ,CAAC,QAAQ,EAAG,IAAI,GAAG,MAAM,CAAC;IAElC;;;;;;;;;;;OAWG;IACH,QAAQ,CAAC,YAAY,EAAG,IAAI,GAAG,MAAM,CAAC;IAEtC;;;;;;;;OAQG;IACH,QAAQ,CAAC,oBAAoB,EAAG,IAAI,GAAG,MAAM,CAAC;IAE9C;;;OAGG;gBACS,QAAQ,CAAC,EAAE,IAAI,GA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AAG,KAAK,CAAC,CAAC;IAE9G;;;;;OAKG;IACH,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,mBAAmB,CAAC,CAAC;IAElE;;;;;;OAMG;IACH,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,kBAAkB,CAAC,CAAC;IAExE;;;;;OAKG;IACH,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC;IAM3D;;OAEG;IACH,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,iBAAiB,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;IAMjE;;;OAGG;IACH,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC;IAErD;;;;;;OAMG;IACH,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC;IAEvD;;;OAGG;IACH,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,kBAAkB,CAAC,CAAC;IAE1G;;;;;OAKG;IACH,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;CACpE"} \ No newline at end of file diff --git a/lib.esm/providers/provider.js b/lib.esm/providers/provider.js new file mode 100644 index 00000000..6de96c62 --- /dev/null +++ b/lib.esm/providers/provider.js @@ -0,0 +1,1320 @@ +//import { resolveAddress } from "@quaisproject/address"; +import { defineProperties, getBigInt, getNumber, hexlify, resolveProperties, assert, assertArgument, isError, makeError } from "../utils/index.js"; +import { accessListify } from "../transaction/index.js"; +const BN_0 = BigInt(0); +// ----------------------- +function getValue(value) { + if (value == null) { + return null; + } + return value; +} +function toJson(value) { + if (value == null) { + return null; + } + return value.toString(); +} +// @TODO? implements Required +/** + * A **FeeData** wraps all the fee-related values associated with + * the network. + */ +export class FeeData { + /** + * The gas price for legacy networks. + */ + gasPrice; + /** + * The maximum fee to pay per gas. + * + * The base fee per gas is defined by the network and based on + * congestion, increasing the cost during times of heavy load + * and lowering when less busy. + * + * The actual fee per gas will be the base fee for the block + * and the priority fee, up to the max fee per gas. + * + * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559)) + */ + maxFeePerGas; + /** + * The additional amout to pay per gas to encourage a validator + * to include the transaction. + * + * The purpose of this is to compensate the validator for the + * adjusted risk for including a given transaction. + * + * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559)) + */ + maxPriorityFeePerGas; + /** + * Creates a new FeeData for %%gasPrice%%, %%maxFeePerGas%% and + * %%maxPriorityFeePerGas%%. + */ + constructor(gasPrice, maxFeePerGas, maxPriorityFeePerGas) { + defineProperties(this, { + gasPrice: getValue(gasPrice), + maxFeePerGas: getValue(maxFeePerGas), + maxPriorityFeePerGas: getValue(maxPriorityFeePerGas) + }); + } + /** + * Returns a JSON-friendly value. + */ + toJSON() { + const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = this; + return { + _type: "FeeData", + gasPrice: toJson(gasPrice), + maxFeePerGas: toJson(maxFeePerGas), + maxPriorityFeePerGas: toJson(maxPriorityFeePerGas), + }; + } +} +; +/** + * Returns a copy of %%req%% with all properties coerced to their strict + * types. + */ +export function copyRequest(req) { + const result = {}; + // These could be addresses, ENS names or Addressables + if (req.to) { + result.to = req.to; + } + if (req.from) { + result.from = req.from; + } + if (req.data) { + result.data = hexlify(req.data); + } + const bigIntKeys = "chainId,gasLimit,gasPrice,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/); + for (const key of bigIntKeys) { + if (!(key in req) || req[key] == null) { + continue; + } + result[key] = getBigInt(req[key], `request.${key}`); + } + const numberKeys = "type,nonce".split(/,/); + for (const key of numberKeys) { + if (!(key in req) || req[key] == null) { + continue; + } + result[key] = getNumber(req[key], `request.${key}`); + } + if (req.accessList) { + result.accessList = accessListify(req.accessList); + } + if ("blockTag" in req) { + result.blockTag = req.blockTag; + } + if ("enableCcipRead" in req) { + result.enableCcipRead = !!req.enableCcipRead; + } + if ("customData" in req) { + result.customData = req.customData; + } + return result; +} +/** + * A **Block** represents the data associated with a full block on + * Ethereum. + */ +export class Block { + /** + * The provider connected to the block used to fetch additional details + * if necessary. + */ + provider; + /** + * The block number, sometimes called the block height. This is a + * sequential number that is one higher than the parent block. + */ + number; + /** + * The block hash. + * + * This hash includes all properties, so can be safely used to identify + * an exact set of block properties. + */ + hash; + /** + * The timestamp for this block, which is the number of seconds since + * epoch that this block was included. + */ + timestamp; + /** + * The block hash of the parent block. + */ + parentHash; + /** + * The nonce. + * + * On legacy networks, this is the random number inserted which + * permitted the difficulty target to be reached. + */ + nonce; + /** + * The difficulty target. + * + * On legacy networks, this is the proof-of-work target required + * for a block to meet the protocol rules to be included. + * + * On modern networks, this is a random number arrived at using + * randao. @TODO: Find links? + */ + difficulty; + /** + * The total gas limit for this block. + */ + gasLimit; + /** + * The total gas used in this block. + */ + gasUsed; + /** + * The miner coinbase address, wihch receives any subsidies for + * including this block. + */ + miner; + /** + * Any extra data the validator wished to include. + */ + extraData; + /** + * The base fee per gas that all transactions in this block were + * charged. + * + * This adjusts after each block, depending on how congested the network + * is. + */ + baseFeePerGas; + manifestHash; + location; + parentDeltaS; + parentEntropy; + order; + subManifest; + totalEntropy; + mixHash; + receiptsRoot; + sha3Uncles; + size; + evmRoot; + utxoRoot; + uncles; + #transactions; + transactionsRoot; + extRollupRoot; + #extTransactions; + extTransactionsRoot; + /** + * Create a new **Block** object. + * + * This should generally not be necessary as the unless implementing a + * low-level library. + */ + constructor(block, provider) { + this.#transactions = block.transactions.map((tx) => { + if (typeof (tx) !== "string") { + return new TransactionResponse(tx, provider); + } + return tx; + }); + this.#extTransactions = block.extTransactions.map((tx) => { + if (typeof (tx) !== "string") { + return new TransactionResponse(tx, provider); + } + return tx; + }); + this.transactionsRoot = block.transactionsRoot; + this.extRollupRoot = block.extRollupRoot; + this.extTransactionsRoot = block.extTransactionsRoot; + defineProperties(this, { + provider, + hash: getValue(block.hash), + number: block.number, + timestamp: block.timestamp, + parentHash: block.parentHash, + nonce: block.nonce, + difficulty: block.difficulty, + gasLimit: block.gasLimit, + gasUsed: block.gasUsed, + miner: block.miner, + extraData: block.extraData, + baseFeePerGas: getValue(block.baseFeePerGas), + manifestHash: block.manifestHash, + location: block.location, + parentDeltaS: block.parentDeltaS, + parentEntropy: block.parentEntropy, + order: block.order, + subManifest: block.subManifest, + totalEntropy: block.totalEntropy, + mixHash: block.mixHash, + receiptsRoot: block.receiptsRoot, + sha3Uncles: block.sha3Uncles, + size: block.size, + evmRoot: block.evmRoot, + utxoRoot: block.utxoRoot, + uncles: block.uncles, + transactionsRoot: block.transactionsRoot, + extRollupRoot: block.extRollupRoot, + extTransactionsRoot: block.extTransactionsRoot, + }); + } + /** + * Returns the list of transaction hashes, in the order + * they were executed within the block. + */ + get transactions() { + return this.#transactions.map((tx) => { + if (typeof (tx) === "string") { + return tx; + } + return tx.hash; + }); + } + get extTransactions() { + return this.#extTransactions.map((tx) => { + if (typeof (tx) === "string") { + return tx; + } + return tx.hash; + }); + } + /** + * Returns the complete transactions, in the order they + * were executed within the block. + * + * This is only available for blocks which prefetched + * transactions, by passing ``true`` to %%prefetchTxs%% + * into [[Provider-getBlock]]. + */ + get prefetchedTransactions() { + const txs = this.#transactions.slice(); + // Doesn't matter... + if (txs.length === 0) { + return []; + } + // Make sure we prefetched the transactions + assert(typeof (txs[0]) === "object", "transactions were not prefetched with block request", "UNSUPPORTED_OPERATION", { + operation: "transactionResponses()" + }); + return txs; + } + get prefetchedExtTransactions() { + const txs = this.#extTransactions.slice(); + // Doesn't matter... + if (txs.length === 0) { + return []; + } + // Make sure we prefetched the transactions + assert(typeof (txs[0]) === "object", "transactions were not prefetched with block request", "UNSUPPORTED_OPERATION", { + operation: "transactionResponses()" + }); + return txs; + } + /** + * Returns a JSON-friendly value. + */ + toJSON() { + const { baseFeePerGas, difficulty, extraData, gasLimit, gasUsed, hash, miner, nonce, number, parentHash, timestamp, manifestHash, location, parentDeltaS, parentEntropy, order, subManifest, totalEntropy, mixHash, receiptsRoot, sha3Uncles, size, evmRoot, utxoRoot, uncles, transactionsRoot, extRollupRoot, extTransactionsRoot } = this; + // Using getters to retrieve the transactions and extTransactions + const transactions = this.transactions; + const extTransactions = this.extTransactions; + return { + _type: "Block", + baseFeePerGas: toJson(baseFeePerGas), + difficulty: toJson(difficulty), + extraData, + gasLimit: toJson(gasLimit), + gasUsed: toJson(gasUsed), + hash, + miner, + nonce, + number, + parentHash, + timestamp, + manifestHash, + location, + parentDeltaS, + parentEntropy, + order, + subManifest, + totalEntropy, + mixHash, + receiptsRoot, + sha3Uncles, + size, + evmRoot, + utxoRoot, + uncles, + transactionsRoot, + extRollupRoot, + extTransactionsRoot, + transactions, + extTransactions // Includes the extended transaction hashes or full transactions based on the prefetched data + }; + } + [Symbol.iterator]() { + let index = 0; + const txs = this.transactions; + return { + next: () => { + if (index < this.length) { + return { + value: txs[index++], done: false + }; + } + return { value: undefined, done: true }; + } + }; + } + /** + * The number of transactions in this block. + */ + get length() { return this.#transactions.length; } + /** + * The [[link-js-date]] this block was included at. + */ + get date() { + if (this.timestamp == null) { + return null; + } + return new Date(this.timestamp * 1000); + } + /** + * Get the transaction at %%indexe%% within this block. + */ + async getTransaction(indexOrHash) { + // Find the internal value by its index or hash + let tx = undefined; + if (typeof (indexOrHash) === "number") { + tx = this.#transactions[indexOrHash]; + } + else { + const hash = indexOrHash.toLowerCase(); + for (const v of this.#transactions) { + if (typeof (v) === "string") { + if (v !== hash) { + continue; + } + tx = v; + break; + } + else { + if (v.hash === hash) { + continue; + } + tx = v; + break; + } + } + } + if (tx == null) { + throw new Error("no such tx"); + } + if (typeof (tx) === "string") { + return (await this.provider.getTransaction(tx)); + } + else { + return tx; + } + } + async getExtTransaction(indexOrHash) { + // Find the internal value by its index or hash + let tx = undefined; + if (typeof (indexOrHash) === "number") { + tx = this.#extTransactions[indexOrHash]; + } + else { + const hash = indexOrHash.toLowerCase(); + for (const v of this.#extTransactions) { + if (typeof (v) === "string") { + if (v !== hash) { + continue; + } + tx = v; + break; + } + else { + if (v.hash === hash) { + continue; + } + tx = v; + break; + } + } + } + if (tx == null) { + throw new Error("no such tx"); + } + if (typeof (tx) === "string") { + return (await this.provider.getTransaction(tx)); + } + else { + return tx; + } + } + /** + * If a **Block** was fetched with a request to include the transactions + * this will allow synchronous access to those transactions. + * + * If the transactions were not prefetched, this will throw. + */ + getPrefetchedTransaction(indexOrHash) { + const txs = this.prefetchedTransactions; + if (typeof (indexOrHash) === "number") { + return txs[indexOrHash]; + } + indexOrHash = indexOrHash.toLowerCase(); + for (const tx of txs) { + if (tx.hash === indexOrHash) { + return tx; + } + } + assertArgument(false, "no matching transaction", "indexOrHash", indexOrHash); + } + /** + * Returns true if this block been mined. This provides a type guard + * for all properties on a [[MinedBlock]]. + */ + isMined() { return !!this.hash; } + /** + * @_ignore: + */ + orphanedEvent() { + if (!this.isMined()) { + throw new Error(""); + } + return createOrphanedBlockFilter(this); + } +} +////////////////////// +// Log +/** + * A **Log** in Ethereum represents an event that has been included in a + * transaction using the ``LOG*`` opcodes, which are most commonly used by + * Solidity's emit for announcing events. + */ +export class Log { + /** + * The provider connected to the log used to fetch additional details + * if necessary. + */ + provider; + /** + * The transaction hash of the transaction this log occurred in. Use the + * [[Log-getTransaction]] to get the [[TransactionResponse]]. + */ + transactionHash; + /** + * The block hash of the block this log occurred in. Use the + * [[Log-getBlock]] to get the [[Block]]. + */ + blockHash; + /** + * The block number of the block this log occurred in. It is preferred + * to use the [[Block-hash]] when fetching the related [[Block]], + * since in the case of an orphaned block, the block at that height may + * have changed. + */ + blockNumber; + /** + * If the **Log** represents a block that was removed due to an orphaned + * block, this will be true. + * + * This can only happen within an orphan event listener. + */ + removed; + /** + * The address of the contract that emitted this log. + */ + address; + /** + * The data included in this log when it was emitted. + */ + data; + /** + * The indexed topics included in this log when it was emitted. + * + * All topics are included in the bloom filters, so they can be + * efficiently filtered using the [[Provider-getLogs]] method. + */ + topics; + /** + * The index within the block this log occurred at. This is generally + * not useful to developers, but can be used with the various roots + * to proof inclusion within a block. + */ + index; + /** + * The index within the transaction of this log. + */ + transactionIndex; + /** + * @_ignore: + */ + constructor(log, provider) { + this.provider = provider; + const topics = Object.freeze(log.topics.slice()); + defineProperties(this, { + transactionHash: log.transactionHash, + blockHash: log.blockHash, + blockNumber: log.blockNumber, + removed: log.removed, + address: log.address, + data: log.data, + topics, + index: log.index, + transactionIndex: log.transactionIndex, + }); + } + /** + * Returns a JSON-compatible object. + */ + toJSON() { + const { address, blockHash, blockNumber, data, index, removed, topics, transactionHash, transactionIndex } = this; + return { + _type: "log", + address, blockHash, blockNumber, data, index, + removed, topics, transactionHash, transactionIndex + }; + } + /** + * Returns the block that this log occurred in. + */ + async getBlock(shard) { + const block = await this.provider.getBlock(shard, this.blockHash); + assert(!!block, "failed to find transaction", "UNKNOWN_ERROR", {}); + return block; + } + /** + * Returns the transaction that this log occurred in. + */ + async getTransaction() { + const tx = await this.provider.getTransaction(this.transactionHash); + assert(!!tx, "failed to find transaction", "UNKNOWN_ERROR", {}); + return tx; + } + /** + * Returns the transaction receipt fot the transaction that this + * log occurred in. + */ + async getTransactionReceipt() { + const receipt = await this.provider.getTransactionReceipt(this.transactionHash); + assert(!!receipt, "failed to find transaction receipt", "UNKNOWN_ERROR", {}); + return receipt; + } + /** + * @_ignore: + */ + removedEvent() { + return createRemovedLogFilter(this); + } +} +////////////////////// +// Transaction Receipt +export function shardFromHash(hash) { + return hash.slice(0, 4); +} +/** + * A **TransactionReceipt** includes additional information about a + * transaction that is only available after it has been mined. + */ +export class TransactionReceipt { + /** + * The provider connected to the log used to fetch additional details + * if necessary. + */ + provider; + /** + * The address the transaction was sent to. + */ + to; + /** + * The sender of the transaction. + */ + from; + /** + * The address of the contract if the transaction was directly + * responsible for deploying one. + * + * This is non-null **only** if the ``to`` is empty and the ``data`` + * was successfully executed as initcode. + */ + contractAddress; + /** + * The transaction hash. + */ + hash; + /** + * The index of this transaction within the block transactions. + */ + index; + /** + * The block hash of the [[Block]] this transaction was included in. + */ + blockHash; + /** + * The block number of the [[Block]] this transaction was included in. + */ + blockNumber; + /** + * The bloom filter bytes that represent all logs that occurred within + * this transaction. This is generally not useful for most developers, + * but can be used to validate the included logs. + */ + logsBloom; + /** + * The actual amount of gas used by this transaction. + * + * When creating a transaction, the amount of gas that will be used can + * only be approximated, but the sender must pay the gas fee for the + * entire gas limit. After the transaction, the difference is refunded. + */ + gasUsed; + /** + * The amount of gas used by all transactions within the block for this + * and all transactions with a lower ``index``. + * + * This is generally not useful for developers but can be used to + * validate certain aspects of execution. + */ + cumulativeGasUsed; + /** + * The actual gas price used during execution. + * + * Due to the complexity of [[link-eip-1559]] this value can only + * be caluclated after the transaction has been mined, snce the base + * fee is protocol-enforced. + */ + gasPrice; + /** + * The [[link-eip-2718]] transaction type. + */ + type; + //readonly byzantium!: boolean; + /** + * The status of this transaction, indicating success (i.e. ``1``) or + * a revert (i.e. ``0``). + * + * This is available in post-byzantium blocks, but some backends may + * backfill this value. + */ + status; + /** + * The root hash of this transaction. + * + * This is no present and was only included in pre-byzantium blocks, but + * could be used to validate certain parts of the receipt. + */ + #logs; + etxs; + /** + * @_ignore: + */ + constructor(tx, provider) { + this.#logs = Object.freeze(tx.logs.map((log) => { + return new Log(log, provider); + })); + let gasPrice = BN_0; + if (tx.effectiveGasPrice != null) { + gasPrice = tx.effectiveGasPrice; + } + else if (tx.gasPrice != null) { + gasPrice = tx.gasPrice; + } + defineProperties(this, { + provider, + to: tx.to, + from: tx.from, + contractAddress: tx.contractAddress, + hash: tx.hash, + index: tx.index, + blockHash: tx.blockHash, + blockNumber: tx.blockNumber, + logsBloom: tx.logsBloom, + gasUsed: tx.gasUsed, + cumulativeGasUsed: tx.cumulativeGasUsed, + gasPrice, + etxs: tx.etxs, + type: tx.type, + //byzantium: tx.byzantium, + status: tx.status, + }); + } + /** + * The logs for this transaction. + */ + get logs() { return this.#logs; } + /** + * Returns a JSON-compatible representation. + */ + toJSON() { + const { to, from, contractAddress, hash, index, blockHash, blockNumber, logsBloom, logs, //byzantium, + status } = this; + return { + _type: "TransactionReceipt", + blockHash, blockNumber, + //byzantium, + contractAddress, + cumulativeGasUsed: toJson(this.cumulativeGasUsed), + from, + gasPrice: toJson(this.gasPrice), + gasUsed: toJson(this.gasUsed), + hash, index, logs, logsBloom, status, to + }; + } + /** + * @_ignore: + */ + get length() { return this.logs.length; } + [Symbol.iterator]() { + let index = 0; + return { + next: () => { + if (index < this.length) { + return { value: this.logs[index++], done: false }; + } + return { value: undefined, done: true }; + } + }; + } + /** + * The total fee for this transaction, in wei. + */ + get fee() { + return this.gasUsed * this.gasPrice; + } + /** + * Resolves to the block this transaction occurred in. + */ + async getBlock(shard) { + const block = await this.provider.getBlock(shard, this.blockHash); + if (block == null) { + throw new Error("TODO"); + } + return block; + } + /** + * Resolves to the transaction this transaction occurred in. + */ + async getTransaction() { + const tx = await this.provider.getTransaction(this.hash); + if (tx == null) { + throw new Error("TODO"); + } + return tx; + } + /** + * Resolves to the return value of the execution of this transaction. + * + * Support for this feature is limited, as it requires an archive node + * with the ``debug_`` or ``trace_`` API enabled. + */ + async getResult() { + return (await this.provider.getTransactionResult(this.hash)); + } + /** + * Resolves to the number of confirmations this transaction has. + */ + async confirmations() { + const shard = shardFromHash(this.hash); + return (await this.provider.getBlockNumber(shard)) - this.blockNumber + 1; + } + /** + * @_ignore: + */ + removedEvent() { + return createRemovedTransactionFilter(this); + } + /** + * @_ignore: + */ + reorderedEvent(other) { + assert(!other || other.isMined(), "unmined 'other' transction cannot be orphaned", "UNSUPPORTED_OPERATION", { operation: "reorderedEvent(other)" }); + return createReorderedTransactionFilter(this, other); + } +} +/** + * A **TransactionResponse** includes all properties about a transaction + * that was sent to the network, which may or may not be included in a + * block. + * + * The [[TransactionResponse-isMined]] can be used to check if the + * transaction has been mined as well as type guard that the otherwise + * possibly ``null`` properties are defined. + */ +export class TransactionResponse { + /** + * The provider this is connected to, which will influence how its + * methods will resolve its async inspection methods. + */ + provider; + /** + * The block number of the block that this transaction was included in. + * + * This is ``null`` for pending transactions. + */ + blockNumber; + /** + * The blockHash of the block that this transaction was included in. + * + * This is ``null`` for pending transactions. + */ + blockHash; + /** + * The index within the block that this transaction resides at. + */ + index; + /** + * The transaction hash. + */ + hash; + /** + * The [[link-eip-2718]] transaction envelope type. This is + * ``0`` for legacy transactions types. + */ + type; + /** + * The receiver of this transaction. + * + * If ``null``, then the transaction is an initcode transaction. + * This means the result of executing the [[data]] will be deployed + * as a new contract on chain (assuming it does not revert) and the + * address may be computed using [[getCreateAddress]]. + */ + to; + /** + * The sender of this transaction. It is implicitly computed + * from the transaction pre-image hash (as the digest) and the + * [[signature]] using ecrecover. + */ + from; + /** + * The nonce, which is used to prevent replay attacks and offer + * a method to ensure transactions from a given sender are explicitly + * ordered. + * + * When sending a transaction, this must be equal to the number of + * transactions ever sent by [[from]]. + */ + nonce; + /** + * The maximum units of gas this transaction can consume. If execution + * exceeds this, the entries transaction is reverted and the sender + * is charged for the full amount, despite not state changes being made. + */ + gasLimit; + /** + * The maximum priority fee (per unit of gas) to allow a + * validator to charge the sender. This is inclusive of the + * [[maxFeeFeePerGas]]. + */ + maxPriorityFeePerGas; + /** + * The maximum fee (per unit of gas) to allow this transaction + * to charge the sender. + */ + maxFeePerGas; + /** + * The data. + */ + data; + /** + * The value, in wei. Use [[formatEther]] to format this value + * as ether. + */ + value; + /** + * The chain ID. + */ + chainId; + /** + * The signature. + */ + signature; + /** + * The [[link-eip-2930]] access list for transaction types that + * support it, otherwise ``null``. + */ + accessList; + // Extrernal transaction specific fields + etxGasLimit; + etxGasPrice; + etxGasTip; + etxData; + etxAccessList; + #startBlock; + /** + * @_ignore: + */ + constructor(tx, provider) { + this.provider = provider; + this.blockNumber = (tx.blockNumber != null) ? tx.blockNumber : null; + this.blockHash = (tx.blockHash != null) ? tx.blockHash : null; + this.hash = tx.hash; + this.index = tx.index; + this.type = tx.type; + this.from = tx.from; + this.to = tx.to || null; + this.gasLimit = tx.gasLimit; + this.nonce = tx.nonce; + this.data = tx.data; + this.value = tx.value; + this.maxPriorityFeePerGas = (tx.maxPriorityFeePerGas != null) ? tx.maxPriorityFeePerGas : null; + this.maxFeePerGas = (tx.maxFeePerGas != null) ? tx.maxFeePerGas : null; + this.chainId = tx.chainId; + this.signature = tx.signature; + this.accessList = (tx.accessList != null) ? tx.accessList : null; + if (tx.type != 2) { + delete tx.etxGasLimit; + delete tx.etxGasPrice; + delete tx.etxGasTip; + delete tx.etxData; + delete tx.etxAccessList; + } + if (tx.etxGasLimit) + this.etxGasLimit = tx.etxGasLimit; + if (tx.etxGasPrice) + this.etxGasPrice = tx.etxGasPrice; + if (tx.etxGasTip) + this.etxGasTip = tx.etxGasTip; + if (tx.etxData) + this.etxData = tx.etxData; + if (tx.etxAccessList) + this.etxAccessList = tx.etxAccessList; + this.#startBlock = -1; + } + /** + * Returns a JSON-compatible representation of this transaction. + */ + toJSON() { + const { blockNumber, blockHash, index, hash, type, to, from, nonce, data, signature, accessList, + //etxGasLimit, etxGasPrice, etxGasTip, etxData, etxAccessList // Include new fields + } = this; + let result = { + _type: "TransactionReceipt", + accessList, blockNumber, blockHash, + chainId: toJson(this.chainId), + data, from, + gasLimit: toJson(this.gasLimit), + hash, + maxFeePerGas: toJson(this.maxFeePerGas), + maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas), + nonce, signature, to, index, type, + value: toJson(this.value), + // Include new fields in the output + // etxGasLimit: etxGasLimit ? toJson(etxGasLimit) : null, + // etxGasPrice: etxGasPrice ? toJson(etxGasPrice) : null, + // etxGasTip: etxGasTip ? toJson(etxGasTip) : null, + // etxData: etxData ? etxData : null, + // etxAccessList: etxAccessList ? etxAccessList : null + }; + return result; + } + /** + * Resolves to the Block that this transaction was included in. + * + * This will return null if the transaction has not been included yet. + */ + async getBlock(shard) { + let blockNumber = this.blockNumber; + if (blockNumber == null) { + const tx = await this.getTransaction(); + if (tx) { + blockNumber = tx.blockNumber; + } + } + if (blockNumber == null) { + return null; + } + const block = this.provider.getBlock(shard, blockNumber); + if (block == null) { + throw new Error("TODO"); + } + return block; + } + /** + * Resolves to this transaction being re-requested from the + * provider. This can be used if you have an unmined transaction + * and wish to get an up-to-date populated instance. + */ + async getTransaction() { + return this.provider.getTransaction(this.hash); + } + /** + * Resolve to the number of confirmations this transaction has. + */ + async confirmations() { + const shard = shardFromHash(this.hash); + if (this.blockNumber == null) { + const { tx, blockNumber } = await resolveProperties({ + tx: this.getTransaction(), + blockNumber: this.provider.getBlockNumber(shard) + }); + // Not mined yet... + if (tx == null || tx.blockNumber == null) { + return 0; + } + return blockNumber - tx.blockNumber + 1; + } + const blockNumber = await this.provider.getBlockNumber(shard); + return blockNumber - this.blockNumber + 1; + } + /** + * Resolves once this transaction has been mined and has + * %%confirms%% blocks including it (default: ``1``) with an + * optional %%timeout%%. + * + * This can resolve to ``null`` only if %%confirms%% is ``0`` + * and the transaction has not been mined, otherwise this will + * wait until enough confirmations have completed. + */ + async wait(_confirms, _timeout) { + const confirms = (_confirms == null) ? 1 : _confirms; + const timeout = (_timeout == null) ? 0 : _timeout; + let startBlock = this.#startBlock; + let nextScan = -1; + let stopScanning = (startBlock === -1) ? true : false; + const shard = shardFromHash(this.hash); + const checkReplacement = async () => { + // Get the current transaction count for this sender + if (stopScanning) { + return null; + } + const { blockNumber, nonce } = await resolveProperties({ + blockNumber: this.provider.getBlockNumber(shard), + nonce: this.provider.getTransactionCount(this.from) + }); + // No transaction or our nonce has not been mined yet; but we + // can start scanning later when we do start + if (nonce < this.nonce) { + startBlock = blockNumber; + return; + } + // We were mined; no replacement + if (stopScanning) { + return null; + } + const mined = await this.getTransaction(); + if (mined && mined.blockNumber != null) { + return; + } + // We were replaced; start scanning for that transaction + // Starting to scan; look back a few extra blocks for safety + if (nextScan === -1) { + nextScan = startBlock - 3; + if (nextScan < this.#startBlock) { + nextScan = this.#startBlock; + } + } + while (nextScan <= blockNumber) { + // Get the next block to scan + if (stopScanning) { + return null; + } + const block = await this.provider.getBlock(shard, nextScan, true); + // This should not happen; but we'll try again shortly + if (block == null) { + return; + } + // We were mined; no replacement + for (const hash of block) { + if (hash === this.hash) { + return; + } + } + // Search for the transaction that replaced us + for (let i = 0; i < block.length; i++) { + const tx = await block.getTransaction(i); + if (tx.from === this.from && tx.nonce === this.nonce) { + // Get the receipt + if (stopScanning) { + return null; + } + const receipt = await this.provider.getTransactionReceipt(tx.hash); + // This should not happen; but we'll try again shortly + if (receipt == null) { + return; + } + // We will retry this on the next block (this case could be optimized) + if ((blockNumber - receipt.blockNumber + 1) < confirms) { + return; + } + // The reason we were replaced + let reason = "replaced"; + if (tx.data === this.data && tx.to === this.to && tx.value === this.value) { + reason = "repriced"; + } + else if (tx.data === "0x" && tx.from === tx.to && tx.value === BN_0) { + reason = "cancelled"; + } + assert(false, "transaction was replaced", "TRANSACTION_REPLACED", { + cancelled: (reason === "replaced" || reason === "cancelled"), + reason, + replacement: tx.replaceableTransaction(startBlock), + hash: tx.hash, + receipt + }); + } + } + nextScan++; + } + return; + }; + const checkReceipt = (receipt) => { + if (receipt == null || receipt.status !== 0) { + return receipt; + } + assert(false, "transaction execution reverted", "CALL_EXCEPTION", { + action: "sendTransaction", + data: null, reason: null, invocation: null, revert: null, + transaction: { + to: receipt.to, + from: receipt.from, + data: "" // @TODO: in v7, split out sendTransaction properties + }, receipt + }); + }; + const receipt = await this.provider.getTransactionReceipt(this.hash); + if (confirms === 0) { + return checkReceipt(receipt); + } + if (receipt) { + if ((await receipt.confirmations()) >= confirms) { + return checkReceipt(receipt); + } + } + else { + // Check for a replacement; throws if a replacement was found + await checkReplacement(); + // Allow null only when the confirms is 0 + if (confirms === 0) { + return null; + } + } + const waiter = new Promise((resolve, reject) => { + // List of things to cancel when we have a result (one way or the other) + const cancellers = []; + const cancel = () => { cancellers.forEach((c) => c()); }; + // On cancel, stop scanning for replacements + cancellers.push(() => { stopScanning = true; }); + // Set up any timeout requested + if (timeout > 0) { + const timer = setTimeout(() => { + cancel(); + reject(makeError("wait for transaction timeout", "TIMEOUT")); + }, timeout); + cancellers.push(() => { clearTimeout(timer); }); + } + const txListener = async (receipt) => { + // Done; return it! + if ((await receipt.confirmations()) >= confirms) { + cancel(); + try { + resolve(checkReceipt(receipt)); + } + catch (error) { + reject(error); + } + } + }; + cancellers.push(() => { this.provider.off(this.hash, txListener); }); + this.provider.on(this.hash, txListener); + // We support replacement detection; start checking + if (startBlock >= 0) { + const replaceListener = async () => { + try { + // Check for a replacement; this throws only if one is found + await checkReplacement(); + } + catch (error) { + // We were replaced (with enough confirms); re-throw the error + if (isError(error, "TRANSACTION_REPLACED")) { + cancel(); + reject(error); + return; + } + } + // Rescheudle a check on the next block + if (!stopScanning) { + this.provider.once("block", replaceListener); + } + }; + cancellers.push(() => { this.provider.off("block", replaceListener); }); + this.provider.once("block", replaceListener); + } + }); + return await waiter; + } + /** + * Returns ``true`` if this transaction has been included. + * + * This is effective only as of the time the TransactionResponse + * was instantiated. To get up-to-date information, use + * [[getTransaction]]. + * + * This provides a Type Guard that this transaction will have + * non-null property values for properties that are null for + * unmined transactions. + */ + isMined() { + return (this.blockHash != null); + } + /** + * Returns a filter which can be used to listen for orphan events + * that evict this transaction. + */ + removedEvent() { + assert(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }); + return createRemovedTransactionFilter(this); + } + /** + * Returns a filter which can be used to listen for orphan events + * that re-order this event against %%other%%. + */ + reorderedEvent(other) { + assert(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }); + assert(!other || other.isMined(), "unmined 'other' transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }); + return createReorderedTransactionFilter(this, other); + } + /** + * Returns a new TransactionResponse instance which has the ability to + * detect (and throw an error) if the transaction is replaced, which + * will begin scanning at %%startBlock%%. + * + * This should generally not be used by developers and is intended + * primarily for internal use. Setting an incorrect %%startBlock%% can + * have devastating performance consequences if used incorrectly. + */ + replaceableTransaction(startBlock) { + assertArgument(Number.isInteger(startBlock) && startBlock >= 0, "invalid startBlock", "startBlock", startBlock); + const tx = new TransactionResponse(this, this.provider); + tx.#startBlock = startBlock; + return tx; + } +} +function createOrphanedBlockFilter(block) { + return { orphan: "drop-block", hash: block.hash, number: block.number }; +} +function createReorderedTransactionFilter(tx, other) { + return { orphan: "reorder-transaction", tx, other }; +} +function createRemovedTransactionFilter(tx) { + return { orphan: "drop-transaction", tx }; +} +function createRemovedLogFilter(log) { + return { orphan: "drop-log", log: { + transactionHash: log.transactionHash, + blockHash: log.blockHash, + blockNumber: log.blockNumber, + address: log.address, + data: log.data, + topics: Object.freeze(log.topics.slice()), + index: log.index + } }; +} +//# sourceMappingURL=provider.js.map \ No newline at end of file diff --git a/lib.esm/providers/provider.js.map b/lib.esm/providers/provider.js.map new file mode 100644 index 00000000..3557baa5 --- /dev/null +++ b/lib.esm/providers/provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src.ts/providers/provider.ts"],"names":[],"mappings":"AAAA,yDAAyD;AACzD,OAAO,EACH,gBAAgB,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,iBAAiB,EAClE,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,SAAS,EAC7C,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAWxD,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AAsBvB,0BAA0B;AAE1B,SAAS,QAAQ,CAAI,KAA2B;IAC5C,IAAI,KAAK,IAAI,IAAI,EAAE;QA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AI,UAAU,IAAI,CAAC,EAAE,oBAAoB,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC;QAChH,MAAM,EAAE,GAAG,IAAI,mBAAmB,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;QACxD,EAAE,CAAC,WAAW,GAAG,UAAU,CAAC;QAC5B,OAAO,EAAE,CAAC;IACd,CAAC;CACJ;AAsCD,SAAS,yBAAyB,CAAC,KAAuC;IACtE,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC;AAC5E,CAAC;AAED,SAAS,gCAAgC,CAAC,EAA4D,EAAE,KAAgE;IACpK,OAAO,EAAE,MAAM,EAAE,qBAAqB,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;AACxD,CAAC;AAED,SAAS,8BAA8B,CAAC,EAA4D;IAChG,OAAO,EAAE,MAAM,EAAE,kBAAkB,EAAE,EAAE,EAAE,CAAC;AAC9C,CAAC;AAED,SAAS,sBAAsB,CAAC,GAAqJ;IACjL,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,EAAE;YAC9B,eAAe,EAAE,GAAG,CAAC,eAAe;YACpC,SAAS,EAAE,GAAG,CAAC,SAAS;YACxB,WAAW,EAAE,GAAG,CAAC,WAAW;YAC5B,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,IAAI,EAAE,GAAG,CAAC,IAAI;YACd,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;YACzC,KAAK,EAAE,GAAG,CAAC,KAAK;SACnB,EAAE,CAAC;AACR,CAAC"} \ No newline at end of file diff --git a/lib.esm/transaction/transaction.d.ts b/lib.esm/transaction/transaction.d.ts new file mode 100644 index 00000000..00742ee8 --- /dev/null +++ b/lib.esm/transaction/transaction.d.ts @@ -0,0 +1,276 @@ +import { Signature } from "../crypto/index.js"; +import type { BigNumberish, BytesLike } from "../utils/index.js"; +import type { SignatureLike } from "../crypto/index.js"; +import type { AccessList, AccessListish } from "./index.js"; +export interface TransactionLike { + /** + * The type. + */ + type?: null | number; + /** + * The recipient address or ``null`` for an ``init`` transaction. + */ + to?: null | A; + /** + * The sender. + */ + from: A; + /** + * The nonce. + */ + nonce?: null | number; + /** + * The maximum amount of gas that can be used. + */ + gasLimit?: null | BigNumberish; + /** + * The gas price for legacy and berlin transactions. + */ + gasPrice?: null | BigNumberish; + /** + * The maximum priority fee per gas for london transactions. + */ + maxPriorityFeePerGas?: null | BigNumberish; + /** + * The maximum total fee per gas for london transactions. + */ + maxFeePerGas?: null | BigNumberish; + /** + * The data. + */ + data?: null | string; + /** + * The value (in wei) to send. + */ + value?: null | BigNumberish; + /** + * The chain ID the transaction is valid on. + */ + chainId?: null | BigNumberish; + /** + * The transaction hash. + */ + hash?: null | string; + /** + * The signature provided by the sender. + */ + signature?: null | SignatureLike; + /** + * The access list for berlin and london transactions. + */ + accessList?: null | AccessListish; + /** + * The external gas price. + */ + externalGasPrice?: null | BigNumberish; + /** + * The external gas tip. + */ + externalGasTip?: null | BigNumberish; + /** + * The external gas limit. + */ + externalGasLimit?: null | BigNumberish; + /** + * The external data. + */ + externalData?: null | string; + /** + * The access list for berlin and london transactions. + */ + externalAccessList?: null | AccessListish; +} +/** + * A **Transaction** describes an operation to be executed on + * Ethereum by an Externally Owned Account (EOA). It includes + * who (the [[to]] address), what (the [[data]]) and how much (the + * [[value]] in ether) the operation should entail. + * + * @example: + * tx = new Transaction() + * //_result: + * + * tx.data = "0x1234"; + * //_result: + */ +export declare class Transaction implements TransactionLike { + #private; + from: string; + /** + * The transaction type. + * + * If null, the type will be automatically inferred based on + * explicit properties. + */ + get type(): null | number; + set type(value: null | number | string); + /** + * The name of the transaction type. + */ + get typeName(): null | string; + /** + * The ``to`` address for the transaction or ``null`` if the + * transaction is an ``init`` transaction. + */ + get to(): null | string; + set to(value: null | string); + /** + * The transaction nonce. + */ + get nonce(): number; + set nonce(value: BigNumberish); + /** + * The gas limit. + */ + get gasLimit(): bigint; + set gasLimit(value: BigNumberish); + /** + * The gas price. + * + * On legacy networks this defines the fee that will be paid. On + * EIP-1559 networks, this should be ``null``. + */ + get gasPrice(): null | bigint; + set gasPrice(value: null | BigNumberish); + /** + * The maximum priority fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get maxPriorityFeePerGas(): null | bigint; + set maxPriorityFeePerGas(value: null | BigNumberish); + /** + * The maximum total fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get maxFeePerGas(): null | bigint; + set maxFeePerGas(value: null | BigNumberish); + /** + * The transaction data. For ``init`` transactions this is the + * deployment code. + */ + get data(): string; + set data(value: BytesLike); + /** + * The amount of ether to send in this transactions. + */ + get value(): bigint; + set value(value: BigNumberish); + /** + * The chain ID this transaction is valid on. + */ + get chainId(): bigint; + set chainId(value: BigNumberish); + /** + * If signed, the signature for this transaction. + */ + get signature(): null | Signature; + set signature(value: null | SignatureLike); + /** + * The access list. + * + * An access list permits discounted (but pre-paid) access to + * bytecode and state variable access within contract execution. + */ + get accessList(): null | AccessList; + set accessList(value: null | AccessListish); + /** + * The gas limit. + */ + get externalGasLimit(): bigint; + set externalGasLimit(value: BigNumberish); + /** + * The maximum priority fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get externalGasTip(): null | bigint; + set externalGasTip(value: null | BigNumberish); + /** + * The maximum total fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get externalGasPrice(): null | bigint; + set externalGasPrice(value: null | BigNumberish); + /** + * The transaction externalData. For ``init`` transactions this is the + * deployment code. + */ + get externalData(): string; + set externalData(value: BytesLike); + /** + * The external access list. + * + * An access list permits discounted (but pre-paid) access to + * bytecode and state variable access within contract execution. + */ + get externalAccessList(): null | AccessList; + set externalAccessList(value: null | AccessListish); + /** + * Creates a new Transaction with default values. + */ + constructor(from: string); + /** + * The transaction hash, if signed. Otherwise, ``null``. + */ + get hash(): null | string; + /** + * The pre-image hash of this transaction. + * + * This is the digest that a [[Signer]] must sign to authorize + * this transaction. + */ + get unsignedHash(): string; + /** + * The public key of the sender, if signed. Otherwise, ``null``. + */ + get fromPublicKey(): null | string; + /** + * Returns true if signed. + * + * This provides a Type Guard that properties requiring a signed + * transaction are non-null. + */ + isSigned(): this is (Transaction & { + type: number; + typeName: string; + from: string; + signature: Signature; + }); + /** + * The serialized transaction. + * + * This throws if the transaction is unsigned. For the pre-image, + * use [[unsignedSerialized]]. + */ + get serialized(): string; + /** + * The transaction pre-image. + * + * The hash of this is the digest which needs to be signed to + * authorize this transaction. + */ + get unsignedSerialized(): string; + /** + * Return the most "likely" type; currently the highest + * supported transaction type. + */ + inferType(): number; + /** + * Validates the explicit properties and returns a list of compatible + * transaction types. + */ + inferTypes(): Array; + /** + * Create a copy of this transaciton. + */ + clone(): Transaction; + /** + * Return a JSON-friendly object. + */ + toJSON(): any; + /** + * Create a **Transaction** from a serialized transaction or a + * Transaction-like object. + */ + static from(tx: string | TransactionLike): Transaction; +} +//# sourceMappingURL=transaction.d.ts.map \ No newline at end of file diff --git a/lib.esm/transaction/transaction.d.ts.map b/lib.esm/transaction/transaction.d.ts.map new file mode 100644 index 00000000..fdd69770 --- /dev/null +++ b/lib.esm/transaction/transaction.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transaction.d.ts","sourceRoot":"","sources":["../../src.ts/transaction/transaction.ts"],"names":[],"mappings":"AAEA,OAAO,EAAa,SAAS,EAAc,MAAM,oBAAoB,CAAC;AAQtE,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAG5D,MAAM,WAAW,eAAe,CAAC,CAAC,GAAG,MAAM;IACvC;;OAEG;IACH,IAAI,CAAC,E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AI,UAAU,IAAI,MAAM,CAIvB;IAED;;;;;OAKG;IACH,IAAI,kBAAkB,IAAI,MAAM,CAE/B;IAED;;;OAGG;IACH,SAAS,IAAI,MAAM;IAInB;;;OAGG;IACH,UAAU,IAAI,KAAK,CAAC,MAAM,CAAC;IAyC3B;;OAEG;IACH,KAAK,IAAI,WAAW;IAIpB;;OAEG;IACH,MAAM,IAAI,GAAG;IA4Bb;;;OAGG;IACH,MAAM,CAAC,IAAI,CAAC,EAAE,EAAE,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC,GAAG,WAAW;CAsCjE"} \ No newline at end of file diff --git a/lib.esm/transaction/transaction.js b/lib.esm/transaction/transaction.js new file mode 100644 index 00000000..cb2b6dde --- /dev/null +++ b/lib.esm/transaction/transaction.js @@ -0,0 +1,545 @@ +import { getAddress } from "../address/index.js"; +import { keccak256, Signature, SigningKey } from "../crypto/index.js"; +import { getBytes, getBigInt, getNumber, hexlify, assert, assertArgument, toBeArray, zeroPadValue, encodeProto, decodeProto, toBigInt } from "../utils/index.js"; +import { accessListify } from "./accesslist.js"; +function handleNumber(_value, param) { + if (_value === "0x") { + return 0; + } + return getNumber(_value, param); +} +function formatNumber(_value, name) { + const value = getBigInt(_value, "value"); + const result = toBeArray(value); + assertArgument(result.length <= 32, `value too large`, `tx.${name}`, value); + return result; +} +function _parseSignature(tx, fields, serialize) { + let yParity; + try { + yParity = handleNumber(fields[0], "yParity"); + if (yParity !== 0 && yParity !== 1) { + throw new Error("bad yParity"); + } + } + catch (error) { + assertArgument(false, "invalid yParity", "yParity", fields[0]); + } + const r = zeroPadValue(fields[1], 32); + const s = zeroPadValue(fields[2], 32); + const signature = Signature.from({ r, s, yParity }); + tx.signature = signature; +} +function _parse(data) { + const decodedTx = decodeProto(getBytes(data)); + const tx = { + type: decodedTx.type, + from: decodedTx.from, + chainId: toBigInt(decodedTx.chain_id), + nonce: decodedTx.nonce, + maxPriorityFeePerGas: toBigInt(decodedTx.gas_tip_cap), + maxFeePerGas: toBigInt(decodedTx.gas_fee_cap), + gasLimit: toBigInt(decodedTx.gas), + to: hexlify(decodedTx.to), + value: toBigInt(decodedTx.value), + data: hexlify(decodedTx.data), + accessList: decodedTx.access_list.access_tuples, + }; + if (decodedTx.type == 2) { + tx.externalGasLimit = toBigInt(decodedTx.etx_gas_limit); + tx.externalGasPrice = toBigInt(decodedTx.etx_gas_price); + tx.externalGasTip = toBigInt(decodedTx.etx_gas_tip); + tx.externalData = hexlify(decodedTx.etx_data); + tx.externalAccessList = decodedTx.etx_access_list.access_tuples; + } + tx.hash = keccak256(data); + const signatureFields = [ + hexlify(decodedTx.v), + hexlify(decodedTx.r), + hexlify(decodedTx.s), + ]; + _parseSignature(tx, signatureFields, _serialize); + return tx; +} +function _serialize(tx, sig) { + const formattedTx = { + chain_id: formatNumber(tx.chainId || 0, "chainId"), + nonce: (tx.nonce || 0), + gas_tip_cap: formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"), + gas_fee_cap: formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"), + gas: Number(tx.gasLimit || 0), + to: tx.to != null ? getBytes(tx.to) : "0x", + value: formatNumber(tx.value || 0, "value"), + data: getBytes(tx.data || "0x"), + access_list: { access_tuples: tx.accessList || [] }, + type: (tx.type || 0), + }; + if (tx.type == 2) { + formattedTx.etx_gas_limit = Number(tx.externalGasLimit || 0); + formattedTx.etx_gas_price = formatNumber(tx.externalGasPrice || 0, "externalGasPrice"); + formattedTx.etx_gas_tip = formatNumber(tx.externalGasTip || 0, "externalGasTip"); + formattedTx.etx_data = getBytes(tx.externalData || "0x"); + formattedTx.etx_access_list = { access_tuples: tx.externalAccessList || [] }; + } + if (sig) { + formattedTx.v = formatNumber(sig.yParity, "yParity"), + formattedTx.r = toBeArray(sig.r), + formattedTx.s = toBeArray(sig.s); + } + return encodeProto(formattedTx); +} +/** + * A **Transaction** describes an operation to be executed on + * Ethereum by an Externally Owned Account (EOA). It includes + * who (the [[to]] address), what (the [[data]]) and how much (the + * [[value]] in ether) the operation should entail. + * + * @example: + * tx = new Transaction() + * //_result: + * + * tx.data = "0x1234"; + * //_result: + */ +export class Transaction { + #type; + #to; + #data; + #nonce; + #gasLimit; + #gasPrice; + #maxPriorityFeePerGas; + #maxFeePerGas; + #value; + #chainId; + #sig; + #accessList; + #externalGasLimit; + #externalGasTip; + #externalGasPrice; + #externalAccessList; + #externalData; + from; + /** + * The transaction type. + * + * If null, the type will be automatically inferred based on + * explicit properties. + */ + get type() { return this.#type; } + set type(value) { + switch (value) { + case null: + this.#type = null; + break; + case 0: + case "standard": + this.#type = 0; + break; + // case 1: case "external": + // this.#type = 1; + // break; + case 2: + case "internalToExternal": + this.#type = 2; + break; + default: + assertArgument(false, "unsupported transaction type", "type", value); + } + } + /** + * The name of the transaction type. + */ + get typeName() { + switch (this.type) { + case 0: return "standard"; + case 1: return "external"; + case 2: return "internalToExternal"; + } + return null; + } + /** + * The ``to`` address for the transaction or ``null`` if the + * transaction is an ``init`` transaction. + */ + get to() { return this.#to; } + set to(value) { + this.#to = (value == null) ? null : getAddress(value); + } + /** + * The transaction nonce. + */ + get nonce() { return this.#nonce; } + set nonce(value) { this.#nonce = getNumber(value, "value"); } + /** + * The gas limit. + */ + get gasLimit() { return this.#gasLimit; } + set gasLimit(value) { this.#gasLimit = getBigInt(value); } + /** + * The gas price. + * + * On legacy networks this defines the fee that will be paid. On + * EIP-1559 networks, this should be ``null``. + */ + get gasPrice() { + const value = this.#gasPrice; + return value; + } + set gasPrice(value) { + this.#gasPrice = (value == null) ? null : getBigInt(value, "gasPrice"); + } + /** + * The maximum priority fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get maxPriorityFeePerGas() { + const value = this.#maxPriorityFeePerGas; + if (value == null) { + return null; + } + return value; + } + set maxPriorityFeePerGas(value) { + this.#maxPriorityFeePerGas = (value == null) ? null : getBigInt(value, "maxPriorityFeePerGas"); + } + /** + * The maximum total fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get maxFeePerGas() { + const value = this.#maxFeePerGas; + if (value == null) { + return null; + } + return value; + } + set maxFeePerGas(value) { + this.#maxFeePerGas = (value == null) ? null : getBigInt(value, "maxFeePerGas"); + } + /** + * The transaction data. For ``init`` transactions this is the + * deployment code. + */ + get data() { return this.#data; } + set data(value) { this.#data = hexlify(value); } + /** + * The amount of ether to send in this transactions. + */ + get value() { return this.#value; } + set value(value) { + this.#value = getBigInt(value, "value"); + } + /** + * The chain ID this transaction is valid on. + */ + get chainId() { return this.#chainId; } + set chainId(value) { this.#chainId = getBigInt(value); } + /** + * If signed, the signature for this transaction. + */ + get signature() { return this.#sig || null; } + set signature(value) { + this.#sig = (value == null) ? null : Signature.from(value); + } + /** + * The access list. + * + * An access list permits discounted (but pre-paid) access to + * bytecode and state variable access within contract execution. + */ + get accessList() { + const value = this.#accessList || null; + if (value == null) { + return null; + } + return value; + } + set accessList(value) { + this.#accessList = (value == null) ? null : accessListify(value); + } + /** + * The gas limit. + */ + get externalGasLimit() { return this.#externalGasLimit; } + set externalGasLimit(value) { this.#externalGasLimit = getBigInt(value); } + /** + * The maximum priority fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get externalGasTip() { + const value = this.#externalGasTip; + if (value == null) { + return null; + } + return value; + } + set externalGasTip(value) { + this.#externalGasTip = (value == null) ? null : getBigInt(value, "externalGasTip"); + } + /** + * The maximum total fee per unit of gas to pay. On legacy + * networks this should be ``null``. + */ + get externalGasPrice() { + const value = this.#externalGasPrice; + if (value == null) { + return null; + } + return value; + } + set externalGasPrice(value) { + this.#externalGasPrice = (value == null) ? null : getBigInt(value, "externalGasPrice"); + } + /** + * The transaction externalData. For ``init`` transactions this is the + * deployment code. + */ + get externalData() { return this.#externalData; } + set externalData(value) { this.#externalData = hexlify(value); } + /** + * The external access list. + * + * An access list permits discounted (but pre-paid) access to + * bytecode and state variable access within contract execution. + */ + get externalAccessList() { + const value = this.#externalAccessList || null; + if (value == null) { + return null; + } + return value; + } + set externalAccessList(value) { + this.#externalAccessList = (value == null) ? null : accessListify(value); + } + /** + * Creates a new Transaction with default values. + */ + constructor(from) { + this.#type = null; + this.#to = null; + this.#nonce = 0; + this.#gasLimit = BigInt(0); + this.#gasPrice = null; + this.#maxPriorityFeePerGas = null; + this.#maxFeePerGas = null; + this.#data = "0x"; + this.#value = BigInt(0); + this.#chainId = BigInt(0); + this.#sig = null; + this.#accessList = null; + this.#externalGasLimit = BigInt(0); + this.#externalGasTip = null; + this.#externalGasPrice = null; + this.#externalData = "0x"; + this.#externalAccessList = null; + this.from = from; + } + /** + * The transaction hash, if signed. Otherwise, ``null``. + */ + get hash() { + if (this.signature == null) { + return null; + } + return keccak256(this.serialized); + } + /** + * The pre-image hash of this transaction. + * + * This is the digest that a [[Signer]] must sign to authorize + * this transaction. + */ + get unsignedHash() { + return keccak256(this.unsignedSerialized); + } + /** + * The public key of the sender, if signed. Otherwise, ``null``. + */ + get fromPublicKey() { + if (this.signature == null) { + return null; + } + return SigningKey.recoverPublicKey(this.unsignedHash, this.signature); + } + /** + * Returns true if signed. + * + * This provides a Type Guard that properties requiring a signed + * transaction are non-null. + */ + isSigned() { + //isSigned(): this is SignedTransaction { + return this.signature != null; + } + /** + * The serialized transaction. + * + * This throws if the transaction is unsigned. For the pre-image, + * use [[unsignedSerialized]]. + */ + get serialized() { + assert(this.signature != null, "cannot serialize unsigned transaction; maybe you meant .unsignedSerialized", "UNSUPPORTED_OPERATION", { operation: ".serialized" }); + return _serialize(this, this.signature); + } + /** + * The transaction pre-image. + * + * The hash of this is the digest which needs to be signed to + * authorize this transaction. + */ + get unsignedSerialized() { + return _serialize(this); + } + /** + * Return the most "likely" type; currently the highest + * supported transaction type. + */ + inferType() { + return (this.inferTypes().pop()); + } + /** + * Validates the explicit properties and returns a list of compatible + * transaction types. + */ + inferTypes() { + // Checks that there are no conflicting properties set + // const hasGasPrice = this.gasPrice != null; + // const hasFee = (this.maxFeePerGas != null || this.maxPriorityFeePerGas != null); + const hasExternal = (this.externalGasLimit != null || this.externalGasTip != null || this.externalGasPrice != null || this.externalData != null || this.externalAccessList != null); + // const hasAccessList = (this.accessList != null); + //if (hasGasPrice && hasFee) { + // throw new Error("transaction cannot have gasPrice and maxFeePerGas"); + //} + if (this.maxFeePerGas != null && this.maxPriorityFeePerGas != null) { + assert(this.maxFeePerGas >= this.maxPriorityFeePerGas, "priorityFee cannot be more than maxFee", "BAD_DATA", { value: this }); + } + //if (this.type === 2 && hasGasPrice) { + // throw new Error("eip-1559 transaction cannot have gasPrice"); + //} + assert(hasExternal || (this.type !== 0 && this.type !== 1), "transaction type cannot have externalGasLimit, externalGasTip, externalGasPrice, externalData, or externalAccessList", "BAD_DATA", { value: this }); + const types = []; + // Explicit type + if (this.type != null) { + types.push(this.type); + } + else { + if (hasExternal) { + types.push(2); + } + else { + types.push(0); + } + } + types.sort(); + return types; + } + /** + * Create a copy of this transaciton. + */ + clone() { + return Transaction.from(this); + } + /** + * Return a JSON-friendly object. + */ + toJSON() { + const s = (v) => { + if (v == null) { + return null; + } + return v.toString(); + }; + return { + type: this.type, + to: this.to, + // from: this.from, + data: this.data, + nonce: this.nonce, + gasLimit: s(this.gasLimit), + gasPrice: s(this.gasPrice), + maxPriorityFeePerGas: s(this.maxPriorityFeePerGas), + maxFeePerGas: s(this.maxFeePerGas), + value: s(this.value), + chainId: s(this.chainId), + sig: this.signature ? this.signature.toJSON() : null, + accessList: this.accessList, + externalGasLimit: s(this.externalGasLimit), + externalGasTip: s(this.externalGasTip), + externalGasPrice: s(this.externalGasPrice), + externalData: this.externalData, + externalAccessList: this.externalAccessList, + }; + } + /** + * Create a **Transaction** from a serialized transaction or a + * Transaction-like object. + */ + static from(tx) { + // if (tx == null) { return new Transaction(); } + if (typeof (tx) === "string") { + const payload = getBytes(tx); + return Transaction.from(_parse(payload)); + } + const result = new Transaction(tx.from); + if (tx.type != null) { + result.type = tx.type; + } + if (tx.to != null) { + result.to = tx.to; + } + if (tx.nonce != null) { + result.nonce = tx.nonce; + } + if (tx.gasLimit != null) { + result.gasLimit = tx.gasLimit; + } + if (tx.maxPriorityFeePerGas != null) { + result.maxPriorityFeePerGas = tx.maxPriorityFeePerGas; + } + if (tx.maxFeePerGas != null) { + result.maxFeePerGas = tx.maxFeePerGas; + } + if (tx.data != null) { + result.data = tx.data; + } + if (tx.value != null) { + result.value = tx.value; + } + if (tx.chainId != null) { + result.chainId = tx.chainId; + } + if (tx.signature != null) { + result.signature = Signature.from(tx.signature); + } + if (tx.accessList != null) { + result.accessList = tx.accessList; + } + if (tx.externalGasLimit != null) { + result.externalGasLimit = tx.externalGasLimit; + } + if (tx.externalGasPrice != null) { + result.externalGasPrice = tx.externalGasPrice; + } + if (tx.externalGasTip != null) { + result.externalGasTip = tx.externalGasTip; + } + if (tx.externalData != null) { + result.externalData = tx.externalData; + } + if (tx.externalAccessList != null) { + result.externalAccessList = tx.externalAccessList; + } + if (tx.hash != null) { + assertArgument(result.isSigned(), "unsigned transaction cannot define hash", "tx", tx); + assertArgument(result.hash === tx.hash, "hash mismatch", "tx", tx); + } + if (tx.from != null) { + // assertArgument(result.isSigned(), "unsigned transaction cannot define from", "tx", tx); + assertArgument(result.from.toLowerCase() === (tx.from || "").toLowerCase(), "from mismatch", "tx", tx); + } + return result; + } +} +//# sourceMappingURL=transaction.js.map \ No newline at end of file diff --git a/lib.esm/transaction/transaction.js.map b/lib.esm/transaction/transaction.js.map new file mode 100644 index 00000000..537e3768 --- /dev/null +++ b/lib.esm/transaction/transaction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transaction.js","sourceRoot":"","sources":["../../src.ts/transaction/transaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,UAAU,EAAC,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACtE,OAAO,EACH,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EACvC,MAAM,EAAE,cAAc,EAAE,SAAS,E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AE,MAAM,CAAC,gBAAgB,GAAG,EAAE,CAAC,gBAAgB,CAAC;SAAE;QACnF,IAAI,EAAE,CAAC,gBAAgB,IAAI,IAAI,EAAE;YAAE,MAAM,CAAC,gBAAgB,GAAG,EAAE,CAAC,gBAAgB,CAAC;SAAE;QACnF,IAAI,EAAE,CAAC,cAAc,IAAI,IAAI,EAAE;YAAE,MAAM,CAAC,cAAc,GAAG,EAAE,CAAC,cAAc,CAAC;SAAE;QAC7E,IAAI,EAAE,CAAC,YAAY,IAAI,IAAI,EAAE;YAAE,MAAM,CAAC,YAAY,GAAG,EAAE,CAAC,YAAY,CAAC;SAAE;QACvE,IAAI,EAAE,CAAC,kBAAkB,IAAI,IAAI,EAAE;YAAE,MAAM,CAAC,kBAAkB,GAAG,EAAE,CAAC,kBAAkB,CAAC;SAAE;QAGzF,IAAI,EAAE,CAAC,IAAI,IAAI,IAAI,EAAE;YACjB,cAAc,CAAC,MAAM,CAAC,QAAQ,EAAE,EAAE,yCAAyC,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;YACvF,cAAc,CAAC,MAAM,CAAC,IAAI,KAAK,EAAE,CAAC,IAAI,EAAE,eAAe,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;SACtE;QAED,IAAI,EAAE,CAAC,IAAI,IAAI,IAAI,EAAE;YAC7B,sGAAsG;YAC1F,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,CAAC,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,EAAE,eAAe,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;SAC1G;QAED,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ"} \ No newline at end of file diff --git a/lib.esm/wallet/base-wallet.js b/lib.esm/wallet/base-wallet.js new file mode 100644 index 00000000..1f42615f --- /dev/null +++ b/lib.esm/wallet/base-wallet.js @@ -0,0 +1,104 @@ +import { getAddress, resolveAddress } from "../address/index.js"; +import { hashMessage, TypedDataEncoder } from "../hash/index.js"; +import { AbstractSigner } from "../providers/index.js"; +import { computeAddress, Transaction } from "../transaction/index.js"; +import { resolveProperties, assert, assertArgument } from "../utils/index.js"; +/** + * The **BaseWallet** is a stream-lined implementation of a + * [[Signer]] that operates with a private key. + * + * It is preferred to use the [[Wallet]] class, as it offers + * additional functionality and simplifies loading a variety + * of JSON formats, Mnemonic Phrases, etc. + * + * This class may be of use for those attempting to implement + * a minimal Signer. + */ +export class BaseWallet extends AbstractSigner { + /** + * The wallet address. + */ + #address; + #signingKey; + /** + * Creates a new BaseWallet for %%privateKey%%, optionally + * connected to %%provider%%. + * + * If %%provider%% is not specified, only offline methods can + * be used. + */ + constructor(privateKey, provider) { + super(provider); + assertArgument(privateKey && typeof (privateKey.sign) === "function", "invalid private key", "privateKey", "[ REDACTED ]"); + this.#signingKey = privateKey; + this.#address = computeAddress(this.signingKey.publicKey); + } + // Store private values behind getters to reduce visibility + // in console.log + /** + * The address of this wallet. + */ + get address() { return this.#address; } + /** + * The [[SigningKey]] used for signing payloads. + */ + get signingKey() { return this.#signingKey; } + /** + * The private key for this wallet. + */ + get privateKey() { return this.signingKey.privateKey; } + async getAddress() { return this.#address; } + connect(provider) { + return new BaseWallet(this.#signingKey, provider); + } + async signTransaction(tx) { + // Replace any Addressable or ENS name with an address + const { to, from } = await resolveProperties({ + to: (tx.to ? resolveAddress(tx.to, this.provider) : undefined), + from: (tx.from ? resolveAddress(tx.from, this.provider) : undefined) + }); + if (to != null) { + tx.to = to; + } + if (from != null) { + tx.from = from; + } + if (tx.from != null) { + assertArgument(getAddress((tx.from)) === this.#address, "transaction from address mismatch", "tx.from", tx.from); + // delete tx.from; + } + // Build the transaction + const btx = Transaction.from(tx); + btx.signature = this.signingKey.sign(btx.unsignedHash); + return btx.serialized; + } + async signMessage(message) { + return this.signMessageSync(message); + } + // @TODO: Add a secialized signTx and signTyped sync that enforces + // all parameters are known? + /** + * Returns the signature for %%message%% signed with this wallet. + */ + signMessageSync(message) { + return this.signingKey.sign(hashMessage(message)).serialized; + } + async signTypedData(domain, types, value) { + // Populate any ENS names + const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (name) => { + // @TODO: this should use resolveName; addresses don't + // need a provider + assert(this.provider != null, "cannot resolve ENS names without a provider", "UNSUPPORTED_OPERATION", { + operation: "resolveName", + info: { name } + }); + const address = await this.provider.resolveName(name); + assert(address != null, "unconfigured ENS name", "UNCONFIGURED_NAME", { + value: name + }); + return address; + }); + return this.signingKey.sign(TypedDataEncoder.hash(populated.domain, types, populated.value)).serialized; + } +} +//# sourceMappingURL=base-wallet.js.map \ No newline at end of file diff --git a/lib.esm/wallet/base-wallet.js.map b/lib.esm/wallet/base-wallet.js.map new file mode 100644 index 00000000..01ecdb0f --- /dev/null +++ b/lib.esm/wallet/base-wallet.js.map @@ -0,0 +1 @@ +{"version":3,"file":"base-wallet.js","sourceRoot":"","sources":["../../src.ts/wallet/base-wallet.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtE,OAAO,EACF,iBAAiB,EAAE,MAAM,EAAE,cAAc,EAC7C,MAAM,mBAAmB,CAAC;AAQ3B;;;;;;;;;;GAUG;AACH,MAAM,OAAO,UAAW,SAAQ,cAAc;IAC1C;;OAEG;IACM,QAAQ,CAAU;IAElB,WAAW,CAAa;IAEjC;;;;;;OAMG;IACH,YAAY,UAAsB,EAAE,QAA0B;QAC1D,KAAK,CAAC,QAAQ,CAAC,CAAC;QAEhB,cAAc,CAAC,UAAU,IAAI,OAAM,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,UAAU,EAAE,qBAAqB,EAAE,YAAY,EAAE,cAA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CAAC,OAAO,IAAI,IAAI,EAAE,uBAAuB,EAAE,mBAAmB,EAAE;gBAClE,KAAK,EAAE,IAAI;aACd,CAAC,CAAC;YAEH,OAAO,OAAO,CAAC;QACnB,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,UAAU,CAAC;IAC5G,CAAC;CACJ"} \ No newline at end of file diff --git a/src.ts/_tests/test-provider-jsonrpc.ts b/src.ts/_tests/test-provider-jsonrpc.ts index 6d88a3ef..d53f3152 100644 --- a/src.ts/_tests/test-provider-jsonrpc.ts +++ b/src.ts/_tests/test-provider-jsonrpc.ts @@ -89,6 +89,7 @@ describe("Ensure Catchable Errors", function() { maxFeePerGas: 2000000000, maxPriorityFeePerGas: 1000000000, to: wallet.address, + from: wallet.address, value: 1, }; const txSign = await wallet.signTransaction(txInfo); @@ -150,6 +151,7 @@ describe("Ensure Catchable Errors", function() { maxFeePerGas: 2000000000, maxPriorityFeePerGas: 1000000000, to: wallet.address, + from: wallet.address, value: 1, }; const txSign = await wallet.signTransaction(txInfo); diff --git a/src.ts/_tests/test-providers-data.ts b/src.ts/_tests/test-providers-data.ts index 5621dd40..248c46e1 100644 --- a/src.ts/_tests/test-providers-data.ts +++ b/src.ts/_tests/test-providers-data.ts @@ -237,7 +237,7 @@ describe("Test Provider Block operations", function() { }) it('should fetch block by number', async function () { - let responseBlock = await providerC1.getBlock('0xA') as quais.Block; + let responseBlock = await providerC1.getBlock('0,0', '0xA') as quais.Block; assert.ok(responseBlock != null, "block != null"); let { provider, ...formatBlock } = { @@ -250,7 +250,7 @@ describe("Test Provider Block operations", function() { it('should fetch block by hash', async function() { assert.ok(block.hash != null, 'block.hash != null') - let responseBlock = await providerC1.getBlock(block.hash) as quais.Block; + let responseBlock = await providerC1.getBlock('0,0', block.hash) as quais.Block; assert.ok(responseBlock != null, "block != null"); let { provider, ...formatBlock } = { diff --git a/src.ts/_tests/test-providers-errors.ts b/src.ts/_tests/test-providers-errors.ts index f146174c..f20930a0 100644 --- a/src.ts/_tests/test-providers-errors.ts +++ b/src.ts/_tests/test-providers-errors.ts @@ -46,6 +46,7 @@ describe("Tests Provider Call Exception", function() { ]; const testAddr = "0x0aff86a125b29b25a9e418c2fb64f1753532c0ca"; //Cyprus1 + const testAddr2 = "0x0aff86a125b29b25a9e418c2fb64f1753532c0ca"; //Cyprus1 const networkName = "colosseum"; for (const { code, reason } of panics) { @@ -64,7 +65,7 @@ describe("Tests Provider Call Exception", function() { await stall(1000); - const tx = { to: testAddr, data }; + const tx = { to: testAddr, from: testAddr2, data }; try { const result = await (method === "call" ? provider.call(tx): provider.estimateGas(tx)); console.log(result); @@ -123,7 +124,7 @@ describe("Tests Provider Call Exception", function() { for (const { data, message, name, reason, revert } of customErrors) { for (const method of [ "call", "estimateGas" ]) { - const tx = { to: testAddr, data }; + const tx = { to: testAddr, from: testAddr2, data }; for (const providerName of providerNames) { const provider = getProvider(providerName, networkName); if (provider == null) { continue; } @@ -168,6 +169,7 @@ describe("Tests Provider Call Exception", function() { describe("Test Provider Blockchain Errors", function() { const wallet = new Wallet((process.env.FAUCET_PRIVATEKEY)); + const wallet2 = new Wallet((process.env.FAUCET_PRIVATEKEY)); const networkName = "colosseum"; for (const providerName of providerNames) { @@ -191,7 +193,7 @@ describe("Test Provider Blockchain Errors", function() { nonce = await w.getNonce("pending"); try { tx1 = await w.sendTransaction({ - nonce, to: wallet, value + nonce, to: wallet, from: wallet2, value }); } catch (error: any) { // Another CI host beat us to this nonce @@ -209,7 +211,7 @@ describe("Test Provider Blockchain Errors", function() { const rejection = assert.rejects(async function() { // Send another tx with the same nonce const tx2 = await w.sendTransaction({ - nonce, to: wallet, value: 1 + nonce, to: wallet, from: wallet2, value: 1 }); console.log({ tx1, tx2 }); }, (error: unknown) => { @@ -237,7 +239,7 @@ describe("Test Provider Blockchain Errors", function() { await assert.rejects(async function() { const tx = await w.sendTransaction({ - to: wallet, value: 1 + to: wallet, from: wallet2, value: 1 }); console.log(tx); }, (error) => { @@ -260,7 +262,7 @@ describe("Test Provider Blockchain Errors", function() { await assert.rejects(async function() { const tx = await w.sendTransaction({ - to: wallet, nonce: 1, value: 1 + to: wallet, from: wallet2, value: 1 }); console.log(tx); }, (error) => { diff --git a/src.ts/_tests/test-providers-fallback.ts b/src.ts/_tests/test-providers-fallback.ts index ac3e38cb..1ed69345 100644 --- a/src.ts/_tests/test-providers-fallback.ts +++ b/src.ts/_tests/test-providers-fallback.ts @@ -57,7 +57,7 @@ describe("Test Fallback broadcast", function() { });; const provider = new FallbackProvider(providers); - return await provider.broadcastTransaction(tx); + return await provider.broadcastTransaction('0,1', tx); } it("picks late non-failed broadcasts", async function() { diff --git a/src.ts/_tests/types.ts b/src.ts/_tests/types.ts index 04b3ada0..edac06cc 100644 --- a/src.ts/_tests/types.ts +++ b/src.ts/_tests/types.ts @@ -183,6 +183,7 @@ export interface TestCaseRlp { export interface TestCaseTransactionTx { to?: string; + from: string; nonce?: number; gasLimit?: string; diff --git a/src.ts/constants/shards.ts b/src.ts/constants/shards.ts index 2a3eafaa..609dcc0d 100644 --- a/src.ts/constants/shards.ts +++ b/src.ts/constants/shards.ts @@ -61,5 +61,12 @@ export const ShardData = [ shard: "zone-2-2", context: 2, byte: "0x22" // 0010 0010 region-2 zone-2 + }, + { + name: "Prime", + nickname: 'prime', + shard: "prime", + context: 2, + byte: "0x" } ]; \ No newline at end of file diff --git a/src.ts/contract/contract.ts b/src.ts/contract/contract.ts index 46830a35..e19b6b11 100644 --- a/src.ts/contract/contract.ts +++ b/src.ts/contract/contract.ts @@ -278,13 +278,20 @@ function buildWrappedMethod = Array, R = any, D extend const fragment = getFragment(...args); // If an overrides was passed in, copy it and normalize the values - let overrides: Omit = { }; + let overrides: Omit; if (fragment.inputs.length + 1 === args.length) { overrides = await copyOverrides(args.pop()); - if (overrides.from) { - overrides.from = await resolveAddress(overrides.from, getResolver(contract.runner)); - } + const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args); + + return Object.assign({ }, overrides, await resolveProperties({ + to: contract.getAddress(), + data: contract.interface.encodeFunctionData(fragment, resolvedArgs) + })); + + // if (overrides.from) { + // overrides.from = await resolveAddress(overrides.from, getResolver(contract.runner)); + // } } if (fragment.inputs.length !== args.length) { @@ -293,10 +300,11 @@ function buildWrappedMethod = Array, R = any, D extend const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args); - return Object.assign({ }, overrides, await resolveProperties({ + return await resolveProperties({ to: contract.getAddress(), + from: args.pop().from, data: contract.interface.encodeFunctionData(fragment, resolvedArgs) - })); + }); } const staticCall = async function(...args: ContractMethodArgs): Promise { @@ -930,13 +938,13 @@ export class BaseContract implements Addressable, EventEmitterable> { + async queryFilter(shard: string, event: ContractEventName, fromBlock?: BlockTag, toBlock?: BlockTag): Promise> { if (fromBlock == null) { fromBlock = 0; } if (toBlock == null) { toBlock = "latest"; } const { addr, addrPromise } = getInternal(this); const address = (addr ? addr: (await addrPromise)); const { fragment, topics } = await getSubInfo(this, event); - const filter = { address, topics, fromBlock, toBlock }; + const filter = { address, topics, fromBlock, toBlock, shard: shard }; const provider = getProvider(this.runner); assert(provider, "contract runner does not have a provider", diff --git a/src.ts/contract/factory.ts b/src.ts/contract/factory.ts index 1b51e67c..9d3b0994 100644 --- a/src.ts/contract/factory.ts +++ b/src.ts/contract/factory.ts @@ -78,12 +78,16 @@ export class ContractFactory = Array, I = BaseContract * into the constructor. */ async getDeployTransaction(...args: ContractMethodArgs): Promise { - let overrides: Omit = { }; + let overrides: Omit; const fragment = this.interface.deploy; if (fragment.inputs.length + 1 === args.length) { overrides = await copyOverrides(args.pop()); + + const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args); + const data = concat([ this.bytecode, this.interface.encodeDeploy(resolvedArgs) ]); + return Object.assign({ }, overrides, { data }); } if (fragment.inputs.length !== args.length) { @@ -93,7 +97,7 @@ export class ContractFactory = Array, I = BaseContract const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args); const data = concat([ this.bytecode, this.interface.encodeDeploy(resolvedArgs) ]); - return Object.assign({ }, overrides, { data }); + return Object.assign({ }, args.pop().from, { data }); } // getDeployTransaction3(...args: Array): TransactionRequest { diff --git a/src.ts/contract/types.ts b/src.ts/contract/types.ts index 8b8aaeb0..0886ef1f 100644 --- a/src.ts/contract/types.ts +++ b/src.ts/contract/types.ts @@ -62,7 +62,8 @@ export interface ContractTransaction extends PreparedTransactionRequest { /** * The from address, if any. */ - from?: string; + from: string; + } /** diff --git a/src.ts/contract/wrappers.ts b/src.ts/contract/wrappers.ts index 7c0697ce..9bd4081f 100644 --- a/src.ts/contract/wrappers.ts +++ b/src.ts/contract/wrappers.ts @@ -160,8 +160,8 @@ export class ContractUnknownEventPayload extends EventPayload { - return await this.log.getBlock(); + async getBlock(shard: string): Promise { + return await this.log.getBlock(shard); } /** diff --git a/src.ts/providers/abstract-provider.ts b/src.ts/providers/abstract-provider.ts index cad8470e..d8bf5bf5 100644 --- a/src.ts/providers/abstract-provider.ts +++ b/src.ts/providers/abstract-provider.ts @@ -15,18 +15,17 @@ // of Signer/ENS name to address so we can sync respond to listenerCount. import { getAddress, resolveAddress } from "../address/index.js"; -import { ZeroAddress } from "../constants/index.js"; +import { ShardData, ZeroAddress } from "../constants/index.js"; import { Contract } from "../contract/index.js"; import { namehash } from "../hash/index.js"; import { Transaction } from "../transaction/index.js"; import { - concat, dataLength, dataSlice, hexlify, isHexString, - getBigInt, getBytes, getNumber, - isCallException, isError, makeError, assert, assertArgument, + hexlify, isHexString, + getBigInt, getNumber, + isError, makeError, assert, assertArgument, FetchRequest, - toBeArray, toQuantity, + toQuantity, defineProperties, EventPayload, resolveProperties, - toUtf8String } from "../utils/index.js"; import { EnsResolver } from "./ens-resolver.js"; @@ -37,7 +36,7 @@ import { Network } from "./network.js"; import { copyRequest, Block, FeeData, Log, TransactionReceipt, TransactionResponse } from "./provider.js"; import type { Addressable, AddressLike } from "../address/index.js"; -import type { BigNumberish, BytesLike } from "../utils/index.js"; +import type { BigNumberish } from "../utils/index.js"; import type { Listener } from "../utils/index.js"; import type { Networkish } from "./network.js"; @@ -324,10 +323,12 @@ export type PerformActionFilter = { topics?: Array>; fromBlock?: BlockTag; toBlock?: BlockTag; + shard: string; } | { address?: string | Array; topics?: Array>; blockHash?: string; + shard: string; }; /** @@ -342,7 +343,7 @@ export interface PerformActionTransaction extends PreparedTransactionRequest { /** * The sender of the transaction. */ - from?: string; + from: string; } /** @@ -351,65 +352,80 @@ export interface PerformActionTransaction extends PreparedTransactionRequest { */ export type PerformActionRequest = { method: "broadcastTransaction", - signedTransaction: string + signedTransaction: string, + shard: string } | { method: "call", - transaction: PerformActionTransaction, blockTag: BlockTag + transaction: PerformActionTransaction, blockTag: BlockTag, shard?: string } | { - method: "chainId" + method: "chainId", shard?: string } | { method: "estimateGas", - transaction: PerformActionTransaction + transaction: PerformActionTransaction, + shard?: string } | { method: "getBalance", - address: string, blockTag: BlockTag + address: string, blockTag: BlockTag, shard: string } | { method: "getBlock", - blockTag: BlockTag, includeTransactions: boolean + blockTag: BlockTag, includeTransactions: boolean, + shard: string } | { method: "getBlock", - blockHash: string, includeTransactions: boolean + blockHash: string, includeTransactions: boolean, + shard: string } | { - method: "getBlockNumber" + method: "getBlockNumber", + shard?: string } | { method: "getCode", - address: string, blockTag: BlockTag + address: string, blockTag: BlockTag, shard: string } | { method: "getGasPrice", - txType: boolean + txType: boolean, + shard?: string } | { method: "getLogs", - filter: PerformActionFilter + filter: PerformActionFilter, + shard: string } | { - method: "getMaxPriorityFeePerGas" + method: "getMaxPriorityFeePerGas", + shard?: string } | { method: "getStorage", - address: string, position: bigint, blockTag: BlockTag + address: string, position: bigint, blockTag: BlockTag, shard: string } | { method: "getTransaction", - hash: string + hash: string, + shard: string } | { method: "getTransactionCount", - address: string, blockTag: BlockTag + address: string, blockTag: BlockTag, shard: string } | { method: "getTransactionReceipt", - hash: string + hash: string, + shard: string } | { method: "getTransactionResult", - hash: string + hash: string, + shard: string } | { - method: "getRunningLocations" + method: "getRunningLocations", + shard?: string } | { - method: "getProtocolTrieExpansionCount" + method: "getProtocolTrieExpansionCount", + shard: string } | { method: "getQiRateAtBlock", - blockTag: BlockTag - amt: number + blockTag: BlockTag, + amt: number, + shard: string } | { method: "getQuaiRateAtBlock", blockTag: BlockTag, - amt: number + amt: number, + shard: string }; @@ -439,14 +455,14 @@ const defaultOptions = { pollingInterval: 4000 }; -type CcipArgs = { - sender: string; - urls: Array; - calldata: string; - selector: string; - extraData: string; - errorArgs: Array -}; +// type CcipArgs = { +// sender: string; +// urls: Array; +// calldata: string; +// selector: string; +// extraData: string; +// errorArgs: Array +// }; /** * An **AbstractProvider** provides a base class for other sub-classes to @@ -456,6 +472,8 @@ type CcipArgs = { */ export class AbstractProvider implements Provider { + _urlMap: Map; + #connect: FetchRequest[]; #subs: Map; #plugins: Map; @@ -514,15 +532,63 @@ export class AbstractProvider implements Provider { this.#timers = new Map(); this.#disableCcipRead = false; + this.#connect = []; + this._urlMap = new Map(); + } + + async initUrlMap(urls: string[] | FetchRequest): Promise { + if (urls instanceof FetchRequest) { + const primeUrl = urls.url.split(":")[0] + ":" + urls.url.split(":")[1] + ":9001"; + this._urlMap.set('0x', primeUrl); + urls.url = primeUrl; + this.#connect.push(urls); + const shards = await this.getRunningLocations(); + shards.forEach((shard) => { + const port = 9100 + 20 * shard[0] + shard[1]; + this._urlMap.set(`0x${shard[0].toString(16)}${shard[1].toString(16)}`, urls.url.split(":")[0] + ":" + urls.url.split(":")[1] + ":" + port); + }); + return; + } + for (const url of urls) { + const primeUrl = url.split(":")[0] + ":" + url.split(":")[1] + ":9001"; + this._urlMap.set('0x', primeUrl); + this.#connect.push(new FetchRequest(primeUrl)); + const shards = await this.getRunningLocations(); // Now waits for the previous to complete + shards.forEach((shard) => { + const port = 9100 + 20 * shard[0] + shard[1]; + this._urlMap.set(`0x${shard[0].toString(16)}${shard[1].toString(16)}`, url.split(":")[0] + ":" + url.split(":")[1] + ":" + port); + }); + } + + } + + shardBytes(shard: string): string { + return ShardData.find(it => + it.name == shard || + it.byte == shard || + it.nickname == shard || + it.shard == shard + )?.byte || ''; + } + + get connect(): FetchRequest[] { return this.#connect; } + + async shardFromAddress(_address: AddressLike): Promise { + let address: string | Promise = this._getAddress(_address); + return (await address).slice(0, 4) } - async getLatestQuaiRate(amt: number = 1): Promise { - const blockNumber = await this.getBlockNumber(); - return this.getQuaiRateAtBlock(blockNumber, amt); + shardFromHash(hash: string): string { + return hash.slice(0, 4); } - async getQuaiRateAtBlock(blockTag: BlockTag, amt: number = 1): Promise { - let resolvedBlockTag = this._getBlockTag(blockTag); + async getLatestQuaiRate(shard: string, amt: number = 1): Promise { + const blockNumber = await this.getBlockNumber(shard); + return this.getQuaiRateAtBlock(shard, blockNumber, amt); + } + + async getQuaiRateAtBlock(shard: string, blockTag: BlockTag, amt: number = 1): Promise { + let resolvedBlockTag = this._getBlockTag(shard, blockTag); if (typeof resolvedBlockTag !== "string") { resolvedBlockTag = await resolvedBlockTag; } @@ -530,17 +596,18 @@ export class AbstractProvider implements Provider { return await this.#perform({ method: "getQuaiRateAtBlock", blockTag: resolvedBlockTag, - amt + amt, + shard: shard }); } - async getLatestQiRate(amt: number = 1): Promise { - const blockNumber = await this.getBlockNumber(); - return this.getQiRateAtBlock(blockNumber, amt); + async getLatestQiRate(shard: string, amt: number = 1): Promise { + const blockNumber = await this.getBlockNumber(shard); + return this.getQiRateAtBlock(shard, blockNumber, amt); } - async getQiRateAtBlock(blockTag: BlockTag, amt: number = 1): Promise { - let resolvedBlockTag = this._getBlockTag(blockTag); + async getQiRateAtBlock(shard: string, blockTag: BlockTag, amt: number = 1): Promise { + let resolvedBlockTag = this._getBlockTag(shard, blockTag); if (typeof resolvedBlockTag !== "string") { resolvedBlockTag = await resolvedBlockTag; } @@ -548,7 +615,8 @@ export class AbstractProvider implements Provider { return await this.#perform({ method: "getQiRateAtBlock", blockTag: resolvedBlockTag, - amt + amt, + shard: shard }); } @@ -717,7 +785,7 @@ export class AbstractProvider implements Provider { * * Sub-classes **must** override this. */ - _detectNetwork(): Promise { + _detectNetwork(shard?: string): Promise { assert(false, "sub-classes must implement this", "UNSUPPORTED_OPERATION", { operation: "_detectNetwork" }); @@ -738,8 +806,8 @@ export class AbstractProvider implements Provider { // State - async getBlockNumber(): Promise { - const blockNumber = getNumber(await this.#perform({ method: "getBlockNumber" }), "%response"); + async getBlockNumber(shard?: string): Promise { + const blockNumber = getNumber(await this.#perform({ method: "getBlockNumber", shard: shard }), "%response"); if (this.#lastBlockNumber >= 0) { this.#lastBlockNumber = blockNumber; } return blockNumber; } @@ -757,7 +825,7 @@ export class AbstractProvider implements Provider { * Returns or resolves to a valid block tag for %%blockTag%%, resolving * negative values and returning if already a valid block tag. */ - _getBlockTag(blockTag?: BlockTag): string | Promise { + _getBlockTag(shard?: string, blockTag?: BlockTag): string | Promise { if (blockTag == null) { return "latest"; } switch (blockTag) { @@ -783,7 +851,7 @@ export class AbstractProvider implements Provider { if (typeof(blockTag) === "number") { if (blockTag >= 0) { return toQuantity(blockTag); } if (this.#lastBlockNumber >= 0) { return toQuantity(this.#lastBlockNumber + blockTag); } - return this.getBlockNumber().then((b) => toQuantity(b + blockTag)); + return this.getBlockNumber(shard).then((b) => toQuantity(b + blockTag)); } assertArgument(false, "invalid blockTag", "blockTag", blockTag); @@ -807,7 +875,7 @@ export class AbstractProvider implements Provider { const blockHash = ("blockHash" in filter) ? filter.blockHash: undefined; - const resolve = (_address: Array, fromBlock?: string, toBlock?: string) => { + const resolve = (_address: Array, fromBlock?: string, toBlock?: string, shard?: string) => { let address: undefined | string | Array = undefined; switch (_address.length) { case 0: break; @@ -831,6 +899,7 @@ export class AbstractProvider implements Provider { if (fromBlock) { filter.fromBlock = fromBlock; } if (toBlock) { filter.toBlock = toBlock; } if (blockHash) { filter.blockHash = blockHash; } + if (shard) { filter.shard = shard; } return filter; }; @@ -846,21 +915,23 @@ export class AbstractProvider implements Provider { } let fromBlock: undefined | string | Promise = undefined; - if ("fromBlock" in filter) { fromBlock = this._getBlockTag(filter.fromBlock); } + if ("fromBlock" in filter) { fromBlock = this._getBlockTag(filter.shard, filter.fromBlock); } let toBlock: undefined | string | Promise = undefined; - if ("toBlock" in filter) { toBlock = this._getBlockTag(filter.toBlock); } + if ("toBlock" in filter) { toBlock = this._getBlockTag(filter.shard, filter.toBlock); } + + const shard = filter.shard if (address.filter((a) => (typeof(a) !== "string")).length || (fromBlock != null && typeof(fromBlock) !== "string") || (toBlock != null && typeof(toBlock) !== "string")) { - return Promise.all([ Promise.all(address), fromBlock, toBlock ]).then((result) => { + return Promise.all([ Promise.all(address), fromBlock, toBlock, shard ]).then((result) => { return resolve(result[0], result[1], result[2]); }); } - return resolve(>address, fromBlock, toBlock); + return resolve(>address, fromBlock, toBlock, shard); } /** @@ -884,7 +955,7 @@ export class AbstractProvider implements Provider { }); if (request.blockTag != null) { - const blockTag = this._getBlockTag(request.blockTag); + const blockTag = this._getBlockTag(request.chainId?.toString(), request.blockTag); if (isPromise(blockTag)) { promises.push((async function() { request.blockTag = await blockTag; })()); } else { @@ -902,7 +973,7 @@ export class AbstractProvider implements Provider { return request; } - async getNetwork(): Promise { + async getNetwork(shard: string = 'prime'): Promise { // No explicit network was set and this is our first time if (this.#networkPromise == null) { @@ -910,7 +981,7 @@ export class AbstractProvider implements Provider { // Detect the current network (shared with all calls) const detectNetwork = (async () => { try { - const network = await this._detectNetwork(); + const network = await this._detectNetwork(shard); this.emit("network", network, null); return network; } catch (error) { @@ -929,7 +1000,7 @@ export class AbstractProvider implements Provider { const [ expected, actual ] = await Promise.all([ networkPromise, // Possibly an explicit Network - this._detectNetwork() // The actual connected network + this._detectNetwork(shard) // The actual connected network ]); if (expected.chainId !== actual.chainId) { @@ -952,30 +1023,30 @@ export class AbstractProvider implements Provider { return expected.clone(); } - async getRunningLocations(): Promise { - return await this.#perform({ method: "getRunningLocations" }); + async getRunningLocations(shard?:string): Promise { + return await this.#perform(shard ? { method: "getRunningLocations", shard: shard } : { method: "getRunningLocations" }); } - async getProtocolTrieExpansionCount(): Promise { - return await this.#perform({ method: "getProtocolTrieExpansionCount" }); + async getProtocolTrieExpansionCount(shard: string): Promise { + return await this.#perform({ method: "getProtocolTrieExpansionCount", shard: shard }); } - async getFeeData(txType: boolean = true): Promise { + async getFeeData(shard?: string, txType: boolean = true): Promise { const network = await this.getNetwork(); const getFeeDataFunc = async () => { const { gasPrice, priorityFee } = await resolveProperties({ gasPrice: ((async () => { try { - const value = await this.#perform({ method: "getGasPrice", txType }); + const value = await this.#perform({ method: "getGasPrice", txType, shard: shard }); return getBigInt(value, "%response"); } catch (error) { } return null })()), priorityFee: ((async () => { try { - const value = txType ? await this.#perform({ method: "getMaxPriorityFeePerGas" }): 0; + const value = txType ? await this.#perform({ method: "getMaxPriorityFeePerGas", shard: shard }): 0; return getBigInt(value, "%response"); } catch (error) { } return null; @@ -1010,8 +1081,9 @@ export class AbstractProvider implements Provider { async estimateGas(_tx: TransactionRequest): Promise { let tx = this._getTransactionRequest(_tx); if (isPromise(tx)) { tx = await tx; } + const shard = await this.shardFromAddress(tx.from) return getBigInt(await this.#perform({ - method: "estimateGas", transaction: tx + method: "estimateGas", transaction: tx, shard: shard }), "%response"); } @@ -1029,60 +1101,60 @@ export class AbstractProvider implements Provider { } catch (error: any) { // CCIP Read OffchainLookup - if (!this.disableCcipRead && isCallException(error) && error.data && attempt >= 0 && blockTag === "latest" && transaction.to != null && dataSlice(error.data, 0, 4) === "0x556f1830") { - const data = error.data; - - const txSender = await resolveAddress(transaction.to, this); - - // Parse the CCIP Read Arguments - let ccipArgs: CcipArgs; - try { - ccipArgs = parseOffchainLookup(dataSlice(error.data, 4)); - } catch (error: any) { - assert(false, error.message, "OFFCHAIN_FAULT", { - reason: "BAD_DATA", transaction, info: { data } }); - } - - // Check the sender of the OffchainLookup matches the transaction - assert(ccipArgs.sender.toLowerCase() === txSender.toLowerCase(), - "CCIP Read sender mismatch", "CALL_EXCEPTION", { - action: "call", - data, - reason: "OffchainLookup", - transaction: transaction, // @TODO: populate data? - invocation: null, - revert: { - signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", - name: "OffchainLookup", - args: ccipArgs.errorArgs - } - }); - - const ccipResult = await this.ccipReadFetch(transaction, ccipArgs.calldata, ccipArgs.urls); - assert(ccipResult != null, "CCIP Read failed to fetch data", "OFFCHAIN_FAULT", { - reason: "FETCH_FAILED", transaction, info: { data: error.data, errorArgs: ccipArgs.errorArgs } }); - - const tx = { - to: txSender, - data: concat([ ccipArgs.selector, encodeBytes([ ccipResult, ccipArgs.extraData ]) ]) - }; - - this.emit("debug", { action: "sendCcipReadCall", transaction: tx }); - try { - const result = await this.#call(tx, blockTag, attempt + 1); - this.emit("debug", { action: "receiveCcipReadCallResult", transaction: Object.assign({ }, tx), result }); - return result; - } catch (error) { - this.emit("debug", { action: "receiveCcipReadCallError", transaction: Object.assign({ }, tx), error }); - throw error; - } - } + // if (!this.disableCcipRead && isCallException(error) && error.data && attempt >= 0 && blockTag === "latest" && transaction.to != null && dataSlice(error.data, 0, 4) === "0x556f1830") { + // const data = error.data; + + // const txSender = await resolveAddress(transaction.to, this); + + // // Parse the CCIP Read Arguments + // let ccipArgs: CcipArgs; + // try { + // ccipArgs = parseOffchainLookup(dataSlice(error.data, 4)); + // } catch (error: any) { + // assert(false, error.message, "OFFCHAIN_FAULT", { + // reason: "BAD_DATA", transaction, info: { data } }); + // } + + // // Check the sender of the OffchainLookup matches the transaction + // assert(ccipArgs.sender.toLowerCase() === txSender.toLowerCase(), + // "CCIP Read sender mismatch", "CALL_EXCEPTION", { + // action: "call", + // data, + // reason: "OffchainLookup", + // transaction: transaction, // @TODO: populate data? + // invocation: null, + // revert: { + // signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", + // name: "OffchainLookup", + // args: ccipArgs.errorArgs + // } + // }); + + // const ccipResult = await this.ccipReadFetch(transaction, ccipArgs.calldata, ccipArgs.urls); + // assert(ccipResult != null, "CCIP Read failed to fetch data", "OFFCHAIN_FAULT", { + // reason: "FETCH_FAILED", transaction, info: { data: error.data, errorArgs: ccipArgs.errorArgs } }); + + // const tx = { + // to: txSender, + // data: concat([ ccipArgs.selector, encodeBytes([ ccipResult, ccipArgs.extraData ]) ]) + // }; + + // this.emit("debug", { action: "sendCcipReadCall", transaction: tx }); + // try { + // const result = await this.#call(tx, blockTag, attempt + 1); + // this.emit("debug", { action: "receiveCcipReadCallResult", transaction: Object.assign({ }, tx), result }); + // return result; + // } catch (error) { + // this.emit("debug", { action: "receiveCcipReadCallError", transaction: Object.assign({ }, tx), error }); + // throw error; + // } + // } throw error; } } - async #checkNetwork(promise: Promise): Promise { + async #checkNetwork(promise: Promise, shard?: string, ): Promise { const { value } = await resolveProperties({ network: this.getNetwork(), value: promise @@ -1091,24 +1163,27 @@ export class AbstractProvider implements Provider { } async call(_tx: TransactionRequest): Promise { + const shard = await this.shardFromAddress(_tx.from); const { tx, blockTag } = await resolveProperties({ tx: this._getTransactionRequest(_tx), - blockTag: this._getBlockTag(_tx.blockTag) + blockTag: this._getBlockTag(shard, _tx.blockTag) }); - return await this.#checkNetwork(this.#call(tx, blockTag, _tx.enableCcipRead ? 0: -1)); + return await this.#checkNetwork(this.#call(tx, blockTag, _tx.enableCcipRead ? 0: -1), shard); } // Account async #getAccountValue(request: _PerformAccountRequest, _address: AddressLike, _blockTag?: BlockTag): Promise { let address: string | Promise = this._getAddress(_address); - let blockTag: string | Promise = this._getBlockTag(_blockTag); + const shard = await this.shardFromAddress(_address); + + let blockTag: string | Promise = this._getBlockTag(shard, _blockTag); if (typeof(address) !== "string" || typeof(blockTag) !== "string") { [ address, blockTag ] = await Promise.all([ address, blockTag ]); } - return await this.#checkNetwork(this.#perform(Object.assign(request, { address, blockTag }))); + return await this.#checkNetwork(this.#perform(Object.assign(request, { address, blockTag, shard: shard })), shard); } async getBalance(address: AddressLike, blockTag?: BlockTag): Promise { @@ -1125,16 +1200,17 @@ export class AbstractProvider implements Provider { async getStorage(address: AddressLike, _position: BigNumberish, blockTag?: BlockTag): Promise { const position = getBigInt(_position, "position"); - return hexlify(await this.#getAccountValue({ method: "getStorage", position }, address, blockTag)); + return hexlify(await this.#getAccountValue({ method: "getStorage", position}, address, blockTag)); } // Write - async broadcastTransaction(signedTx: string): Promise { + async broadcastTransaction(shard: string, signedTx: string): Promise { const { blockNumber, hash, network } = await resolveProperties({ - blockNumber: this.getBlockNumber(), + blockNumber: this.getBlockNumber(shard), hash: this._perform({ method: "broadcastTransaction", - signedTransaction: signedTx + signedTransaction: signedTx, + shard: shard }), network: this.getNetwork() }); @@ -1146,46 +1222,47 @@ export class AbstractProvider implements Provider { } async #validateTransactionHash(computedHash: string, nodehash: string){ - if (computedHash.substring(0,4) !== nodehash.substring(0,4)) + if (computedHash.substring(0,4) !== nodehash.substring(0,4)) throw new Error("Transaction hash mismatch in origin Zone"); - if (computedHash.substring(6,8) !== nodehash.substring(6,8)) + if (computedHash.substring(6,8) !== nodehash.substring(6,8)) throw new Error("Transaction hash mismatch in destination Zone"); - if (parseInt(computedHash[4], 16) < 8 !== parseInt(nodehash[4], 16) < 8) + if (parseInt(computedHash[4], 16) < 8 !== parseInt(nodehash[4], 16) < 8) throw new Error("Transaction ledger mismatch in origin Zone"); - if (parseInt(computedHash[8], 16) < 8 !== parseInt(nodehash[8], 16) < 8) - throw new Error("Transaction ledger mismatch in destination Zone"); + if (parseInt(computedHash[8], 16) < 8 !== parseInt(nodehash[8], 16) < 8) + throw new Error("Transaction ledger mismatch in destination Zone"); } - async #getBlock(block: BlockTag | string, includeTransactions: boolean): Promise { + async #getBlock(shard: string, block: BlockTag | string, includeTransactions: boolean): Promise { // @TODO: Add CustomBlockPlugin check if (isHexString(block, 32)) { return await this.#perform({ - method: "getBlock", blockHash: block, includeTransactions + method: "getBlock", blockHash: block, includeTransactions, shard: shard }); } - let blockTag = this._getBlockTag(block); + let blockTag = this._getBlockTag(shard, block); if (typeof(blockTag) !== "string") { blockTag = await blockTag; } return await this.#perform({ - method: "getBlock", blockTag, includeTransactions + method: "getBlock", blockTag, includeTransactions, shard: shard }); } // Queries - async getBlock(block: BlockTag | string, prefetchTxs?: boolean): Promise { + async getBlock(shard: string, block: BlockTag | string, prefetchTxs?: boolean): Promise { const { network, params } = await resolveProperties({ network: this.getNetwork(), - params: this.#getBlock(block, !!prefetchTxs) + params: this.#getBlock(shard, block, !!prefetchTxs) }); if (params == null) { return null; } return this._wrapBlock(params, network); } async getTransaction(hash: string): Promise { + const shard = this.shardFromHash(hash); const { network, params } = await resolveProperties({ network: this.getNetwork(), - params: this.#perform({ method: "getTransaction", hash }) + params: this.#perform({ method: "getTransaction", hash, shard: shard }) }); if (params == null) { return null; } @@ -1193,15 +1270,16 @@ export class AbstractProvider implements Provider { } async getTransactionReceipt(hash: string): Promise { + const shard = this.shardFromHash(hash); const { network, params } = await resolveProperties({ network: this.getNetwork(), - params: this.#perform({ method: "getTransactionReceipt", hash }) + params: this.#perform({ method: "getTransactionReceipt", hash, shard: shard }) }); if (params == null) { return null; } // Some backends did not backfill the effectiveGasPrice in to old transactions // in the receipt, so we look it up manually and inject it. if (params.gasPrice == null && params.effectiveGasPrice == null) { - const tx = await this.#perform({ method: "getTransaction", hash }); + const tx = await this.#perform({ method: "getTransaction", hash, shard: shard }); if (tx == null) { throw new Error("report this; could not find tx or effectiveGasPrice"); } params.effectiveGasPrice = tx.gasPrice; } @@ -1210,9 +1288,10 @@ export class AbstractProvider implements Provider { } async getTransactionResult(hash: string): Promise { + const shard = this.shardFromHash(hash); const { result } = await resolveProperties({ network: this.getNetwork(), - result: this.#perform({ method: "getTransactionResult", hash }) + result: this.#perform({ method: "getTransactionResult", hash, shard: shard }) }); if (result == null) { return null; } return hexlify(result); @@ -1222,10 +1301,11 @@ export class AbstractProvider implements Provider { async getLogs(_filter: Filter | FilterByBlockHash): Promise> { let filter = this._getFilter(_filter); if (isPromise(filter)) { filter = await filter; } + const shard = filter.shard const { network, params } = await resolveProperties({ network: this.getNetwork(), - params: this.#perform>({ method: "getLogs", filter }) + params: this.#perform>({ method: "getLogs", filter, shard: shard }) }); return params.map((p) => this._wrapLog(p, network)); @@ -1295,6 +1375,7 @@ export class AbstractProvider implements Provider { } async waitForTransaction(hash: string, _confirms?: null | number, timeout?: null | number): Promise { + const shard = this.shardFromHash(hash); const confirms = (_confirms != null) ? _confirms: 1; if (confirms === 0) { return this.getTransactionReceipt(hash); } @@ -1330,11 +1411,11 @@ export class AbstractProvider implements Provider { }, timeout); } - listener(await this.getBlockNumber()); + listener(await this.getBlockNumber(shard)); }); } - async waitForBlock(blockTag?: BlockTag): Promise { + async waitForBlock(shard: string, blockTag?: BlockTag): Promise { assert(false, "not implemented yet", "NOT_IMPLEMENTED", { operation: "waitForBlock" }); @@ -1664,134 +1745,134 @@ export class AbstractProvider implements Provider { } -function _parseString(result: string, start: number): null | string { - try { - const bytes = _parseBytes(result, start); - if (bytes) { return toUtf8String(bytes); } - } catch(error) { } - return null; -} - -function _parseBytes(result: string, start: number): null | string { - if (result === "0x") { return null; } - try { - const offset = getNumber(dataSlice(result, start, start + 32)); - const length = getNumber(dataSlice(result, offset, offset + 32)); - - return dataSlice(result, offset + 32, offset + 32 + length); - } catch (error) { } - return null; -} - -function numPad(value: number): Uint8Array { - const result = toBeArray(value); - if (result.length > 32) { throw new Error("internal; should not happen"); } - - const padded = new Uint8Array(32); - padded.set(result, 32 - result.length); - return padded; -} - -function bytesPad(value: Uint8Array): Uint8Array { - if ((value.length % 32) === 0) { return value; } - - const result = new Uint8Array(Math.ceil(value.length / 32) * 32); - result.set(value); - return result; -} - -const empty: Uint8Array = new Uint8Array([ ]); +// function _parseString(result: string, start: number): null | string { +// try { +// const bytes = _parseBytes(result, start); +// if (bytes) { return toUtf8String(bytes); } +// } catch(error) { } +// return null; +// } + +// function _parseBytes(result: string, start: number): null | string { +// if (result === "0x") { return null; } +// try { +// const offset = getNumber(dataSlice(result, start, start + 32)); +// const length = getNumber(dataSlice(result, offset, offset + 32)); +// +// return dataSlice(result, offset + 32, offset + 32 + length); +// } catch (error) { } +// return null; +// } + +// function numPad(value: number): Uint8Array { +// const result = toBeArray(value); +// if (result.length > 32) { throw new Error("internal; should not happen"); } +// +// const padded = new Uint8Array(32); +// padded.set(result, 32 - result.length); +// return padded; +// } + +// function bytesPad(value: Uint8Array): Uint8Array { +// if ((value.length % 32) === 0) { return value; } +// +// const result = new Uint8Array(Math.ceil(value.length / 32) * 32); +// result.set(value); +// return result; +// } + +// const empty: Uint8Array = new Uint8Array([ ]); // ABI Encodes a series of (bytes, bytes, ...) -function encodeBytes(datas: Array): string { - const result: Array = [ ]; - - let byteCount = 0; - - // Add place-holders for pointers as we add items - for (let i = 0; i < datas.length; i++) { - result.push(empty); - byteCount += 32; - } - - for (let i = 0; i < datas.length; i++) { - const data = getBytes(datas[i]); - - // Update the bytes offset - result[i] = numPad(byteCount); - - // The length and padded value of data - result.push(numPad(data.length)); - result.push(bytesPad(data)); - byteCount += 32 + Math.ceil(data.length / 32) * 32; - } - - return concat(result); -} - -const zeros = "0x0000000000000000000000000000000000000000000000000000000000000000" -function parseOffchainLookup(data: string): CcipArgs { - const result: CcipArgs = { - sender: "", urls: [ ], calldata: "", selector: "", extraData: "", errorArgs: [ ] - }; - - assert(dataLength(data) >= 5 * 32, "insufficient OffchainLookup data", "OFFCHAIN_FAULT", { - reason: "insufficient OffchainLookup data" - }); - - const sender = dataSlice(data, 0, 32); - assert(dataSlice(sender, 0, 12) === dataSlice(zeros, 0, 12), "corrupt OffchainLookup sender", "OFFCHAIN_FAULT", { - reason: "corrupt OffchainLookup sender" - }); - result.sender = dataSlice(sender, 12); - - // Read the URLs from the response - try { - const urls: Array = []; - const urlsOffset = getNumber(dataSlice(data, 32, 64)); - const urlsLength = getNumber(dataSlice(data, urlsOffset, urlsOffset + 32)); - const urlsData = dataSlice(data, urlsOffset + 32); - for (let u = 0; u < urlsLength; u++) { - const url = _parseString(urlsData, u * 32); - if (url == null) { throw new Error("abort"); } - urls.push(url); - } - result.urls = urls; - } catch (error) { - assert(false, "corrupt OffchainLookup urls", "OFFCHAIN_FAULT", { - reason: "corrupt OffchainLookup urls" - }); - } - - // Get the CCIP calldata to forward - try { - const calldata = _parseBytes(data, 64); - if (calldata == null) { throw new Error("abort"); } - result.calldata = calldata; - } catch (error) { - assert(false, "corrupt OffchainLookup calldata", "OFFCHAIN_FAULT", { - reason: "corrupt OffchainLookup calldata" - }); - } - - // Get the callbackSelector (bytes4) - assert(dataSlice(data, 100, 128) === dataSlice(zeros, 0, 28), "corrupt OffchainLookup callbaackSelector", "OFFCHAIN_FAULT", { - reason: "corrupt OffchainLookup callbaackSelector" - }); - result.selector = dataSlice(data, 96, 100); - - // Get the extra data to send back to the contract as context - try { - const extraData = _parseBytes(data, 128); - if (extraData == null) { throw new Error("abort"); } - result.extraData = extraData; - } catch (error) { - assert(false, "corrupt OffchainLookup extraData", "OFFCHAIN_FAULT", { - reason: "corrupt OffchainLookup extraData" - }); - } - - result.errorArgs = "sender,urls,calldata,selector,extraData".split(/,/).map((k) => (result)[k]) - - return result; -} +// function encodeBytes(datas: Array): string { +// const result: Array = [ ]; +// +// let byteCount = 0; +// +// // Add place-holders for pointers as we add items +// for (let i = 0; i < datas.length; i++) { +// result.push(empty); +// byteCount += 32; +// } +// +// for (let i = 0; i < datas.length; i++) { +// const data = getBytes(datas[i]); +// +// // Update the bytes offset +// result[i] = numPad(byteCount); +// +// // The length and padded value of data +// result.push(numPad(data.length)); +// result.push(bytesPad(data)); +// byteCount += 32 + Math.ceil(data.length / 32) * 32; +// } +// +// return concat(result); +// } + +// const zeros = "0x0000000000000000000000000000000000000000000000000000000000000000" +// function parseOffchainLookup(data: string): CcipArgs { +// const result: CcipArgs = { +// sender: "", urls: [ ], calldata: "", selector: "", extraData: "", errorArgs: [ ] +// }; +// +// assert(dataLength(data) >= 5 * 32, "insufficient OffchainLookup data", "OFFCHAIN_FAULT", { +// reason: "insufficient OffchainLookup data" +// }); +// +// const sender = dataSlice(data, 0, 32); +// assert(dataSlice(sender, 0, 12) === dataSlice(zeros, 0, 12), "corrupt OffchainLookup sender", "OFFCHAIN_FAULT", { +// reason: "corrupt OffchainLookup sender" +// }); +// result.sender = dataSlice(sender, 12); +// +// // Read the URLs from the response +// try { +// const urls: Array = []; +// const urlsOffset = getNumber(dataSlice(data, 32, 64)); +// const urlsLength = getNumber(dataSlice(data, urlsOffset, urlsOffset + 32)); +// const urlsData = dataSlice(data, urlsOffset + 32); +// for (let u = 0; u < urlsLength; u++) { +// const url = _parseString(urlsData, u * 32); +// if (url == null) { throw new Error("abort"); } +// urls.push(url); +// } +// result.urls = urls; +// } catch (error) { +// assert(false, "corrupt OffchainLookup urls", "OFFCHAIN_FAULT", { +// reason: "corrupt OffchainLookup urls" +// }); +// } +// +// // Get the CCIP calldata to forward +// try { +// const calldata = _parseBytes(data, 64); +// if (calldata == null) { throw new Error("abort"); } +// result.calldata = calldata; +// } catch (error) { +// assert(false, "corrupt OffchainLookup calldata", "OFFCHAIN_FAULT", { +// reason: "corrupt OffchainLookup calldata" +// }); +// } +// +// // Get the callbackSelector (bytes4) +// assert(dataSlice(data, 100, 128) === dataSlice(zeros, 0, 28), "corrupt OffchainLookup callbaackSelector", "OFFCHAIN_FAULT", { +// reason: "corrupt OffchainLookup callbaackSelector" +// }); +// result.selector = dataSlice(data, 96, 100); +// +// // Get the extra data to send back to the contract as context +// try { +// const extraData = _parseBytes(data, 128); +// if (extraData == null) { throw new Error("abort"); } +// result.extraData = extraData; +// } catch (error) { +// assert(false, "corrupt OffchainLookup extraData", "OFFCHAIN_FAULT", { +// reason: "corrupt OffchainLookup extraData" +// }); +// } +// +// result.errorArgs = "sender,urls,calldata,selector,extraData".split(/,/).map((k) => (result)[k]) +// +// return result; +// } diff --git a/src.ts/providers/abstract-signer.ts b/src.ts/providers/abstract-signer.ts index 56a2d13e..b087941a 100644 --- a/src.ts/providers/abstract-signer.ts +++ b/src.ts/providers/abstract-signer.ts @@ -5,7 +5,7 @@ * * @_section: api/providers/abstract-signer: Subclassing Signer [abstract-signer] */ -import { resolveAddress } from "../address/index.js"; +import {AddressLike, resolveAddress} from "../address/index.js"; import { Transaction } from "../transaction/index.js"; import { defineProperties, getBigInt, resolveProperties, @@ -74,6 +74,15 @@ export abstract class AbstractSigner

; + + _getAddress(address: AddressLike): string | Promise { + return resolveAddress(address, this); + } + + async shardFromAddress(_address: AddressLike): Promise { + let address: string | Promise = this._getAddress(_address); + return (await address).slice(0, 4) + } /** * Returns the signer connected to %%provider%%. * @@ -98,6 +107,7 @@ export abstract class AbstractSigner

> { console.log("populateTransaction") const provider = checkProvider(this, "populateTransaction"); + const shard = await this.shardFromAddress(tx.from) const pop = await populate(this, tx); @@ -125,12 +135,12 @@ export abstract class AbstractSigner

{ console.log('sendTransaction', tx) const provider = checkProvider(this, "sendTransaction"); + const shard = await this.shardFromAddress(tx.from) const pop = await this.populateTransaction(tx); console.log("populated tx", pop) - delete pop.from; - +// delete pop.from; const txObj = Transaction.from(pop); const signedTx = await this.signTransaction(txObj); - const result = await provider.broadcastTransaction(signedTx); - return result + console.log("signedTX: ", JSON.stringify(txObj)) + return await provider.broadcastTransaction(shard, signedTx); } abstract signTransaction(tx: TransactionRequest): Promise; diff --git a/src.ts/providers/default-provider.ts b/src.ts/providers/default-provider.ts index 264abcba..e4d88692 100644 --- a/src.ts/providers/default-provider.ts +++ b/src.ts/providers/default-provider.ts @@ -60,7 +60,7 @@ const Testnets = "goerli kovan sepolia classicKotti optimism-goerli arbitrum-goe * exclusive: [ "quaiscan", "infura" ] * }); */ -export function getDefaultProvider(network: string | Networkish | WebSocketLike, options?: any): AbstractProvider { +export function getDefaultProvider(network: string | string[] | Networkish | WebSocketLike, options?: any): AbstractProvider { if (options == null) { options = { }; } const allowService = (name: string) => { @@ -78,10 +78,24 @@ export function getDefaultProvider(network: string | Networkish | WebSocketLike, return new JsonRpcProvider(network); } + if (Array.isArray(network) && network[0].match(/^https?:/)) { + return new JsonRpcProvider(network); + } + if (typeof(network) === "string" && network.match(/^wss?:/) || isWebSocketLike(network)) { return new WebSocketProvider(network); } + if (Array.isArray(network) && (network[0].match(/^wss?:/) || isWebSocketLike(network[0]))) { + return new WebSocketProvider(network[0]); + } + + if (Array.isArray(network)) { + assert(false, "unsupported default network", "UNSUPPORTED_OPERATION", { + operation: "getDefaultProvider" + }); + } + // Get the network and name, if possible let staticNetwork: null | Network = null; try { diff --git a/src.ts/providers/formatting.ts b/src.ts/providers/formatting.ts index 1d783219..d6fb7598 100644 --- a/src.ts/providers/formatting.ts +++ b/src.ts/providers/formatting.ts @@ -287,6 +287,7 @@ export interface TransactionReceiptParams { status: null | number; etxs: ReadonlyArray; + } diff --git a/src.ts/providers/provider-fallback.ts b/src.ts/providers/provider-fallback.ts index 58c40cf4..22cd135d 100644 --- a/src.ts/providers/provider-fallback.ts +++ b/src.ts/providers/provider-fallback.ts @@ -439,7 +439,7 @@ export class FallbackProvider extends AbstractProvider { async _translatePerform(provider: AbstractProvider, req: PerformActionRequest): Promise { switch (req.method) { case "broadcastTransaction": - return await provider.broadcastTransaction(req.signedTransaction); + return await provider.broadcastTransaction(req.shard, req.signedTransaction); case "call": return await provider.call(Object.assign({ }, req.transaction, { blockTag: req.blockTag })); case "chainId": @@ -450,7 +450,7 @@ export class FallbackProvider extends AbstractProvider { return await provider.getBalance(req.address, req.blockTag); case "getBlock": { const block = ("blockHash" in req) ? req.blockHash: req.blockTag; - return await provider.getBlock(block, req.includeTransactions); + return await provider.getBlock(req.shard, block, req.includeTransactions); } case "getBlockNumber": return await provider.getBlockNumber(); diff --git a/src.ts/providers/provider-jsonrpc.ts b/src.ts/providers/provider-jsonrpc.ts index e0b5cc05..a0b445a3 100644 --- a/src.ts/providers/provider-jsonrpc.ts +++ b/src.ts/providers/provider-jsonrpc.ts @@ -339,7 +339,8 @@ export class JsonRpcSigner extends AbstractSigner { async sendTransaction(tx: TransactionRequest): Promise { // This cannot be mined any earlier than any recent block - const blockNumber = await this.provider.getBlockNumber(); + const shard = await this.shardFromAddress(tx.from); + const blockNumber = await this.provider.getBlockNumber(shard); // Send the transaction const hash = await this.sendUncheckedTransaction(tx); @@ -456,7 +457,7 @@ export class JsonRpcSigner extends AbstractSigner { type ResolveFunc = (result: JsonRpcResult) => void; type RejectFunc = (error: Error) => void; -type Payload = { payload: JsonRpcPayload, resolve: ResolveFunc, reject: RejectFunc }; +type Payload = { payload: JsonRpcPayload, resolve: ResolveFunc, reject: RejectFunc, shard?: string }; /** * The JsonRpcApiProvider is an abstract class and **MUST** be @@ -487,6 +488,8 @@ export abstract class JsonRpcApiProvider extends AbstractProvider { #network: null | Network; #pendingDetectNetwork: null | Promise; + initPromise?: Promise; + #scheduleDrain(): void { if (this.#drainTimer) { return; } @@ -515,13 +518,30 @@ export abstract class JsonRpcApiProvider extends AbstractProvider { // Process the result to each payload (async () => { - const payload = ((batch.length === 1) ? batch[0].payload: batch.map((p) => p.payload)); + const payloadMap: Map> = new Map() + for (let i = 0; i < batch.length; i++) { + if (!payloadMap.has(batch[i].shard)) { + if (batch[i].payload != null) { payloadMap.set(batch[i].shard, [batch[i].payload]) }; + } else { + payloadMap.get(batch[i].shard)?.push(batch[i].payload); + } + } + + let rawResult: Array> = [] + await Promise.all(Array.from(payloadMap).map(async ([key, value]) => { + const payload = value.length === 1 ? value[0] : value; + const shard = key; - this.emit("debug", { action: "sendRpcPayload", payload }); + this.emit("debug", { action: "sendRpcPayload", payload }); + + rawResult.push(await this._send(payload, shard)); + + this.emit("debug", { action: "receiveRpcResult", payload }); + })); + + const result: Array = rawResult.flat(); try { - const result = await this._send(payload); - this.emit("debug", { action: "receiveRpcResult", result }); // Process results in batch order for (const { resolve, reject, payload } of batch) { @@ -624,7 +644,7 @@ export abstract class JsonRpcApiProvider extends AbstractProvider { * * Sub-classes **MUST** override this. */ - abstract _send(payload: JsonRpcPayload | Array): Promise>; + abstract _send(payload: JsonRpcPayload | Array, shard?: string): Promise>; /** @@ -636,12 +656,13 @@ export abstract class JsonRpcApiProvider extends AbstractProvider { async _perform(req: PerformActionRequest): Promise { // Legacy networks do not like the type field being passed along (which // is fair), so we delete type if it is 0 and a non-EIP-1559 network + await this.initPromise; if (req.method === "call" || req.method === "estimateGas") { let tx = req.transaction; if (tx && tx.type != null && getBigInt(tx.type)) { // If there are no EIP-1559 properties, it might be non-EIP-a559 if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) { - const feeData = await this.getFeeData(); + const feeData = await this.getFeeData(req.shard); if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) { // Network doesn't know about EIP-1559 (and hence type) req = Object.assign({ }, req, { @@ -655,7 +676,7 @@ export abstract class JsonRpcApiProvider extends AbstractProvider { const request = this.getRpcRequest(req); if (request != null) { - return await this.send(request.method, request.args); + return await this.send(request.method, request.args, req.shard); } return super._perform(req); @@ -1075,7 +1096,7 @@ export abstract class JsonRpcApiProvider extends AbstractProvider { * override [[_send]] or force the options values in the * call to the constructor to modify this method's behavior. */ - send(method: string, params: Array | Record): Promise { + send(method: string, params: Array | Record, shard?: string): Promise { // @TODO: cache chainId?? purge on switch_networks // We have been destroyed; no operations are supported anymore @@ -1086,7 +1107,8 @@ export abstract class JsonRpcApiProvider extends AbstractProvider { const promise = new Promise((resolve, reject) => { this.#payloads.push({ resolve, reject, - payload: { method, params, id, jsonrpc: "2.0" } + payload: { method, params, id, jsonrpc: "2.0" }, + shard: shard }); }); @@ -1174,16 +1196,17 @@ export abstract class JsonRpcApiProvider extends AbstractProvider { * for updates. */ export class JsonRpcProvider extends JsonRpcApiProvider { - #connect: FetchRequest; - constructor(url?: string | FetchRequest, network?: Networkish, options?: JsonRpcApiProviderOptions) { - if (url == null) { url = "http:/\/localhost:8545"; } + constructor(urls?: string | string[] | FetchRequest, network?: Networkish, options?: JsonRpcApiProviderOptions) { + if (urls == null) { urls = ["http:/\/localhost:8545"]; } super(network, options); - if (typeof(url) === "string") { - this.#connect = new FetchRequest(url); + if (Array.isArray(urls)) { + this.initPromise = this.initUrlMap(urls); + } else if(typeof urls === "string") { + this.initPromise = this.initUrlMap([urls]); } else { - this.#connect = url.clone(); + this.initPromise = this.initUrlMap(urls.clone()); } } @@ -1192,22 +1215,28 @@ export class JsonRpcProvider extends JsonRpcApiProvider { return subscriber; } - _getConnection(): FetchRequest { - return this.#connect.clone(); + _getConnection(shard?: string): FetchRequest { + const connection = this.connect[this.connect.length - 1]!.clone(); + if (typeof shard === "string") { + const shardBytes = this.shardBytes(shard); + connection.url = this._urlMap.get(shardBytes) ?? connection.url; + } + return connection } - async send(method: string, params: Array | Record): Promise { + async send(method: string, params: Array | Record, shard?: string): Promise { // All requests are over HTTP, so we can just start handling requests // We do this here rather than the constructor so that we don't send any // requests to the network (i.e. quai_chainId) until we absolutely have to. +// await this.initPromise; await this._start(); - return await super.send(method, params); + return await super.send(method, params, shard); } - async _send(payload: JsonRpcPayload | Array): Promise> { + async _send(payload: JsonRpcPayload | Array, shard?: string): Promise> { // Configure a POST connection for the requested method - const request = this._getConnection(); + const request = this._getConnection(shard); request.body = JSON.stringify(payload); request.setHeader("content-type", "application/json"); const response = await request.send(); diff --git a/src.ts/providers/provider.ts b/src.ts/providers/provider.ts index eacba88f..d9bbfffb 100644 --- a/src.ts/providers/provider.ts +++ b/src.ts/providers/provider.ts @@ -134,7 +134,7 @@ export interface TransactionRequest { /** * The sender of the transaction. */ - from?: null | AddressLike; + from: AddressLike; /** * The nonce of the transaction, used to prevent replay attacks. @@ -226,7 +226,7 @@ export interface PreparedTransactionRequest { /** * The sender of the transaction. */ - from?: AddressLike; + from: AddressLike; /** * The nonce of the transaction, used to prevent replay attacks. @@ -907,8 +907,8 @@ export class Log implements LogParams { /** * Returns the block that this log occurred in. */ - async getBlock(): Promise { - const block = await this.provider.getBlock(this.blockHash); + async getBlock(shard: string): Promise { + const block = await this.provider.getBlock(shard, this.blockHash); assert(!!block, "failed to find transaction", "UNKNOWN_ERROR", { }); return block; } @@ -944,6 +944,9 @@ export class Log implements LogParams { // Transaction Receipt +export function shardFromHash(hash: string): string { + return hash.slice(0, 4); +} /** * A **TransactionReceipt** includes additional information about a * transaction that is only available after it has been mined. @@ -1150,8 +1153,8 @@ export class TransactionReceipt implements TransactionReceiptParams, Iterable { - const block = await this.provider.getBlock(this.blockHash); + async getBlock(shard: string): Promise { + const block = await this.provider.getBlock(shard, this.blockHash); if (block == null) { throw new Error("TODO"); } return block; } @@ -1179,7 +1182,8 @@ export class TransactionReceipt implements TransactionReceiptParams, Iterable { - return (await this.provider.getBlockNumber()) - this.blockNumber + 1; + const shard = shardFromHash(this.hash); + return (await this.provider.getBlockNumber(shard)) - this.blockNumber + 1; } /** @@ -1414,14 +1418,14 @@ export class TransactionResponse implements TransactionLike, Transaction * * This will return null if the transaction has not been included yet. */ - async getBlock(): Promise { + async getBlock(shard: string): Promise { let blockNumber = this.blockNumber; if (blockNumber == null) { const tx = await this.getTransaction(); if (tx) { blockNumber = tx.blockNumber; } } if (blockNumber == null) { return null; } - const block = this.provider.getBlock(blockNumber); + const block = this.provider.getBlock(shard, blockNumber); if (block == null) { throw new Error("TODO"); } return block; } @@ -1439,10 +1443,11 @@ export class TransactionResponse implements TransactionLike, Transaction * Resolve to the number of confirmations this transaction has. */ async confirmations(): Promise { + const shard = shardFromHash(this.hash); if (this.blockNumber == null) { const { tx, blockNumber } = await resolveProperties({ tx: this.getTransaction(), - blockNumber: this.provider.getBlockNumber() + blockNumber: this.provider.getBlockNumber(shard) }); // Not mined yet... @@ -1451,7 +1456,7 @@ export class TransactionResponse implements TransactionLike, Transaction return blockNumber - tx.blockNumber + 1; } - const blockNumber = await this.provider.getBlockNumber(); + const blockNumber = await this.provider.getBlockNumber(shard); return blockNumber - this.blockNumber + 1; } @@ -1471,11 +1476,12 @@ export class TransactionResponse implements TransactionLike, Transaction let startBlock = this.#startBlock let nextScan = -1; let stopScanning = (startBlock === -1) ? true: false; + const shard = shardFromHash(this.hash); const checkReplacement = async () => { // Get the current transaction count for this sender if (stopScanning) { return null; } const { blockNumber, nonce } = await resolveProperties({ - blockNumber: this.provider.getBlockNumber(), + blockNumber: this.provider.getBlockNumber(shard), nonce: this.provider.getTransactionCount(this.from) }); @@ -1502,7 +1508,7 @@ export class TransactionResponse implements TransactionLike, Transaction while (nextScan <= blockNumber) { // Get the next block to scan if (stopScanning) { return null; } - const block = await this.provider.getBlock(nextScan, true); + const block = await this.provider.getBlock(shard, nextScan, true); // This should not happen; but we'll try again shortly if (block == null) { return; } @@ -1794,6 +1800,8 @@ export interface Filter extends EventFilter { * The end block for the filter (inclusive). */ toBlock?: BlockTag; + + shard: string } /** @@ -1805,6 +1813,7 @@ export interface FilterByBlockHash extends EventFilter { * The blockhash of the specific block for the filter. */ blockHash?: string; + shard: string; } @@ -1884,17 +1893,17 @@ export interface Provider extends ContractRunner, EventEmitterable; + getBlockNumber(shard: string): Promise; /** * Get the connected [[Network]]. */ - getNetwork(): Promise; + getNetwork(shard?: string): Promise; /** * Get the best guess at the recommended [[FeeData]]. */ - getFeeData(): Promise; + getFeeData(shard: string): Promise; //////////////////// @@ -1958,7 +1967,7 @@ export interface Provider extends ContractRunner, EventEmitterable; + broadcastTransaction(shard: string, signedTx: string): Promise; //////////////////// @@ -1972,7 +1981,7 @@ export interface Provider extends ContractRunner, EventEmitterable; + getBlock(shard: string, blockHashOrBlockTag: BlockTag | string, prefetchTxs?: boolean): Promise; /** * Resolves to the transaction for %%hash%%. @@ -2039,5 +2048,5 @@ export interface Provider extends ContractRunner, EventEmitterable; + waitForBlock(shard: string, blockTag?: BlockTag): Promise; } diff --git a/src.ts/transaction/transaction.ts b/src.ts/transaction/transaction.ts index 77bf1b00..8f5e1ecd 100644 --- a/src.ts/transaction/transaction.ts +++ b/src.ts/transaction/transaction.ts @@ -1,5 +1,5 @@ -import { getAddress } from "../address/index.js"; +import {getAddress} from "../address/index.js"; import { keccak256, Signature, SigningKey } from "../crypto/index.js"; import { getBytes, getBigInt, getNumber, hexlify, @@ -28,8 +28,7 @@ export interface TransactionLike { /** * The sender. */ - from?: null | A; - + from: A; /** * The nonce. */ @@ -123,6 +122,7 @@ function _parse(data: Uint8Array): TransactionLike { const decodedTx: any = decodeProto(getBytes(data)); const tx: TransactionLike = { type: decodedTx.type, + from: decodedTx.from, chainId: toBigInt(decodedTx.chain_id), nonce: decodedTx.nonce, maxPriorityFeePerGas: toBigInt(decodedTx.gas_tip_cap), @@ -143,7 +143,7 @@ function _parse(data: Uint8Array): TransactionLike { _parseSignature(tx, signatureFields); tx.hash = getTransactionHash(tx, data); - + return tx; } @@ -166,8 +166,8 @@ function getTransactionHash (tx: TransactionLike, data: Uint8Array): string { let hash = keccak256(data) hash = '0x' + originShardByte + (originUtxo ? 'F' : '1') + hash.charAt(5) + originShardByte + (destUtxo ? 'F' : '1') + hash.slice(9) - - //TODO alter comparison + + //TODO alter comparison return hash; } @@ -229,6 +229,7 @@ export class Transaction implements TransactionLike { #hash: null | string; #inputsUTXO: null | UTXOTransactionInput[]; #outputsUTXO: null | UTXOTransactionOutput[]; + from: string; /** * The transaction type. @@ -391,7 +392,7 @@ export class Transaction implements TransactionLike { /** * Creates a new Transaction with default values. */ - constructor() { + constructor(from: string) { this.#type = null; this.#to = null; this.#nonce = 0; @@ -407,6 +408,7 @@ export class Transaction implements TransactionLike { this.#hash = null; this.#inputsUTXO = null; this.#outputsUTXO = null; + this.from = from } /** @@ -432,14 +434,6 @@ export class Transaction implements TransactionLike { return keccak256(this.unsignedSerialized); } - /** - * The sending address, if signed. Otherwise, ``null``. - */ - get from(): null | string { - if (this.signature == null) { return null; } - return recoverAddress(this.unsignedHash, this.signature); - } - /** * The public key of the sender, if signed. Otherwise, ``null``. */ @@ -514,7 +508,7 @@ export class Transaction implements TransactionLike { } else { types.push(0); - + } types.sort(); @@ -559,14 +553,14 @@ export class Transaction implements TransactionLike { * Create a **Transaction** from a serialized transaction or a * Transaction-like object. */ - static from(tx?: string | TransactionLike): Transaction { - if (tx == null) { return new Transaction(); } - + static from(tx: string | TransactionLike): Transaction { +// if (tx == null) { return new Transaction(); } + if (typeof(tx) === "string") { const payload = getBytes(tx); return Transaction.from(_parse(payload)); } - const result = new Transaction(); + const result = new Transaction(tx.from); if (tx.type != null) { result.type = tx.type; } if (tx.to != null) { result.to = tx.to; } if (tx.nonce != null) { result.nonce = tx.nonce; } @@ -578,7 +572,7 @@ export class Transaction implements TransactionLike { if (tx.chainId != null) { result.chainId = tx.chainId; } if (tx.signature != null) { result.signature = Signature.from(tx.signature); } if (tx.accessList != null) { result.accessList = tx.accessList; } - + if (tx.hash != null) { assertArgument(result.isSigned(), "unsigned transaction cannot define hash", "tx", tx); @@ -586,7 +580,7 @@ export class Transaction implements TransactionLike { } if (tx.from != null) { - assertArgument(result.isSigned(), "unsigned transaction cannot define from", "tx", tx); +// assertArgument(result.isSigned(), "unsigned transaction cannot define from", "tx", tx); assertArgument(result.from.toLowerCase() === (tx.from || "").toLowerCase(), "from mismatch", "tx", tx); } return result; diff --git a/src.ts/wallet/base-wallet.ts b/src.ts/wallet/base-wallet.ts index daa7acaa..188ea2a8 100644 --- a/src.ts/wallet/base-wallet.ts +++ b/src.ts/wallet/base-wallet.ts @@ -91,7 +91,7 @@ export class BaseWallet extends AbstractSigner { if (tx.from != null) { assertArgument(getAddress((tx.from)) === this.#address, "transaction from address mismatch", "tx.from", tx.from); - delete tx.from; +// delete tx.from; } // Build the transaction